Merge "Make sure mTransmitPowerInfo is always populated"
diff --git a/Android.bp b/Android.bp
index e17a9b4..1eba3e2 100644
--- a/Android.bp
+++ b/Android.bp
@@ -112,6 +112,14 @@
 }
 
 filegroup {
+    name: "framework-mime-sources",
+    srcs: [
+        "mime/java/**/*.java",
+    ],
+    path: "mime/java",
+}
+
+filegroup {
     name: "framework-opengl-sources",
     srcs: [
         "opengl/java/**/*.java",
@@ -154,6 +162,23 @@
 }
 
 filegroup {
+    name: "framework-telephony-common-sources",
+    srcs: [
+        "telephony/common/**/*.java",
+    ],
+    path: "telephony/common",
+}
+
+filegroup {
+    name: "framework-mms-sources",
+    srcs: [
+        "mms/java/**/*.java",
+        "mms/java/**/*.aidl",
+    ],
+    path: "mms/java",
+}
+
+filegroup {
     name: "framework-wifi-sources",
     srcs: [
         "wifi/java/**/*.java",
@@ -176,10 +201,13 @@
         ":framework-mca-effect-sources",
         ":framework-mca-filterfw-sources",
         ":framework-mca-filterpacks-sources",
+        ":framework-mime-sources",
+        ":framework-mms-sources",
         ":framework-opengl-sources",
         ":framework-rs-sources",
         ":framework-sax-sources",
         ":framework-telecomm-sources",
+        ":framework-telephony-common-sources",
         ":framework-telephony-sources",
         ":framework-wifi-sources",
         ":PacProcessor-aidl-sources",
@@ -234,6 +262,7 @@
             "media/mca/effect/java",
             "media/mca/filterfw/java",
             "media/mca/filterpacks/java",
+            "mms/java",
             "opengl/java",
             "rs/java",
             "sax/java",
@@ -244,8 +273,9 @@
     },
 
     required: [
-        // TODO: remove gps_debug when the build system propagates "required" properly.
+        // TODO: remove gps_debug and protolog.conf.json when the build system propagates "required" properly.
         "gps_debug.conf",
+	"protolog.conf.json.gz",
     ],
 }
 
@@ -315,7 +345,10 @@
 
     jarjar_rules: ":framework-jarjar-rules",
 
-    static_libs: ["framework-internal-utils"],
+    static_libs: [
+        "framework-internal-utils",
+        "mimemap",
+    ],
 
     dxflags: [
         "--core-library",
@@ -393,7 +426,7 @@
 
 java_library {
     name: "framework-annotation-proc",
-    defaults: ["framework-defaults"],
+    defaults: ["framework-aidl-export-defaults"],
     srcs: [":framework-all-sources"],
     installable: false,
     plugins: [
@@ -798,9 +831,11 @@
     "media/mca/filterfw/java",
     "media/mca/filterpacks/java",
     "drm/java",
+    "mms/java",
     "opengl/java",
     "sax/java",
     "telecomm/java",
+    "telephony/common",
     "telephony/java",
     "wifi/java",
     "lowpan/java",
@@ -899,8 +934,10 @@
 
 packages_to_document = [
     "android",
+    "dalvik",
     "java",
     "javax",
+    "junit",
     "org.apache.http",
     "org.json",
     "org.w3c.dom",
@@ -916,6 +953,7 @@
         "test-base/src/**/*.java",
         ":opt-telephony-srcs",
         ":opt-net-voip-srcs",
+        ":core-current-stubs-source",
         ":core_public_api_files",
         ":updatable-media-srcs",
         "test-mock/src/**/*.java",
@@ -931,7 +969,7 @@
         "sdk-dir",
         "api-versions-jars-dir",
     ],
-    previous_api: ":last-released-public-api",
+    previous_api: ":last-released-public-api-for-metalava-annotations",
     merge_annotations_dirs: [
         "metalava-manual",
         "ojluni-annotated-sdk-stubs",
@@ -980,6 +1018,7 @@
         "core/java/**/*.logtags",
         ":opt-telephony-srcs",
         ":opt-net-voip-srcs",
+        ":core-current-stubs-source",
         ":core_public_api_files",
         ":updatable-media-srcs",
         ":jobscheduler-framework-source",
@@ -988,7 +1027,7 @@
     local_sourcepaths: frameworks_base_subdirs,
     installable: false,
     annotations_enabled: true,
-    previous_api: ":last-released-public-api",
+    previous_api: ":last-released-public-api-for-metalava-annotations",
     merge_annotations_dirs: [
         "metalava-manual",
         "ojluni-annotated-sdk-stubs",
@@ -1324,7 +1363,7 @@
     installable: false,
     sdk_version: "core_platform",
     annotations_enabled: true,
-    previous_api: ":last-released-public-api",
+    previous_api: ":last-released-public-api-for-metalava-annotations",
     merge_annotations_dirs: [
         "metalava-manual",
         "ojluni-annotated-sdk-stubs",
@@ -1511,3 +1550,36 @@
         targets: ["droidcore"],
     },
 }
+
+// Avoid including Parcelable classes as we don't want to have two copies of
+// Parcelable cross the process.
+filegroup {
+    name: "framework-telephony-stack-shared-srcs",
+    srcs: [
+        "core/java/android/os/RegistrantList.java",
+        "core/java/android/os/Registrant.java",
+        "core/java/android/util/LocalLog.java",
+        "core/java/android/util/Slog.java",
+        "core/java/android/util/TimeUtils.java",
+        "core/java/com/android/internal/os/SomeArgs.java",
+        "core/java/com/android/internal/util/Preconditions.java",
+        "core/java/com/android/internal/util/State.java",
+        "core/java/com/android/internal/util/StateMachine.java",
+        "core/java/com/android/internal/util/XmlUtils.java",
+        "core/java/com/android/internal/util/HexDump.java",
+        "core/java/com/android/internal/util/IndentingPrintWriter.java",
+        "core/java/com/android/internal/util/DumpUtils.java"
+    ],
+}
+
+// Avoid including Parcelable classes as we don't want to have two copies of
+// Parcelable cross the process.
+filegroup {
+    name: "framework-cellbroadcast-shared-srcs",
+    srcs: [
+        "core/java/android/util/LocalLog.java",
+        "core/java/android/util/Slog.java",
+        "core/java/com/android/internal/util/State.java",
+        "core/java/com/android/internal/util/StateMachine.java",
+    ],
+}
\ No newline at end of file
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 6a909c0..f7a2858 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -254,6 +254,7 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/priv-app/DefaultContainerService)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/CaptivePortalLogin)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/framework/ext.jar)
+$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/telephony/java/com/google/android/mms)
 # ******************************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THIS BANNER
 # ******************************************************************
diff --git a/apct-tests/perftests/core/Android.mk b/apct-tests/perftests/core/Android.mk
index 3f87a1c..968478c 100644
--- a/apct-tests/perftests/core/Android.mk
+++ b/apct-tests/perftests/core/Android.mk
@@ -9,8 +9,11 @@
   src/android/os/ISomeService.aidl
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
+    androidx.appcompat_appcompat \
     androidx.test.rules \
     androidx.annotation_annotation \
+    apct-perftests-overlay-apps \
+    apct-perftests-resources-manager-apps \
     apct-perftests-utils \
     guava
 
@@ -25,5 +28,6 @@
 LOCAL_ASSET_DIR := $(TOP)/external/google-fonts/dancing-script
 
 LOCAL_COMPATIBILITY_SUITE += device-tests
+LOCAL_CERTIFICATE := platform
 
-include $(BUILD_PACKAGE)
+include $(BUILD_PACKAGE)
\ No newline at end of file
diff --git a/apct-tests/perftests/core/AndroidManifest.xml b/apct-tests/perftests/core/AndroidManifest.xml
index a564a4d..525975d 100644
--- a/apct-tests/perftests/core/AndroidManifest.xml
+++ b/apct-tests/perftests/core/AndroidManifest.xml
@@ -5,8 +5,11 @@
     <permission android:name="com.android.perftests.core.TestPermission" />
     <uses-permission android:name="com.android.perftests.core.TestPermission" />
 
-    <uses-permission
-        android:name="android.permission.GET_ACCOUNTS" />
+    <uses-permission android:name="android.permission.CHANGE_OVERLAY_PACKAGES" />
+    <uses-permission android:name="android.permission.DELETE_PACKAGES" />
+    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
+    <uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
 
     <application>
         <uses-library android:name="android.test.runner" />
diff --git a/apct-tests/perftests/core/apps/overlay/Android.bp b/apct-tests/perftests/core/apps/overlay/Android.bp
new file mode 100644
index 0000000..7bee30e
--- /dev/null
+++ b/apct-tests/perftests/core/apps/overlay/Android.bp
@@ -0,0 +1,188 @@
+// Copyright (C) 2019 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.
+
+android_test_helper_app {
+    name: "Overlay0",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay0",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay1",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay1",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay2",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay2",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay3",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay3",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay4",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay4",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay5",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay5",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay6",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay6",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay7",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay7",
+    ]
+}
+android_test_helper_app {
+    name: "Overlay8",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay8",
+    ]
+}
+
+android_test_helper_app {
+    name: "Overlay9",
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay9",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay0",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large0",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay1",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large1",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay2",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large2",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay3",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large3",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay4",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large4",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay5",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large5",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay6",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large6",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay7",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large7",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay8",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large8",
+    ]
+}
+
+android_test_helper_app {
+    name: "LargeOverlay9",
+    resource_dirs : [ "res_large" ],
+    aaptflags: [
+        "--rename-manifest-package com.android.perftests.overlay.large9",
+    ]
+}
+
+java_library {
+    name: "apct-perftests-overlay-apps",
+    java_resources: [
+        ":Overlay0",
+        ":Overlay1",
+        ":Overlay2",
+        ":Overlay3",
+        ":Overlay4",
+        ":Overlay5",
+        ":Overlay6",
+        ":Overlay7",
+        ":Overlay8",
+        ":Overlay9",
+        ":LargeOverlay0",
+        ":LargeOverlay1",
+        ":LargeOverlay2",
+        ":LargeOverlay3",
+        ":LargeOverlay4",
+        ":LargeOverlay5",
+        ":LargeOverlay6",
+        ":LargeOverlay7",
+        ":LargeOverlay8",
+        ":LargeOverlay9",
+    ],
+}
\ No newline at end of file
diff --git a/apct-tests/perftests/core/apps/overlay/AndroidManifest.xml b/apct-tests/perftests/core/apps/overlay/AndroidManifest.xml
new file mode 100644
index 0000000..52f5a89
--- /dev/null
+++ b/apct-tests/perftests/core/apps/overlay/AndroidManifest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.perftests.overlay">
+    <application android:hasCode="false" />
+    <uses-sdk android:targetSdkVersion="29" />
+    <overlay android:targetPackage="com.android.perftests.core" android:targetName="TestResources"/>
+</manifest>
\ No newline at end of file
diff --git a/apct-tests/perftests/core/apps/overlay/res/values/values.xml b/apct-tests/perftests/core/apps/overlay/res/values/values.xml
new file mode 100644
index 0000000..a1a8d83
--- /dev/null
+++ b/apct-tests/perftests/core/apps/overlay/res/values/values.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<resources>
+  <string name="short_text">B</string>
+</resources>
diff --git a/apct-tests/perftests/core/apps/overlay/res_large/values/values.xml b/apct-tests/perftests/core/apps/overlay/res_large/values/values.xml
new file mode 100644
index 0000000..e741446
--- /dev/null
+++ b/apct-tests/perftests/core/apps/overlay/res_large/values/values.xml
@@ -0,0 +1,274 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<resources>
+  <string name="short_text000">B</string>
+  <string name="short_text001">B</string>
+  <string name="short_text002">B</string>
+  <string name="short_text003">B</string>
+  <string name="short_text004">B</string>
+  <string name="short_text005">B</string>
+  <string name="short_text006">B</string>
+  <string name="short_text007">B</string>
+  <string name="short_text008">B</string>
+  <string name="short_text009">B</string>
+  <string name="short_text010">B</string>
+  <string name="short_text011">B</string>
+  <string name="short_text012">B</string>
+  <string name="short_text013">B</string>
+  <string name="short_text014">B</string>
+  <string name="short_text015">B</string>
+  <string name="short_text016">B</string>
+  <string name="short_text017">B</string>
+  <string name="short_text018">B</string>
+  <string name="short_text019">B</string>
+  <string name="short_text020">B</string>
+  <string name="short_text021">B</string>
+  <string name="short_text022">B</string>
+  <string name="short_text023">B</string>
+  <string name="short_text024">B</string>
+  <string name="short_text025">B</string>
+  <string name="short_text026">B</string>
+  <string name="short_text027">B</string>
+  <string name="short_text028">B</string>
+  <string name="short_text029">B</string>
+  <string name="short_text030">B</string>
+  <string name="short_text031">B</string>
+  <string name="short_text032">B</string>
+  <string name="short_text033">B</string>
+  <string name="short_text034">B</string>
+  <string name="short_text035">B</string>
+  <string name="short_text036">B</string>
+  <string name="short_text037">B</string>
+  <string name="short_text038">B</string>
+  <string name="short_text039">B</string>
+  <string name="short_text040">B</string>
+  <string name="short_text041">B</string>
+  <string name="short_text042">B</string>
+  <string name="short_text043">B</string>
+  <string name="short_text044">B</string>
+  <string name="short_text045">B</string>
+  <string name="short_text046">B</string>
+  <string name="short_text047">B</string>
+  <string name="short_text048">B</string>
+  <string name="short_text049">B</string>
+  <string name="short_text050">B</string>
+  <string name="short_text051">B</string>
+  <string name="short_text052">B</string>
+  <string name="short_text053">B</string>
+  <string name="short_text054">B</string>
+  <string name="short_text055">B</string>
+  <string name="short_text056">B</string>
+  <string name="short_text057">B</string>
+  <string name="short_text058">B</string>
+  <string name="short_text059">B</string>
+  <string name="short_text060">B</string>
+  <string name="short_text061">B</string>
+  <string name="short_text062">B</string>
+  <string name="short_text063">B</string>
+  <string name="short_text064">B</string>
+  <string name="short_text065">B</string>
+  <string name="short_text066">B</string>
+  <string name="short_text067">B</string>
+  <string name="short_text068">B</string>
+  <string name="short_text069">B</string>
+  <string name="short_text070">B</string>
+  <string name="short_text071">B</string>
+  <string name="short_text072">B</string>
+  <string name="short_text073">B</string>
+  <string name="short_text074">B</string>
+  <string name="short_text075">B</string>
+  <string name="short_text076">B</string>
+  <string name="short_text077">B</string>
+  <string name="short_text078">B</string>
+  <string name="short_text079">B</string>
+  <string name="short_text080">B</string>
+  <string name="short_text081">B</string>
+  <string name="short_text082">B</string>
+  <string name="short_text083">B</string>
+  <string name="short_text084">B</string>
+  <string name="short_text085">B</string>
+  <string name="short_text086">B</string>
+  <string name="short_text087">B</string>
+  <string name="short_text088">B</string>
+  <string name="short_text089">B</string>
+  <string name="short_text090">B</string>
+  <string name="short_text091">B</string>
+  <string name="short_text092">B</string>
+  <string name="short_text093">B</string>
+  <string name="short_text094">B</string>
+  <string name="short_text095">B</string>
+  <string name="short_text096">B</string>
+  <string name="short_text097">B</string>
+  <string name="short_text098">B</string>
+  <string name="short_text099">B</string>
+  <string name="short_text100">B</string>
+  <string name="short_text101">B</string>
+  <string name="short_text102">B</string>
+  <string name="short_text103">B</string>
+  <string name="short_text104">B</string>
+  <string name="short_text105">B</string>
+  <string name="short_text106">B</string>
+  <string name="short_text107">B</string>
+  <string name="short_text108">B</string>
+  <string name="short_text109">B</string>
+  <string name="short_text110">B</string>
+  <string name="short_text111">B</string>
+  <string name="short_text112">B</string>
+  <string name="short_text113">B</string>
+  <string name="short_text114">B</string>
+  <string name="short_text115">B</string>
+  <string name="short_text116">B</string>
+  <string name="short_text117">B</string>
+  <string name="short_text118">B</string>
+  <string name="short_text119">B</string>
+  <string name="short_text120">B</string>
+  <string name="short_text121">B</string>
+  <string name="short_text122">B</string>
+  <string name="short_text123">B</string>
+  <string name="short_text124">B</string>
+  <string name="short_text125">B</string>
+  <string name="short_text126">B</string>
+  <string name="short_text127">B</string>
+  <string name="short_text128">B</string>
+  <string name="short_text129">B</string>
+  <string name="short_text130">B</string>
+  <string name="short_text131">B</string>
+  <string name="short_text132">B</string>
+  <string name="short_text133">B</string>
+  <string name="short_text134">B</string>
+  <string name="short_text135">B</string>
+  <string name="short_text136">B</string>
+  <string name="short_text137">B</string>
+  <string name="short_text138">B</string>
+  <string name="short_text139">B</string>
+  <string name="short_text140">B</string>
+  <string name="short_text141">B</string>
+  <string name="short_text142">B</string>
+  <string name="short_text143">B</string>
+  <string name="short_text144">B</string>
+  <string name="short_text145">B</string>
+  <string name="short_text146">B</string>
+  <string name="short_text147">B</string>
+  <string name="short_text148">B</string>
+  <string name="short_text149">B</string>
+  <string name="short_text150">B</string>
+  <string name="short_text151">B</string>
+  <string name="short_text152">B</string>
+  <string name="short_text153">B</string>
+  <string name="short_text154">B</string>
+  <string name="short_text155">B</string>
+  <string name="short_text156">B</string>
+  <string name="short_text157">B</string>
+  <string name="short_text158">B</string>
+  <string name="short_text159">B</string>
+  <string name="short_text160">B</string>
+  <string name="short_text161">B</string>
+  <string name="short_text162">B</string>
+  <string name="short_text163">B</string>
+  <string name="short_text164">B</string>
+  <string name="short_text165">B</string>
+  <string name="short_text166">B</string>
+  <string name="short_text167">B</string>
+  <string name="short_text168">B</string>
+  <string name="short_text169">B</string>
+  <string name="short_text170">B</string>
+  <string name="short_text171">B</string>
+  <string name="short_text172">B</string>
+  <string name="short_text173">B</string>
+  <string name="short_text174">B</string>
+  <string name="short_text175">B</string>
+  <string name="short_text176">B</string>
+  <string name="short_text177">B</string>
+  <string name="short_text178">B</string>
+  <string name="short_text179">B</string>
+  <string name="short_text180">B</string>
+  <string name="short_text181">B</string>
+  <string name="short_text182">B</string>
+  <string name="short_text183">B</string>
+  <string name="short_text184">B</string>
+  <string name="short_text185">B</string>
+  <string name="short_text186">B</string>
+  <string name="short_text187">B</string>
+  <string name="short_text188">B</string>
+  <string name="short_text189">B</string>
+  <string name="short_text190">B</string>
+  <string name="short_text191">B</string>
+  <string name="short_text192">B</string>
+  <string name="short_text193">B</string>
+  <string name="short_text194">B</string>
+  <string name="short_text195">B</string>
+  <string name="short_text196">B</string>
+  <string name="short_text197">B</string>
+  <string name="short_text198">B</string>
+  <string name="short_text199">B</string>
+  <string name="short_text200">B</string>
+  <string name="short_text201">B</string>
+  <string name="short_text202">B</string>
+  <string name="short_text203">B</string>
+  <string name="short_text204">B</string>
+  <string name="short_text205">B</string>
+  <string name="short_text206">B</string>
+  <string name="short_text207">B</string>
+  <string name="short_text208">B</string>
+  <string name="short_text209">B</string>
+  <string name="short_text210">B</string>
+  <string name="short_text211">B</string>
+  <string name="short_text212">B</string>
+  <string name="short_text213">B</string>
+  <string name="short_text214">B</string>
+  <string name="short_text215">B</string>
+  <string name="short_text216">B</string>
+  <string name="short_text217">B</string>
+  <string name="short_text218">B</string>
+  <string name="short_text219">B</string>
+  <string name="short_text220">B</string>
+  <string name="short_text221">B</string>
+  <string name="short_text222">B</string>
+  <string name="short_text223">B</string>
+  <string name="short_text224">B</string>
+  <string name="short_text225">B</string>
+  <string name="short_text226">B</string>
+  <string name="short_text227">B</string>
+  <string name="short_text228">B</string>
+  <string name="short_text229">B</string>
+  <string name="short_text230">B</string>
+  <string name="short_text231">B</string>
+  <string name="short_text232">B</string>
+  <string name="short_text233">B</string>
+  <string name="short_text234">B</string>
+  <string name="short_text235">B</string>
+  <string name="short_text236">B</string>
+  <string name="short_text237">B</string>
+  <string name="short_text238">B</string>
+  <string name="short_text239">B</string>
+  <string name="short_text240">B</string>
+  <string name="short_text241">B</string>
+  <string name="short_text242">B</string>
+  <string name="short_text243">B</string>
+  <string name="short_text244">B</string>
+  <string name="short_text245">B</string>
+  <string name="short_text246">B</string>
+  <string name="short_text247">B</string>
+  <string name="short_text248">B</string>
+  <string name="short_text249">B</string>
+  <string name="short_text250">B</string>
+  <string name="short_text251">B</string>
+  <string name="short_text252">B</string>
+  <string name="short_text253">B</string>
+  <string name="short_text254">B</string>
+  <string name="short_text255">B</string>
+</resources>
diff --git a/apct-tests/perftests/core/apps/reources_manager/Android.bp b/apct-tests/perftests/core/apps/reources_manager/Android.bp
new file mode 100644
index 0000000..4516132
--- /dev/null
+++ b/apct-tests/perftests/core/apps/reources_manager/Android.bp
@@ -0,0 +1,34 @@
+// Copyright (C) 2019 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.
+
+android_test_helper_app {
+    name: "LargeResourcesCompressed",
+    static_libs: [ "androidx.appcompat_appcompat" ],
+}
+
+genrule {
+    name: "LargeResourcesUncompressed",
+    srcs: [ ":LargeResourcesCompressed" ],
+    out: ["LargeResourcesUncompressed.apk"],
+    cmd: "cp $(in) $(out) && unzip -o $(out) resources.arsc"
+         + " && zip $(out) resources.arsc"
+}
+
+java_library {
+    name: "apct-perftests-resources-manager-apps",
+    java_resources: [
+        ":LargeResourcesCompressed",
+        ":LargeResourcesUncompressed",
+    ],
+}
\ No newline at end of file
diff --git a/apct-tests/perftests/core/apps/reources_manager/AndroidManifest.xml b/apct-tests/perftests/core/apps/reources_manager/AndroidManifest.xml
new file mode 100644
index 0000000..adb4e40
--- /dev/null
+++ b/apct-tests/perftests/core/apps/reources_manager/AndroidManifest.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="fake.android">
+    <application android:hasCode="false" />
+    <uses-sdk android:targetSdkVersion="29" />
+</manifest>
\ No newline at end of file
diff --git a/apct-tests/perftests/core/res/color/color_state_list.xml b/apct-tests/perftests/core/res/color/color_state_list.xml
new file mode 100644
index 0000000..142e47a
--- /dev/null
+++ b/apct-tests/perftests/core/res/color/color_state_list.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:state_focused="true"
+        android:color="#000000" />
+    <item android:state_pressed="true"
+        android:state_enabled="false"
+        android:color="#212121" />
+    <item android:state_enabled="false"
+        android:color="#414141" />
+    <item android:color="#616161" />
+</selector>
\ No newline at end of file
diff --git a/apct-tests/perftests/core/res/values/overlayable.xml b/apct-tests/perftests/core/res/values/overlayable.xml
new file mode 100644
index 0000000..70cedd7
--- /dev/null
+++ b/apct-tests/perftests/core/res/values/overlayable.xml
@@ -0,0 +1,280 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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
+  -->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <overlayable name="TestResources">
+        <policy type="public">
+            <item type="string" name="short_text" />
+             <item type="string" name="short_text000" />
+             <item type="string" name="short_text001" />
+             <item type="string" name="short_text002" />
+             <item type="string" name="short_text003" />
+             <item type="string" name="short_text004" />
+             <item type="string" name="short_text005" />
+             <item type="string" name="short_text006" />
+             <item type="string" name="short_text007" />
+             <item type="string" name="short_text008" />
+             <item type="string" name="short_text009" />
+             <item type="string" name="short_text010" />
+             <item type="string" name="short_text011" />
+             <item type="string" name="short_text012" />
+             <item type="string" name="short_text013" />
+             <item type="string" name="short_text014" />
+             <item type="string" name="short_text015" />
+             <item type="string" name="short_text016" />
+             <item type="string" name="short_text017" />
+             <item type="string" name="short_text018" />
+             <item type="string" name="short_text019" />
+             <item type="string" name="short_text020" />
+             <item type="string" name="short_text021" />
+             <item type="string" name="short_text022" />
+             <item type="string" name="short_text023" />
+             <item type="string" name="short_text024" />
+             <item type="string" name="short_text025" />
+             <item type="string" name="short_text026" />
+             <item type="string" name="short_text027" />
+             <item type="string" name="short_text028" />
+             <item type="string" name="short_text029" />
+             <item type="string" name="short_text030" />
+             <item type="string" name="short_text031" />
+             <item type="string" name="short_text032" />
+             <item type="string" name="short_text033" />
+             <item type="string" name="short_text034" />
+             <item type="string" name="short_text035" />
+             <item type="string" name="short_text036" />
+             <item type="string" name="short_text037" />
+             <item type="string" name="short_text038" />
+             <item type="string" name="short_text039" />
+             <item type="string" name="short_text040" />
+             <item type="string" name="short_text041" />
+             <item type="string" name="short_text042" />
+             <item type="string" name="short_text043" />
+             <item type="string" name="short_text044" />
+             <item type="string" name="short_text045" />
+             <item type="string" name="short_text046" />
+             <item type="string" name="short_text047" />
+             <item type="string" name="short_text048" />
+             <item type="string" name="short_text049" />
+             <item type="string" name="short_text050" />
+             <item type="string" name="short_text051" />
+             <item type="string" name="short_text052" />
+             <item type="string" name="short_text053" />
+             <item type="string" name="short_text054" />
+             <item type="string" name="short_text055" />
+             <item type="string" name="short_text056" />
+             <item type="string" name="short_text057" />
+             <item type="string" name="short_text058" />
+             <item type="string" name="short_text059" />
+             <item type="string" name="short_text060" />
+             <item type="string" name="short_text061" />
+             <item type="string" name="short_text062" />
+             <item type="string" name="short_text063" />
+             <item type="string" name="short_text064" />
+             <item type="string" name="short_text065" />
+             <item type="string" name="short_text066" />
+             <item type="string" name="short_text067" />
+             <item type="string" name="short_text068" />
+             <item type="string" name="short_text069" />
+             <item type="string" name="short_text070" />
+             <item type="string" name="short_text071" />
+             <item type="string" name="short_text072" />
+             <item type="string" name="short_text073" />
+             <item type="string" name="short_text074" />
+             <item type="string" name="short_text075" />
+             <item type="string" name="short_text076" />
+             <item type="string" name="short_text077" />
+             <item type="string" name="short_text078" />
+             <item type="string" name="short_text079" />
+             <item type="string" name="short_text080" />
+             <item type="string" name="short_text081" />
+             <item type="string" name="short_text082" />
+             <item type="string" name="short_text083" />
+             <item type="string" name="short_text084" />
+             <item type="string" name="short_text085" />
+             <item type="string" name="short_text086" />
+             <item type="string" name="short_text087" />
+             <item type="string" name="short_text088" />
+             <item type="string" name="short_text089" />
+             <item type="string" name="short_text090" />
+             <item type="string" name="short_text091" />
+             <item type="string" name="short_text092" />
+             <item type="string" name="short_text093" />
+             <item type="string" name="short_text094" />
+             <item type="string" name="short_text095" />
+             <item type="string" name="short_text096" />
+             <item type="string" name="short_text097" />
+             <item type="string" name="short_text098" />
+             <item type="string" name="short_text099" />
+             <item type="string" name="short_text100" />
+             <item type="string" name="short_text101" />
+             <item type="string" name="short_text102" />
+             <item type="string" name="short_text103" />
+             <item type="string" name="short_text104" />
+             <item type="string" name="short_text105" />
+             <item type="string" name="short_text106" />
+             <item type="string" name="short_text107" />
+             <item type="string" name="short_text108" />
+             <item type="string" name="short_text109" />
+             <item type="string" name="short_text110" />
+             <item type="string" name="short_text111" />
+             <item type="string" name="short_text112" />
+             <item type="string" name="short_text113" />
+             <item type="string" name="short_text114" />
+             <item type="string" name="short_text115" />
+             <item type="string" name="short_text116" />
+             <item type="string" name="short_text117" />
+             <item type="string" name="short_text118" />
+             <item type="string" name="short_text119" />
+             <item type="string" name="short_text120" />
+             <item type="string" name="short_text121" />
+             <item type="string" name="short_text122" />
+             <item type="string" name="short_text123" />
+             <item type="string" name="short_text124" />
+             <item type="string" name="short_text125" />
+             <item type="string" name="short_text126" />
+             <item type="string" name="short_text127" />
+             <item type="string" name="short_text128" />
+             <item type="string" name="short_text129" />
+             <item type="string" name="short_text130" />
+             <item type="string" name="short_text131" />
+             <item type="string" name="short_text132" />
+             <item type="string" name="short_text133" />
+             <item type="string" name="short_text134" />
+             <item type="string" name="short_text135" />
+             <item type="string" name="short_text136" />
+             <item type="string" name="short_text137" />
+             <item type="string" name="short_text138" />
+             <item type="string" name="short_text139" />
+             <item type="string" name="short_text140" />
+             <item type="string" name="short_text141" />
+             <item type="string" name="short_text142" />
+             <item type="string" name="short_text143" />
+             <item type="string" name="short_text144" />
+             <item type="string" name="short_text145" />
+             <item type="string" name="short_text146" />
+             <item type="string" name="short_text147" />
+             <item type="string" name="short_text148" />
+             <item type="string" name="short_text149" />
+             <item type="string" name="short_text150" />
+             <item type="string" name="short_text151" />
+             <item type="string" name="short_text152" />
+             <item type="string" name="short_text153" />
+             <item type="string" name="short_text154" />
+             <item type="string" name="short_text155" />
+             <item type="string" name="short_text156" />
+             <item type="string" name="short_text157" />
+             <item type="string" name="short_text158" />
+             <item type="string" name="short_text159" />
+             <item type="string" name="short_text160" />
+             <item type="string" name="short_text161" />
+             <item type="string" name="short_text162" />
+             <item type="string" name="short_text163" />
+             <item type="string" name="short_text164" />
+             <item type="string" name="short_text165" />
+             <item type="string" name="short_text166" />
+             <item type="string" name="short_text167" />
+             <item type="string" name="short_text168" />
+             <item type="string" name="short_text169" />
+             <item type="string" name="short_text170" />
+             <item type="string" name="short_text171" />
+             <item type="string" name="short_text172" />
+             <item type="string" name="short_text173" />
+             <item type="string" name="short_text174" />
+             <item type="string" name="short_text175" />
+             <item type="string" name="short_text176" />
+             <item type="string" name="short_text177" />
+             <item type="string" name="short_text178" />
+             <item type="string" name="short_text179" />
+             <item type="string" name="short_text180" />
+             <item type="string" name="short_text181" />
+             <item type="string" name="short_text182" />
+             <item type="string" name="short_text183" />
+             <item type="string" name="short_text184" />
+             <item type="string" name="short_text185" />
+             <item type="string" name="short_text186" />
+             <item type="string" name="short_text187" />
+             <item type="string" name="short_text188" />
+             <item type="string" name="short_text189" />
+             <item type="string" name="short_text190" />
+             <item type="string" name="short_text191" />
+             <item type="string" name="short_text192" />
+             <item type="string" name="short_text193" />
+             <item type="string" name="short_text194" />
+             <item type="string" name="short_text195" />
+             <item type="string" name="short_text196" />
+             <item type="string" name="short_text197" />
+             <item type="string" name="short_text198" />
+             <item type="string" name="short_text199" />
+             <item type="string" name="short_text200" />
+             <item type="string" name="short_text201" />
+             <item type="string" name="short_text202" />
+             <item type="string" name="short_text203" />
+             <item type="string" name="short_text204" />
+             <item type="string" name="short_text205" />
+             <item type="string" name="short_text206" />
+             <item type="string" name="short_text207" />
+             <item type="string" name="short_text208" />
+             <item type="string" name="short_text209" />
+             <item type="string" name="short_text210" />
+             <item type="string" name="short_text211" />
+             <item type="string" name="short_text212" />
+             <item type="string" name="short_text213" />
+             <item type="string" name="short_text214" />
+             <item type="string" name="short_text215" />
+             <item type="string" name="short_text216" />
+             <item type="string" name="short_text217" />
+             <item type="string" name="short_text218" />
+             <item type="string" name="short_text219" />
+             <item type="string" name="short_text220" />
+             <item type="string" name="short_text221" />
+             <item type="string" name="short_text222" />
+             <item type="string" name="short_text223" />
+             <item type="string" name="short_text224" />
+             <item type="string" name="short_text225" />
+             <item type="string" name="short_text226" />
+             <item type="string" name="short_text227" />
+             <item type="string" name="short_text228" />
+             <item type="string" name="short_text229" />
+             <item type="string" name="short_text230" />
+             <item type="string" name="short_text231" />
+             <item type="string" name="short_text232" />
+             <item type="string" name="short_text233" />
+             <item type="string" name="short_text234" />
+             <item type="string" name="short_text235" />
+             <item type="string" name="short_text236" />
+             <item type="string" name="short_text237" />
+             <item type="string" name="short_text238" />
+             <item type="string" name="short_text239" />
+             <item type="string" name="short_text240" />
+             <item type="string" name="short_text241" />
+             <item type="string" name="short_text242" />
+             <item type="string" name="short_text243" />
+             <item type="string" name="short_text244" />
+             <item type="string" name="short_text245" />
+             <item type="string" name="short_text246" />
+             <item type="string" name="short_text247" />
+             <item type="string" name="short_text248" />
+             <item type="string" name="short_text249" />
+             <item type="string" name="short_text250" />
+             <item type="string" name="short_text251" />
+             <item type="string" name="short_text252" />
+             <item type="string" name="short_text253" />
+             <item type="string" name="short_text254" />
+             <item type="string" name="short_text255" />
+        </policy>
+    </overlayable>
+</resources>
diff --git a/apct-tests/perftests/core/res/values/strings.xml b/apct-tests/perftests/core/res/values/strings.xml
deleted file mode 100644
index 7ab325f..0000000
--- a/apct-tests/perftests/core/res/values/strings.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="long_text">text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text typo text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text text text text text
-        text text text text text text text text text text text text </string>
-    <string name="short_text">text text</string>
-</resources>
diff --git a/apct-tests/perftests/core/res/values/values.xml b/apct-tests/perftests/core/res/values/values.xml
new file mode 100644
index 0000000..aad42ba
--- /dev/null
+++ b/apct-tests/perftests/core/res/values/values.xml
@@ -0,0 +1,368 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="long_text">text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text typo text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text text text text text
+        text text text text text text text text text text text text </string>
+
+    <plurals name="plurals_text">
+        <item quantity="one">1 text</item>
+        <item quantity="other"><xliff:g id="count" example="3">%d</xliff:g> texts</item>
+    </plurals>
+
+    <string-array name="strings">
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+        <item>Run</item>
+        <item>the</item>
+        <item>performance</item>
+        <item>tests!</item>
+    </string-array>
+
+    <integer-array name="ints">
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+        <item>0</item>
+        <item>1</item>
+        <item>2</item>
+        <item>3</item>
+    </integer-array>
+
+    <color name="white">#ffffff</color>
+
+    <integer name="forty_two">42</integer>
+
+    <string name="short_text">text text</string>
+    <string name="short_text000">B</string>
+    <string name="short_text001">B</string>
+    <string name="short_text002">B</string>
+    <string name="short_text003">B</string>
+    <string name="short_text004">B</string>
+    <string name="short_text005">B</string>
+    <string name="short_text006">B</string>
+    <string name="short_text007">B</string>
+    <string name="short_text008">B</string>
+    <string name="short_text009">B</string>
+    <string name="short_text010">B</string>
+    <string name="short_text011">B</string>
+    <string name="short_text012">B</string>
+    <string name="short_text013">B</string>
+    <string name="short_text014">B</string>
+    <string name="short_text015">B</string>
+    <string name="short_text016">B</string>
+    <string name="short_text017">B</string>
+    <string name="short_text018">B</string>
+    <string name="short_text019">B</string>
+    <string name="short_text020">B</string>
+    <string name="short_text021">B</string>
+    <string name="short_text022">B</string>
+    <string name="short_text023">B</string>
+    <string name="short_text024">B</string>
+    <string name="short_text025">B</string>
+    <string name="short_text026">B</string>
+    <string name="short_text027">B</string>
+    <string name="short_text028">B</string>
+    <string name="short_text029">B</string>
+    <string name="short_text030">B</string>
+    <string name="short_text031">B</string>
+    <string name="short_text032">B</string>
+    <string name="short_text033">B</string>
+    <string name="short_text034">B</string>
+    <string name="short_text035">B</string>
+    <string name="short_text036">B</string>
+    <string name="short_text037">B</string>
+    <string name="short_text038">B</string>
+    <string name="short_text039">B</string>
+    <string name="short_text040">B</string>
+    <string name="short_text041">B</string>
+    <string name="short_text042">B</string>
+    <string name="short_text043">B</string>
+    <string name="short_text044">B</string>
+    <string name="short_text045">B</string>
+    <string name="short_text046">B</string>
+    <string name="short_text047">B</string>
+    <string name="short_text048">B</string>
+    <string name="short_text049">B</string>
+    <string name="short_text050">B</string>
+    <string name="short_text051">B</string>
+    <string name="short_text052">B</string>
+    <string name="short_text053">B</string>
+    <string name="short_text054">B</string>
+    <string name="short_text055">B</string>
+    <string name="short_text056">B</string>
+    <string name="short_text057">B</string>
+    <string name="short_text058">B</string>
+    <string name="short_text059">B</string>
+    <string name="short_text060">B</string>
+    <string name="short_text061">B</string>
+    <string name="short_text062">B</string>
+    <string name="short_text063">B</string>
+    <string name="short_text064">B</string>
+    <string name="short_text065">B</string>
+    <string name="short_text066">B</string>
+    <string name="short_text067">B</string>
+    <string name="short_text068">B</string>
+    <string name="short_text069">B</string>
+    <string name="short_text070">B</string>
+    <string name="short_text071">B</string>
+    <string name="short_text072">B</string>
+    <string name="short_text073">B</string>
+    <string name="short_text074">B</string>
+    <string name="short_text075">B</string>
+    <string name="short_text076">B</string>
+    <string name="short_text077">B</string>
+    <string name="short_text078">B</string>
+    <string name="short_text079">B</string>
+    <string name="short_text080">B</string>
+    <string name="short_text081">B</string>
+    <string name="short_text082">B</string>
+    <string name="short_text083">B</string>
+    <string name="short_text084">B</string>
+    <string name="short_text085">B</string>
+    <string name="short_text086">B</string>
+    <string name="short_text087">B</string>
+    <string name="short_text088">B</string>
+    <string name="short_text089">B</string>
+    <string name="short_text090">B</string>
+    <string name="short_text091">B</string>
+    <string name="short_text092">B</string>
+    <string name="short_text093">B</string>
+    <string name="short_text094">B</string>
+    <string name="short_text095">B</string>
+    <string name="short_text096">B</string>
+    <string name="short_text097">B</string>
+    <string name="short_text098">B</string>
+    <string name="short_text099">B</string>
+    <string name="short_text100">B</string>
+    <string name="short_text101">B</string>
+    <string name="short_text102">B</string>
+    <string name="short_text103">B</string>
+    <string name="short_text104">B</string>
+    <string name="short_text105">B</string>
+    <string name="short_text106">B</string>
+    <string name="short_text107">B</string>
+    <string name="short_text108">B</string>
+    <string name="short_text109">B</string>
+    <string name="short_text110">B</string>
+    <string name="short_text111">B</string>
+    <string name="short_text112">B</string>
+    <string name="short_text113">B</string>
+    <string name="short_text114">B</string>
+    <string name="short_text115">B</string>
+    <string name="short_text116">B</string>
+    <string name="short_text117">B</string>
+    <string name="short_text118">B</string>
+    <string name="short_text119">B</string>
+    <string name="short_text120">B</string>
+    <string name="short_text121">B</string>
+    <string name="short_text122">B</string>
+    <string name="short_text123">B</string>
+    <string name="short_text124">B</string>
+    <string name="short_text125">B</string>
+    <string name="short_text126">B</string>
+    <string name="short_text127">B</string>
+    <string name="short_text128">B</string>
+    <string name="short_text129">B</string>
+    <string name="short_text130">B</string>
+    <string name="short_text131">B</string>
+    <string name="short_text132">B</string>
+    <string name="short_text133">B</string>
+    <string name="short_text134">B</string>
+    <string name="short_text135">B</string>
+    <string name="short_text136">B</string>
+    <string name="short_text137">B</string>
+    <string name="short_text138">B</string>
+    <string name="short_text139">B</string>
+    <string name="short_text140">B</string>
+    <string name="short_text141">B</string>
+    <string name="short_text142">B</string>
+    <string name="short_text143">B</string>
+    <string name="short_text144">B</string>
+    <string name="short_text145">B</string>
+    <string name="short_text146">B</string>
+    <string name="short_text147">B</string>
+    <string name="short_text148">B</string>
+    <string name="short_text149">B</string>
+    <string name="short_text150">B</string>
+    <string name="short_text151">B</string>
+    <string name="short_text152">B</string>
+    <string name="short_text153">B</string>
+    <string name="short_text154">B</string>
+    <string name="short_text155">B</string>
+    <string name="short_text156">B</string>
+    <string name="short_text157">B</string>
+    <string name="short_text158">B</string>
+    <string name="short_text159">B</string>
+    <string name="short_text160">B</string>
+    <string name="short_text161">B</string>
+    <string name="short_text162">B</string>
+    <string name="short_text163">B</string>
+    <string name="short_text164">B</string>
+    <string name="short_text165">B</string>
+    <string name="short_text166">B</string>
+    <string name="short_text167">B</string>
+    <string name="short_text168">B</string>
+    <string name="short_text169">B</string>
+    <string name="short_text170">B</string>
+    <string name="short_text171">B</string>
+    <string name="short_text172">B</string>
+    <string name="short_text173">B</string>
+    <string name="short_text174">B</string>
+    <string name="short_text175">B</string>
+    <string name="short_text176">B</string>
+    <string name="short_text177">B</string>
+    <string name="short_text178">B</string>
+    <string name="short_text179">B</string>
+    <string name="short_text180">B</string>
+    <string name="short_text181">B</string>
+    <string name="short_text182">B</string>
+    <string name="short_text183">B</string>
+    <string name="short_text184">B</string>
+    <string name="short_text185">B</string>
+    <string name="short_text186">B</string>
+    <string name="short_text187">B</string>
+    <string name="short_text188">B</string>
+    <string name="short_text189">B</string>
+    <string name="short_text190">B</string>
+    <string name="short_text191">B</string>
+    <string name="short_text192">B</string>
+    <string name="short_text193">B</string>
+    <string name="short_text194">B</string>
+    <string name="short_text195">B</string>
+    <string name="short_text196">B</string>
+    <string name="short_text197">B</string>
+    <string name="short_text198">B</string>
+    <string name="short_text199">B</string>
+    <string name="short_text200">B</string>
+    <string name="short_text201">B</string>
+    <string name="short_text202">B</string>
+    <string name="short_text203">B</string>
+    <string name="short_text204">B</string>
+    <string name="short_text205">B</string>
+    <string name="short_text206">B</string>
+    <string name="short_text207">B</string>
+    <string name="short_text208">B</string>
+    <string name="short_text209">B</string>
+    <string name="short_text210">B</string>
+    <string name="short_text211">B</string>
+    <string name="short_text212">B</string>
+    <string name="short_text213">B</string>
+    <string name="short_text214">B</string>
+    <string name="short_text215">B</string>
+    <string name="short_text216">B</string>
+    <string name="short_text217">B</string>
+    <string name="short_text218">B</string>
+    <string name="short_text219">B</string>
+    <string name="short_text220">B</string>
+    <string name="short_text221">B</string>
+    <string name="short_text222">B</string>
+    <string name="short_text223">B</string>
+    <string name="short_text224">B</string>
+    <string name="short_text225">B</string>
+    <string name="short_text226">B</string>
+    <string name="short_text227">B</string>
+    <string name="short_text228">B</string>
+    <string name="short_text229">B</string>
+    <string name="short_text230">B</string>
+    <string name="short_text231">B</string>
+    <string name="short_text232">B</string>
+    <string name="short_text233">B</string>
+    <string name="short_text234">B</string>
+    <string name="short_text235">B</string>
+    <string name="short_text236">B</string>
+    <string name="short_text237">B</string>
+    <string name="short_text238">B</string>
+    <string name="short_text239">B</string>
+    <string name="short_text240">B</string>
+    <string name="short_text241">B</string>
+    <string name="short_text242">B</string>
+    <string name="short_text243">B</string>
+    <string name="short_text244">B</string>
+    <string name="short_text245">B</string>
+    <string name="short_text246">B</string>
+    <string name="short_text247">B</string>
+    <string name="short_text248">B</string>
+    <string name="short_text249">B</string>
+    <string name="short_text250">B</string>
+    <string name="short_text251">B</string>
+    <string name="short_text252">B</string>
+    <string name="short_text253">B</string>
+    <string name="short_text254">B</string>
+    <string name="short_text255">B</string>
+</resources>
diff --git a/apct-tests/perftests/core/src/android/app/OverlayManagerPerfTest.java b/apct-tests/perftests/core/src/android/app/OverlayManagerPerfTest.java
new file mode 100644
index 0000000..fcb13a8
--- /dev/null
+++ b/apct-tests/perftests/core/src/android/app/OverlayManagerPerfTest.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright (C) 2019 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.app;
+
+import static org.junit.Assert.assertTrue;
+
+import android.content.Context;
+import android.content.om.OverlayManager;
+import android.os.UserHandle;
+import android.perftests.utils.BenchmarkState;
+import android.perftests.utils.PerfStatusReporter;
+import android.perftests.utils.TestPackageInstaller;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.LargeTest;
+
+import com.android.perftests.core.R;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Benchmarks for {@link android.content.om.OverlayManager}.
+ */
+@LargeTest
+public class OverlayManagerPerfTest {
+    private static final int OVERLAY_PKG_COUNT = 10;
+    private static Context sContext;
+    private static OverlayManager sOverlayManager;
+    private static Executor sExecutor;
+    private static ArrayList<TestPackageInstaller.InstalledPackage> sSmallOverlays =
+            new ArrayList<>();
+    private static ArrayList<TestPackageInstaller.InstalledPackage> sLargeOverlays =
+            new ArrayList<>();
+
+    @Rule
+    public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
+
+    @BeforeClass
+    public static void classSetUp() throws Exception {
+        sContext = InstrumentationRegistry.getTargetContext();
+        sOverlayManager = new OverlayManager(sContext);
+        sExecutor = (command) -> new Thread(command).start();
+
+        // Install all of the test overlays.
+        TestPackageInstaller installer = new TestPackageInstaller(sContext);
+        for (int i = 0; i < OVERLAY_PKG_COUNT; i++) {
+            sSmallOverlays.add(installer.installPackage("Overlay" + i +".apk"));
+            sLargeOverlays.add(installer.installPackage("LargeOverlay" + i +".apk"));
+        }
+    }
+
+    @AfterClass
+    public static void classTearDown() throws Exception {
+        for (TestPackageInstaller.InstalledPackage overlay : sSmallOverlays) {
+            overlay.uninstall();
+        }
+
+        for (TestPackageInstaller.InstalledPackage overlay : sLargeOverlays) {
+            overlay.uninstall();
+        }
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        // Disable all test overlays after each test.
+        for (TestPackageInstaller.InstalledPackage overlay : sSmallOverlays) {
+            assertSetEnabled(sContext, overlay.getPackageName(), false);
+        }
+
+        for (TestPackageInstaller.InstalledPackage overlay : sLargeOverlays) {
+            assertSetEnabled(sContext, overlay.getPackageName(), false);
+        }
+    }
+
+    /**
+     * Enables the overlay and waits for the APK path change sto be propagated to the context
+     * AssetManager.
+     */
+    private void assertSetEnabled(Context context, String overlayPackage, boolean eanabled)
+            throws Exception {
+        sOverlayManager.setEnabled(overlayPackage, true, UserHandle.SYSTEM);
+
+        // Wait for the overlay changes to propagate
+        FutureTask<Boolean> task = new FutureTask<>(() -> {
+            while (true) {
+                for (String path : context.getAssets().getApkPaths()) {
+                    if (eanabled == path.contains(overlayPackage)) {
+                        return true;
+                    }
+                }
+            }
+        });
+
+        sExecutor.execute(task);
+        assertTrue("Failed to load overlay " + overlayPackage,
+                task.get(20, TimeUnit.SECONDS));
+    }
+
+    @Test
+    public void setEnabledWarmCache() throws Exception {
+        String packageName = sSmallOverlays.get(0).getPackageName();
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            assertSetEnabled(sContext, packageName, true);
+
+            // Disable the overlay for the next iteration of the test
+            state.pauseTiming();
+            assertSetEnabled(sContext, packageName, false);
+            state.resumeTiming();
+        }
+    }
+
+    @Test
+    public void setEnabledColdCacheSmallOverlay() throws Exception {
+        String packageName = sSmallOverlays.get(0).getPackageName();
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            assertSetEnabled(sContext, packageName, true);
+
+            // Disable the overlay and remove the idmap for the next iteration of the test
+            state.pauseTiming();
+            assertSetEnabled(sContext, packageName, false);
+            sOverlayManager.invalidateCachesForOverlay(packageName, UserHandle.SYSTEM);
+            state.resumeTiming();
+        }
+    }
+
+    @Test
+    public void setEnabledColdCacheLargeOverlay() throws Exception {
+        String packageName = sLargeOverlays.get(0).getPackageName();
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            assertSetEnabled(sContext, packageName, true);
+
+            // Disable the overlay and remove the idmap for the next iteration of the test
+            state.pauseTiming();
+            assertSetEnabled(sContext, packageName, false);
+            sOverlayManager.invalidateCachesForOverlay(packageName, UserHandle.SYSTEM);
+            state.resumeTiming();
+        }
+    }
+
+    @Test
+    public void setEnabledDisable() throws Exception {
+        String packageName = sSmallOverlays.get(0).getPackageName();
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            state.pauseTiming();
+            assertSetEnabled(sContext, packageName, true);
+            state.resumeTiming();
+
+            assertSetEnabled(sContext, packageName, false);
+        }
+    }
+
+    @Test
+    public void getStringOneSmallOverlay() throws Exception {
+        String packageName = sSmallOverlays.get(0).getPackageName();
+        assertSetEnabled(sContext, packageName, true);
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            sContext.getString(R.string.short_text);
+        }
+
+        assertSetEnabled(sContext, packageName, false);
+    }
+
+    @Test
+    public void getStringOneLargeOverlay() throws Exception {
+        String packageName = sLargeOverlays.get(0).getPackageName();
+        assertSetEnabled(sContext, packageName, true);
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            for (int resId = R.string.short_text000; resId < R.string.short_text255; resId++) {
+                sContext.getString(resId);
+            }
+        }
+
+        assertSetEnabled(sContext, packageName, false);
+    }
+
+    @Test
+    public void getStringTenOverlays() throws Exception {
+        // Enable all test overlays
+        for (TestPackageInstaller.InstalledPackage overlay : sSmallOverlays) {
+            assertSetEnabled(sContext, overlay.getPackageName(), true);
+        }
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            sContext.getString(R.string.short_text);
+        }
+    }
+
+    @Test
+    public void getStringLargeTenOverlays() throws Exception {
+        // Enable all test overlays
+        for (TestPackageInstaller.InstalledPackage overlay : sLargeOverlays) {
+            assertSetEnabled(sContext, overlay.getPackageName(), true);
+        }
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            for (int resId = R.string.short_text000; resId < R.string.short_text255; resId++) {
+                sContext.getString(resId);
+            }
+        }
+    }
+}
diff --git a/apct-tests/perftests/core/src/android/app/ResourcesManagerPerfTest.java b/apct-tests/perftests/core/src/android/app/ResourcesManagerPerfTest.java
new file mode 100644
index 0000000..2955d2c
--- /dev/null
+++ b/apct-tests/perftests/core/src/android/app/ResourcesManagerPerfTest.java
@@ -0,0 +1,139 @@
+/*
+ * 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.app;
+
+import android.content.Context;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.perftests.utils.BenchmarkState;
+import android.perftests.utils.PerfStatusReporter;
+import android.view.Display;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.LargeTest;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * Benchmarks for {@link android.app.ResourcesManager}.
+ */
+@LargeTest
+public class ResourcesManagerPerfTest {
+    private static Context sContext;
+    private static File sResourcesCompressed;
+    private static File sResourcesUncompressed;
+
+    @Rule
+    public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+        sContext = InstrumentationRegistry.getTargetContext();
+        sResourcesCompressed = copyApkToTemp("LargeResourcesCompressed.apk",
+                "LargeResourcesCompressed.apk");
+        sResourcesUncompressed = copyApkToTemp("LargeResourcesUncompressed.apk",
+                "LargeResourcesUncompressed.apk");
+    }
+
+    @AfterClass
+    public static void tearDown() {
+        Assert.assertTrue(sResourcesCompressed.delete());
+        Assert.assertTrue(sResourcesUncompressed.delete());
+    }
+
+    private static File copyApkToTemp(String inputFileName, String fileName) throws Exception {
+        File file = File.createTempFile(fileName, null, sContext.getCacheDir());
+        try (OutputStream tempOutputStream = new FileOutputStream(file);
+             InputStream is = sContext.getResources().getAssets().openNonAsset(inputFileName)) {
+            byte[] buffer = new byte[4096];
+            int n;
+            while ((n = is.read(buffer)) >= 0) {
+                tempOutputStream.write(buffer, 0, n);
+            }
+            tempOutputStream.flush();
+        }
+        return file;
+    }
+
+    private void getResourcesForPath(String path) {
+        ResourcesManager.getInstance().getResources(null, path, null, null, null,
+                Display.DEFAULT_DISPLAY, null, sContext.getResources().getCompatibilityInfo(),
+                null);
+    }
+
+    @Test
+    public void getResourcesCached() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        getResourcesForPath(sResourcesCompressed.getPath());
+        while (state.keepRunning()) {
+            getResourcesForPath(sResourcesCompressed.getPath());
+        }
+    }
+
+    @Test
+    public void getResourcesCompressedUncached() {
+        ResourcesManager resourcesManager = ResourcesManager.getInstance();
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            state.pauseTiming();
+            resourcesManager.invalidatePath(sResourcesCompressed.getPath());
+            state.resumeTiming();
+
+            getResourcesForPath(sResourcesCompressed.getPath());
+        }
+    }
+
+    @Test
+    public void getResourcesUncompressedUncached() {
+        ResourcesManager resourcesManager = ResourcesManager.getInstance();
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            state.pauseTiming();
+            resourcesManager.invalidatePath(sResourcesUncompressed.getPath());
+            state.resumeTiming();
+
+            getResourcesForPath(sResourcesUncompressed.getPath());
+        }
+    }
+
+    @Test
+    public void applyConfigurationToResourcesLocked() {
+        ResourcesManager resourcesManager = ResourcesManager.getInstance();
+        Configuration c = new Configuration(resourcesManager.getConfiguration());
+        c.uiMode = Configuration.UI_MODE_TYPE_WATCH;
+
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            resourcesManager.applyConfigurationToResources(c, null);
+
+            // Alternate configurations to ensure the set configuration is different each iteration
+            if (c.uiMode == Configuration.UI_MODE_TYPE_WATCH) {
+                c.uiMode = Configuration.UI_MODE_TYPE_TELEVISION;
+            } else {
+                c.uiMode = Configuration.UI_MODE_TYPE_WATCH;
+            }
+        }
+    }
+}
diff --git a/apct-tests/perftests/core/src/android/app/ResourcesPerfTest.java b/apct-tests/perftests/core/src/android/app/ResourcesPerfTest.java
index c3e43ee..7216244 100644
--- a/apct-tests/perftests/core/src/android/app/ResourcesPerfTest.java
+++ b/apct-tests/perftests/core/src/android/app/ResourcesPerfTest.java
@@ -18,15 +18,18 @@
 
 import static org.junit.Assert.fail;
 
-import android.content.res.AssetManager;
+import android.content.Context;
 import android.content.res.Resources;
 import android.content.res.XmlResourceParser;
 import android.perftests.utils.BenchmarkState;
 import android.perftests.utils.PerfStatusReporter;
+import android.util.TypedValue;
 
+import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.LargeTest;
 
-import org.junit.After;
+import com.android.perftests.core.R;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -43,36 +46,123 @@
     @Rule
     public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
 
-    private AssetManager mAsset;
     private Resources mRes;
 
-    private int mTextId;
-    private int mColorId;
-    private int mIntegerId;
-    private int mLayoutId;
-
     @Before
     public void setUp() {
-        mAsset = new AssetManager();
-        mAsset.addAssetPath("/system/framework/framework-res.apk");
-        mRes = new Resources(mAsset, null, null);
-
-        mTextId = mRes.getIdentifier("cancel", "string", "android");
-        mColorId = mRes.getIdentifier("transparent", "color", "android");
-        mIntegerId = mRes.getIdentifier("config_shortAnimTime", "integer", "android");
-        mLayoutId = mRes.getIdentifier("two_line_list_item", "layout", "android");
+        Context context = InstrumentationRegistry.getTargetContext();
+        mRes = context.getResources();
     }
 
-    @After
-    public void tearDown() {
-        mAsset.close();
+    @Test
+    public void getValue() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        TypedValue value = new TypedValue();
+        while (state.keepRunning()) {
+            mRes.getValue(R.integer.forty_two, value, false /* resolve_refs */);
+        }
+    }
+
+    @Test
+    public void getFrameworkValue() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        TypedValue value = new TypedValue();
+        while (state.keepRunning()) {
+            mRes.getValue(com.android.internal.R.integer.autofill_max_visible_datasets, value,
+                    false /* resolve_refs */);
+        }
+    }
+
+    @Test
+    public void getValueString() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        TypedValue value = new TypedValue();
+        while (state.keepRunning()) {
+            mRes.getValue(R.string.long_text, value, false /* resolve_refs */);
+        }
+    }
+
+    @Test
+    public void getFrameworkStringValue() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        TypedValue value = new TypedValue();
+        while (state.keepRunning()) {
+            mRes.getValue(com.android.internal.R.string.cancel, value, false /* resolve_refs */);
+        }
+    }
+
+    @Test
+    public void getValueManyConfigurations() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        TypedValue value = new TypedValue();
+        while (state.keepRunning()) {
+            mRes.getValue(com.android.internal.R.string.mmcc_illegal_me, value,
+                    false /* resolve_refs */);
+        }
     }
 
     @Test
     public void getText() {
         final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
         while (state.keepRunning()) {
-            mRes.getText(mTextId);
+            mRes.getText(R.string.long_text);
+        }
+    }
+
+
+    @Test
+    public void getFont() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getFont(R.font.samplefont);
+        }
+    }
+
+    @Test
+    public void getString() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getString(R.string.long_text);
+        }
+    }
+
+    @Test
+    public void getQuantityString() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getQuantityString(R.plurals.plurals_text, 5);
+        }
+    }
+
+    @Test
+    public void getQuantityText() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getQuantityText(R.plurals.plurals_text, 5);
+        }
+    }
+
+    @Test
+    public void getTextArray() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getTextArray(R.array.strings);
+        }
+    }
+
+    @Test
+    public void getStringArray() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getStringArray(R.array.strings);
+        }
+    }
+
+    @Test
+    public void getIntegerArray() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getIntArray(R.array.ints);
         }
     }
 
@@ -80,15 +170,23 @@
     public void getColor() {
         final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
         while (state.keepRunning()) {
-            mRes.getColor(mColorId, null);
+            mRes.getColor(R.color.white, null);
         }
     }
 
     @Test
-    public void getInteger() {
+    public void getColorStateList() {
         final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
         while (state.keepRunning()) {
-            mRes.getInteger(mIntegerId);
+            mRes.getColorStateList(R.color.color_state_list, null);
+        }
+    }
+
+    @Test
+    public void getVectorDrawable() {
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            mRes.getDrawable(R.drawable.vector_drawable01, null);
         }
     }
 
@@ -96,7 +194,7 @@
     public void getLayoutAndTravese() {
         final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
         while (state.keepRunning()) {
-            try (XmlResourceParser parser = mRes.getLayout(mLayoutId)) {
+            try (XmlResourceParser parser = mRes.getLayout(R.layout.test_relative_layout)) {
                 while (parser.next() != XmlPullParser.END_DOCUMENT) {
                     // Walk the entire tree
                 }
@@ -105,4 +203,23 @@
             }
         }
     }
-}
+
+    @Test
+    public void getLayoutAndTraverseInvalidateCaches() {
+        mRes.flushLayoutCache();
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            try (XmlResourceParser parser = mRes.getLayout(R.layout.test_relative_layout)) {
+                while (parser.next() != XmlPullParser.END_DOCUMENT) {
+                    // Walk the entire tree
+                }
+            } catch (IOException | XmlPullParserException exception) {
+                fail("Parsing of the layout failed. Something is really broken");
+            }
+
+            state.pauseTiming();
+            mRes.flushLayoutCache();
+            state.resumeTiming();
+        }
+    }
+}
\ No newline at end of file
diff --git a/apct-tests/perftests/core/src/android/app/ResourcesThemePerfTest.java b/apct-tests/perftests/core/src/android/app/ResourcesThemePerfTest.java
index 1b07572..6123e69 100644
--- a/apct-tests/perftests/core/src/android/app/ResourcesThemePerfTest.java
+++ b/apct-tests/perftests/core/src/android/app/ResourcesThemePerfTest.java
@@ -16,13 +16,19 @@
 package android.app;
 
 import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.res.Configuration;
 import android.content.res.Resources;
+import android.os.UserHandle;
 import android.perftests.utils.BenchmarkState;
 import android.perftests.utils.PerfStatusReporter;
+import android.view.Display;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.LargeTest;
 
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -35,13 +41,69 @@
     @Rule
     public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
 
+    private Context mContext;
+    private int mThemeResId;
     private Resources.Theme mTheme;
 
     @Before
-    public void setUp() {
-        Context context = InstrumentationRegistry.getTargetContext();
-        mTheme = context.getTheme();
+    public void setUp() throws Exception {
+        mContext = InstrumentationRegistry.getTargetContext();
+        mThemeResId = com.android.perftests.core.R.style.Base_V7_Theme_AppCompat;
+        mTheme = mContext.getResources().newTheme();
+        mTheme.applyStyle(mThemeResId, true /* force */);
+    }
 
+    @Test
+    public void applyStyle() {
+        Resources.Theme destTheme = mContext.getResources().newTheme();
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            destTheme.applyStyle(mThemeResId, true /* force */);
+        }
+    }
+
+    @Test
+    public void rebase() {
+        Resources.Theme destTheme = mContext.getResources().newTheme();
+        destTheme.applyStyle(mThemeResId, true /* force */);
+        destTheme.applyStyle(android.R.style.Theme_Material, true /* force */);
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            destTheme.rebase();
+        }
+    }
+
+    @Test
+    public void setToSameAssetManager() {
+        Resources.Theme destTheme = mContext.getResources().newTheme();
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            destTheme.setTo(mTheme);
+        }
+    }
+
+    @Test
+    public void setToDifferentAssetManager() throws Exception {
+        // Create a new Resources object with the same asset paths but a different AssetManager
+        PackageManager packageManager = mContext.getApplicationContext().getPackageManager();
+        ApplicationInfo ai = packageManager.getApplicationInfo(mContext.getPackageName(),
+                UserHandle.myUserId());
+
+        ResourcesManager resourcesManager = ResourcesManager.getInstance();
+        Configuration c = resourcesManager.getConfiguration();
+        c.orientation = (c.orientation == Configuration.ORIENTATION_PORTRAIT)
+                ? Configuration.ORIENTATION_LANDSCAPE : Configuration.ORIENTATION_PORTRAIT;
+
+        Resources destResources = resourcesManager.getResources(null, ai.sourceDir,
+                ai.splitSourceDirs, ai.resourceDirs, ai.sharedLibraryFiles, Display.DEFAULT_DISPLAY,
+                c, mContext.getResources().getCompatibilityInfo(), null);
+        Assert.assertNotEquals(destResources.getAssets(), mContext.getAssets());
+
+        Resources.Theme destTheme = destResources.newTheme();
+        final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        while (state.keepRunning()) {
+            destTheme.setTo(mTheme);
+        }
     }
 
     @Test
@@ -51,5 +113,4 @@
             mTheme.obtainStyledAttributes(android.R.style.Theme_Material, android.R.styleable.View);
         }
     }
-
-}
+}
\ No newline at end of file
diff --git a/apct-tests/perftests/multiuser/AndroidManifest.xml b/apct-tests/perftests/multiuser/AndroidManifest.xml
index b2a9524..893c8ca 100644
--- a/apct-tests/perftests/multiuser/AndroidManifest.xml
+++ b/apct-tests/perftests/multiuser/AndroidManifest.xml
@@ -22,6 +22,7 @@
     <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
     <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
     <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 
     <application>
         <uses-library android:name="android.test.runner" />
diff --git a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
index 32107b4..e74e4a9 100644
--- a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
+++ b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
@@ -38,8 +38,10 @@
 import android.os.IBinder;
 import android.os.IProgressListener;
 import android.os.RemoteException;
+import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.perftests.utils.ShellHelper;
 import android.util.Log;
 import android.view.WindowManagerGlobal;
 
@@ -85,6 +87,14 @@
 
     private static final String DUMMY_PACKAGE_NAME = "perftests.multiuser.apps.dummyapp";
 
+    // Copy of UserSystemPackageInstaller whitelist mode constants.
+    private static final String PACKAGE_WHITELIST_MODE_PROP =
+            "persist.debug.user.package_whitelist_mode";
+    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE = 0;
+    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE = 0b001;
+    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST = 0b100;
+    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT = -1;
+
     private UserManager mUm;
     private ActivityManager mAm;
     private IActivityManager mIam;
@@ -442,6 +452,55 @@
         }
     }
 
+    // TODO: This is just a POC. Do this properly and add more.
+    /** Tests starting (unlocking) a newly-created profile using the user-type-pkg-whitelist. */
+    @Test
+    public void managedProfileUnlock_usingWhitelist() throws Exception {
+        assumeTrue(mHasManagedUserFeature);
+        final int origMode = getUserTypePackageWhitelistMode();
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE
+                | USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST);
+
+        try {
+            while (mRunner.keepRunning()) {
+                mRunner.pauseTiming();
+                final int userId = createManagedProfile();
+                mRunner.resumeTiming();
+
+                startUserInBackground(userId);
+
+                mRunner.pauseTiming();
+                removeUser(userId);
+                mRunner.resumeTiming();
+            }
+        } finally {
+            setUserTypePackageWhitelistMode(origMode);
+        }
+    }
+    /** Tests starting (unlocking) a newly-created profile NOT using the user-type-pkg-whitelist. */
+    @Test
+    public void managedProfileUnlock_notUsingWhitelist() throws Exception {
+        assumeTrue(mHasManagedUserFeature);
+        final int origMode = getUserTypePackageWhitelistMode();
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE);
+
+        try {
+            while (mRunner.keepRunning()) {
+                mRunner.pauseTiming();
+                final int userId = createManagedProfile();
+                mRunner.resumeTiming();
+
+                startUserInBackground(userId);
+
+                mRunner.pauseTiming();
+                removeUser(userId);
+                mRunner.resumeTiming();
+            }
+        } finally {
+            setUserTypePackageWhitelistMode(origMode);
+        }
+    }
+
     /** Creates a new user, returning its userId. */
     private int createUserNoFlags() {
         return createUserWithFlags(/* flags= */ 0);
@@ -458,6 +517,10 @@
     private int createManagedProfile() {
         final UserInfo userInfo = mUm.createProfileForUser("TestProfile",
                 UserInfo.FLAG_MANAGED_PROFILE, mAm.getCurrentUser());
+        if (userInfo == null) {
+            throw new IllegalStateException("Creating managed profile failed. Most likely there is "
+                    + "already a pre-existing profile on the device.");
+        }
         mUsersToRemove.add(userInfo.id);
         return userInfo.id;
     }
@@ -627,6 +690,20 @@
         }
     }
 
+    /** Gets the PACKAGE_WHITELIST_MODE_PROP System Property. */
+    private int getUserTypePackageWhitelistMode() {
+        return SystemProperties.getInt(PACKAGE_WHITELIST_MODE_PROP,
+                USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT);
+    }
+
+    /** Sets the PACKAGE_WHITELIST_MODE_PROP System Property to the given value. */
+    private void setUserTypePackageWhitelistMode(int mode) {
+        String result = ShellHelper.runShellCommand(
+                String.format("setprop %s %d", PACKAGE_WHITELIST_MODE_PROP, mode));
+        attestFalse("Failed to set sysprop " + PACKAGE_WHITELIST_MODE_PROP + ": " + result,
+                result != null && result.contains("Failed"));
+    }
+
     private void removeUser(int userId) {
         try {
             mUm.removeUser(userId);
diff --git a/apct-tests/perftests/textclassifier/run.sh b/apct-tests/perftests/textclassifier/run.sh
index 8660d26..d36d190 100755
--- a/apct-tests/perftests/textclassifier/run.sh
+++ b/apct-tests/perftests/textclassifier/run.sh
@@ -1,5 +1,5 @@
 set -e
-make TextClassifierPerfTests perf-setup.sh
+build/soong/soong_ui.bash --make-mode TextClassifierPerfTests perf-setup.sh
 adb install ${OUT}/testcases/TextClassifierPerfTests/arm64/TextClassifierPerfTests.apk
 adb shell cmd package compile -m speed -f com.android.perftests.textclassifier
 adb push ${OUT}/obj/EXECUTABLES/perf-setup.sh_intermediates/perf-setup.sh /data/local/tmp/
diff --git a/apct-tests/perftests/utils/src/android/perftests/utils/TestPackageInstaller.java b/apct-tests/perftests/utils/src/android/perftests/utils/TestPackageInstaller.java
new file mode 100644
index 0000000..a433d80
--- /dev/null
+++ b/apct-tests/perftests/utils/src/android/perftests/utils/TestPackageInstaller.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2019 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.perftests.utils;
+
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.IntentSender;
+import android.content.pm.PackageInstaller;
+import android.content.res.Resources;
+import android.util.Log;
+
+import org.junit.Assert;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+/**
+ * Installs packages included within the assets directory.
+ */
+public class TestPackageInstaller {
+    private static final String LOG_TAG = "TestPackageInstaller";
+    private static final String BROADCAST_ACTION =
+            "com.android.perftests.core.ACTION_INSTALL_COMMIT";
+
+    private final Context mContext;
+    public TestPackageInstaller(Context context) {
+        mContext = context;
+    }
+
+
+
+    /**
+     * Installs an APK located at the specified path in the assets directory.
+     **/
+    public InstalledPackage installPackage(String resourceName) throws IOException,
+            InterruptedException {
+        Log.d(LOG_TAG, "Installing resource APK '" + resourceName + "'");
+        LocalBroadcastReceiver intentSender = new LocalBroadcastReceiver(mContext);
+
+        // Initialize the package install session.
+        PackageInstaller packageInstaller = mContext.getPackageManager().getPackageInstaller();
+        PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
+                PackageInstaller.SessionParams.MODE_FULL_INSTALL);
+        params.setInstallAsInstantApp(false);
+        int sessionId = packageInstaller.createSession(params);
+        PackageInstaller.Session session = packageInstaller.openSession(sessionId);
+
+        // Copy the apk to the install session.
+        try (OutputStream os = session.openWrite("TestPackageInstaller", 0, -1);
+             InputStream is = mContext.getResources().getAssets().openNonAsset(resourceName)) {
+            if (is == null) {
+                throw new IOException("Resource " + resourceName + " not found");
+            }
+            byte[] buffer = new byte[4096];
+            int n;
+            while ((n = is.read(buffer)) >= 0) {
+                os.write(buffer, 0, n);
+            }
+        }
+
+        session.commit(intentSender.getIntentSender(sessionId));
+        session.close();
+
+        // Retrieve the results of the installation.
+        Intent intent = intentSender.getIntentSenderResult();
+        int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS,
+                PackageInstaller.STATUS_FAILURE);
+        Assert.assertEquals(PackageInstaller.STATUS_SUCCESS, status);
+        String packageName = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME);
+        return new InstalledPackage(sessionId, packageName);
+    }
+
+    public class InstalledPackage {
+        private int mSessionId;
+        private String mPackageName;
+
+        private InstalledPackage(int sessionId, String packageName) {
+            mSessionId = sessionId;
+            mPackageName = packageName;
+        }
+
+        public String getPackageName() {
+            return mPackageName;
+        }
+
+        public void uninstall() throws Exception {
+            Log.d(LOG_TAG, "Uninstalling package '" + mPackageName + "'");
+            LocalBroadcastReceiver intentSender = new LocalBroadcastReceiver(mContext);
+            PackageInstaller packageInstaller = mContext.getPackageManager().getPackageInstaller();
+            packageInstaller.uninstall(mPackageName, intentSender.getIntentSender(mSessionId));
+            int status = intentSender.getIntentSenderResult()
+                    .getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
+            Assert.assertEquals(PackageInstaller.STATUS_SUCCESS, status);
+        }
+    }
+
+    private class LocalBroadcastReceiver extends BroadcastReceiver {
+        private final BlockingQueue<Intent> mIntentSenderResults = new LinkedBlockingQueue<>();
+        private final Context mContext;
+
+        private LocalBroadcastReceiver(Context context) {
+            mContext = context;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            mIntentSenderResults.add(intent);
+        }
+
+        IntentSender getIntentSender(int sessionId) {
+            String action = BROADCAST_ACTION + "." + sessionId;
+            IntentFilter filter = new IntentFilter(action);
+            mContext.registerReceiver(this, filter);
+
+            Intent intent = new Intent(action);
+            PendingIntent pending = PendingIntent.getBroadcast(mContext, sessionId, intent,
+                    PendingIntent.FLAG_UPDATE_CURRENT);
+            return pending.getIntentSender();
+        }
+
+        Intent getIntentSenderResult() throws InterruptedException {
+            return mIntentSenderResults.take();
+        }
+    }
+}
diff --git a/apex/jobscheduler/README_js-mainline.md b/apex/jobscheduler/README_js-mainline.md
index c1ad666..ea20e3e 100644
--- a/apex/jobscheduler/README_js-mainline.md
+++ b/apex/jobscheduler/README_js-mainline.md
@@ -1,23 +1,11 @@
 # Making Job Scheduler into a Mainline Module
 
-## TODOs
-
-See also:
-- http://go/moving-js-code-for-mainline
-- http://go/jobscheduler-code-dependencies-2019-07
-
-- [ ] Move this into `frameworks/apex/jobscheduler/...`. Currently it's in `frameworks/base/apex/...`
-because `frameworks/apex/` is not a part of any git projects. (and also working on multiple
-projects is a pain.)
-
 ## Current structure
 
 - JS service side classes are put in `jobscheduler-service.jar`.
 It's *not* included in services.jar, and instead it's put in the system server classpath,
 which currently looks like the following:
-`SYSTEMSERVERCLASSPATH=/system/framework/services.jar:/system/framework/jobscheduler-service.jar:/system/framework/ethernet-service.jar:/system/framework/wifi-service.jar:/system/framework/com.android.location.provider.jar`
-
-  (Note `jobscheduler-service.jar` will be put at the end in http://ag/9128109)
+`SYSTEMSERVERCLASSPATH=/system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/com.android.location.provider.jar:/system/framework/jobscheduler-service.jar`
 
   `SYSTEMSERVERCLASSPATH` is generated from `PRODUCT_SYSTEM_SERVER_JARS`.
 
@@ -29,10 +17,4 @@
   `framework.jar` merging the two jar files, and this jar file is what's
   put on the device and loaded by Zygote.
 
-
-This is *not* the final design. From a gerrit comment on http://ag/9145619:
-
-> This CL is just the first step, and the current state isn't not really the final form. For now we just want to have two separate jars, which makes it easier for us to analyze dependencies between them, and I wanted to minimize the change to the rest of the system. So, for example, zygote will still only have "framework.jar" in its classpath, instead of the two jars for now.
-> But yes, eventually, we won't even be able to have the monolithic "framework.jar" file because of mainline, so we need to figure out how to build the system without creating it. At that point zygote will have the two separate jar files in its classpath.
-> When we reach that point, we should revisit the naming of it, and yes, maybe the simple "framework.jar" is a good option.
-> But again, for now, I want to make this change as transparent as possible to the rest of the world.
+The current structure is *not* the final design.
diff --git a/apex/jobscheduler/framework/java/android/app/DeviceIdleFrameworkInitializer.java b/apex/jobscheduler/framework/java/android/app/DeviceIdleFrameworkInitializer.java
index a807eb1..5b14056 100644
--- a/apex/jobscheduler/framework/java/android/app/DeviceIdleFrameworkInitializer.java
+++ b/apex/jobscheduler/framework/java/android/app/DeviceIdleFrameworkInitializer.java
@@ -36,7 +36,7 @@
         SystemServiceRegistry.registerCachedService(
                 Context.DEVICE_IDLE_CONTROLLER, DeviceIdleManager.class,
                 (context, b) -> new DeviceIdleManager(
-                        context.getOuterContext(), IDeviceIdleController.Stub.asInterface(b)));
+                        context, IDeviceIdleController.Stub.asInterface(b)));
         PowerManager.setIsIgnoringBatteryOptimizationsCallback((packageName) -> {
             // No need for synchronization on sIDeviceIdleController; worst case
             // we just initialize it twice.
diff --git a/apex/jobscheduler/framework/java/com/android/server/usage/AppStandbyInternal.java b/apex/jobscheduler/framework/java/com/android/server/usage/AppStandbyInternal.java
new file mode 100644
index 0000000..3cfb080
--- /dev/null
+++ b/apex/jobscheduler/framework/java/com/android/server/usage/AppStandbyInternal.java
@@ -0,0 +1,112 @@
+package com.android.server.usage;
+
+import android.app.usage.AppStandbyInfo;
+import android.app.usage.UsageEvents;
+import android.app.usage.UsageStatsManager.StandbyBuckets;
+import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
+import android.content.Context;
+import android.os.Looper;
+
+import com.android.internal.util.IndentingPrintWriter;
+
+import java.io.PrintWriter;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.List;
+import java.util.Set;
+
+public interface AppStandbyInternal {
+    /**
+     * TODO AppStandbyController should probably be a binder service, and then we shouldn't need
+     * this method.
+     */
+    static AppStandbyInternal newAppStandbyController(ClassLoader loader, Context context,
+            Looper looper) {
+        try {
+            final Class<?> clazz = Class.forName("com.android.server.usage.AppStandbyController",
+                    true, loader);
+            final Constructor<?> ctor =  clazz.getConstructor(Context.class, Looper.class);
+            return (AppStandbyInternal) ctor.newInstance(context, looper);
+        } catch (NoSuchMethodException | InstantiationException
+                | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
+            throw new RuntimeException("Unable to instantiate AppStandbyController!", e);
+        }
+    }
+
+    void onBootPhase(int phase);
+
+    boolean isParoledOrCharging();
+
+    void postCheckIdleStates(int userId);
+
+    /**
+     * We send a different message to check idle states once, otherwise we would end up
+     * scheduling a series of repeating checkIdleStates each time we fired off one.
+     */
+    void postOneTimeCheckIdleStates();
+
+    void reportEvent(UsageEvents.Event event, long elapsedRealtime, int userId);
+
+    void setLastJobRunTime(String packageName, int userId, long elapsedRealtime);
+
+    long getTimeSinceLastJobRun(String packageName, int userId);
+
+    void onUserRemoved(int userId);
+
+    void addListener(AppIdleStateChangeListener listener);
+
+    void removeListener(AppIdleStateChangeListener listener);
+
+    int getAppId(String packageName);
+
+    boolean isAppIdleFilteredOrParoled(String packageName, int userId, long elapsedRealtime,
+            boolean shouldObfuscateInstantApps);
+
+    /**
+     * Checks if an app has been idle for a while and filters out apps that are excluded.
+     * It returns false if the current system state allows all apps to be considered active.
+     * This happens if the device is plugged in or temporarily allowed to make exceptions.
+     * Called by interface impls.
+     */
+    boolean isAppIdleFiltered(String packageName, int appId, int userId,
+            long elapsedRealtime);
+
+    int[] getIdleUidsForUser(int userId);
+
+    void setAppIdleAsync(String packageName, boolean idle, int userId);
+
+    @StandbyBuckets
+    int getAppStandbyBucket(String packageName, int userId,
+            long elapsedRealtime, boolean shouldObfuscateInstantApps);
+
+    List<AppStandbyInfo> getAppStandbyBuckets(int userId);
+
+    void setAppStandbyBucket(String packageName, int userId, @StandbyBuckets int newBucket,
+            int reason, long elapsedRealtime, boolean resetTimeout);
+
+    void addActiveDeviceAdmin(String adminPkg, int userId);
+
+    void setActiveAdminApps(Set<String> adminPkgs, int userId);
+
+    void onAdminDataAvailable();
+
+    void clearCarrierPrivilegedApps();
+
+    void flushToDisk(int userId);
+
+    void flushDurationsToDisk();
+
+    void initializeDefaultsForSystemApps(int userId);
+
+    void postReportContentProviderUsage(String name, String packageName, int userId);
+
+    void postReportSyncScheduled(String packageName, int userId, boolean exempted);
+
+    void postReportExemptedSyncStart(String packageName, int userId);
+
+    void dumpUser(IndentingPrintWriter idpw, int userId, String pkg);
+
+    void dumpState(String[] args, PrintWriter pw);
+
+    boolean isAppIdleEnabled();
+}
diff --git a/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java b/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java
index 65aaf20..3dc9a28 100644
--- a/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java
+++ b/apex/jobscheduler/service/java/com/android/server/DeviceIdleController.java
@@ -48,7 +48,6 @@
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.Environment;
-import android.os.FileUtils;
 import android.os.Handler;
 import android.os.IDeviceIdleController;
 import android.os.Looper;
@@ -1684,7 +1683,7 @@
 
     static class Injector {
         private final Context mContext;
-        private ConnectivityService mConnectivityService;
+        private ConnectivityManager mConnectivityManager;
         private Constants mConstants;
         private LocationManager mLocationManager;
 
@@ -1705,12 +1704,11 @@
             return new AppStateTracker(ctx, looper);
         }
 
-        ConnectivityService getConnectivityService() {
-            if (mConnectivityService == null) {
-                mConnectivityService = (ConnectivityService) ServiceManager.getService(
-                        Context.CONNECTIVITY_SERVICE);
+        ConnectivityManager getConnectivityManager() {
+            if (mConnectivityManager == null) {
+                mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
             }
-            return mConnectivityService;
+            return mConnectivityManager;
         }
 
         Constants getConstants(DeviceIdleController controller, Handler handler,
@@ -1909,7 +1907,7 @@
 
                 if (getContext().getResources().getBoolean(
                         com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
-                    mLocationRequest = new LocationRequest()
+                    mLocationRequest = LocationRequest.create()
                         .setQuality(LocationRequest.ACCURACY_FINE)
                         .setInterval(0)
                         .setFastestInterval(0)
@@ -2497,9 +2495,9 @@
     }
 
     void updateConnectivityState(Intent connIntent) {
-        ConnectivityService cm;
+        ConnectivityManager cm;
         synchronized (this) {
-            cm = mInjector.getConnectivityService();
+            cm = mInjector.getConnectivityManager();
         }
         if (cm == null) {
             return;
@@ -3598,9 +3596,6 @@
             try {
                 stream = mConfigFile.startWrite();
                 memStream.writeTo(stream);
-                stream.flush();
-                FileUtils.sync(stream);
-                stream.close();
                 mConfigFile.finishWrite(stream);
             } catch (IOException e) {
                 Slog.w(TAG, "Error writing config file", e);
diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java
index a633350..7273ea7 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java
@@ -56,8 +56,6 @@
 import android.os.BatteryStatsInternal;
 import android.os.Binder;
 import android.os.Handler;
-import android.os.IThermalService;
-import android.os.IThermalStatusListener;
 import android.os.Looper;
 import android.os.Message;
 import android.os.Process;
@@ -66,7 +64,6 @@
 import android.os.ServiceManager;
 import android.os.ShellCallback;
 import android.os.SystemClock;
-import android.os.Temperature;
 import android.os.UserHandle;
 import android.os.UserManagerInternal;
 import android.os.WorkSource;
@@ -81,7 +78,6 @@
 import android.util.TimeUtils;
 import android.util.proto.ProtoOutputStream;
 
-import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.IBatteryStats;
 import com.android.internal.util.ArrayUtils;
@@ -105,12 +101,17 @@
 import com.android.server.job.controllers.StateController;
 import com.android.server.job.controllers.StorageController;
 import com.android.server.job.controllers.TimeController;
+import com.android.server.job.restrictions.JobRestriction;
+import com.android.server.job.restrictions.ThermalStatusRestriction;
 
 import libcore.util.EmptyArray;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -146,10 +147,53 @@
 
     @VisibleForTesting
     public static Clock sSystemClock = Clock.systemUTC();
+
+    private abstract static class MySimpleClock extends Clock {
+        private final ZoneId mZoneId;
+
+        MySimpleClock(ZoneId zoneId) {
+            this.mZoneId = zoneId;
+        }
+
+        @Override
+        public ZoneId getZone() {
+            return mZoneId;
+        }
+
+        @Override
+        public Clock withZone(ZoneId zone) {
+            return new MySimpleClock(zone) {
+                @Override
+                public long millis() {
+                    return MySimpleClock.this.millis();
+                }
+            };
+        }
+
+        @Override
+        public abstract long millis();
+
+        @Override
+        public Instant instant() {
+            return Instant.ofEpochMilli(millis());
+        }
+    }
+
     @VisibleForTesting
-    public static Clock sUptimeMillisClock = SystemClock.uptimeClock();
+    public static Clock sUptimeMillisClock = new MySimpleClock(ZoneOffset.UTC) {
+        @Override
+        public long millis() {
+            return SystemClock.uptimeMillis();
+        }
+    };
+
     @VisibleForTesting
-    public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
+    public static Clock sElapsedRealtimeClock =  new MySimpleClock(ZoneOffset.UTC) {
+        @Override
+        public long millis() {
+            return SystemClock.elapsedRealtime();
+        }
+    };
 
     /** Global local for all job scheduler state. */
     final Object mLock = new Object();
@@ -186,12 +230,12 @@
     private final DeviceIdleJobsController mDeviceIdleJobsController;
     /** Needed to get remaining quota time. */
     private final QuotaController mQuotaController;
-
-    /** Need directly for receiving thermal events */
-    private IThermalService mThermalService;
-    /** Thermal constraint. */
-    @GuardedBy("mLock")
-    private boolean mThermalConstraint = false;
+    /**
+     * List of restrictions.
+     * Note: do not add to or remove from this list at runtime except in the constructor, because we
+     * do not synchronize access to this list.
+     */
+    private final List<JobRestriction> mJobRestrictions;
 
     /**
      * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
@@ -285,19 +329,6 @@
         }
     }
 
-    /**
-     *  Thermal event received from Thermal Service
-     */
-    private final class ThermalStatusListener extends IThermalStatusListener.Stub {
-        @Override public void onStatusChange(int status) {
-            // Throttle for Temperature.THROTTLING_SEVERE and above
-            synchronized (mLock) {
-                mThermalConstraint = status >= Temperature.THROTTLING_SEVERE;
-            }
-            onControllerStateChanged();
-        }
-    }
-
     static class MaxJobCounts {
         private final KeyValueListParser.IntValue mTotal;
         private final KeyValueListParser.IntValue mMaxBg;
@@ -1292,6 +1323,10 @@
         mQuotaController = new QuotaController(this);
         mControllers.add(mQuotaController);
 
+        // Create restrictions
+        mJobRestrictions = new ArrayList<>();
+        mJobRestrictions.add(new ThermalStatusRestriction(this));
+
         // If the job store determined that it can't yet reschedule persisted jobs,
         // we need to start watching the clock.
         if (!mJobs.jobTimesInflatedValid()) {
@@ -1383,15 +1418,9 @@
 
             // Remove any jobs that are not associated with any of the current users.
             cancelJobsForNonExistentUsers();
-            // Register thermal callback
-            mThermalService = IThermalService.Stub.asInterface(
-                    ServiceManager.getService(Context.THERMAL_SERVICE));
-            if (mThermalService != null) {
-                try {
-                    mThermalService.registerThermalStatusListener(new ThermalStatusListener());
-                } catch (RemoteException e) {
-                    Slog.e(TAG, "Failed to register thermal callback.", e);
-                }
+
+            for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
+                mJobRestrictions.get(i).onSystemServicesReady();
             }
         } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
             synchronized (mLock) {
@@ -1833,9 +1862,28 @@
         }
     }
 
-    private boolean isJobThermalConstrainedLocked(JobStatus job) {
-        return mThermalConstraint && job.hasConnectivityConstraint()
-                && (evaluateJobPriorityLocked(job) < JobInfo.PRIORITY_FOREGROUND_APP);
+    /**
+     * Check if a job is restricted by any of the declared {@link JobRestriction}s.
+     * Note, that the jobs with {@link JobInfo#PRIORITY_FOREGROUND_APP} priority or higher may not
+     * be restricted, thus we won't even perform the check, but simply return null early.
+     *
+     * @param job to be checked
+     * @return the first {@link JobRestriction} restricting the given job that has been found; null
+     * - if passes all the restrictions or has priority {@link JobInfo#PRIORITY_FOREGROUND_APP}
+     * or higher.
+     */
+    private JobRestriction checkIfRestricted(JobStatus job) {
+        if (evaluateJobPriorityLocked(job) >= JobInfo.PRIORITY_FOREGROUND_APP) {
+            // Jobs with PRIORITY_FOREGROUND_APP or higher should not be restricted
+            return null;
+        }
+        for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
+            final JobRestriction restriction = mJobRestrictions.get(i);
+            if (restriction.isJobRestricted(job)) {
+                return restriction;
+            }
+        }
+        return null;
     }
 
     private void stopNonReadyActiveJobsLocked() {
@@ -1849,10 +1897,13 @@
                 serviceContext.cancelExecutingJobLocked(
                         JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
                         "cancelled due to unsatisfied constraints");
-            } else if (isJobThermalConstrainedLocked(running)) {
-                serviceContext.cancelExecutingJobLocked(
-                        JobParameters.REASON_DEVICE_THERMAL,
-                        "cancelled due to thermal condition");
+            } else {
+                final JobRestriction restriction = checkIfRestricted(running);
+                if (restriction != null) {
+                    final int reason = restriction.getReason();
+                    serviceContext.cancelExecutingJobLocked(reason,
+                            "restricted due to " + JobParameters.getReasonName(reason));
+                }
             }
         }
     }
@@ -2089,7 +2140,7 @@
             return false;
         }
 
-        if (isJobThermalConstrainedLocked(job)) {
+        if (checkIfRestricted(job) != null) {
             return false;
         }
 
@@ -2121,7 +2172,7 @@
                     job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
                     job.getUserId());
         } catch (RemoteException e) {
-            throw e.rethrowAsRuntimeException();
+            throw new RuntimeException(e);
         }
 
         if (service == null) {
@@ -2170,7 +2221,7 @@
             return false;
         }
 
-        if (isJobThermalConstrainedLocked(job)) {
+        if (checkIfRestricted(job) != null) {
             return false;
         }
 
@@ -2982,9 +3033,12 @@
             pw.print("    In parole?: ");
             pw.print(mInParole);
             pw.println();
-            pw.print("    In thermal throttling?: ");
-            pw.print(mThermalConstraint);
-            pw.println();
+
+            for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
+                pw.print("    ");
+                mJobRestrictions.get(i).dumpConstants(pw);
+                pw.println();
+            }
             pw.println();
 
             pw.println("Started users: " + Arrays.toString(mStartedUsers));
@@ -3005,14 +3059,30 @@
 
                     job.dump(pw, "    ", true, nowElapsed);
 
+
+                    pw.print("    Restricted due to:");
+                    final boolean isRestricted = checkIfRestricted(job) != null;
+                    if (isRestricted) {
+                        for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
+                            final JobRestriction restriction = mJobRestrictions.get(i);
+                            if (restriction.isJobRestricted(job)) {
+                                final int reason = restriction.getReason();
+                                pw.write(" " + JobParameters.getReasonName(reason) + "[" + reason + "]");
+                            }
+                        }
+                    } else {
+                        pw.print(" none");
+                    }
+                    pw.println(".");
+
                     pw.print("    Ready: ");
                     pw.print(isReadyToBeExecutedLocked(job));
                     pw.print(" (job=");
                     pw.print(job.isReady());
                     pw.print(" user=");
                     pw.print(areUsersStartedLocked(job));
-                    pw.print(" !thermal=");
-                    pw.print(!isJobThermalConstrainedLocked(job));
+                    pw.print(" !restricted=");
+                    pw.print(!isRestricted);
                     pw.print(" !pending=");
                     pw.print(!mPendingJobs.contains(job));
                     pw.print(" !active=");
@@ -3152,7 +3222,9 @@
             proto.end(settingsToken);
 
             proto.write(JobSchedulerServiceDumpProto.IN_PAROLE, mInParole);
-            proto.write(JobSchedulerServiceDumpProto.IN_THERMAL, mThermalConstraint);
+            for (int i = mJobRestrictions.size() - 1; i >= 0; i--) {
+                mJobRestrictions.get(i).dumpConstants(proto);
+            }
 
             for (int u : mStartedUsers) {
                 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
@@ -3179,8 +3251,8 @@
                     proto.write(JobSchedulerServiceDumpProto.RegisteredJob.ARE_USERS_STARTED,
                             areUsersStartedLocked(job));
                     proto.write(
-                            JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_THERMAL_CONSTRAINED,
-                            isJobThermalConstrainedLocked(job));
+                            JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_RESTRICTED,
+                            checkIfRestricted(job) != null);
                     proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
                             mPendingJobs.contains(job));
                     proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
@@ -3190,6 +3262,16 @@
                     proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_USABLE,
                             isComponentUsable(job));
 
+                    for (JobRestriction restriction : mJobRestrictions) {
+                        final long restrictionsToken = proto.start(
+                                JobSchedulerServiceDumpProto.RegisteredJob.RESTRICTIONS);
+                        proto.write(JobSchedulerServiceDumpProto.JobRestriction.REASON,
+                                restriction.getReason());
+                        proto.write(JobSchedulerServiceDumpProto.JobRestriction.IS_RESTRICTING,
+                                restriction.isJobRestricted(job));
+                        proto.end(restrictionsToken);
+                    }
+
                     proto.end(rjToken);
                 }
             }
diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobStore.java b/apex/jobscheduler/service/java/com/android/server/job/JobStore.java
index c2bdb6c..2f5f555 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/JobStore.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/JobStore.java
@@ -1157,22 +1157,14 @@
         private void removeAll(Predicate<JobStatus> predicate) {
             for (int jobSetIndex = mJobs.size() - 1; jobSetIndex >= 0; jobSetIndex--) {
                 final ArraySet<JobStatus> jobs = mJobs.valueAt(jobSetIndex);
-                for (int jobIndex = jobs.size() - 1; jobIndex >= 0; jobIndex--) {
-                    if (predicate.test(jobs.valueAt(jobIndex))) {
-                        jobs.removeAt(jobIndex);
-                    }
-                }
+                jobs.removeIf(predicate);
                 if (jobs.size() == 0) {
                     mJobs.removeAt(jobSetIndex);
                 }
             }
             for (int jobSetIndex = mJobsPerSourceUid.size() - 1; jobSetIndex >= 0; jobSetIndex--) {
                 final ArraySet<JobStatus> jobs = mJobsPerSourceUid.valueAt(jobSetIndex);
-                for (int jobIndex = jobs.size() - 1; jobIndex >= 0; jobIndex--) {
-                    if (predicate.test(jobs.valueAt(jobIndex))) {
-                        jobs.removeAt(jobIndex);
-                    }
-                }
+                jobs.removeIf(predicate);
                 if (jobs.size() == 0) {
                     mJobsPerSourceUid.removeAt(jobSetIndex);
                 }
diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java
index 43e8dfb..7d36303 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java
@@ -34,6 +34,7 @@
 import android.os.Message;
 import android.os.UserHandle;
 import android.text.format.DateUtils;
+import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.DataUnit;
 import android.util.Log;
@@ -441,7 +442,7 @@
         synchronized (mLock) {
             // Since this is a really hot codepath, temporarily cache any
             // answers that we get from ConnectivityManager.
-            final SparseArray<NetworkCapabilities> networkToCapabilities = new SparseArray<>();
+            final ArrayMap<Network, NetworkCapabilities> networkToCapabilities = new ArrayMap<>();
 
             boolean changed = false;
             if (filterUid == -1) {
@@ -460,17 +461,16 @@
     }
 
     private boolean updateTrackedJobsLocked(ArraySet<JobStatus> jobs, Network filterNetwork,
-            SparseArray<NetworkCapabilities> networkToCapabilities) {
+            ArrayMap<Network, NetworkCapabilities> networkToCapabilities) {
         if (jobs == null || jobs.size() == 0) {
             return false;
         }
 
         final Network network = mConnManager.getActiveNetworkForUid(jobs.valueAt(0).getSourceUid());
-        final int netId = network != null ? network.netId : -1;
-        NetworkCapabilities capabilities = networkToCapabilities.get(netId);
+        NetworkCapabilities capabilities = networkToCapabilities.get(network);
         if (capabilities == null) {
             capabilities = mConnManager.getNetworkCapabilities(network);
-            networkToCapabilities.put(netId, capabilities);
+            networkToCapabilities.put(network, capabilities);
         }
         final boolean networkMatch = (filterNetwork == null
                 || Objects.equals(filterNetwork, network));
diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
index adb4314..c76346f 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java
@@ -28,7 +28,7 @@
 import android.net.Uri;
 import android.os.RemoteException;
 import android.os.UserHandle;
-import android.text.format.TimeMigrationUtils;
+import android.text.format.DateFormat;
 import android.util.ArraySet;
 import android.util.Pair;
 import android.util.Slog;
@@ -1518,7 +1518,7 @@
             if (job.getClipData() != null) {
                 pw.print(prefix); pw.print("  Clip data: ");
                 StringBuilder b = new StringBuilder(128);
-                job.getClipData().toShortString(b);
+                b.append(job.getClipData());
                 pw.println(b);
             }
             if (uriPerms != null) {
@@ -1659,14 +1659,18 @@
         }
         if (mLastSuccessfulRunTime != 0) {
             pw.print(prefix); pw.print("Last successful run: ");
-            pw.println(TimeMigrationUtils.formatMillisWithFixedFormat(mLastSuccessfulRunTime));
+            pw.println(formatTime(mLastSuccessfulRunTime));
         }
         if (mLastFailedRunTime != 0) {
             pw.print(prefix); pw.print("Last failed run: ");
-            pw.println(TimeMigrationUtils.formatMillisWithFixedFormat(mLastFailedRunTime));
+            pw.println(formatTime(mLastFailedRunTime));
         }
     }
 
+    private static CharSequence formatTime(long time) {
+        return DateFormat.format("yyyy-MM-dd HH:mm:ss", time);
+    }
+
     public void dump(ProtoOutputStream proto, long fieldId, boolean full, long elapsedRealtimeMillis) {
         final long token = proto.start(fieldId);
 
diff --git a/apex/jobscheduler/service/java/com/android/server/job/restrictions/JobRestriction.java b/apex/jobscheduler/service/java/com/android/server/job/restrictions/JobRestriction.java
new file mode 100644
index 0000000..e180c55
--- /dev/null
+++ b/apex/jobscheduler/service/java/com/android/server/job/restrictions/JobRestriction.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2019 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.job.restrictions;
+
+import android.app.job.JobInfo;
+import android.util.proto.ProtoOutputStream;
+
+import com.android.internal.util.IndentingPrintWriter;
+import com.android.server.job.JobSchedulerService;
+import com.android.server.job.controllers.JobStatus;
+
+/**
+ * Used by {@link JobSchedulerService} to impose additional restrictions regarding whether jobs
+ * should be scheduled or not based on the state of the system/device.
+ * Every restriction is associated with exactly one reason (from {@link
+ * android.app.job.JobParameters#JOB_STOP_REASON_CODES}), which could be retrieved using {@link
+ * #getReason()}.
+ * Note, that this is not taken into account for the jobs that have priority
+ * {@link JobInfo#PRIORITY_FOREGROUND_APP} or higher.
+ */
+public abstract class JobRestriction {
+
+    final JobSchedulerService mService;
+    private final int mReason;
+
+    JobRestriction(JobSchedulerService service, int reason) {
+        mService = service;
+        mReason = reason;
+    }
+
+    /**
+     * Called when the system boot phase has reached
+     * {@link com.android.server.SystemService#PHASE_SYSTEM_SERVICES_READY}.
+     */
+    public void onSystemServicesReady() {
+    }
+
+    /**
+     * Called by {@link JobSchedulerService} to check if it may proceed with scheduling the job (in
+     * case all constraints are satisfied and all other {@link JobRestriction}s are fine with it)
+     *
+     * @param job to be checked
+     * @return false if the {@link JobSchedulerService} should not schedule this job at the moment,
+     * true - otherwise
+     */
+    public abstract boolean isJobRestricted(JobStatus job);
+
+    /** Dump any internal constants the Restriction may have. */
+    public abstract void dumpConstants(IndentingPrintWriter pw);
+
+    /** Dump any internal constants the Restriction may have. */
+    public abstract void dumpConstants(ProtoOutputStream proto);
+
+    /** @return reason code for the Restriction. */
+    public final int getReason() {
+        return mReason;
+    }
+}
diff --git a/apex/jobscheduler/service/java/com/android/server/job/restrictions/ThermalStatusRestriction.java b/apex/jobscheduler/service/java/com/android/server/job/restrictions/ThermalStatusRestriction.java
new file mode 100644
index 0000000..b97da59
--- /dev/null
+++ b/apex/jobscheduler/service/java/com/android/server/job/restrictions/ThermalStatusRestriction.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2019 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.job.restrictions;
+
+import android.app.job.JobParameters;
+import android.content.Context;
+import android.os.IThermalService;
+import android.os.IThermalStatusListener;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.Temperature;
+import android.util.Slog;
+import android.util.proto.ProtoOutputStream;
+
+import com.android.internal.util.IndentingPrintWriter;
+import com.android.server.job.JobSchedulerService;
+import com.android.server.job.JobSchedulerServiceDumpProto;
+import com.android.server.job.controllers.JobStatus;
+
+public class ThermalStatusRestriction extends JobRestriction {
+    private static final String TAG = "ThermalStatusRestriction";
+
+    private volatile boolean mIsThermalRestricted = false;
+
+    public ThermalStatusRestriction(JobSchedulerService service) {
+        super(service, JobParameters.REASON_DEVICE_THERMAL);
+    }
+
+    @Override
+    public void onSystemServicesReady() {
+        final IThermalService thermalService = IThermalService.Stub.asInterface(
+                ServiceManager.getService(Context.THERMAL_SERVICE));
+        if (thermalService != null) {
+            try {
+                thermalService.registerThermalStatusListener(new IThermalStatusListener.Stub() {
+                    @Override
+                    public void onStatusChange(int status) {
+                        final boolean shouldBeActive = status >= Temperature.THROTTLING_SEVERE;
+                        if (mIsThermalRestricted == shouldBeActive) {
+                            return;
+                        }
+                        mIsThermalRestricted = shouldBeActive;
+                        mService.onControllerStateChanged();
+                    }
+                });
+            } catch (RemoteException e) {
+                Slog.e(TAG, "Failed to register thermal callback.", e);
+            }
+        }
+    }
+
+    @Override
+    public boolean isJobRestricted(JobStatus job) {
+        return mIsThermalRestricted && job.hasConnectivityConstraint();
+    }
+
+    @Override
+    public void dumpConstants(IndentingPrintWriter pw) {
+        pw.print("In thermal throttling?: ");
+        pw.print(mIsThermalRestricted);
+    }
+
+    @Override
+    public void dumpConstants(ProtoOutputStream proto) {
+        proto.write(JobSchedulerServiceDumpProto.IN_THERMAL, mIsThermalRestricted);
+    }
+}
diff --git a/services/usage/java/com/android/server/usage/AppIdleHistory.java b/apex/jobscheduler/service/java/com/android/server/usage/AppIdleHistory.java
similarity index 100%
rename from services/usage/java/com/android/server/usage/AppIdleHistory.java
rename to apex/jobscheduler/service/java/com/android/server/usage/AppIdleHistory.java
diff --git a/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java b/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java
new file mode 100644
index 0000000..7c472a9
--- /dev/null
+++ b/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java
@@ -0,0 +1,2038 @@
+/**
+ * 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.usage;
+
+import static android.app.usage.UsageStatsManager.REASON_MAIN_DEFAULT;
+import static android.app.usage.UsageStatsManager.REASON_MAIN_FORCED;
+import static android.app.usage.UsageStatsManager.REASON_MAIN_MASK;
+import static android.app.usage.UsageStatsManager.REASON_MAIN_PREDICTED;
+import static android.app.usage.UsageStatsManager.REASON_MAIN_TIMEOUT;
+import static android.app.usage.UsageStatsManager.REASON_MAIN_USAGE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_PREDICTED_RESTORED;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_ACTIVE_TIMEOUT;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_START;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_FOREGROUND_SERVICE_START;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_BACKGROUND;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_NOTIFICATION_SEEN;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SLICE_PINNED;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SLICE_PINNED_PRIV;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYNC_ADAPTER;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_INTERACTION;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_UPDATE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED;
+import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_USER_INTERACTION;
+import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_ACTIVE;
+import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_EXEMPTED;
+import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_FREQUENT;
+import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_NEVER;
+import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_RARE;
+import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_WORKING_SET;
+
+import static com.android.server.SystemService.PHASE_BOOT_COMPLETED;
+import static com.android.server.SystemService.PHASE_SYSTEM_SERVICES_READY;
+
+import android.annotation.UserIdInt;
+import android.app.ActivityManager;
+import android.app.AppGlobals;
+import android.app.usage.AppStandbyInfo;
+import android.app.usage.UsageEvents;
+import android.app.usage.UsageStatsManager.StandbyBuckets;
+import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
+import android.appwidget.AppWidgetManager;
+import android.content.BroadcastReceiver;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManagerInternal;
+import android.content.pm.ParceledListSlice;
+import android.database.ContentObserver;
+import android.hardware.display.DisplayManager;
+import android.net.ConnectivityManager;
+import android.net.Network;
+import android.net.NetworkInfo;
+import android.net.NetworkRequest;
+import android.net.NetworkScoreManager;
+import android.os.BatteryManager;
+import android.os.BatteryStats;
+import android.os.Environment;
+import android.os.Handler;
+import android.os.IDeviceIdleController;
+import android.os.Looper;
+import android.os.Message;
+import android.os.PowerManager;
+import android.os.Process;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.SystemClock;
+import android.os.UserHandle;
+import android.provider.Settings.Global;
+import android.telephony.TelephonyManager;
+import android.util.ArraySet;
+import android.util.KeyValueListParser;
+import android.util.Slog;
+import android.util.SparseArray;
+import android.util.SparseIntArray;
+import android.util.TimeUtils;
+import android.view.Display;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.app.IBatteryStats;
+import com.android.internal.os.SomeArgs;
+import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.ConcurrentUtils;
+import com.android.internal.util.IndentingPrintWriter;
+import com.android.server.LocalServices;
+import com.android.server.usage.AppIdleHistory.AppUsageHistory;
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.time.Duration;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * Manages the standby state of an app, listening to various events.
+ *
+ * Unit test:
+   atest com.android.server.usage.AppStandbyControllerTests
+ */
+public class AppStandbyController implements AppStandbyInternal {
+
+    private static final String TAG = "AppStandbyController";
+    static final boolean DEBUG = false;
+
+    static final boolean COMPRESS_TIME = false;
+    private static final long ONE_MINUTE = 60 * 1000;
+    private static final long ONE_HOUR = ONE_MINUTE * 60;
+    private static final long ONE_DAY = ONE_HOUR * 24;
+
+    static final long[] SCREEN_TIME_THRESHOLDS = {
+            0,
+            0,
+            COMPRESS_TIME ? 120 * 1000 : 1 * ONE_HOUR,
+            COMPRESS_TIME ? 240 * 1000 : 2 * ONE_HOUR
+    };
+
+    static final long[] ELAPSED_TIME_THRESHOLDS = {
+            0,
+            COMPRESS_TIME ?  1 * ONE_MINUTE : 12 * ONE_HOUR,
+            COMPRESS_TIME ?  4 * ONE_MINUTE : 24 * ONE_HOUR,
+            COMPRESS_TIME ? 16 * ONE_MINUTE : 48 * ONE_HOUR
+    };
+
+    static final int[] THRESHOLD_BUCKETS = {
+            STANDBY_BUCKET_ACTIVE,
+            STANDBY_BUCKET_WORKING_SET,
+            STANDBY_BUCKET_FREQUENT,
+            STANDBY_BUCKET_RARE
+    };
+
+    /** Default expiration time for bucket prediction. After this, use thresholds to downgrade. */
+    private static final long DEFAULT_PREDICTION_TIMEOUT = 12 * ONE_HOUR;
+
+    /**
+     * Indicates the maximum wait time for admin data to be available;
+     */
+    private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
+
+    // To name the lock for stack traces
+    static class Lock {}
+
+    /** Lock to protect the app's standby state. Required for calls into AppIdleHistory */
+    private final Object mAppIdleLock = new Lock();
+
+    /** Keeps the history and state for each app. */
+    @GuardedBy("mAppIdleLock")
+    private AppIdleHistory mAppIdleHistory;
+
+    @GuardedBy("mPackageAccessListeners")
+    private ArrayList<AppIdleStateChangeListener>
+            mPackageAccessListeners = new ArrayList<>();
+
+    /** Whether we've queried the list of carrier privileged apps. */
+    @GuardedBy("mAppIdleLock")
+    private boolean mHaveCarrierPrivilegedApps;
+
+    /** List of carrier-privileged apps that should be excluded from standby */
+    @GuardedBy("mAppIdleLock")
+    private List<String> mCarrierPrivilegedApps;
+
+    @GuardedBy("mActiveAdminApps")
+    private final SparseArray<Set<String>> mActiveAdminApps = new SparseArray<>();
+
+    private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
+
+    // Messages for the handler
+    static final int MSG_INFORM_LISTENERS = 3;
+    static final int MSG_FORCE_IDLE_STATE = 4;
+    static final int MSG_CHECK_IDLE_STATES = 5;
+    static final int MSG_CHECK_PAROLE_TIMEOUT = 6;
+    static final int MSG_PAROLE_END_TIMEOUT = 7;
+    static final int MSG_REPORT_CONTENT_PROVIDER_USAGE = 8;
+    static final int MSG_PAROLE_STATE_CHANGED = 9;
+    static final int MSG_ONE_TIME_CHECK_IDLE_STATES = 10;
+    /** Check the state of one app: arg1 = userId, arg2 = uid, obj = (String) packageName */
+    static final int MSG_CHECK_PACKAGE_IDLE_STATE = 11;
+    static final int MSG_REPORT_SYNC_SCHEDULED = 12;
+    static final int MSG_REPORT_EXEMPTED_SYNC_START = 13;
+    static final int MSG_UPDATE_STABLE_CHARGING= 14;
+
+    long mCheckIdleIntervalMillis;
+    long mAppIdleParoleIntervalMillis;
+    long mAppIdleParoleWindowMillis;
+    long mAppIdleParoleDurationMillis;
+    long[] mAppStandbyScreenThresholds = SCREEN_TIME_THRESHOLDS;
+    long[] mAppStandbyElapsedThresholds = ELAPSED_TIME_THRESHOLDS;
+    /** Minimum time a strong usage event should keep the bucket elevated. */
+    long mStrongUsageTimeoutMillis;
+    /** Minimum time a notification seen event should keep the bucket elevated. */
+    long mNotificationSeenTimeoutMillis;
+    /** Minimum time a system update event should keep the buckets elevated. */
+    long mSystemUpdateUsageTimeoutMillis;
+    /** Maximum time to wait for a prediction before using simple timeouts to downgrade buckets. */
+    long mPredictionTimeoutMillis;
+    /** Maximum time a sync adapter associated with a CP should keep the buckets elevated. */
+    long mSyncAdapterTimeoutMillis;
+    /**
+     * Maximum time an exempted sync should keep the buckets elevated, when sync is scheduled in
+     * non-doze
+     */
+    long mExemptedSyncScheduledNonDozeTimeoutMillis;
+    /**
+     * Maximum time an exempted sync should keep the buckets elevated, when sync is scheduled in
+     * doze
+     */
+    long mExemptedSyncScheduledDozeTimeoutMillis;
+    /**
+     * Maximum time an exempted sync should keep the buckets elevated, when sync is started.
+     */
+    long mExemptedSyncStartTimeoutMillis;
+    /**
+     * Maximum time an unexempted sync should keep the buckets elevated, when sync is scheduled
+     */
+    long mUnexemptedSyncScheduledTimeoutMillis;
+    /** Maximum time a system interaction should keep the buckets elevated. */
+    long mSystemInteractionTimeoutMillis;
+    /**
+     * Maximum time a foreground service start should keep the buckets elevated if the service
+     * start is the first usage of the app
+     */
+    long mInitialForegroundServiceStartTimeoutMillis;
+    /** The length of time phone must be charging before considered stable enough to run jobs  */
+    long mStableChargingThresholdMillis;
+
+    private volatile boolean mAppIdleEnabled;
+    boolean mAppIdleTempParoled;
+    boolean mCharging;
+    boolean mChargingStable;
+    private long mLastAppIdleParoledTime;
+    private boolean mSystemServicesReady = false;
+    // There was a system update, defaults need to be initialized after services are ready
+    private boolean mPendingInitializeDefaults;
+
+    private final DeviceStateReceiver mDeviceStateReceiver;
+
+    private volatile boolean mPendingOneTimeCheckIdleStates;
+
+    private final AppStandbyHandler mHandler;
+    private final Context mContext;
+
+    // TODO: Provide a mechanism to set an external bucketing service
+
+    private AppWidgetManager mAppWidgetManager;
+    private ConnectivityManager mConnectivityManager;
+    private PowerManager mPowerManager;
+    private PackageManager mPackageManager;
+    Injector mInjector;
+
+    static final ArrayList<StandbyUpdateRecord> sStandbyUpdatePool = new ArrayList<>(4);
+
+    public static class StandbyUpdateRecord {
+        // Identity of the app whose standby state has changed
+        String packageName;
+        int userId;
+
+        // What the standby bucket the app is now in
+        int bucket;
+
+        // Whether the bucket change is because the user has started interacting with the app
+        boolean isUserInteraction;
+
+        // Reason for bucket change
+        int reason;
+
+        StandbyUpdateRecord(String pkgName, int userId, int bucket, int reason,
+                boolean isInteraction) {
+            this.packageName = pkgName;
+            this.userId = userId;
+            this.bucket = bucket;
+            this.reason = reason;
+            this.isUserInteraction = isInteraction;
+        }
+
+        public static StandbyUpdateRecord obtain(String pkgName, int userId,
+                int bucket, int reason, boolean isInteraction) {
+            synchronized (sStandbyUpdatePool) {
+                final int size = sStandbyUpdatePool.size();
+                if (size < 1) {
+                    return new StandbyUpdateRecord(pkgName, userId, bucket, reason, isInteraction);
+                }
+                StandbyUpdateRecord r = sStandbyUpdatePool.remove(size - 1);
+                r.packageName = pkgName;
+                r.userId = userId;
+                r.bucket = bucket;
+                r.reason = reason;
+                r.isUserInteraction = isInteraction;
+                return r;
+            }
+        }
+
+        public void recycle() {
+            synchronized (sStandbyUpdatePool) {
+                sStandbyUpdatePool.add(this);
+            }
+        }
+    }
+
+    public AppStandbyController(Context context, Looper looper) {
+        this(new Injector(context, looper));
+    }
+
+    AppStandbyController(Injector injector) {
+        mInjector = injector;
+        mContext = mInjector.getContext();
+        mHandler = new AppStandbyHandler(mInjector.getLooper());
+        mPackageManager = mContext.getPackageManager();
+        mDeviceStateReceiver = new DeviceStateReceiver();
+
+        IntentFilter deviceStates = new IntentFilter(BatteryManager.ACTION_CHARGING);
+        deviceStates.addAction(BatteryManager.ACTION_DISCHARGING);
+        deviceStates.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
+        mContext.registerReceiver(mDeviceStateReceiver, deviceStates);
+
+        synchronized (mAppIdleLock) {
+            mAppIdleHistory = new AppIdleHistory(mInjector.getDataSystemDirectory(),
+                    mInjector.elapsedRealtime());
+        }
+
+        IntentFilter packageFilter = new IntentFilter();
+        packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
+        packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
+        packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+        packageFilter.addDataScheme("package");
+
+        mContext.registerReceiverAsUser(new PackageReceiver(), UserHandle.ALL, packageFilter,
+                null, mHandler);
+    }
+
+    @VisibleForTesting
+    void setAppIdleEnabled(boolean enabled) {
+        synchronized (mAppIdleLock) {
+            if (mAppIdleEnabled != enabled) {
+                final boolean oldParoleState = isParoledOrCharging();
+                mAppIdleEnabled = enabled;
+                if (isParoledOrCharging() != oldParoleState) {
+                    postParoleStateChanged();
+                }
+            }
+        }
+    }
+
+    @Override
+    public boolean isAppIdleEnabled() {
+        return mAppIdleEnabled;
+    }
+
+    @Override
+    public void onBootPhase(int phase) {
+        mInjector.onBootPhase(phase);
+        if (phase == PHASE_SYSTEM_SERVICES_READY) {
+            Slog.d(TAG, "Setting app idle enabled state");
+            // Observe changes to the threshold
+            SettingsObserver settingsObserver = new SettingsObserver(mHandler);
+            settingsObserver.registerObserver();
+            settingsObserver.updateSettings();
+
+            mAppWidgetManager = mContext.getSystemService(AppWidgetManager.class);
+            mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
+            mPowerManager = mContext.getSystemService(PowerManager.class);
+
+            mInjector.registerDisplayListener(mDisplayListener, mHandler);
+            synchronized (mAppIdleLock) {
+                mAppIdleHistory.updateDisplay(isDisplayOn(), mInjector.elapsedRealtime());
+            }
+
+            mSystemServicesReady = true;
+
+            boolean userFileExists;
+            synchronized (mAppIdleLock) {
+                userFileExists = mAppIdleHistory.userFileExists(UserHandle.USER_SYSTEM);
+            }
+
+            if (mPendingInitializeDefaults || !userFileExists) {
+                initializeDefaultsForSystemApps(UserHandle.USER_SYSTEM);
+            }
+
+            if (mPendingOneTimeCheckIdleStates) {
+                postOneTimeCheckIdleStates();
+            }
+        } else if (phase == PHASE_BOOT_COMPLETED) {
+            setChargingState(mInjector.isCharging());
+        }
+    }
+
+    private void reportContentProviderUsage(String authority, String providerPkgName, int userId) {
+        if (!mAppIdleEnabled) return;
+
+        // Get sync adapters for the authority
+        String[] packages = ContentResolver.getSyncAdapterPackagesForAuthorityAsUser(
+                authority, userId);
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+        for (String packageName: packages) {
+            // Only force the sync adapters to active if the provider is not in the same package and
+            // the sync adapter is a system package.
+            try {
+                PackageInfo pi = mPackageManager.getPackageInfoAsUser(
+                        packageName, PackageManager.MATCH_SYSTEM_ONLY, userId);
+                if (pi == null || pi.applicationInfo == null) {
+                    continue;
+                }
+                if (!packageName.equals(providerPkgName)) {
+                    synchronized (mAppIdleLock) {
+                        AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
+                                STANDBY_BUCKET_ACTIVE, REASON_SUB_USAGE_SYNC_ADAPTER,
+                                0,
+                                elapsedRealtime + mSyncAdapterTimeoutMillis);
+                        maybeInformListeners(packageName, userId, elapsedRealtime,
+                                appUsage.currentBucket, appUsage.bucketingReason, false);
+                    }
+                }
+            } catch (PackageManager.NameNotFoundException e) {
+                // Shouldn't happen
+            }
+        }
+    }
+
+    private void reportExemptedSyncScheduled(String packageName, int userId) {
+        if (!mAppIdleEnabled) return;
+
+        final int bucketToPromote;
+        final int usageReason;
+        final long durationMillis;
+
+        if (!mInjector.isDeviceIdleMode()) {
+            // Not dozing.
+            bucketToPromote = STANDBY_BUCKET_ACTIVE;
+            usageReason = REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE;
+            durationMillis = mExemptedSyncScheduledNonDozeTimeoutMillis;
+        } else {
+            // Dozing.
+            bucketToPromote = STANDBY_BUCKET_WORKING_SET;
+            usageReason = REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE;
+            durationMillis = mExemptedSyncScheduledDozeTimeoutMillis;
+        }
+
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+
+        synchronized (mAppIdleLock) {
+            AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
+                    bucketToPromote, usageReason,
+                    0,
+                    elapsedRealtime + durationMillis);
+            maybeInformListeners(packageName, userId, elapsedRealtime,
+                    appUsage.currentBucket, appUsage.bucketingReason, false);
+        }
+    }
+
+    private void reportUnexemptedSyncScheduled(String packageName, int userId) {
+        if (!mAppIdleEnabled) return;
+
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+        synchronized (mAppIdleLock) {
+            final int currentBucket =
+                    mAppIdleHistory.getAppStandbyBucket(packageName, userId, elapsedRealtime);
+            if (currentBucket == STANDBY_BUCKET_NEVER) {
+                // Bring the app out of the never bucket
+                AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
+                        STANDBY_BUCKET_WORKING_SET, REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED,
+                        0,
+                        elapsedRealtime + mUnexemptedSyncScheduledTimeoutMillis);
+                maybeInformListeners(packageName, userId, elapsedRealtime,
+                        appUsage.currentBucket, appUsage.bucketingReason, false);
+            }
+        }
+    }
+
+    private void reportExemptedSyncStart(String packageName, int userId) {
+        if (!mAppIdleEnabled) return;
+
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+
+        synchronized (mAppIdleLock) {
+            AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
+                    STANDBY_BUCKET_ACTIVE, REASON_SUB_USAGE_EXEMPTED_SYNC_START,
+                    0,
+                    elapsedRealtime + mExemptedSyncStartTimeoutMillis);
+            maybeInformListeners(packageName, userId, elapsedRealtime,
+                    appUsage.currentBucket, appUsage.bucketingReason, false);
+        }
+    }
+
+    @VisibleForTesting
+    void setChargingState(boolean charging) {
+        synchronized (mAppIdleLock) {
+            if (mCharging != charging) {
+                mCharging = charging;
+                if (DEBUG) Slog.d(TAG, "Setting mCharging to " + charging);
+                if (charging) {
+                    if (DEBUG) {
+                        Slog.d(TAG, "Scheduling MSG_UPDATE_STABLE_CHARGING  delay = "
+                                + mStableChargingThresholdMillis);
+                    }
+                    mHandler.sendEmptyMessageDelayed(MSG_UPDATE_STABLE_CHARGING,
+                            mStableChargingThresholdMillis);
+                } else {
+                    mHandler.removeMessages(MSG_UPDATE_STABLE_CHARGING);
+                    updateChargingStableState();
+                }
+            }
+        }
+    }
+
+    private void updateChargingStableState() {
+        synchronized (mAppIdleLock) {
+            if (mChargingStable != mCharging) {
+                if (DEBUG) Slog.d(TAG, "Setting mChargingStable to " + mCharging);
+                mChargingStable = mCharging;
+                postParoleStateChanged();
+            }
+        }
+    }
+
+    private void setAppIdleParoled(boolean paroled) {
+        synchronized (mAppIdleLock) {
+            final long now = mInjector.currentTimeMillis();
+            if (mAppIdleTempParoled != paroled) {
+                mAppIdleTempParoled = paroled;
+                if (DEBUG) Slog.d(TAG, "Changing paroled to " + mAppIdleTempParoled);
+                if (paroled) {
+                    postParoleEndTimeout();
+                } else {
+                    mLastAppIdleParoledTime = now;
+                    postNextParoleTimeout(now, false);
+                }
+                postParoleStateChanged();
+            }
+        }
+    }
+
+    @Override
+    public boolean isParoledOrCharging() {
+        if (!mAppIdleEnabled) return true;
+        synchronized (mAppIdleLock) {
+            // Only consider stable charging when determining charge state.
+            return mAppIdleTempParoled || mChargingStable;
+        }
+    }
+
+    private void postNextParoleTimeout(long now, boolean forced) {
+        if (DEBUG) Slog.d(TAG, "Posting MSG_CHECK_PAROLE_TIMEOUT");
+        mHandler.removeMessages(MSG_CHECK_PAROLE_TIMEOUT);
+        // Compute when the next parole needs to happen. We check more frequently than necessary
+        // since the message handler delays are based on elapsedRealTime and not wallclock time.
+        // The comparison is done in wallclock time.
+        long timeLeft = (mLastAppIdleParoledTime + mAppIdleParoleIntervalMillis) - now;
+        if (forced) {
+            // Set next timeout for the end of the parole window
+            // If parole is not set by the end of the window it will be forced
+            timeLeft += mAppIdleParoleWindowMillis;
+        }
+        if (timeLeft < 0) {
+            timeLeft = 0;
+        }
+        mHandler.sendEmptyMessageDelayed(MSG_CHECK_PAROLE_TIMEOUT, timeLeft);
+    }
+
+    private void postParoleEndTimeout() {
+        if (DEBUG) Slog.d(TAG, "Posting MSG_PAROLE_END_TIMEOUT");
+        mHandler.removeMessages(MSG_PAROLE_END_TIMEOUT);
+        mHandler.sendEmptyMessageDelayed(MSG_PAROLE_END_TIMEOUT, mAppIdleParoleDurationMillis);
+    }
+
+    private void postParoleStateChanged() {
+        if (DEBUG) Slog.d(TAG, "Posting MSG_PAROLE_STATE_CHANGED");
+        mHandler.removeMessages(MSG_PAROLE_STATE_CHANGED);
+        mHandler.sendEmptyMessage(MSG_PAROLE_STATE_CHANGED);
+    }
+
+    @Override
+    public void postCheckIdleStates(int userId) {
+        mHandler.sendMessage(mHandler.obtainMessage(MSG_CHECK_IDLE_STATES, userId, 0));
+    }
+
+    @Override
+    public void postOneTimeCheckIdleStates() {
+        if (mInjector.getBootPhase() < PHASE_SYSTEM_SERVICES_READY) {
+            // Not booted yet; wait for it!
+            mPendingOneTimeCheckIdleStates = true;
+        } else {
+            mHandler.sendEmptyMessage(MSG_ONE_TIME_CHECK_IDLE_STATES);
+            mPendingOneTimeCheckIdleStates = false;
+        }
+    }
+
+    @VisibleForTesting
+    boolean checkIdleStates(int checkUserId) {
+        if (!mAppIdleEnabled) {
+            return false;
+        }
+
+        final int[] runningUserIds;
+        try {
+            runningUserIds = mInjector.getRunningUserIds();
+            if (checkUserId != UserHandle.USER_ALL
+                    && !ArrayUtils.contains(runningUserIds, checkUserId)) {
+                return false;
+            }
+        } catch (RemoteException re) {
+            throw re.rethrowFromSystemServer();
+        }
+
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+        for (int i = 0; i < runningUserIds.length; i++) {
+            final int userId = runningUserIds[i];
+            if (checkUserId != UserHandle.USER_ALL && checkUserId != userId) {
+                continue;
+            }
+            if (DEBUG) {
+                Slog.d(TAG, "Checking idle state for user " + userId);
+            }
+            List<PackageInfo> packages = mPackageManager.getInstalledPackagesAsUser(
+                    PackageManager.MATCH_DISABLED_COMPONENTS,
+                    userId);
+            final int packageCount = packages.size();
+            for (int p = 0; p < packageCount; p++) {
+                final PackageInfo pi = packages.get(p);
+                final String packageName = pi.packageName;
+                checkAndUpdateStandbyState(packageName, userId, pi.applicationInfo.uid,
+                        elapsedRealtime);
+            }
+        }
+        if (DEBUG) {
+            Slog.d(TAG, "checkIdleStates took "
+                    + (mInjector.elapsedRealtime() - elapsedRealtime));
+        }
+        return true;
+    }
+
+    /** Check if we need to update the standby state of a specific app. */
+    private void checkAndUpdateStandbyState(String packageName, @UserIdInt int userId,
+            int uid, long elapsedRealtime) {
+        if (uid <= 0) {
+            try {
+                uid = mPackageManager.getPackageUidAsUser(packageName, userId);
+            } catch (PackageManager.NameNotFoundException e) {
+                // Not a valid package for this user, nothing to do
+                // TODO: Remove any history of removed packages
+                return;
+            }
+        }
+        final boolean isSpecial = isAppSpecial(packageName,
+                UserHandle.getAppId(uid),
+                userId);
+        if (DEBUG) {
+            Slog.d(TAG, "   Checking idle state for " + packageName + " special=" +
+                    isSpecial);
+        }
+        if (isSpecial) {
+            synchronized (mAppIdleLock) {
+                mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime,
+                        STANDBY_BUCKET_EXEMPTED, REASON_MAIN_DEFAULT);
+            }
+            maybeInformListeners(packageName, userId, elapsedRealtime,
+                    STANDBY_BUCKET_EXEMPTED, REASON_MAIN_DEFAULT, false);
+        } else {
+            synchronized (mAppIdleLock) {
+                final AppIdleHistory.AppUsageHistory app =
+                        mAppIdleHistory.getAppUsageHistory(packageName,
+                        userId, elapsedRealtime);
+                int reason = app.bucketingReason;
+                final int oldMainReason = reason & REASON_MAIN_MASK;
+
+                // If the bucket was forced by the user/developer, leave it alone.
+                // A usage event will be the only way to bring it out of this forced state
+                if (oldMainReason == REASON_MAIN_FORCED) {
+                    return;
+                }
+                final int oldBucket = app.currentBucket;
+                int newBucket = Math.max(oldBucket, STANDBY_BUCKET_ACTIVE); // Undo EXEMPTED
+                boolean predictionLate = predictionTimedOut(app, elapsedRealtime);
+                // Compute age-based bucket
+                if (oldMainReason == REASON_MAIN_DEFAULT
+                        || oldMainReason == REASON_MAIN_USAGE
+                        || oldMainReason == REASON_MAIN_TIMEOUT
+                        || predictionLate) {
+
+                    if (!predictionLate && app.lastPredictedBucket >= STANDBY_BUCKET_ACTIVE
+                            && app.lastPredictedBucket <= STANDBY_BUCKET_RARE) {
+                        newBucket = app.lastPredictedBucket;
+                        reason = REASON_MAIN_PREDICTED | REASON_SUB_PREDICTED_RESTORED;
+                        if (DEBUG) {
+                            Slog.d(TAG, "Restored predicted newBucket = " + newBucket);
+                        }
+                    } else {
+                        newBucket = getBucketForLocked(packageName, userId,
+                                elapsedRealtime);
+                        if (DEBUG) {
+                            Slog.d(TAG, "Evaluated AOSP newBucket = " + newBucket);
+                        }
+                        reason = REASON_MAIN_TIMEOUT;
+                    }
+                }
+
+                // Check if the app is within one of the timeouts for forced bucket elevation
+                final long elapsedTimeAdjusted = mAppIdleHistory.getElapsedTime(elapsedRealtime);
+                if (newBucket >= STANDBY_BUCKET_ACTIVE
+                        && app.bucketActiveTimeoutTime > elapsedTimeAdjusted) {
+                    newBucket = STANDBY_BUCKET_ACTIVE;
+                    reason = app.bucketingReason;
+                    if (DEBUG) {
+                        Slog.d(TAG, "    Keeping at ACTIVE due to min timeout");
+                    }
+                } else if (newBucket >= STANDBY_BUCKET_WORKING_SET
+                        && app.bucketWorkingSetTimeoutTime > elapsedTimeAdjusted) {
+                    newBucket = STANDBY_BUCKET_WORKING_SET;
+                    // If it was already there, keep the reason, else assume timeout to WS
+                    reason = (newBucket == oldBucket)
+                            ? app.bucketingReason
+                            : REASON_MAIN_USAGE | REASON_SUB_USAGE_ACTIVE_TIMEOUT;
+                    if (DEBUG) {
+                        Slog.d(TAG, "    Keeping at WORKING_SET due to min timeout");
+                    }
+                }
+                if (DEBUG) {
+                    Slog.d(TAG, "     Old bucket=" + oldBucket
+                            + ", newBucket=" + newBucket);
+                }
+                if (oldBucket < newBucket || predictionLate) {
+                    mAppIdleHistory.setAppStandbyBucket(packageName, userId,
+                            elapsedRealtime, newBucket, reason);
+                    maybeInformListeners(packageName, userId, elapsedRealtime,
+                            newBucket, reason, false);
+                }
+            }
+        }
+    }
+
+    /** Returns true if there hasn't been a prediction for the app in a while. */
+    private boolean predictionTimedOut(AppIdleHistory.AppUsageHistory app, long elapsedRealtime) {
+        return app.lastPredictedTime > 0
+                && mAppIdleHistory.getElapsedTime(elapsedRealtime)
+                    - app.lastPredictedTime > mPredictionTimeoutMillis;
+    }
+
+    /** Inform listeners if the bucket has changed since it was last reported to listeners */
+    private void maybeInformListeners(String packageName, int userId,
+            long elapsedRealtime, int bucket, int reason, boolean userStartedInteracting) {
+        synchronized (mAppIdleLock) {
+            if (mAppIdleHistory.shouldInformListeners(packageName, userId,
+                    elapsedRealtime, bucket)) {
+                final StandbyUpdateRecord r = StandbyUpdateRecord.obtain(packageName, userId,
+                        bucket, reason, userStartedInteracting);
+                if (DEBUG) Slog.d(TAG, "Standby bucket for " + packageName + "=" + bucket);
+                mHandler.sendMessage(mHandler.obtainMessage(MSG_INFORM_LISTENERS, r));
+            }
+        }
+    }
+
+    /**
+     * Evaluates next bucket based on time since last used and the bucketing thresholds.
+     * @param packageName the app
+     * @param userId the user
+     * @param elapsedRealtime as the name suggests, current elapsed time
+     * @return the bucket for the app, based on time since last used
+     */
+    @GuardedBy("mAppIdleLock")
+    @StandbyBuckets
+    private int getBucketForLocked(String packageName, int userId,
+            long elapsedRealtime) {
+        int bucketIndex = mAppIdleHistory.getThresholdIndex(packageName, userId,
+                elapsedRealtime, mAppStandbyScreenThresholds, mAppStandbyElapsedThresholds);
+        return THRESHOLD_BUCKETS[bucketIndex];
+    }
+
+    private void checkParoleTimeout() {
+        boolean setParoled = false;
+        boolean waitForNetwork = false;
+        NetworkInfo activeNetwork = mConnectivityManager.getActiveNetworkInfo();
+        boolean networkActive = activeNetwork != null &&
+                activeNetwork.isConnected();
+
+        synchronized (mAppIdleLock) {
+            final long now = mInjector.currentTimeMillis();
+            if (!mAppIdleTempParoled) {
+                final long timeSinceLastParole = now - mLastAppIdleParoledTime;
+                if (timeSinceLastParole > mAppIdleParoleIntervalMillis) {
+                    if (DEBUG) Slog.d(TAG, "Crossed default parole interval");
+                    if (networkActive) {
+                        // If network is active set parole
+                        setParoled = true;
+                    } else {
+                        if (timeSinceLastParole
+                                > mAppIdleParoleIntervalMillis + mAppIdleParoleWindowMillis) {
+                            if (DEBUG) Slog.d(TAG, "Crossed end of parole window, force parole");
+                            setParoled = true;
+                        } else {
+                            if (DEBUG) Slog.d(TAG, "Network unavailable, delaying parole");
+                            waitForNetwork = true;
+                            postNextParoleTimeout(now, true);
+                        }
+                    }
+                } else {
+                    if (DEBUG) Slog.d(TAG, "Not long enough to go to parole");
+                    postNextParoleTimeout(now, false);
+                }
+            }
+        }
+        if (waitForNetwork) {
+            mConnectivityManager.registerNetworkCallback(mNetworkRequest, mNetworkCallback);
+        }
+        if (setParoled) {
+            // Set parole if network is available
+            setAppIdleParoled(true);
+        }
+    }
+
+    private void notifyBatteryStats(String packageName, int userId, boolean idle) {
+        try {
+            final int uid = mPackageManager.getPackageUidAsUser(packageName,
+                    PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
+            if (idle) {
+                mInjector.noteEvent(BatteryStats.HistoryItem.EVENT_PACKAGE_INACTIVE,
+                        packageName, uid);
+            } else {
+                mInjector.noteEvent(BatteryStats.HistoryItem.EVENT_PACKAGE_ACTIVE,
+                        packageName, uid);
+            }
+        } catch (PackageManager.NameNotFoundException | RemoteException e) {
+        }
+    }
+
+    private void onDeviceIdleModeChanged() {
+        final boolean deviceIdle = mPowerManager.isDeviceIdleMode();
+        if (DEBUG) Slog.i(TAG, "DeviceIdleMode changed to " + deviceIdle);
+        boolean paroled = false;
+        synchronized (mAppIdleLock) {
+            final long timeSinceLastParole =
+                    mInjector.currentTimeMillis() - mLastAppIdleParoledTime;
+            if (!deviceIdle
+                    && timeSinceLastParole >= mAppIdleParoleIntervalMillis) {
+                if (DEBUG) {
+                    Slog.i(TAG,
+                            "Bringing idle apps out of inactive state due to deviceIdleMode=false");
+                }
+                paroled = true;
+            } else if (deviceIdle) {
+                if (DEBUG) Slog.i(TAG, "Device idle, back to prison");
+                paroled = false;
+            } else {
+                return;
+            }
+        }
+        setAppIdleParoled(paroled);
+    }
+
+    @Override
+    public void reportEvent(UsageEvents.Event event, long elapsedRealtime, int userId) {
+        if (!mAppIdleEnabled) return;
+        synchronized (mAppIdleLock) {
+            final String pkg = event.getPackageName();
+            final int eventType = event.getEventType();
+            // TODO: Ideally this should call isAppIdleFiltered() to avoid calling back
+            // about apps that are on some kind of whitelist anyway.
+            final boolean previouslyIdle = mAppIdleHistory.isIdle(
+                    pkg, userId, elapsedRealtime);
+            // Inform listeners if necessary
+            if ((eventType == UsageEvents.Event.ACTIVITY_RESUMED
+                    || eventType == UsageEvents.Event.ACTIVITY_PAUSED
+                    || eventType == UsageEvents.Event.SYSTEM_INTERACTION
+                    || eventType == UsageEvents.Event.USER_INTERACTION
+                    || eventType == UsageEvents.Event.NOTIFICATION_SEEN
+                    || eventType == UsageEvents.Event.SLICE_PINNED
+                    || eventType == UsageEvents.Event.SLICE_PINNED_PRIV
+                    || eventType == UsageEvents.Event.FOREGROUND_SERVICE_START)) {
+
+                final AppUsageHistory appHistory = mAppIdleHistory.getAppUsageHistory(
+                        pkg, userId, elapsedRealtime);
+                final int prevBucket = appHistory.currentBucket;
+                final int prevBucketReason = appHistory.bucketingReason;
+                final long nextCheckTime;
+                final int subReason = usageEventToSubReason(eventType);
+                final int reason = REASON_MAIN_USAGE | subReason;
+                if (eventType == UsageEvents.Event.NOTIFICATION_SEEN
+                        || eventType == UsageEvents.Event.SLICE_PINNED) {
+                    // Mild usage elevates to WORKING_SET but doesn't change usage time.
+                    mAppIdleHistory.reportUsage(appHistory, pkg,
+                            STANDBY_BUCKET_WORKING_SET, subReason,
+                            0, elapsedRealtime + mNotificationSeenTimeoutMillis);
+                    nextCheckTime = mNotificationSeenTimeoutMillis;
+                } else if (eventType == UsageEvents.Event.SYSTEM_INTERACTION) {
+                    mAppIdleHistory.reportUsage(appHistory, pkg,
+                            STANDBY_BUCKET_ACTIVE, subReason,
+                            0, elapsedRealtime + mSystemInteractionTimeoutMillis);
+                    nextCheckTime = mSystemInteractionTimeoutMillis;
+                } else if (eventType == UsageEvents.Event.FOREGROUND_SERVICE_START) {
+                    // Only elevate bucket if this is the first usage of the app
+                    if (prevBucket != STANDBY_BUCKET_NEVER) return;
+                    mAppIdleHistory.reportUsage(appHistory, pkg,
+                            STANDBY_BUCKET_ACTIVE, subReason,
+                            0, elapsedRealtime + mInitialForegroundServiceStartTimeoutMillis);
+                    nextCheckTime = mInitialForegroundServiceStartTimeoutMillis;
+                } else {
+                    mAppIdleHistory.reportUsage(appHistory, pkg,
+                            STANDBY_BUCKET_ACTIVE, subReason,
+                            elapsedRealtime, elapsedRealtime + mStrongUsageTimeoutMillis);
+                    nextCheckTime = mStrongUsageTimeoutMillis;
+                }
+                mHandler.sendMessageDelayed(mHandler.obtainMessage
+                        (MSG_CHECK_PACKAGE_IDLE_STATE, userId, -1, pkg),
+                        nextCheckTime);
+                final boolean userStartedInteracting =
+                        appHistory.currentBucket == STANDBY_BUCKET_ACTIVE &&
+                        prevBucket != appHistory.currentBucket &&
+                        (prevBucketReason & REASON_MAIN_MASK) != REASON_MAIN_USAGE;
+                maybeInformListeners(pkg, userId, elapsedRealtime,
+                        appHistory.currentBucket, reason, userStartedInteracting);
+
+                if (previouslyIdle) {
+                    notifyBatteryStats(pkg, userId, false);
+                }
+            }
+        }
+    }
+
+    private int usageEventToSubReason(int eventType) {
+        switch (eventType) {
+            case UsageEvents.Event.ACTIVITY_RESUMED: return REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
+            case UsageEvents.Event.ACTIVITY_PAUSED: return REASON_SUB_USAGE_MOVE_TO_BACKGROUND;
+            case UsageEvents.Event.SYSTEM_INTERACTION: return REASON_SUB_USAGE_SYSTEM_INTERACTION;
+            case UsageEvents.Event.USER_INTERACTION: return REASON_SUB_USAGE_USER_INTERACTION;
+            case UsageEvents.Event.NOTIFICATION_SEEN: return REASON_SUB_USAGE_NOTIFICATION_SEEN;
+            case UsageEvents.Event.SLICE_PINNED: return REASON_SUB_USAGE_SLICE_PINNED;
+            case UsageEvents.Event.SLICE_PINNED_PRIV: return REASON_SUB_USAGE_SLICE_PINNED_PRIV;
+            case UsageEvents.Event.FOREGROUND_SERVICE_START:
+                return REASON_SUB_USAGE_FOREGROUND_SERVICE_START;
+            default: return 0;
+        }
+    }
+
+    @VisibleForTesting
+    void forceIdleState(String packageName, int userId, boolean idle) {
+        if (!mAppIdleEnabled) return;
+
+        final int appId = getAppId(packageName);
+        if (appId < 0) return;
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+
+        final boolean previouslyIdle = isAppIdleFiltered(packageName, appId,
+                userId, elapsedRealtime);
+        final int standbyBucket;
+        synchronized (mAppIdleLock) {
+            standbyBucket = mAppIdleHistory.setIdle(packageName, userId, idle, elapsedRealtime);
+        }
+        final boolean stillIdle = isAppIdleFiltered(packageName, appId,
+                userId, elapsedRealtime);
+        // Inform listeners if necessary
+        if (previouslyIdle != stillIdle) {
+            maybeInformListeners(packageName, userId, elapsedRealtime, standbyBucket,
+                    REASON_MAIN_FORCED, false);
+            if (!stillIdle) {
+                notifyBatteryStats(packageName, userId, idle);
+            }
+        }
+    }
+
+    @Override
+    public void setLastJobRunTime(String packageName, int userId, long elapsedRealtime) {
+        synchronized (mAppIdleLock) {
+            mAppIdleHistory.setLastJobRunTime(packageName, userId, elapsedRealtime);
+        }
+    }
+
+    @Override
+    public long getTimeSinceLastJobRun(String packageName, int userId) {
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+        synchronized (mAppIdleLock) {
+            return mAppIdleHistory.getTimeSinceLastJobRun(packageName, userId, elapsedRealtime);
+        }
+    }
+
+    @Override
+    public void onUserRemoved(int userId) {
+        synchronized (mAppIdleLock) {
+            mAppIdleHistory.onUserRemoved(userId);
+            synchronized (mActiveAdminApps) {
+                mActiveAdminApps.remove(userId);
+            }
+        }
+    }
+
+    private boolean isAppIdleUnfiltered(String packageName, int userId, long elapsedRealtime) {
+        synchronized (mAppIdleLock) {
+            return mAppIdleHistory.isIdle(packageName, userId, elapsedRealtime);
+        }
+    }
+
+    @Override
+    public void addListener(AppIdleStateChangeListener listener) {
+        synchronized (mPackageAccessListeners) {
+            if (!mPackageAccessListeners.contains(listener)) {
+                mPackageAccessListeners.add(listener);
+            }
+        }
+    }
+
+    @Override
+    public void removeListener(AppIdleStateChangeListener listener) {
+        synchronized (mPackageAccessListeners) {
+            mPackageAccessListeners.remove(listener);
+        }
+    }
+
+    @Override
+    public int getAppId(String packageName) {
+        try {
+            ApplicationInfo ai = mPackageManager.getApplicationInfo(packageName,
+                    PackageManager.MATCH_ANY_USER
+                            | PackageManager.MATCH_DISABLED_COMPONENTS);
+            return ai.uid;
+        } catch (PackageManager.NameNotFoundException re) {
+            return -1;
+        }
+    }
+
+    @Override
+    public boolean isAppIdleFilteredOrParoled(String packageName, int userId, long elapsedRealtime,
+            boolean shouldObfuscateInstantApps) {
+        if (isParoledOrCharging()) {
+            return false;
+        }
+        if (shouldObfuscateInstantApps &&
+                mInjector.isPackageEphemeral(userId, packageName)) {
+            return false;
+        }
+        return isAppIdleFiltered(packageName, getAppId(packageName), userId, elapsedRealtime);
+    }
+
+    private boolean isAppSpecial(String packageName, int appId, int userId) {
+        if (packageName == null) return false;
+        // If not enabled at all, of course nobody is ever idle.
+        if (!mAppIdleEnabled) {
+            return true;
+        }
+        if (appId < Process.FIRST_APPLICATION_UID) {
+            // System uids never go idle.
+            return true;
+        }
+        if (packageName.equals("android")) {
+            // Nor does the framework (which should be redundant with the above, but for MR1 we will
+            // retain this for safety).
+            return true;
+        }
+        if (mSystemServicesReady) {
+            try {
+                // We allow all whitelisted apps, including those that don't want to be whitelisted
+                // for idle mode, because app idle (aka app standby) is really not as big an issue
+                // for controlling who participates vs. doze mode.
+                if (mInjector.isPowerSaveWhitelistExceptIdleApp(packageName)) {
+                    return true;
+                }
+            } catch (RemoteException re) {
+                throw re.rethrowFromSystemServer();
+            }
+
+            if (isActiveDeviceAdmin(packageName, userId)) {
+                return true;
+            }
+
+            if (isActiveNetworkScorer(packageName)) {
+                return true;
+            }
+
+            if (mAppWidgetManager != null
+                    && mInjector.isBoundWidgetPackage(mAppWidgetManager, packageName, userId)) {
+                return true;
+            }
+
+            if (isDeviceProvisioningPackage(packageName)) {
+                return true;
+            }
+        }
+
+        // Check this last, as it can be the most expensive check
+        if (isCarrierApp(packageName)) {
+            return true;
+        }
+
+        return false;
+    }
+
+    @Override
+    public boolean isAppIdleFiltered(String packageName, int appId, int userId,
+            long elapsedRealtime) {
+        if (isAppSpecial(packageName, appId, userId)) {
+            return false;
+        } else {
+            return isAppIdleUnfiltered(packageName, userId, elapsedRealtime);
+        }
+    }
+
+    @Override
+    public int[] getIdleUidsForUser(int userId) {
+        if (!mAppIdleEnabled) {
+            return new int[0];
+        }
+
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+
+        List<ApplicationInfo> apps;
+        try {
+            ParceledListSlice<ApplicationInfo> slice = AppGlobals.getPackageManager()
+                    .getInstalledApplications(/* flags= */ 0, userId);
+            if (slice == null) {
+                return new int[0];
+            }
+            apps = slice.getList();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+
+        // State of each uid.  Key is the uid.  Value lower 16 bits is the number of apps
+        // associated with that uid, upper 16 bits is the number of those apps that is idle.
+        SparseIntArray uidStates = new SparseIntArray();
+
+        // Now resolve all app state.  Iterating over all apps, keeping track of how many
+        // we find for each uid and how many of those are idle.
+        for (int i = apps.size() - 1; i >= 0; i--) {
+            ApplicationInfo ai = apps.get(i);
+
+            // Check whether this app is idle.
+            boolean idle = isAppIdleFiltered(ai.packageName, UserHandle.getAppId(ai.uid),
+                    userId, elapsedRealtime);
+
+            int index = uidStates.indexOfKey(ai.uid);
+            if (index < 0) {
+                uidStates.put(ai.uid, 1 + (idle ? 1<<16 : 0));
+            } else {
+                int value = uidStates.valueAt(index);
+                uidStates.setValueAt(index, value + 1 + (idle ? 1<<16 : 0));
+            }
+        }
+        if (DEBUG) {
+            Slog.d(TAG, "getIdleUids took " + (mInjector.elapsedRealtime() - elapsedRealtime));
+        }
+        int numIdle = 0;
+        for (int i = uidStates.size() - 1; i >= 0; i--) {
+            int value = uidStates.valueAt(i);
+            if ((value&0x7fff) == (value>>16)) {
+                numIdle++;
+            }
+        }
+
+        int[] res = new int[numIdle];
+        numIdle = 0;
+        for (int i = uidStates.size() - 1; i >= 0; i--) {
+            int value = uidStates.valueAt(i);
+            if ((value&0x7fff) == (value>>16)) {
+                res[numIdle] = uidStates.keyAt(i);
+                numIdle++;
+            }
+        }
+
+        return res;
+    }
+
+    @Override
+    public void setAppIdleAsync(String packageName, boolean idle, int userId) {
+        if (packageName == null || !mAppIdleEnabled) return;
+
+        mHandler.obtainMessage(MSG_FORCE_IDLE_STATE, userId, idle ? 1 : 0, packageName)
+                .sendToTarget();
+    }
+
+    @Override
+    @StandbyBuckets public int getAppStandbyBucket(String packageName, int userId,
+            long elapsedRealtime, boolean shouldObfuscateInstantApps) {
+        if (!mAppIdleEnabled || (shouldObfuscateInstantApps
+                && mInjector.isPackageEphemeral(userId, packageName))) {
+            return STANDBY_BUCKET_ACTIVE;
+        }
+
+        synchronized (mAppIdleLock) {
+            return mAppIdleHistory.getAppStandbyBucket(packageName, userId, elapsedRealtime);
+        }
+    }
+
+    @Override
+    public List<AppStandbyInfo> getAppStandbyBuckets(int userId) {
+        synchronized (mAppIdleLock) {
+            return mAppIdleHistory.getAppStandbyBuckets(userId, mAppIdleEnabled);
+        }
+    }
+
+    @VisibleForTesting
+    void setAppStandbyBucket(String packageName, int userId, @StandbyBuckets int newBucket,
+            int reason, long elapsedRealtime) {
+        setAppStandbyBucket(packageName, userId, newBucket, reason, elapsedRealtime, false);
+    }
+
+    @Override
+    public void setAppStandbyBucket(String packageName, int userId, @StandbyBuckets int newBucket,
+            int reason, long elapsedRealtime, boolean resetTimeout) {
+        synchronized (mAppIdleLock) {
+            // If the package is not installed, don't allow the bucket to be set.
+            if (!mInjector.isPackageInstalled(packageName, 0, userId)) {
+                return;
+            }
+            AppIdleHistory.AppUsageHistory app = mAppIdleHistory.getAppUsageHistory(packageName,
+                    userId, elapsedRealtime);
+            boolean predicted = (reason & REASON_MAIN_MASK) == REASON_MAIN_PREDICTED;
+
+            // Don't allow changing bucket if higher than ACTIVE
+            if (app.currentBucket < STANDBY_BUCKET_ACTIVE) return;
+
+            // Don't allow prediction to change from/to NEVER
+            if ((app.currentBucket == STANDBY_BUCKET_NEVER
+                    || newBucket == STANDBY_BUCKET_NEVER)
+                    && predicted) {
+                return;
+            }
+
+            // If the bucket was forced, don't allow prediction to override
+            if ((app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_FORCED && predicted) return;
+
+            // If the bucket is required to stay in a higher state for a specified duration, don't
+            // override unless the duration has passed
+            if (predicted) {
+                // Check if the app is within one of the timeouts for forced bucket elevation
+                final long elapsedTimeAdjusted = mAppIdleHistory.getElapsedTime(elapsedRealtime);
+                // In case of not using the prediction, just keep track of it for applying after
+                // ACTIVE or WORKING_SET timeout.
+                mAppIdleHistory.updateLastPrediction(app, elapsedTimeAdjusted, newBucket);
+
+                if (newBucket > STANDBY_BUCKET_ACTIVE
+                        && app.bucketActiveTimeoutTime > elapsedTimeAdjusted) {
+                    newBucket = STANDBY_BUCKET_ACTIVE;
+                    reason = app.bucketingReason;
+                    if (DEBUG) {
+                        Slog.d(TAG, "    Keeping at ACTIVE due to min timeout");
+                    }
+                } else if (newBucket > STANDBY_BUCKET_WORKING_SET
+                        && app.bucketWorkingSetTimeoutTime > elapsedTimeAdjusted) {
+                    newBucket = STANDBY_BUCKET_WORKING_SET;
+                    if (app.currentBucket != newBucket) {
+                        reason = REASON_MAIN_USAGE | REASON_SUB_USAGE_ACTIVE_TIMEOUT;
+                    } else {
+                        reason = app.bucketingReason;
+                    }
+                    if (DEBUG) {
+                        Slog.d(TAG, "    Keeping at WORKING_SET due to min timeout");
+                    }
+                }
+            }
+
+            mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime, newBucket,
+                    reason, resetTimeout);
+        }
+        maybeInformListeners(packageName, userId, elapsedRealtime, newBucket, reason, false);
+    }
+
+    @VisibleForTesting
+    boolean isActiveDeviceAdmin(String packageName, int userId) {
+        synchronized (mActiveAdminApps) {
+            final Set<String> adminPkgs = mActiveAdminApps.get(userId);
+            return adminPkgs != null && adminPkgs.contains(packageName);
+        }
+    }
+
+    @Override
+    public void addActiveDeviceAdmin(String adminPkg, int userId) {
+        synchronized (mActiveAdminApps) {
+            Set<String> adminPkgs = mActiveAdminApps.get(userId);
+            if (adminPkgs == null) {
+                adminPkgs = new ArraySet<>();
+                mActiveAdminApps.put(userId, adminPkgs);
+            }
+            adminPkgs.add(adminPkg);
+        }
+    }
+
+    @Override
+    public void setActiveAdminApps(Set<String> adminPkgs, int userId) {
+        synchronized (mActiveAdminApps) {
+            if (adminPkgs == null) {
+                mActiveAdminApps.remove(userId);
+            } else {
+                mActiveAdminApps.put(userId, adminPkgs);
+            }
+        }
+    }
+
+    @Override
+    public void onAdminDataAvailable() {
+        mAdminDataAvailableLatch.countDown();
+    }
+
+    /**
+     * This will only ever be called once - during device boot.
+     */
+    private void waitForAdminData() {
+        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
+            ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
+                    WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
+        }
+    }
+
+    @VisibleForTesting
+    Set<String> getActiveAdminAppsForTest(int userId) {
+        synchronized (mActiveAdminApps) {
+            return mActiveAdminApps.get(userId);
+        }
+    }
+
+    /**
+     * Returns {@code true} if the supplied package is the device provisioning app. Otherwise,
+     * returns {@code false}.
+     */
+    private boolean isDeviceProvisioningPackage(String packageName) {
+        String deviceProvisioningPackage = mContext.getResources().getString(
+                com.android.internal.R.string.config_deviceProvisioningPackage);
+        return deviceProvisioningPackage != null && deviceProvisioningPackage.equals(packageName);
+    }
+
+    private boolean isCarrierApp(String packageName) {
+        synchronized (mAppIdleLock) {
+            if (!mHaveCarrierPrivilegedApps) {
+                fetchCarrierPrivilegedAppsLocked();
+            }
+            if (mCarrierPrivilegedApps != null) {
+                return mCarrierPrivilegedApps.contains(packageName);
+            }
+            return false;
+        }
+    }
+
+    @Override
+    public void clearCarrierPrivilegedApps() {
+        if (DEBUG) {
+            Slog.i(TAG, "Clearing carrier privileged apps list");
+        }
+        synchronized (mAppIdleLock) {
+            mHaveCarrierPrivilegedApps = false;
+            mCarrierPrivilegedApps = null; // Need to be refetched.
+        }
+    }
+
+    @GuardedBy("mAppIdleLock")
+    private void fetchCarrierPrivilegedAppsLocked() {
+        TelephonyManager telephonyManager =
+                mContext.getSystemService(TelephonyManager.class);
+        mCarrierPrivilegedApps = telephonyManager.getPackagesWithCarrierPrivilegesForAllPhones();
+        mHaveCarrierPrivilegedApps = true;
+        if (DEBUG) {
+            Slog.d(TAG, "apps with carrier privilege " + mCarrierPrivilegedApps);
+        }
+    }
+
+    private boolean isActiveNetworkScorer(String packageName) {
+        String activeScorer = mInjector.getActiveNetworkScorer();
+        return packageName != null && packageName.equals(activeScorer);
+    }
+
+    private void informListeners(String packageName, int userId, int bucket, int reason,
+            boolean userInteraction) {
+        final boolean idle = bucket >= STANDBY_BUCKET_RARE;
+        synchronized (mPackageAccessListeners) {
+            for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
+                listener.onAppIdleStateChanged(packageName, userId, idle, bucket, reason);
+                if (userInteraction) {
+                    listener.onUserInteractionStarted(packageName, userId);
+                }
+            }
+        }
+    }
+
+    private void informParoleStateChanged() {
+        final boolean paroled = isParoledOrCharging();
+        synchronized (mPackageAccessListeners) {
+            for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
+                listener.onParoleStateChanged(paroled);
+            }
+        }
+    }
+
+    @Override
+    public void flushToDisk(int userId) {
+        synchronized (mAppIdleLock) {
+            mAppIdleHistory.writeAppIdleTimes(userId);
+        }
+    }
+
+    @Override
+    public void flushDurationsToDisk() {
+        // Persist elapsed and screen on time. If this fails for whatever reason, the apps will be
+        // considered not-idle, which is the safest outcome in such an event.
+        synchronized (mAppIdleLock) {
+            mAppIdleHistory.writeAppIdleDurations();
+        }
+    }
+
+    private boolean isDisplayOn() {
+        return mInjector.isDefaultDisplayOn();
+    }
+
+    @VisibleForTesting
+    void clearAppIdleForPackage(String packageName, int userId) {
+        synchronized (mAppIdleLock) {
+            mAppIdleHistory.clearUsage(packageName, userId);
+        }
+    }
+
+    private class PackageReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            final String action = intent.getAction();
+            if (Intent.ACTION_PACKAGE_ADDED.equals(action)
+                    || Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
+                clearCarrierPrivilegedApps();
+            }
+            if ((Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
+                    Intent.ACTION_PACKAGE_ADDED.equals(action))
+                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
+                clearAppIdleForPackage(intent.getData().getSchemeSpecificPart(),
+                        getSendingUserId());
+            }
+        }
+    }
+
+    @Override
+    public void initializeDefaultsForSystemApps(int userId) {
+        if (!mSystemServicesReady) {
+            // Do it later, since SettingsProvider wasn't queried yet for app_standby_enabled
+            mPendingInitializeDefaults = true;
+            return;
+        }
+        Slog.d(TAG, "Initializing defaults for system apps on user " + userId + ", "
+                + "appIdleEnabled=" + mAppIdleEnabled);
+        final long elapsedRealtime = mInjector.elapsedRealtime();
+        List<PackageInfo> packages = mPackageManager.getInstalledPackagesAsUser(
+                PackageManager.MATCH_DISABLED_COMPONENTS,
+                userId);
+        final int packageCount = packages.size();
+        synchronized (mAppIdleLock) {
+            for (int i = 0; i < packageCount; i++) {
+                final PackageInfo pi = packages.get(i);
+                String packageName = pi.packageName;
+                if (pi.applicationInfo != null && pi.applicationInfo.isSystemApp()) {
+                    // Mark app as used for 2 hours. After that it can timeout to whatever the
+                    // past usage pattern was.
+                    mAppIdleHistory.reportUsage(packageName, userId, STANDBY_BUCKET_ACTIVE,
+                            REASON_SUB_USAGE_SYSTEM_UPDATE, 0,
+                            elapsedRealtime + mSystemUpdateUsageTimeoutMillis);
+                }
+            }
+            // Immediately persist defaults to disk
+            mAppIdleHistory.writeAppIdleTimes(userId);
+        }
+    }
+
+    @Override
+    public void postReportContentProviderUsage(String name, String packageName, int userId) {
+        SomeArgs args = SomeArgs.obtain();
+        args.arg1 = name;
+        args.arg2 = packageName;
+        args.arg3 = userId;
+        mHandler.obtainMessage(MSG_REPORT_CONTENT_PROVIDER_USAGE, args)
+                .sendToTarget();
+    }
+
+    @Override
+    public void postReportSyncScheduled(String packageName, int userId, boolean exempted) {
+        mHandler.obtainMessage(MSG_REPORT_SYNC_SCHEDULED, userId, exempted ? 1 : 0, packageName)
+                .sendToTarget();
+    }
+
+    @Override
+    public void postReportExemptedSyncStart(String packageName, int userId) {
+        mHandler.obtainMessage(MSG_REPORT_EXEMPTED_SYNC_START, userId, 0, packageName)
+                .sendToTarget();
+    }
+
+    @Override
+    public void dumpUser(IndentingPrintWriter idpw, int userId, String pkg) {
+        synchronized (mAppIdleLock) {
+            mAppIdleHistory.dump(idpw, userId, pkg);
+        }
+    }
+
+    @Override
+    public void dumpState(String[] args, PrintWriter pw) {
+        synchronized (mAppIdleLock) {
+            pw.println("Carrier privileged apps (have=" + mHaveCarrierPrivilegedApps
+                    + "): " + mCarrierPrivilegedApps);
+        }
+
+        final long now = System.currentTimeMillis();
+
+        pw.println();
+        pw.println("Settings:");
+
+        pw.print("  mCheckIdleIntervalMillis=");
+        TimeUtils.formatDuration(mCheckIdleIntervalMillis, pw);
+        pw.println();
+
+        pw.print("  mAppIdleParoleIntervalMillis=");
+        TimeUtils.formatDuration(mAppIdleParoleIntervalMillis, pw);
+        pw.println();
+
+        pw.print("  mAppIdleParoleWindowMillis=");
+        TimeUtils.formatDuration(mAppIdleParoleWindowMillis, pw);
+        pw.println();
+
+        pw.print("  mAppIdleParoleDurationMillis=");
+        TimeUtils.formatDuration(mAppIdleParoleDurationMillis, pw);
+        pw.println();
+
+        pw.print("  mStrongUsageTimeoutMillis=");
+        TimeUtils.formatDuration(mStrongUsageTimeoutMillis, pw);
+        pw.println();
+        pw.print("  mNotificationSeenTimeoutMillis=");
+        TimeUtils.formatDuration(mNotificationSeenTimeoutMillis, pw);
+        pw.println();
+        pw.print("  mSyncAdapterTimeoutMillis=");
+        TimeUtils.formatDuration(mSyncAdapterTimeoutMillis, pw);
+        pw.println();
+        pw.print("  mSystemInteractionTimeoutMillis=");
+        TimeUtils.formatDuration(mSystemInteractionTimeoutMillis, pw);
+        pw.println();
+        pw.print("  mInitialForegroundServiceStartTimeoutMillis=");
+        TimeUtils.formatDuration(mInitialForegroundServiceStartTimeoutMillis, pw);
+        pw.println();
+
+        pw.print("  mPredictionTimeoutMillis=");
+        TimeUtils.formatDuration(mPredictionTimeoutMillis, pw);
+        pw.println();
+
+        pw.print("  mExemptedSyncScheduledNonDozeTimeoutMillis=");
+        TimeUtils.formatDuration(mExemptedSyncScheduledNonDozeTimeoutMillis, pw);
+        pw.println();
+        pw.print("  mExemptedSyncScheduledDozeTimeoutMillis=");
+        TimeUtils.formatDuration(mExemptedSyncScheduledDozeTimeoutMillis, pw);
+        pw.println();
+        pw.print("  mExemptedSyncStartTimeoutMillis=");
+        TimeUtils.formatDuration(mExemptedSyncStartTimeoutMillis, pw);
+        pw.println();
+        pw.print("  mUnexemptedSyncScheduledTimeoutMillis=");
+        TimeUtils.formatDuration(mUnexemptedSyncScheduledTimeoutMillis, pw);
+        pw.println();
+
+        pw.print("  mSystemUpdateUsageTimeoutMillis=");
+        TimeUtils.formatDuration(mSystemUpdateUsageTimeoutMillis, pw);
+        pw.println();
+
+        pw.print("  mStableChargingThresholdMillis=");
+        TimeUtils.formatDuration(mStableChargingThresholdMillis, pw);
+        pw.println();
+
+        pw.println();
+        pw.print("mAppIdleEnabled="); pw.print(mAppIdleEnabled);
+        pw.print(" mAppIdleTempParoled="); pw.print(mAppIdleTempParoled);
+        pw.print(" mCharging="); pw.print(mCharging);
+        pw.print(" mChargingStable="); pw.print(mChargingStable);
+        pw.print(" mLastAppIdleParoledTime=");
+        TimeUtils.formatDuration(now - mLastAppIdleParoledTime, pw);
+        pw.println();
+        pw.print("mScreenThresholds="); pw.println(Arrays.toString(mAppStandbyScreenThresholds));
+        pw.print("mElapsedThresholds="); pw.println(Arrays.toString(mAppStandbyElapsedThresholds));
+        pw.print("mStableChargingThresholdMillis=");
+        TimeUtils.formatDuration(mStableChargingThresholdMillis, pw);
+        pw.println();
+    }
+
+    /**
+     * Injector for interaction with external code. Override methods to provide a mock
+     * implementation for tests.
+     * onBootPhase() must be called with at least the PHASE_SYSTEM_SERVICES_READY
+     */
+    static class Injector {
+
+        private final Context mContext;
+        private final Looper mLooper;
+        private IDeviceIdleController mDeviceIdleController;
+        private IBatteryStats mBatteryStats;
+        private PackageManagerInternal mPackageManagerInternal;
+        private DisplayManager mDisplayManager;
+        private PowerManager mPowerManager;
+        int mBootPhase;
+
+        Injector(Context context, Looper looper) {
+            mContext = context;
+            mLooper = looper;
+        }
+
+        Context getContext() {
+            return mContext;
+        }
+
+        Looper getLooper() {
+            return mLooper;
+        }
+
+        void onBootPhase(int phase) {
+            if (phase == PHASE_SYSTEM_SERVICES_READY) {
+                mDeviceIdleController = IDeviceIdleController.Stub.asInterface(
+                        ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
+                mBatteryStats = IBatteryStats.Stub.asInterface(
+                        ServiceManager.getService(BatteryStats.SERVICE_NAME));
+                mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
+                mDisplayManager = (DisplayManager) mContext.getSystemService(
+                        Context.DISPLAY_SERVICE);
+                mPowerManager = mContext.getSystemService(PowerManager.class);
+            }
+            mBootPhase = phase;
+        }
+
+        int getBootPhase() {
+            return mBootPhase;
+        }
+
+        /**
+         * Returns the elapsed realtime since the device started. Override this
+         * to control the clock.
+         * @return elapsed realtime
+         */
+        long elapsedRealtime() {
+            return SystemClock.elapsedRealtime();
+        }
+
+        long currentTimeMillis() {
+            return System.currentTimeMillis();
+        }
+
+        boolean isAppIdleEnabled() {
+            final boolean buildFlag = mContext.getResources().getBoolean(
+                    com.android.internal.R.bool.config_enableAutoPowerModes);
+            final boolean runtimeFlag = Global.getInt(mContext.getContentResolver(),
+                    Global.APP_STANDBY_ENABLED, 1) == 1
+                    && Global.getInt(mContext.getContentResolver(),
+                    Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED, 1) == 1;
+            return buildFlag && runtimeFlag;
+        }
+
+        boolean isCharging() {
+            return mContext.getSystemService(BatteryManager.class).isCharging();
+        }
+
+        boolean isPowerSaveWhitelistExceptIdleApp(String packageName) throws RemoteException {
+            return mDeviceIdleController.isPowerSaveWhitelistExceptIdleApp(packageName);
+        }
+
+        File getDataSystemDirectory() {
+            return Environment.getDataSystemDirectory();
+        }
+
+        void noteEvent(int event, String packageName, int uid) throws RemoteException {
+            mBatteryStats.noteEvent(event, packageName, uid);
+        }
+
+        boolean isPackageEphemeral(int userId, String packageName) {
+            return mPackageManagerInternal.isPackageEphemeral(userId, packageName);
+        }
+
+        boolean isPackageInstalled(String packageName, int flags, int userId) {
+            return mPackageManagerInternal.getPackageUid(packageName, flags, userId) >= 0;
+        }
+
+        int[] getRunningUserIds() throws RemoteException {
+            return ActivityManager.getService().getRunningUserIds();
+        }
+
+        boolean isDefaultDisplayOn() {
+            return mDisplayManager
+                    .getDisplay(Display.DEFAULT_DISPLAY).getState() == Display.STATE_ON;
+        }
+
+        void registerDisplayListener(DisplayManager.DisplayListener listener, Handler handler) {
+            mDisplayManager.registerDisplayListener(listener, handler);
+        }
+
+        String getActiveNetworkScorer() {
+            NetworkScoreManager nsm = (NetworkScoreManager) mContext.getSystemService(
+                    Context.NETWORK_SCORE_SERVICE);
+            return nsm.getActiveScorerPackage();
+        }
+
+        public boolean isBoundWidgetPackage(AppWidgetManager appWidgetManager, String packageName,
+                int userId) {
+            return appWidgetManager.isBoundWidgetPackage(packageName, userId);
+        }
+
+        String getAppIdleSettings() {
+            return Global.getString(mContext.getContentResolver(),
+                    Global.APP_IDLE_CONSTANTS);
+        }
+
+        /** Whether the device is in doze or not. */
+        public boolean isDeviceIdleMode() {
+            return mPowerManager.isDeviceIdleMode();
+        }
+    }
+
+    class AppStandbyHandler extends Handler {
+
+        AppStandbyHandler(Looper looper) {
+            super(looper);
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case MSG_INFORM_LISTENERS:
+                    StandbyUpdateRecord r = (StandbyUpdateRecord) msg.obj;
+                    informListeners(r.packageName, r.userId, r.bucket, r.reason,
+                            r.isUserInteraction);
+                    r.recycle();
+                    break;
+
+                case MSG_FORCE_IDLE_STATE:
+                    forceIdleState((String) msg.obj, msg.arg1, msg.arg2 == 1);
+                    break;
+
+                case MSG_CHECK_IDLE_STATES:
+                    if (checkIdleStates(msg.arg1) && mAppIdleEnabled) {
+                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
+                                MSG_CHECK_IDLE_STATES, msg.arg1, 0),
+                                mCheckIdleIntervalMillis);
+                    }
+                    break;
+
+                case MSG_ONE_TIME_CHECK_IDLE_STATES:
+                    mHandler.removeMessages(MSG_ONE_TIME_CHECK_IDLE_STATES);
+                    waitForAdminData();
+                    checkIdleStates(UserHandle.USER_ALL);
+                    break;
+
+                case MSG_CHECK_PAROLE_TIMEOUT:
+                    checkParoleTimeout();
+                    break;
+
+                case MSG_PAROLE_END_TIMEOUT:
+                    if (DEBUG) Slog.d(TAG, "Ending parole");
+                    setAppIdleParoled(false);
+                    break;
+
+                case MSG_REPORT_CONTENT_PROVIDER_USAGE:
+                    SomeArgs args = (SomeArgs) msg.obj;
+                    reportContentProviderUsage((String) args.arg1, // authority name
+                            (String) args.arg2, // package name
+                            (int) args.arg3); // userId
+                    args.recycle();
+                    break;
+
+                case MSG_PAROLE_STATE_CHANGED:
+                    if (DEBUG) Slog.d(TAG, "Parole state: " + mAppIdleTempParoled
+                            + ", Charging state:" + mChargingStable);
+                    informParoleStateChanged();
+                    break;
+                case MSG_CHECK_PACKAGE_IDLE_STATE:
+                    checkAndUpdateStandbyState((String) msg.obj, msg.arg1, msg.arg2,
+                            mInjector.elapsedRealtime());
+                    break;
+
+                case MSG_REPORT_SYNC_SCHEDULED:
+                    final boolean exempted = msg.arg1 > 0 ? true : false;
+                    if (exempted) {
+                        reportExemptedSyncScheduled((String) msg.obj, msg.arg1);
+                    } else {
+                        reportUnexemptedSyncScheduled((String) msg.obj, msg.arg1);
+                    }
+                    break;
+
+                case MSG_REPORT_EXEMPTED_SYNC_START:
+                    reportExemptedSyncStart((String) msg.obj, msg.arg1);
+                    break;
+
+                case MSG_UPDATE_STABLE_CHARGING:
+                    updateChargingStableState();
+                    break;
+
+                default:
+                    super.handleMessage(msg);
+                    break;
+
+            }
+        }
+    };
+
+    private class DeviceStateReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            switch (intent.getAction()) {
+                case BatteryManager.ACTION_CHARGING:
+                    setChargingState(true);
+                    break;
+                case BatteryManager.ACTION_DISCHARGING:
+                    setChargingState(false);
+                    break;
+                case PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED:
+                    onDeviceIdleModeChanged();
+                    break;
+            }
+        }
+    }
+
+    private final NetworkRequest mNetworkRequest = new NetworkRequest.Builder().build();
+
+    private final ConnectivityManager.NetworkCallback mNetworkCallback
+            = new ConnectivityManager.NetworkCallback() {
+        @Override
+        public void onAvailable(Network network) {
+            mConnectivityManager.unregisterNetworkCallback(this);
+            checkParoleTimeout();
+        }
+    };
+
+    private final DisplayManager.DisplayListener mDisplayListener
+            = new DisplayManager.DisplayListener() {
+
+        @Override public void onDisplayAdded(int displayId) {
+        }
+
+        @Override public void onDisplayRemoved(int displayId) {
+        }
+
+        @Override public void onDisplayChanged(int displayId) {
+            if (displayId == Display.DEFAULT_DISPLAY) {
+                final boolean displayOn = isDisplayOn();
+                synchronized (mAppIdleLock) {
+                    mAppIdleHistory.updateDisplay(displayOn, mInjector.elapsedRealtime());
+                }
+            }
+        }
+    };
+
+    /**
+     * Observe settings changes for {@link Global#APP_IDLE_CONSTANTS}.
+     */
+    private class SettingsObserver extends ContentObserver {
+        private static final String KEY_PAROLE_INTERVAL = "parole_interval";
+        private static final String KEY_PAROLE_WINDOW = "parole_window";
+        private static final String KEY_PAROLE_DURATION = "parole_duration";
+        private static final String KEY_SCREEN_TIME_THRESHOLDS = "screen_thresholds";
+        private static final String KEY_ELAPSED_TIME_THRESHOLDS = "elapsed_thresholds";
+        private static final String KEY_STRONG_USAGE_HOLD_DURATION = "strong_usage_duration";
+        private static final String KEY_NOTIFICATION_SEEN_HOLD_DURATION =
+                "notification_seen_duration";
+        private static final String KEY_SYSTEM_UPDATE_HOLD_DURATION =
+                "system_update_usage_duration";
+        private static final String KEY_PREDICTION_TIMEOUT = "prediction_timeout";
+        private static final String KEY_SYNC_ADAPTER_HOLD_DURATION = "sync_adapter_duration";
+        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION =
+                "exempted_sync_scheduled_nd_duration";
+        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION =
+                "exempted_sync_scheduled_d_duration";
+        private static final String KEY_EXEMPTED_SYNC_START_HOLD_DURATION =
+                "exempted_sync_start_duration";
+        private static final String KEY_UNEXEMPTED_SYNC_SCHEDULED_HOLD_DURATION =
+                "unexempted_sync_scheduled_duration";
+        private static final String KEY_SYSTEM_INTERACTION_HOLD_DURATION =
+                "system_interaction_duration";
+        private static final String KEY_INITIAL_FOREGROUND_SERVICE_START_HOLD_DURATION =
+                "initial_foreground_service_start_duration";
+        private static final String KEY_STABLE_CHARGING_THRESHOLD = "stable_charging_threshold";
+        public static final long DEFAULT_STRONG_USAGE_TIMEOUT = 1 * ONE_HOUR;
+        public static final long DEFAULT_NOTIFICATION_TIMEOUT = 12 * ONE_HOUR;
+        public static final long DEFAULT_SYSTEM_UPDATE_TIMEOUT = 2 * ONE_HOUR;
+        public static final long DEFAULT_SYSTEM_INTERACTION_TIMEOUT = 10 * ONE_MINUTE;
+        public static final long DEFAULT_SYNC_ADAPTER_TIMEOUT = 10 * ONE_MINUTE;
+        public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT = 10 * ONE_MINUTE;
+        public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT = 4 * ONE_HOUR;
+        public static final long DEFAULT_EXEMPTED_SYNC_START_TIMEOUT = 10 * ONE_MINUTE;
+        public static final long DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT = 10 * ONE_MINUTE;
+        public static final long DEFAULT_STABLE_CHARGING_THRESHOLD = 10 * ONE_MINUTE;
+        public static final long DEFAULT_INITIAL_FOREGROUND_SERVICE_START_TIMEOUT = 30 * ONE_MINUTE;
+
+        private final KeyValueListParser mParser = new KeyValueListParser(',');
+
+        SettingsObserver(Handler handler) {
+            super(handler);
+        }
+
+        void registerObserver() {
+            final ContentResolver cr = mContext.getContentResolver();
+            cr.registerContentObserver(Global.getUriFor(Global.APP_IDLE_CONSTANTS), false, this);
+            cr.registerContentObserver(Global.getUriFor(Global.APP_STANDBY_ENABLED), false, this);
+            cr.registerContentObserver(Global.getUriFor(Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED),
+                    false, this);
+        }
+
+        @Override
+        public void onChange(boolean selfChange) {
+            updateSettings();
+            postOneTimeCheckIdleStates();
+        }
+
+        void updateSettings() {
+            if (DEBUG) {
+                Slog.d(TAG,
+                        "appidle=" + Global.getString(mContext.getContentResolver(),
+                                Global.APP_STANDBY_ENABLED));
+                Slog.d(TAG,
+                        "adaptivebat=" + Global.getString(mContext.getContentResolver(),
+                                Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED));
+                Slog.d(TAG, "appidleconstants=" + Global.getString(
+                        mContext.getContentResolver(),
+                        Global.APP_IDLE_CONSTANTS));
+            }
+
+            // Look at global settings for this.
+            // TODO: Maybe apply different thresholds for different users.
+            try {
+                mParser.setString(mInjector.getAppIdleSettings());
+            } catch (IllegalArgumentException e) {
+                Slog.e(TAG, "Bad value for app idle settings: " + e.getMessage());
+                // fallthrough, mParser is empty and all defaults will be returned.
+            }
+
+            synchronized (mAppIdleLock) {
+
+                // Default: 24 hours between paroles
+                mAppIdleParoleIntervalMillis = mParser.getDurationMillis(KEY_PAROLE_INTERVAL,
+                        COMPRESS_TIME ? ONE_MINUTE * 10 : 24 * 60 * ONE_MINUTE);
+
+                // Default: 2 hours to wait on network
+                mAppIdleParoleWindowMillis = mParser.getDurationMillis(KEY_PAROLE_WINDOW,
+                        COMPRESS_TIME ? ONE_MINUTE * 2 : 2 * 60 * ONE_MINUTE);
+
+                mAppIdleParoleDurationMillis = mParser.getDurationMillis(KEY_PAROLE_DURATION,
+                        COMPRESS_TIME ? ONE_MINUTE : 10 * ONE_MINUTE); // 10 minutes
+
+                String screenThresholdsValue = mParser.getString(KEY_SCREEN_TIME_THRESHOLDS, null);
+                mAppStandbyScreenThresholds = parseLongArray(screenThresholdsValue,
+                        SCREEN_TIME_THRESHOLDS);
+
+                String elapsedThresholdsValue = mParser.getString(KEY_ELAPSED_TIME_THRESHOLDS,
+                        null);
+                mAppStandbyElapsedThresholds = parseLongArray(elapsedThresholdsValue,
+                        ELAPSED_TIME_THRESHOLDS);
+                mCheckIdleIntervalMillis = Math.min(mAppStandbyElapsedThresholds[1] / 4,
+                        COMPRESS_TIME ? ONE_MINUTE : 4 * 60 * ONE_MINUTE); // 4 hours
+                mStrongUsageTimeoutMillis = mParser.getDurationMillis(
+                        KEY_STRONG_USAGE_HOLD_DURATION,
+                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_STRONG_USAGE_TIMEOUT);
+                mNotificationSeenTimeoutMillis = mParser.getDurationMillis(
+                        KEY_NOTIFICATION_SEEN_HOLD_DURATION,
+                                COMPRESS_TIME ? 12 * ONE_MINUTE : DEFAULT_NOTIFICATION_TIMEOUT);
+                mSystemUpdateUsageTimeoutMillis = mParser.getDurationMillis(
+                        KEY_SYSTEM_UPDATE_HOLD_DURATION,
+                                COMPRESS_TIME ? 2 * ONE_MINUTE : DEFAULT_SYSTEM_UPDATE_TIMEOUT);
+                mPredictionTimeoutMillis = mParser.getDurationMillis(
+                        KEY_PREDICTION_TIMEOUT,
+                                COMPRESS_TIME ? 10 * ONE_MINUTE : DEFAULT_PREDICTION_TIMEOUT);
+                mSyncAdapterTimeoutMillis = mParser.getDurationMillis(
+                        KEY_SYNC_ADAPTER_HOLD_DURATION,
+                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_SYNC_ADAPTER_TIMEOUT);
+
+                mExemptedSyncScheduledNonDozeTimeoutMillis = mParser.getDurationMillis(
+                        KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION,
+                                COMPRESS_TIME ? (ONE_MINUTE / 2)
+                                        : DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT);
+
+                mExemptedSyncScheduledDozeTimeoutMillis = mParser.getDurationMillis(
+                        KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION,
+                                COMPRESS_TIME ? ONE_MINUTE
+                                        : DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT);
+
+                mExemptedSyncStartTimeoutMillis = mParser.getDurationMillis(
+                        KEY_EXEMPTED_SYNC_START_HOLD_DURATION,
+                                COMPRESS_TIME ? ONE_MINUTE
+                                        : DEFAULT_EXEMPTED_SYNC_START_TIMEOUT);
+
+                mUnexemptedSyncScheduledTimeoutMillis = mParser.getDurationMillis(
+                        KEY_UNEXEMPTED_SYNC_SCHEDULED_HOLD_DURATION,
+                                COMPRESS_TIME ? ONE_MINUTE
+                                        : DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT); // TODO
+
+                mSystemInteractionTimeoutMillis = mParser.getDurationMillis(
+                        KEY_SYSTEM_INTERACTION_HOLD_DURATION,
+                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_SYSTEM_INTERACTION_TIMEOUT);
+
+                mInitialForegroundServiceStartTimeoutMillis = mParser.getDurationMillis(
+                        KEY_INITIAL_FOREGROUND_SERVICE_START_HOLD_DURATION,
+                        COMPRESS_TIME ? ONE_MINUTE :
+                                DEFAULT_INITIAL_FOREGROUND_SERVICE_START_TIMEOUT);
+
+                mStableChargingThresholdMillis = mParser.getDurationMillis(
+                        KEY_STABLE_CHARGING_THRESHOLD,
+                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_STABLE_CHARGING_THRESHOLD);
+            }
+
+            // Check if app_idle_enabled has changed. Do this after getting the rest of the settings
+            // in case we need to change something based on the new values.
+            setAppIdleEnabled(mInjector.isAppIdleEnabled());
+        }
+
+        long[] parseLongArray(String values, long[] defaults) {
+            if (values == null) return defaults;
+            if (values.isEmpty()) {
+                // Reset to defaults
+                return defaults;
+            } else {
+                String[] thresholds = values.split("/");
+                if (thresholds.length == THRESHOLD_BUCKETS.length) {
+                    long[] array = new long[THRESHOLD_BUCKETS.length];
+                    for (int i = 0; i < THRESHOLD_BUCKETS.length; i++) {
+                        try {
+                            if (thresholds[i].startsWith("P") || thresholds[i].startsWith("p")) {
+                                array[i] = Duration.parse(thresholds[i]).toMillis();
+                            } else {
+                                array[i] = Long.parseLong(thresholds[i]);
+                            }
+                        } catch (NumberFormatException|DateTimeParseException e) {
+                            return defaults;
+                        }
+                    }
+                    return array;
+                } else {
+                    return defaults;
+                }
+            }
+        }
+    }
+}
diff --git a/apex/statsd/OWNERS b/apex/statsd/OWNERS
new file mode 100644
index 0000000..bed9600
--- /dev/null
+++ b/apex/statsd/OWNERS
@@ -0,0 +1,9 @@
+jeffreyhuang@google.com
+joeo@google.com
+jtnguyen@google.com
+muhammadq@google.com
+ruchirr@google.com
+singhtejinder@google.com
+tsaichristine@google.com
+yaochen@google.com
+yro@google.com
\ No newline at end of file
diff --git a/apex/statsd/service/Android.bp b/apex/statsd/service/Android.bp
new file mode 100644
index 0000000..786e8b0
--- /dev/null
+++ b/apex/statsd/service/Android.bp
@@ -0,0 +1,16 @@
+// Statsd Service jar, which will eventually be put in the statsd mainline apex.
+// statsd-service needs to be added to PRODUCT_SYSTEM_SERVER_JARS.
+// This jar will contain StatsCompanionService
+java_library {
+    name: "statsd-service",
+    installable: true,
+
+    srcs: [
+        "java/**/*.java",
+    ],
+
+    libs: [
+        "framework",
+        "services.core",
+    ],
+}
\ No newline at end of file
diff --git a/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
new file mode 100644
index 0000000..1a10753
--- /dev/null
+++ b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
@@ -0,0 +1,2762 @@
+/*
+ * 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.stats;
+
+import static android.app.AppOpsManager.OP_FLAGS_ALL_TRUSTED;
+import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
+import static android.content.pm.PermissionInfo.PROTECTION_DANGEROUS;
+import static android.os.Process.getPidsForCommands;
+import static android.os.Process.getUidForPid;
+import static android.os.storage.VolumeInfo.TYPE_PRIVATE;
+import static android.os.storage.VolumeInfo.TYPE_PUBLIC;
+
+import static com.android.internal.util.Preconditions.checkNotNull;
+import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
+import static com.android.server.stats.IonMemoryUtil.readProcessSystemIonHeapSizesFromDebugfs;
+import static com.android.server.stats.IonMemoryUtil.readSystemIonHeapSizeFromDebugfs;
+import static com.android.server.stats.ProcfsMemoryUtil.readCmdlineFromProcfs;
+import static com.android.server.stats.ProcfsMemoryUtil.readMemorySnapshotFromProcfs;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.app.ActivityManagerInternal;
+import android.app.AlarmManager;
+import android.app.AlarmManager.OnAlarmListener;
+import android.app.AppOpsManager;
+import android.app.AppOpsManager.HistoricalOps;
+import android.app.AppOpsManager.HistoricalOpsRequest;
+import android.app.AppOpsManager.HistoricalPackageOps;
+import android.app.AppOpsManager.HistoricalUidOps;
+import android.app.ProcessMemoryState;
+import android.app.StatsManager;
+import android.bluetooth.BluetoothActivityEnergyInfo;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.UidTraffic;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.IntentSender;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PermissionInfo;
+import android.content.pm.UserInfo;
+import android.hardware.biometrics.BiometricsProtoEnums;
+import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.FingerprintManager;
+import android.net.ConnectivityManager;
+import android.net.INetworkStatsService;
+import android.net.Network;
+import android.net.NetworkRequest;
+import android.net.NetworkStats;
+import android.net.wifi.IWifiManager;
+import android.net.wifi.WifiActivityEnergyInfo;
+import android.os.BatteryStats;
+import android.os.BatteryStatsInternal;
+import android.os.Binder;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.CoolingDevice;
+import android.os.Environment;
+import android.os.FileUtils;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.IStatsCompanionService;
+import android.os.IStatsManager;
+import android.os.IStoraged;
+import android.os.IThermalEventListener;
+import android.os.IThermalService;
+import android.os.Looper;
+import android.os.ParcelFileDescriptor;
+import android.os.Parcelable;
+import android.os.Process;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.StatFs;
+import android.os.StatsDimensionsValue;
+import android.os.StatsLogEventWrapper;
+import android.os.SynchronousResultReceiver;
+import android.os.SystemClock;
+import android.os.SystemProperties;
+import android.os.Temperature;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.os.storage.DiskInfo;
+import android.os.storage.StorageManager;
+import android.os.storage.VolumeInfo;
+import android.provider.Settings;
+import android.stats.storage.StorageEnums;
+import android.telephony.ModemActivityInfo;
+import android.telephony.TelephonyManager;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.util.Log;
+import android.util.Slog;
+import android.util.StatsLog;
+import android.util.proto.ProtoOutputStream;
+import android.util.proto.ProtoStream;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.app.procstats.IProcessStats;
+import com.android.internal.app.procstats.ProcessStats;
+import com.android.internal.os.BackgroundThread;
+import com.android.internal.os.BatterySipper;
+import com.android.internal.os.BatteryStatsHelper;
+import com.android.internal.os.BinderCallsStats.ExportedCallStat;
+import com.android.internal.os.KernelCpuSpeedReader;
+import com.android.internal.os.KernelCpuThreadReader;
+import com.android.internal.os.KernelCpuThreadReaderDiff;
+import com.android.internal.os.KernelCpuThreadReaderSettingsObserver;
+import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidActiveTimeReader;
+import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidClusterTimeReader;
+import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidFreqTimeReader;
+import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidUserSysTimeReader;
+import com.android.internal.os.KernelWakelockReader;
+import com.android.internal.os.KernelWakelockStats;
+import com.android.internal.os.LooperStats;
+import com.android.internal.os.PowerProfile;
+import com.android.internal.os.ProcessCpuTracker;
+import com.android.internal.os.StoragedUidIoStatsReader;
+import com.android.internal.util.DumpUtils;
+import com.android.server.BinderCallsStatsService;
+import com.android.server.LocalServices;
+import com.android.server.SystemService;
+import com.android.server.SystemServiceManager;
+import com.android.server.am.MemoryStatUtil.MemoryStat;
+import com.android.server.role.RoleManagerInternal;
+import com.android.server.stats.IonMemoryUtil.IonAllocations;
+import com.android.server.stats.ProcfsMemoryUtil.MemorySnapshot;
+import com.android.server.storage.DiskStatsFileLogger;
+import com.android.server.storage.DiskStatsLoggingService;
+
+import libcore.io.IoUtils;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * Helper service for statsd (the native stats management service in cmds/statsd/).
+ * Used for registering and receiving alarms on behalf of statsd.
+ *
+ * @hide
+ */
+public class StatsCompanionService extends IStatsCompanionService.Stub {
+    /**
+     * How long to wait on an individual subsystem to return its stats.
+     */
+    private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
+    private static final long MILLIS_IN_A_DAY = TimeUnit.DAYS.toMillis(1);
+
+    public static final String RESULT_RECEIVER_CONTROLLER_KEY = "controller_activity";
+    public static final String CONFIG_DIR = "/data/misc/stats-service";
+
+    static final String TAG = "StatsCompanionService";
+    static final boolean DEBUG = false;
+    /**
+     * Hard coded field ids of frameworks/base/cmds/statsd/src/uid_data.proto
+     * to be used in ProtoOutputStream.
+     */
+    private static final int APPLICATION_INFO_FIELD_ID = 1;
+    private static final int UID_FIELD_ID = 1;
+    private static final int VERSION_FIELD_ID = 2;
+    private static final int VERSION_STRING_FIELD_ID = 3;
+    private static final int PACKAGE_NAME_FIELD_ID = 4;
+    private static final int INSTALLER_FIELD_ID = 5;
+
+    public static final int CODE_DATA_BROADCAST = 1;
+    public static final int CODE_SUBSCRIBER_BROADCAST = 1;
+    public static final int CODE_ACTIVE_CONFIGS_BROADCAST = 1;
+    /**
+     * The last report time is provided with each intent registered to
+     * StatsManager#setFetchReportsOperation. This allows easy de-duping in the receiver if
+     * statsd is requesting the client to retrieve the same statsd data. The last report time
+     * corresponds to the last_report_elapsed_nanos that will provided in the current
+     * ConfigMetricsReport, and this timestamp also corresponds to the
+     * current_report_elapsed_nanos of the most recently obtained ConfigMetricsReport.
+     */
+    public static final String EXTRA_LAST_REPORT_TIME = "android.app.extra.LAST_REPORT_TIME";
+    public static final int DEATH_THRESHOLD = 10;
+    /**
+     * Which native processes to snapshot memory for.
+     *
+     * <p>Processes are matched by their cmdline in procfs. Example: cat /proc/pid/cmdline returns
+     * /system/bin/statsd for the stats daemon.
+     */
+    private static final String[] MEMORY_INTERESTING_NATIVE_PROCESSES = new String[]{
+            "/system/bin/statsd",  // Stats daemon.
+            "/system/bin/surfaceflinger",
+            "/system/bin/apexd",  // APEX daemon.
+            "/system/bin/audioserver",
+            "/system/bin/cameraserver",
+            "/system/bin/drmserver",
+            "/system/bin/healthd",
+            "/system/bin/incidentd",
+            "/system/bin/installd",
+            "/system/bin/lmkd",  // Low memory killer daemon.
+            "/system/bin/logd",
+            "media.codec",
+            "media.extractor",
+            "media.metrics",
+            "/system/bin/mediadrmserver",
+            "/system/bin/mediaserver",
+            "/system/bin/performanced",
+            "/system/bin/tombstoned",
+            "/system/bin/traced",  // Perfetto.
+            "/system/bin/traced_probes",  // Perfetto.
+            "webview_zygote",
+            "zygote",
+            "zygote64",
+    };
+    /**
+     * Lowest available uid for apps.
+     *
+     * <p>Used to quickly discard memory snapshots of the zygote forks from native process
+     * measurements.
+     */
+    private static final int MIN_APP_UID = 10_000;
+
+    private static final int CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES = 8;
+
+    static final class CompanionHandler extends Handler {
+        CompanionHandler(Looper looper) {
+            super(looper);
+        }
+    }
+
+    private final Context mContext;
+    private final AlarmManager mAlarmManager;
+    private final INetworkStatsService mNetworkStatsService;
+    @GuardedBy("sStatsdLock")
+    private static IStatsManager sStatsd;
+    private static final Object sStatsdLock = new Object();
+
+    private final OnAlarmListener mAnomalyAlarmListener = new AnomalyAlarmListener();
+    private final OnAlarmListener mPullingAlarmListener = new PullingAlarmListener();
+    private final OnAlarmListener mPeriodicAlarmListener = new PeriodicAlarmListener();
+    private final BroadcastReceiver mAppUpdateReceiver;
+    private final BroadcastReceiver mUserUpdateReceiver;
+    private final ShutdownEventReceiver mShutdownEventReceiver;
+    private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
+    private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
+    private IWifiManager mWifiManager = null;
+    private TelephonyManager mTelephony = null;
+    @GuardedBy("sStatsdLock")
+    private final HashSet<Long> mDeathTimeMillis = new HashSet<>();
+    @GuardedBy("sStatsdLock")
+    private final HashMap<Long, String> mDeletedFiles = new HashMap<>();
+    private final CompanionHandler mHandler;
+
+    // Disables throttler on CPU time readers.
+    private KernelCpuUidUserSysTimeReader mCpuUidUserSysTimeReader =
+            new KernelCpuUidUserSysTimeReader(false);
+    private KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
+    private KernelCpuUidFreqTimeReader mCpuUidFreqTimeReader =
+            new KernelCpuUidFreqTimeReader(false);
+    private KernelCpuUidActiveTimeReader mCpuUidActiveTimeReader =
+            new KernelCpuUidActiveTimeReader(false);
+    private KernelCpuUidClusterTimeReader mCpuUidClusterTimeReader =
+            new KernelCpuUidClusterTimeReader(false);
+    private StoragedUidIoStatsReader mStoragedUidIoStatsReader =
+            new StoragedUidIoStatsReader();
+    @Nullable
+    private final KernelCpuThreadReaderDiff mKernelCpuThreadReader;
+
+    private long mDebugElapsedClockPreviousValue = 0;
+    private long mDebugElapsedClockPullCount = 0;
+    private long mDebugFailingElapsedClockPreviousValue = 0;
+    private long mDebugFailingElapsedClockPullCount = 0;
+    private BatteryStatsHelper mBatteryStatsHelper = null;
+    private static final int MAX_BATTERY_STATS_HELPER_FREQUENCY_MS = 1000;
+    private long mBatteryStatsHelperTimestampMs = -MAX_BATTERY_STATS_HELPER_FREQUENCY_MS;
+
+    private static IThermalService sThermalService;
+    private File mBaseDir =
+            new File(SystemServiceManager.ensureSystemDir(), "stats_companion");
+    @GuardedBy("this")
+    ProcessCpuTracker mProcessCpuTracker = null;
+
+    public StatsCompanionService(Context context) {
+        super();
+        mContext = context;
+        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
+        mNetworkStatsService = INetworkStatsService.Stub.asInterface(
+              ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
+        mBaseDir.mkdirs();
+        mAppUpdateReceiver = new AppUpdateReceiver();
+        mUserUpdateReceiver = new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                synchronized (sStatsdLock) {
+                    sStatsd = fetchStatsdService();
+                    if (sStatsd == null) {
+                        Slog.w(TAG, "Could not access statsd for UserUpdateReceiver");
+                        return;
+                    }
+                    try {
+                        // Pull the latest state of UID->app name, version mapping.
+                        // Needed since the new user basically has a version of every app.
+                        informAllUidsLocked(context);
+                    } catch (RemoteException e) {
+                        Slog.e(TAG, "Failed to inform statsd latest update of all apps", e);
+                        forgetEverythingLocked();
+                    }
+                }
+            }
+        };
+        mShutdownEventReceiver = new ShutdownEventReceiver();
+        if (DEBUG) Slog.d(TAG, "Registered receiver for ACTION_PACKAGE_REPLACED and ADDED.");
+        PowerProfile powerProfile = new PowerProfile(context);
+        final int numClusters = powerProfile.getNumCpuClusters();
+        mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
+        int firstCpuOfCluster = 0;
+        for (int i = 0; i < numClusters; i++) {
+            final int numSpeedSteps = powerProfile.getNumSpeedStepsInCpuCluster(i);
+            mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
+                    numSpeedSteps);
+            firstCpuOfCluster += powerProfile.getNumCoresInCpuCluster(i);
+        }
+
+        // Enable push notifications of throttling from vendor thermal
+        // management subsystem via thermalservice.
+        IBinder b = ServiceManager.getService("thermalservice");
+
+        if (b != null) {
+            sThermalService = IThermalService.Stub.asInterface(b);
+            try {
+                sThermalService.registerThermalEventListener(
+                        new ThermalEventListener());
+                Slog.i(TAG, "register thermal listener successfully");
+            } catch (RemoteException e) {
+                // Should never happen.
+                Slog.e(TAG, "register thermal listener error");
+            }
+        } else {
+            Slog.e(TAG, "cannot find thermalservice, no throttling push notifications");
+        }
+
+        // Default NetworkRequest should cover all transport types.
+        final NetworkRequest request = new NetworkRequest.Builder().build();
+        final ConnectivityManager connectivityManager =
+                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
+        connectivityManager.registerNetworkCallback(request, new ConnectivityStatsCallback());
+
+        HandlerThread handlerThread = new HandlerThread(TAG);
+        handlerThread.start();
+        mHandler = new CompanionHandler(handlerThread.getLooper());
+
+        mKernelCpuThreadReader =
+                KernelCpuThreadReaderSettingsObserver.getSettingsModifiedReader(mContext);
+    }
+
+    @Override
+    public void sendDataBroadcast(IBinder intentSenderBinder, long lastReportTimeNs) {
+        enforceCallingPermission();
+        IntentSender intentSender = new IntentSender(intentSenderBinder);
+        Intent intent = new Intent();
+        intent.putExtra(EXTRA_LAST_REPORT_TIME, lastReportTimeNs);
+        try {
+            intentSender.sendIntent(mContext, CODE_DATA_BROADCAST, intent, null, null);
+        } catch (IntentSender.SendIntentException e) {
+            Slog.w(TAG, "Unable to send using IntentSender");
+        }
+    }
+
+    @Override
+    public void sendActiveConfigsChangedBroadcast(IBinder intentSenderBinder, long[] configIds) {
+        enforceCallingPermission();
+        IntentSender intentSender = new IntentSender(intentSenderBinder);
+        Intent intent = new Intent();
+        intent.putExtra(StatsManager.EXTRA_STATS_ACTIVE_CONFIG_KEYS, configIds);
+        try {
+            intentSender.sendIntent(mContext, CODE_ACTIVE_CONFIGS_BROADCAST, intent, null, null);
+            if (DEBUG) {
+                Slog.d(TAG, "Sent broadcast with config ids " + Arrays.toString(configIds));
+            }
+        } catch (IntentSender.SendIntentException e) {
+            Slog.w(TAG, "Unable to send active configs changed broadcast using IntentSender");
+        }
+    }
+
+    @Override
+    public void sendSubscriberBroadcast(IBinder intentSenderBinder, long configUid, long configKey,
+            long subscriptionId, long subscriptionRuleId, String[] cookies,
+            StatsDimensionsValue dimensionsValue) {
+        enforceCallingPermission();
+        IntentSender intentSender = new IntentSender(intentSenderBinder);
+        Intent intent =
+                new Intent()
+                        .putExtra(StatsManager.EXTRA_STATS_CONFIG_UID, configUid)
+                        .putExtra(StatsManager.EXTRA_STATS_CONFIG_KEY, configKey)
+                        .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_ID, subscriptionId)
+                        .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_RULE_ID, subscriptionRuleId)
+                        .putExtra(StatsManager.EXTRA_STATS_DIMENSIONS_VALUE, dimensionsValue);
+
+        ArrayList<String> cookieList = new ArrayList<>(cookies.length);
+        for (String cookie : cookies) {
+            cookieList.add(cookie);
+        }
+        intent.putStringArrayListExtra(
+                StatsManager.EXTRA_STATS_BROADCAST_SUBSCRIBER_COOKIES, cookieList);
+
+        if (DEBUG) {
+            Slog.d(TAG,
+                    String.format("Statsd sendSubscriberBroadcast with params {%d %d %d %d %s %s}",
+                            configUid, configKey, subscriptionId, subscriptionRuleId,
+                            Arrays.toString(cookies),
+                            dimensionsValue));
+        }
+        try {
+            intentSender.sendIntent(mContext, CODE_SUBSCRIBER_BROADCAST, intent, null, null);
+        } catch (IntentSender.SendIntentException e) {
+            Slog.w(TAG,
+                    "Unable to send using IntentSender from uid " + configUid
+                            + "; presumably it had been cancelled.");
+        }
+    }
+
+    private final static int[] toIntArray(List<Integer> list) {
+        int[] ret = new int[list.size()];
+        for (int i = 0; i < ret.length; i++) {
+            ret[i] = list.get(i);
+        }
+        return ret;
+    }
+
+    private final static long[] toLongArray(List<Long> list) {
+        long[] ret = new long[list.size()];
+        for (int i = 0; i < ret.length; i++) {
+            ret[i] = list.get(i);
+        }
+        return ret;
+    }
+
+    // Assumes that sStatsdLock is held.
+    @GuardedBy("sStatsdLock")
+    private final void informAllUidsLocked(Context context) throws RemoteException {
+        UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
+        PackageManager pm = context.getPackageManager();
+        final List<UserInfo> users = um.getUsers(true);
+        if (DEBUG) {
+            Slog.d(TAG, "Iterating over " + users.size() + " profiles.");
+        }
+
+        ParcelFileDescriptor[] fds;
+        try {
+            fds = ParcelFileDescriptor.createPipe();
+        } catch (IOException e) {
+            Slog.e(TAG, "Failed to create a pipe to send uid map data.", e);
+            return;
+        }
+        sStatsd.informAllUidData(fds[0]);
+        try {
+            fds[0].close();
+        } catch (IOException e) {
+            Slog.e(TAG, "Failed to close the read side of the pipe.", e);
+        }
+        final ParcelFileDescriptor writeFd = fds[1];
+        BackgroundThread.getHandler().post(() -> {
+            FileOutputStream fout = new ParcelFileDescriptor.AutoCloseOutputStream(writeFd);
+            try {
+                ProtoOutputStream output = new ProtoOutputStream(fout);
+                int numRecords = 0;
+                // Add in all the apps for every user/profile.
+                for (UserInfo profile : users) {
+                    List<PackageInfo> pi =
+                            pm.getInstalledPackagesAsUser(PackageManager.MATCH_KNOWN_PACKAGES,
+                                    profile.id);
+                    for (int j = 0; j < pi.size(); j++) {
+                        if (pi.get(j).applicationInfo != null) {
+                            String installer;
+                            try {
+                                installer = pm.getInstallerPackageName(pi.get(j).packageName);
+                            } catch (IllegalArgumentException e) {
+                                installer = "";
+                            }
+                            long applicationInfoToken =
+                                    output.start(ProtoStream.FIELD_TYPE_MESSAGE
+                                            | ProtoStream.FIELD_COUNT_REPEATED
+                                                    | APPLICATION_INFO_FIELD_ID);
+                            output.write(ProtoStream.FIELD_TYPE_INT32
+                                    | ProtoStream.FIELD_COUNT_SINGLE | UID_FIELD_ID,
+                                            pi.get(j).applicationInfo.uid);
+                            output.write(ProtoStream.FIELD_TYPE_INT64
+                                    | ProtoStream.FIELD_COUNT_SINGLE
+                                            | VERSION_FIELD_ID, pi.get(j).getLongVersionCode());
+                            output.write(ProtoStream.FIELD_TYPE_STRING
+                                    | ProtoStream.FIELD_COUNT_SINGLE | VERSION_STRING_FIELD_ID,
+                                            pi.get(j).versionName);
+                            output.write(ProtoStream.FIELD_TYPE_STRING
+                                    | ProtoStream.FIELD_COUNT_SINGLE
+                                            | PACKAGE_NAME_FIELD_ID, pi.get(j).packageName);
+                            output.write(ProtoStream.FIELD_TYPE_STRING
+                                    | ProtoStream.FIELD_COUNT_SINGLE
+                                            | INSTALLER_FIELD_ID,
+                                                    installer == null ? "" : installer);
+                            numRecords++;
+                            output.end(applicationInfoToken);
+                        }
+                    }
+                }
+                output.flush();
+                if (DEBUG) {
+                    Slog.d(TAG, "Sent data for " + numRecords + " apps");
+                }
+            } finally {
+                IoUtils.closeQuietly(fout);
+            }
+        });
+    }
+
+    private final static class AppUpdateReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            /**
+             * App updates actually consist of REMOVE, ADD, and then REPLACE broadcasts. To avoid
+             * waste, we ignore the REMOVE and ADD broadcasts that contain the replacing flag.
+             * If we can't find the value for EXTRA_REPLACING, we default to false.
+             */
+            if (!intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)
+                    && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
+                return; // Keep only replacing or normal add and remove.
+            }
+            if (DEBUG) Slog.d(TAG, "StatsCompanionService noticed an app was updated.");
+            synchronized (sStatsdLock) {
+                if (sStatsd == null) {
+                    Slog.w(TAG, "Could not access statsd to inform it of an app update");
+                    return;
+                }
+                try {
+                    if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
+                        Bundle b = intent.getExtras();
+                        int uid = b.getInt(Intent.EXTRA_UID);
+                        boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
+                        if (!replacing) {
+                            // Don't bother sending an update if we're right about to get another
+                            // intent for the new version that's added.
+                            PackageManager pm = context.getPackageManager();
+                            String app = intent.getData().getSchemeSpecificPart();
+                            sStatsd.informOnePackageRemoved(app, uid);
+                        }
+                    } else {
+                        PackageManager pm = context.getPackageManager();
+                        Bundle b = intent.getExtras();
+                        int uid = b.getInt(Intent.EXTRA_UID);
+                        String app = intent.getData().getSchemeSpecificPart();
+                        PackageInfo pi = pm.getPackageInfo(app, PackageManager.MATCH_ANY_USER);
+                        String installer;
+                        try {
+                            installer = pm.getInstallerPackageName(app);
+                        } catch (IllegalArgumentException e) {
+                            installer = "";
+                        }
+                        sStatsd.informOnePackage(app, uid, pi.getLongVersionCode(), pi.versionName,
+                                installer == null ? "" : installer);
+                    }
+                } catch (Exception e) {
+                    Slog.w(TAG, "Failed to inform statsd of an app update", e);
+                }
+            }
+        }
+    }
+
+    public final static class AnomalyAlarmListener implements OnAlarmListener {
+        @Override
+        public void onAlarm() {
+            Slog.i(TAG, "StatsCompanionService believes an anomaly has occurred at time "
+                    + System.currentTimeMillis() + "ms.");
+            synchronized (sStatsdLock) {
+                if (sStatsd == null) {
+                    Slog.w(TAG, "Could not access statsd to inform it of anomaly alarm firing");
+                    return;
+                }
+                try {
+                    // Two-way call to statsd to retain AlarmManager wakelock
+                    sStatsd.informAnomalyAlarmFired();
+                } catch (RemoteException e) {
+                    Slog.w(TAG, "Failed to inform statsd of anomaly alarm firing", e);
+                }
+            }
+            // AlarmManager releases its own wakelock here.
+        }
+    }
+
+    public final static class PullingAlarmListener implements OnAlarmListener {
+        @Override
+        public void onAlarm() {
+            if (DEBUG) {
+                Slog.d(TAG, "Time to poll something.");
+            }
+            synchronized (sStatsdLock) {
+                if (sStatsd == null) {
+                    Slog.w(TAG, "Could not access statsd to inform it of pulling alarm firing.");
+                    return;
+                }
+                try {
+                    // Two-way call to statsd to retain AlarmManager wakelock
+                    sStatsd.informPollAlarmFired();
+                } catch (RemoteException e) {
+                    Slog.w(TAG, "Failed to inform statsd of pulling alarm firing.", e);
+                }
+            }
+        }
+    }
+
+    public final static class PeriodicAlarmListener implements OnAlarmListener {
+        @Override
+        public void onAlarm() {
+            if (DEBUG) {
+                Slog.d(TAG, "Time to trigger periodic alarm.");
+            }
+            synchronized (sStatsdLock) {
+                if (sStatsd == null) {
+                    Slog.w(TAG, "Could not access statsd to inform it of periodic alarm firing.");
+                    return;
+                }
+                try {
+                    // Two-way call to statsd to retain AlarmManager wakelock
+                    sStatsd.informAlarmForSubscriberTriggeringFired();
+                } catch (RemoteException e) {
+                    Slog.w(TAG, "Failed to inform statsd of periodic alarm firing.", e);
+                }
+            }
+            // AlarmManager releases its own wakelock here.
+        }
+    }
+
+    public final static class ShutdownEventReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            /**
+             * Skip immediately if intent is not relevant to device shutdown.
+             */
+            if (!intent.getAction().equals(Intent.ACTION_REBOOT)
+                    && !(intent.getAction().equals(Intent.ACTION_SHUTDOWN)
+                    && (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0)) {
+                return;
+            }
+
+            Slog.i(TAG, "StatsCompanionService noticed a shutdown.");
+            synchronized (sStatsdLock) {
+                if (sStatsd == null) {
+                    Slog.w(TAG, "Could not access statsd to inform it of a shutdown event.");
+                    return;
+                }
+                try {
+                    sStatsd.informDeviceShutdown();
+                } catch (Exception e) {
+                    Slog.w(TAG, "Failed to inform statsd of a shutdown event.", e);
+                }
+            }
+        }
+    }
+
+    @Override // Binder call
+    public void setAnomalyAlarm(long timestampMs) {
+        enforceCallingPermission();
+        if (DEBUG) Slog.d(TAG, "Setting anomaly alarm for " + timestampMs);
+        final long callingToken = Binder.clearCallingIdentity();
+        try {
+            // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
+            // only fire when it awakens.
+            // AlarmManager will automatically cancel any previous mAnomalyAlarmListener alarm.
+            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".anomaly",
+                    mAnomalyAlarmListener, mHandler);
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    @Override // Binder call
+    public void cancelAnomalyAlarm() {
+        enforceCallingPermission();
+        if (DEBUG) Slog.d(TAG, "Cancelling anomaly alarm");
+        final long callingToken = Binder.clearCallingIdentity();
+        try {
+            mAlarmManager.cancel(mAnomalyAlarmListener);
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    @Override // Binder call
+    public void setAlarmForSubscriberTriggering(long timestampMs) {
+        enforceCallingPermission();
+        if (DEBUG) {
+            Slog.d(TAG,
+                    "Setting periodic alarm in about " + (timestampMs
+                            - SystemClock.elapsedRealtime()));
+        }
+        final long callingToken = Binder.clearCallingIdentity();
+        try {
+            // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
+            // only fire when it awakens.
+            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".periodic",
+                    mPeriodicAlarmListener, mHandler);
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    @Override // Binder call
+    public void cancelAlarmForSubscriberTriggering() {
+        enforceCallingPermission();
+        if (DEBUG) {
+            Slog.d(TAG, "Cancelling periodic alarm");
+        }
+        final long callingToken = Binder.clearCallingIdentity();
+        try {
+            mAlarmManager.cancel(mPeriodicAlarmListener);
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    @Override // Binder call
+    public void setPullingAlarm(long nextPullTimeMs) {
+        enforceCallingPermission();
+        if (DEBUG) {
+            Slog.d(TAG, "Setting pulling alarm in about "
+                    + (nextPullTimeMs - SystemClock.elapsedRealtime()));
+        }
+        final long callingToken = Binder.clearCallingIdentity();
+        try {
+            // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
+            // only fire when it awakens.
+            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, nextPullTimeMs, TAG + ".pull",
+                    mPullingAlarmListener, mHandler);
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    @Override // Binder call
+    public void cancelPullingAlarm() {
+        enforceCallingPermission();
+        if (DEBUG) {
+            Slog.d(TAG, "Cancelling pulling alarm");
+        }
+        final long callingToken = Binder.clearCallingIdentity();
+        try {
+            mAlarmManager.cancel(mPullingAlarmListener);
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    private void addNetworkStats(
+            int tag, List<StatsLogEventWrapper> ret, NetworkStats stats, boolean withFGBG) {
+        int size = stats.size();
+        long elapsedNanos = SystemClock.elapsedRealtimeNanos();
+        long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
+        NetworkStats.Entry entry = new NetworkStats.Entry(); // For recycling
+        for (int j = 0; j < size; j++) {
+            stats.getValues(j, entry);
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tag, elapsedNanos, wallClockNanos);
+            e.writeInt(entry.uid);
+            if (withFGBG) {
+                e.writeInt(entry.set);
+            }
+            e.writeLong(entry.rxBytes);
+            e.writeLong(entry.rxPackets);
+            e.writeLong(entry.txBytes);
+            e.writeLong(entry.txPackets);
+            ret.add(e);
+        }
+    }
+
+    /**
+     * Allows rollups per UID but keeping the set (foreground/background) slicing.
+     * Adapted from groupedByUid in frameworks/base/core/java/android/net/NetworkStats.java
+     */
+    private NetworkStats rollupNetworkStatsByFGBG(NetworkStats stats) {
+        final NetworkStats ret = new NetworkStats(stats.getElapsedRealtime(), 1);
+
+        final NetworkStats.Entry entry = new NetworkStats.Entry();
+        entry.iface = NetworkStats.IFACE_ALL;
+        entry.tag = NetworkStats.TAG_NONE;
+        entry.metered = NetworkStats.METERED_ALL;
+        entry.roaming = NetworkStats.ROAMING_ALL;
+
+        int size = stats.size();
+        NetworkStats.Entry recycle = new NetworkStats.Entry(); // Used for retrieving values
+        for (int i = 0; i < size; i++) {
+            stats.getValues(i, recycle);
+
+            // Skip specific tags, since already counted in TAG_NONE
+            if (recycle.tag != NetworkStats.TAG_NONE) continue;
+
+            entry.set = recycle.set; // Allows slicing by background/foreground
+            entry.uid = recycle.uid;
+            entry.rxBytes = recycle.rxBytes;
+            entry.rxPackets = recycle.rxPackets;
+            entry.txBytes = recycle.txBytes;
+            entry.txPackets = recycle.txPackets;
+            // Operations purposefully omitted since we don't use them for statsd.
+            ret.combineValues(entry);
+        }
+        return ret;
+    }
+
+    /**
+     * Helper method to extract the Parcelable controller info from a
+     * SynchronousResultReceiver.
+     */
+    private static <T extends Parcelable> T awaitControllerInfo(
+            @Nullable SynchronousResultReceiver receiver) {
+        if (receiver == null) {
+            return null;
+        }
+
+        try {
+            final SynchronousResultReceiver.Result result =
+                    receiver.awaitResult(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS);
+            if (result.bundle != null) {
+                // This is the final destination for the Bundle.
+                result.bundle.setDefusable(true);
+
+                final T data = result.bundle.getParcelable(
+                        RESULT_RECEIVER_CONTROLLER_KEY);
+                if (data != null) {
+                    return data;
+                }
+            }
+            Slog.e(TAG, "no controller energy info supplied for " + receiver.getName());
+        } catch (TimeoutException e) {
+            Slog.w(TAG, "timeout reading " + receiver.getName() + " stats");
+        }
+        return null;
+    }
+
+    private void pullKernelWakelock(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        final KernelWakelockStats wakelockStats =
+                mKernelWakelockReader.readKernelWakelockStats(mTmpWakelockStats);
+        for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
+            String name = ent.getKey();
+            KernelWakelockStats.Entry kws = ent.getValue();
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeString(name);
+            e.writeInt(kws.mCount);
+            e.writeInt(kws.mVersion);
+            e.writeLong(kws.mTotalTime);
+            pulledData.add(e);
+        }
+    }
+
+    private void pullWifiBytesTransfer(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        try {
+            // TODO: Consider caching the following call to get BatteryStatsInternal.
+            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
+            String[] ifaces = bs.getWifiIfaces();
+            if (ifaces.length == 0) {
+                return;
+            }
+            if (mNetworkStatsService == null) {
+                Slog.e(TAG, "NetworkStats Service is not available!");
+                return;
+            }
+            // Combine all the metrics per Uid into one record.
+            NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
+            addNetworkStats(tagId, pulledData, stats, false);
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Pulling netstats for wifi bytes has error", e);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    private void pullWifiBytesTransferByFgBg(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        try {
+            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
+            String[] ifaces = bs.getWifiIfaces();
+            if (ifaces.length == 0) {
+                return;
+            }
+            if (mNetworkStatsService == null) {
+                Slog.e(TAG, "NetworkStats Service is not available!");
+                return;
+            }
+            NetworkStats stats = rollupNetworkStatsByFGBG(
+                    mNetworkStatsService.getDetailedUidStats(ifaces));
+            addNetworkStats(tagId, pulledData, stats, true);
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Pulling netstats for wifi bytes w/ fg/bg has error", e);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    private void pullMobileBytesTransfer(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        try {
+            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
+            String[] ifaces = bs.getMobileIfaces();
+            if (ifaces.length == 0) {
+                return;
+            }
+            if (mNetworkStatsService == null) {
+                Slog.e(TAG, "NetworkStats Service is not available!");
+                return;
+            }
+            // Combine all the metrics per Uid into one record.
+            NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
+            addNetworkStats(tagId, pulledData, stats, false);
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Pulling netstats for mobile bytes has error", e);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    private void pullBluetoothBytesTransfer(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        BluetoothActivityEnergyInfo info = fetchBluetoothData();
+        if (info.getUidTraffic() != null) {
+            for (UidTraffic traffic : info.getUidTraffic()) {
+                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                        wallClockNanos);
+                e.writeInt(traffic.getUid());
+                e.writeLong(traffic.getRxBytes());
+                e.writeLong(traffic.getTxBytes());
+                pulledData.add(e);
+            }
+        }
+    }
+
+    private void pullMobileBytesTransferByFgBg(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        try {
+            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
+            String[] ifaces = bs.getMobileIfaces();
+            if (ifaces.length == 0) {
+                return;
+            }
+            if (mNetworkStatsService == null) {
+                Slog.e(TAG, "NetworkStats Service is not available!");
+                return;
+            }
+            NetworkStats stats = rollupNetworkStatsByFGBG(
+                    mNetworkStatsService.getDetailedUidStats(ifaces));
+            addNetworkStats(tagId, pulledData, stats, true);
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Pulling netstats for mobile bytes w/ fg/bg has error", e);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    private void pullCpuTimePerFreq(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
+            long[] clusterTimeMs = mKernelCpuSpeedReaders[cluster].readAbsolute();
+            if (clusterTimeMs != null) {
+                for (int speed = clusterTimeMs.length - 1; speed >= 0; --speed) {
+                    StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                            wallClockNanos);
+                    e.writeInt(cluster);
+                    e.writeInt(speed);
+                    e.writeLong(clusterTimeMs[speed]);
+                    pulledData.add(e);
+                }
+            }
+        }
+    }
+
+    private void pullKernelUidCpuTime(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        mCpuUidUserSysTimeReader.readAbsolute((uid, timesUs) -> {
+            long userTimeUs = timesUs[0], systemTimeUs = timesUs[1];
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(uid);
+            e.writeLong(userTimeUs);
+            e.writeLong(systemTimeUs);
+            pulledData.add(e);
+        });
+    }
+
+    private void pullKernelUidCpuFreqTime(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        mCpuUidFreqTimeReader.readAbsolute((uid, cpuFreqTimeMs) -> {
+            for (int freqIndex = 0; freqIndex < cpuFreqTimeMs.length; ++freqIndex) {
+                if (cpuFreqTimeMs[freqIndex] != 0) {
+                    StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                            wallClockNanos);
+                    e.writeInt(uid);
+                    e.writeInt(freqIndex);
+                    e.writeLong(cpuFreqTimeMs[freqIndex]);
+                    pulledData.add(e);
+                }
+            }
+        });
+    }
+
+    private void pullKernelUidCpuClusterTime(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        mCpuUidClusterTimeReader.readAbsolute((uid, cpuClusterTimesMs) -> {
+            for (int i = 0; i < cpuClusterTimesMs.length; i++) {
+                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                        wallClockNanos);
+                e.writeInt(uid);
+                e.writeInt(i);
+                e.writeLong(cpuClusterTimesMs[i]);
+                pulledData.add(e);
+            }
+        });
+    }
+
+    private void pullKernelUidCpuActiveTime(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        mCpuUidActiveTimeReader.readAbsolute((uid, cpuActiveTimesMs) -> {
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(uid);
+            e.writeLong((long) cpuActiveTimesMs);
+            pulledData.add(e);
+        });
+    }
+
+    private void pullWifiActivityInfo(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        synchronized (this) {
+            if (mWifiManager == null) {
+                mWifiManager =
+                        IWifiManager.Stub.asInterface(
+                                ServiceManager.getService(Context.WIFI_SERVICE));
+            }
+        }
+        if (mWifiManager != null) {
+            try {
+                SynchronousResultReceiver wifiReceiver = new SynchronousResultReceiver("wifi");
+                mWifiManager.requestActivityInfo(wifiReceiver);
+                final WifiActivityEnergyInfo wifiInfo = awaitControllerInfo(wifiReceiver);
+                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                        wallClockNanos);
+                e.writeLong(wifiInfo.getTimeStamp());
+                e.writeInt(wifiInfo.getStackState());
+                e.writeLong(wifiInfo.getControllerTxTimeMillis());
+                e.writeLong(wifiInfo.getControllerRxTimeMillis());
+                e.writeLong(wifiInfo.getControllerIdleTimeMillis());
+                e.writeLong(wifiInfo.getControllerEnergyUsed());
+                pulledData.add(e);
+            } catch (RemoteException e) {
+                Slog.e(TAG,
+                        "Pulling wifiManager for wifi controller activity energy info has error",
+                        e);
+            } finally {
+                Binder.restoreCallingIdentity(token);
+            }
+        }
+    }
+
+    private void pullModemActivityInfo(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        synchronized (this) {
+            if (mTelephony == null) {
+                mTelephony = TelephonyManager.from(mContext);
+            }
+        }
+        if (mTelephony != null) {
+            SynchronousResultReceiver modemReceiver = new SynchronousResultReceiver("telephony");
+            mTelephony.requestModemActivityInfo(modemReceiver);
+            final ModemActivityInfo modemInfo = awaitControllerInfo(modemReceiver);
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeLong(modemInfo.getTimestamp());
+            e.writeLong(modemInfo.getSleepTimeMillis());
+            e.writeLong(modemInfo.getIdleTimeMillis());
+            e.writeLong(modemInfo.getTransmitPowerInfo().get(0).getTimeInMillis());
+            e.writeLong(modemInfo.getTransmitPowerInfo().get(1).getTimeInMillis());
+            e.writeLong(modemInfo.getTransmitPowerInfo().get(2).getTimeInMillis());
+            e.writeLong(modemInfo.getTransmitPowerInfo().get(3).getTimeInMillis());
+            e.writeLong(modemInfo.getTransmitPowerInfo().get(4).getTimeInMillis());
+            e.writeLong(modemInfo.getReceiveTimeMillis());
+            pulledData.add(e);
+        }
+    }
+
+    private void pullBluetoothActivityInfo(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        BluetoothActivityEnergyInfo info = fetchBluetoothData();
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeLong(info.getTimeStamp());
+        e.writeInt(info.getBluetoothStackState());
+        e.writeLong(info.getControllerTxTimeMillis());
+        e.writeLong(info.getControllerRxTimeMillis());
+        e.writeLong(info.getControllerIdleTimeMillis());
+        e.writeLong(info.getControllerEnergyUsed());
+        pulledData.add(e);
+    }
+
+    private synchronized BluetoothActivityEnergyInfo fetchBluetoothData() {
+        final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
+        if (adapter != null) {
+            SynchronousResultReceiver bluetoothReceiver = new SynchronousResultReceiver(
+                    "bluetooth");
+            adapter.requestControllerActivityEnergyInfo(bluetoothReceiver);
+            return awaitControllerInfo(bluetoothReceiver);
+        } else {
+            Slog.e(TAG, "Failed to get bluetooth adapter!");
+            return null;
+        }
+    }
+
+    private void pullSystemElapsedRealtime(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeLong(SystemClock.elapsedRealtime());
+        pulledData.add(e);
+    }
+
+    private void pullSystemUpTime(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeLong(SystemClock.uptimeMillis());
+        pulledData.add(e);
+    }
+
+    private void pullProcessMemoryState(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        List<ProcessMemoryState> processMemoryStates =
+                LocalServices.getService(
+                        ActivityManagerInternal.class).getMemoryStateForProcesses();
+        for (ProcessMemoryState processMemoryState : processMemoryStates) {
+            final MemoryStat memoryStat = readMemoryStatFromFilesystem(processMemoryState.uid,
+                    processMemoryState.pid);
+            if (memoryStat == null) {
+                continue;
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(processMemoryState.uid);
+            e.writeString(processMemoryState.processName);
+            e.writeInt(processMemoryState.oomScore);
+            e.writeLong(memoryStat.pgfault);
+            e.writeLong(memoryStat.pgmajfault);
+            e.writeLong(memoryStat.rssInBytes);
+            e.writeLong(memoryStat.cacheInBytes);
+            e.writeLong(memoryStat.swapInBytes);
+            e.writeLong(-1);  // unused
+            e.writeLong(-1);  // unused
+            e.writeInt(-1);  // unsed
+            pulledData.add(e);
+        }
+    }
+
+    private void pullProcessMemoryHighWaterMark(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        List<ProcessMemoryState> managedProcessList =
+                LocalServices.getService(
+                        ActivityManagerInternal.class).getMemoryStateForProcesses();
+        for (ProcessMemoryState managedProcess : managedProcessList) {
+            final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(managedProcess.pid);
+            if (snapshot == null) {
+                continue;
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(managedProcess.uid);
+            e.writeString(managedProcess.processName);
+            // RSS high-water mark in bytes.
+            e.writeLong((long) snapshot.rssHighWaterMarkInKilobytes * 1024L);
+            e.writeInt(snapshot.rssHighWaterMarkInKilobytes);
+            pulledData.add(e);
+        }
+        int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
+        for (int pid : pids) {
+            final String processName = readCmdlineFromProcfs(pid);
+            final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(pid);
+            if (snapshot == null) {
+                continue;
+            }
+            // Sometimes we get here a process that is not included in the whitelist. It comes
+            // from forking the zygote for an app. We can ignore that sample because this process
+            // is collected by ProcessMemoryState.
+            if (isAppUid(snapshot.uid)) {
+                continue;
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(snapshot.uid);
+            e.writeString(processName);
+            // RSS high-water mark in bytes.
+            e.writeLong((long) snapshot.rssHighWaterMarkInKilobytes * 1024L);
+            e.writeInt(snapshot.rssHighWaterMarkInKilobytes);
+            pulledData.add(e);
+        }
+        // Invoke rss_hwm_reset binary to reset RSS HWM counters for all processes.
+        SystemProperties.set("sys.rss_hwm_reset.on", "1");
+    }
+
+    private void pullProcessMemorySnapshot(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        List<ProcessMemoryState> managedProcessList =
+                LocalServices.getService(
+                        ActivityManagerInternal.class).getMemoryStateForProcesses();
+        for (ProcessMemoryState managedProcess : managedProcessList) {
+            final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(managedProcess.pid);
+            if (snapshot == null) {
+                continue;
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(managedProcess.uid);
+            e.writeString(managedProcess.processName);
+            e.writeInt(managedProcess.pid);
+            e.writeInt(managedProcess.oomScore);
+            e.writeInt(snapshot.rssInKilobytes);
+            e.writeInt(snapshot.anonRssInKilobytes);
+            e.writeInt(snapshot.swapInKilobytes);
+            e.writeInt(snapshot.anonRssInKilobytes + snapshot.swapInKilobytes);
+            pulledData.add(e);
+        }
+        int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
+        for (int pid : pids) {
+            final String processName = readCmdlineFromProcfs(pid);
+            final MemorySnapshot snapshot = readMemorySnapshotFromProcfs(pid);
+            if (snapshot == null) {
+                continue;
+            }
+            // Sometimes we get here a process that is not included in the whitelist. It comes
+            // from forking the zygote for an app. We can ignore that sample because this process
+            // is collected by ProcessMemoryState.
+            if (isAppUid(snapshot.uid)) {
+                continue;
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(snapshot.uid);
+            e.writeString(processName);
+            e.writeInt(pid);
+            e.writeInt(-1001);  // Placeholder for native processes, OOM_SCORE_ADJ_MIN - 1.
+            e.writeInt(snapshot.rssInKilobytes);
+            e.writeInt(snapshot.anonRssInKilobytes);
+            e.writeInt(snapshot.swapInKilobytes);
+            e.writeInt(snapshot.anonRssInKilobytes + snapshot.swapInKilobytes);
+            pulledData.add(e);
+        }
+    }
+
+    private static boolean isAppUid(int uid) {
+        return uid >= MIN_APP_UID;
+    }
+
+    private void pullSystemIonHeapSize(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        final long systemIonHeapSizeInBytes = readSystemIonHeapSizeFromDebugfs();
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeLong(systemIonHeapSizeInBytes);
+        pulledData.add(e);
+    }
+
+    private void pullProcessSystemIonHeapSize(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        List<IonAllocations> result = readProcessSystemIonHeapSizesFromDebugfs();
+        for (IonAllocations allocations : result) {
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(getUidForPid(allocations.pid));
+            e.writeString(readCmdlineFromProcfs(allocations.pid));
+            e.writeInt((int) (allocations.totalSizeInBytes / 1024));
+            e.writeInt(allocations.count);
+            e.writeInt((int) (allocations.maxSizeInBytes / 1024));
+            pulledData.add(e);
+        }
+    }
+
+    private void pullBinderCallsStats(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        BinderCallsStatsService.Internal binderStats =
+                LocalServices.getService(BinderCallsStatsService.Internal.class);
+        if (binderStats == null) {
+            throw new IllegalStateException("binderStats is null");
+        }
+
+        List<ExportedCallStat> callStats = binderStats.getExportedCallStats();
+        binderStats.reset();
+        for (ExportedCallStat callStat : callStats) {
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(callStat.workSourceUid);
+            e.writeString(callStat.className);
+            e.writeString(callStat.methodName);
+            e.writeLong(callStat.callCount);
+            e.writeLong(callStat.exceptionCount);
+            e.writeLong(callStat.latencyMicros);
+            e.writeLong(callStat.maxLatencyMicros);
+            e.writeLong(callStat.cpuTimeMicros);
+            e.writeLong(callStat.maxCpuTimeMicros);
+            e.writeLong(callStat.maxReplySizeBytes);
+            e.writeLong(callStat.maxRequestSizeBytes);
+            e.writeLong(callStat.recordedCallCount);
+            e.writeInt(callStat.screenInteractive ? 1 : 0);
+            e.writeInt(callStat.callingUid);
+            pulledData.add(e);
+        }
+    }
+
+    private void pullBinderCallsStatsExceptions(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        BinderCallsStatsService.Internal binderStats =
+                LocalServices.getService(BinderCallsStatsService.Internal.class);
+        if (binderStats == null) {
+            throw new IllegalStateException("binderStats is null");
+        }
+
+        ArrayMap<String, Integer> exceptionStats = binderStats.getExportedExceptionStats();
+        // TODO: decouple binder calls exceptions with the rest of the binder calls data so that we
+        // can reset the exception stats.
+        for (Entry<String, Integer> entry : exceptionStats.entrySet()) {
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeString(entry.getKey());
+            e.writeInt(entry.getValue());
+            pulledData.add(e);
+        }
+    }
+
+    private void pullLooperStats(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        LooperStats looperStats = LocalServices.getService(LooperStats.class);
+        if (looperStats == null) {
+            throw new IllegalStateException("looperStats null");
+        }
+
+        List<LooperStats.ExportedEntry> entries = looperStats.getEntries();
+        looperStats.reset();
+        for (LooperStats.ExportedEntry entry : entries) {
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(entry.workSourceUid);
+            e.writeString(entry.handlerClassName);
+            e.writeString(entry.threadName);
+            e.writeString(entry.messageName);
+            e.writeLong(entry.messageCount);
+            e.writeLong(entry.exceptionCount);
+            e.writeLong(entry.recordedMessageCount);
+            e.writeLong(entry.totalLatencyMicros);
+            e.writeLong(entry.cpuUsageMicros);
+            e.writeBoolean(entry.isInteractive);
+            e.writeLong(entry.maxCpuUsageMicros);
+            e.writeLong(entry.maxLatencyMicros);
+            e.writeLong(entry.recordedDelayMessageCount);
+            e.writeLong(entry.delayMillis);
+            e.writeLong(entry.maxDelayMillis);
+            pulledData.add(e);
+        }
+    }
+
+    private void pullDiskStats(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        // Run a quick-and-dirty performance test: write 512 bytes
+        byte[] junk = new byte[512];
+        for (int i = 0; i < junk.length; i++) junk[i] = (byte) i;  // Write nonzero bytes
+
+        File tmp = new File(Environment.getDataDirectory(), "system/statsdperftest.tmp");
+        FileOutputStream fos = null;
+        IOException error = null;
+
+        long before = SystemClock.elapsedRealtime();
+        try {
+            fos = new FileOutputStream(tmp);
+            fos.write(junk);
+        } catch (IOException e) {
+            error = e;
+        } finally {
+            try {
+                if (fos != null) fos.close();
+            } catch (IOException e) {
+                // Do nothing.
+            }
+        }
+
+        long latency = SystemClock.elapsedRealtime() - before;
+        if (tmp.exists()) tmp.delete();
+
+        if (error != null) {
+            Slog.e(TAG, "Error performing diskstats latency test");
+            latency = -1;
+        }
+        // File based encryption.
+        boolean fileBased = StorageManager.isFileEncryptedNativeOnly();
+
+        //Recent disk write speed. Binder call to storaged.
+        int writeSpeed = -1;
+        try {
+            IBinder binder = ServiceManager.getService("storaged");
+            if (binder == null) {
+                Slog.e(TAG, "storaged not found");
+            }
+            IStoraged storaged = IStoraged.Stub.asInterface(binder);
+            writeSpeed = storaged.getRecentPerf();
+        } catch (RemoteException e) {
+            Slog.e(TAG, "storaged not found");
+        }
+
+        // Add info pulledData.
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeLong(latency);
+        e.writeBoolean(fileBased);
+        e.writeInt(writeSpeed);
+        pulledData.add(e);
+    }
+
+    private void pullDirectoryUsage(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        StatFs statFsData = new StatFs(Environment.getDataDirectory().getAbsolutePath());
+        StatFs statFsSystem = new StatFs(Environment.getRootDirectory().getAbsolutePath());
+        StatFs statFsCache = new StatFs(Environment.getDownloadCacheDirectory().getAbsolutePath());
+
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__DATA);
+        e.writeLong(statFsData.getAvailableBytes());
+        e.writeLong(statFsData.getTotalBytes());
+        pulledData.add(e);
+
+        e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__CACHE);
+        e.writeLong(statFsCache.getAvailableBytes());
+        e.writeLong(statFsCache.getTotalBytes());
+        pulledData.add(e);
+
+        e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__SYSTEM);
+        e.writeLong(statFsSystem.getAvailableBytes());
+        e.writeLong(statFsSystem.getTotalBytes());
+        pulledData.add(e);
+    }
+
+    private void pullAppSize(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        try {
+            String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
+            JSONObject json = new JSONObject(jsonStr);
+            long cache_time = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
+            JSONArray pkg_names = json.getJSONArray(DiskStatsFileLogger.PACKAGE_NAMES_KEY);
+            JSONArray app_sizes = json.getJSONArray(DiskStatsFileLogger.APP_SIZES_KEY);
+            JSONArray app_data_sizes = json.getJSONArray(DiskStatsFileLogger.APP_DATA_KEY);
+            JSONArray app_cache_sizes = json.getJSONArray(DiskStatsFileLogger.APP_CACHES_KEY);
+            // Sanity check: Ensure all 4 lists have the same length.
+            int length = pkg_names.length();
+            if (app_sizes.length() != length || app_data_sizes.length() != length
+                    || app_cache_sizes.length() != length) {
+                Slog.e(TAG, "formatting error in diskstats cache file!");
+                return;
+            }
+            for (int i = 0; i < length; i++) {
+                StatsLogEventWrapper e =
+                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+                e.writeString(pkg_names.getString(i));
+                e.writeLong(app_sizes.optLong(i, -1L));
+                e.writeLong(app_data_sizes.optLong(i, -1L));
+                e.writeLong(app_cache_sizes.optLong(i, -1L));
+                e.writeLong(cache_time);
+                pulledData.add(e);
+            }
+        } catch (IOException | JSONException e) {
+            Slog.e(TAG, "exception reading diskstats cache file", e);
+        }
+    }
+
+    private void pullCategorySize(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        try {
+            String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
+            JSONObject json = new JSONObject(jsonStr);
+            long cacheTime = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
+
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_SIZE);
+            e.writeLong(json.optLong(DiskStatsFileLogger.APP_SIZE_AGG_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_DATA_SIZE);
+            e.writeLong(json.optLong(DiskStatsFileLogger.APP_DATA_SIZE_AGG_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_CACHE_SIZE);
+            e.writeLong(json.optLong(DiskStatsFileLogger.APP_CACHE_AGG_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__PHOTOS);
+            e.writeLong(json.optLong(DiskStatsFileLogger.PHOTOS_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__VIDEOS);
+            e.writeLong(json.optLong(DiskStatsFileLogger.VIDEOS_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__AUDIO);
+            e.writeLong(json.optLong(DiskStatsFileLogger.AUDIO_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__DOWNLOADS);
+            e.writeLong(json.optLong(DiskStatsFileLogger.DOWNLOADS_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__SYSTEM);
+            e.writeLong(json.optLong(DiskStatsFileLogger.SYSTEM_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+
+            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__OTHER);
+            e.writeLong(json.optLong(DiskStatsFileLogger.MISC_KEY, -1L));
+            e.writeLong(cacheTime);
+            pulledData.add(e);
+        } catch (IOException | JSONException e) {
+            Slog.e(TAG, "exception reading diskstats cache file", e);
+        }
+    }
+
+    private void pullNumBiometricsEnrolled(int modality, int tagId, long elapsedNanos,
+            long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        final PackageManager pm = mContext.getPackageManager();
+        FingerprintManager fingerprintManager = null;
+        FaceManager faceManager = null;
+
+        if (pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
+            fingerprintManager = mContext.getSystemService(
+                    FingerprintManager.class);
+        }
+        if (pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
+            faceManager = mContext.getSystemService(FaceManager.class);
+        }
+
+        if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT && fingerprintManager == null) {
+            return;
+        }
+        if (modality == BiometricsProtoEnums.MODALITY_FACE && faceManager == null) {
+            return;
+        }
+        UserManager userManager = mContext.getSystemService(UserManager.class);
+        if (userManager == null) {
+            return;
+        }
+
+        final long token = Binder.clearCallingIdentity();
+        for (UserInfo user : userManager.getUsers()) {
+            final int userId = user.getUserHandle().getIdentifier();
+            int numEnrolled = 0;
+            if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
+                numEnrolled = fingerprintManager.getEnrolledFingerprints(userId).size();
+            } else if (modality == BiometricsProtoEnums.MODALITY_FACE) {
+                numEnrolled = faceManager.getEnrolledFaces(userId).size();
+            } else {
+                return;
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(userId);
+            e.writeInt(numEnrolled);
+            pulledData.add(e);
+        }
+        Binder.restoreCallingIdentity(token);
+    }
+
+    // read high watermark for section
+    private long readProcStatsHighWaterMark(int section) {
+        try {
+            File[] files = mBaseDir.listFiles((d, name) -> {
+                return name.toLowerCase().startsWith(String.valueOf(section) + '_');
+            });
+            if (files == null || files.length == 0) {
+                return 0;
+            }
+            if (files.length > 1) {
+                Log.e(TAG, "Only 1 file expected for high water mark. Found " + files.length);
+            }
+            return Long.valueOf(files[0].getName().split("_")[1]);
+        } catch (SecurityException e) {
+            Log.e(TAG, "Failed to get procstats high watermark file.", e);
+        } catch (NumberFormatException e) {
+            Log.e(TAG, "Failed to parse file name.", e);
+        }
+        return 0;
+    }
+
+    private IProcessStats mProcessStats =
+            IProcessStats.Stub.asInterface(ServiceManager.getService(ProcessStats.SERVICE_NAME));
+
+    private void pullProcessStats(int section, int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        synchronized (this) {
+            try {
+                long lastHighWaterMark = readProcStatsHighWaterMark(section);
+                List<ParcelFileDescriptor> statsFiles = new ArrayList<>();
+                long highWaterMark = mProcessStats.getCommittedStats(
+                        lastHighWaterMark, section, true, statsFiles);
+                if (statsFiles.size() != 1) {
+                    return;
+                }
+                InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(
+                        statsFiles.get(0));
+                int[] len = new int[1];
+                byte[] stats = readFully(stream, len);
+                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                        wallClockNanos);
+                e.writeStorage(Arrays.copyOf(stats, len[0]));
+                pulledData.add(e);
+                new File(mBaseDir.getAbsolutePath() + "/" + section + "_"
+                        + lastHighWaterMark).delete();
+                new File(
+                        mBaseDir.getAbsolutePath() + "/" + section + "_"
+                                + highWaterMark).createNewFile();
+            } catch (IOException e) {
+                Log.e(TAG, "Getting procstats failed: ", e);
+            } catch (RemoteException e) {
+                Log.e(TAG, "Getting procstats failed: ", e);
+            } catch (SecurityException e) {
+                Log.e(TAG, "Getting procstats failed: ", e);
+            }
+        }
+    }
+
+    static byte[] readFully(InputStream stream, int[] outLen) throws IOException {
+        int pos = 0;
+        final int initialAvail = stream.available();
+        byte[] data = new byte[initialAvail > 0 ? (initialAvail + 1) : 16384];
+        while (true) {
+            int amt = stream.read(data, pos, data.length - pos);
+            if (DEBUG) {
+                Slog.i(TAG, "Read " + amt + " bytes at " + pos + " of avail " + data.length);
+            }
+            if (amt < 0) {
+                if (DEBUG) {
+                    Slog.i(TAG, "**** FINISHED READING: pos=" + pos + " len=" + data.length);
+                }
+                outLen[0] = pos;
+                return data;
+            }
+            pos += amt;
+            if (pos >= data.length) {
+                byte[] newData = new byte[pos + 16384];
+                if (DEBUG) {
+                    Slog.i(TAG, "Copying " + pos + " bytes to new array len " + newData.length);
+                }
+                System.arraycopy(data, 0, newData, 0, pos);
+                data = newData;
+            }
+        }
+    }
+
+    private void pullPowerProfile(
+            int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        PowerProfile powerProfile = new PowerProfile(mContext);
+        checkNotNull(powerProfile);
+
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                wallClockNanos);
+        ProtoOutputStream proto = new ProtoOutputStream();
+        powerProfile.writeToProto(proto);
+        proto.flush();
+        e.writeStorage(proto.getBytes());
+        pulledData.add(e);
+    }
+
+    private void pullBuildInformation(int tagId,
+            long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeString(Build.FINGERPRINT);
+        e.writeString(Build.BRAND);
+        e.writeString(Build.PRODUCT);
+        e.writeString(Build.DEVICE);
+        e.writeString(Build.VERSION.RELEASE);
+        e.writeString(Build.ID);
+        e.writeString(Build.VERSION.INCREMENTAL);
+        e.writeString(Build.TYPE);
+        e.writeString(Build.TAGS);
+        pulledData.add(e);
+    }
+
+    private BatteryStatsHelper getBatteryStatsHelper() {
+        if (mBatteryStatsHelper == null) {
+            final long callingToken = Binder.clearCallingIdentity();
+            try {
+                // clearCallingIdentity required for BatteryStatsHelper.checkWifiOnly().
+                mBatteryStatsHelper = new BatteryStatsHelper(mContext, false);
+            } finally {
+                Binder.restoreCallingIdentity(callingToken);
+            }
+            mBatteryStatsHelper.create((Bundle) null);
+        }
+        long currentTime = SystemClock.elapsedRealtime();
+        if (currentTime - mBatteryStatsHelperTimestampMs >= MAX_BATTERY_STATS_HELPER_FREQUENCY_MS) {
+            // Load BatteryStats and do all the calculations.
+            mBatteryStatsHelper.refreshStats(BatteryStats.STATS_SINCE_CHARGED, UserHandle.USER_ALL);
+            // Calculations are done so we don't need to save the raw BatteryStats data in RAM.
+            mBatteryStatsHelper.clearStats();
+            mBatteryStatsHelperTimestampMs = currentTime;
+        }
+        return mBatteryStatsHelper;
+    }
+
+    private long milliAmpHrsToNanoAmpSecs(double mAh) {
+        final long MILLI_AMP_HR_TO_NANO_AMP_SECS = 1_000_000L * 3600L;
+        return (long) (mAh * MILLI_AMP_HR_TO_NANO_AMP_SECS + 0.5);
+    }
+
+    private void pullDeviceCalculatedPowerUse(int tagId,
+            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        BatteryStatsHelper bsHelper = getBatteryStatsHelper();
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeLong(milliAmpHrsToNanoAmpSecs(bsHelper.getComputedPower()));
+        pulledData.add(e);
+    }
+
+    private void pullDeviceCalculatedPowerBlameUid(int tagId,
+            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
+        if (sippers == null) {
+            return;
+        }
+        for (BatterySipper bs : sippers) {
+            if (bs.drainType != bs.drainType.APP) {
+                continue;
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(bs.uidObj.getUid());
+            e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
+            pulledData.add(e);
+        }
+    }
+
+    private void pullDeviceCalculatedPowerBlameOther(int tagId,
+            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
+        if (sippers == null) {
+            return;
+        }
+        for (BatterySipper bs : sippers) {
+            if (bs.drainType == bs.drainType.APP) {
+                continue; // This is a separate atom; see pullDeviceCalculatedPowerBlameUid().
+            }
+            if (bs.drainType == bs.drainType.USER) {
+                continue; // This is not supported. We purposefully calculate over USER_ALL.
+            }
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e.writeInt(bs.drainType.ordinal());
+            e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
+            pulledData.add(e);
+        }
+    }
+
+    private void pullDiskIo(int tagId, long elapsedNanos, final long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        mStoragedUidIoStatsReader.readAbsolute((uid, fgCharsRead, fgCharsWrite, fgBytesRead,
+                fgBytesWrite, bgCharsRead, bgCharsWrite, bgBytesRead, bgBytesWrite,
+                fgFsync, bgFsync) -> {
+            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                    wallClockNanos);
+            e.writeInt(uid);
+            e.writeLong(fgCharsRead);
+            e.writeLong(fgCharsWrite);
+            e.writeLong(fgBytesRead);
+            e.writeLong(fgBytesWrite);
+            e.writeLong(bgCharsRead);
+            e.writeLong(bgCharsWrite);
+            e.writeLong(bgBytesRead);
+            e.writeLong(bgBytesWrite);
+            e.writeLong(fgFsync);
+            e.writeLong(bgFsync);
+            pulledData.add(e);
+        });
+    }
+
+    private void pullProcessCpuTime(int tagId, long elapsedNanos, final long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        synchronized (this) {
+            if (mProcessCpuTracker == null) {
+                mProcessCpuTracker = new ProcessCpuTracker(false);
+                mProcessCpuTracker.init();
+            }
+            mProcessCpuTracker.update();
+            for (int i = 0; i < mProcessCpuTracker.countStats(); i++) {
+                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
+                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
+                        wallClockNanos);
+                e.writeInt(st.uid);
+                e.writeString(st.name);
+                e.writeLong(st.base_utime);
+                e.writeLong(st.base_stime);
+                pulledData.add(e);
+            }
+        }
+    }
+
+    private void pullCpuTimePerThreadFreq(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        if (this.mKernelCpuThreadReader == null) {
+            throw new IllegalStateException("mKernelCpuThreadReader is null");
+        }
+        ArrayList<KernelCpuThreadReader.ProcessCpuUsage> processCpuUsages =
+                this.mKernelCpuThreadReader.getProcessCpuUsageDiffed();
+        if (processCpuUsages == null) {
+            throw new IllegalStateException("processCpuUsages is null");
+        }
+        int[] cpuFrequencies = mKernelCpuThreadReader.getCpuFrequenciesKhz();
+        if (cpuFrequencies.length > CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES) {
+            String message = "Expected maximum " + CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES
+                    + " frequencies, but got " + cpuFrequencies.length;
+            Slog.w(TAG, message);
+            throw new IllegalStateException(message);
+        }
+        for (int i = 0; i < processCpuUsages.size(); i++) {
+            KernelCpuThreadReader.ProcessCpuUsage processCpuUsage = processCpuUsages.get(i);
+            ArrayList<KernelCpuThreadReader.ThreadCpuUsage> threadCpuUsages =
+                    processCpuUsage.threadCpuUsages;
+            for (int j = 0; j < threadCpuUsages.size(); j++) {
+                KernelCpuThreadReader.ThreadCpuUsage threadCpuUsage = threadCpuUsages.get(j);
+                if (threadCpuUsage.usageTimesMillis.length != cpuFrequencies.length) {
+                    String message = "Unexpected number of usage times,"
+                            + " expected " + cpuFrequencies.length
+                            + " but got " + threadCpuUsage.usageTimesMillis.length;
+                    Slog.w(TAG, message);
+                    throw new IllegalStateException(message);
+                }
+
+                StatsLogEventWrapper e =
+                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+                e.writeInt(processCpuUsage.uid);
+                e.writeInt(processCpuUsage.processId);
+                e.writeInt(threadCpuUsage.threadId);
+                e.writeString(processCpuUsage.processName);
+                e.writeString(threadCpuUsage.threadName);
+                for (int k = 0; k < CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES; k++) {
+                    if (k < cpuFrequencies.length) {
+                        e.writeInt(cpuFrequencies[k]);
+                        e.writeInt(threadCpuUsage.usageTimesMillis[k]);
+                    } else {
+                        // If we have no more frequencies to write, we still must write empty data.
+                        // We know that this data is empty (and not just zero) because all
+                        // frequencies are expected to be greater than zero
+                        e.writeInt(0);
+                        e.writeInt(0);
+                    }
+                }
+                pulledData.add(e);
+            }
+        }
+    }
+
+    private void pullTemperature(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long callingToken = Binder.clearCallingIdentity();
+        try {
+            List<Temperature> temperatures = sThermalService.getCurrentTemperatures();
+            for (Temperature temp : temperatures) {
+                StatsLogEventWrapper e =
+                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+                e.writeInt(temp.getType());
+                e.writeString(temp.getName());
+                e.writeInt((int) (temp.getValue() * 10));
+                e.writeInt(temp.getStatus());
+                pulledData.add(e);
+            }
+        } catch (RemoteException e) {
+            // Should not happen.
+            Slog.e(TAG, "Disconnected from thermal service. Cannot pull temperatures.");
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    private void pullCoolingDevices(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long callingToken = Binder.clearCallingIdentity();
+        try {
+            List<CoolingDevice> devices = sThermalService.getCurrentCoolingDevices();
+            for (CoolingDevice device : devices) {
+                StatsLogEventWrapper e =
+                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+                e.writeInt(device.getType());
+                e.writeString(device.getName());
+                e.writeInt((int) (device.getValue()));
+                pulledData.add(e);
+            }
+        } catch (RemoteException e) {
+            // Should not happen.
+            Slog.e(TAG, "Disconnected from thermal service. Cannot pull temperatures.");
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    private void pullDebugElapsedClock(int tagId,
+            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        final long elapsedMillis = SystemClock.elapsedRealtime();
+        final long clockDiffMillis = mDebugElapsedClockPreviousValue == 0
+                ? 0 : elapsedMillis - mDebugElapsedClockPreviousValue;
+
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeLong(mDebugElapsedClockPullCount);
+        e.writeLong(elapsedMillis);
+        // Log it twice to be able to test multi-value aggregation from ValueMetric.
+        e.writeLong(elapsedMillis);
+        e.writeLong(clockDiffMillis);
+        e.writeInt(1 /* always set */);
+        pulledData.add(e);
+
+        if (mDebugElapsedClockPullCount % 2 == 1) {
+            StatsLogEventWrapper e2 = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+            e2.writeLong(mDebugElapsedClockPullCount);
+            e2.writeLong(elapsedMillis);
+            // Log it twice to be able to test multi-value aggregation from ValueMetric.
+            e2.writeLong(elapsedMillis);
+            e2.writeLong(clockDiffMillis);
+            e2.writeInt(2 /* set on odd pulls */);
+            pulledData.add(e2);
+        }
+
+        mDebugElapsedClockPullCount++;
+        mDebugElapsedClockPreviousValue = elapsedMillis;
+    }
+
+    private void pullDebugFailingElapsedClock(int tagId,
+            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        final long elapsedMillis = SystemClock.elapsedRealtime();
+        // Fails every 5 buckets.
+        if (mDebugFailingElapsedClockPullCount++ % 5 == 0) {
+            mDebugFailingElapsedClockPreviousValue = elapsedMillis;
+            throw new RuntimeException("Failing debug elapsed clock");
+        }
+
+        e.writeLong(mDebugFailingElapsedClockPullCount);
+        e.writeLong(elapsedMillis);
+        // Log it twice to be able to test multi-value aggregation from ValueMetric.
+        e.writeLong(elapsedMillis);
+        e.writeLong(mDebugFailingElapsedClockPreviousValue == 0
+                ? 0 : elapsedMillis - mDebugFailingElapsedClockPreviousValue);
+        mDebugFailingElapsedClockPreviousValue = elapsedMillis;
+        pulledData.add(e);
+    }
+
+    private void pullDangerousPermissionState(long elapsedNanos, final long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        try {
+            PackageManager pm = mContext.getPackageManager();
+
+            List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
+
+            int numUsers = users.size();
+            for (int userNum = 0; userNum < numUsers; userNum++) {
+                UserHandle user = users.get(userNum).getUserHandle();
+
+                List<PackageInfo> pkgs = pm.getInstalledPackagesAsUser(
+                        PackageManager.GET_PERMISSIONS, user.getIdentifier());
+
+                int numPkgs = pkgs.size();
+                for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
+                    PackageInfo pkg = pkgs.get(pkgNum);
+
+                    if (pkg.requestedPermissions == null) {
+                        continue;
+                    }
+
+                    int numPerms = pkg.requestedPermissions.length;
+                    for (int permNum  = 0; permNum < numPerms; permNum++) {
+                        String permName = pkg.requestedPermissions[permNum];
+
+                        PermissionInfo permissionInfo;
+                        int permissionFlags = 0;
+                        try {
+                            permissionInfo = pm.getPermissionInfo(permName, 0);
+                            permissionFlags =
+                                pm.getPermissionFlags(permName, pkg.packageName, user);
+
+                        } catch (PackageManager.NameNotFoundException ignored) {
+                            continue;
+                        }
+
+                        if (permissionInfo.getProtection() != PROTECTION_DANGEROUS) {
+                            continue;
+                        }
+
+                        StatsLogEventWrapper e = new StatsLogEventWrapper(
+                                StatsLog.DANGEROUS_PERMISSION_STATE, elapsedNanos, wallClockNanos);
+
+                        e.writeString(permName);
+                        e.writeInt(pkg.applicationInfo.uid);
+                        e.writeString(pkg.packageName);
+                        e.writeBoolean((pkg.requestedPermissionsFlags[permNum]
+                                & REQUESTED_PERMISSION_GRANTED) != 0);
+                        e.writeInt(permissionFlags);
+
+                        pulledData.add(e);
+                    }
+                }
+            }
+        } catch (Throwable t) {
+            Log.e(TAG, "Could not read permissions", t);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    private void pullAppOps(long elapsedNanos, final long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long token = Binder.clearCallingIdentity();
+        try {
+            AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
+
+            CompletableFuture<HistoricalOps> ops = new CompletableFuture<>();
+            HistoricalOpsRequest histOpsRequest =
+                    new HistoricalOpsRequest.Builder(
+                            Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli(),
+                            Long.MAX_VALUE).build();
+            appOps.getHistoricalOps(histOpsRequest, mContext.getMainExecutor(), ops::complete);
+
+            HistoricalOps histOps = ops.get(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS,
+                    TimeUnit.MILLISECONDS);
+
+            for (int uidIdx = 0; uidIdx < histOps.getUidCount(); uidIdx++) {
+                final HistoricalUidOps uidOps = histOps.getUidOpsAt(uidIdx);
+                final int uid = uidOps.getUid();
+                for (int pkgIdx = 0; pkgIdx < uidOps.getPackageCount(); pkgIdx++) {
+                    final HistoricalPackageOps packageOps = uidOps.getPackageOpsAt(pkgIdx);
+                    for (int opIdx = 0; opIdx < packageOps.getOpCount(); opIdx++) {
+                        final AppOpsManager.HistoricalOp op  = packageOps.getOpAt(opIdx);
+                        StatsLogEventWrapper e = new StatsLogEventWrapper(StatsLog.APP_OPS,
+                                elapsedNanos, wallClockNanos);
+
+                        e.writeInt(uid);
+                        e.writeString(packageOps.getPackageName());
+                        e.writeInt(op.getOpCode());
+                        e.writeLong(op.getForegroundAccessCount(OP_FLAGS_ALL_TRUSTED));
+                        e.writeLong(op.getBackgroundAccessCount(OP_FLAGS_ALL_TRUSTED));
+                        e.writeLong(op.getForegroundRejectCount(OP_FLAGS_ALL_TRUSTED));
+                        e.writeLong(op.getBackgroundRejectCount(OP_FLAGS_ALL_TRUSTED));
+                        e.writeLong(op.getForegroundAccessDuration(OP_FLAGS_ALL_TRUSTED));
+                        e.writeLong(op.getBackgroundAccessDuration(OP_FLAGS_ALL_TRUSTED));
+                        pulledData.add(e);
+                    }
+                }
+            }
+        } catch (Throwable t) {
+            Log.e(TAG, "Could not read appops", t);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+
+    /**
+     * Add a RoleHolder atom for each package that holds a role.
+     *
+     * @param elapsedNanos the time since boot
+     * @param wallClockNanos the time on the clock
+     * @param pulledData the data sink to write to
+     */
+    private void pullRoleHolders(long elapsedNanos, final long wallClockNanos,
+            @NonNull List<StatsLogEventWrapper> pulledData) {
+        long callingToken = Binder.clearCallingIdentity();
+        try {
+            PackageManager pm = mContext.getPackageManager();
+            RoleManagerInternal rmi = LocalServices.getService(RoleManagerInternal.class);
+
+            List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
+
+            int numUsers = users.size();
+            for (int userNum = 0; userNum < numUsers; userNum++) {
+                int userId = users.get(userNum).getUserHandle().getIdentifier();
+
+                ArrayMap<String, ArraySet<String>> roles = rmi.getRolesAndHolders(
+                        userId);
+
+                int numRoles = roles.size();
+                for (int roleNum = 0; roleNum < numRoles; roleNum++) {
+                    String roleName = roles.keyAt(roleNum);
+                    ArraySet<String> holders = roles.valueAt(roleNum);
+
+                    int numHolders = holders.size();
+                    for (int holderNum = 0; holderNum < numHolders; holderNum++) {
+                        String holderName = holders.valueAt(holderNum);
+
+                        PackageInfo pkg;
+                        try {
+                            pkg = pm.getPackageInfoAsUser(holderName, 0, userId);
+                        } catch (PackageManager.NameNotFoundException e) {
+                            Log.w(TAG, "Role holder " + holderName + " not found");
+                            return;
+                        }
+
+                        StatsLogEventWrapper e = new StatsLogEventWrapper(StatsLog.ROLE_HOLDER,
+                                elapsedNanos, wallClockNanos);
+                        e.writeInt(pkg.applicationInfo.uid);
+                        e.writeString(holderName);
+                        e.writeString(roleName);
+                        pulledData.add(e);
+                    }
+                }
+            }
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    private void pullTimeZoneDataInfo(int tagId,
+            long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
+        String tzDbVersion = "Unknown";
+        try {
+            tzDbVersion = android.icu.util.TimeZone.getTZDataVersion();
+        } catch (Exception e) {
+            Log.e(TAG, "Getting tzdb version failed: ", e);
+        }
+
+        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+        e.writeString(tzDbVersion);
+        pulledData.add(e);
+    }
+
+    private void pullExternalStorageInfo(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        StorageManager storageManager = mContext.getSystemService(StorageManager.class);
+        if (storageManager != null) {
+            List<VolumeInfo> volumes = storageManager.getVolumes();
+            for (VolumeInfo vol : volumes) {
+                final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
+                final DiskInfo diskInfo = vol.getDisk();
+                if (diskInfo != null) {
+                    if (envState.equals(Environment.MEDIA_MOUNTED)) {
+                        // Get the type of the volume, if it is adoptable or portable.
+                        int volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__OTHER;
+                        if (vol.getType() == TYPE_PUBLIC) {
+                            volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__PUBLIC;
+                        } else if (vol.getType() == TYPE_PRIVATE) {
+                            volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__PRIVATE;
+                        }
+                        // Get the type of external storage inserted in the device (sd cards,
+                        // usb, etc)
+                        int externalStorageType;
+                        if (diskInfo.isSd()) {
+                            externalStorageType = StorageEnums.SD_CARD;
+                        } else if (diskInfo.isUsb()) {
+                            externalStorageType = StorageEnums.USB;
+                        } else {
+                            externalStorageType = StorageEnums.OTHER;
+                        }
+                        StatsLogEventWrapper e =
+                                new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+                        e.writeInt(externalStorageType);
+                        e.writeInt(volumeType);
+                        e.writeLong(diskInfo.size);
+                        pulledData.add(e);
+                    }
+                }
+            }
+        }
+    }
+
+    private void pullAppsOnExternalStorageInfo(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        PackageManager pm = mContext.getPackageManager();
+        StorageManager storage = mContext.getSystemService(StorageManager.class);
+        List<ApplicationInfo> apps = pm.getInstalledApplications(/* flags = */ 0);
+        for (ApplicationInfo appInfo : apps) {
+            UUID storageUuid = appInfo.storageUuid;
+            if (storageUuid != null) {
+                VolumeInfo volumeInfo = storage.findVolumeByUuid(appInfo.storageUuid.toString());
+                if (volumeInfo != null) {
+                    DiskInfo diskInfo = volumeInfo.getDisk();
+                    if (diskInfo != null) {
+                        int externalStorageType = -1;
+                        if (diskInfo.isSd()) {
+                            externalStorageType = StorageEnums.SD_CARD;
+                        } else if (diskInfo.isUsb()) {
+                            externalStorageType = StorageEnums.USB;
+                        } else if (appInfo.isExternal()) {
+                            externalStorageType = StorageEnums.OTHER;
+                        }
+                        // App is installed on external storage.
+                        if (externalStorageType != -1) {
+                            StatsLogEventWrapper e =
+                                    new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+                            e.writeInt(externalStorageType);
+                            e.writeString(appInfo.packageName);
+                            pulledData.add(e);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    private void pullFaceSettings(int tagId, long elapsedNanos, long wallClockNanos,
+            List<StatsLogEventWrapper> pulledData) {
+        long callingToken = Binder.clearCallingIdentity();
+        try {
+            List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
+            int numUsers = users.size();
+            for (int userNum = 0; userNum < numUsers; userNum++) {
+                int userId = users.get(userNum).getUserHandle().getIdentifier();
+
+                StatsLogEventWrapper e =
+                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
+                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.FACE_UNLOCK_KEYGUARD_ENABLED, 1,
+                        userId) != 0);
+                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.FACE_UNLOCK_DISMISSES_KEYGUARD,
+                        0, userId) != 0);
+                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.FACE_UNLOCK_ATTENTION_REQUIRED, 1,
+                        userId) != 0);
+                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.FACE_UNLOCK_APP_ENABLED, 1,
+                        userId) != 0);
+                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION, 0,
+                        userId) != 0);
+                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.FACE_UNLOCK_DIVERSITY_REQUIRED, 1,
+                        userId) != 0);
+
+                pulledData.add(e);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(callingToken);
+        }
+    }
+
+    /**
+     * Pulls various data.
+     */
+    @Override // Binder call
+    public StatsLogEventWrapper[] pullData(int tagId) {
+        enforceCallingPermission();
+        if (DEBUG) {
+            Slog.d(TAG, "Pulling " + tagId);
+        }
+        List<StatsLogEventWrapper> ret = new ArrayList<>();
+        long elapsedNanos = SystemClock.elapsedRealtimeNanos();
+        long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
+        switch (tagId) {
+            case StatsLog.WIFI_BYTES_TRANSFER: {
+                pullWifiBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.MOBILE_BYTES_TRANSFER: {
+                pullMobileBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.WIFI_BYTES_TRANSFER_BY_FG_BG: {
+                pullWifiBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.MOBILE_BYTES_TRANSFER_BY_FG_BG: {
+                pullMobileBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.BLUETOOTH_BYTES_TRANSFER: {
+                pullBluetoothBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.KERNEL_WAKELOCK: {
+                pullKernelWakelock(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.CPU_TIME_PER_FREQ: {
+                pullCpuTimePerFreq(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.CPU_TIME_PER_UID: {
+                pullKernelUidCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.CPU_TIME_PER_UID_FREQ: {
+                pullKernelUidCpuFreqTime(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.CPU_CLUSTER_TIME: {
+                pullKernelUidCpuClusterTime(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.CPU_ACTIVE_TIME: {
+                pullKernelUidCpuActiveTime(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.WIFI_ACTIVITY_INFO: {
+                pullWifiActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.MODEM_ACTIVITY_INFO: {
+                pullModemActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.BLUETOOTH_ACTIVITY_INFO: {
+                pullBluetoothActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.SYSTEM_UPTIME: {
+                pullSystemUpTime(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.SYSTEM_ELAPSED_REALTIME: {
+                pullSystemElapsedRealtime(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.PROCESS_MEMORY_STATE: {
+                pullProcessMemoryState(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.PROCESS_MEMORY_HIGH_WATER_MARK: {
+                pullProcessMemoryHighWaterMark(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.PROCESS_MEMORY_SNAPSHOT: {
+                pullProcessMemorySnapshot(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.SYSTEM_ION_HEAP_SIZE: {
+                pullSystemIonHeapSize(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.PROCESS_SYSTEM_ION_HEAP_SIZE: {
+                pullProcessSystemIonHeapSize(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.BINDER_CALLS: {
+                pullBinderCallsStats(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.BINDER_CALLS_EXCEPTIONS: {
+                pullBinderCallsStatsExceptions(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.LOOPER_STATS: {
+                pullLooperStats(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DISK_STATS: {
+                pullDiskStats(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DIRECTORY_USAGE: {
+                pullDirectoryUsage(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.APP_SIZE: {
+                pullAppSize(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.CATEGORY_SIZE: {
+                pullCategorySize(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.NUM_FINGERPRINTS_ENROLLED: {
+                pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FINGERPRINT, tagId,
+                        elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.NUM_FACES_ENROLLED: {
+                pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FACE, tagId, elapsedNanos,
+                        wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.PROC_STATS: {
+                pullProcessStats(ProcessStats.REPORT_ALL, tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.PROC_STATS_PKG_PROC: {
+                pullProcessStats(ProcessStats.REPORT_PKG_PROC_STATS, tagId, elapsedNanos,
+                        wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DISK_IO: {
+                pullDiskIo(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.POWER_PROFILE: {
+                pullPowerProfile(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.BUILD_INFORMATION: {
+                pullBuildInformation(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.PROCESS_CPU_TIME: {
+                pullProcessCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.CPU_TIME_PER_THREAD_FREQ: {
+                pullCpuTimePerThreadFreq(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DEVICE_CALCULATED_POWER_USE: {
+                pullDeviceCalculatedPowerUse(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DEVICE_CALCULATED_POWER_BLAME_UID: {
+                pullDeviceCalculatedPowerBlameUid(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DEVICE_CALCULATED_POWER_BLAME_OTHER: {
+                pullDeviceCalculatedPowerBlameOther(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.TEMPERATURE: {
+                pullTemperature(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.COOLING_DEVICE: {
+                pullCoolingDevices(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DEBUG_ELAPSED_CLOCK: {
+                pullDebugElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DEBUG_FAILING_ELAPSED_CLOCK: {
+                pullDebugFailingElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.ROLE_HOLDER: {
+                pullRoleHolders(elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.DANGEROUS_PERMISSION_STATE: {
+                pullDangerousPermissionState(elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.TIME_ZONE_DATA_INFO: {
+                pullTimeZoneDataInfo(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.EXTERNAL_STORAGE_INFO: {
+                pullExternalStorageInfo(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.APPS_ON_EXTERNAL_STORAGE_INFO: {
+                pullAppsOnExternalStorageInfo(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.FACE_SETTINGS: {
+                pullFaceSettings(tagId, elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            case StatsLog.APP_OPS: {
+                pullAppOps(elapsedNanos, wallClockNanos, ret);
+                break;
+            }
+            default:
+                Slog.w(TAG, "No such tagId data as " + tagId);
+                return null;
+        }
+        return ret.toArray(new StatsLogEventWrapper[ret.size()]);
+    }
+
+    @Override // Binder call
+    public void statsdReady() {
+        enforceCallingPermission();
+        if (DEBUG) {
+            Slog.d(TAG, "learned that statsdReady");
+        }
+        sayHiToStatsd(); // tell statsd that we're ready too and link to it
+        mContext.sendBroadcastAsUser(new Intent(StatsManager.ACTION_STATSD_STARTED)
+                        .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
+                UserHandle.SYSTEM, android.Manifest.permission.DUMP);
+    }
+
+    @Override
+    public void triggerUidSnapshot() {
+        enforceCallingPermission();
+        synchronized (sStatsdLock) {
+            final long token = Binder.clearCallingIdentity();
+            try {
+                informAllUidsLocked(mContext);
+            } catch (RemoteException e) {
+                Slog.e(TAG, "Failed to trigger uid snapshot.", e);
+            } finally {
+                restoreCallingIdentity(token);
+            }
+        }
+    }
+
+    private void enforceCallingPermission() {
+        if (Binder.getCallingPid() == Process.myPid()) {
+            return;
+        }
+        mContext.enforceCallingPermission(android.Manifest.permission.STATSCOMPANION, null);
+    }
+
+    // Lifecycle and related code
+
+    /**
+     * Fetches the statsd IBinder service
+     */
+    private static IStatsManager fetchStatsdService() {
+        return IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
+    }
+
+    public static final class Lifecycle extends SystemService {
+        private StatsCompanionService mStatsCompanionService;
+
+        public Lifecycle(Context context) {
+            super(context);
+        }
+
+        @Override
+        public void onStart() {
+            mStatsCompanionService = new StatsCompanionService(getContext());
+            try {
+                publishBinderService(Context.STATS_COMPANION_SERVICE,
+                        mStatsCompanionService);
+                if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_COMPANION_SERVICE);
+            } catch (Exception e) {
+                Slog.e(TAG, "Failed to publishBinderService", e);
+            }
+        }
+
+        @Override
+        public void onBootPhase(int phase) {
+            super.onBootPhase(phase);
+            if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
+                mStatsCompanionService.systemReady();
+            }
+        }
+    }
+
+    /**
+     * Now that the android system is ready, StatsCompanion is ready too, so inform statsd.
+     */
+    private void systemReady() {
+        if (DEBUG) Slog.d(TAG, "Learned that systemReady");
+        sayHiToStatsd();
+    }
+
+    /**
+     * Tells statsd that statscompanion is ready. If the binder call returns, link to
+     * statsd.
+     */
+    private void sayHiToStatsd() {
+        synchronized (sStatsdLock) {
+            if (sStatsd != null) {
+                Slog.e(TAG, "Trying to fetch statsd, but it was already fetched",
+                        new IllegalStateException(
+                                "sStatsd is not null when being fetched"));
+                return;
+            }
+            sStatsd = fetchStatsdService();
+            if (sStatsd == null) {
+                Slog.i(TAG,
+                        "Could not yet find statsd to tell it that StatsCompanion is "
+                                + "alive.");
+                return;
+            }
+            if (DEBUG) Slog.d(TAG, "Saying hi to statsd");
+            try {
+                sStatsd.statsCompanionReady();
+                // If the statsCompanionReady two-way binder call returns, link to statsd.
+                try {
+                    sStatsd.asBinder().linkToDeath(new StatsdDeathRecipient(), 0);
+                } catch (RemoteException e) {
+                    Slog.e(TAG, "linkToDeath(StatsdDeathRecipient) failed", e);
+                    forgetEverythingLocked();
+                }
+                // Setup broadcast receiver for updates.
+                IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REPLACED);
+                filter.addAction(Intent.ACTION_PACKAGE_ADDED);
+                filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+                filter.addDataScheme("package");
+                mContext.registerReceiverAsUser(mAppUpdateReceiver, UserHandle.ALL, filter,
+                        null,
+                        null);
+
+                // Setup receiver for user initialize (which happens once for a new user)
+                // and
+                // if a user is removed.
+                filter = new IntentFilter(Intent.ACTION_USER_INITIALIZE);
+                filter.addAction(Intent.ACTION_USER_REMOVED);
+                mContext.registerReceiverAsUser(mUserUpdateReceiver, UserHandle.ALL,
+                        filter, null, null);
+
+                // Setup receiver for device reboots or shutdowns.
+                filter = new IntentFilter(Intent.ACTION_REBOOT);
+                filter.addAction(Intent.ACTION_SHUTDOWN);
+                mContext.registerReceiverAsUser(
+                        mShutdownEventReceiver, UserHandle.ALL, filter, null, null);
+                final long token = Binder.clearCallingIdentity();
+                try {
+                    // Pull the latest state of UID->app name, version mapping when
+                    // statsd starts.
+                    informAllUidsLocked(mContext);
+                } finally {
+                    restoreCallingIdentity(token);
+                }
+                Slog.i(TAG, "Told statsd that StatsCompanionService is alive.");
+            } catch (RemoteException e) {
+                Slog.e(TAG, "Failed to inform statsd that statscompanion is ready", e);
+                forgetEverythingLocked();
+            }
+        }
+    }
+
+    private class StatsdDeathRecipient implements IBinder.DeathRecipient {
+        @Override
+        public void binderDied() {
+            Slog.i(TAG, "Statsd is dead - erase all my knowledge.");
+            synchronized (sStatsdLock) {
+                long now = SystemClock.elapsedRealtime();
+                for (Long timeMillis : mDeathTimeMillis) {
+                    long ageMillis = now - timeMillis;
+                    if (ageMillis > MILLIS_IN_A_DAY) {
+                        mDeathTimeMillis.remove(timeMillis);
+                    }
+                }
+                for (Long timeMillis : mDeletedFiles.keySet()) {
+                    long ageMillis = now - timeMillis;
+                    if (ageMillis > MILLIS_IN_A_DAY * 7) {
+                        mDeletedFiles.remove(timeMillis);
+                    }
+                }
+                mDeathTimeMillis.add(now);
+                if (mDeathTimeMillis.size() >= DEATH_THRESHOLD) {
+                    mDeathTimeMillis.clear();
+                    File[] configs = FileUtils.listFilesOrEmpty(new File(CONFIG_DIR));
+                    if (configs.length > 0) {
+                        String fileName = configs[0].getName();
+                        if (configs[0].delete()) {
+                            mDeletedFiles.put(now, fileName);
+                        }
+                    }
+                }
+                forgetEverythingLocked();
+            }
+        }
+    }
+
+    @GuardedBy("StatsCompanionService.sStatsdLock")
+    private void forgetEverythingLocked() {
+        sStatsd = null;
+        mContext.unregisterReceiver(mAppUpdateReceiver);
+        mContext.unregisterReceiver(mUserUpdateReceiver);
+        mContext.unregisterReceiver(mShutdownEventReceiver);
+        cancelAnomalyAlarm();
+        cancelPullingAlarm();
+
+        BinderCallsStatsService.Internal binderStats =
+                LocalServices.getService(BinderCallsStatsService.Internal.class);
+        if (binderStats != null) {
+            binderStats.reset();
+        }
+
+        LooperStats looperStats = LocalServices.getService(LooperStats.class);
+        if (looperStats != null) {
+            looperStats.reset();
+        }
+    }
+
+    @Override
+    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
+        if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
+
+        synchronized (sStatsdLock) {
+            writer.println(
+                    "Number of configuration files deleted: " + mDeletedFiles.size());
+            if (mDeletedFiles.size() > 0) {
+                writer.println("  timestamp, deleted file name");
+            }
+            long lastBootMillis =
+                    SystemClock.currentThreadTimeMillis() - SystemClock.elapsedRealtime();
+            for (Long elapsedMillis : mDeletedFiles.keySet()) {
+                long deletionMillis = lastBootMillis + elapsedMillis;
+                writer.println(
+                        "  " + deletionMillis + ", " + mDeletedFiles.get(elapsedMillis));
+            }
+        }
+    }
+
+    // Thermal event received from vendor thermal management subsystem
+    private static final class ThermalEventListener extends IThermalEventListener.Stub {
+        @Override
+        public void notifyThrottling(Temperature temp) {
+            StatsLog.write(StatsLog.THERMAL_THROTTLING_SEVERITY_STATE_CHANGED, temp.getType(),
+                    temp.getName(), (int) (temp.getValue() * 10), temp.getStatus());
+        }
+    }
+
+    private static final class ConnectivityStatsCallback extends
+            ConnectivityManager.NetworkCallback {
+        @Override
+        public void onAvailable(Network network) {
+            StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
+                    StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__CONNECTED);
+        }
+
+        @Override
+        public void onLost(Network network) {
+            StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
+                    StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__DISCONNECTED);
+        }
+    }
+}
diff --git a/api/current.txt b/api/current.txt
index b4d110e..e6e2b40 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -2833,6 +2833,7 @@
     method public final android.accessibilityservice.AccessibilityServiceInfo getServiceInfo();
     method @NonNull public final android.accessibilityservice.AccessibilityService.SoftKeyboardController getSoftKeyboardController();
     method public java.util.List<android.view.accessibility.AccessibilityWindowInfo> getWindows();
+    method @NonNull public final android.util.SparseArray<java.util.List<android.view.accessibility.AccessibilityWindowInfo>> getWindowsOnAllDisplays();
     method public abstract void onAccessibilityEvent(android.view.accessibility.AccessibilityEvent);
     method public final android.os.IBinder onBind(android.content.Intent);
     method @Deprecated protected boolean onGesture(int);
@@ -6362,6 +6363,7 @@
     method public android.view.WindowAnimationFrameStats getWindowAnimationFrameStats();
     method public android.view.WindowContentFrameStats getWindowContentFrameStats(int);
     method public java.util.List<android.view.accessibility.AccessibilityWindowInfo> getWindows();
+    method @NonNull public android.util.SparseArray<java.util.List<android.view.accessibility.AccessibilityWindowInfo>> getWindowsOnAllDisplays();
     method public void grantRuntimePermission(String, String);
     method public void grantRuntimePermissionAsUser(String, String, android.os.UserHandle);
     method public boolean injectInputEvent(android.view.InputEvent, boolean);
@@ -6799,6 +6801,7 @@
     method public boolean isResetPasswordTokenActive(android.content.ComponentName);
     method public boolean isSecurityLoggingEnabled(@Nullable android.content.ComponentName);
     method public boolean isUninstallBlocked(@Nullable android.content.ComponentName, String);
+    method public boolean isUniqueDeviceAttestationSupported();
     method public boolean isUsingUnifiedPassword(@NonNull android.content.ComponentName);
     method public void lockNow();
     method public void lockNow(int);
@@ -6980,6 +6983,7 @@
     field public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 1; // 0x1
     field public static final int ID_TYPE_BASE_INFO = 1; // 0x1
     field public static final int ID_TYPE_IMEI = 4; // 0x4
+    field public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16; // 0x10
     field public static final int ID_TYPE_MEID = 8; // 0x8
     field public static final int ID_TYPE_SERIAL = 2; // 0x2
     field public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1; // 0x1
@@ -9675,6 +9679,7 @@
     field public static final String QUERY_ARG_SORT_COLLATION = "android:query-arg-sort-collation";
     field public static final String QUERY_ARG_SORT_COLUMNS = "android:query-arg-sort-columns";
     field public static final String QUERY_ARG_SORT_DIRECTION = "android:query-arg-sort-direction";
+    field public static final String QUERY_ARG_SORT_LOCALE = "android:query-arg-sort-locale";
     field public static final String QUERY_ARG_SQL_SELECTION = "android:query-arg-sql-selection";
     field public static final String QUERY_ARG_SQL_SELECTION_ARGS = "android:query-arg-sql-selection-args";
     field public static final String QUERY_ARG_SQL_SORT_ORDER = "android:query-arg-sql-sort-order";
@@ -10411,6 +10416,7 @@
     field public static final String ACTION_VOICE_COMMAND = "android.intent.action.VOICE_COMMAND";
     field @Deprecated public static final String ACTION_WALLPAPER_CHANGED = "android.intent.action.WALLPAPER_CHANGED";
     field public static final String ACTION_WEB_SEARCH = "android.intent.action.WEB_SEARCH";
+    field public static final String CATEGORY_ACCESSIBILITY_SHORTCUT_TARGET = "android.intent.category.ACCESSIBILITY_SHORTCUT_TARGET";
     field public static final String CATEGORY_ALTERNATIVE = "android.intent.category.ALTERNATIVE";
     field public static final String CATEGORY_APP_BROWSER = "android.intent.category.APP_BROWSER";
     field public static final String CATEGORY_APP_CALCULATOR = "android.intent.category.APP_CALCULATOR";
@@ -11392,7 +11398,7 @@
     method public abstract void onPackageRemoved(String, android.os.UserHandle);
     method public abstract void onPackagesAvailable(String[], android.os.UserHandle, boolean);
     method public void onPackagesSuspended(String[], android.os.UserHandle);
-    method public void onPackagesSuspended(String[], android.os.UserHandle, @Nullable android.os.Bundle);
+    method @Deprecated public void onPackagesSuspended(String[], android.os.UserHandle, @Nullable android.os.Bundle);
     method public abstract void onPackagesUnavailable(String[], android.os.UserHandle, boolean);
     method public void onPackagesUnsuspended(String[], android.os.UserHandle);
     method public void onShortcutsChanged(@NonNull String, @NonNull java.util.List<android.content.pm.ShortcutInfo>, @NonNull android.os.UserHandle);
@@ -11905,6 +11911,7 @@
     field public static final int SIGNATURE_NO_MATCH = -3; // 0xfffffffd
     field public static final int SIGNATURE_SECOND_NOT_SIGNED = -2; // 0xfffffffe
     field public static final int SIGNATURE_UNKNOWN_PACKAGE = -4; // 0xfffffffc
+    field public static final int SYNCHRONOUS = 2; // 0x2
     field public static final int VERIFICATION_ALLOW = 1; // 0x1
     field public static final int VERIFICATION_REJECT = -1; // 0xffffffff
     field public static final int VERSION_CODE_HIGHEST = -1; // 0xffffffff
@@ -23089,8 +23096,9 @@
 
   public class LocationManager {
     method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean addGpsStatusListener(android.location.GpsStatus.Listener);
-    method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean addNmeaListener(@NonNull android.location.OnNmeaMessageListener);
+    method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean addNmeaListener(@NonNull android.location.OnNmeaMessageListener);
     method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean addNmeaListener(@NonNull android.location.OnNmeaMessageListener, @Nullable android.os.Handler);
+    method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean addNmeaListener(@NonNull java.util.concurrent.Executor, @NonNull android.location.OnNmeaMessageListener);
     method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void addProximityAlert(double, double, float, long, @NonNull android.app.PendingIntent);
     method public void addTestProvider(@NonNull String, boolean, boolean, boolean, boolean, boolean, boolean, boolean, int, int);
     method @Deprecated public void clearTestProviderEnabled(@NonNull String);
@@ -23107,12 +23115,15 @@
     method @NonNull public java.util.List<java.lang.String> getProviders(@NonNull android.location.Criteria, boolean);
     method public boolean isLocationEnabled();
     method public boolean isProviderEnabled(@NonNull String);
-    method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssMeasurementsCallback(@NonNull android.location.GnssMeasurementsEvent.Callback);
+    method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssMeasurementsCallback(@NonNull android.location.GnssMeasurementsEvent.Callback);
     method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssMeasurementsCallback(@NonNull android.location.GnssMeasurementsEvent.Callback, @Nullable android.os.Handler);
-    method public boolean registerGnssNavigationMessageCallback(@NonNull android.location.GnssNavigationMessage.Callback);
+    method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssMeasurementsCallback(@NonNull java.util.concurrent.Executor, @NonNull android.location.GnssMeasurementsEvent.Callback);
+    method @Deprecated public boolean registerGnssNavigationMessageCallback(@NonNull android.location.GnssNavigationMessage.Callback);
     method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssNavigationMessageCallback(@NonNull android.location.GnssNavigationMessage.Callback, @Nullable android.os.Handler);
-    method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssStatusCallback(@NonNull android.location.GnssStatus.Callback);
+    method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssNavigationMessageCallback(@NonNull java.util.concurrent.Executor, @NonNull android.location.GnssNavigationMessage.Callback);
+    method @Deprecated @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssStatusCallback(@NonNull android.location.GnssStatus.Callback);
     method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssStatusCallback(@NonNull android.location.GnssStatus.Callback, @Nullable android.os.Handler);
+    method @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) public boolean registerGnssStatusCallback(@NonNull java.util.concurrent.Executor, @NonNull android.location.GnssStatus.Callback);
     method @Deprecated public void removeGpsStatusListener(android.location.GpsStatus.Listener);
     method public void removeNmeaListener(@NonNull android.location.OnNmeaMessageListener);
     method @RequiresPermission(anyOf={"android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"}, apis="..22") public void removeProximityAlert(@NonNull android.app.PendingIntent);
@@ -23121,13 +23132,15 @@
     method public void removeUpdates(@NonNull android.app.PendingIntent);
     method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull String, long, float, @NonNull android.location.LocationListener);
     method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull String, long, float, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull String, long, float, @NonNull java.util.concurrent.Executor, @NonNull android.location.LocationListener);
     method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(long, float, @NonNull android.location.Criteria, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(long, float, @NonNull android.location.Criteria, @NonNull java.util.concurrent.Executor, @NonNull android.location.LocationListener);
     method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull String, long, float, @NonNull android.app.PendingIntent);
     method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(long, float, @NonNull android.location.Criteria, @NonNull android.app.PendingIntent);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull String, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull android.location.Criteria, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull String, @NonNull android.app.PendingIntent);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull android.location.Criteria, @NonNull android.app.PendingIntent);
+    method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull String, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
+    method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull android.location.Criteria, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
+    method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull String, @NonNull android.app.PendingIntent);
+    method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestSingleUpdate(@NonNull android.location.Criteria, @NonNull android.app.PendingIntent);
     method public boolean sendExtraCommand(@NonNull String, @NonNull String, @Nullable android.os.Bundle);
     method public void setTestProviderEnabled(@NonNull String, boolean);
     method public void setTestProviderLocation(@NonNull String, @NonNull android.location.Location);
@@ -23955,6 +23968,7 @@
     ctor public ExifInterface(@NonNull String) throws java.io.IOException;
     ctor public ExifInterface(@NonNull java.io.FileDescriptor) throws java.io.IOException;
     ctor public ExifInterface(@NonNull java.io.InputStream) throws java.io.IOException;
+    method @NonNull public static android.media.ExifInterface fromStandalone(@NonNull java.io.InputStream) throws java.io.IOException;
     method public double getAltitude(double);
     method @Nullable public String getAttribute(@NonNull String);
     method @Nullable public byte[] getAttributeBytes(@NonNull String);
@@ -25373,6 +25387,7 @@
     method public android.graphics.Bitmap getFrameAtIndex(int, @NonNull android.media.MediaMetadataRetriever.BitmapParams);
     method public android.graphics.Bitmap getFrameAtIndex(int);
     method public android.graphics.Bitmap getFrameAtTime(long, int);
+    method public android.graphics.Bitmap getFrameAtTime(long, int, @NonNull android.media.MediaMetadataRetriever.BitmapParams);
     method public android.graphics.Bitmap getFrameAtTime(long);
     method public android.graphics.Bitmap getFrameAtTime();
     method @NonNull public java.util.List<android.graphics.Bitmap> getFramesAtIndex(int, int, @NonNull android.media.MediaMetadataRetriever.BitmapParams);
@@ -25382,6 +25397,7 @@
     method public android.graphics.Bitmap getPrimaryImage(@NonNull android.media.MediaMetadataRetriever.BitmapParams);
     method public android.graphics.Bitmap getPrimaryImage();
     method public android.graphics.Bitmap getScaledFrameAtTime(long, int, int, int);
+    method public android.graphics.Bitmap getScaledFrameAtTime(long, int, int, int, @NonNull android.media.MediaMetadataRetriever.BitmapParams);
     method public void release();
     method public void setDataSource(String) throws java.lang.IllegalArgumentException;
     method public void setDataSource(String, java.util.Map<java.lang.String,java.lang.String>) throws java.lang.IllegalArgumentException;
@@ -28795,6 +28811,7 @@
     method @Nullable public String getPrivateDnsServerName();
     method @NonNull public java.util.List<android.net.RouteInfo> getRoutes();
     method public boolean isPrivateDnsActive();
+    method public boolean isWakeOnLanSupported();
     method public void setDnsServers(@NonNull java.util.Collection<java.net.InetAddress>);
     method public void setDomains(@Nullable String);
     method public void setHttpProxy(@Nullable android.net.ProxyInfo);
@@ -29463,7 +29480,8 @@
   }
 
   public class AudioGroup {
-    ctor public AudioGroup();
+    ctor @Deprecated public AudioGroup();
+    ctor public AudioGroup(@Nullable android.content.Context);
     method public void clear();
     method public int getMode();
     method public android.net.rtp.AudioStream[] getStreams();
@@ -40789,6 +40807,7 @@
     field public static final String EXTRA_KEY_ALIAS = "android.security.extra.KEY_ALIAS";
     field public static final String EXTRA_NAME = "name";
     field public static final String EXTRA_PKCS12 = "PKCS12";
+    field public static final String KEY_ALIAS_SELECTION_DENIED = "alias-selection-denied-ef829e15-210a-409d-96c9-ee684fc41972";
   }
 
   public interface KeyChainAliasCallback {
@@ -43161,6 +43180,7 @@
     field public static final String EXTRA_SILENT_RINGING_REQUESTED = "android.telecom.extra.SILENT_RINGING_REQUESTED";
     field public static final String EXTRA_SUGGESTED_PHONE_ACCOUNTS = "android.telecom.extra.SUGGESTED_PHONE_ACCOUNTS";
     field public static final int STATE_ACTIVE = 4; // 0x4
+    field public static final int STATE_AUDIO_PROCESSING = 12; // 0xc
     field public static final int STATE_CONNECTING = 9; // 0x9
     field public static final int STATE_DIALING = 1; // 0x1
     field public static final int STATE_DISCONNECTED = 7; // 0x7
@@ -43170,6 +43190,7 @@
     field public static final int STATE_PULLING_CALL = 11; // 0xb
     field public static final int STATE_RINGING = 2; // 0x2
     field public static final int STATE_SELECT_PHONE_ACCOUNT = 8; // 0x8
+    field public static final int STATE_SIMULATED_RINGING = 13; // 0xd
   }
 
   public abstract static class Call.Callback {
@@ -44281,6 +44302,7 @@
     field public static final String KEY_USE_HFA_FOR_PROVISIONING_BOOL = "use_hfa_for_provisioning_bool";
     field public static final String KEY_USE_OTASP_FOR_PROVISIONING_BOOL = "use_otasp_for_provisioning_bool";
     field public static final String KEY_USE_RCS_PRESENCE_BOOL = "use_rcs_presence_bool";
+    field public static final String KEY_USE_RCS_SIP_OPTIONS_BOOL = "use_rcs_sip_options_bool";
     field public static final String KEY_VOICEMAIL_NOTIFICATION_PERSISTENT_BOOL = "voicemail_notification_persistent_bool";
     field public static final String KEY_VOICE_PRIVACY_DISABLE_UI_BOOL = "voice_privacy_disable_ui_bool";
     field public static final String KEY_VOLTE_REPLACEMENT_RAT_INT = "volte_replacement_rat_int";
@@ -45012,6 +45034,7 @@
     field public static final int DATA_ROAMING_DISABLE = 0; // 0x0
     field public static final int DATA_ROAMING_ENABLE = 1; // 0x1
     field public static final int DEFAULT_SUBSCRIPTION_ID = 2147483647; // 0x7fffffff
+    field public static final String EXTRA_SLOT_INDEX = "android.telephony.extra.SLOT_INDEX";
     field public static final String EXTRA_SUBSCRIPTION_INDEX = "android.telephony.extra.SUBSCRIPTION_INDEX";
     field public static final int INVALID_SIM_SLOT_INDEX = -1; // 0xffffffff
     field public static final int INVALID_SUBSCRIPTION_ID = -1; // 0xffffffff
@@ -45090,7 +45113,7 @@
     method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public String getMeid(int);
     method public String getMmsUAProfUrl();
     method public String getMmsUserAgent();
-    method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getNai();
+    method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public String getNai();
     method public String getNetworkCountryIso();
     method public String getNetworkOperator();
     method public String getNetworkOperatorName();
@@ -45149,6 +45172,7 @@
     method @RequiresPermission(android.Manifest.permission.CALL_PHONE) public void sendUssdRequest(String, android.telephony.TelephonyManager.UssdResponseCallback, android.os.Handler);
     method public void sendVisualVoicemailSms(String, int, String, android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setDataEnabled(boolean);
+    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int setForbiddenPlmns(@NonNull java.util.List<java.lang.String>);
     method public boolean setLine1NumberForDisplay(String, String);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setNetworkSelectionModeAutomatic();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setNetworkSelectionModeManual(String, boolean);
@@ -45163,6 +45187,7 @@
     method public void updateAvailableNetworks(@NonNull java.util.List<android.telephony.AvailableNetworkInfo>, @Nullable java.util.concurrent.Executor, @Nullable java.util.function.Consumer<java.lang.Integer>);
     field public static final String ACTION_CARRIER_MESSAGING_CLIENT_SERVICE = "android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE";
     field public static final String ACTION_CONFIGURE_VOICEMAIL = "android.telephony.action.CONFIGURE_VOICEMAIL";
+    field public static final String ACTION_MULTI_SIM_CONFIG_CHANGED = "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
     field public static final String ACTION_NETWORK_COUNTRY_CHANGED = "android.telephony.action.NETWORK_COUNTRY_CHANGED";
     field @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public static final String ACTION_PHONE_STATE_CHANGED = "android.intent.action.PHONE_STATE";
     field public static final String ACTION_RESPOND_VIA_MESSAGE = "android.intent.action.RESPOND_VIA_MESSAGE";
@@ -45203,6 +45228,7 @@
     field public static final String EXTRA_LAUNCH_VOICEMAIL_SETTINGS_INTENT = "android.telephony.extra.LAUNCH_VOICEMAIL_SETTINGS_INTENT";
     field public static final String EXTRA_NETWORK_COUNTRY = "android.telephony.extra.NETWORK_COUNTRY";
     field public static final String EXTRA_NOTIFICATION_COUNT = "android.telephony.extra.NOTIFICATION_COUNT";
+    field public static final String EXTRA_NUM_OF_ACTIVE_SIM_SUPPORTED = "android.telephony.extra.NUM_OF_ACTIVE_SIM_SUPPORTED";
     field public static final String EXTRA_PHONE_ACCOUNT_HANDLE = "android.telephony.extra.PHONE_ACCOUNT_HANDLE";
     field public static final String EXTRA_SPECIFIC_CARRIER_ID = "android.telephony.extra.SPECIFIC_CARRIER_ID";
     field public static final String EXTRA_SPECIFIC_CARRIER_NAME = "android.telephony.extra.SPECIFIC_CARRIER_NAME";
@@ -47114,7 +47140,9 @@
   public abstract class ReplacementSpan extends android.text.style.MetricAffectingSpan {
     ctor public ReplacementSpan();
     method public abstract void draw(@NonNull android.graphics.Canvas, CharSequence, @IntRange(from=0) int, @IntRange(from=0) int, float, int, int, int, @NonNull android.graphics.Paint);
+    method @Nullable public CharSequence getContentDescription();
     method public abstract int getSize(@NonNull android.graphics.Paint, CharSequence, @IntRange(from=0) int, @IntRange(from=0) int, @Nullable android.graphics.Paint.FontMetricsInt);
+    method public void setContentDescription(@Nullable CharSequence);
     method public void updateDrawState(android.text.TextPaint);
     method public void updateMeasureState(android.text.TextPaint);
   }
@@ -47888,6 +47916,7 @@
     ctor public ArraySet(int);
     ctor public ArraySet(android.util.ArraySet<E>);
     ctor public ArraySet(java.util.Collection<? extends E>);
+    ctor public ArraySet(@Nullable E[]);
     method public boolean add(E);
     method public void addAll(android.util.ArraySet<? extends E>);
     method public boolean addAll(java.util.Collection<? extends E>);
@@ -53041,7 +53070,8 @@
     method @NonNull public android.view.autofill.AutofillId newAutofillId(@NonNull android.view.autofill.AutofillId, long);
     method @NonNull public final android.view.ViewStructure newViewStructure(@NonNull android.view.View);
     method @NonNull public final android.view.ViewStructure newVirtualViewStructure(@NonNull android.view.autofill.AutofillId, long);
-    method public final void notifySessionLifecycle(boolean);
+    method public final void notifySessionPaused();
+    method public final void notifySessionResumed();
     method public final void notifyViewAppeared(@NonNull android.view.ViewStructure);
     method public final void notifyViewDisappeared(@NonNull android.view.autofill.AutofillId);
     method public final void notifyViewTextChanged(@NonNull android.view.autofill.AutofillId, @Nullable CharSequence);
@@ -57394,7 +57424,7 @@
     method public boolean onPrivateIMECommand(String, android.os.Bundle);
     method public void onRestoreInstanceState(android.os.Parcelable);
     method public android.os.Parcelable onSaveInstanceState();
-    method protected void onSelectionChanged(int, int);
+    method @CallSuper protected void onSelectionChanged(int, int);
     method protected void onTextChanged(CharSequence, int, int, int);
     method public boolean onTextContextMenuItem(int);
     method public void removeTextChangedListener(android.text.TextWatcher);
diff --git a/api/system-current.txt b/api/system-current.txt
index 283433e..4db7f4a 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -24,6 +24,7 @@
     field public static final String BACKUP = "android.permission.BACKUP";
     field public static final String BIND_ATTENTION_SERVICE = "android.permission.BIND_ATTENTION_SERVICE";
     field public static final String BIND_AUGMENTED_AUTOFILL_SERVICE = "android.permission.BIND_AUGMENTED_AUTOFILL_SERVICE";
+    field public static final String BIND_CELL_BROADCAST_SERVICE = "android.permission.BIND_CELL_BROADCAST_SERVICE";
     field @Deprecated public static final String BIND_CONNECTION_SERVICE = "android.permission.BIND_CONNECTION_SERVICE";
     field public static final String BIND_CONTENT_CAPTURE_SERVICE = "android.permission.BIND_CONTENT_CAPTURE_SERVICE";
     field public static final String BIND_CONTENT_SUGGESTIONS_SERVICE = "android.permission.BIND_CONTENT_SUGGESTIONS_SERVICE";
@@ -1382,6 +1383,7 @@
     field public static final String STATS_MANAGER = "stats";
     field public static final String STATUS_BAR_SERVICE = "statusbar";
     field public static final String SYSTEM_UPDATE_SERVICE = "system_update";
+    field public static final String TELEPHONY_REGISTRY_SERVICE = "telephony_registry";
     field public static final String VR_SERVICE = "vrmanager";
     field @Deprecated public static final String WIFI_RTT_SERVICE = "rttmanager";
     field public static final String WIFI_SCANNING_SERVICE = "wifiscanner";
@@ -1663,7 +1665,8 @@
     field public static final int FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT = 4096; // 0x1000
     field public static final int FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT = 8192; // 0x2000
     field public static final int FLAG_PERMISSION_REVIEW_REQUIRED = 64; // 0x40
-    field public static final int FLAG_PERMISSION_REVOKE_ON_UPGRADE = 8; // 0x8
+    field public static final int FLAG_PERMISSION_REVOKED_COMPAT = 8; // 0x8
+    field @Deprecated public static final int FLAG_PERMISSION_REVOKE_ON_UPGRADE = 8; // 0x8
     field public static final int FLAG_PERMISSION_SYSTEM_FIXED = 16; // 0x10
     field public static final int FLAG_PERMISSION_USER_FIXED = 2; // 0x2
     field public static final int FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED = 512; // 0x200
@@ -1731,7 +1734,7 @@
     method public void onPermissionsChanged(int);
   }
 
-  @IntDef(prefix={"FLAG_PERMISSION_"}, value={android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET, android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE, android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_INSTALLER_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_APPLY_RESTRICTION, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_ROLE}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface PackageManager.PermissionFlags {
+  @IntDef(prefix={"FLAG_PERMISSION_"}, value={android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET, android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE, android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_INSTALLER_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_APPLY_RESTRICTION, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_ROLE, android.content.pm.PackageManager.FLAG_PERMISSION_REVOKED_COMPAT}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface PackageManager.PermissionFlags {
   }
 
   public class PermissionGroupInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
@@ -3429,8 +3432,9 @@
     method public boolean isProviderEnabledForUser(@NonNull String, @NonNull android.os.UserHandle);
     method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public boolean isProviderPackage(@NonNull String);
     method @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE) public boolean registerGnssBatchedLocationCallback(long, boolean, @NonNull android.location.BatchedLocationCallback, @Nullable android.os.Handler);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull android.location.LocationRequest, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull android.location.LocationRequest, @NonNull android.app.PendingIntent);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull java.util.concurrent.Executor, @NonNull android.location.LocationListener);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE) public void setExtraLocationControllerPackage(@Nullable String);
     method @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE) public void setExtraLocationControllerPackageEnabled(boolean);
     method @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public void setLocationEnabledForUser(boolean, @NonNull android.os.UserHandle);
@@ -4721,7 +4725,7 @@
     method @RequiresPermission("android.permission.WIFI_UPDATE_USABILITY_STATS_SCORE") public void addOnWifiUsabilityStatsListener(@NonNull java.util.concurrent.Executor, @NonNull android.net.wifi.WifiManager.OnWifiUsabilityStatsListener);
     method @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD, "android.permission.NETWORK_STACK"}) public void connect(@NonNull android.net.wifi.WifiConfiguration, @Nullable android.net.wifi.WifiManager.ActionListener);
     method @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD, "android.permission.NETWORK_STACK"}) public void connect(int, @Nullable android.net.wifi.WifiManager.ActionListener);
-    method @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD, "android.permission.NETWORK_STACK"}) public void disable(int, @Nullable android.net.wifi.WifiManager.ActionListener);
+    method @Deprecated @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD, "android.permission.NETWORK_STACK"}) public void disable(int, @Nullable android.net.wifi.WifiManager.ActionListener);
     method @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD, "android.permission.NETWORK_STACK"}) public void forget(int, @Nullable android.net.wifi.WifiManager.ActionListener);
     method @NonNull @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD}) public java.util.List<android.util.Pair<android.net.wifi.WifiConfiguration,java.util.Map<java.lang.Integer,java.util.List<android.net.wifi.ScanResult>>>> getAllMatchingWifiConfigs(@NonNull java.util.List<android.net.wifi.ScanResult>);
     method @NonNull @RequiresPermission(anyOf={"android.permission.NETWORK_SETTINGS", android.Manifest.permission.NETWORK_SETUP_WIZARD}) public java.util.Map<android.net.wifi.hotspot2.OsuProvider,java.util.List<android.net.wifi.ScanResult>> getMatchingOsuProviders(@Nullable java.util.List<android.net.wifi.ScanResult>);
@@ -5516,7 +5520,7 @@
   public class UpdateEngine {
     ctor public UpdateEngine();
     method public void applyPayload(String, long, long, String[]);
-    method public void applyPayload(@NonNull java.io.FileDescriptor, long, long, @NonNull String[]);
+    method public void applyPayload(@NonNull android.os.ParcelFileDescriptor, long, long, @NonNull String[]);
     method public boolean bind(android.os.UpdateEngineCallback, android.os.Handler);
     method public boolean bind(android.os.UpdateEngineCallback);
     method public void cancel();
@@ -5680,6 +5684,14 @@
 
 }
 
+package android.os.telephony {
+
+  public class TelephonyRegistryManager {
+    method public void notifyCarrierNetworkChange(boolean);
+  }
+
+}
+
 package android.permission {
 
   public final class PermissionControllerManager {
@@ -5890,7 +5902,8 @@
     field public static final String NAMESPACE_RUNTIME_NATIVE = "runtime_native";
     field public static final String NAMESPACE_RUNTIME_NATIVE_BOOT = "runtime_native_boot";
     field public static final String NAMESPACE_SCHEDULER = "scheduler";
-    field public static final String NAMESPACE_STORAGE = "storage";
+    field @Deprecated public static final String NAMESPACE_STORAGE = "storage";
+    field public static final String NAMESPACE_STORAGE_NATIVE_BOOT = "storage_native_boot";
     field public static final String NAMESPACE_SYSTEMUI = "systemui";
     field public static final String NAMESPACE_TELEPHONY = "telephony";
     field public static final String NAMESPACE_TEXTCLASSIFIER = "textclassifier";
@@ -6170,6 +6183,7 @@
     field public static final int ID_TYPE_IMEI = 2; // 0x2
     field public static final int ID_TYPE_MEID = 3; // 0x3
     field public static final int ID_TYPE_SERIAL = 1; // 0x1
+    field public static final int USE_INDIVIDUAL_ATTESTATION = 4; // 0x4
   }
 
   public class DeviceIdAttestationException extends java.lang.Exception {
@@ -6348,6 +6362,7 @@
     method public android.os.IBinder onBind(android.content.Intent);
     method @Nullable public float[][] onCalculateScores(@NonNull java.util.List<android.view.autofill.AutofillValue>, @NonNull java.util.List<java.lang.String>, @NonNull java.util.List<java.lang.String>, @Nullable String, @Nullable android.os.Bundle, @Nullable java.util.Map, @Nullable java.util.Map);
     method @Deprecated @Nullable public float[][] onGetScores(@Nullable String, @Nullable android.os.Bundle, @NonNull java.util.List<android.view.autofill.AutofillValue>, @NonNull java.util.List<java.lang.String>);
+    field public static final String REQUIRED_ALGORITHM_CREDIT_CARD = "CREDIT_CARD";
     field public static final String REQUIRED_ALGORITHM_EDIT_DISTANCE = "EDIT_DISTANCE";
     field public static final String REQUIRED_ALGORITHM_EXACT_MATCH = "EXACT_MATCH";
     field public static final String SERVICE_INTERFACE = "android.service.autofill.AutofillFieldClassificationService";
@@ -6542,7 +6557,8 @@
     method public abstract int onDeleteSubscription(int, String);
     method public android.service.euicc.DownloadSubscriptionResult onDownloadSubscription(int, @NonNull android.telephony.euicc.DownloadableSubscription, boolean, boolean, @Nullable android.os.Bundle);
     method @Deprecated public int onDownloadSubscription(int, @NonNull android.telephony.euicc.DownloadableSubscription, boolean, boolean);
-    method public abstract int onEraseSubscriptions(int);
+    method @Deprecated public abstract int onEraseSubscriptions(int);
+    method public int onEraseSubscriptionsWithOptions(int, @android.telephony.euicc.EuiccCardManager.ResetOption int);
     method public abstract android.service.euicc.GetDefaultDownloadableSubscriptionListResult onGetDefaultDownloadableSubscriptionList(int, boolean);
     method public abstract android.service.euicc.GetDownloadableSubscriptionMetadataResult onGetDownloadableSubscriptionMetadata(int, android.telephony.euicc.DownloadableSubscription, boolean);
     method public abstract String onGetEid(int);
@@ -6954,6 +6970,8 @@
 
   public final class Call {
     method @Deprecated public void addListener(android.telecom.Call.Listener);
+    method public void enterBackgroundAudioProcessing();
+    method public void exitBackgroundAudioProcessing(boolean);
     method @Deprecated public void removeListener(android.telecom.Call.Listener);
     field @Deprecated public static final int STATE_PRE_DIAL_WAIT = 8; // 0x8
   }
@@ -6962,6 +6980,10 @@
     ctor @Deprecated public Call.Listener();
   }
 
+  public static class CallScreeningService.CallResponse.Builder {
+    method public android.telecom.CallScreeningService.CallResponse.Builder setShouldScreenCallFurther(boolean);
+  }
+
   public abstract class Conference extends android.telecom.Conferenceable {
     method @Deprecated public final android.telecom.AudioState getAudioState();
     method @Deprecated public final long getConnectTimeMillis();
@@ -7284,6 +7306,14 @@
     method @NonNull public android.telephony.CarrierRestrictionRules.Builder setMultiSimPolicy(int);
   }
 
+  public abstract class CellBroadcastService extends android.app.Service {
+    ctor public CellBroadcastService();
+    method @CallSuper public android.os.IBinder onBind(android.content.Intent);
+    method public abstract void onCdmaCellBroadcastSms(int, byte[]);
+    method public abstract void onGsmCellBroadcastSms(int, byte[]);
+    field public static final String CELL_BROADCAST_SERVICE_INTERFACE = "android.telephony.CellBroadcastService";
+  }
+
   public final class DataFailCause {
     field public static final int ACCESS_ATTEMPT_ALREADY_IN_PROGRESS = 2219; // 0x8ab
     field public static final int ACCESS_BLOCK = 2087; // 0x827
@@ -7846,6 +7876,8 @@
     method public void onCallAttributesChanged(@NonNull android.telephony.CallAttributes);
     method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onCallDisconnectCauseChanged(int, int);
     method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onImsCallDisconnectCauseChanged(@NonNull android.telephony.ims.ImsReasonInfo);
+    method public void onOutgoingEmergencyCall(@NonNull android.telephony.emergency.EmergencyNumber);
+    method public void onOutgoingEmergencySms(@NonNull android.telephony.emergency.EmergencyNumber);
     method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseCallStateChanged(@NonNull android.telephony.PreciseCallState);
     method @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public void onPreciseDataConnectionStateChanged(@NonNull android.telephony.PreciseDataConnectionState);
     method public void onRadioPowerStateChanged(int);
@@ -7854,8 +7886,8 @@
     field public static final int LISTEN_CALL_ATTRIBUTES_CHANGED = 67108864; // 0x4000000
     field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_CALL_DISCONNECT_CAUSES = 33554432; // 0x2000000
     field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES = 134217728; // 0x8000000
-    field @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public static final int LISTEN_OUTGOING_CALL_EMERGENCY_NUMBER = 268435456; // 0x10000000
-    field @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public static final int LISTEN_OUTGOING_SMS_EMERGENCY_NUMBER = 536870912; // 0x20000000
+    field @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public static final int LISTEN_OUTGOING_EMERGENCY_CALL = 268435456; // 0x10000000
+    field @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public static final int LISTEN_OUTGOING_EMERGENCY_SMS = 536870912; // 0x20000000
     field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_CALL_STATE = 2048; // 0x800
     field @RequiresPermission("android.permission.READ_PRECISE_PHONE_STATE") public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE = 4096; // 0x1000
     field public static final int LISTEN_RADIO_POWER_STATE_CHANGED = 8388608; // 0x800000
@@ -8083,7 +8115,7 @@
   }
 
   public final class SmsCbMessage implements android.os.Parcelable {
-    ctor public SmsCbMessage(int, int, int, @NonNull android.telephony.SmsCbLocation, int, @Nullable String, @Nullable String, int, @Nullable android.telephony.SmsCbEtwsInfo, @Nullable android.telephony.SmsCbCmasInfo);
+    ctor public SmsCbMessage(int, int, int, @NonNull android.telephony.SmsCbLocation, int, @Nullable String, @Nullable String, int, @Nullable android.telephony.SmsCbEtwsInfo, @Nullable android.telephony.SmsCbCmasInfo, int);
     method @NonNull public static android.telephony.SmsCbMessage createFromCursor(@NonNull android.database.Cursor);
     method public int describeContents();
     method @Nullable public android.telephony.SmsCbCmasInfo getCmasWarningInfo();
@@ -8098,6 +8130,7 @@
     method public long getReceivedTime();
     method public int getSerialNumber();
     method public int getServiceCategory();
+    method public int getSlotIndex();
     method public boolean isCmasMessage();
     method public boolean isEmergencyMessage();
     method public boolean isEtwsMessage();
@@ -8203,7 +8236,7 @@
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean disableDataConnectivity();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean enableDataConnectivity();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean enableModemForSlot(int, boolean);
-    method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void enableVideoCalling(boolean);
+    method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void enableVideoCalling(boolean);
     method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getAidForAppType(int);
     method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.List<android.service.carrier.CarrierIdentifier> getAllowedCarriers(int);
     method public java.util.List<java.lang.String> getCarrierPackageNamesForIntent(android.content.Intent);
@@ -8224,6 +8257,7 @@
     method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getIsimIst();
     method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.Map<java.lang.Integer,java.lang.Integer> getLogicalToPhysicalSlotMapping();
     method public static long getMaxNumberVerificationTimeoutMillis();
+    method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getNetworkCountryIso(int);
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public long getPreferredNetworkTypeBitmask();
     method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public int getRadioPowerState();
     method public int getSimApplicationState();
@@ -8244,13 +8278,14 @@
     method @Nullable @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String iccTransmitApduLogicalChannelBySlot(int, int, int, int, int, int, int, @Nullable String);
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isApplicationOnUicc(int);
     method public boolean isDataConnectivityPossible();
+    method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isDataEnabledForApn(int);
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isEmergencyAssistanceEnabled();
     method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isIdle();
     method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isOffhook();
     method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isPotentialEmergencyNumber(@NonNull String);
     method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isRadioOn();
     method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isRinging();
-    method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isVideoCallingEnabled();
+    method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isVideoCallingEnabled();
     method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public boolean isVisualVoicemailEnabled(android.telecom.PhoneAccountHandle);
     method public boolean needsOtaServiceProvisioning();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean rebootRadio();
@@ -8367,6 +8402,27 @@
 
 }
 
+package android.telephony.cdma {
+
+  public final class CdmaSmsCbProgramData implements android.os.Parcelable {
+    method public int describeContents();
+    method public int getCategory();
+    method public int getOperation();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final int CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY = 4099; // 0x1003
+    field public static final int CATEGORY_CMAS_EXTREME_THREAT = 4097; // 0x1001
+    field public static final int CATEGORY_CMAS_LAST_RESERVED_VALUE = 4351; // 0x10ff
+    field public static final int CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT = 4096; // 0x1000
+    field public static final int CATEGORY_CMAS_SEVERE_THREAT = 4098; // 0x1002
+    field public static final int CATEGORY_CMAS_TEST_MESSAGE = 4100; // 0x1004
+    field @NonNull public static final android.os.Parcelable.Creator<android.telephony.cdma.CdmaSmsCbProgramData> CREATOR;
+    field public static final int OPERATION_ADD_CATEGORY = 1; // 0x1
+    field public static final int OPERATION_CLEAR_CATEGORIES = 2; // 0x2
+    field public static final int OPERATION_DELETE_CATEGORY = 0; // 0x0
+  }
+
+}
+
 package android.telephony.data {
 
   public final class DataCallResponse implements android.os.Parcelable {
@@ -8565,7 +8621,8 @@
 
   public class EuiccManager {
     method @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS) public void continueOperation(android.content.Intent, android.os.Bundle);
-    method @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS) public void eraseSubscriptions(android.app.PendingIntent);
+    method @Deprecated @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS) public void eraseSubscriptions(@NonNull android.app.PendingIntent);
+    method @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS) public void eraseSubscriptionsWithOptions(@android.telephony.euicc.EuiccCardManager.ResetOption int, @NonNull android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS) public void getDefaultDownloadableSubscriptionList(android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS) public void getDownloadableSubscriptionMetadata(android.telephony.euicc.DownloadableSubscription, android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS) public int getOtaStatus();
diff --git a/api/test-current.txt b/api/test-current.txt
index 34312f6..70837a8 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -5,6 +5,7 @@
     field public static final String ACCESS_NOTIFICATIONS = "android.permission.ACCESS_NOTIFICATIONS";
     field public static final String ACTIVITY_EMBEDDING = "android.permission.ACTIVITY_EMBEDDING";
     field public static final String APPROVE_INCIDENT_REPORTS = "android.permission.APPROVE_INCIDENT_REPORTS";
+    field public static final String BIND_CELL_BROADCAST_SERVICE = "android.permission.BIND_CELL_BROADCAST_SERVICE";
     field public static final String BRIGHTNESS_SLIDER_USAGE = "android.permission.BRIGHTNESS_SLIDER_USAGE";
     field public static final String CHANGE_APP_IDLE_STATE = "android.permission.CHANGE_APP_IDLE_STATE";
     field public static final String CLEAR_APP_USER_DATA = "android.permission.CLEAR_APP_USER_DATA";
@@ -21,6 +22,10 @@
     field public static final String WRITE_OBB = "android.permission.WRITE_OBB";
   }
 
+  public static final class Manifest.permission_group {
+    field public static final String UNDEFINED = "android.permission-group.UNDEFINED";
+  }
+
   public static final class R.bool {
     field public static final int config_perDisplayFocusEnabled = 17891332; // 0x1110004
   }
@@ -739,7 +744,8 @@
     field public static final int FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT = 4096; // 0x1000
     field public static final int FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT = 8192; // 0x2000
     field public static final int FLAG_PERMISSION_REVIEW_REQUIRED = 64; // 0x40
-    field public static final int FLAG_PERMISSION_REVOKE_ON_UPGRADE = 8; // 0x8
+    field public static final int FLAG_PERMISSION_REVOKED_COMPAT = 8; // 0x8
+    field @Deprecated public static final int FLAG_PERMISSION_REVOKE_ON_UPGRADE = 8; // 0x8
     field public static final int FLAG_PERMISSION_REVOKE_WHEN_REQUESTED = 128; // 0x80
     field public static final int FLAG_PERMISSION_SYSTEM_FIXED = 16; // 0x10
     field public static final int FLAG_PERMISSION_USER_FIXED = 2; // 0x2
@@ -781,7 +787,7 @@
 
   public final class AssetManager implements java.lang.AutoCloseable {
     method @NonNull public String[] getApkPaths();
-    method @Nullable public java.util.Map<java.lang.String,java.lang.String> getOverlayableMap(String);
+    method @Nullable public String getOverlayablesToString(String);
   }
 
   public final class Configuration implements java.lang.Comparable<android.content.res.Configuration> android.os.Parcelable {
@@ -920,6 +926,10 @@
     field public static final int SESSION_OPERATION_MODE_VENDOR_START = 32768; // 0x8000
   }
 
+  public final class CameraManager {
+    method public String[] getCameraIdListNoLazy() throws android.hardware.camera2.CameraAccessException;
+  }
+
 }
 
 package android.hardware.display {
@@ -1084,8 +1094,9 @@
     method @NonNull public String[] getBackgroundThrottlingWhitelist();
     method @NonNull public String[] getIgnoreSettingsWhitelist();
     method @NonNull public java.util.List<android.location.LocationRequest> getTestProviderCurrentRequests(String);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull android.location.LocationRequest, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
-    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@NonNull android.location.LocationRequest, @NonNull android.app.PendingIntent);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull android.location.LocationListener, @Nullable android.os.Looper);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull java.util.concurrent.Executor, @NonNull android.location.LocationListener);
+    method @RequiresPermission(anyOf={android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}) public void requestLocationUpdates(@Nullable android.location.LocationRequest, @NonNull android.app.PendingIntent);
     method @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public void setLocationEnabledForUser(boolean, @NonNull android.os.UserHandle);
   }
 
@@ -2023,10 +2034,18 @@
   public final class UserHandle implements android.os.Parcelable {
     method public static int getAppId(int);
     method public int getIdentifier();
+    method public static int getUid(int, int);
+    method public static int getUserId(int);
     method public static boolean isApp(int);
+    method public static int myUserId();
+    method public static android.os.UserHandle of(int);
     field @NonNull public static final android.os.UserHandle ALL;
     field @NonNull public static final android.os.UserHandle CURRENT;
+    field public static final int MIN_SECONDARY_USER_ID = 10; // 0xa
     field @NonNull public static final android.os.UserHandle SYSTEM;
+    field public static final int USER_ALL = -1; // 0xffffffff
+    field public static final int USER_NULL = -10000; // 0xffffd8f0
+    field public static final int USER_SYSTEM = 0; // 0x0
   }
 
   public class UserManager {
@@ -2394,7 +2413,6 @@
     field public static final String LOCATION_ACCESS_CHECK_DELAY_MILLIS = "location_access_check_delay_millis";
     field public static final String LOCATION_ACCESS_CHECK_INTERVAL_MILLIS = "location_access_check_interval_millis";
     field public static final String NOTIFICATION_BADGING = "notification_badging";
-    field @Deprecated public static final String NOTIFICATION_BUBBLES = "notification_bubbles";
     field @RequiresPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) public static final String SYNC_PARENT_SOUNDS = "sync_parent_sounds";
     field public static final String USER_SETUP_COMPLETE = "user_setup_complete";
     field public static final String VOICE_INTERACTION_SERVICE = "voice_interaction_service";
@@ -2426,6 +2444,7 @@
     field public static final int ID_TYPE_IMEI = 2; // 0x2
     field public static final int ID_TYPE_MEID = 3; // 0x3
     field public static final int ID_TYPE_SERIAL = 1; // 0x1
+    field public static final int USE_INDIVIDUAL_ATTESTATION = 4; // 0x4
   }
 
   public class DeviceIdAttestationException extends java.lang.Exception {
@@ -2470,6 +2489,7 @@
   public abstract class AutofillFieldClassificationService extends android.app.Service {
     ctor public AutofillFieldClassificationService();
     method public android.os.IBinder onBind(android.content.Intent);
+    field public static final String REQUIRED_ALGORITHM_CREDIT_CARD = "CREDIT_CARD";
     field public static final String REQUIRED_ALGORITHM_EDIT_DISTANCE = "EDIT_DISTANCE";
     field public static final String REQUIRED_ALGORITHM_EXACT_MATCH = "EXACT_MATCH";
     field public static final String SERVICE_INTERFACE = "android.service.autofill.AutofillFieldClassificationService";
@@ -2760,10 +2780,19 @@
 
 package android.telecom {
 
+  public final class Call {
+    method public void enterBackgroundAudioProcessing();
+    method public void exitBackgroundAudioProcessing(boolean);
+  }
+
   public final class CallAudioState implements android.os.Parcelable {
     ctor public CallAudioState(boolean, int, int, @Nullable android.bluetooth.BluetoothDevice, @NonNull java.util.Collection<android.bluetooth.BluetoothDevice>);
   }
 
+  public static class CallScreeningService.CallResponse.Builder {
+    method public android.telecom.CallScreeningService.CallResponse.Builder setShouldScreenCallFurther(boolean);
+  }
+
   public abstract class Conference extends android.telecom.Conferenceable {
     method public android.telecom.Connection getPrimaryConnection();
   }
@@ -2879,6 +2908,13 @@
     method public static void setMinMatchForTest(int);
   }
 
+  public class PhoneStateListener {
+    method public void onOutgoingEmergencyCall(@NonNull android.telephony.emergency.EmergencyNumber);
+    method public void onOutgoingEmergencySms(@NonNull android.telephony.emergency.EmergencyNumber);
+    field @RequiresPermission("android.permission.READ_ACTIVE_EMERGENCY_SESSION") public static final int LISTEN_OUTGOING_EMERGENCY_CALL = 268435456; // 0x10000000
+    field @RequiresPermission("android.permission.READ_ACTIVE_EMERGENCY_SESSION") public static final int LISTEN_OUTGOING_EMERGENCY_SMS = 536870912; // 0x20000000
+  }
+
   public class ServiceState implements android.os.Parcelable {
     method public void addNetworkRegistrationInfo(android.telephony.NetworkRegistrationInfo);
     method public void setCdmaSystemAndNetworkId(int, int);
@@ -2903,6 +2939,7 @@
     method public int checkCarrierPrivilegesForPackage(String);
     method public int getCarrierIdListVersion();
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getLine1AlphaTag();
+    method @NonNull @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public String getNetworkCountryIso(int);
     method public android.util.Pair<java.lang.Integer,java.lang.Integer> getRadioHalVersion();
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void refreshUiccProfile();
     method @Deprecated public void setCarrierTestOverride(String, String, String, String, String, String, String);
@@ -2916,6 +2953,14 @@
 
 }
 
+package android.telephony.emergency {
+
+  public final class EmergencyNumber implements java.lang.Comparable<android.telephony.emergency.EmergencyNumber> android.os.Parcelable {
+    field public static final int EMERGENCY_NUMBER_SOURCE_TEST = 32; // 0x20
+  }
+
+}
+
 package android.telephony.mbms {
 
   public static class DownloadRequest.Builder {
@@ -3338,6 +3383,7 @@
   public class WindowlessViewRoot {
     ctor public WindowlessViewRoot(android.content.Context, android.view.Display, android.view.SurfaceControl);
     method public void addView(android.view.View, android.view.WindowManager.LayoutParams);
+    method public void relayout(android.view.WindowManager.LayoutParams);
   }
 
 }
diff --git a/cmds/idmap2/Android.bp b/cmds/idmap2/Android.bp
index d4d5871..4c77ba4 100644
--- a/cmds/idmap2/Android.bp
+++ b/cmds/idmap2/Android.bp
@@ -69,6 +69,7 @@
             static_libs: [
                 "libandroidfw",
                 "libbase",
+                "libcutils",
                 "libutils",
                 "libziparchive",
             ],
@@ -121,6 +122,7 @@
             static_libs: [
                 "libandroidfw",
                 "libbase",
+                "libcutils",
                 "libidmap2",
                 "liblog",
                 "libutils",
@@ -163,6 +165,7 @@
             static_libs: [
                 "libandroidfw",
                 "libbase",
+                "libcutils",
                 "libidmap2",
                 "liblog",
                 "libutils",
diff --git a/cmds/idmap2/idmap2/Create.cpp b/cmds/idmap2/idmap2/Create.cpp
index bb8d927..f482191 100644
--- a/cmds/idmap2/idmap2/Create.cpp
+++ b/cmds/idmap2/idmap2/Create.cpp
@@ -50,7 +50,7 @@
   std::string overlay_apk_path;
   std::string idmap_path;
   std::vector<std::string> policies;
-  bool ignore_overlayable;
+  bool ignore_overlayable = false;
 
   const CommandLineOptions opts =
       CommandLineOptions("idmap2 create")
diff --git a/cmds/idmap2/idmap2/Dump.cpp b/cmds/idmap2/idmap2/Dump.cpp
index 8716bf3..47f442a 100644
--- a/cmds/idmap2/idmap2/Dump.cpp
+++ b/cmds/idmap2/idmap2/Dump.cpp
@@ -39,7 +39,7 @@
 Result<Unit> Dump(const std::vector<std::string>& args) {
   SYSTRACE << "Dump " << args;
   std::string idmap_path;
-  bool verbose;
+  bool verbose = false;
 
   const CommandLineOptions opts =
       CommandLineOptions("idmap2 dump")
diff --git a/cmds/idmap2/idmap2/Scan.cpp b/cmds/idmap2/idmap2/Scan.cpp
index 053b7bc..d0530f2 100644
--- a/cmds/idmap2/idmap2/Scan.cpp
+++ b/cmds/idmap2/idmap2/Scan.cpp
@@ -178,6 +178,17 @@
       continue;
     }
 
+    // Note that conditional property enablement/exclusion only applies if
+    // the attribute is present. In its absence, all overlays are presumed enabled.
+    if (!overlay_info->requiredSystemPropertyName.empty()
+        && !overlay_info->requiredSystemPropertyValue.empty()) {
+      // if property set & equal to value, then include overlay - otherwise skip
+      if (android::base::GetProperty(overlay_info->requiredSystemPropertyName, "")
+          != overlay_info->requiredSystemPropertyValue) {
+        continue;
+      }
+    }
+
     std::vector<std::string> fulfilled_policies;
     if (!override_policies.empty()) {
       fulfilled_policies = override_policies;
diff --git a/cmds/idmap2/include/idmap2/ResourceUtils.h b/cmds/idmap2/include/idmap2/ResourceUtils.h
index 8797a78..9a0c2ab 100644
--- a/cmds/idmap2/include/idmap2/ResourceUtils.h
+++ b/cmds/idmap2/include/idmap2/ResourceUtils.h
@@ -30,6 +30,8 @@
 struct OverlayManifestInfo {
   std::string target_package;  // NOLINT(misc-non-private-member-variables-in-classes)
   std::string target_name;     // NOLINT(misc-non-private-member-variables-in-classes)
+  std::string requiredSystemPropertyName;  // NOLINT(misc-non-private-member-variables-in-classes)
+  std::string requiredSystemPropertyValue;  // NOLINT(misc-non-private-member-variables-in-classes)
   bool is_static;              // NOLINT(misc-non-private-member-variables-in-classes)
   int priority = -1;           // NOLINT(misc-non-private-member-variables-in-classes)
 };
diff --git a/cmds/idmap2/libidmap2/ResourceUtils.cpp b/cmds/idmap2/libidmap2/ResourceUtils.cpp
index 71ba3f0..dce83e3 100644
--- a/cmds/idmap2/libidmap2/ResourceUtils.cpp
+++ b/cmds/idmap2/libidmap2/ResourceUtils.cpp
@@ -103,6 +103,16 @@
     info.priority = std::stoi(iter->second);
   }
 
+  iter = tag->find("requiredSystemPropertyName");
+  if (iter != tag->end()) {
+    info.requiredSystemPropertyName = iter->second;
+  }
+
+  iter = tag->find("requiredSystemPropertyValue");
+  if (iter != tag->end()) {
+    info.requiredSystemPropertyValue = iter->second;
+  }
+
   return info;
 }
 
diff --git a/cmds/idmap2/libidmap2/ZipFile.cpp b/cmds/idmap2/libidmap2/ZipFile.cpp
index 4f5e3a4..1e1a218 100644
--- a/cmds/idmap2/libidmap2/ZipFile.cpp
+++ b/cmds/idmap2/libidmap2/ZipFile.cpp
@@ -34,6 +34,7 @@
   ::ZipArchiveHandle handle;
   int32_t status = ::OpenArchive(path.c_str(), &handle);
   if (status != 0) {
+    ::CloseArchive(handle);
     return nullptr;
   }
   return std::unique_ptr<ZipFile>(new ZipFile(handle));
diff --git a/cmds/idmap2/static-checks.sh b/cmds/idmap2/static-checks.sh
index 41d3c69..a372abd 100755
--- a/cmds/idmap2/static-checks.sh
+++ b/cmds/idmap2/static-checks.sh
@@ -27,10 +27,11 @@
     local red="\e[31m"
     local green="\e[32m"
     local reset="\e[0m"
+    local output
 
     _log "${green}[ RUN      ]${reset} ${label}"
-    local output="$(eval "$cmd")"
-    if [[ -z "${output}" ]]; then
+    output="$(eval "$cmd" 2>&1)"
+    if [[ $? -eq 0 ]]; then
         _log "${green}[       OK ]${reset} ${label}"
         return 0
     else
diff --git a/cmds/idmap2/valgrind.sh b/cmds/idmap2/valgrind.sh
new file mode 100755
index 0000000..b4ebab0
--- /dev/null
+++ b/cmds/idmap2/valgrind.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+#
+# Copyright (C) 2019 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.
+#
+
+function _log()
+{
+    echo -e "$*" >&2
+}
+
+function _eval()
+{
+    local label="$1"
+    local cmd="$2"
+    local red="\e[31m"
+    local green="\e[32m"
+    local reset="\e[0m"
+    local output
+
+    _log "${green}[ RUN      ]${reset} ${label}"
+    output="$(eval "$cmd" 2>&1)"
+    if [[ $? -eq 0 ]]; then
+        _log "${green}[       OK ]${reset} ${label}"
+        return 0
+    else
+        echo "${output}"
+        _log "${red}[  FAILED  ]${reset} ${label}"
+        errors=$((errors + 1))
+        return 1
+    fi
+}
+
+errors=0
+script="$(readlink -f "$BASH_SOURCE")"
+prefix="$(dirname "$script")"
+target_path="${prefix}/tests/data/target/target.apk"
+overlay_path="${prefix}/tests/data/overlay/overlay.apk"
+idmap_path="/tmp/a.idmap"
+valgrind="valgrind --error-exitcode=1 -q --track-origins=yes --leak-check=full"
+
+_eval "idmap2 create" "$valgrind idmap2 create --policy public --target-apk-path $target_path --overlay-apk-path $overlay_path --idmap-path $idmap_path"
+_eval "idmap2 dump" "$valgrind idmap2 dump --idmap-path $idmap_path"
+_eval "idmap2 lookup" "$valgrind idmap2 lookup --idmap-path $idmap_path --config '' --resid test.target:string/str1"
+_eval "idmap2 scan" "$valgrind idmap2 scan --input-directory ${prefix}/tests/data/overlay --recursive --target-package-name test.target --target-apk-path $target_path --output-directory /tmp --override-policy public"
+_eval "idmap2 verify" "$valgrind idmap2 verify --idmap-path $idmap_path"
+_eval "idmap2_tests" "$valgrind $ANDROID_HOST_OUT/nativetest64/idmap2_tests/idmap2_tests"
+exit $errors
diff --git a/cmds/locksettings/TEST_MAPPING b/cmds/locksettings/TEST_MAPPING
index c1cba5f..56f5cc0 100644
--- a/cmds/locksettings/TEST_MAPPING
+++ b/cmds/locksettings/TEST_MAPPING
@@ -1,5 +1,5 @@
 {
-    "presubmit": [
+    "presubmit-devicepolicy": [
         {
             "name": "CtsDevicePolicyManagerTestCases",
             "options": [
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index 43058d5..cb27325 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -74,6 +74,7 @@
         "src/external/StatsPuller.cpp",
         "src/external/StatsPullerManager.cpp",
         "src/external/SubsystemSleepStatePuller.cpp",
+        "src/external/SurfaceflingerStatsPuller.cpp",
         "src/external/TrainInfoPuller.cpp",
         "src/FieldValue.cpp",
         "src/guardrail/StatsdStats.cpp",
@@ -99,6 +100,8 @@
         "src/shell/shell_config.proto",
         "src/shell/ShellSubscriber.cpp",
         "src/socket/StatsSocketListener.cpp",
+        "src/state/StateManager.cpp",
+        "src/state/StateTracker.cpp",
         "src/stats_log_util.cpp",
         "src/statscompanion_util.cpp",
         "src/statsd_config.proto",
@@ -135,7 +138,9 @@
         "libprotoutil",
         "libservices",
         "libstatslog",
+        "libstatssocket",
         "libsysutils",
+        "libtimestats_proto",
         "libutils",
     ],
 }
@@ -237,6 +242,7 @@
         "tests/external/IncidentReportArgs_test.cpp",
         "tests/external/puller_util_test.cpp",
         "tests/external/StatsPuller_test.cpp",
+        "tests/external/SurfaceflingerStatsPuller_test.cpp",
         "tests/FieldValue_test.cpp",
         "tests/guardrail/StatsdStats_test.cpp",
         "tests/indexed_priority_queue_test.cpp",
@@ -253,6 +259,7 @@
         "tests/metrics/ValueMetricProducer_test.cpp",
         "tests/MetricsManager_test.cpp",
         "tests/shell/ShellSubscriber_test.cpp",
+        "tests/state/StateTracker_test.cpp",
         "tests/statsd_test_util.cpp",
         "tests/StatsLogProcessor_test.cpp",
         "tests/StatsService_test.cpp",
diff --git a/cmds/statsd/src/HashableDimensionKey.cpp b/cmds/statsd/src/HashableDimensionKey.cpp
index af8b3af..5e156bb 100644
--- a/cmds/statsd/src/HashableDimensionKey.cpp
+++ b/cmds/statsd/src/HashableDimensionKey.cpp
@@ -59,6 +59,16 @@
     return JenkinsHashWhiten(hash);
 }
 
+bool filterValues(const Matcher& matcherField, const vector<FieldValue>& values, Value* output) {
+    for (const auto& value : values) {
+        if (value.mField.matches(matcherField)) {
+            (*output) = value.mValue;
+            return true;
+        }
+    }
+    return false;
+}
+
 bool filterValues(const vector<Matcher>& matcherFields, const vector<FieldValue>& values,
                   HashableDimensionKey* output) {
     size_t num_matches = 0;
diff --git a/cmds/statsd/src/HashableDimensionKey.h b/cmds/statsd/src/HashableDimensionKey.h
index 6f4941f..a123850 100644
--- a/cmds/statsd/src/HashableDimensionKey.h
+++ b/cmds/statsd/src/HashableDimensionKey.h
@@ -120,6 +120,13 @@
 android::hash_t hashDimension(const HashableDimensionKey& key);
 
 /**
+ * Returns true if a FieldValue field matches the matcher field.
+ * The value of the FieldValue is output.
+ */
+bool filterValues(const Matcher& matcherField, const std::vector<FieldValue>& values,
+                  Value* output);
+
+/**
  * Creating HashableDimensionKeys from FieldValues using matcher.
  *
  * This function may make modifications to the Field if the matcher has Position=FIRST,LAST or ALL
@@ -169,4 +176,4 @@
         return android::JenkinsHashWhiten(hash);
     }
 };
-}  // namespace std
\ No newline at end of file
+}  // namespace std
diff --git a/cmds/statsd/src/StatsLogProcessor.h b/cmds/statsd/src/StatsLogProcessor.h
index f0db1b0..3d002d2 100644
--- a/cmds/statsd/src/StatsLogProcessor.h
+++ b/cmds/statsd/src/StatsLogProcessor.h
@@ -248,19 +248,6 @@
     FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents_LateAlarm);
     FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents_WithActivation);
 
-    FRIEND_TEST(DimensionInConditionE2eTest, TestCreateCountMetric_NoLink_OR_CombinationCondition);
-    FRIEND_TEST(DimensionInConditionE2eTest, TestCreateCountMetric_Link_OR_CombinationCondition);
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_OR_CombinationCondition);
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_OR_CombinationCondition);
-
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_SimpleCondition);
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_SimpleCondition);
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_PartialLink_SimpleCondition);
-
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_PartialLink_AND_CombinationCondition);
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_AND_CombinationCondition);
-    FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_AND_CombinationCondition);
-
     FRIEND_TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_single_bucket);
     FRIEND_TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_multiple_buckets);
     FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_single_bucket);
diff --git a/cmds/statsd/src/StatsService.cpp b/cmds/statsd/src/StatsService.cpp
index 1c7180f..b665a8b 100644
--- a/cmds/statsd/src/StatsService.cpp
+++ b/cmds/statsd/src/StatsService.cpp
@@ -266,7 +266,9 @@
                     IResultReceiver::asInterface(data.readStrongBinder());
 
             err = command(in, out, err, args, resultReceiver);
-            resultReceiver->send(err);
+            if (resultReceiver != nullptr) {
+                resultReceiver->send(err);
+            }
             return NO_ERROR;
         }
         default: { return BnStatsManager::onTransact(code, data, reply, flags); }
@@ -411,13 +413,20 @@
             return cmd_trigger_active_config_broadcast(out, args);
         }
         if (!args[0].compare(String8("data-subscribe"))) {
-            if (mShellSubscriber == nullptr) {
-                mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
+            {
+                std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
+                if (mShellSubscriber == nullptr) {
+                    mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
+                }
             }
             int timeoutSec = -1;
             if (argCount >= 2) {
                 timeoutSec = atoi(args[1].c_str());
             }
+            if (resultReceiver == nullptr) {
+                ALOGI("Null resultReceiver given, no subscription will be started");
+                return UNEXPECTED_NULL;
+            }
             mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
             return NO_ERROR;
         }
diff --git a/cmds/statsd/src/StatsService.h b/cmds/statsd/src/StatsService.h
index 53b6ce9..9490948 100644
--- a/cmds/statsd/src/StatsService.h
+++ b/cmds/statsd/src/StatsService.h
@@ -432,6 +432,10 @@
 
     sp<ShellSubscriber> mShellSubscriber;
 
+    /**
+     * Mutex for setting the shell subscriber
+     */
+    mutable mutex mShellSubscriberMutex;
     std::shared_ptr<LogEventQueue> mEventQueue;
 
     FRIEND_TEST(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart);
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index 78a6609..6249de3 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -340,7 +340,7 @@
     }
 
     // Pulled events will start at field 10000.
-    // Next: 10064
+    // Next: 10065
     oneof pulled {
         WifiBytesTransfer wifi_bytes_transfer = 10000;
         WifiBytesTransferByFgBg wifi_bytes_transfer_by_fg_bg = 10001;
@@ -378,7 +378,6 @@
         PowerProfile power_profile = 10033;
         ProcStatsPkgProc proc_stats_pkg_proc = 10034;
         ProcessCpuTime process_cpu_time = 10035;
-        NativeProcessMemoryState native_process_memory_state = 10036;
         CpuTimePerThreadFreq cpu_time_per_thread_freq = 10037;
         OnDevicePowerMeasurement on_device_power_measurement = 10038;
         DeviceCalculatedPowerUse device_calculated_power_use = 10039;
@@ -406,11 +405,14 @@
         ProcessSystemIonHeapSize process_system_ion_heap_size = 10061;
         SurfaceflingerStatsGlobalInfo surfaceflinger_stats_global_info = 10062;
         SurfaceflingerStatsLayerInfo surfaceflinger_stats_layer_info = 10063;
+        ProcessMemorySnapshot process_memory_snapshot = 10064;
     }
 
     // DO NOT USE field numbers above 100,000 in AOSP.
     // Field numbers 100,000 - 199,999 are reserved for non-AOSP (e.g. OEMs) to use.
     // Field numbers 200,000 and above are reserved for future use; do not use them at all.
+
+    reserved 10036;
 }
 
 /**
@@ -3069,9 +3071,9 @@
  *     services/core/java/com/android/server/wm/Session.java
  */
 message OverlayStateChanged {
-    optional int32 uid = 1 [(is_uid) = true];
+    optional int32 uid = 1 [(state_field_option).option = PRIMARY, (is_uid) = true];
 
-    optional string package_name = 2;
+    optional string package_name = 2 [(state_field_option).option = PRIMARY];
 
     optional bool using_alert_window = 3;
 
@@ -3079,7 +3081,7 @@
         ENTERED = 1;
         EXITED = 2;
     }
-    optional State state = 4;
+    optional State state = 4 [(state_field_option).option = EXCLUSIVE];
 }
 
 /*
@@ -4018,8 +4020,8 @@
     optional int64 page_major_fault = 5;
 
     // RSS
-    // Value is read from /proc/PID/status. Or from memory.stat, field
-    // total_rss if per-app memory cgroups are enabled.
+    // Value is read from memory.stat, field total_rss if per-app memory
+    // cgroups are enabled. Otherwise, value from /proc/pid/stat.
     optional int64 rss_in_bytes = 6;
 
     // CACHE
@@ -4029,56 +4031,17 @@
 
     // SWAP
     // Value is read from memory.stat, field total_swap if per-app memory
-    // cgroups are enabled. Otherwise, VmSwap from /proc/PID/status.
+    // cgroups are enabled. Otherwise, 0.
     optional int64 swap_in_bytes = 8;
 
-    // Deprecated: use ProcessMemoryHighWaterMark atom instead. Always 0.
+    // Deprecated: use ProcessMemoryHighWaterMark atom instead. Always -1.
     optional int64 rss_high_watermark_in_bytes = 9 [deprecated = true];
 
-    // Elapsed real time when the process started.
-    // Value is read from /proc/PID/stat, field 22. 0 if read from per-app memory cgroups.
-    optional int64 start_time_nanos = 10;
+    // Deprecated: use ProcessMemorySnapshot atom instead. Always -1.
+    optional int64 start_time_nanos = 10 [deprecated = true];
 
-    // Anonymous page size plus swap size. Values are read from /proc/PID/status.
-    optional int32 anon_rss_and_swap_in_kilobytes = 11;
-}
-
-/*
- * Logs the memory stats for a native process (from procfs).
- *
- * Pulled from StatsCompanionService for selected native processes.
- */
-message NativeProcessMemoryState {
-    // The uid if available. -1 means not available.
-    optional int32 uid = 1 [(is_uid) = true];
-
-    // The process name.
-    // Value read from /proc/PID/cmdline.
-    optional string process_name = 2;
-
-    // # of page-faults
-    optional int64 page_fault = 3;
-
-    // # of major page-faults
-    optional int64 page_major_fault = 4;
-
-    // RSS
-    // Value read from /proc/PID/status.
-    optional int64 rss_in_bytes = 5;
-
-    // Deprecated: use ProcessMemoryHighWaterMark atom instead. Always 0.
-    optional int64 rss_high_watermark_in_bytes = 6 [deprecated = true];
-
-    // Elapsed real time when the process started.
-    // Value is read from /proc/PID/stat, field 22.
-    optional int64 start_time_nanos = 7;
-
-    // SWAP
-    // Value read from /proc/PID/status, field VmSwap.
-    optional int64 swap_in_bytes = 8;
-
-    // Anonymous page size plus swap size. Values are read from /proc/PID/status.
-    optional int32 anon_rss_and_swap_in_kilobytes = 9;
+    // Deprecated: use ProcessMemorySnapshot atom instead. Always -1.
+    optional int32 anon_rss_and_swap_in_kilobytes = 11 [deprecated = true];
 }
 
 /*
@@ -4108,6 +4071,46 @@
 }
 
 /*
+ * Logs the memory stats for a process.
+ *
+ * Pulled from StatsCompanionService for all managed processes (from ActivityManagerService)
+ * and for selected native processes.
+ */
+message ProcessMemorySnapshot {
+    // The uid if available. -1 means not available.
+    optional int32 uid = 1 [(is_uid) = true];
+
+    // The process name.
+    // Usually package name or process cmdline.
+    // Provided by ActivityManagerService or read from /proc/PID/cmdline.
+    optional string process_name = 2;
+
+    // The pid of the process.
+    // Allows to disambiguate instances of the process.
+    optional int32 pid = 3;
+
+    // The current OOM score adjustment value.
+    // Read from ProcessRecord for managed processes.
+    // Placeholder -1001 (OOM_SCORE_ADJ_MIN - 1, outside of allowed range) for native ones.
+    optional int32 oom_score_adj = 4;
+
+    // The current RSS of the process.
+    // VmRSS from /proc/pid/status.
+    optional int32 rss_in_kilobytes = 5;
+
+    // The current anon RSS of the process.
+    // RssAnon from /proc/pid/status.
+    optional int32 anon_rss_in_kilobytes = 6;
+
+    // The current swap size of the process.
+    // VmSwap from /proc/pid/status.
+    optional int32 swap_in_kilobytes = 7;
+
+    // The sum of rss_in_kilobytes and swap_in_kilobytes.
+    optional int32 anon_rss_and_swap_in_kilobytes = 8;
+}
+
+/*
  * Elapsed real time from SystemClock.
  */
 message SystemElapsedRealtime {
diff --git a/cmds/statsd/src/external/GpuStatsPuller.cpp b/cmds/statsd/src/external/GpuStatsPuller.cpp
index bbdb540..d38b87f 100644
--- a/cmds/statsd/src/external/GpuStatsPuller.cpp
+++ b/cmds/statsd/src/external/GpuStatsPuller.cpp
@@ -92,9 +92,15 @@
                 android::util::GPU_STATS_APP_INFO, getWallClockNs(), getElapsedRealtimeNs());
         if (!event->write(info.appPackageName)) return false;
         if (!event->write((int64_t)info.driverVersionCode)) return false;
-        if (!event->write(int64VectorToProtoByteString(info.glDriverLoadingTime))) return false;
-        if (!event->write(int64VectorToProtoByteString(info.vkDriverLoadingTime))) return false;
-        if (!event->write(int64VectorToProtoByteString(info.angleDriverLoadingTime))) return false;
+        if (!event->writeBytes(int64VectorToProtoByteString(info.glDriverLoadingTime)))  {
+            return false;
+        }
+        if (!event->writeBytes(int64VectorToProtoByteString(info.vkDriverLoadingTime))) {
+            return false;
+        }
+        if (!event->writeBytes(int64VectorToProtoByteString(info.angleDriverLoadingTime))) {
+            return false;
+        }
         if (!event->write(info.cpuVulkanInUse)) return false;
         if (!event->write(info.falsePrerotation)) return false;
         event->init();
diff --git a/cmds/statsd/src/external/StatsPullerManager.cpp b/cmds/statsd/src/external/StatsPullerManager.cpp
index 475f18a..43e33f5 100644
--- a/cmds/statsd/src/external/StatsPullerManager.cpp
+++ b/cmds/statsd/src/external/StatsPullerManager.cpp
@@ -17,12 +17,17 @@
 #define DEBUG false
 #include "Log.h"
 
+#include "StatsPullerManager.h"
+
 #include <android/os/IStatsCompanionService.h>
 #include <android/os/IStatsPullerCallback.h>
 #include <cutils/log.h>
 #include <math.h>
 #include <stdint.h>
+
 #include <algorithm>
+#include <iostream>
+
 #include "../StatsService.h"
 #include "../logd/LogEvent.h"
 #include "../stats_log_util.h"
@@ -32,13 +37,11 @@
 #include "ResourceHealthManagerPuller.h"
 #include "StatsCallbackPuller.h"
 #include "StatsCompanionServicePuller.h"
-#include "StatsPullerManager.h"
 #include "SubsystemSleepStatePuller.h"
+#include "SurfaceflingerStatsPuller.h"
 #include "TrainInfoPuller.h"
 #include "statslog.h"
 
-#include <iostream>
-
 using std::make_shared;
 using std::map;
 using std::shared_ptr;
@@ -142,17 +145,15 @@
          {.puller = new ResourceHealthManagerPuller(android::util::BATTERY_CYCLE_COUNT)}},
         // process_memory_state
         {android::util::PROCESS_MEMORY_STATE,
-         {.additiveFields = {4, 5, 6, 7, 8, 9},
+         {.additiveFields = {4, 5, 6, 7, 8},
           .puller = new StatsCompanionServicePuller(android::util::PROCESS_MEMORY_STATE)}},
-        // native_process_memory_state
-        {android::util::NATIVE_PROCESS_MEMORY_STATE,
-         {.additiveFields = {3, 4, 5, 6, 8},
-          .puller = new StatsCompanionServicePuller(android::util::NATIVE_PROCESS_MEMORY_STATE)}},
         // process_memory_high_water_mark
         {android::util::PROCESS_MEMORY_HIGH_WATER_MARK,
-         {.additiveFields = {3},
-          .puller =
+         {.puller =
                   new StatsCompanionServicePuller(android::util::PROCESS_MEMORY_HIGH_WATER_MARK)}},
+        // process_memory_snapshot
+        {android::util::PROCESS_MEMORY_SNAPSHOT,
+         {.puller = new StatsCompanionServicePuller(android::util::PROCESS_MEMORY_SNAPSHOT)}},
         // system_ion_heap_size
         {android::util::SYSTEM_ION_HEAP_SIZE,
          {.puller = new StatsCompanionServicePuller(android::util::SYSTEM_ION_HEAP_SIZE)}},
@@ -266,6 +267,10 @@
         // App ops
         {android::util::APP_OPS,
          {.puller = new StatsCompanionServicePuller(android::util::APP_OPS)}},
+        // SurfaceflingerStatsGlobalInfo
+        {android::util::SURFACEFLINGER_STATS_GLOBAL_INFO,
+         {.puller =
+                  new SurfaceflingerStatsPuller(android::util::SURFACEFLINGER_STATS_GLOBAL_INFO)}},
 };
 
 StatsPullerManager::StatsPullerManager() : mNextPullTimeNs(NO_ALARM_UPDATE) {
diff --git a/cmds/statsd/src/external/SurfaceflingerStatsPuller.cpp b/cmds/statsd/src/external/SurfaceflingerStatsPuller.cpp
new file mode 100644
index 0000000..23b2236
--- /dev/null
+++ b/cmds/statsd/src/external/SurfaceflingerStatsPuller.cpp
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2019 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.
+ */
+
+#include "SurfaceflingerStatsPuller.h"
+
+#include <cutils/compiler.h>
+
+#include <numeric>
+
+#include "logd/LogEvent.h"
+#include "stats_log_util.h"
+#include "statslog.h"
+
+namespace android {
+namespace os {
+namespace statsd {
+
+SurfaceflingerStatsPuller::SurfaceflingerStatsPuller(const int tagId) : StatsPuller(tagId) {
+}
+
+bool SurfaceflingerStatsPuller::PullInternal(std::vector<std::shared_ptr<LogEvent>>* data) {
+    switch (mTagId) {
+        case android::util::SURFACEFLINGER_STATS_GLOBAL_INFO:
+            return pullGlobalInfo(data);
+        default:
+            break;
+    }
+
+    return false;
+}
+
+static int64_t getTotalTime(
+        const google::protobuf::RepeatedPtrField<surfaceflinger::SFTimeStatsHistogramBucketProto>&
+                buckets) {
+    int64_t total = 0;
+    for (const auto& bucket : buckets) {
+        if (bucket.time_millis() == 1000) {
+            continue;
+        }
+
+        total += bucket.time_millis() * bucket.frame_count();
+    }
+
+    return total;
+}
+
+bool SurfaceflingerStatsPuller::pullGlobalInfo(std::vector<std::shared_ptr<LogEvent>>* data) {
+    std::string protoBytes;
+    if (CC_UNLIKELY(mStatsProvider)) {
+        protoBytes = mStatsProvider();
+    } else {
+        std::unique_ptr<FILE, decltype(&pclose)> pipe(popen("dumpsys SurfaceFlinger --timestats -dump --proto", "r"), pclose);
+        if (!pipe.get()) {
+            return false;
+        }
+        char buf[1024];
+        size_t bytesRead = 0;
+        do {
+            bytesRead = fread(buf, 1, sizeof(buf), pipe.get());
+            protoBytes.append(buf, bytesRead);
+        } while (bytesRead > 0);
+    }
+    surfaceflinger::SFTimeStatsGlobalProto proto;
+    proto.ParseFromString(protoBytes);
+
+    int64_t totalTime = getTotalTime(proto.present_to_present());
+
+    data->clear();
+    data->reserve(1);
+    std::shared_ptr<LogEvent> event =
+            make_shared<LogEvent>(android::util::SURFACEFLINGER_STATS_GLOBAL_INFO, getWallClockNs(),
+                                  getElapsedRealtimeNs());
+    if (!event->write(proto.total_frames())) return false;
+    if (!event->write(proto.missed_frames())) return false;
+    if (!event->write(proto.client_composition_frames())) return false;
+    if (!event->write(proto.display_on_time())) return false;
+    if (!event->write(totalTime)) return false;
+    event->init();
+    data->emplace_back(event);
+
+    return true;
+}
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
diff --git a/cmds/statsd/src/external/SurfaceflingerStatsPuller.h b/cmds/statsd/src/external/SurfaceflingerStatsPuller.h
new file mode 100644
index 0000000..ed7153e
--- /dev/null
+++ b/cmds/statsd/src/external/SurfaceflingerStatsPuller.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2019 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.
+ */
+
+#pragma once
+
+#include <timestatsproto/TimeStatsProtoHeader.h>
+
+#include "StatsPuller.h"
+
+namespace android {
+namespace os {
+namespace statsd {
+
+/**
+ * Pull metrics from Surfaceflinger
+ */
+class SurfaceflingerStatsPuller : public StatsPuller {
+public:
+    explicit SurfaceflingerStatsPuller(const int tagId);
+
+    // StatsPuller interface
+    bool PullInternal(std::vector<std::shared_ptr<LogEvent>>* data) override;
+
+protected:
+    // Test-only, for injecting fake data
+    using StatsProvider = std::function<std::string()>;
+    StatsProvider mStatsProvider;
+
+private:
+    bool pullGlobalInfo(std::vector<std::shared_ptr<LogEvent>>* data);
+};
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
diff --git a/cmds/statsd/src/logd/LogEvent.cpp b/cmds/statsd/src/logd/LogEvent.cpp
index 0ade531..fd19c9d 100644
--- a/cmds/statsd/src/logd/LogEvent.cpp
+++ b/cmds/statsd/src/logd/LogEvent.cpp
@@ -332,6 +332,13 @@
     return false;
 }
 
+bool LogEvent::writeBytes(const string& value) {
+    if (mContext) {
+        return android_log_write_char_array(mContext, value.c_str(), value.length()) >= 0;
+    }
+    return false;
+}
+
 bool LogEvent::writeKeyValuePairs(int32_t uid,
                                   const std::map<int32_t, int32_t>& int_map,
                                   const std::map<int32_t, int64_t>& long_map,
diff --git a/cmds/statsd/src/logd/LogEvent.h b/cmds/statsd/src/logd/LogEvent.h
index 531ce29..f1f45a2 100644
--- a/cmds/statsd/src/logd/LogEvent.h
+++ b/cmds/statsd/src/logd/LogEvent.h
@@ -21,9 +21,9 @@
 #include <android/frameworks/stats/1.0/types.h>
 #include <android/os/StatsLogEventWrapper.h>
 #include <android/util/ProtoOutputStream.h>
-#include <log/log_event_list.h>
 #include <log/log_read.h>
 #include <private/android_logger.h>
+#include <stats_event_list.h>
 #include <utils/Errors.h>
 
 #include <string>
@@ -157,6 +157,7 @@
     bool write(float value);
     bool write(const std::vector<AttributionNodeInternal>& nodes);
     bool write(const AttributionNodeInternal& node);
+    bool writeBytes(const std::string& value);
     bool writeKeyValuePairs(int32_t uid,
                             const std::map<int32_t, int32_t>& int_map,
                             const std::map<int32_t, int64_t>& long_map,
diff --git a/cmds/statsd/src/main.cpp b/cmds/statsd/src/main.cpp
index 42132ee..7d446a9 100644
--- a/cmds/statsd/src/main.cpp
+++ b/cmds/statsd/src/main.cpp
@@ -53,6 +53,8 @@
     if (gStatsService != nullptr) {
         gStatsService->Terminate();
     }
+    ALOGW("statsd terminated on receiving signal %d.", sig);
+    exit(1);
 }
 
 void registerSigHandler()
diff --git a/cmds/statsd/src/metrics/CountMetricProducer.cpp b/cmds/statsd/src/metrics/CountMetricProducer.cpp
index 23d025f..b5c8e35 100644
--- a/cmds/statsd/src/metrics/CountMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/CountMetricProducer.cpp
@@ -37,6 +37,7 @@
 using std::string;
 using std::unordered_map;
 using std::vector;
+using std::shared_ptr;
 
 namespace android {
 namespace os {
@@ -67,8 +68,13 @@
 CountMetricProducer::CountMetricProducer(const ConfigKey& key, const CountMetric& metric,
                                          const int conditionIndex,
                                          const sp<ConditionWizard>& wizard,
-                                         const int64_t timeBaseNs, const int64_t startTimeNs)
-    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard) {
+                                         const int64_t timeBaseNs, const int64_t startTimeNs,
+                                         const unordered_map<int, shared_ptr<Activation>>&
+                                                 eventActivationMap,
+                                         const unordered_map<int, vector<shared_ptr<Activation>>>&
+                                                 eventDeactivationMap)
+    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard, eventActivationMap,
+                     eventDeactivationMap) {
     if (metric.has_bucket()) {
         mBucketSizeNs =
                 TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket()) * 1000000;
@@ -251,6 +257,7 @@
         if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
             ALOGE("CountMetric %lld dropping data for dimension key %s",
                 (long long)mMetricId, newKey.toString().c_str());
+            StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
             return true;
         }
     }
diff --git a/cmds/statsd/src/metrics/CountMetricProducer.h b/cmds/statsd/src/metrics/CountMetricProducer.h
index b4a910c..61913c7 100644
--- a/cmds/statsd/src/metrics/CountMetricProducer.h
+++ b/cmds/statsd/src/metrics/CountMetricProducer.h
@@ -42,7 +42,11 @@
 public:
     CountMetricProducer(const ConfigKey& key, const CountMetric& countMetric,
                         const int conditionIndex, const sp<ConditionWizard>& wizard,
-                        const int64_t timeBaseNs, const int64_t startTimeNs);
+                        const int64_t timeBaseNs, const int64_t startTimeNs,
+                        const std::unordered_map<int, std::shared_ptr<Activation>>&
+                                eventActivationMap = {},
+                        const std::unordered_map<int, std::vector<std::shared_ptr<Activation>>>&
+                                eventDeactivationMap = {});
 
     virtual ~CountMetricProducer();
 
diff --git a/cmds/statsd/src/metrics/DurationMetricProducer.cpp b/cmds/statsd/src/metrics/DurationMetricProducer.cpp
index cca793b..31b90f3 100644
--- a/cmds/statsd/src/metrics/DurationMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/DurationMetricProducer.cpp
@@ -36,6 +36,7 @@
 using std::string;
 using std::unordered_map;
 using std::vector;
+using std::shared_ptr;
 
 namespace android {
 namespace os {
@@ -62,14 +63,15 @@
 const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
 const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
 
-DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const DurationMetric& metric,
-                                               const int conditionIndex, const size_t startIndex,
-                                               const size_t stopIndex, const size_t stopAllIndex,
-                                               const bool nesting,
-                                               const sp<ConditionWizard>& wizard,
-                                               const FieldMatcher& internalDimensions,
-                                               const int64_t timeBaseNs, const int64_t startTimeNs)
-    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard),
+DurationMetricProducer::DurationMetricProducer(
+        const ConfigKey& key, const DurationMetric& metric, const int conditionIndex,
+        const size_t startIndex, const size_t stopIndex, const size_t stopAllIndex,
+        const bool nesting, const sp<ConditionWizard>& wizard,
+        const FieldMatcher& internalDimensions, const int64_t timeBaseNs, const int64_t startTimeNs,
+        const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
+        const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap)
+    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard, eventActivationMap,
+                     eventDeactivationMap),
       mAggregationType(metric.aggregation_type()),
       mStartIndex(startIndex),
       mStopIndex(stopIndex),
@@ -491,6 +493,7 @@
             if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
                 ALOGE("DurationMetric %lld dropping data for condition dimension key %s",
                     (long long)mMetricId, newKey.getDimensionKeyInCondition().toString().c_str());
+                StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
                 return true;
             }
         }
@@ -504,6 +507,7 @@
             if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
                 ALOGE("DurationMetric %lld dropping data for what dimension key %s",
                     (long long)mMetricId, newKey.getDimensionKeyInWhat().toString().c_str());
+                StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
                 return true;
             }
         }
diff --git a/cmds/statsd/src/metrics/DurationMetricProducer.h b/cmds/statsd/src/metrics/DurationMetricProducer.h
index 56c9fd6..0592b18 100644
--- a/cmds/statsd/src/metrics/DurationMetricProducer.h
+++ b/cmds/statsd/src/metrics/DurationMetricProducer.h
@@ -42,7 +42,12 @@
                            const int conditionIndex, const size_t startIndex,
                            const size_t stopIndex, const size_t stopAllIndex, const bool nesting,
                            const sp<ConditionWizard>& wizard,
-                           const FieldMatcher& internalDimensions, const int64_t timeBaseNs, const int64_t startTimeNs);
+                           const FieldMatcher& internalDimensions, const int64_t timeBaseNs,
+                           const int64_t startTimeNs,
+                           const unordered_map<int, shared_ptr<Activation>>&
+                                   eventActivationMap = {},
+                           const unordered_map<int, vector<shared_ptr<Activation>>>&
+                                   eventDeactivationMap = {});
 
     virtual ~DurationMetricProducer();
 
diff --git a/cmds/statsd/src/metrics/EventMetricProducer.cpp b/cmds/statsd/src/metrics/EventMetricProducer.cpp
index 96133bd..a60a916 100644
--- a/cmds/statsd/src/metrics/EventMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/EventMetricProducer.cpp
@@ -36,6 +36,7 @@
 using std::string;
 using std::unordered_map;
 using std::vector;
+using std::shared_ptr;
 
 namespace android {
 namespace os {
@@ -54,8 +55,13 @@
 EventMetricProducer::EventMetricProducer(const ConfigKey& key, const EventMetric& metric,
                                          const int conditionIndex,
                                          const sp<ConditionWizard>& wizard,
-                                         const int64_t startTimeNs)
-    : MetricProducer(metric.id(), key, startTimeNs, conditionIndex, wizard) {
+                                         const int64_t startTimeNs,
+                                         const unordered_map<int, shared_ptr<Activation>>&
+                                                 eventActivationMap,
+                                         const unordered_map<int, vector<shared_ptr<Activation>>>&
+                                                 eventDeactivationMap)
+    : MetricProducer(metric.id(), key, startTimeNs, conditionIndex, wizard, eventActivationMap,
+                     eventDeactivationMap) {
     if (metric.links().size() > 0) {
         for (const auto& link : metric.links()) {
             Metric2Condition mc;
diff --git a/cmds/statsd/src/metrics/EventMetricProducer.h b/cmds/statsd/src/metrics/EventMetricProducer.h
index 74e6bc8..aab53c8 100644
--- a/cmds/statsd/src/metrics/EventMetricProducer.h
+++ b/cmds/statsd/src/metrics/EventMetricProducer.h
@@ -35,7 +35,11 @@
 public:
     EventMetricProducer(const ConfigKey& key, const EventMetric& eventMetric,
                         const int conditionIndex, const sp<ConditionWizard>& wizard,
-                        const int64_t startTimeNs);
+                        const int64_t startTimeNs,
+                        const std::unordered_map<int, std::shared_ptr<Activation>>&
+                                eventActivationMap = {},
+                        const std::unordered_map<int, std::vector<std::shared_ptr<Activation>>>&
+                                eventDeactivationMap = {});
 
     virtual ~EventMetricProducer();
 
diff --git a/cmds/statsd/src/metrics/GaugeMetricProducer.cpp b/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
index 1f423cd..e409b6fb 100644
--- a/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
@@ -72,8 +72,11 @@
         const sp<ConditionWizard>& wizard, const int whatMatcherIndex,
         const sp<EventMatcherWizard>& matcherWizard, const int pullTagId, const int triggerAtomId,
         const int atomId, const int64_t timeBaseNs, const int64_t startTimeNs,
-        const sp<StatsPullerManager>& pullerManager)
-    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard),
+        const sp<StatsPullerManager>& pullerManager,
+        const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
+        const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap)
+    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard, eventActivationMap,
+            eventDeactivationMap),
       mWhatMatcherIndex(whatMatcherIndex),
       mEventMatcherWizard(matcherWizard),
       mPullerManager(pullerManager),
@@ -133,8 +136,11 @@
                                          mBucketSizeNs);
     }
 
-    // Adjust start for partial bucket
+    // Adjust start for partial first bucket and then pull if needed
     mCurrentBucketStartTimeNs = startTimeNs;
+    if (mIsActive && mIsPulled && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
+        pullAndMatchEventsLocked(mCurrentBucketStartTimeNs);
+    }
 
     VLOG("Gauge metric %lld created. bucket size %lld start_time: %lld sliced %d",
          (long long)metric.id(), (long long)mBucketSizeNs, (long long)mTimeBaseNs,
@@ -295,11 +301,6 @@
     }
 }
 
-void GaugeMetricProducer::prepareFirstBucketLocked() {
-    if (mIsActive && mIsPulled && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
-        pullAndMatchEventsLocked(mCurrentBucketStartTimeNs);
-    }
-}
 
 void GaugeMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
     bool triggerPuller = false;
@@ -439,6 +440,7 @@
         if (newTupleCount > mDimensionHardLimit) {
             ALOGE("GaugeMetric %lld dropping data for dimension key %s",
                 (long long)mMetricId, newKey.toString().c_str());
+            StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
             return true;
         }
     }
diff --git a/cmds/statsd/src/metrics/GaugeMetricProducer.h b/cmds/statsd/src/metrics/GaugeMetricProducer.h
index a612adf..dfe1d56 100644
--- a/cmds/statsd/src/metrics/GaugeMetricProducer.h
+++ b/cmds/statsd/src/metrics/GaugeMetricProducer.h
@@ -58,11 +58,14 @@
 public:
     GaugeMetricProducer(const ConfigKey& key, const GaugeMetric& gaugeMetric,
                         const int conditionIndex, const sp<ConditionWizard>& conditionWizard,
-                        const int whatMatcherIndex,
-                        const sp<EventMatcherWizard>& matcherWizard,
+                        const int whatMatcherIndex,const sp<EventMatcherWizard>& matcherWizard,
                         const int pullTagId, const int triggerAtomId, const int atomId,
                         const int64_t timeBaseNs, const int64_t startTimeNs,
-                        const sp<StatsPullerManager>& pullerManager);
+                        const sp<StatsPullerManager>& pullerManager,
+                        const std::unordered_map<int, std::shared_ptr<Activation>>&
+                                eventActivationMap = {},
+                        const std::unordered_map<int, std::vector<std::shared_ptr<Activation>>>&
+                                eventDeactivationMap = {});
 
     virtual ~GaugeMetricProducer();
 
@@ -125,8 +128,6 @@
     void flushCurrentBucketLocked(const int64_t& eventTimeNs,
                                   const int64_t& nextBucketStartTimeNs) override;
 
-    void prepareFirstBucketLocked() override;
-
     void pullAndMatchEventsLocked(const int64_t timestampNs);
 
     const int mWhatMatcherIndex;
diff --git a/cmds/statsd/src/metrics/MetricProducer.cpp b/cmds/statsd/src/metrics/MetricProducer.cpp
index 1ab4fdf..3426a19 100644
--- a/cmds/statsd/src/metrics/MetricProducer.cpp
+++ b/cmds/statsd/src/metrics/MetricProducer.cpp
@@ -40,6 +40,29 @@
 const int FIELD_ID_ACTIVE_EVENT_ACTIVATION_REMAINING_TTL_NANOS = 2;
 const int FIELD_ID_ACTIVE_EVENT_ACTIVATION_STATE = 3;
 
+MetricProducer::MetricProducer(
+        const int64_t& metricId, const ConfigKey& key, const int64_t timeBaseNs,
+        const int conditionIndex, const sp<ConditionWizard>& wizard,
+        const std::unordered_map<int, std::shared_ptr<Activation>>& eventActivationMap,
+        const std::unordered_map<int, std::vector<std::shared_ptr<Activation>>>&
+                eventDeactivationMap)
+        : mMetricId(metricId),
+          mConfigKey(key),
+          mTimeBaseNs(timeBaseNs),
+          mCurrentBucketStartTimeNs(timeBaseNs),
+          mCurrentBucketNum(0),
+          mCondition(initialCondition(conditionIndex)),
+          mConditionTrackerIndex(conditionIndex),
+          mConditionSliced(false),
+          mWizard(wizard),
+          mContainANYPositionInDimensionsInWhat(false),
+          mSliceByPositionALL(false),
+          mHasLinksToAllConditionDimensionsInTracker(false),
+          mEventActivationMap(eventActivationMap),
+          mEventDeactivationMap(eventDeactivationMap),
+          mIsActive(mEventActivationMap.empty()) {
+    }
+
 void MetricProducer::onMatchedLogEventLocked(const size_t matcherIndex, const LogEvent& event) {
     if (!mIsActive) {
         return;
@@ -97,24 +120,6 @@
     }
 }
 
-void MetricProducer::addActivation(int activationTrackerIndex, const ActivationType& activationType,
-        int64_t ttl_seconds, int deactivationTrackerIndex) {
-    std::lock_guard<std::mutex> lock(mMutex);
-    // When a metric producer does not depend on any activation, its mIsActive is true.
-    // Therefore, if this is the 1st activation, mIsActive will turn to false. Otherwise it does not
-    // change.
-    if  (mEventActivationMap.empty()) {
-        mIsActive = false;
-    }
-    std::shared_ptr<Activation> activation =
-            std::make_shared<Activation>(activationType, ttl_seconds * NS_PER_SEC);
-    mEventActivationMap.emplace(activationTrackerIndex, activation);
-    if (-1 != deactivationTrackerIndex) {
-        auto& deactivationList = mEventDeactivationMap[deactivationTrackerIndex];
-        deactivationList.push_back(activation);
-    }
-}
-
 void MetricProducer::activateLocked(int activationTrackerIndex, int64_t elapsedTimestampNs) {
     auto it = mEventActivationMap.find(activationTrackerIndex);
     if (it == mEventActivationMap.end()) {
diff --git a/cmds/statsd/src/metrics/MetricProducer.h b/cmds/statsd/src/metrics/MetricProducer.h
index 94f833b..1e1eb69 100644
--- a/cmds/statsd/src/metrics/MetricProducer.h
+++ b/cmds/statsd/src/metrics/MetricProducer.h
@@ -69,6 +69,19 @@
     NO_TIME_CONSTRAINTS = 2
 };
 
+struct Activation {
+    Activation(const ActivationType& activationType, const int64_t ttlNs)
+        : ttl_ns(ttlNs),
+          start_ns(0),
+          state(ActivationState::kNotActive),
+          activationType(activationType) {}
+
+    const int64_t ttl_ns;
+    int64_t start_ns;
+    ActivationState state;
+    const ActivationType activationType;
+};
+
 // A MetricProducer is responsible for compute one single metrics, creating stats log report, and
 // writing the report to dropbox. MetricProducers should respond to package changes as required in
 // PackageInfoListener, but if none of the metrics are slicing by package name, then the update can
@@ -76,21 +89,10 @@
 class MetricProducer : public virtual PackageInfoListener {
 public:
     MetricProducer(const int64_t& metricId, const ConfigKey& key, const int64_t timeBaseNs,
-                   const int conditionIndex, const sp<ConditionWizard>& wizard)
-        : mMetricId(metricId),
-          mConfigKey(key),
-          mTimeBaseNs(timeBaseNs),
-          mCurrentBucketStartTimeNs(timeBaseNs),
-          mCurrentBucketNum(0),
-          mCondition(initialCondition(conditionIndex)),
-          mConditionSliced(false),
-          mWizard(wizard),
-          mConditionTrackerIndex(conditionIndex),
-          mContainANYPositionInDimensionsInWhat(false),
-          mSliceByPositionALL(false),
-          mHasLinksToAllConditionDimensionsInTracker(false),
-          mIsActive(true) {
-    }
+                   const int conditionIndex, const sp<ConditionWizard>& wizard,
+                   const std::unordered_map<int, std::shared_ptr<Activation>>& eventActivationMap,
+                   const std::unordered_map<int, std::vector<std::shared_ptr<Activation>>>&
+                           eventDeactivationMap);
 
     virtual ~MetricProducer(){};
 
@@ -167,11 +169,6 @@
         return clearPastBucketsLocked(dumpTimeNs);
     }
 
-    void dumpStates(FILE* out, bool verbose) const {
-        std::lock_guard<std::mutex> lock(mMutex);
-        dumpStatesLocked(out, verbose);
-    }
-
     // Returns the memory in bytes currently used to store this metric's data. Does not change
     // state.
     size_t byteSize() const {
@@ -179,34 +176,9 @@
         return byteSizeLocked();
     }
 
-    /* If alert is valid, adds an AnomalyTracker and returns it. If invalid, returns nullptr. */
-    virtual sp<AnomalyTracker> addAnomalyTracker(const Alert &alert,
-                                                 const sp<AlarmMonitor>& anomalyAlarmMonitor) {
+    void dumpStates(FILE* out, bool verbose) const {
         std::lock_guard<std::mutex> lock(mMutex);
-        sp<AnomalyTracker> anomalyTracker = new AnomalyTracker(alert, mConfigKey);
-        if (anomalyTracker != nullptr) {
-            mAnomalyTrackers.push_back(anomalyTracker);
-        }
-        return anomalyTracker;
-    }
-
-    int64_t getBuckeSizeInNs() const {
-        std::lock_guard<std::mutex> lock(mMutex);
-        return mBucketSizeNs;
-    }
-
-    // Only needed for unit-testing to override guardrail.
-    void setBucketSize(int64_t bucketSize) {
-        mBucketSizeNs = bucketSize;
-    }
-
-    inline const int64_t& getMetricId() const {
-        return mMetricId;
-    }
-
-    void loadActiveMetric(const ActiveMetric& activeMetric, int64_t currentTimeNs) {
-        std::lock_guard<std::mutex> lock(mMutex);
-        loadActiveMetricLocked(activeMetric, currentTimeNs);
+        dumpStatesLocked(out, verbose);
     }
 
     // Let MetricProducer drop in-memory data to save memory.
@@ -218,9 +190,9 @@
         dropDataLocked(dropTimeNs);
     }
 
-    // For test only.
-    inline int64_t getCurrentBucketNum() const {
-        return mCurrentBucketNum;
+    void loadActiveMetric(const ActiveMetric& activeMetric, int64_t currentTimeNs) {
+        std::lock_guard<std::mutex> lock(mMutex);
+        loadActiveMetricLocked(activeMetric, currentTimeNs);
     }
 
     void activate(int activationTrackerIndex, int64_t elapsedTimestampNs) {
@@ -238,44 +210,38 @@
         return isActiveLocked();
     }
 
-    void addActivation(int activationTrackerIndex, const ActivationType& activationType,
-            int64_t ttl_seconds, int deactivationTrackerIndex = -1);
-
-    void prepareFirstBucket() {
-        std::lock_guard<std::mutex> lock(mMutex);
-        prepareFirstBucketLocked();
-    }
-
     void flushIfExpire(int64_t elapsedTimestampNs);
 
     void writeActiveMetricToProtoOutputStream(
             int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto);
-protected:
-    virtual void onConditionChangedLocked(const bool condition, const int64_t eventTime) = 0;
-    virtual void onSlicedConditionMayChangeLocked(bool overallCondition,
-                                                  const int64_t eventTime) = 0;
-    virtual void onDumpReportLocked(const int64_t dumpTimeNs,
-                                    const bool include_current_partial_bucket,
-                                    const bool erase_data,
-                                    const DumpLatency dumpLatency,
-                                    std::set<string> *str_set,
-                                    android::util::ProtoOutputStream* protoOutput) = 0;
-    virtual void clearPastBucketsLocked(const int64_t dumpTimeNs) = 0;
-    virtual size_t byteSizeLocked() const = 0;
-    virtual void dumpStatesLocked(FILE* out, bool verbose) const = 0;
 
-    bool evaluateActiveStateLocked(int64_t elapsedTimestampNs);
-
-    void activateLocked(int activationTrackerIndex, int64_t elapsedTimestampNs);
-    void cancelEventActivationLocked(int deactivationTrackerIndex);
-
-    inline bool isActiveLocked() const {
-        return mIsActive;
+    // Start: getters/setters
+    inline const int64_t& getMetricId() const {
+        return mMetricId;
     }
 
-    void loadActiveMetricLocked(const ActiveMetric& activeMetric, int64_t currentTimeNs);
+    // For test only.
+    inline int64_t getCurrentBucketNum() const {
+        return mCurrentBucketNum;
+    }
 
-    virtual void prepareFirstBucketLocked() {};
+    int64_t getBucketSizeInNs() const {
+        std::lock_guard<std::mutex> lock(mMutex);
+        return mBucketSizeNs;
+    }
+
+    /* If alert is valid, adds an AnomalyTracker and returns it. If invalid, returns nullptr. */
+    virtual sp<AnomalyTracker> addAnomalyTracker(const Alert &alert,
+                                                 const sp<AlarmMonitor>& anomalyAlarmMonitor) {
+        std::lock_guard<std::mutex> lock(mMutex);
+        sp<AnomalyTracker> anomalyTracker = new AnomalyTracker(alert, mConfigKey);
+        if (anomalyTracker != nullptr) {
+            mAnomalyTrackers.push_back(anomalyTracker);
+        }
+        return anomalyTracker;
+    }
+    // End: getters/setters
+protected:
     /**
      * Flushes the current bucket if the eventTime is after the current bucket's end time. This will
        also flush the current partial bucket in memory.
@@ -283,14 +249,6 @@
     virtual void flushIfNeededLocked(const int64_t& eventTime){};
 
     /**
-     * Flushes all the data including the current partial bucket.
-     */
-    virtual void flushLocked(const int64_t& eventTimeNs) {
-        flushIfNeededLocked(eventTimeNs);
-        flushCurrentBucketLocked(eventTimeNs, eventTimeNs);
-    };
-
-    /**
      * For metrics that aggregate (ie, every metric producer except for EventMetricProducer),
      * we need to be able to flush the current buckets on demand (ie, end the current bucket and
      * start new bucket). If this function is called when eventTimeNs is greater than the current
@@ -303,62 +261,13 @@
     virtual void flushCurrentBucketLocked(const int64_t& eventTimeNs,
                                           const int64_t& nextBucketStartTimeNs) {};
 
-    virtual void onActiveStateChangedLocked(const int64_t& eventTimeNs) {
-        if (!mIsActive) {
-            flushLocked(eventTimeNs);
-        }
-    }
-
-    // Convenience to compute the current bucket's end time, which is always aligned with the
-    // start time of the metric.
-    int64_t getCurrentBucketEndTimeNs() const {
-        return mTimeBaseNs + (mCurrentBucketNum + 1) * mBucketSizeNs;
-    }
-
-    int64_t getBucketNumFromEndTimeNs(const int64_t endNs) {
-        return (endNs - mTimeBaseNs) / mBucketSizeNs - 1;
-    }
-
-    virtual void dropDataLocked(const int64_t dropTimeNs) = 0;
-
-    const int64_t mMetricId;
-
-    const ConfigKey mConfigKey;
-
-    // The time when this metric producer was first created. The end time for the current bucket
-    // can be computed from this based on mCurrentBucketNum.
-    int64_t mTimeBaseNs;
-
-    // Start time may not be aligned with the start of statsd if there is an app upgrade in the
-    // middle of a bucket.
-    int64_t mCurrentBucketStartTimeNs;
-
-    // Used by anomaly detector to track which bucket we are in. This is not sent with the produced
-    // report.
-    int64_t mCurrentBucketNum;
-
-    int64_t mBucketSizeNs;
-
-    ConditionState mCondition;
-
-    bool mConditionSliced;
-
-    sp<ConditionWizard> mWizard;
-
-    int mConditionTrackerIndex;
-
-    vector<Matcher> mDimensionsInWhat;       // The dimensions_in_what defined in statsd_config
-
-    bool mContainANYPositionInDimensionsInWhat;
-    bool mSliceByPositionALL;
-
-    // True iff the metric to condition links cover all dimension fields in the condition tracker.
-    // This field is always false for combinational condition trackers.
-    bool mHasLinksToAllConditionDimensionsInTracker;
-
-    std::vector<Metric2Condition> mMetric2ConditionLinks;
-
-    std::vector<sp<AnomalyTracker>> mAnomalyTrackers;
+    /**
+     * Flushes all the data including the current partial bucket.
+     */
+    virtual void flushLocked(const int64_t& eventTimeNs) {
+        flushIfNeededLocked(eventTimeNs);
+        flushCurrentBucketLocked(eventTimeNs, eventTimeNs);
+    };
 
     /*
      * Individual metrics can implement their own business logic here. All pre-processing is done.
@@ -382,21 +291,87 @@
 
     // Consume the parsed stats log entry that already matched the "what" of the metric.
     virtual void onMatchedLogEventLocked(const size_t matcherIndex, const LogEvent& event);
+    virtual void onConditionChangedLocked(const bool condition, const int64_t eventTime) = 0;
+    virtual void onSlicedConditionMayChangeLocked(bool overallCondition,
+                                                  const int64_t eventTime) = 0;
+    virtual void onDumpReportLocked(const int64_t dumpTimeNs,
+                                    const bool include_current_partial_bucket,
+                                    const bool erase_data,
+                                    const DumpLatency dumpLatency,
+                                    std::set<string> *str_set,
+                                    android::util::ProtoOutputStream* protoOutput) = 0;
+    virtual void clearPastBucketsLocked(const int64_t dumpTimeNs) = 0;
+    virtual size_t byteSizeLocked() const = 0;
+    virtual void dumpStatesLocked(FILE* out, bool verbose) const = 0;
+    virtual void dropDataLocked(const int64_t dropTimeNs) = 0;
+    void loadActiveMetricLocked(const ActiveMetric& activeMetric, int64_t currentTimeNs);
+    void activateLocked(int activationTrackerIndex, int64_t elapsedTimestampNs);
+    void cancelEventActivationLocked(int deactivationTrackerIndex);
+
+    bool evaluateActiveStateLocked(int64_t elapsedTimestampNs);
+
+    virtual void onActiveStateChangedLocked(const int64_t& eventTimeNs) {
+        if (!mIsActive) {
+            flushLocked(eventTimeNs);
+        }
+    }
+
+    inline bool isActiveLocked() const {
+        return mIsActive;
+    }
+
+    // Convenience to compute the current bucket's end time, which is always aligned with the
+    // start time of the metric.
+    int64_t getCurrentBucketEndTimeNs() const {
+        return mTimeBaseNs + (mCurrentBucketNum + 1) * mBucketSizeNs;
+    }
+
+    int64_t getBucketNumFromEndTimeNs(const int64_t endNs) {
+        return (endNs - mTimeBaseNs) / mBucketSizeNs - 1;
+    }
+
+    const int64_t mMetricId;
+
+    const ConfigKey mConfigKey;
+
+    // The time when this metric producer was first created. The end time for the current bucket
+    // can be computed from this based on mCurrentBucketNum.
+    int64_t mTimeBaseNs;
+
+    // Start time may not be aligned with the start of statsd if there is an app upgrade in the
+    // middle of a bucket.
+    int64_t mCurrentBucketStartTimeNs;
+
+    // Used by anomaly detector to track which bucket we are in. This is not sent with the produced
+    // report.
+    int64_t mCurrentBucketNum;
+
+    int64_t mBucketSizeNs;
+
+    ConditionState mCondition;
+
+    int mConditionTrackerIndex;
+
+    bool mConditionSliced;
+
+    sp<ConditionWizard> mWizard;
+
+    bool mContainANYPositionInDimensionsInWhat;
+
+    bool mSliceByPositionALL;
+
+    vector<Matcher> mDimensionsInWhat;  // The dimensions_in_what defined in statsd_config
+
+    // True iff the metric to condition links cover all dimension fields in the condition tracker.
+    // This field is always false for combinational condition trackers.
+    bool mHasLinksToAllConditionDimensionsInTracker;
+
+    std::vector<Metric2Condition> mMetric2ConditionLinks;
+
+    std::vector<sp<AnomalyTracker>> mAnomalyTrackers;
 
     mutable std::mutex mMutex;
 
-    struct Activation {
-        Activation(const ActivationType& activationType, const int64_t ttlNs)
-            : ttl_ns(ttlNs),
-              start_ns(0),
-              state(ActivationState::kNotActive),
-              activationType(activationType) {}
-
-        const int64_t ttl_ns;
-        int64_t start_ns;
-        ActivationState state;
-        const ActivationType activationType;
-    };
     // When the metric producer has multiple activations, these activations are ORed to determine
     // whether the metric producer is ready to generate metrics.
     std::unordered_map<int, std::shared_ptr<Activation>> mEventActivationMap;
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.cpp b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
index bc16024..7fe5a83 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
@@ -81,8 +81,11 @@
         const ConfigKey& key, const ValueMetric& metric, const int conditionIndex,
         const sp<ConditionWizard>& conditionWizard, const int whatMatcherIndex,
         const sp<EventMatcherWizard>& matcherWizard, const int pullTagId, const int64_t timeBaseNs,
-        const int64_t startTimeNs, const sp<StatsPullerManager>& pullerManager)
-    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, conditionWizard),
+        const int64_t startTimeNs, const sp<StatsPullerManager>& pullerManager,
+        const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
+        const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap)
+    : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, conditionWizard,
+                     eventActivationMap, eventDeactivationMap),
       mWhatMatcherIndex(whatMatcherIndex),
       mEventMatcherWizard(matcherWizard),
       mPullerManager(pullerManager),
@@ -108,7 +111,7 @@
       mMaxPullDelayNs(metric.max_pull_delay_sec() > 0 ? metric.max_pull_delay_sec() * NS_PER_SEC
                                                       : StatsdStats::kPullMaxDelayNs),
       mSplitBucketForAppUpgrade(metric.split_bucket_for_app_upgrade()),
-      // Condition timer will be set in prepareFirstBucketLocked.
+      // Condition timer will be set later within the constructor after pulling events
       mConditionTimer(false, timeBaseNs) {
     int64_t bucketSizeMills = 0;
     if (metric.has_bucket()) {
@@ -154,6 +157,15 @@
     // Adjust start for partial bucket
     mCurrentBucketStartTimeNs = startTimeNs;
     mConditionTimer.newBucketStart(mCurrentBucketStartTimeNs);
+
+     // Kicks off the puller immediately if condition is true and diff based.
+    if (mIsActive && mIsPulled && mCondition == ConditionState::kTrue && mUseDiff) {
+        pullAndMatchEventsLocked(mCurrentBucketStartTimeNs, mCondition);
+    }
+    // Now that activations are processed, start the condition timer if needed.
+    mConditionTimer.onConditionChanged(mIsActive && mCondition == ConditionState::kTrue,
+                                       mCurrentBucketStartTimeNs);
+
     VLOG("value metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
          (long long)mBucketSizeNs, (long long)mTimeBaseNs);
 }
@@ -165,16 +177,6 @@
     }
 }
 
-void ValueMetricProducer::prepareFirstBucketLocked() {
-    // Kicks off the puller immediately if condition is true and diff based.
-    if (mIsActive && mIsPulled && mCondition == ConditionState::kTrue && mUseDiff) {
-        pullAndMatchEventsLocked(mCurrentBucketStartTimeNs, mCondition);
-    }
-    // Now that activations are processed, start the condition timer if needed.
-    mConditionTimer.onConditionChanged(mIsActive && mCondition == ConditionState::kTrue,
-                                       mCurrentBucketStartTimeNs);
-}
-
 void ValueMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
                                                            const int64_t eventTime) {
     VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.h b/cmds/statsd/src/metrics/ValueMetricProducer.h
index 739f6ef..d7cd397 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.h
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.h
@@ -54,10 +54,13 @@
 public:
     ValueMetricProducer(const ConfigKey& key, const ValueMetric& valueMetric,
                         const int conditionIndex, const sp<ConditionWizard>& conditionWizard,
-                        const int whatMatcherIndex,
-                        const sp<EventMatcherWizard>& matcherWizard,
+                        const int whatMatcherIndex, const sp<EventMatcherWizard>& matcherWizard,
                         const int pullTagId, const int64_t timeBaseNs, const int64_t startTimeNs,
-                        const sp<StatsPullerManager>& pullerManager);
+                        const sp<StatsPullerManager>& pullerManager,
+                        const std::unordered_map<int, std::shared_ptr<Activation>>&
+                                eventActivationMap = {},
+                        const std::unordered_map<int, std::vector<std::shared_ptr<Activation>>>&
+                                eventDeactivationMap = {});
 
     virtual ~ValueMetricProducer();
 
@@ -116,8 +119,6 @@
     void flushCurrentBucketLocked(const int64_t& eventTimeNs,
                                   const int64_t& nextBucketStartTimeNs) override;
 
-    void prepareFirstBucketLocked() override;
-
     void dropDataLocked(const int64_t dropTimeNs) override;
 
     // Calculate previous bucket end time based on current time.
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.cpp b/cmds/statsd/src/metrics/metrics_manager_util.cpp
index 40484f4..0fee71e 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.cpp
+++ b/cmds/statsd/src/metrics/metrics_manager_util.cpp
@@ -18,6 +18,7 @@
 #include "Log.h"
 
 #include "metrics_manager_util.h"
+#include "MetricProducer.h"
 
 #include "../condition/CombinationConditionTracker.h"
 #include "../condition/SimpleConditionTracker.h"
@@ -137,6 +138,62 @@
     return true;
 }
 
+// Validates a metricActivation and populates state.
+// EventActivationMap and EventDeactivationMap are supplied to a MetricProducer
+//      to provide the producer with state about its activators and deactivators.
+// Returns false if there are errors.
+bool handleMetricActivation(
+        const StatsdConfig& config,
+        const int64_t metricId,
+        const int metricIndex,
+        const unordered_map<int64_t, int>& metricToActivationMap,
+        const unordered_map<int64_t, int>& logTrackerMap,
+        unordered_map<int, vector<int>>& activationAtomTrackerToMetricMap,
+        unordered_map<int, vector<int>>& deactivationAtomTrackerToMetricMap,
+        vector<int>& metricsWithActivation,
+        unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
+        unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap) {
+    // Check if metric has an associated activation
+    auto itr = metricToActivationMap.find(metricId);
+    if (itr == metricToActivationMap.end()) return true;
+
+    int activationIndex = itr->second;
+    const MetricActivation& metricActivation = config.metric_activation(activationIndex);
+
+    for (int i = 0; i < metricActivation.event_activation_size(); i++) {
+        const EventActivation& activation = metricActivation.event_activation(i);
+
+        auto itr = logTrackerMap.find(activation.atom_matcher_id());
+        if (itr == logTrackerMap.end()) {
+            ALOGE("Atom matcher not found for event activation.");
+            return false;
+        }
+
+        ActivationType activationType = (activation.has_activation_type()) ?
+                activation.activation_type() : metricActivation.activation_type();
+        std::shared_ptr<Activation> activationWrapper = std::make_shared<Activation>(
+                activationType, activation.ttl_seconds() * NS_PER_SEC);
+
+        int atomMatcherIndex = itr->second;
+        activationAtomTrackerToMetricMap[atomMatcherIndex].push_back(metricIndex);
+        eventActivationMap.emplace(atomMatcherIndex, activationWrapper);
+
+        if (activation.has_deactivation_atom_matcher_id()) {
+            itr = logTrackerMap.find(activation.deactivation_atom_matcher_id());
+            if (itr == logTrackerMap.end()) {
+                ALOGE("Atom matcher not found for event deactivation.");
+                return false;
+            }
+            int deactivationAtomMatcherIndex = itr->second;
+            deactivationAtomTrackerToMetricMap[deactivationAtomMatcherIndex].push_back(metricIndex);
+            eventDeactivationMap[deactivationAtomMatcherIndex].push_back(activationWrapper);
+        }
+    }
+
+    metricsWithActivation.push_back(metricIndex);
+    return true;
+}
+
 bool initLogTrackers(const StatsdConfig& config, const UidMap& uidMap,
                      unordered_map<int64_t, int>& logTrackerMap,
                      vector<sp<LogMatchingTracker>>& allAtomMatchers, set<int>& allTagIds) {
@@ -293,16 +350,33 @@
                  const vector<sp<LogMatchingTracker>>& allAtomMatchers,
                  vector<sp<ConditionTracker>>& allConditionTrackers,
                  vector<sp<MetricProducer>>& allMetricProducers,
-                 unordered_map<int, std::vector<int>>& conditionToMetricMap,
-                 unordered_map<int, std::vector<int>>& trackerToMetricMap,
-                 unordered_map<int64_t, int>& metricMap, std::set<int64_t>& noReportMetricIds) {
+                 unordered_map<int, vector<int>>& conditionToMetricMap,
+                 unordered_map<int, vector<int>>& trackerToMetricMap,
+                 unordered_map<int64_t, int>& metricMap, std::set<int64_t>& noReportMetricIds,
+                 unordered_map<int, vector<int>>& activationAtomTrackerToMetricMap,
+                 unordered_map<int, vector<int>>& deactivationAtomTrackerToMetricMap,
+                 vector<int>& metricsWithActivation) {
     sp<ConditionWizard> wizard = new ConditionWizard(allConditionTrackers);
     sp<EventMatcherWizard> matcherWizard = new EventMatcherWizard(allAtomMatchers);
     const int allMetricsCount = config.count_metric_size() + config.duration_metric_size() +
-                                config.event_metric_size() + config.value_metric_size();
+                                config.event_metric_size() + config.gauge_metric_size() +
+                                config.value_metric_size();
     allMetricProducers.reserve(allMetricsCount);
     StatsPullerManager statsPullerManager;
 
+    // Construct map from metric id to metric activation index. The map will be used to determine
+    // the metric activation corresponding to a metric.
+    unordered_map<int64_t, int> metricToActivationMap;
+    for (int i = 0; i < config.metric_activation_size(); i++) {
+        const MetricActivation& metricActivation = config.metric_activation(i);
+        int64_t metricId = metricActivation.metric_id();
+        if (metricToActivationMap.find(metricId) != metricToActivationMap.end()) {
+            ALOGE("Metric %lld has multiple MetricActivations", (long long) metricId);
+            return false;
+        }
+        metricToActivationMap.insert({metricId, i});
+    }
+
     // Build MetricProducers for each metric defined in config.
     // build CountMetricProducer
     for (int i = 0; i < config.count_metric_size(); i++) {
@@ -337,8 +411,17 @@
             }
         }
 
-        sp<MetricProducer> countProducer =
-                new CountMetricProducer(key, metric, conditionIndex, wizard, timeBaseTimeNs, currentTimeNs);
+        unordered_map<int, shared_ptr<Activation>> eventActivationMap;
+        unordered_map<int, vector<shared_ptr<Activation>>> eventDeactivationMap;
+        bool success = handleMetricActivation(config, metric.id(), metricIndex,
+                metricToActivationMap, logTrackerMap, activationAtomTrackerToMetricMap,
+                deactivationAtomTrackerToMetricMap, metricsWithActivation, eventActivationMap,
+                eventDeactivationMap);
+        if (!success) return false;
+
+        sp<MetricProducer> countProducer = new CountMetricProducer(
+                key, metric, conditionIndex, wizard, timeBaseTimeNs, currentTimeNs,
+                eventActivationMap, eventDeactivationMap);
         allMetricProducers.push_back(countProducer);
     }
 
@@ -406,9 +489,18 @@
             }
         }
 
+        unordered_map<int, shared_ptr<Activation>> eventActivationMap;
+        unordered_map<int, vector<shared_ptr<Activation>>> eventDeactivationMap;
+        bool success = handleMetricActivation(config, metric.id(), metricIndex,
+                metricToActivationMap, logTrackerMap, activationAtomTrackerToMetricMap,
+                deactivationAtomTrackerToMetricMap, metricsWithActivation, eventActivationMap,
+                eventDeactivationMap);
+        if (!success) return false;
+
         sp<MetricProducer> durationMetric = new DurationMetricProducer(
                 key, metric, conditionIndex, trackerIndices[0], trackerIndices[1],
-                trackerIndices[2], nesting, wizard, internalDimensions, timeBaseTimeNs, currentTimeNs);
+                trackerIndices[2], nesting, wizard, internalDimensions, timeBaseTimeNs,
+                currentTimeNs, eventActivationMap, eventDeactivationMap);
 
         allMetricProducers.push_back(durationMetric);
     }
@@ -443,8 +535,17 @@
             }
         }
 
-        sp<MetricProducer> eventMetric =
-                new EventMetricProducer(key, metric, conditionIndex, wizard, timeBaseTimeNs);
+        unordered_map<int, shared_ptr<Activation>> eventActivationMap;
+        unordered_map<int, vector<shared_ptr<Activation>>> eventDeactivationMap;
+        bool success = handleMetricActivation(config, metric.id(), metricIndex,
+                metricToActivationMap, logTrackerMap, activationAtomTrackerToMetricMap,
+                deactivationAtomTrackerToMetricMap, metricsWithActivation, eventActivationMap,
+                eventDeactivationMap);
+        if (!success) return false;
+
+        sp<MetricProducer> eventMetric = new EventMetricProducer(
+                key, metric, conditionIndex, wizard, timeBaseTimeNs, eventActivationMap,
+                eventDeactivationMap);
 
         allMetricProducers.push_back(eventMetric);
     }
@@ -500,9 +601,18 @@
             }
         }
 
+        unordered_map<int, shared_ptr<Activation>> eventActivationMap;
+        unordered_map<int, vector<shared_ptr<Activation>>> eventDeactivationMap;
+        bool success = handleMetricActivation(config, metric.id(), metricIndex,
+                metricToActivationMap, logTrackerMap, activationAtomTrackerToMetricMap,
+                deactivationAtomTrackerToMetricMap, metricsWithActivation, eventActivationMap,
+                eventDeactivationMap);
+        if (!success) return false;
+
         sp<MetricProducer> valueProducer = new ValueMetricProducer(
                 key, metric, conditionIndex, wizard, trackerIndex, matcherWizard, pullTagId,
-                timeBaseTimeNs, currentTimeNs, pullerManager);
+                timeBaseTimeNs, currentTimeNs, pullerManager, eventActivationMap,
+                eventDeactivationMap);
         allMetricProducers.push_back(valueProducer);
     }
 
@@ -586,10 +696,19 @@
             }
         }
 
+        unordered_map<int, shared_ptr<Activation>> eventActivationMap;
+        unordered_map<int, vector<shared_ptr<Activation>>> eventDeactivationMap;
+        bool success = handleMetricActivation(config, metric.id(), metricIndex,
+                metricToActivationMap, logTrackerMap, activationAtomTrackerToMetricMap,
+                deactivationAtomTrackerToMetricMap, metricsWithActivation, eventActivationMap,
+                eventDeactivationMap);
+        if (!success) return false;
+
         sp<MetricProducer> gaugeProducer = new GaugeMetricProducer(
                 key, metric, conditionIndex, wizard,
                 trackerIndex, matcherWizard, pullTagId, triggerAtomId, atomTagId,
-                timeBaseTimeNs, currentTimeNs, pullerManager);
+                timeBaseTimeNs, currentTimeNs, pullerManager,
+                eventActivationMap, eventDeactivationMap);
         allMetricProducers.push_back(gaugeProducer);
     }
     for (int i = 0; i < config.no_report_metric_size(); ++i) {
@@ -707,73 +826,6 @@
     return true;
 }
 
-bool initMetricActivations(const ConfigKey& key, const StatsdConfig& config,
-                           const int64_t currentTimeNs,
-                           const unordered_map<int64_t, int> &logEventTrackerMap,
-                           const unordered_map<int64_t, int> &metricProducerMap,
-                           vector<sp<MetricProducer>>& allMetricProducers,
-                           unordered_map<int, std::vector<int>>& activationAtomTrackerToMetricMap,
-                           unordered_map<int, std::vector<int>>& deactivationAtomTrackerToMetricMap,
-                           vector<int>& metricsWithActivation) {
-    for (int i = 0; i < config.metric_activation_size(); ++i) {
-        const MetricActivation& metric_activation = config.metric_activation(i);
-        auto itr = metricProducerMap.find(metric_activation.metric_id());
-        if (itr == metricProducerMap.end()) {
-            ALOGE("Metric id not found in metric activation: %lld",
-                (long long)metric_activation.metric_id());
-            return false;
-        }
-        const int metricTrackerIndex = itr->second;
-        if (metricTrackerIndex < 0 || metricTrackerIndex >= (int)allMetricProducers.size()) {
-            ALOGE("Invalid metric tracker index.");
-            return false;
-        }
-        const sp<MetricProducer>& metric = allMetricProducers[metricTrackerIndex];
-        metricsWithActivation.push_back(metricTrackerIndex);
-        for (int j = 0; j < metric_activation.event_activation_size(); ++j) {
-            const EventActivation& activation = metric_activation.event_activation(j);
-            auto logTrackerIt = logEventTrackerMap.find(activation.atom_matcher_id());
-            if (logTrackerIt == logEventTrackerMap.end()) {
-                ALOGE("Atom matcher not found for event activation.");
-                return false;
-            }
-            const int atomMatcherIndex = logTrackerIt->second;
-            activationAtomTrackerToMetricMap[atomMatcherIndex].push_back(
-                metricTrackerIndex);
-
-            ActivationType activationType;
-            if (activation.has_activation_type()) {
-                activationType = activation.activation_type();
-            } else {
-                activationType = metric_activation.activation_type();
-            }
-
-            if (activation.has_deactivation_atom_matcher_id()) {
-                auto deactivationAtomMatcherIt =
-                        logEventTrackerMap.find(activation.deactivation_atom_matcher_id());
-                if (deactivationAtomMatcherIt == logEventTrackerMap.end()) {
-                    ALOGE("Atom matcher not found for event deactivation.");
-                    return false;
-                }
-                const int deactivationMatcherIndex = deactivationAtomMatcherIt->second;
-                deactivationAtomTrackerToMetricMap[deactivationMatcherIndex]
-                        .push_back(metricTrackerIndex);
-                metric->addActivation(atomMatcherIndex, activationType, activation.ttl_seconds(),
-                                      deactivationMatcherIndex);
-            } else {
-                metric->addActivation(atomMatcherIndex, activationType, activation.ttl_seconds());
-            }
-        }
-    }
-    return true;
-}
-
-void prepareFirstBucket(const vector<sp<MetricProducer>>& allMetricProducers) {
-    for (const auto& metric: allMetricProducers) {
-        metric->prepareFirstBucket();
-    }
-}
-
 bool initStatsdConfig(const ConfigKey& key, const StatsdConfig& config, UidMap& uidMap,
                       const sp<StatsPullerManager>& pullerManager,
                       const sp<AlarmMonitor>& anomalyAlarmMonitor,
@@ -810,7 +862,8 @@
     if (!initMetrics(key, config, timeBaseNs, currentTimeNs, uidMap, pullerManager, logTrackerMap,
                      conditionTrackerMap, allAtomMatchers, allConditionTrackers, allMetricProducers,
                      conditionToMetricMap, trackerToMetricMap, metricProducerMap,
-                     noReportMetricIds)) {
+                     noReportMetricIds, activationAtomTrackerToMetricMap,
+                     deactivationAtomTrackerToMetricMap, metricsWithActivation)) {
         ALOGE("initMetricProducers failed");
         return false;
     }
@@ -824,14 +877,6 @@
         ALOGE("initAlarms failed");
         return false;
     }
-    if (!initMetricActivations(key, config, currentTimeNs, logTrackerMap, metricProducerMap,
-            allMetricProducers, activationAtomTrackerToMetricMap,
-            deactivationAtomTrackerToMetricMap, metricsWithActivation)) {
-        ALOGE("initMetricActivations failed");
-        return false;
-    }
-
-    prepareFirstBucket(allMetricProducers);
 
     return true;
 }
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.h b/cmds/statsd/src/metrics/metrics_manager_util.h
index 3704969..3802948 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.h
+++ b/cmds/statsd/src/metrics/metrics_manager_util.h
@@ -91,7 +91,10 @@
         std::vector<sp<MetricProducer>>& allMetricProducers,
         std::unordered_map<int, std::vector<int>>& conditionToMetricMap,
         std::unordered_map<int, std::vector<int>>& trackerToMetricMap,
-        std::set<int64_t>& noReportMetricIds);
+        std::set<int64_t>& noReportMetricIds,
+        std::unordered_map<int, std::vector<int>>& activationAtomTrackerToMetricMap,
+        std::unordered_map<int, std::vector<int>>& deactivationAtomTrackerToMetricMap,
+        std::vector<int>& metricsWithActivation);
 
 // Initialize MetricsManager from StatsdConfig.
 // Parameters are the members of MetricsManager. See MetricsManager for declaration.
diff --git a/cmds/statsd/src/state/StateListener.h b/cmds/statsd/src/state/StateListener.h
new file mode 100644
index 0000000..a31690a
--- /dev/null
+++ b/cmds/statsd/src/state/StateListener.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+#pragma once
+
+#include <utils/RefBase.h>
+
+#include "HashableDimensionKey.h"
+
+namespace android {
+namespace os {
+namespace statsd {
+
+class StateListener : public virtual RefBase {
+public:
+    StateListener(){};
+
+    virtual ~StateListener(){};
+
+    /**
+     * Interface for handling a state change.
+     *
+     * The old and new state values map to the original state values.
+     * StateTrackers only track the original state values and are unaware
+     * of higher-level state groups. MetricProducers hold information on
+     * state groups and are responsible for mapping original state values to
+     * the correct state group.
+     *
+     * [atomId]: The id of the state atom
+     * [primaryKey]: The primary field values of the state atom
+     * [oldState]: Previous state value before state change
+     * [newState]: Current state value after state change
+     */
+    virtual void onStateChanged(int atomId, const HashableDimensionKey& primaryKey, int oldState,
+                                int newState) = 0;
+};
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
diff --git a/cmds/statsd/src/state/StateManager.cpp b/cmds/statsd/src/state/StateManager.cpp
new file mode 100644
index 0000000..a3059c5
--- /dev/null
+++ b/cmds/statsd/src/state/StateManager.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+
+#define DEBUG false  // STOPSHIP if true
+#include "Log.h"
+
+#include "StateManager.h"
+
+namespace android {
+namespace os {
+namespace statsd {
+
+StateManager& StateManager::getInstance() {
+    static StateManager sStateManager;
+    return sStateManager;
+}
+
+void StateManager::onLogEvent(const LogEvent& event) {
+    std::lock_guard<std::mutex> lock(mMutex);
+    if (mStateTrackers.find(event.GetTagId()) != mStateTrackers.end()) {
+        mStateTrackers[event.GetTagId()]->onLogEvent(event);
+    }
+}
+
+bool StateManager::registerListener(int stateAtomId, wp<StateListener> listener) {
+    std::lock_guard<std::mutex> lock(mMutex);
+
+    // Check if state tracker already exists
+    if (mStateTrackers.find(stateAtomId) == mStateTrackers.end()) {
+        // Create a new state tracker iff atom is a state atom
+        auto it = android::util::AtomsInfo::kStateAtomsFieldOptions.find(stateAtomId);
+        if (it != android::util::AtomsInfo::kStateAtomsFieldOptions.end()) {
+            mStateTrackers[stateAtomId] = new StateTracker(stateAtomId, it->second);
+        } else {
+            ALOGE("StateManager cannot register listener, Atom %d is not a state atom",
+                  stateAtomId);
+            return false;
+        }
+    }
+    mStateTrackers[stateAtomId]->registerListener(listener);
+    return true;
+}
+
+void StateManager::unregisterListener(int stateAtomId, wp<StateListener> listener) {
+    std::unique_lock<std::mutex> lock(mMutex);
+
+    // Hold the sp<> until the lock is released so that ~StateTracker() is
+    // not called while the lock is held.
+    sp<StateTracker> toRemove;
+
+    // Unregister listener from correct StateTracker
+    auto it = mStateTrackers.find(stateAtomId);
+    if (it != mStateTrackers.end()) {
+        it->second->unregisterListener(listener);
+
+        // Remove the StateTracker if it has no listeners
+        if (it->second->getListenersCount() == 0) {
+            toRemove = it->second;
+            mStateTrackers.erase(it);
+        }
+    } else {
+        ALOGE("StateManager cannot unregister listener, StateTracker for atom %d does not exist",
+              stateAtomId);
+    }
+    lock.unlock();
+}
+
+int StateManager::getState(int stateAtomId, const HashableDimensionKey& key) {
+    std::lock_guard<std::mutex> lock(mMutex);
+    if (mStateTrackers.find(stateAtomId) != mStateTrackers.end()) {
+        return mStateTrackers[stateAtomId]->getState(key);
+    }
+
+    return StateTracker::kStateUnknown;
+}
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
diff --git a/cmds/statsd/src/state/StateManager.h b/cmds/statsd/src/state/StateManager.h
new file mode 100644
index 0000000..ce60f14
--- /dev/null
+++ b/cmds/statsd/src/state/StateManager.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+#pragma once
+
+//#include <utils/Log.h>
+#include <utils/RefBase.h>
+#include "HashableDimensionKey.h"
+
+#include "state/StateListener.h"
+#include "state/StateTracker.h"
+
+namespace android {
+namespace os {
+namespace statsd {
+
+class StateManager : public virtual RefBase {
+public:
+    StateManager(){};
+
+    ~StateManager(){};
+
+    // Returns a pointer to the single, shared StateManager object.
+    static StateManager& getInstance();
+
+    // Notifies the correct StateTracker of an event.
+    void onLogEvent(const LogEvent& event);
+
+    // Returns true if stateAtomId is the id of a state atom and notifies the
+    // correct StateTracker to register the listener. If the correct
+    // StateTracker does not exist, a new StateTracker is created.
+    bool registerListener(int stateAtomId, wp<StateListener> listener);
+
+    // Notifies the correct StateTracker to unregister a listener
+    // and removes the tracker if it no longer has any listeners.
+    void unregisterListener(int stateAtomId, wp<StateListener> listener);
+
+    // Queries the correct StateTracker for the state that is mapped to the given
+    // query key.
+    // If the StateTracker doesn't exist, returns StateTracker::kStateUnknown.
+    int getState(int stateAtomId, const HashableDimensionKey& queryKey);
+
+    inline int getStateTrackersCount() {
+        std::lock_guard<std::mutex> lock(mMutex);
+        return mStateTrackers.size();
+    }
+
+    inline int getListenersCount(int stateAtomId) {
+        std::lock_guard<std::mutex> lock(mMutex);
+        if (mStateTrackers.find(stateAtomId) != mStateTrackers.end()) {
+            return mStateTrackers[stateAtomId]->getListenersCount();
+        }
+        return -1;
+    }
+
+private:
+  mutable std::mutex mMutex;
+
+  // Maps state atom ids to StateTrackers
+  std::unordered_map<int, sp<StateTracker>> mStateTrackers;
+};
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
diff --git a/cmds/statsd/src/state/StateTracker.cpp b/cmds/statsd/src/state/StateTracker.cpp
new file mode 100644
index 0000000..5a91950
--- /dev/null
+++ b/cmds/statsd/src/state/StateTracker.cpp
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+
+#define DEBUG true  // STOPSHIP if true
+#include "Log.h"
+
+#include "stats_util.h"
+
+#include "StateTracker.h"
+
+namespace android {
+namespace os {
+namespace statsd {
+
+StateTracker::StateTracker(const int atomId,
+                           const util::StateAtomFieldOptions& stateAtomInfo)
+  : mAtomId(atomId),
+    mStateField(getSimpleMatcher(atomId, stateAtomInfo.exclusiveField)) {
+    // create matcher for each primary field
+    // TODO(tsaichristine): handle when primary field is first uid in chain
+    for (const auto& primary : stateAtomInfo.primaryFields) {
+        Matcher matcher = getSimpleMatcher(atomId, primary);
+        mPrimaryFields.push_back(matcher);
+    }
+
+    // TODO(tsaichristine): set default state, reset state, and nesting
+}
+
+void StateTracker::onLogEvent(const LogEvent& event) {
+    // parse event for primary field values i.e. primary key
+    HashableDimensionKey primaryKey;
+    if (mPrimaryFields.size() > 0) {
+        if (!filterValues(mPrimaryFields, event.getValues(), &primaryKey) ||
+            primaryKey.getValues().size() != mPrimaryFields.size()) {
+            ALOGE("StateTracker error extracting primary key from log event.");
+            handleReset();
+            return;
+        }
+    } else {
+        // atom has no primary fields
+        primaryKey = DEFAULT_DIMENSION_KEY;
+    }
+
+    // parse event for state value
+    Value state;
+    int32_t stateValue;
+    if (!filterValues(mStateField, event.getValues(), &state) || state.getType() != INT) {
+        ALOGE("StateTracker error extracting state from log event. Type: %d", state.getType());
+        handlePartialReset(primaryKey);
+        return;
+    }
+    stateValue = state.int_value;
+
+    if (stateValue == mResetState) {
+        VLOG("StateTracker Reset state: %s", state.toString().c_str());
+        handleReset();
+    }
+
+    // track and update state
+    int32_t oldState = 0;
+    int32_t newState = 0;
+    updateState(primaryKey, stateValue, &oldState, &newState);
+
+    // notify all listeners if state has changed
+    if (oldState != newState) {
+        VLOG("StateTracker updated state");
+        for (auto listener : mListeners) {
+            auto sListener = listener.promote();  // safe access to wp<>
+            if (sListener != nullptr) {
+                sListener->onStateChanged(mAtomId, primaryKey, oldState, newState);
+            }
+        }
+    } else {
+        VLOG("StateTracker NO updated state");
+    }
+}
+
+void StateTracker::registerListener(wp<StateListener> listener) {
+    mListeners.insert(listener);
+}
+
+void StateTracker::unregisterListener(wp<StateListener> listener) {
+    mListeners.erase(listener);
+}
+
+int StateTracker::getState(const HashableDimensionKey& queryKey) const {
+    if (queryKey.getValues().size() == mPrimaryFields.size()) {
+        auto it = mStateMap.find(queryKey);
+        if (it != mStateMap.end()) {
+            return it->second.state;
+        }
+    } else if (queryKey.getValues().size() > mPrimaryFields.size()) {
+        ALOGE("StateTracker query key size > primary key size is illegal");
+    } else {
+        ALOGE("StateTracker query key size < primary key size is not supported");
+    }
+    return mDefaultState;
+}
+
+void StateTracker::handleReset() {
+    VLOG("StateTracker handle reset");
+    for (const auto pair : mStateMap) {
+        for (auto l : mListeners) {
+            auto sl = l.promote();
+            if (sl != nullptr) {
+                sl->onStateChanged(mAtomId, pair.first, pair.second.state, mDefaultState);
+            }
+        }
+    }
+    mStateMap.clear();
+}
+
+void StateTracker::handlePartialReset(const HashableDimensionKey& primaryKey) {
+    VLOG("StateTracker handle partial reset");
+    if (mStateMap.find(primaryKey) != mStateMap.end()) {
+        mStateMap.erase(primaryKey);
+    }
+}
+
+void StateTracker::updateState(const HashableDimensionKey& primaryKey, const int32_t eventState,
+                               int32_t* oldState, int32_t* newState) {
+    // get old state (either current state in map or default state)
+    auto it = mStateMap.find(primaryKey);
+    if (it != mStateMap.end()) {
+        *oldState = it->second.state;
+    } else {
+        *oldState = mDefaultState;
+    }
+
+    // update state map
+    if (eventState == mDefaultState) {
+        // remove (key, state) pair if state returns to default state
+        VLOG("\t StateTracker changed to default state")
+        mStateMap.erase(primaryKey);
+    } else {
+        mStateMap[primaryKey].state = eventState;
+        mStateMap[primaryKey].count = 1;
+    }
+    *newState = eventState;
+
+    // TODO(tsaichristine): support atoms with nested counting
+}
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
diff --git a/cmds/statsd/src/state/StateTracker.h b/cmds/statsd/src/state/StateTracker.h
new file mode 100644
index 0000000..f22706c
--- /dev/null
+++ b/cmds/statsd/src/state/StateTracker.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+#pragma once
+
+#include <statslog.h>
+#include <utils/RefBase.h>
+#include "HashableDimensionKey.h"
+#include "logd/LogEvent.h"
+
+#include "state/StateListener.h"
+
+#include <unordered_map>
+
+namespace android {
+namespace os {
+namespace statsd {
+
+class StateTracker : public virtual RefBase {
+public:
+    StateTracker(const int atomId, const util::StateAtomFieldOptions& stateAtomInfo);
+
+    virtual ~StateTracker(){};
+
+    // Updates state map and notifies all listeners if a state change occurs.
+    // Checks if a state change has occurred by getting the state value from
+    // the log event and comparing the old and new states.
+    void onLogEvent(const LogEvent& event);
+
+    // Adds new listeners to set of StateListeners. If a listener is already
+    // registered, it is ignored.
+    void registerListener(wp<StateListener> listener);
+
+    void unregisterListener(wp<StateListener> listener);
+
+    // Returns the state value mapped to the given query key.
+    // If the key isn't mapped to a state or the key size doesn't match the
+    // primary key size, the default state is returned.
+    int getState(const HashableDimensionKey& queryKey) const;
+
+    inline int getListenersCount() const {
+        return mListeners.size();
+    }
+
+    const static int kStateUnknown = -1;
+
+private:
+    struct StateValueInfo {
+        int32_t state;  // state value
+        int count;      // nested count (only used for binary states)
+    };
+
+    const int32_t mAtomId;  // id of the state atom being tracked
+
+    Matcher mStateField;  // matches the atom's exclusive state field
+
+    std::vector<Matcher> mPrimaryFields;  // matches the atom's primary fields
+
+    int32_t mDefaultState = kStateUnknown;
+
+    int32_t mResetState;
+
+    // Maps primary key to state value info
+    std::unordered_map<HashableDimensionKey, StateValueInfo> mStateMap;
+
+    // Set of all StateListeners (objects listening for state changes)
+    std::set<wp<StateListener>> mListeners;
+
+    // Reset all state values in map to default state
+    void handleReset();
+
+    // Reset only the state value mapped to primary key to default state
+    void handlePartialReset(const HashableDimensionKey& primaryKey);
+
+    // Update the StateMap based on the received state value.
+    // Store the old and new states.
+    void updateState(const HashableDimensionKey& primaryKey, const int32_t eventState,
+                     int32_t* oldState, int32_t* newState);
+};
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
diff --git a/cmds/statsd/src/stats_log.proto b/cmds/statsd/src/stats_log.proto
index d9c04f2..e45e24fe 100644
--- a/cmds/statsd/src/stats_log.proto
+++ b/cmds/statsd/src/stats_log.proto
@@ -41,6 +41,15 @@
   repeated DimensionsValue dimensions_value = 1;
 }
 
+message StateValue {
+  optional int32 atom_id = 1;
+
+  oneof contents {
+    int64 group_id = 2;
+    int32 value = 3;
+  }
+}
+
 message EventMetricData {
   optional int64 elapsed_timestamp_nanos = 1;
 
@@ -66,12 +75,14 @@
 message CountMetricData {
   optional DimensionsValue dimensions_in_what = 1;
 
-  optional DimensionsValue dimensions_in_condition = 2 [deprecated = true];
+  repeated StateValue slice_by_state = 6;
 
   repeated CountBucketInfo bucket_info = 3;
 
   repeated DimensionsValue dimension_leaf_values_in_what = 4;
 
+  optional DimensionsValue dimensions_in_condition = 2 [deprecated = true];
+
   repeated DimensionsValue dimension_leaf_values_in_condition = 5 [deprecated = true];
 }
 
diff --git a/cmds/statsd/src/statsd_config.proto b/cmds/statsd/src/statsd_config.proto
index 1b7f398..c107397 100644
--- a/cmds/statsd/src/statsd_config.proto
+++ b/cmds/statsd/src/statsd_config.proto
@@ -150,6 +150,24 @@
   }
 }
 
+message StateMap {
+  message StateGroup {
+    optional int64 group_id = 1;
+
+    repeated int32 value = 2;
+  }
+
+  repeated StateGroup group = 1;
+}
+
+message State {
+  optional int64 id = 1;
+
+  optional int32 atom_id = 2;
+
+  optional StateMap map = 3;
+}
+
 message MetricConditionLink {
   optional int64 condition = 1;
 
@@ -158,6 +176,14 @@
   optional FieldMatcher fields_in_condition = 3;
 }
 
+message MetricStateLink {
+  optional int64 state = 1;
+
+  optional FieldMatcher fields_in_what = 2;
+
+  optional FieldMatcher fields_in_state = 3;
+}
+
 message FieldFilter {
   optional bool include_all = 1 [default = false];
   optional FieldMatcher fields = 2;
@@ -182,11 +208,15 @@
 
   optional FieldMatcher dimensions_in_what = 4;
 
-  optional FieldMatcher dimensions_in_condition = 7 [deprecated = true];
+  repeated int64 slice_by_state = 8;
 
   optional TimeUnit bucket = 5;
 
   repeated MetricConditionLink links = 6;
+
+  repeated MetricStateLink state_link = 9;
+
+  optional FieldMatcher dimensions_in_condition = 7 [deprecated = true];
 }
 
 message DurationMetric {
@@ -438,6 +468,8 @@
 
   optional bool persist_locally = 20 [default = false];
 
+  repeated State state = 21;
+
   // Field number 1000 is reserved for later use.
   reserved 1000;
 }
diff --git a/cmds/statsd/tests/LogEvent_test.cpp b/cmds/statsd/tests/LogEvent_test.cpp
index 504ee22..0743480 100644
--- a/cmds/statsd/tests/LogEvent_test.cpp
+++ b/cmds/statsd/tests/LogEvent_test.cpp
@@ -582,7 +582,7 @@
     event1.write((int32_t)stats::launcher::LauncherAction::LONGPRESS);
     event1.write((int32_t)stats::launcher::LauncherState::OVERVIEW);
     event1.write((int64_t)stats::launcher::LauncherState::ALLAPPS);
-    event1.write(extension_str);
+    event1.writeBytes(extension_str);
     event1.init();
 
     ProtoOutputStream proto;
@@ -621,7 +621,7 @@
     event1.write((int32_t)stats::launcher::LauncherAction::LONGPRESS);
     event1.write((int32_t)stats::launcher::LauncherState::OVERVIEW);
     event1.write((int64_t)stats::launcher::LauncherState::ALLAPPS);
-    event1.write(extension_str);
+    event1.writeBytes(extension_str);
     event1.init();
 
     ProtoOutputStream proto;
diff --git a/cmds/statsd/tests/StatsLogProcessor_test.cpp b/cmds/statsd/tests/StatsLogProcessor_test.cpp
index fe25a25..460b9e0 100644
--- a/cmds/statsd/tests/StatsLogProcessor_test.cpp
+++ b/cmds/statsd/tests/StatsLogProcessor_test.cpp
@@ -1199,87 +1199,66 @@
 
     ConfigKey cfgKey1(uid, 12341);
     long timeBase1 = 1;
-    sp<StatsLogProcessor> processor =
+    sp<StatsLogProcessor> processor1 =
             CreateStatsLogProcessor(timeBase1, timeBase1, config1, cfgKey1);
 
     // Metric 1 is not active.
     // Metric 2 is active.
     // {{{---------------------------------------------------------------------------
-    EXPECT_EQ(1, processor->mMetricsManagers.size());
-    auto it = processor->mMetricsManagers.find(cfgKey1);
-    EXPECT_TRUE(it != processor->mMetricsManagers.end());
+    EXPECT_EQ(1, processor1->mMetricsManagers.size());
+    auto it = processor1->mMetricsManagers.find(cfgKey1);
+    EXPECT_TRUE(it != processor1->mMetricsManagers.end());
     auto& metricsManager1 = it->second;
     EXPECT_TRUE(metricsManager1->isActive());
 
-    auto metricIt = metricsManager1->mAllMetricProducers.begin();
-    for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
-        if ((*metricIt)->getMetricId() == metricId1) {
-            break;
-        }
-    }
-    EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
-    auto& metricProducer1 = *metricIt;
-    EXPECT_FALSE(metricProducer1->isActive());
+    EXPECT_EQ(metricsManager1->mAllMetricProducers.size(), 2);
+    // We assume that the index of a MetricProducer within the mAllMetricProducers
+    // array follows the order in which metrics are added to the config.
+    auto& metricProducer1_1 = metricsManager1->mAllMetricProducers[0];
+    EXPECT_EQ(metricProducer1_1->getMetricId(), metricId1);
+    EXPECT_FALSE(metricProducer1_1->isActive());  // inactive due to associated MetricActivation
 
-    metricIt = metricsManager1->mAllMetricProducers.begin();
-    for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
-        if ((*metricIt)->getMetricId() == metricId2) {
-            break;
-        }
-    }
-    EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
-    auto& metricProducer2 = *metricIt;
-    EXPECT_TRUE(metricProducer2->isActive());
+    auto& metricProducer1_2 = metricsManager1->mAllMetricProducers[1];
+    EXPECT_EQ(metricProducer1_2->getMetricId(), metricId2);
+    EXPECT_TRUE(metricProducer1_2->isActive());
 
-    int i = 0;
-    for (; i < metricsManager1->mAllAtomMatchers.size(); i++) {
-        if (metricsManager1->mAllAtomMatchers[i]->getId() ==
-                metric1ActivationTrigger1->atom_matcher_id()) {
-            break;
-        }
-    }
-    const auto& activation1 = metricProducer1->mEventActivationMap.at(i);
-    EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
-    EXPECT_EQ(0, activation1->start_ns);
-    EXPECT_EQ(kNotActive, activation1->state);
-    EXPECT_EQ(ACTIVATE_ON_BOOT, activation1->activationType);
+    EXPECT_EQ(metricProducer1_1->mEventActivationMap.size(), 2);
+    // The key in mEventActivationMap is the index of the associated atom matcher. We assume
+    // that matchers are indexed in the order that they are added to the config.
+    const auto& activation1_1_1 = metricProducer1_1->mEventActivationMap.at(0);
+    EXPECT_EQ(100 * NS_PER_SEC, activation1_1_1->ttl_ns);
+    EXPECT_EQ(0, activation1_1_1->start_ns);
+    EXPECT_EQ(kNotActive, activation1_1_1->state);
+    EXPECT_EQ(ACTIVATE_ON_BOOT, activation1_1_1->activationType);
 
-    i = 0;
-    for (; i < metricsManager1->mAllAtomMatchers.size(); i++) {
-        if (metricsManager1->mAllAtomMatchers[i]->getId() ==
-                metric1ActivationTrigger2->atom_matcher_id()) {
-            break;
-        }
-    }
-    const auto& activation2 = metricProducer1->mEventActivationMap.at(i);
-    EXPECT_EQ(200 * NS_PER_SEC, activation2->ttl_ns);
-    EXPECT_EQ(0, activation2->start_ns);
-    EXPECT_EQ(kNotActive, activation2->state);
-    EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation2->activationType);
+    const auto& activation1_1_2 = metricProducer1_1->mEventActivationMap.at(1);
+    EXPECT_EQ(200 * NS_PER_SEC, activation1_1_2->ttl_ns);
+    EXPECT_EQ(0, activation1_1_2->start_ns);
+    EXPECT_EQ(kNotActive, activation1_1_2->state);
+    EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1_1_2->activationType);
     // }}}------------------------------------------------------------------------------
 
     // Trigger Activation 1 for Metric 1
     std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1")};
     auto event = CreateAcquireWakelockEvent(attributions1, "wl1", 100 + timeBase1);
-    processor->OnLogEvent(event.get());
+    processor1->OnLogEvent(event.get());
 
     // Metric 1 is not active; Activation 1 set to kActiveOnBoot
     // Metric 2 is active.
     // {{{---------------------------------------------------------------------------
-    EXPECT_FALSE(metricProducer1->isActive());
-    EXPECT_EQ(0, activation1->start_ns);
-    EXPECT_EQ(kActiveOnBoot, activation1->state);
-    EXPECT_EQ(0, activation2->start_ns);
-    EXPECT_EQ(kNotActive, activation2->state);
+    EXPECT_FALSE(metricProducer1_1->isActive());
+    EXPECT_EQ(0, activation1_1_1->start_ns);
+    EXPECT_EQ(kActiveOnBoot, activation1_1_1->state);
+    EXPECT_EQ(0, activation1_1_2->start_ns);
+    EXPECT_EQ(kNotActive, activation1_1_2->state);
 
-    EXPECT_TRUE(metricProducer2->isActive());
+    EXPECT_TRUE(metricProducer1_2->isActive());
     // }}}-----------------------------------------------------------------------------
 
     // Simulate shutdown by saving state to disk
     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
-    processor->SaveActiveConfigsToDisk(shutDownTime);
-    EXPECT_FALSE(metricProducer1->isActive());
-    int64_t ttl1 = metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC;
+    processor1->SaveActiveConfigsToDisk(shutDownTime);
+    EXPECT_FALSE(metricProducer1_1->isActive());
 
     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
     // same config.
@@ -1293,55 +1272,34 @@
     EXPECT_EQ(1, processor2->mMetricsManagers.size());
     it = processor2->mMetricsManagers.find(cfgKey1);
     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
-    auto& metricsManager1001 = it->second;
-    EXPECT_TRUE(metricsManager1001->isActive());
+    auto& metricsManager2 = it->second;
+    EXPECT_TRUE(metricsManager2->isActive());
 
-    metricIt = metricsManager1001->mAllMetricProducers.begin();
-    for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
-        if ((*metricIt)->getMetricId() == metricId1) {
-            break;
-        }
-    }
-    EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
-    auto& metricProducer1001 = *metricIt;
-    EXPECT_FALSE(metricProducer1001->isActive());
+    EXPECT_EQ(metricsManager2->mAllMetricProducers.size(), 2);
+    // We assume that the index of a MetricProducer within the mAllMetricProducers
+    // array follows the order in which metrics are added to the config.
+    auto& metricProducer2_1 = metricsManager2->mAllMetricProducers[0];
+    EXPECT_EQ(metricProducer2_1->getMetricId(), metricId1);
+    EXPECT_FALSE(metricProducer2_1->isActive());
 
-    metricIt = metricsManager1001->mAllMetricProducers.begin();
-    for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
-        if ((*metricIt)->getMetricId() == metricId2) {
-            break;
-        }
-    }
-    EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
-    auto& metricProducer1002 = *metricIt;
-    EXPECT_TRUE(metricProducer1002->isActive());
+    auto& metricProducer2_2 = metricsManager2->mAllMetricProducers[1];
+    EXPECT_EQ(metricProducer2_2->getMetricId(), metricId2);
+    EXPECT_TRUE(metricProducer2_2->isActive());
 
-    i = 0;
-    for (; i < metricsManager1001->mAllAtomMatchers.size(); i++) {
-        if (metricsManager1001->mAllAtomMatchers[i]->getId() ==
-                metric1ActivationTrigger1->atom_matcher_id()) {
-            break;
-        }
-    }
-    const auto& activation1001_1 = metricProducer1001->mEventActivationMap.at(i);
-    EXPECT_EQ(100 * NS_PER_SEC, activation1001_1->ttl_ns);
-    EXPECT_EQ(0, activation1001_1->start_ns);
-    EXPECT_EQ(kNotActive, activation1001_1->state);
-    EXPECT_EQ(ACTIVATE_ON_BOOT, activation1001_1->activationType);
+    EXPECT_EQ(metricProducer2_1->mEventActivationMap.size(), 2);
+    // The key in mEventActivationMap is the index of the associated atom matcher. We assume
+    // that matchers are indexed in the order that they are added to the config.
+    const auto& activation2_1_1 = metricProducer2_1->mEventActivationMap.at(0);
+    EXPECT_EQ(100 * NS_PER_SEC, activation2_1_1->ttl_ns);
+    EXPECT_EQ(0, activation2_1_1->start_ns);
+    EXPECT_EQ(kNotActive, activation2_1_1->state);
+    EXPECT_EQ(ACTIVATE_ON_BOOT, activation2_1_1->activationType);
 
-    i = 0;
-    for (; i < metricsManager1001->mAllAtomMatchers.size(); i++) {
-        if (metricsManager1001->mAllAtomMatchers[i]->getId() ==
-                metric1ActivationTrigger2->atom_matcher_id()) {
-            break;
-        }
-    }
-
-    const auto& activation1001_2 = metricProducer1001->mEventActivationMap.at(i);
-    EXPECT_EQ(200 * NS_PER_SEC, activation1001_2->ttl_ns);
-    EXPECT_EQ(0, activation1001_2->start_ns);
-    EXPECT_EQ(kNotActive, activation1001_2->state);
-    EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1001_2->activationType);
+    const auto& activation2_1_2 = metricProducer2_1->mEventActivationMap.at(1);
+    EXPECT_EQ(200 * NS_PER_SEC, activation2_1_2->ttl_ns);
+    EXPECT_EQ(0, activation2_1_2->start_ns);
+    EXPECT_EQ(kNotActive, activation2_1_2->state);
+    EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation2_1_2->activationType);
     // }}}-----------------------------------------------------------------------------------
 
     // Load saved state from disk.
@@ -1350,13 +1308,14 @@
     // Metric 1 active; Activation 1 is active, Activation 2 is not active
     // Metric 2 is active.
     // {{{---------------------------------------------------------------------------
-    EXPECT_TRUE(metricProducer1001->isActive());
-    EXPECT_EQ(timeBase2 + ttl1 - activation1001_1->ttl_ns, activation1001_1->start_ns);
-    EXPECT_EQ(kActive, activation1001_1->state);
-    EXPECT_EQ(0, activation1001_2->start_ns);
-    EXPECT_EQ(kNotActive, activation1001_2->state);
+    EXPECT_TRUE(metricProducer2_1->isActive());
+    int64_t ttl1 = metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC;
+    EXPECT_EQ(timeBase2 + ttl1 - activation2_1_1->ttl_ns, activation2_1_1->start_ns);
+    EXPECT_EQ(kActive, activation2_1_1->state);
+    EXPECT_EQ(0, activation2_1_2->start_ns);
+    EXPECT_EQ(kNotActive, activation2_1_2->state);
 
-    EXPECT_TRUE(metricProducer1002->isActive());
+    EXPECT_TRUE(metricProducer2_2->isActive());
     // }}}--------------------------------------------------------------------------------
 
     // Trigger Activation 2 for Metric 1.
@@ -1369,23 +1328,23 @@
     // Metric 1 active; Activation 1 is active, Activation 2 is active
     // Metric 2 is active.
     // {{{---------------------------------------------------------------------------
-    EXPECT_TRUE(metricProducer1001->isActive());
-    EXPECT_EQ(timeBase2 + ttl1 - activation1001_1->ttl_ns, activation1001_1->start_ns);
-    EXPECT_EQ(kActive, activation1001_1->state);
-    EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activation1001_2->start_ns);
-    EXPECT_EQ(kActive, activation1001_2->state);
+    EXPECT_TRUE(metricProducer2_1->isActive());
+    EXPECT_EQ(timeBase2 + ttl1 - activation2_1_1->ttl_ns, activation2_1_1->start_ns);
+    EXPECT_EQ(kActive, activation2_1_1->state);
+    EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activation2_1_2->start_ns);
+    EXPECT_EQ(kActive, activation2_1_2->state);
 
-    EXPECT_TRUE(metricProducer1002->isActive());
+    EXPECT_TRUE(metricProducer2_2->isActive());
     // }}}---------------------------------------------------------------------------
 
     // Simulate shutdown by saving state to disk
     shutDownTime = timeBase2 + 50 * NS_PER_SEC;
     processor2->SaveActiveConfigsToDisk(shutDownTime);
-    EXPECT_TRUE(metricProducer1001->isActive());
-    EXPECT_TRUE(metricProducer1002->isActive());
-    ttl1 = timeBase2 + metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC - shutDownTime;
-    int64_t ttl2 = screenOnEvent->GetElapsedTimestampNs() +
-            metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC - shutDownTime;
+    EXPECT_TRUE(metricProducer2_1->isActive());
+    EXPECT_TRUE(metricProducer2_2->isActive());
+    ttl1 -= shutDownTime - timeBase2;
+    int64_t ttl2 = metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC
+            - (shutDownTime - screenOnEvent->GetElapsedTimestampNs());
 
     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
     // same config.
@@ -1399,55 +1358,34 @@
     EXPECT_EQ(1, processor3->mMetricsManagers.size());
     it = processor3->mMetricsManagers.find(cfgKey1);
     EXPECT_TRUE(it != processor3->mMetricsManagers.end());
-    auto& metricsManagerTimeBase3 = it->second;
-    EXPECT_TRUE(metricsManagerTimeBase3->isActive());
+    auto& metricsManager3 = it->second;
+    EXPECT_TRUE(metricsManager3->isActive());
 
-    metricIt = metricsManagerTimeBase3->mAllMetricProducers.begin();
-    for (; metricIt != metricsManagerTimeBase3->mAllMetricProducers.end(); metricIt++) {
-        if ((*metricIt)->getMetricId() == metricId1) {
-            break;
-        }
-    }
-    EXPECT_TRUE(metricIt != metricsManagerTimeBase3->mAllMetricProducers.end());
-    auto& metricProducerTimeBase3_1 = *metricIt;
-    EXPECT_FALSE(metricProducerTimeBase3_1->isActive());
+    EXPECT_EQ(metricsManager3->mAllMetricProducers.size(), 2);
+    // We assume that the index of a MetricProducer within the mAllMetricProducers
+    // array follows the order in which metrics are added to the config.
+    auto& metricProducer3_1 = metricsManager3->mAllMetricProducers[0];
+    EXPECT_EQ(metricProducer3_1->getMetricId(), metricId1);
+    EXPECT_FALSE(metricProducer3_1->isActive());
 
-    metricIt = metricsManagerTimeBase3->mAllMetricProducers.begin();
-    for (; metricIt != metricsManagerTimeBase3->mAllMetricProducers.end(); metricIt++) {
-        if ((*metricIt)->getMetricId() == metricId2) {
-            break;
-        }
-    }
-    EXPECT_TRUE(metricIt != metricsManagerTimeBase3->mAllMetricProducers.end());
-    auto& metricProducerTimeBase3_2 = *metricIt;
-    EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
+    auto& metricProducer3_2 = metricsManager3->mAllMetricProducers[1];
+    EXPECT_EQ(metricProducer3_2->getMetricId(), metricId2);
+    EXPECT_TRUE(metricProducer3_2->isActive());
 
-    i = 0;
-    for (; i < metricsManagerTimeBase3->mAllAtomMatchers.size(); i++) {
-        if (metricsManagerTimeBase3->mAllAtomMatchers[i]->getId() ==
-                metric1ActivationTrigger1->atom_matcher_id()) {
-            break;
-        }
-    }
-    const auto& activationTimeBase3_1 = metricProducerTimeBase3_1->mEventActivationMap.at(i);
-    EXPECT_EQ(100 * NS_PER_SEC, activationTimeBase3_1->ttl_ns);
-    EXPECT_EQ(0, activationTimeBase3_1->start_ns);
-    EXPECT_EQ(kNotActive, activationTimeBase3_1->state);
-    EXPECT_EQ(ACTIVATE_ON_BOOT, activationTimeBase3_1->activationType);
+    EXPECT_EQ(metricProducer3_1->mEventActivationMap.size(), 2);
+    // The key in mEventActivationMap is the index of the associated atom matcher. We assume
+    // that matchers are indexed in the order that they are added to the config.
+    const auto& activation3_1_1 = metricProducer3_1->mEventActivationMap.at(0);
+    EXPECT_EQ(100 * NS_PER_SEC, activation3_1_1->ttl_ns);
+    EXPECT_EQ(0, activation3_1_1->start_ns);
+    EXPECT_EQ(kNotActive, activation3_1_1->state);
+    EXPECT_EQ(ACTIVATE_ON_BOOT, activation3_1_1->activationType);
 
-    i = 0;
-    for (; i < metricsManagerTimeBase3->mAllAtomMatchers.size(); i++) {
-        if (metricsManagerTimeBase3->mAllAtomMatchers[i]->getId() ==
-                metric1ActivationTrigger2->atom_matcher_id()) {
-            break;
-        }
-    }
-
-    const auto& activationTimeBase3_2 = metricProducerTimeBase3_1->mEventActivationMap.at(i);
-    EXPECT_EQ(200 * NS_PER_SEC, activationTimeBase3_2->ttl_ns);
-    EXPECT_EQ(0, activationTimeBase3_2->start_ns);
-    EXPECT_EQ(kNotActive, activationTimeBase3_2->state);
-    EXPECT_EQ(ACTIVATE_IMMEDIATELY, activationTimeBase3_2->activationType);
+    const auto& activation3_1_2 = metricProducer3_1->mEventActivationMap.at(1);
+    EXPECT_EQ(200 * NS_PER_SEC, activation3_1_2->ttl_ns);
+    EXPECT_EQ(0, activation3_1_2->start_ns);
+    EXPECT_EQ(kNotActive, activation3_1_2->state);
+    EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation3_1_2->activationType);
     // }}}----------------------------------------------------------------------------------
 
     // Load saved state from disk.
@@ -1456,13 +1394,13 @@
     // Metric 1 active: Activation 1 is active, Activation 2 is active
     // Metric 2 is active.
     // {{{---------------------------------------------------------------------------
-    EXPECT_TRUE(metricProducerTimeBase3_1->isActive());
-    EXPECT_EQ(timeBase3 + ttl1 - activationTimeBase3_1->ttl_ns, activationTimeBase3_1->start_ns);
-    EXPECT_EQ(kActive, activationTimeBase3_1->state);
-    EXPECT_EQ(timeBase3 + ttl2 - activationTimeBase3_2->ttl_ns, activationTimeBase3_2->start_ns);
-    EXPECT_EQ(kActive, activationTimeBase3_2->state);
+    EXPECT_TRUE(metricProducer3_1->isActive());
+    EXPECT_EQ(timeBase3 + ttl1 - activation3_1_1->ttl_ns, activation3_1_1->start_ns);
+    EXPECT_EQ(kActive, activation3_1_1->state);
+    EXPECT_EQ(timeBase3 + ttl2 - activation3_1_2->ttl_ns, activation3_1_2->start_ns);
+    EXPECT_EQ(kActive, activation3_1_2->state);
 
-    EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
+    EXPECT_TRUE(metricProducer3_2->isActive());
     // }}}-------------------------------------------------------------------------------
 
 
@@ -1473,15 +1411,16 @@
     );
     processor3->OnLogEvent(screenOnEvent.get());
 
-    // Metric 1 active; Activation 1 is not active, Activation 2 is set to active
+    // Metric 1 active; Activation 1 is inactive (above screenOnEvent causes ttl1 to expire),
+    //                  Activation 2 is set to active
     // Metric 2 is active.
     // {{{---------------------------------------------------------------------------
-    EXPECT_TRUE(metricProducerTimeBase3_1->isActive());
-    EXPECT_EQ(kNotActive, activationTimeBase3_1->state);
-    EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activationTimeBase3_2->start_ns);
-    EXPECT_EQ(kActive, activationTimeBase3_2->state);
+    EXPECT_TRUE(metricProducer3_1->isActive());
+    EXPECT_EQ(kNotActive, activation3_1_1->state);
+    EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activation3_1_2->start_ns);
+    EXPECT_EQ(kActive, activation3_1_2->state);
 
-    EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
+    EXPECT_TRUE(metricProducer3_2->isActive());
     // }}}---------------------------------------------------------------------------
 }
 
@@ -1713,6 +1652,11 @@
     EXPECT_EQ(kActive, activation1004->state);
     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1004->activationType);
     // }}}------------------------------------------------------------------------------
+
+    // Clear the data stored on disk as a result of the system server death.
+    vector<uint8_t> buffer;
+    processor->onDumpReport(cfgKey1, configAddedTimeNs + NS_PER_SEC, false, true,
+                                ADB_DUMP, FAST, &buffer);
 }
 
 #else
diff --git a/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp b/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp
index b98dc60..325e869 100644
--- a/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp
@@ -96,6 +96,11 @@
 
     EXPECT_EQ((int64_t)(bucketStartTimeNs + 25 * bucketSizeNs + 2 + 2 * 3600 * NS_PER_SEC),
               processor->mMetricsManagers.begin()->second->getTtlEndNs());
+
+    // Clear the data stored on disk as a result of the ttl.
+    vector<uint8_t> buffer;
+    processor->onDumpReport(cfgKey, bucketStartTimeNs + 25 * bucketSizeNs + 3, false, true,
+                                ADB_DUMP, FAST, &buffer);
 }
 
 
diff --git a/cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp b/cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp
new file mode 100644
index 0000000..5c9636f
--- /dev/null
+++ b/cmds/statsd/tests/external/SurfaceflingerStatsPuller_test.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2019 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.
+ */
+
+#undef LOG_TAG
+#define LOG_TAG "SurfaceflingerStatsPuller_test"
+
+#include "src/external/SurfaceflingerStatsPuller.h"
+
+#include <gtest/gtest.h>
+#include <log/log.h>
+
+#ifdef __ANDROID__
+
+namespace android {
+namespace os {
+namespace statsd {
+
+class TestableSurfaceflingerStatsPuller : public SurfaceflingerStatsPuller {
+public:
+    TestableSurfaceflingerStatsPuller(const int tagId) : SurfaceflingerStatsPuller(tagId){};
+
+    void injectStats(const StatsProvider& statsProvider) {
+        mStatsProvider = statsProvider;
+    }
+};
+
+class SurfaceflingerStatsPullerTest : public ::testing::Test {
+public:
+    SurfaceflingerStatsPullerTest() {
+        const ::testing::TestInfo* const test_info =
+                ::testing::UnitTest::GetInstance()->current_test_info();
+        ALOGD("**** Setting up for %s.%s\n", test_info->test_case_name(), test_info->name());
+    }
+
+    ~SurfaceflingerStatsPullerTest() {
+        const ::testing::TestInfo* const test_info =
+                ::testing::UnitTest::GetInstance()->current_test_info();
+        ALOGD("**** Tearing down after %s.%s\n", test_info->test_case_name(), test_info->name());
+    }
+};
+
+TEST_F(SurfaceflingerStatsPullerTest, pullGlobalStats) {
+    surfaceflinger::SFTimeStatsGlobalProto proto;
+    proto.set_total_frames(1);
+    proto.set_missed_frames(2);
+    proto.set_client_composition_frames(2);
+    proto.set_display_on_time(4);
+
+    auto bucketOne = proto.add_present_to_present();
+    bucketOne->set_time_millis(2);
+    bucketOne->set_frame_count(4);
+    auto bucketTwo = proto.add_present_to_present();
+    bucketTwo->set_time_millis(4);
+    bucketTwo->set_frame_count(1);
+    auto bucketThree = proto.add_present_to_present();
+    bucketThree->set_time_millis(1000);
+    bucketThree->set_frame_count(1);
+    static constexpr int64_t expectedAnimationMillis = 12;
+    TestableSurfaceflingerStatsPuller puller(android::util::SURFACEFLINGER_STATS_GLOBAL_INFO);
+
+    puller.injectStats([&] {
+        return proto.SerializeAsString();
+    });
+    puller.ForceClearCache();
+    vector<std::shared_ptr<LogEvent>> outData;
+    puller.Pull(&outData);
+
+    ASSERT_EQ(1, outData.size());
+    EXPECT_EQ(android::util::SURFACEFLINGER_STATS_GLOBAL_INFO, outData[0]->GetTagId());
+    EXPECT_EQ(proto.total_frames(), outData[0]->getValues()[0].mValue.long_value);
+    EXPECT_EQ(proto.missed_frames(), outData[0]->getValues()[1].mValue.long_value);
+    EXPECT_EQ(proto.client_composition_frames(), outData[0]->getValues()[2].mValue.long_value);
+    EXPECT_EQ(proto.display_on_time(), outData[0]->getValues()[3].mValue.long_value);
+    EXPECT_EQ(expectedAnimationMillis, outData[0]->getValues()[4].mValue.long_value);
+}
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
+#else
+GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
diff --git a/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp b/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
index 47c21aa..b027e8e 100644
--- a/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
@@ -79,8 +79,6 @@
                                       logEventMatcherIndex, eventMatcherWizard,
                                       -1, -1, tagId, 5, 600 * NS_PER_SEC + NS_PER_SEC / 2,
                                       pullerManager);
-    gaugeProducer.prepareFirstBucket();
-
 
     EXPECT_EQ(600500000000, gaugeProducer.mCurrentBucketStartTimeNs);
     EXPECT_EQ(10, gaugeProducer.mCurrentBucketNum);
@@ -126,8 +124,6 @@
                                       tagId, -1, tagId, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
 
-    gaugeProducer.prepareFirstBucket();
-
     vector<shared_ptr<LogEvent>> allData;
     allData.clear();
     shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1);
@@ -211,7 +207,6 @@
                                       logEventMatcherIndex, eventMatcherWizard,
                                       -1 /* -1 means no pulling */, -1, tagId, bucketStartTimeNs,
                                       bucketStartTimeNs, pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     sp<AnomalyTracker> anomalyTracker = gaugeProducer.addAnomalyTracker(alert, alarmMonitor);
     EXPECT_TRUE(anomalyTracker != nullptr);
@@ -303,7 +298,6 @@
     GaugeMetricProducer gaugeProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
                                       logEventMatcherIndex, eventMatcherWizard, tagId, -1, tagId,
                                       bucketStartTimeNs, bucketStartTimeNs, pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
     shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1);
@@ -370,7 +364,6 @@
                                       logEventMatcherIndex, eventMatcherWizard,
                                       tagId, -1, tagId, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
     shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1);
@@ -431,7 +424,6 @@
     GaugeMetricProducer gaugeProducer(kConfigKey, metric, 1, wizard,
                                       logEventMatcherIndex, eventMatcherWizard, tagId, -1, tagId,
                                       bucketStartTimeNs, bucketStartTimeNs, pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     gaugeProducer.onConditionChanged(true, bucketStartTimeNs + 8);
     EXPECT_EQ(1UL, gaugeProducer.mCurrentSlicedBucket->size());
@@ -521,7 +513,6 @@
     GaugeMetricProducer gaugeProducer(kConfigKey, metric, 1, wizard,
                                       logEventMatcherIndex, eventMatcherWizard, tagId, -1, tagId,
                                       bucketStartTimeNs, bucketStartTimeNs, pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     gaugeProducer.onSlicedConditionMayChange(true, bucketStartTimeNs + 8);
 
@@ -572,7 +563,6 @@
                                       logEventMatcherIndex, eventMatcherWizard,
                                       tagId, -1, tagId, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     Alert alert;
     alert.set_id(101);
@@ -681,7 +671,6 @@
                                       logEventMatcherIndex, eventMatcherWizard,
                                       tagId, triggerId, tagId, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
 
@@ -766,7 +755,6 @@
                                       logEventMatcherIndex, eventMatcherWizard,
                                       tagId, triggerId, tagId, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    gaugeProducer.prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
 
diff --git a/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp b/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
index 2262c76..4b9d0c0 100644
--- a/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
@@ -105,7 +105,6 @@
                 kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
                 logEventMatcherIndex, eventMatcherWizard, tagId,
                 bucketStartTimeNs, bucketStartTimeNs, pullerManager);
-        valueProducer->prepareFirstBucket();
         return valueProducer;
     }
 
@@ -125,7 +124,6 @@
                 new ValueMetricProducer(kConfigKey, metric, 1, wizard, logEventMatcherIndex,
                                         eventMatcherWizard, tagId, bucketStartTimeNs,
                                         bucketStartTimeNs, pullerManager);
-        valueProducer->prepareFirstBucket();
         valueProducer->mCondition = ConditionState::kFalse;
         return valueProducer;
     }
@@ -169,7 +167,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
                                       logEventMatcherIndex, eventMatcherWizard, -1, startTimeBase,
                                       22, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     EXPECT_EQ(startTimeBase, valueProducer.calcPreviousBucketEndTime(60 * NS_PER_SEC + 10));
     EXPECT_EQ(startTimeBase, valueProducer.calcPreviousBucketEndTime(60 * NS_PER_SEC + 10));
@@ -199,7 +196,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
                                       logEventMatcherIndex, eventMatcherWizard, -1, 5,
                                       600 * NS_PER_SEC + NS_PER_SEC / 2, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     EXPECT_EQ(600500000000, valueProducer.mCurrentBucketStartTimeNs);
     EXPECT_EQ(10, valueProducer.mCurrentBucketNum);
@@ -381,7 +377,6 @@
             kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
             logEventMatcherIndex, eventMatcherWizard, tagId,
             bucketStartTimeNs, bucketStartTimeNs, pullerManager);
-    valueProducer->prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
     allData.clear();
@@ -670,7 +665,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -728,7 +722,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, tagId, bucketStartTimeNs,
                                       bucketStartTimeNs, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
     allData.clear();
@@ -779,7 +772,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, tagId, bucketStartTimeNs,
                                       bucketStartTimeNs, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
     allData.clear();
@@ -854,7 +846,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -897,7 +888,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, 1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
     valueProducer.mCondition = ConditionState::kFalse;
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
@@ -972,7 +962,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
                                       logEventMatcherIndex, eventMatcherWizard, -1 /*not pulled*/,
                                       bucketStartTimeNs, bucketStartTimeNs, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     sp<AnomalyTracker> anomalyTracker = valueProducer.addAnomalyTracker(alert, alarmMonitor);
 
@@ -1269,7 +1258,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -1314,7 +1302,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -1361,7 +1348,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -1412,7 +1398,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -1458,7 +1443,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -1532,7 +1516,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs,
                                       pullerManager);
-    valueProducer.prepareFirstBucket();
 
     shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10);
     event1->write(1);
@@ -2081,7 +2064,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, 1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, tagId, bucket2StartTimeNs,
                                       bucket2StartTimeNs, pullerManager);
-    valueProducer.prepareFirstBucket();
     valueProducer.mCondition = ConditionState::kFalse;
 
     // Event should be skipped since it is from previous bucket.
@@ -2862,7 +2844,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, tagId, bucketStartTimeNs,
                                       bucketStartTimeNs, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     ProtoOutputStream output;
     std::set<string> strSet;
@@ -2905,7 +2886,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, tagId, bucketStartTimeNs,
                                       bucketStartTimeNs, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     vector<shared_ptr<LogEvent>> allData;
     allData.clear();
@@ -2969,7 +2949,6 @@
     ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex,
                                       eventMatcherWizard, tagId, bucketStartTimeNs,
                                       bucketStartTimeNs, pullerManager);
-    valueProducer.prepareFirstBucket();
 
     ProtoOutputStream output;
     std::set<string> strSet;
diff --git a/cmds/statsd/tests/state/StateTracker_test.cpp b/cmds/statsd/tests/state/StateTracker_test.cpp
new file mode 100644
index 0000000..c89ffea
--- /dev/null
+++ b/cmds/statsd/tests/state/StateTracker_test.cpp
@@ -0,0 +1,356 @@
+/*
+ * Copyright (C) 2019, 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.
+ */
+#include <gtest/gtest.h>
+#include "state/StateManager.h"
+#include "state/StateTracker.h"
+#include "state/StateListener.h"
+
+#include "tests/statsd_test_util.h"
+
+#ifdef __ANDROID__
+
+namespace android {
+namespace os {
+namespace statsd {
+
+/**
+ * Mock StateListener class for testing.
+ * Stores primary key and state pairs.
+ */
+class TestStateListener : public virtual StateListener {
+public:
+    TestStateListener(){};
+
+    virtual ~TestStateListener(){};
+
+    struct Update {
+        Update(const HashableDimensionKey& key, int state) : mKey(key), mState(state){};
+        HashableDimensionKey mKey;
+        int mState;
+    };
+
+    std::vector<Update> updates;
+
+    void onStateChanged(int stateAtomId, const HashableDimensionKey& primaryKey, int oldState,
+                        int newState) {
+        updates.emplace_back(primaryKey, newState);
+    }
+};
+
+// START: build event functions.
+// State with no primary fields - ScreenStateChanged
+std::shared_ptr<LogEvent> buildScreenEvent(int state) {
+    std::shared_ptr<LogEvent> event =
+            std::make_shared<LogEvent>(android::util::SCREEN_STATE_CHANGED, 1000 /*timestamp*/);
+    event->write((int32_t)state);
+    event->init();
+    return event;
+}
+
+// State with one primary field - UidProcessStateChanged
+std::shared_ptr<LogEvent> buildUidProcessEvent(int uid, int state) {
+    std::shared_ptr<LogEvent> event =
+            std::make_shared<LogEvent>(android::util::UID_PROCESS_STATE_CHANGED, 1000 /*timestamp*/);
+    event->write((int32_t)uid);
+    event->write((int32_t)state);
+    event->init();
+    return event;
+}
+
+// State with multiple primary fields - OverlayStateChanged
+std::shared_ptr<LogEvent> buildOverlayEvent(int uid, const std::string& packageName, int state) {
+    std::shared_ptr<LogEvent> event =
+            std::make_shared<LogEvent>(android::util::OVERLAY_STATE_CHANGED, 1000 /*timestamp*/);
+    event->write((int32_t)uid);
+    event->write(packageName);
+    event->write(true);  // using_alert_window
+    event->write((int32_t)state);
+    event->init();
+    return event;
+}
+
+std::shared_ptr<LogEvent> buildIncorrectOverlayEvent(int uid, const std::string& packageName, int state) {
+    std::shared_ptr<LogEvent> event =
+            std::make_shared<LogEvent>(android::util::OVERLAY_STATE_CHANGED, 1000 /*timestamp*/);
+    event->write((int32_t)uid);
+    event->write(packageName);
+    event->write((int32_t)state);
+    event->init();
+    return event;
+}
+// END: build event functions.
+
+// START: get primary key functions
+void getUidProcessKey(int uid, HashableDimensionKey* key) {
+    int pos1[] = {1, 0, 0};
+    Field field1(27 /* atom id */, pos1, 0 /* depth */);
+    Value value1((int32_t)uid);
+
+    key->addValue(FieldValue(field1, value1));
+}
+
+void getOverlayKey(int uid, string packageName, HashableDimensionKey* key) {
+    int pos1[] = {1, 0, 0};
+    int pos2[] = {2, 0, 0};
+
+    Field field1(59 /* atom id */, pos1, 0 /* depth */);
+    Field field2(59 /* atom id */, pos2, 0 /* depth */);
+
+    Value value1((int32_t)uid);
+    Value value2(packageName);
+
+    key->addValue(FieldValue(field1, value1));
+    key->addValue(FieldValue(field2, value2));
+}
+// END: get primary key functions
+
+TEST(StateListenerTest, TestStateListenerWeakPointer) {
+    sp<TestStateListener> listener = new TestStateListener();
+    wp<TestStateListener> wListener = listener;
+    listener = nullptr;  // let go of listener
+    EXPECT_TRUE(wListener.promote() == nullptr);
+}
+
+TEST(StateManagerTest, TestStateManagerGetInstance) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    StateManager& mgr = StateManager::getInstance();
+
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener1);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+    EXPECT_EQ(1, StateManager::getInstance().getStateTrackersCount());
+}
+
+/**
+ * Test registering listeners to StateTrackers
+ *
+ * - StateManager will create a new StateTracker if it doesn't already exist
+ * and then register the listener to the StateTracker.
+ * - If a listener is already registered to a StateTracker, it is not added again.
+ * - StateTrackers are only created for atoms that are state atoms.
+ */
+TEST(StateTrackerTest, TestRegisterListener) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    sp<TestStateListener> listener2 = new TestStateListener();
+    StateManager mgr;
+
+    // Register listener to non-existing StateTracker
+    EXPECT_EQ(0, mgr.getStateTrackersCount());
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener1);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+    EXPECT_EQ(1, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+
+    // Register listener to existing StateTracker
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener2);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+    EXPECT_EQ(2, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+
+    // Register already registered listener to existing StateTracker
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener2);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+    EXPECT_EQ(2, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+
+    // Register listener to non-state atom
+    mgr.registerListener(android::util::BATTERY_LEVEL_CHANGED, listener2);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+}
+
+/**
+ * Test unregistering listeners from StateTrackers
+ *
+ * - StateManager will unregister listeners from a StateTracker only if the
+ * StateTracker exists and the listener is registered to the StateTracker.
+ * - Once all listeners are removed from a StateTracker, the StateTracker
+ * is also removed.
+ */
+TEST(StateTrackerTest, TestUnregisterListener) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    sp<TestStateListener> listener2 = new TestStateListener();
+    StateManager mgr;
+
+    // Unregister listener from non-existing StateTracker
+    EXPECT_EQ(0, mgr.getStateTrackersCount());
+    mgr.unregisterListener(android::util::SCREEN_STATE_CHANGED, listener1);
+    EXPECT_EQ(0, mgr.getStateTrackersCount());
+    EXPECT_EQ(-1, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+
+    // Unregister non-registered listener from existing StateTracker
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener1);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+    EXPECT_EQ(1, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+    mgr.unregisterListener(android::util::SCREEN_STATE_CHANGED, listener2);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+    EXPECT_EQ(1, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+
+    // Unregister second-to-last listener from StateTracker
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener2);
+    mgr.unregisterListener(android::util::SCREEN_STATE_CHANGED, listener1);
+    EXPECT_EQ(1, mgr.getStateTrackersCount());
+    EXPECT_EQ(1, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+
+    // Unregister last listener from StateTracker
+    mgr.unregisterListener(android::util::SCREEN_STATE_CHANGED, listener2);
+    EXPECT_EQ(0, mgr.getStateTrackersCount());
+    EXPECT_EQ(-1, mgr.getListenersCount(android::util::SCREEN_STATE_CHANGED));
+}
+
+/**
+ * Test StateManager's onLogEvent and StateListener's onStateChanged correctly
+ * updates listener for states without primary keys.
+ */
+TEST(StateTrackerTest, TestStateChangeNoPrimaryFields) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    StateManager mgr;
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener1);
+
+    // log event
+    std::shared_ptr<LogEvent> event =
+            buildScreenEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+    mgr.onLogEvent(*event);
+
+    // check listener was updated
+    EXPECT_EQ(1, listener1->updates.size());
+    EXPECT_EQ(DEFAULT_DIMENSION_KEY, listener1->updates[0].mKey);
+    EXPECT_EQ(2, listener1->updates[0].mState);
+
+    // check StateTracker was updated by querying for state
+    HashableDimensionKey queryKey = DEFAULT_DIMENSION_KEY;
+    EXPECT_EQ(2, mgr.getState(android::util::SCREEN_STATE_CHANGED, queryKey));
+}
+
+/**
+ * Test StateManager's onLogEvent and StateListener's onStateChanged correctly
+ * updates listener for states with primary keys.
+ */
+TEST(StateTrackerTest, TestStateChangeOnePrimaryField) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    StateManager mgr;
+    mgr.registerListener(android::util::UID_PROCESS_STATE_CHANGED, listener1);
+
+    // log event
+    std::shared_ptr<LogEvent> event = buildUidProcessEvent(
+            1000,
+            android::app::ProcessStateEnum::PROCESS_STATE_TOP);  //  state value: 1002
+    mgr.onLogEvent(*event);
+
+    // check listener was updated
+    EXPECT_EQ(1, listener1->updates.size());
+    EXPECT_EQ(1000, listener1->updates[0].mKey.getValues()[0].mValue.int_value);
+    EXPECT_EQ(1002, listener1->updates[0].mState);
+
+    // check StateTracker was updated by querying for state
+    HashableDimensionKey queryKey;
+    getUidProcessKey(1000, &queryKey);
+    EXPECT_EQ(1002, mgr.getState(android::util::UID_PROCESS_STATE_CHANGED, queryKey));
+}
+
+TEST(StateTrackerTest, TestStateChangeMultiplePrimaryFields) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    StateManager mgr;
+    mgr.registerListener(android::util::OVERLAY_STATE_CHANGED, listener1);
+
+    // log event
+    std::shared_ptr<LogEvent> event = buildOverlayEvent(1000, "package1", 1);  // state: ENTERED
+    mgr.onLogEvent(*event);
+
+    // check listener update
+    EXPECT_EQ(1, listener1->updates.size());
+    EXPECT_EQ(1000, listener1->updates[0].mKey.getValues()[0].mValue.int_value);
+    EXPECT_EQ(1, listener1->updates[0].mState);
+}
+
+/**
+ * Test StateManager's onLogEvent and StateListener's onStateChanged
+ * when there is an error extracting state from log event. Listener is not
+ * updated of state change.
+ */
+TEST(StateTrackerTest, TestStateChangeEventError) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    StateManager mgr;
+    mgr.registerListener(android::util::OVERLAY_STATE_CHANGED, listener1);
+
+    // log event
+    std::shared_ptr<LogEvent> event =
+            buildIncorrectOverlayEvent(1000, "package1", 1);  // state: ENTERED
+    mgr.onLogEvent(*event);
+
+    // check listener update
+    EXPECT_EQ(0, listener1->updates.size());
+}
+
+TEST(StateTrackerTest, TestStateQuery) {
+    sp<TestStateListener> listener1 = new TestStateListener();
+    sp<TestStateListener> listener2 = new TestStateListener();
+    sp<TestStateListener> listener3 = new TestStateListener();
+    StateManager mgr;
+    mgr.registerListener(android::util::SCREEN_STATE_CHANGED, listener1);
+    mgr.registerListener(android::util::UID_PROCESS_STATE_CHANGED, listener2);
+    mgr.registerListener(android::util::OVERLAY_STATE_CHANGED, listener3);
+
+    std::shared_ptr<LogEvent> event1 = buildUidProcessEvent(
+            1000,
+            android::app::ProcessStateEnum::PROCESS_STATE_TOP);  // state value: 1002
+    std::shared_ptr<LogEvent> event2 = buildUidProcessEvent(
+            1001,
+            android::app::ProcessStateEnum::PROCESS_STATE_FOREGROUND_SERVICE);  // state value: 1003
+    std::shared_ptr<LogEvent> event3 = buildUidProcessEvent(
+            1002,
+            android::app::ProcessStateEnum::PROCESS_STATE_PERSISTENT);  // state value: 1000
+    std::shared_ptr<LogEvent> event4 = buildUidProcessEvent(
+            1001,
+            android::app::ProcessStateEnum::PROCESS_STATE_TOP);  // state value: 1002
+    std::shared_ptr<LogEvent> event5 =
+            buildScreenEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON);  // state value:
+    std::shared_ptr<LogEvent> event6 = buildOverlayEvent(1000, "package1", 1);
+    std::shared_ptr<LogEvent> event7 = buildOverlayEvent(1000, "package2", 2);
+
+    mgr.onLogEvent(*event1);
+    mgr.onLogEvent(*event2);
+    mgr.onLogEvent(*event3);
+    mgr.onLogEvent(*event5);
+    mgr.onLogEvent(*event5);
+    mgr.onLogEvent(*event6);
+    mgr.onLogEvent(*event7);
+
+    // Query for UidProcessState of uid 1001
+    HashableDimensionKey queryKey1;
+    getUidProcessKey(1001, &queryKey1);
+    EXPECT_EQ(1003, mgr.getState(android::util::UID_PROCESS_STATE_CHANGED, queryKey1));
+
+    // Query for UidProcessState of uid 1004 - not in state map
+    HashableDimensionKey queryKey2;
+    getUidProcessKey(1004, &queryKey2);
+    EXPECT_EQ(-1,
+              mgr.getState(android::util::UID_PROCESS_STATE_CHANGED, queryKey2));  // default state
+
+    // Query for UidProcessState of uid 1001 - after change in state
+    mgr.onLogEvent(*event4);
+    EXPECT_EQ(1002, mgr.getState(android::util::UID_PROCESS_STATE_CHANGED, queryKey1));
+
+    // Query for ScreenState
+    EXPECT_EQ(2, mgr.getState(android::util::SCREEN_STATE_CHANGED, DEFAULT_DIMENSION_KEY));
+
+    // Query for OverlayState of uid 1000, package name "package2"
+    HashableDimensionKey queryKey3;
+    getOverlayKey(1000, "package2", &queryKey3);
+    EXPECT_EQ(2, mgr.getState(android::util::OVERLAY_STATE_CHANGED, queryKey3));
+}
+
+}  // namespace statsd
+}  // namespace os
+}  // namespace android
+#else
+GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
diff --git a/cmds/telecom/src/com/android/commands/telecom/Telecom.java b/cmds/telecom/src/com/android/commands/telecom/Telecom.java
index e0f7d86..c9f069d 100644
--- a/cmds/telecom/src/com/android/commands/telecom/Telecom.java
+++ b/cmds/telecom/src/com/android/commands/telecom/Telecom.java
@@ -65,11 +65,21 @@
     private static final String COMMAND_UNREGISTER_PHONE_ACCOUNT = "unregister-phone-account";
     private static final String COMMAND_SET_DEFAULT_DIALER = "set-default-dialer";
     private static final String COMMAND_GET_DEFAULT_DIALER = "get-default-dialer";
+    /**
+     * Change the system dialer package name if a package name was specified,
+     * Example: adb shell telecom set-system-dialer <PACKAGE>
+     *
+     * Restore it to the default if if argument is "default" or no argument is passed.
+     * Example: adb shell telecom set-system-dialer default
+     */
+    private static final String COMMAND_SET_SYSTEM_DIALER = "set-system-dialer";
     private static final String COMMAND_GET_SYSTEM_DIALER = "get-system-dialer";
     private static final String COMMAND_WAIT_ON_HANDLERS = "wait-on-handlers";
     private static final String COMMAND_SET_SIM_COUNT = "set-sim-count";
     private static final String COMMAND_GET_SIM_CONFIG = "get-sim-config";
     private static final String COMMAND_GET_MAX_PHONES = "get-max-phones";
+    private static final String COMMAND_SET_TEST_EMERGENCY_PHONE_ACCOUNT_PACKAGE_FILTER =
+            "set-test-emergency-phone-account-package-filter";
 
     private ComponentName mComponent;
     private String mAccountId;
@@ -83,7 +93,10 @@
                 + "usage: telecom set-phone-account-enabled <COMPONENT> <ID> <USER_SN>\n"
                 + "usage: telecom set-phone-account-disabled <COMPONENT> <ID> <USER_SN>\n"
                 + "usage: telecom register-phone-account <COMPONENT> <ID> <USER_SN> <LABEL>\n"
-                + "usage: telecom set-user-selected-outgoing-phone-account <COMPONENT> <ID> "
+                + "usage: telecom register-sim-phone-account [-e] <COMPONENT> <ID> <USER_SN>"
+                        + " <LABEL>: registers a PhoneAccount with CAPABILITY_SIM_SUBSCRIPTION"
+                        + " and optionally CAPABILITY_PLACE_EMERGENCY_CALLS if \"-e\" is provided\n"
+                + "usage: telecom set-user-selected-outgoing-phone-account [-e] <COMPONENT> <ID> "
                 + "<USER_SN>\n"
                 + "usage: telecom set-test-call-redirection-app <PACKAGE>\n"
                 + "usage: telecom set-test-call-screening-app <PACKAGE>\n"
@@ -100,6 +113,7 @@
                 + "usage: telecom set-sim-count <COUNT>\n"
                 + "usage: telecom get-sim-config\n"
                 + "usage: telecom get-max-phones\n"
+                + "usage: telecom set-emer-phone-account-filter <PACKAGE>\n"
                 + "\n"
                 + "telecom set-phone-account-enabled: Enables the given phone account, if it has"
                         + " already been registered with Telecom.\n"
@@ -113,6 +127,8 @@
                 + "telecom get-default-dialer: Displays the current default dialer.\n"
                 + "\n"
                 + "telecom get-system-dialer: Displays the current system dialer.\n"
+                + "telecom set-system-dialer: Set the override system dialer to the given"
+                        + " component. To remove the override, send \"default\"\n"
                 + "\n"
                 + "telecom wait-on-handlers: Wait until all handlers finish their work.\n"
                 + "\n"
@@ -123,6 +139,10 @@
                         + " or \"\" for single SIM\n"
                 + "\n"
                 + "telecom get-max-phones: Get the max supported phones from the modem.\n"
+                + "telecom set-test-emergency-phone-account-package-filter <PACKAGE>: sets a"
+                        + " package name that will be used for test emergency calls. To clear,"
+                        + " send an empty package name. Real emergency calls will still be placed"
+                        + " over Telephony.\n"
         );
     }
 
@@ -193,6 +213,9 @@
             case COMMAND_GET_DEFAULT_DIALER:
                 runGetDefaultDialer();
                 break;
+            case COMMAND_SET_SYSTEM_DIALER:
+                runSetSystemDialer();
+                break;
             case COMMAND_GET_SYSTEM_DIALER:
                 runGetSystemDialer();
                 break;
@@ -208,6 +231,9 @@
             case COMMAND_GET_MAX_PHONES:
                 runGetMaxPhones();
                 break;
+            case COMMAND_SET_TEST_EMERGENCY_PHONE_ACCOUNT_PACKAGE_FILTER:
+                runSetEmergencyPhoneAccountPackageFilter();
+                break;
             default:
                 Log.w(this, "onRun: unknown command: %s", command);
                 throw new IllegalArgumentException ("unknown command '" + command + "'");
@@ -234,19 +260,31 @@
     }
 
     private void runRegisterSimPhoneAccount() throws RemoteException {
+        boolean isEmergencyAccount = false;
+        String opt;
+        while ((opt = nextOption()) != null) {
+            switch (opt) {
+                case "-e": {
+                    isEmergencyAccount = true;
+                    break;
+                }
+            }
+        }
         final PhoneAccountHandle handle = getPhoneAccountHandleFromArgs();
         final String label = nextArgRequired();
         final String address = nextArgRequired();
+        int capabilities = PhoneAccount.CAPABILITY_CALL_PROVIDER
+                | PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION
+                | (isEmergencyAccount ? PhoneAccount.CAPABILITY_PLACE_EMERGENCY_CALLS : 0);
         PhoneAccount account = PhoneAccount.builder(
             handle, label)
-            .setAddress(Uri.parse(address))
-            .setSubscriptionAddress(Uri.parse(address))
-            .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
-                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
-            .setShortDescription(label)
-            .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
-            .addSupportedUriScheme(PhoneAccount.SCHEME_VOICEMAIL)
-            .build();
+                .setAddress(Uri.parse(address))
+                .setSubscriptionAddress(Uri.parse(address))
+                .setCapabilities(capabilities)
+                .setShortDescription(label)
+                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
+                .addSupportedUriScheme(PhoneAccount.SCHEME_VOICEMAIL)
+                .build();
         mTelecomService.registerPhoneAccount(account);
         System.out.println("Success - " + handle + " registered.");
     }
@@ -297,6 +335,14 @@
         System.out.println("Success - " + packageName + " set as override default dialer.");
     }
 
+    private void runSetSystemDialer() throws RemoteException {
+        final String flatComponentName = nextArg();
+        final ComponentName componentName = (flatComponentName.equals("default")
+                ? null : parseComponentName(flatComponentName));
+        mTelecomService.setSystemDialer(componentName);
+        System.out.println("Success - " + componentName + " set as override system dialer.");
+    }
+
     private void runGetDefaultDialer() throws RemoteException {
         System.out.println(mTelecomService.getDefaultDialerPackage());
     }
@@ -338,6 +384,18 @@
         }
     }
 
+    private void runSetEmergencyPhoneAccountPackageFilter() throws RemoteException {
+        String packageName = mArgs.getNextArg();
+        if (TextUtils.isEmpty(packageName)) {
+            mTelecomService.setTestEmergencyPhoneAccountPackageNameFilter(null);
+            System.out.println("Success - filter cleared");
+        } else {
+            mTelecomService.setTestEmergencyPhoneAccountPackageNameFilter(packageName);
+            System.out.println("Success = filter set to " + packageName);
+        }
+
+    }
+
     private PhoneAccountHandle getPhoneAccountHandleFromArgs() throws RemoteException {
         if (TextUtils.isEmpty(mArgs.peekNextArg())) {
             return null;
diff --git a/config/hiddenapi-greylist.txt b/config/hiddenapi-greylist.txt
index a6e1f0a..3cb2273 100644
--- a/config/hiddenapi-greylist.txt
+++ b/config/hiddenapi-greylist.txt
@@ -218,7 +218,6 @@
 Landroid/location/ILocationManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/location/ILocationManager;
 Landroid/location/ILocationManager$Stub;->TRANSACTION_getAllProviders:I
 Landroid/location/INetInitiatedListener$Stub;-><init>()V
-Landroid/location/LocationManager$ListenerTransport;-><init>(Landroid/location/LocationManager;Landroid/location/LocationListener;Landroid/os/Looper;)V
 Landroid/Manifest$permission;->CAPTURE_SECURE_VIDEO_OUTPUT:Ljava/lang/String;
 Landroid/Manifest$permission;->CAPTURE_VIDEO_OUTPUT:Ljava/lang/String;
 Landroid/Manifest$permission;->READ_FRAME_BUFFER:Ljava/lang/String;
@@ -1150,6 +1149,8 @@
 Lcom/android/internal/statusbar/IStatusBarService$Stub;-><init>()V
 Lcom/android/internal/statusbar/IStatusBarService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/statusbar/IStatusBarService;
 Lcom/android/internal/telecom/ITelecomService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telecom/ITelecomService;
+Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;->mRemote:Landroid/os/IBinder;
+Lcom/android/internal/telephony/IIccPhoneBook$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/IIccPhoneBook;
 Lcom/android/internal/telephony/IMms$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/IMms;
 Lcom/android/internal/telephony/IPhoneStateListener$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/IPhoneStateListener;
 Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
@@ -1157,6 +1158,7 @@
 Lcom/android/internal/telephony/IPhoneSubInfo$Stub;->TRANSACTION_getDeviceId:I
 Lcom/android/internal/telephony/ISms$Stub;-><init>()V
 Lcom/android/internal/telephony/ISms$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/ISms;
+Lcom/android/internal/telephony/ISub$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Lcom/android/internal/telephony/ISub$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/ISub;
 Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-><init>(Landroid/os/IBinder;)V
 Lcom/android/internal/telephony/ITelephony$Stub$Proxy;->mRemote:Landroid/os/IBinder;
@@ -1180,283 +1182,4 @@
 Lcom/android/server/ResettableTimeout$T;-><init>(Lcom/android/server/ResettableTimeout;)V
 Lcom/google/android/gles_jni/EGLImpl;-><init>()V
 Lcom/google/android/gles_jni/GLImpl;-><init>()V
-Lcom/google/android/mms/ContentType;->getAudioTypes()Ljava/util/ArrayList;
-Lcom/google/android/mms/ContentType;->getImageTypes()Ljava/util/ArrayList;
-Lcom/google/android/mms/ContentType;->getVideoTypes()Ljava/util/ArrayList;
-Lcom/google/android/mms/ContentType;->isAudioType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isDrmType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isImageType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isSupportedAudioType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isSupportedImageType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isSupportedType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isSupportedVideoType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isTextType(Ljava/lang/String;)Z
-Lcom/google/android/mms/ContentType;->isVideoType(Ljava/lang/String;)Z
-Lcom/google/android/mms/InvalidHeaderValueException;-><init>(Ljava/lang/String;)V
-Lcom/google/android/mms/MmsException;-><init>()V
-Lcom/google/android/mms/MmsException;-><init>(Ljava/lang/String;)V
-Lcom/google/android/mms/MmsException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V
-Lcom/google/android/mms/MmsException;-><init>(Ljava/lang/Throwable;)V
-Lcom/google/android/mms/pdu/AcknowledgeInd;-><init>(I[B)V
-Lcom/google/android/mms/pdu/AcknowledgeInd;-><init>(Lcom/google/android/mms/pdu/PduHeaders;)V
-Lcom/google/android/mms/pdu/AcknowledgeInd;->setReportAllowed(I)V
-Lcom/google/android/mms/pdu/AcknowledgeInd;->setTransactionId([B)V
-Lcom/google/android/mms/pdu/Base64;->decodeBase64([B)[B
-Lcom/google/android/mms/pdu/CharacterSets;->getMibEnumValue(Ljava/lang/String;)I
-Lcom/google/android/mms/pdu/CharacterSets;->getMimeName(I)Ljava/lang/String;
-Lcom/google/android/mms/pdu/DeliveryInd;-><init>(Lcom/google/android/mms/pdu/PduHeaders;)V
-Lcom/google/android/mms/pdu/DeliveryInd;->getDate()J
-Lcom/google/android/mms/pdu/DeliveryInd;->getMessageId()[B
-Lcom/google/android/mms/pdu/DeliveryInd;->getStatus()I
-Lcom/google/android/mms/pdu/DeliveryInd;->getTo()[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/EncodedStringValue;-><init>(I[B)V
-Lcom/google/android/mms/pdu/EncodedStringValue;-><init>(Ljava/lang/String;)V
-Lcom/google/android/mms/pdu/EncodedStringValue;-><init>([B)V
-Lcom/google/android/mms/pdu/EncodedStringValue;->appendTextString([B)V
-Lcom/google/android/mms/pdu/EncodedStringValue;->concat([Lcom/google/android/mms/pdu/EncodedStringValue;)Ljava/lang/String;
-Lcom/google/android/mms/pdu/EncodedStringValue;->copy(Lcom/google/android/mms/pdu/EncodedStringValue;)Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/EncodedStringValue;->encodeStrings([Ljava/lang/String;)[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/EncodedStringValue;->extract(Ljava/lang/String;)[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/EncodedStringValue;->getCharacterSet()I
-Lcom/google/android/mms/pdu/EncodedStringValue;->getString()Ljava/lang/String;
-Lcom/google/android/mms/pdu/EncodedStringValue;->getTextString()[B
-Lcom/google/android/mms/pdu/EncodedStringValue;->setCharacterSet(I)V
-Lcom/google/android/mms/pdu/EncodedStringValue;->setTextString([B)V
-Lcom/google/android/mms/pdu/GenericPdu;-><init>()V
-Lcom/google/android/mms/pdu/GenericPdu;->getFrom()Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/GenericPdu;->getMessageType()I
-Lcom/google/android/mms/pdu/GenericPdu;->getPduHeaders()Lcom/google/android/mms/pdu/PduHeaders;
-Lcom/google/android/mms/pdu/GenericPdu;->mPduHeaders:Lcom/google/android/mms/pdu/PduHeaders;
-Lcom/google/android/mms/pdu/GenericPdu;->setFrom(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/GenericPdu;->setMessageType(I)V
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;-><init>()V
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;-><init>(Lcom/google/android/mms/pdu/PduHeaders;Lcom/google/android/mms/pdu/PduBody;)V
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->addTo(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->getBody()Lcom/google/android/mms/pdu/PduBody;
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->getDate()J
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->getPriority()I
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->getSubject()Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->getTo()[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->setBody(Lcom/google/android/mms/pdu/PduBody;)V
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->setDate(J)V
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->setPriority(I)V
-Lcom/google/android/mms/pdu/MultimediaMessagePdu;->setSubject(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/NotificationInd;-><init>()V
-Lcom/google/android/mms/pdu/NotificationInd;-><init>(Lcom/google/android/mms/pdu/PduHeaders;)V
-Lcom/google/android/mms/pdu/NotificationInd;->getContentClass()I
-Lcom/google/android/mms/pdu/NotificationInd;->getContentLocation()[B
-Lcom/google/android/mms/pdu/NotificationInd;->getDeliveryReport()I
-Lcom/google/android/mms/pdu/NotificationInd;->getExpiry()J
-Lcom/google/android/mms/pdu/NotificationInd;->getFrom()Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/NotificationInd;->getMessageClass()[B
-Lcom/google/android/mms/pdu/NotificationInd;->getMessageSize()J
-Lcom/google/android/mms/pdu/NotificationInd;->getSubject()Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/NotificationInd;->getTransactionId()[B
-Lcom/google/android/mms/pdu/NotificationInd;->setContentClass(I)V
-Lcom/google/android/mms/pdu/NotificationInd;->setContentLocation([B)V
-Lcom/google/android/mms/pdu/NotificationInd;->setDeliveryReport(I)V
-Lcom/google/android/mms/pdu/NotificationInd;->setExpiry(J)V
-Lcom/google/android/mms/pdu/NotificationInd;->setFrom(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/NotificationInd;->setMessageClass([B)V
-Lcom/google/android/mms/pdu/NotificationInd;->setMessageSize(J)V
-Lcom/google/android/mms/pdu/NotificationInd;->setSubject(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/NotificationInd;->setTransactionId([B)V
-Lcom/google/android/mms/pdu/NotifyRespInd;-><init>(I[BI)V
-Lcom/google/android/mms/pdu/NotifyRespInd;-><init>(Lcom/google/android/mms/pdu/PduHeaders;)V
-Lcom/google/android/mms/pdu/NotifyRespInd;->setReportAllowed(I)V
-Lcom/google/android/mms/pdu/NotifyRespInd;->setStatus(I)V
-Lcom/google/android/mms/pdu/NotifyRespInd;->setTransactionId([B)V
-Lcom/google/android/mms/pdu/PduBody;-><init>()V
-Lcom/google/android/mms/pdu/PduBody;->addPart(ILcom/google/android/mms/pdu/PduPart;)V
-Lcom/google/android/mms/pdu/PduBody;->addPart(Lcom/google/android/mms/pdu/PduPart;)Z
-Lcom/google/android/mms/pdu/PduBody;->getPart(I)Lcom/google/android/mms/pdu/PduPart;
-Lcom/google/android/mms/pdu/PduBody;->getPartByContentId(Ljava/lang/String;)Lcom/google/android/mms/pdu/PduPart;
-Lcom/google/android/mms/pdu/PduBody;->getPartByContentLocation(Ljava/lang/String;)Lcom/google/android/mms/pdu/PduPart;
-Lcom/google/android/mms/pdu/PduBody;->getPartByFileName(Ljava/lang/String;)Lcom/google/android/mms/pdu/PduPart;
-Lcom/google/android/mms/pdu/PduBody;->getPartByName(Ljava/lang/String;)Lcom/google/android/mms/pdu/PduPart;
-Lcom/google/android/mms/pdu/PduBody;->getPartIndex(Lcom/google/android/mms/pdu/PduPart;)I
-Lcom/google/android/mms/pdu/PduBody;->getPartsNum()I
-Lcom/google/android/mms/pdu/PduBody;->removePart(I)Lcom/google/android/mms/pdu/PduPart;
-Lcom/google/android/mms/pdu/PduComposer$BufferStack;->copy()V
-Lcom/google/android/mms/pdu/PduComposer$BufferStack;->mark()Lcom/google/android/mms/pdu/PduComposer$PositionMarker;
-Lcom/google/android/mms/pdu/PduComposer$BufferStack;->newbuf()V
-Lcom/google/android/mms/pdu/PduComposer$BufferStack;->pop()V
-Lcom/google/android/mms/pdu/PduComposer$PositionMarker;->getLength()I
-Lcom/google/android/mms/pdu/PduComposer;-><init>(Landroid/content/Context;Lcom/google/android/mms/pdu/GenericPdu;)V
-Lcom/google/android/mms/pdu/PduComposer;->appendEncodedString(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/PduComposer;->appendHeader(I)I
-Lcom/google/android/mms/pdu/PduComposer;->appendLongInteger(J)V
-Lcom/google/android/mms/pdu/PduComposer;->appendOctet(I)V
-Lcom/google/android/mms/pdu/PduComposer;->appendQuotedString(Ljava/lang/String;)V
-Lcom/google/android/mms/pdu/PduComposer;->appendQuotedString([B)V
-Lcom/google/android/mms/pdu/PduComposer;->appendShortInteger(I)V
-Lcom/google/android/mms/pdu/PduComposer;->appendTextString(Ljava/lang/String;)V
-Lcom/google/android/mms/pdu/PduComposer;->appendTextString([B)V
-Lcom/google/android/mms/pdu/PduComposer;->appendUintvarInteger(J)V
-Lcom/google/android/mms/pdu/PduComposer;->appendValueLength(J)V
-Lcom/google/android/mms/pdu/PduComposer;->arraycopy([BII)V
-Lcom/google/android/mms/pdu/PduComposer;->make()[B
-Lcom/google/android/mms/pdu/PduComposer;->mContentTypeMap:Ljava/util/HashMap;
-Lcom/google/android/mms/pdu/PduComposer;->mMessage:Ljava/io/ByteArrayOutputStream;
-Lcom/google/android/mms/pdu/PduComposer;->mPdu:Lcom/google/android/mms/pdu/GenericPdu;
-Lcom/google/android/mms/pdu/PduComposer;->mPduHeader:Lcom/google/android/mms/pdu/PduHeaders;
-Lcom/google/android/mms/pdu/PduComposer;->mPosition:I
-Lcom/google/android/mms/pdu/PduComposer;->mResolver:Landroid/content/ContentResolver;
-Lcom/google/android/mms/pdu/PduComposer;->mStack:Lcom/google/android/mms/pdu/PduComposer$BufferStack;
-Lcom/google/android/mms/pdu/PduContentTypes;->contentTypes:[Ljava/lang/String;
-Lcom/google/android/mms/pdu/PduHeaders;-><init>()V
-Lcom/google/android/mms/pdu/PduHeaders;->appendEncodedStringValue(Lcom/google/android/mms/pdu/EncodedStringValue;I)V
-Lcom/google/android/mms/pdu/PduHeaders;->getEncodedStringValue(I)Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/PduHeaders;->getEncodedStringValues(I)[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/PduHeaders;->getLongInteger(I)J
-Lcom/google/android/mms/pdu/PduHeaders;->getOctet(I)I
-Lcom/google/android/mms/pdu/PduHeaders;->getTextString(I)[B
-Lcom/google/android/mms/pdu/PduHeaders;->setEncodedStringValue(Lcom/google/android/mms/pdu/EncodedStringValue;I)V
-Lcom/google/android/mms/pdu/PduHeaders;->setLongInteger(JI)V
-Lcom/google/android/mms/pdu/PduHeaders;->setOctet(II)V
-Lcom/google/android/mms/pdu/PduParser;-><init>([BZ)V
-Lcom/google/android/mms/pdu/PduParser;->checkPartPosition(Lcom/google/android/mms/pdu/PduPart;)I
-Lcom/google/android/mms/pdu/PduParser;->log(Ljava/lang/String;)V
-Lcom/google/android/mms/pdu/PduParser;->parse()Lcom/google/android/mms/pdu/GenericPdu;
-Lcom/google/android/mms/pdu/PduParser;->parseContentType(Ljava/io/ByteArrayInputStream;Ljava/util/HashMap;)[B
-Lcom/google/android/mms/pdu/PduParser;->parsePartHeaders(Ljava/io/ByteArrayInputStream;Lcom/google/android/mms/pdu/PduPart;I)Z
-Lcom/google/android/mms/pdu/PduParser;->parseShortInteger(Ljava/io/ByteArrayInputStream;)I
-Lcom/google/android/mms/pdu/PduParser;->parseUnsignedInt(Ljava/io/ByteArrayInputStream;)I
-Lcom/google/android/mms/pdu/PduParser;->parseValueLength(Ljava/io/ByteArrayInputStream;)I
-Lcom/google/android/mms/pdu/PduParser;->parseWapString(Ljava/io/ByteArrayInputStream;I)[B
-Lcom/google/android/mms/pdu/PduPart;-><init>()V
-Lcom/google/android/mms/pdu/PduPart;->generateLocation()Ljava/lang/String;
-Lcom/google/android/mms/pdu/PduPart;->getCharset()I
-Lcom/google/android/mms/pdu/PduPart;->getContentDisposition()[B
-Lcom/google/android/mms/pdu/PduPart;->getContentId()[B
-Lcom/google/android/mms/pdu/PduPart;->getContentLocation()[B
-Lcom/google/android/mms/pdu/PduPart;->getContentTransferEncoding()[B
-Lcom/google/android/mms/pdu/PduPart;->getContentType()[B
-Lcom/google/android/mms/pdu/PduPart;->getData()[B
-Lcom/google/android/mms/pdu/PduPart;->getDataLength()I
-Lcom/google/android/mms/pdu/PduPart;->getDataUri()Landroid/net/Uri;
-Lcom/google/android/mms/pdu/PduPart;->getFilename()[B
-Lcom/google/android/mms/pdu/PduPart;->getName()[B
-Lcom/google/android/mms/pdu/PduPart;->setCharset(I)V
-Lcom/google/android/mms/pdu/PduPart;->setContentDisposition([B)V
-Lcom/google/android/mms/pdu/PduPart;->setContentId([B)V
-Lcom/google/android/mms/pdu/PduPart;->setContentLocation([B)V
-Lcom/google/android/mms/pdu/PduPart;->setContentTransferEncoding([B)V
-Lcom/google/android/mms/pdu/PduPart;->setContentType([B)V
-Lcom/google/android/mms/pdu/PduPart;->setData([B)V
-Lcom/google/android/mms/pdu/PduPart;->setDataUri(Landroid/net/Uri;)V
-Lcom/google/android/mms/pdu/PduPart;->setFilename([B)V
-Lcom/google/android/mms/pdu/PduPart;->setName([B)V
-Lcom/google/android/mms/pdu/PduPersister;->ADDRESS_FIELDS:[I
-Lcom/google/android/mms/pdu/PduPersister;->CHARSET_COLUMN_NAME_MAP:Ljava/util/HashMap;
-Lcom/google/android/mms/pdu/PduPersister;->ENCODED_STRING_COLUMN_NAME_MAP:Ljava/util/HashMap;
-Lcom/google/android/mms/pdu/PduPersister;->getByteArrayFromPartColumn(Landroid/database/Cursor;I)[B
-Lcom/google/android/mms/pdu/PduPersister;->getBytes(Ljava/lang/String;)[B
-Lcom/google/android/mms/pdu/PduPersister;->getIntegerFromPartColumn(Landroid/database/Cursor;I)Ljava/lang/Integer;
-Lcom/google/android/mms/pdu/PduPersister;->getPartContentType(Lcom/google/android/mms/pdu/PduPart;)Ljava/lang/String;
-Lcom/google/android/mms/pdu/PduPersister;->getPduPersister(Landroid/content/Context;)Lcom/google/android/mms/pdu/PduPersister;
-Lcom/google/android/mms/pdu/PduPersister;->getPendingMessages(J)Landroid/database/Cursor;
-Lcom/google/android/mms/pdu/PduPersister;->load(Landroid/net/Uri;)Lcom/google/android/mms/pdu/GenericPdu;
-Lcom/google/android/mms/pdu/PduPersister;->loadRecipients(ILjava/util/HashSet;Ljava/util/HashMap;Z)V
-Lcom/google/android/mms/pdu/PduPersister;->LONG_COLUMN_NAME_MAP:Ljava/util/HashMap;
-Lcom/google/android/mms/pdu/PduPersister;->mContentResolver:Landroid/content/ContentResolver;
-Lcom/google/android/mms/pdu/PduPersister;->mContext:Landroid/content/Context;
-Lcom/google/android/mms/pdu/PduPersister;->MESSAGE_BOX_MAP:Ljava/util/HashMap;
-Lcom/google/android/mms/pdu/PduPersister;->move(Landroid/net/Uri;Landroid/net/Uri;)Landroid/net/Uri;
-Lcom/google/android/mms/pdu/PduPersister;->mTelephonyManager:Landroid/telephony/TelephonyManager;
-Lcom/google/android/mms/pdu/PduPersister;->OCTET_COLUMN_NAME_MAP:Ljava/util/HashMap;
-Lcom/google/android/mms/pdu/PduPersister;->PART_PROJECTION:[Ljava/lang/String;
-Lcom/google/android/mms/pdu/PduPersister;->PDU_CACHE_INSTANCE:Lcom/google/android/mms/util/PduCache;
-Lcom/google/android/mms/pdu/PduPersister;->persist(Lcom/google/android/mms/pdu/GenericPdu;Landroid/net/Uri;ZZLjava/util/HashMap;)Landroid/net/Uri;
-Lcom/google/android/mms/pdu/PduPersister;->persistAddress(JI[Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/PduPersister;->persistPart(Lcom/google/android/mms/pdu/PduPart;JLjava/util/HashMap;)Landroid/net/Uri;
-Lcom/google/android/mms/pdu/PduPersister;->TEXT_STRING_COLUMN_NAME_MAP:Ljava/util/HashMap;
-Lcom/google/android/mms/pdu/PduPersister;->toIsoString([B)Ljava/lang/String;
-Lcom/google/android/mms/pdu/PduPersister;->updateAddress(JI[Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/PduPersister;->updateHeaders(Landroid/net/Uri;Lcom/google/android/mms/pdu/SendReq;)V
-Lcom/google/android/mms/pdu/PduPersister;->updateParts(Landroid/net/Uri;Lcom/google/android/mms/pdu/PduBody;Ljava/util/HashMap;)V
-Lcom/google/android/mms/pdu/QuotedPrintable;->decodeQuotedPrintable([B)[B
-Lcom/google/android/mms/pdu/ReadOrigInd;-><init>(Lcom/google/android/mms/pdu/PduHeaders;)V
-Lcom/google/android/mms/pdu/ReadOrigInd;->getMessageId()[B
-Lcom/google/android/mms/pdu/ReadOrigInd;->getReadStatus()I
-Lcom/google/android/mms/pdu/ReadRecInd;-><init>(Lcom/google/android/mms/pdu/EncodedStringValue;[BII[Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/ReadRecInd;-><init>(Lcom/google/android/mms/pdu/PduHeaders;)V
-Lcom/google/android/mms/pdu/ReadRecInd;->getMessageId()[B
-Lcom/google/android/mms/pdu/ReadRecInd;->setDate(J)V
-Lcom/google/android/mms/pdu/RetrieveConf;-><init>()V
-Lcom/google/android/mms/pdu/RetrieveConf;-><init>(Lcom/google/android/mms/pdu/PduHeaders;Lcom/google/android/mms/pdu/PduBody;)V
-Lcom/google/android/mms/pdu/RetrieveConf;->addCc(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/RetrieveConf;->getCc()[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/RetrieveConf;->getContentType()[B
-Lcom/google/android/mms/pdu/RetrieveConf;->getDeliveryReport()I
-Lcom/google/android/mms/pdu/RetrieveConf;->getFrom()Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/RetrieveConf;->getMessageClass()[B
-Lcom/google/android/mms/pdu/RetrieveConf;->getMessageId()[B
-Lcom/google/android/mms/pdu/RetrieveConf;->getReadReport()I
-Lcom/google/android/mms/pdu/RetrieveConf;->getRetrieveStatus()I
-Lcom/google/android/mms/pdu/RetrieveConf;->getRetrieveText()Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/RetrieveConf;->getTransactionId()[B
-Lcom/google/android/mms/pdu/RetrieveConf;->setContentType([B)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setDeliveryReport(I)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setFrom(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setMessageClass([B)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setMessageId([B)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setReadReport(I)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setRetrieveStatus(I)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setRetrieveText(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/RetrieveConf;->setTransactionId([B)V
-Lcom/google/android/mms/pdu/SendConf;-><init>()V
-Lcom/google/android/mms/pdu/SendConf;-><init>(Lcom/google/android/mms/pdu/PduHeaders;)V
-Lcom/google/android/mms/pdu/SendConf;->getMessageId()[B
-Lcom/google/android/mms/pdu/SendConf;->getResponseStatus()I
-Lcom/google/android/mms/pdu/SendConf;->getTransactionId()[B
-Lcom/google/android/mms/pdu/SendReq;-><init>()V
-Lcom/google/android/mms/pdu/SendReq;-><init>(Lcom/google/android/mms/pdu/PduHeaders;Lcom/google/android/mms/pdu/PduBody;)V
-Lcom/google/android/mms/pdu/SendReq;->addBcc(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/SendReq;->addCc(Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/SendReq;->getBcc()[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/SendReq;->getCc()[Lcom/google/android/mms/pdu/EncodedStringValue;
-Lcom/google/android/mms/pdu/SendReq;->getContentType()[B
-Lcom/google/android/mms/pdu/SendReq;->getDeliveryReport()I
-Lcom/google/android/mms/pdu/SendReq;->getExpiry()J
-Lcom/google/android/mms/pdu/SendReq;->getMessageClass()[B
-Lcom/google/android/mms/pdu/SendReq;->getMessageSize()J
-Lcom/google/android/mms/pdu/SendReq;->getReadReport()I
-Lcom/google/android/mms/pdu/SendReq;->getTransactionId()[B
-Lcom/google/android/mms/pdu/SendReq;->setBcc([Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/SendReq;->setCc([Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/SendReq;->setContentType([B)V
-Lcom/google/android/mms/pdu/SendReq;->setDeliveryReport(I)V
-Lcom/google/android/mms/pdu/SendReq;->setExpiry(J)V
-Lcom/google/android/mms/pdu/SendReq;->setMessageClass([B)V
-Lcom/google/android/mms/pdu/SendReq;->setMessageSize(J)V
-Lcom/google/android/mms/pdu/SendReq;->setReadReport(I)V
-Lcom/google/android/mms/pdu/SendReq;->setTo([Lcom/google/android/mms/pdu/EncodedStringValue;)V
-Lcom/google/android/mms/pdu/SendReq;->setTransactionId([B)V
-Lcom/google/android/mms/util/AbstractCache;-><init>()V
-Lcom/google/android/mms/util/AbstractCache;->get(Ljava/lang/Object;)Ljava/lang/Object;
-Lcom/google/android/mms/util/AbstractCache;->purge(Ljava/lang/Object;)Ljava/lang/Object;
-Lcom/google/android/mms/util/AbstractCache;->purgeAll()V
-Lcom/google/android/mms/util/AbstractCache;->put(Ljava/lang/Object;Ljava/lang/Object;)Z
-Lcom/google/android/mms/util/DownloadDrmHelper;->isDrmConvertNeeded(Ljava/lang/String;)Z
-Lcom/google/android/mms/util/DownloadDrmHelper;->modifyDrmFwLockFileExtension(Ljava/lang/String;)Ljava/lang/String;
-Lcom/google/android/mms/util/DrmConvertSession;->close(Ljava/lang/String;)I
-Lcom/google/android/mms/util/DrmConvertSession;->convert([BI)[B
-Lcom/google/android/mms/util/DrmConvertSession;->open(Landroid/content/Context;Ljava/lang/String;)Lcom/google/android/mms/util/DrmConvertSession;
-Lcom/google/android/mms/util/PduCache;-><init>()V
-Lcom/google/android/mms/util/PduCache;->getInstance()Lcom/google/android/mms/util/PduCache;
-Lcom/google/android/mms/util/PduCache;->isUpdating(Landroid/net/Uri;)Z
-Lcom/google/android/mms/util/PduCache;->purge(Landroid/net/Uri;)Lcom/google/android/mms/util/PduCacheEntry;
-Lcom/google/android/mms/util/PduCache;->purge(Ljava/lang/Object;)Ljava/lang/Object;
-Lcom/google/android/mms/util/PduCache;->purgeAll()V
-Lcom/google/android/mms/util/PduCacheEntry;-><init>(Lcom/google/android/mms/pdu/GenericPdu;IJ)V
-Lcom/google/android/mms/util/PduCacheEntry;->getMessageBox()I
-Lcom/google/android/mms/util/PduCacheEntry;->getPdu()Lcom/google/android/mms/pdu/GenericPdu;
-Lcom/google/android/mms/util/PduCacheEntry;->getThreadId()J
-Lcom/google/android/mms/util/SqliteWrapper;->checkSQLiteException(Landroid/content/Context;Landroid/database/sqlite/SQLiteException;)V
-Lcom/google/android/mms/util/SqliteWrapper;->delete(Landroid/content/Context;Landroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I
-Lcom/google/android/mms/util/SqliteWrapper;->insert(Landroid/content/Context;Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;
-Lcom/google/android/mms/util/SqliteWrapper;->query(Landroid/content/Context;Landroid/content/ContentResolver;Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;
-Lcom/google/android/mms/util/SqliteWrapper;->requery(Landroid/content/Context;Landroid/database/Cursor;)Z
-Lcom/google/android/mms/util/SqliteWrapper;->update(Landroid/content/Context;Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
 Lcom/google/android/util/AbstractMessageParser$Token$Type;->values()[Lcom/google/android/util/AbstractMessageParser$Token$Type;
diff --git a/config/preloaded-classes b/config/preloaded-classes
index e117e68..8d91144 100644
--- a/config/preloaded-classes
+++ b/config/preloaded-classes
@@ -4838,7 +4838,6 @@
 com.android.internal.telephony.PhoneConstants$DataState
 com.android.internal.telephony.PhoneConstants$State
 com.android.internal.telephony.PhoneFactory
-com.android.internal.telephony.PhoneInternalInterface$DataActivityState
 com.android.internal.telephony.PhoneInternalInterface
 com.android.internal.telephony.PhoneNotifier
 com.android.internal.telephony.PhoneStateIntentReceiver
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index d3c274f..4603f08 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -605,7 +605,7 @@
     }
 
     /**
-     * Gets the windows on the screen. This method returns only the windows
+     * Gets the windows on the screen of the default display. This method returns only the windows
      * that a sighted user can interact with, as opposed to all windows.
      * For example, if there is a modal dialog shown and the user cannot touch
      * anything behind it, then only the modal window will be reported
@@ -632,6 +632,34 @@
     }
 
     /**
+     * Gets the windows on the screen of all displays. This method returns only the windows
+     * that a sighted user can interact with, as opposed to all windows.
+     * For example, if there is a modal dialog shown and the user cannot touch
+     * anything behind it, then only the modal window will be reported
+     * (assuming it is the top one). For convenience the returned windows
+     * are ordered in a descending layer order, which is the windows that
+     * are on top are reported first. Since the user can always
+     * interact with the window that has input focus by typing, the focused
+     * window is always returned (even if covered by a modal window).
+     * <p>
+     * <strong>Note:</strong> In order to access the windows your service has
+     * to declare the capability to retrieve window content by setting the
+     * {@link android.R.styleable#AccessibilityService_canRetrieveWindowContent}
+     * property in its meta-data. For details refer to {@link #SERVICE_META_DATA}.
+     * Also the service has to opt-in to retrieve the interactive windows by
+     * setting the {@link AccessibilityServiceInfo#FLAG_RETRIEVE_INTERACTIVE_WINDOWS}
+     * flag.
+     * </p>
+     *
+     * @return The windows of all displays if there are windows and the service is can retrieve
+     *         them, otherwise an empty list. The key of SparseArray is display ID.
+     */
+    @NonNull
+    public final SparseArray<List<AccessibilityWindowInfo>> getWindowsOnAllDisplays() {
+        return AccessibilityInteractionClient.getInstance().getWindowsOnAllDisplays(mConnectionId);
+    }
+
+    /**
      * Gets the root node in the currently active window if this service
      * can retrieve window content. The active window is the one that the user
      * is currently touching or the window with input focus, if the user is not
diff --git a/core/java/android/accessibilityservice/AccessibilityShortcutInfo.java b/core/java/android/accessibilityservice/AccessibilityShortcutInfo.java
new file mode 100644
index 0000000..f4cadfd
--- /dev/null
+++ b/core/java/android/accessibilityservice/AccessibilityShortcutInfo.java
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2019 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.accessibilityservice;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.content.res.XmlResourceParser;
+import android.util.AttributeSet;
+import android.util.Xml;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+
+/**
+ * Activities of interest to users with accessibility needs may request to be targets of the
+ * accessibility shortcut. These activities must handle the
+ * {@link Intent#ACTION_MAIN} intent with category
+ * {@link Intent#CATEGORY_ACCESSIBILITY_SHORTCUT_TARGET}, which will be dispatched by the system
+ * when the user activates the shortcut when it is configured to point at this target.
+ *
+ * @see Intent#CATEGORY_ACCESSIBILITY_SHORTCUT_TARGET
+ *
+ * @hide
+ */
+public final class AccessibilityShortcutInfo {
+    private static final String TAG_ACCESSIBILITY_SHORTCUT = "accessibility-shortcut-target";
+
+    /**
+     * Name under which an activity component of the accessibility shortcut publishes information
+     * about itself. This meta-data must reference an XML resource containing an
+     * <code>&lt;accessibility-shortcut-target&gt;</code> tag.
+     */
+    public static final String META_DATA = "android.accessibilityshortcut.target";
+
+    /**
+     * The component name of the accessibility shortcut target.
+     */
+    private final ComponentName mComponentName;
+
+    /**
+     * The activity info of the accessibility shortcut target.
+     */
+    private final ActivityInfo mActivityInfo;
+
+    /**
+     * Resource id of the summary of the accessibility shortcut target.
+     */
+    private final int mSummaryResId;
+
+    /**
+     * Resource id of the description of the accessibility shortcut target.
+     */
+    private final int mDescriptionResId;
+
+    /**
+     * Creates a new instance.
+     *
+     * @param context Context for accessing resources.
+     * @param activityInfo The activity info.
+     * @throws XmlPullParserException If a XML parsing error occurs.
+     * @throws IOException If a XML parsing error occurs.
+     */
+    public AccessibilityShortcutInfo(@NonNull Context context, @NonNull ActivityInfo activityInfo)
+            throws XmlPullParserException, IOException {
+        final PackageManager packageManager = context.getPackageManager();
+        mComponentName = activityInfo.getComponentName();
+        mActivityInfo = activityInfo;
+
+        try (XmlResourceParser parser = mActivityInfo.loadXmlMetaData(
+                packageManager, META_DATA)) {
+            if (parser == null) {
+                throw new XmlPullParserException("Meta-data "
+                        + TAG_ACCESSIBILITY_SHORTCUT + " does not exist");
+            }
+
+            int type = 0;
+            while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
+                type = parser.next();
+            }
+
+            final String nodeName = parser.getName();
+            if (!TAG_ACCESSIBILITY_SHORTCUT.equals(nodeName)) {
+                throw new XmlPullParserException("Meta-data does not start with"
+                        + TAG_ACCESSIBILITY_SHORTCUT + " tag");
+            }
+
+            final AttributeSet allAttributes = Xml.asAttributeSet(parser);
+            final Resources resources = packageManager.getResourcesForApplication(
+                    mActivityInfo.applicationInfo);
+            final TypedArray asAttributes = resources.obtainAttributes(allAttributes,
+                    com.android.internal.R.styleable.AccessibilityShortcutTarget);
+
+            // Gets description
+            mDescriptionResId = asAttributes.getResourceId(
+                    com.android.internal.R.styleable.AccessibilityShortcutTarget_description, 0);
+            // Gets summary
+            mSummaryResId = asAttributes.getResourceId(
+                    com.android.internal.R.styleable.AccessibilityShortcutTarget_summary, 0);
+            asAttributes.recycle();
+
+            if (mDescriptionResId == 0 || mSummaryResId == 0) {
+                throw new XmlPullParserException("No description or summary in meta-data");
+            }
+        } catch (PackageManager.NameNotFoundException e) {
+            throw new XmlPullParserException("Unable to create context for: "
+                    + mActivityInfo.packageName);
+        }
+    }
+
+    /**
+     * The {@link ActivityInfo} of accessibility shortcut target.
+     *
+     * @return The activity info.
+     */
+    @NonNull
+    public ActivityInfo getActivityInfo() {
+        return mActivityInfo;
+    }
+
+    /**
+     * The localized summary of the accessibility shortcut target.
+     *
+     * @return The localized summary if available, and {@code null} if a summary
+     * has not been provided.
+     */
+    @Nullable
+    public String loadSummary(@NonNull PackageManager packageManager) {
+        return loadResourceString(packageManager, mActivityInfo, mSummaryResId);
+    }
+
+    /**
+     * The localized description of the accessibility shortcut target.
+     *
+     * @return The localized description.
+     */
+    @Nullable
+    public String loadDescription(@NonNull PackageManager packageManager) {
+        return loadResourceString(packageManager, mActivityInfo, mDescriptionResId);
+    }
+
+    /**
+     * Gets string resource by the given activity and resource id.
+     */
+    @Nullable
+    private String loadResourceString(@NonNull PackageManager packageManager,
+            @NonNull ActivityInfo activityInfo, int resId) {
+        if (resId == 0) {
+            return null;
+        }
+        final CharSequence text = packageManager.getText(activityInfo.packageName,
+                resId, activityInfo.applicationInfo);
+        if (text != null) {
+            return text.toString().trim();
+        }
+        return null;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public int hashCode() {
+        return 31 * 1 + ((mComponentName == null) ? 0 : mComponentName.hashCode());
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        final AccessibilityShortcutInfo other = (AccessibilityShortcutInfo) obj;
+        if (mComponentName == null) {
+            if (other.mComponentName != null) {
+                return false;
+            }
+        } else if (!mComponentName.equals(other.mComponentName)) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public String toString() {
+        StringBuilder stringBuilder = new StringBuilder();
+        stringBuilder.append("AccessibilityShortcutInfo[");
+        stringBuilder.append("activityInfo: ").append(mActivityInfo);
+        stringBuilder.append("]");
+        return stringBuilder.toString();
+    }
+}
diff --git a/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl b/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl
index 1ca07dd..4841781 100644
--- a/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl
+++ b/core/java/android/accessibilityservice/IAccessibilityServiceConnection.aidl
@@ -60,7 +60,7 @@
 
     AccessibilityWindowInfo getWindow(int windowId);
 
-    List<AccessibilityWindowInfo> getWindows();
+    AccessibilityWindowInfo.WindowListSparseArray getWindows();
 
     AccessibilityServiceInfo getServiceInfo();
 
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index bf7d632..03300e4 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -76,7 +76,6 @@
 import android.os.RemoteException;
 import android.os.ServiceManager.ServiceNotFoundException;
 import android.os.StrictMode;
-import android.os.SystemProperties;
 import android.os.Trace;
 import android.os.UserHandle;
 import android.text.Selection;
@@ -1925,11 +1924,15 @@
     }
 
     /**
-     * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
-     * of a voice interaction.  That is, returns true if this activity was directly
+     * Like {@link #isVoiceInteraction}, but only returns {@code true} if this is also the root
+     * of a voice interaction.  That is, returns {@code true} if this activity was directly
      * started by the voice interaction service as the initiation of a voice interaction.
      * Otherwise, for example if it was started by another activity while under voice
-     * interaction, returns false.
+     * interaction, returns {@code false}.
+     * If the activity {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode} is
+     * {@code singleTask}, it forces the activity to launch in a new task, separate from the one
+     * that started it. Therefore, there is no longer a relationship between them, and
+     * {@link #isVoiceInteractionRoot()} return {@code false} in this case.
      */
     public boolean isVoiceInteractionRoot() {
         try {
@@ -2473,17 +2476,13 @@
             getAutofillManager().onInvisibleForAutofill();
         }
 
-        if (isFinishing()) {
-            if (mAutoFillResetNeeded) {
-                getAutofillManager().onActivityFinishing();
-            } else if (mIntent != null
-                    && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
-                // Activity was launched when user tapped a link in the Autofill Save UI - since
-                // user launched another activity, the Save UI should not be restored when this
-                // activity is finished.
-                getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_CANCEL,
-                        mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN));
-            }
+        if (isFinishing() && !mAutoFillResetNeeded && mIntent != null
+                && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
+            // Activity was launched when user tapped a link in the Autofill Save UI - since
+            // user launched another activity, the Save UI should not be restored when this
+            // activity is finished.
+            getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_CANCEL,
+                    mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN));
         }
         mEnterAnimationComplete = false;
     }
@@ -2521,6 +2520,10 @@
         if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
         mCalled = true;
 
+        if (isFinishing() && mAutoFillResetNeeded) {
+            getAutofillManager().onActivityFinishing();
+        }
+
         // dismiss any dialogs we are managing.
         if (mManagedDialogs != null) {
             final int numDialogs = mManagedDialogs.size();
@@ -7862,13 +7865,10 @@
         mFragments.dispatchStart();
         mFragments.reportLoaderStart();
 
+        // Warn app developers if the dynamic linker logged anything during startup.
         boolean isAppDebuggable =
                 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
-
-        // This property is set for all non-user builds except final release
-        boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
-
-        if (isAppDebuggable || isDlwarningEnabled) {
+        if (isAppDebuggable) {
             String dlwarning = getDlWarning();
             if (dlwarning != null) {
                 String appName = getApplicationInfo().loadLabel(getPackageManager())
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index cb99a3a..7f597fe 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -188,57 +188,6 @@
     final ArrayMap<OnUidImportanceListener, UidObserver> mImportanceListeners = new ArrayMap<>();
 
     /**
-     * Defines acceptable types of bugreports.
-     * @hide
-     */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(prefix = { "BUGREPORT_OPTION_" }, value = {
-            BUGREPORT_OPTION_FULL,
-            BUGREPORT_OPTION_INTERACTIVE,
-            BUGREPORT_OPTION_REMOTE,
-            BUGREPORT_OPTION_WEAR,
-            BUGREPORT_OPTION_TELEPHONY,
-            BUGREPORT_OPTION_WIFI
-    })
-    public @interface BugreportMode {}
-    /**
-     * Takes a bugreport without user interference (and hence causing less
-     * interference to the system), but includes all sections.
-     * @hide
-     */
-    public static final int BUGREPORT_OPTION_FULL = 0;
-    /**
-     * Allows user to monitor progress and enter additional data; might not include all
-     * sections.
-     * @hide
-     */
-    public static final int BUGREPORT_OPTION_INTERACTIVE = 1;
-    /**
-     * Takes a bugreport requested remotely by administrator of the Device Owner app,
-     * not the device's user.
-     * @hide
-     */
-    public static final int BUGREPORT_OPTION_REMOTE = 2;
-    /**
-     * Takes a bugreport on a wearable device.
-     * @hide
-     */
-    public static final int BUGREPORT_OPTION_WEAR = 3;
-
-    /**
-     * Takes a lightweight version of bugreport that only includes a few, urgent sections
-     * used to report telephony bugs.
-     * @hide
-     */
-    public static final int BUGREPORT_OPTION_TELEPHONY = 4;
-
-    /**
-     * Takes a lightweight bugreport that only includes a few sections related to Wifi.
-     * @hide
-     */
-    public static final int BUGREPORT_OPTION_WIFI = 5;
-
-    /**
      * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
      * <meta-data>}</a> name for a 'home' Activity that declares a package that is to be
      * uninstalled in lieu of the declaring one.  The package named here must be
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 1cc8499..7f27368 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -1163,6 +1163,10 @@
             sendMessage(H.ATTACH_AGENT, agent);
         }
 
+        public void attachStartupAgents(String dataDir) {
+            sendMessage(H.ATTACH_STARTUP_AGENTS, dataDir);
+        }
+
         public void setSchedulingGroup(int group) {
             // Note: do this immediately, since going into the foreground
             // should happen regardless of what pending work we have to do
@@ -1812,6 +1816,7 @@
         public static final int EXECUTE_TRANSACTION = 159;
         public static final int RELAUNCH_ACTIVITY = 160;
         public static final int PURGE_RESOURCES = 161;
+        public static final int ATTACH_STARTUP_AGENTS = 162;
 
         String codeToString(int code) {
             if (DEBUG_MESSAGES) {
@@ -1855,6 +1860,7 @@
                     case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
                     case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
                     case PURGE_RESOURCES: return "PURGE_RESOURCES";
+                    case ATTACH_STARTUP_AGENTS: return "ATTACH_STARTUP_AGENTS";
                 }
             }
             return Integer.toString(code);
@@ -2043,6 +2049,9 @@
                 case PURGE_RESOURCES:
                     schedulePurgeIdler();
                     break;
+                case ATTACH_STARTUP_AGENTS:
+                    handleAttachStartupAgents((String) msg.obj);
+                    break;
             }
             Object obj = msg.obj;
             if (obj instanceof SomeArgs) {
@@ -3779,6 +3788,27 @@
         }
     }
 
+    static void handleAttachStartupAgents(String dataDir) {
+        try {
+            Path code_cache = ContextImpl.getCodeCacheDirBeforeBind(new File(dataDir)).toPath();
+            if (!Files.exists(code_cache)) {
+                return;
+            }
+            Path startup_path = code_cache.resolve("startup_agents");
+            if (Files.exists(startup_path)) {
+                for (Path p : Files.newDirectoryStream(startup_path)) {
+                    handleAttachAgent(
+                            p.toAbsolutePath().toString()
+                            + "="
+                            + dataDir,
+                            null);
+                }
+            }
+        } catch (Exception e) {
+            // Ignored.
+        }
+    }
+
     private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
 
     /**
@@ -4835,7 +4865,7 @@
         View.sDebugViewAttributesApplicationPackage = mCoreSettings.getString(
                 Settings.Global.DEBUG_VIEW_ATTRIBUTES_APPLICATION_PACKAGE, "");
         String currentPackage = (mBoundApplication != null && mBoundApplication.appInfo != null)
-                ? mBoundApplication.appInfo.packageName : "";
+                ? mBoundApplication.appInfo.packageName : "<unknown-app>";
         View.sDebugViewAttributes =
                 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0
                         || View.sDebugViewAttributesApplicationPackage.equals(currentPackage);
@@ -6427,26 +6457,6 @@
         NetworkSecurityConfigProvider.install(appContext);
         Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
 
-
-        if (isAppDebuggable) {
-            try {
-                // Load all the agents in the code_cache/startup_agents directory.
-                // We pass the absolute path to the data_dir as an argument.
-                Path startup_path = appContext.getCodeCacheDir().toPath().resolve("startup_agents");
-                if (Files.exists(startup_path)) {
-                    for (Path p : Files.newDirectoryStream(startup_path)) {
-                        handleAttachAgent(
-                                p.toAbsolutePath().toString()
-                                + "="
-                                + appContext.getDataDir().toPath().toAbsolutePath().toString(),
-                                data.info);
-                    }
-                }
-            } catch (Exception e) {
-                // Ignored.
-            }
-        }
-
         // Continue loading instrumentation.
         if (ii != null) {
             ApplicationInfo instrApp;
diff --git a/core/java/android/app/ActivityView.java b/core/java/android/app/ActivityView.java
index e891828..b56c00e 100644
--- a/core/java/android/app/ActivityView.java
+++ b/core/java/android/app/ActivityView.java
@@ -29,6 +29,7 @@
 import android.content.Intent;
 import android.graphics.Insets;
 import android.graphics.Matrix;
+import android.graphics.Rect;
 import android.graphics.Region;
 import android.hardware.display.DisplayManager;
 import android.hardware.display.VirtualDisplay;
@@ -101,6 +102,8 @@
 
     private Insets mForwardedInsets;
 
+    private float mCornerRadius;
+
     public ActivityView(Context context) {
         this(context, null /* attrs */);
     }
@@ -204,6 +207,45 @@
     }
 
     /**
+     * @hide
+     */
+    public float getCornerRadius() {
+        return mSurfaceView.getCornerRadius();
+    }
+
+    /**
+     * Control whether the surface is clipped to the same bounds as the View. If true, then
+     * the bounds set by {@link #setSurfaceClipBounds(Rect)} are applied to the surface as
+     * window-crop.
+     *
+     * @param clippingEnabled whether to enable surface clipping
+     * @hide
+     */
+    public void setSurfaceClippingEnabled(boolean clippingEnabled) {
+        mSurfaceView.setEnableSurfaceClipping(clippingEnabled);
+    }
+
+    /**
+     * Sets an area on the contained surface to which it will be clipped
+     * when it is drawn. Setting the value to null will remove the clip bounds
+     * and the surface will draw normally, using its full bounds.
+     *
+     * @param clipBounds The rectangular area, in the local coordinates of
+     * this view, to which future drawing operations will be clipped.
+     * @hide
+     */
+    public void setSurfaceClipBounds(Rect clipBounds) {
+        mSurfaceView.setClipBounds(clipBounds);
+    }
+
+    /**
+     * @hide
+     */
+    public boolean getSurfaceClipBounds(Rect outRect) {
+        return mSurfaceView.getClipBounds(outRect);
+    }
+
+    /**
      * Launch a new activity into this container.
      * <p>Activity resolved by the provided {@link Intent} must have
      * {@link android.R.attr#resizeableActivity} attribute set to {@code true} in order to be
diff --git a/core/java/android/app/AppCompatCallbacks.java b/core/java/android/app/AppCompatCallbacks.java
index 08c97eb..19d158d 100644
--- a/core/java/android/app/AppCompatCallbacks.java
+++ b/core/java/android/app/AppCompatCallbacks.java
@@ -18,7 +18,6 @@
 
 import android.compat.Compatibility;
 import android.os.Process;
-import android.util.Log;
 import android.util.StatsLog;
 
 import com.android.internal.compat.ChangeReporter;
@@ -31,8 +30,6 @@
  * @hide
  */
 public final class AppCompatCallbacks extends Compatibility.Callbacks {
-    private static final String TAG = "Compatibility";
-
     private final long[] mDisabledChanges;
     private final ChangeReporter mChangeReporter;
 
@@ -48,7 +45,8 @@
     private AppCompatCallbacks(long[] disabledChanges) {
         mDisabledChanges = Arrays.copyOf(disabledChanges, disabledChanges.length);
         Arrays.sort(mDisabledChanges);
-        mChangeReporter = new ChangeReporter();
+        mChangeReporter = new ChangeReporter(
+                StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__SOURCE__APP_PROCESS);
     }
 
     protected void reportChange(long changeId) {
@@ -67,10 +65,7 @@
 
     private void reportChange(long changeId, int state) {
         int uid = Process.myUid();
-        //TODO(b/138374585): Implement rate limiting for the logs.
-        Log.d(TAG, ChangeReporter.createLogString(uid, changeId, state));
-        mChangeReporter.reportChange(uid, changeId,
-                state, /* source */StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__SOURCE__APP_PROCESS);
+        mChangeReporter.reportChange(uid, changeId, state);
     }
 
 }
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 563174b..1649e8b 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -853,12 +853,14 @@
     public static final int OP_ACCESS_ACCESSIBILITY = 88;
     /** @hide Read the device identifiers (IMEI / MEID, IMSI, SIM / Build serial) */
     public static final int OP_READ_DEVICE_IDENTIFIERS = 89;
+    /** @hide Read location metadata from media */
+    public static final int OP_ACCESS_MEDIA_LOCATION = 90;
     /** @hide Query all apps on device, regardless of declarations in the calling app manifest */
-    public static final int OP_QUERY_ALL_PACKAGES = 90;
+    public static final int OP_QUERY_ALL_PACKAGES = 91;
 
     /** @hide */
     @UnsupportedAppUsage
-    public static final int _NUM_OP = 91;
+    public static final int _NUM_OP = 92;
 
     /** Access to coarse location information. */
     public static final String OPSTR_COARSE_LOCATION = "android:coarse_location";
@@ -1134,6 +1136,8 @@
     /** @hide Has a legacy (non-isolated) view of storage. */
     @SystemApi @TestApi
     public static final String OPSTR_LEGACY_STORAGE = "android:legacy_storage";
+    /** @hide Read location metadata from media */
+    public static final String OPSTR_ACCESS_MEDIA_LOCATION = "android:access_media_location";
 
     /** @hide Interact with accessibility. */
     @SystemApi
@@ -1180,6 +1184,7 @@
             // Storage
             OP_READ_EXTERNAL_STORAGE,
             OP_WRITE_EXTERNAL_STORAGE,
+            OP_ACCESS_MEDIA_LOCATION,
             // Location
             OP_COARSE_LOCATION,
             OP_FINE_LOCATION,
@@ -1322,6 +1327,7 @@
             OP_LEGACY_STORAGE,                  // LEGACY_STORAGE
             OP_ACCESS_ACCESSIBILITY,            // ACCESS_ACCESSIBILITY
             OP_READ_DEVICE_IDENTIFIERS,         // READ_DEVICE_IDENTIFIERS
+            OP_ACCESS_MEDIA_LOCATION,           // ACCESS_MEDIA_LOCATION
             OP_QUERY_ALL_PACKAGES,              // QUERY_ALL_PACKAGES
     };
 
@@ -1419,6 +1425,7 @@
             OPSTR_LEGACY_STORAGE,
             OPSTR_ACCESS_ACCESSIBILITY,
             OPSTR_READ_DEVICE_IDENTIFIERS,
+            OPSTR_ACCESS_MEDIA_LOCATION,
             OPSTR_QUERY_ALL_PACKAGES,
     };
 
@@ -1517,6 +1524,7 @@
             "LEGACY_STORAGE",
             "ACCESS_ACCESSIBILITY",
             "READ_DEVICE_IDENTIFIERS",
+            "ACCESS_MEDIA_LOCATION",
             "QUERY_ALL_PACKAGES",
     };
 
@@ -1616,6 +1624,7 @@
             null, // no permission for OP_LEGACY_STORAGE
             null, // no permission for OP_ACCESS_ACCESSIBILITY
             null, // no direct permission for OP_READ_DEVICE_IDENTIFIERS
+            Manifest.permission.ACCESS_MEDIA_LOCATION,
             null, // no permission for OP_QUERY_ALL_PACKAGES
     };
 
@@ -1715,6 +1724,7 @@
             null, // LEGACY_STORAGE
             null, // ACCESS_ACCESSIBILITY
             null, // READ_DEVICE_IDENTIFIERS
+            null, // ACCESS_MEDIA_LOCATION
             null, // QUERY_ALL_PACKAGES
     };
 
@@ -1813,6 +1823,7 @@
             false, // LEGACY_STORAGE
             false, // ACCESS_ACCESSIBILITY
             false, // READ_DEVICE_IDENTIFIERS
+            false, // ACCESS_MEDIA_LOCATION
             false, // QUERY_ALL_PACKAGES
     };
 
@@ -1910,6 +1921,7 @@
             AppOpsManager.MODE_DEFAULT, // LEGACY_STORAGE
             AppOpsManager.MODE_ALLOWED, // ACCESS_ACCESSIBILITY
             AppOpsManager.MODE_ERRORED, // READ_DEVICE_IDENTIFIERS
+            AppOpsManager.MODE_ALLOWED, // ALLOW_MEDIA_LOCATION
             AppOpsManager.MODE_DEFAULT, // QUERY_ALL_PACKAGES
     };
 
@@ -2011,6 +2023,7 @@
             false, // LEGACY_STORAGE
             false, // ACCESS_ACCESSIBILITY
             false, // READ_DEVICE_IDENTIFIERS
+            false, // ACCESS_MEDIA_LOCATION
             false, // QUERY_ALL_PACKAGES
     };
 
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index d74399c..86bf20a 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -2414,14 +2414,11 @@
 
     @Override
     public Bundle getSuspendedPackageAppExtras() {
-        final PersistableBundle extras;
         try {
-            extras = mPM.getSuspendedPackageAppExtras(mContext.getOpPackageName(),
-                    getUserId());
+            return mPM.getSuspendedPackageAppExtras(mContext.getOpPackageName(), getUserId());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
-        return extras != null ? new Bundle(extras.deepCopy()) : null;
     }
 
     @Override
@@ -3172,6 +3169,15 @@
     }
 
     @Override
+    public String getSetupWizardPackageName() {
+        try {
+            return mPM.getSetupWizardPackageName();
+        } catch (RemoteException e) {
+            throw e.rethrowAsRuntimeException();
+        }
+    }
+
+    @Override
     public String getIncidentReportApproverPackageName() {
         try {
             return mPM.getIncidentReportApproverPackageName();
diff --git a/core/java/android/app/AsyncNotedAppOp.java b/core/java/android/app/AsyncNotedAppOp.java
index 64f886a..df6533a 100644
--- a/core/java/android/app/AsyncNotedAppOp.java
+++ b/core/java/android/app/AsyncNotedAppOp.java
@@ -238,7 +238,7 @@
             time = 1566503083973L,
             codegenVersion = "1.0.0",
             sourceFile = "frameworks/base/core/java/android/app/AsyncNotedAppOp.java",
-            inputSignatures = "private final @android.annotation.IntRange(from=0L, to=90L) int mOpCode\nprivate final @android.annotation.IntRange(from=0L) int mNotingUid\nprivate final @android.annotation.Nullable java.lang.String mNotingPackageName\nprivate final @android.annotation.NonNull java.lang.String mMessage\nprivate final @android.annotation.IntRange(from=0L) long mTime\npublic @android.annotation.NonNull java.lang.String getOp()\nclass AsyncNotedAppOp extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genAidl=true, genHiddenConstructor=true)")
+            inputSignatures = "private final @android.annotation.IntRange(from=0L, to=91L) int mOpCode\nprivate final @android.annotation.IntRange(from=0L) int mNotingUid\nprivate final @android.annotation.Nullable java.lang.String mNotingPackageName\nprivate final @android.annotation.NonNull java.lang.String mMessage\nprivate final @android.annotation.IntRange(from=0L) long mTime\npublic @android.annotation.NonNull java.lang.String getOp()\nclass AsyncNotedAppOp extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genAidl=true, genHiddenConstructor=true)")
     @Deprecated
     private void __metadata() {}
 
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index ef23d5e..5b211e14 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -741,12 +741,21 @@
     public File getCodeCacheDir() {
         synchronized (mSync) {
             if (mCodeCacheDir == null) {
-                mCodeCacheDir = new File(getDataDir(), "code_cache");
+                mCodeCacheDir = getCodeCacheDirBeforeBind(getDataDir());
             }
             return ensurePrivateCacheDirExists(mCodeCacheDir, XATTR_INODE_CODE_CACHE);
         }
     }
 
+    /**
+     * Helper for getting code-cache dir potentially before application bind.
+     *
+     * @hide
+     */
+    static File getCodeCacheDirBeforeBind(File dataDir) {
+        return new File(dataDir, "code_cache");
+    }
+
     @Override
     public File getExternalCacheDir() {
         // Operates on primary external storage
diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl
index cfa065b..51a64ff 100644
--- a/core/java/android/app/IApplicationThread.aidl
+++ b/core/java/android/app/IApplicationThread.aidl
@@ -137,6 +137,7 @@
             IVoiceInteractor voiceInteractor);
     void handleTrustStorageUpdate();
     void attachAgent(String path);
+    void attachStartupAgents(String dataDir);
     void scheduleApplicationInfoChanged(in ApplicationInfo ai);
     void setNetworkBlockSeq(long procStateSeq);
     void scheduleTransaction(in ClientTransaction transaction);
diff --git a/core/java/android/app/ITaskStackListener.aidl b/core/java/android/app/ITaskStackListener.aidl
index 750020e..0ba1989 100644
--- a/core/java/android/app/ITaskStackListener.aidl
+++ b/core/java/android/app/ITaskStackListener.aidl
@@ -197,4 +197,11 @@
      * Called when any additions or deletions to the recent tasks list have been made.
      */
     void onRecentTaskListUpdated();
+
+    /**
+     * Called when Recent Tasks list is frozen or unfrozen.
+     *
+     * @param frozen if true, Recents Tasks list is currently frozen, false otherwise
+     */
+    void onRecentTaskListFrozenChanged(boolean frozen);
 }
diff --git a/core/java/android/app/KeyguardManager.java b/core/java/android/app/KeyguardManager.java
index 9b667a1..b1565ab 100644
--- a/core/java/android/app/KeyguardManager.java
+++ b/core/java/android/app/KeyguardManager.java
@@ -87,12 +87,6 @@
             "android.app.action.CONFIRM_FRP_CREDENTIAL";
 
     /**
-     * @hide
-     */
-    public static final String EXTRA_BIOMETRIC_PROMPT_BUNDLE =
-            "android.app.extra.BIOMETRIC_PROMPT_BUNDLE";
-
-    /**
      * A CharSequence dialog title to show to the user when used with a
      * {@link #ACTION_CONFIRM_DEVICE_CREDENTIAL}.
      * @hide
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 2f03ed4..efb9f6bb 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -10511,12 +10511,7 @@
         final StandardTemplateParams fillTextsFrom(Builder b) {
             Bundle extras = b.mN.extras;
             this.title = b.processLegacyText(extras.getCharSequence(EXTRA_TITLE));
-
-            CharSequence text = extras.getCharSequence(EXTRA_BIG_TEXT);
-            if (TextUtils.isEmpty(text)) {
-                text = extras.getCharSequence(EXTRA_TEXT);
-            }
-            this.text = b.processLegacyText(text);
+            this.text = b.processLegacyText(extras.getCharSequence(EXTRA_TEXT));
             this.summaryText = extras.getCharSequence(EXTRA_SUB_TEXT);
             return this;
         }
diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java
index 40cb29f..cb9ebac 100644
--- a/core/java/android/app/ResourcesManager.java
+++ b/core/java/android/app/ResourcesManager.java
@@ -20,6 +20,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
@@ -191,6 +192,17 @@
                 }
             }
             Log.i(TAG, "Invalidated " + count + " asset managers that referenced " + path);
+
+            for (int i = mCachedApkAssets.size() - 1; i >= 0; i--) {
+                final ApkKey key = mCachedApkAssets.keyAt(i);
+                if (key.path.equals(path)) {
+                    WeakReference<ApkAssets> apkAssetsRef = mCachedApkAssets.remove(key);
+                    if (apkAssetsRef != null && apkAssetsRef.get() != null) {
+                        apkAssetsRef.get().close();
+                    }
+                    mCachedApkAssets.remove(key);
+                }
+            }
         }
     }
 
@@ -1000,6 +1012,14 @@
         }
     }
 
+    @TestApi
+    public final boolean applyConfigurationToResources(@NonNull Configuration config,
+            @Nullable CompatibilityInfo compat) {
+        synchronized(this) {
+            return applyConfigurationToResourcesLocked(config, compat);
+        }
+    }
+
     public final boolean applyConfigurationToResourcesLocked(@NonNull Configuration config,
                                                              @Nullable CompatibilityInfo compat) {
         try {
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index e4fd566..e81dc1c 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -152,6 +152,7 @@
 import android.os.image.DynamicSystemManager;
 import android.os.image.IDynamicSystemService;
 import android.os.storage.StorageManager;
+import android.os.telephony.TelephonyRegistryManager;
 import android.permission.PermissionControllerManager;
 import android.permission.PermissionManager;
 import android.print.IPrintManager;
@@ -606,6 +607,13 @@
                 return new TelephonyManager(ctx.getOuterContext());
             }});
 
+        registerService(Context.TELEPHONY_REGISTRY_SERVICE, TelephonyRegistryManager.class,
+            new CachedServiceFetcher<TelephonyRegistryManager>() {
+                @Override
+                public TelephonyRegistryManager createService(ContextImpl ctx) {
+                    return new TelephonyRegistryManager();
+                }});
+
         registerService(Context.TELEPHONY_SUBSCRIPTION_SERVICE, SubscriptionManager.class,
                 new CachedServiceFetcher<SubscriptionManager>() {
             @Override
@@ -1335,13 +1343,13 @@
      * @hide
      */
     public static <T> void registerCachedService(String serviceName, Class<T> serviceWrapperClass,
-            BiFunction<ContextImpl, IBinder, T> serviceFetcher) {
+            BiFunction<Context, IBinder, T> serviceFetcher) {
         registerService(serviceName, serviceWrapperClass,
                 new CachedServiceFetcher<T>() {
                     @Override
                     public T createService(ContextImpl ctx) throws ServiceNotFoundException {
                         IBinder b = ServiceManager.getServiceOrThrow(serviceName);
-                        return serviceFetcher.apply(ctx, b);
+                        return serviceFetcher.apply(ctx.getOuterContext(), b);
                     }});
     }
 
diff --git a/core/java/android/app/TEST_MAPPING b/core/java/android/app/TEST_MAPPING
index def1f45..35c7104 100644
--- a/core/java/android/app/TEST_MAPPING
+++ b/core/java/android/app/TEST_MAPPING
@@ -26,6 +26,15 @@
                     "include-filter": "com.android.server.appop"
                 }
             ]
+        },
+        {
+            "file_patterns": ["(/|^)AppOpsManager.java"],
+            "name": "CtsPermission2TestCases",
+            "options": [
+                {
+                    "include-filter": "android.permission2.cts.RuntimePermissionProperties"
+                }
+            ]
         }
     ],
     "postsubmit": [
diff --git a/core/java/android/app/TaskStackListener.java b/core/java/android/app/TaskStackListener.java
index 46045fa..f21aaf3 100644
--- a/core/java/android/app/TaskStackListener.java
+++ b/core/java/android/app/TaskStackListener.java
@@ -190,4 +190,8 @@
     @Override
     public void onRecentTaskListUpdated() throws RemoteException {
     }
+
+    @Override
+    public void onRecentTaskListFrozenChanged(boolean frozen) {
+    }
 }
diff --git a/core/java/android/app/UiAutomation.java b/core/java/android/app/UiAutomation.java
index fd93450..13d566c 100644
--- a/core/java/android/app/UiAutomation.java
+++ b/core/java/android/app/UiAutomation.java
@@ -42,6 +42,7 @@
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.util.Log;
+import android.util.SparseArray;
 import android.view.Display;
 import android.view.InputEvent;
 import android.view.KeyEvent;
@@ -535,7 +536,7 @@
     }
 
     /**
-     * Gets the windows on the screen. This method returns only the windows
+     * Gets the windows on the screen of the default display. This method returns only the windows
      * that a sighted user can interact with, as opposed to all windows.
      * For example, if there is a modal dialog shown and the user cannot touch
      * anything behind it, then only the modal window will be reported
@@ -562,6 +563,35 @@
     }
 
     /**
+     * Gets the windows on the screen of all displays. This method returns only the windows
+     * that a sighted user can interact with, as opposed to all windows.
+     * For example, if there is a modal dialog shown and the user cannot touch
+     * anything behind it, then only the modal window will be reported
+     * (assuming it is the top one). For convenience the returned windows
+     * are ordered in a descending layer order, which is the windows that
+     * are higher in the Z-order are reported first.
+     * <p>
+     * <strong>Note:</strong> In order to access the windows you have to opt-in
+     * to retrieve the interactive windows by setting the
+     * {@link AccessibilityServiceInfo#FLAG_RETRIEVE_INTERACTIVE_WINDOWS} flag.
+     * </p>
+     *
+     * @return The windows of all displays if there are windows and the service is can retrieve
+     *         them, otherwise an empty list. The key of SparseArray is display ID.
+     */
+    @NonNull
+    public SparseArray<List<AccessibilityWindowInfo>> getWindowsOnAllDisplays() {
+        final int connectionId;
+        synchronized (mLock) {
+            throwIfNotConnectedLocked();
+            connectionId = mConnectionId;
+        }
+        // Calling out without a lock held.
+        return AccessibilityInteractionClient.getInstance()
+                .getWindowsOnAllDisplays(connectionId);
+    }
+
+    /**
      * Gets the root {@link AccessibilityNodeInfo} in the active window.
      *
      * @return The root info.
diff --git a/core/java/android/app/admin/DelegatedAdminReceiver.java b/core/java/android/app/admin/DelegatedAdminReceiver.java
index f66de8d..25b8eab 100644
--- a/core/java/android/app/admin/DelegatedAdminReceiver.java
+++ b/core/java/android/app/admin/DelegatedAdminReceiver.java
@@ -63,6 +63,10 @@
      * Allows this receiver to select the alias for a private key and certificate pair for
      * authentication.  If this method returns null, the default {@link android.app.Activity} will
      * be shown that lets the user pick a private key and certificate pair.
+     * If this method returns {@link KeyChain#KEY_ALIAS_SELECTION_DENIED},
+     * the default {@link android.app.Activity} will not be shown and the user will not be allowed
+     * to pick anything. And the app, that called {@link KeyChain#choosePrivateKeyAlias}, will
+     * receive {@code null} back.
      *
      * <p> This callback is only applicable if the delegated app has
      * {@link DevicePolicyManager#DELEGATION_CERT_SELECTION} capability. Additionally, it must
diff --git a/core/java/android/app/admin/DeviceAdminReceiver.java b/core/java/android/app/admin/DeviceAdminReceiver.java
index 0c500da..d175a66 100644
--- a/core/java/android/app/admin/DeviceAdminReceiver.java
+++ b/core/java/android/app/admin/DeviceAdminReceiver.java
@@ -791,6 +791,10 @@
      * Allows this receiver to select the alias for a private key and certificate pair for
      * authentication. If this method returns null, the default {@link android.app.Activity} will be
      * shown that lets the user pick a private key and certificate pair.
+     * If this method returns {@link KeyChain#KEY_ALIAS_SELECTION_DENIED},
+     * the default {@link android.app.Activity} will not be shown and the user will not be allowed
+     * to pick anything. And the app, that called {@link KeyChain#choosePrivateKeyAlias}, will
+     * receive {@code null} back.
      *
      * @param context The running context as per {@link #onReceive}.
      * @param intent The received intent as per {@link #onReceive}.
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index a136bbd..c3c383c 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -1551,7 +1551,8 @@
      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
      * {@link #EXTRA_DELEGATION_SCOPES} key.
      *
-     * <p class=”note”> Note: This is a protected intent that can only be sent by the system.</p>
+     * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
+     * system.</p>
      */
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
@@ -2078,7 +2079,8 @@
         ID_TYPE_BASE_INFO,
         ID_TYPE_SERIAL,
         ID_TYPE_IMEI,
-        ID_TYPE_MEID
+        ID_TYPE_MEID,
+        ID_TYPE_INDIVIDUAL_ATTESTATION
     })
     public @interface AttestationIdType {}
 
@@ -2113,6 +2115,14 @@
     public static final int ID_TYPE_MEID = 8;
 
     /**
+     * Specifies that the device should attest using an individual attestation certificate.
+     * For use with {@link #generateKeyPair}.
+     *
+     * @see #generateKeyPair
+     */
+    public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
+
+    /**
      * Service-specific error code for {@link #generateKeyPair}:
      * Indicates the call has failed due to StrongBox unavailability.
      * @hide
@@ -2531,14 +2541,13 @@
     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
 
     /**
-     * Constant for {@link #setPasswordQuality}: the user must have entered a
-     * password containing at least a letter, a numerical digit and a special
-     * symbol, by default. With this password quality, passwords can be
-     * restricted to contain various sets of characters, like at least an
-     * uppercase letter, etc. These are specified using various methods,
-     * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
-     * that quality constants are ordered so that higher values are more
-     * restrictive.
+     * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
+     * characters of various types the password should contain to satisfy the policy. The admin
+     * should set these requirements via {@link #setPasswordMinimumLetters},
+     * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
+     * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
+     * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
+     * Note that quality constants are ordered so that higher values are more restrictive.
      */
     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
 
@@ -2610,6 +2619,7 @@
      *
      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
+     *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
@@ -2668,7 +2678,10 @@
      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
-     * {@link #setPasswordQuality}.
+     * {@link #setPasswordQuality}. If an app targeting SDK level
+     * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
+     * password quality to one of these values first, this method will throw
+     * {@link IllegalStateException}.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password is always treated as empty.
@@ -2683,9 +2696,12 @@
      *
      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
      * @param length The new desired minimum password length. A value of 0 means there is no
-     *            restriction.
+     *     restriction.
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
-     *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     *     does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     * @throws IllegalStateException if the calling app is targeting SDK level
+     *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
+     *     quality requirement prior to calling this method.
      */
     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
         if (mService != null) {
@@ -2737,7 +2753,10 @@
      * place immediately. To prompt the user for a new password, use
      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
      * setting this value. This constraint is only imposed if the administrator has also requested
-     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
+     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
+     * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
+     * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
+     * {@link IllegalStateException}. The default value is 0.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password is always treated as empty.
@@ -2755,6 +2774,9 @@
      *            A value of 0 means there is no restriction.
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     * @throws IllegalStateException if the calling app is targeting SDK level
+     *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
+     *     quality requirement prior to calling this method.
      */
     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
         if (mService != null) {
@@ -2813,7 +2835,10 @@
      * place immediately. To prompt the user for a new password, use
      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
      * setting this value. This constraint is only imposed if the administrator has also requested
-     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
+     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
+     * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
+     * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
+     * {@link IllegalStateException}. The default value is 0.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password is always treated as empty.
@@ -2831,6 +2856,9 @@
      *            A value of 0 means there is no restriction.
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     * @throws IllegalStateException if the calling app is targeting SDK level
+     *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
+     *     quality requirement prior to calling this method.
      */
     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
         if (mService != null) {
@@ -2889,7 +2917,10 @@
      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
-     * {@link #setPasswordQuality}. The default value is 1.
+     * {@link #setPasswordQuality}. If an app targeting SDK level
+     * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
+     * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
+     * {@link IllegalStateException}. The default value is 1.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password is always treated as empty.
@@ -2907,6 +2938,9 @@
      *            0 means there is no restriction.
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     * @throws IllegalStateException if the calling app is targeting SDK level
+     *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
+     *     quality requirement prior to calling this method.
      */
     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
         if (mService != null) {
@@ -2964,7 +2998,10 @@
      * place immediately. To prompt the user for a new password, use
      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
      * setting this value. This constraint is only imposed if the administrator has also requested
-     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
+     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
+     * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
+     * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
+     * {@link IllegalStateException}. The default value is 1.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password is always treated as empty.
@@ -2982,6 +3019,9 @@
      *            value of 0 means there is no restriction.
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     * @throws IllegalStateException if the calling app is targeting SDK level
+     *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
+     *     quality requirement prior to calling this method.
      */
     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
         if (mService != null) {
@@ -3039,7 +3079,10 @@
      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
-     * {@link #setPasswordQuality}. The default value is 1.
+     * {@link #setPasswordQuality}. If an app targeting SDK level
+     * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
+     * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
+     * {@link IllegalStateException}. The default value is 1.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password is always treated as empty.
@@ -3057,6 +3100,9 @@
      *            0 means there is no restriction.
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     * @throws IllegalStateException if the calling app is targeting SDK level
+     *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
+     *     quality requirement prior to calling this method.
      */
     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
         if (mService != null) {
@@ -3113,7 +3159,10 @@
      * one, so the change does not take place immediately. To prompt the user for a new password,
      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
      * setting this value. This constraint is only imposed if the administrator has also requested
-     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
+     * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
+     * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
+     * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
+     * {@link IllegalStateException}. The default value is 0.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password is always treated as empty.
@@ -3131,6 +3180,9 @@
      *            0 means there is no restriction.
      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
+     * @throws IllegalStateException if the calling app is targeting SDK level
+     *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
+     *     quality requirement prior to calling this method.
      */
     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
         if (mService != null) {
@@ -3186,10 +3238,7 @@
      * same as any password in the history. Note that the current password will remain until the
      * user has set a new one, so the change does not take place immediately. To prompt the user for
      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
-     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
-     * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
-     * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
-     * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
+     * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
      * <p>
      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
      * password history length is always 0.
@@ -4894,24 +4943,47 @@
      * have been given to access the key and certificates associated with this alias will be
      * revoked.
      *
+     * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
+     * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
+     * {@code idAttestationFlags} parameter, it is possible to request the device's unique
+     * identity to be included in the attestation record.
+     *
+     * <p>Specific identifiers can be included in the attestation record, and an individual
+     * attestation certificate can be used to sign the attestation record. To find out if the device
+     * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
+     * {@link #isUniqueDeviceAttestationSupported()}.
+     *
+     * <p>Device owner, profile owner and their delegated certificate installer can use
+     * {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
+     * including manufacturer, model, brand, device and product in the attestation record.
+     * Only device owner and their delegated certificate installer can use
+     * {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} to request
+     * unique device identifiers to be attested (the serial number, IMEI and MEID correspondingly),
+     * if supported by the device (see {@link #isDeviceIdAttestationSupported()}).
+     * Additionally, device owner and their delegated certificate installer can also request the
+     * attestation record to be signed using an individual attestation certificate by specifying
+     * the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} flag (if supported by the device, see
+     * {@link #isUniqueDeviceAttestationSupported()}).
+     * <p>
+     * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
+     * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
+     * <p>
+     * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
+     * key generation is done in StrongBox.
+     *
      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
      *            {@code null} if calling from a delegated certificate installer.
      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
      * @param keySpec Specification of the key to generate, see
      * {@link java.security.KeyPairGenerator}.
-     * @param idAttestationFlags A bitmask of all the identifiers that should be included in the
+     * @param idAttestationFlags A bitmask of the identifiers that should be included in the
      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
-     *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), or {@code 0} if no device
-     *        identification is required in the attestation record.
-     *        Device owner, profile owner and their delegated certificate installer can use
-     *        {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
-     *        including manufacturer, model, brand, device and product in the attestation record.
-     *        Only device owner and their delegated certificate installer can use
-     *        {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} to request
-     *        unique device identifiers to be attested.
+     *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
+     *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
+     *        using an individual attestation certificate.
      *        <p>
-     *        If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
-     *        is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
+     *        {@code 0} should be passed in if no device identification is required in the
+     *        attestation record and the batch attestation certificate should be used.
      *        <p>
      *        If any flag is specified, then an attestation challenge must be included in the
      *        {@code keySpec}.
@@ -5053,7 +5125,8 @@
 
     /**
      * Returns {@code true} if the device supports attestation of device identifiers in addition
-     * to key attestation.
+     * to key attestation. See
+     * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
      * @return {@code true} if Device ID attestation is supported.
      */
     public boolean isDeviceIdAttestationSupported() {
@@ -5062,6 +5135,20 @@
     }
 
     /**
+     * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
+     * with an individual attestation certificate and can sign attestation records using it (as
+     * attestation using an individual attestation certificate is a feature only Keymaster
+     * implementations with StrongBox security level can implement).
+     * For use prior to calling
+     * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
+     * @return {@code true} if individual attestation is supported.
+     */
+    public boolean isUniqueDeviceAttestationSupported() {
+        PackageManager pm = mContext.getPackageManager();
+        return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
+    }
+
+    /**
      * Called by a device or profile owner, or delegated certificate installer, to associate
      * certificates with a key pair that was generated using {@link #generateKeyPair}, and
      * set whether the key is available for the user to choose in the certificate selection
diff --git a/core/java/android/app/admin/DevicePolicyManagerInternal.java b/core/java/android/app/admin/DevicePolicyManagerInternal.java
index 8765760..713126e 100644
--- a/core/java/android/app/admin/DevicePolicyManagerInternal.java
+++ b/core/java/android/app/admin/DevicePolicyManagerInternal.java
@@ -24,6 +24,10 @@
 /**
  * Device policy manager local system service interface.
  *
+ * Maintenance note: if you need to expose information from DPMS to lower level services such as
+ * PM/UM/AM/etc, then exposing it from DevicePolicyManagerInternal is not safe because it may cause
+ * lock order inversion. Consider using {@link DevicePolicyCache} instead.
+ *
  * @hide Only for use within the system server.
  */
 public abstract class DevicePolicyManagerInternal {
@@ -81,6 +85,16 @@
     public abstract boolean isActiveAdminWithPolicy(int uid, int reqPolicy);
 
     /**
+     * Checks if an app with given uid is the active supervision admin.
+     *
+     * <p>This takes the DPMS lock. DO NOT call from PM/UM/AM with their lock held.
+     *
+     * @param uid App uid.
+     * @return true if the uid is the active supervision app.
+     */
+    public abstract boolean isActiveSupervisionApp(int uid);
+
+    /**
      * Creates an intent to show the admin support dialog to say that an action is disallowed by
      * the device/profile owner.
      *
@@ -153,4 +167,11 @@
      * Do not call it directly. Use {@link DevicePolicyCache#getInstance()} instead.
      */
     protected abstract DevicePolicyCache getDevicePolicyCache();
+
+    /**
+     * @return cached version of device state related to DPM that can be accessed without risking
+     * deadlocks.
+     * Do not call it directly. Use {@link DevicePolicyCache#getInstance()} instead.
+     */
+    protected abstract DeviceStateCache getDeviceStateCache();
 }
diff --git a/core/java/android/app/admin/DeviceStateCache.java b/core/java/android/app/admin/DeviceStateCache.java
new file mode 100644
index 0000000..7619aa2
--- /dev/null
+++ b/core/java/android/app/admin/DeviceStateCache.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2019 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.app.admin;
+
+import com.android.server.LocalServices;
+
+/**
+ * Stores a copy of the set of device state maintained by {@link DevicePolicyManager} which
+ * is not directly related to admin policies. This lives in its own class so that the state
+ * can be accessed from any place without risking dead locks.
+ *
+ * @hide
+ */
+public abstract class DeviceStateCache {
+    protected DeviceStateCache() {
+    }
+
+    /**
+     * @return the instance.
+     */
+    public static DeviceStateCache getInstance() {
+        final DevicePolicyManagerInternal dpmi =
+                LocalServices.getService(DevicePolicyManagerInternal.class);
+        return (dpmi != null) ? dpmi.getDeviceStateCache() : EmptyDeviceStateCache.INSTANCE;
+    }
+
+    /**
+     * See {@link DevicePolicyManager#isDeviceProvisioned}
+     */
+    public abstract boolean isDeviceProvisioned();
+
+    /**
+     * Empty implementation.
+     */
+    private static class EmptyDeviceStateCache extends DeviceStateCache {
+        private static final EmptyDeviceStateCache INSTANCE = new EmptyDeviceStateCache();
+
+        @Override
+        public boolean isDeviceProvisioned() {
+            return false;
+        }
+    }
+}
diff --git a/core/java/android/app/assist/AssistStructure.java b/core/java/android/app/assist/AssistStructure.java
index f9e710e..80c5b17 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -684,8 +684,9 @@
         static final int FLAGS_HAS_EXTRAS = 0x00400000;
         static final int FLAGS_HAS_ID = 0x00200000;
         static final int FLAGS_HAS_CHILDREN = 0x00100000;
-        static final int FLAGS_HAS_URL = 0x00080000;
+        static final int FLAGS_HAS_URL_DOMAIN = 0x00080000;
         static final int FLAGS_HAS_INPUT_TYPE = 0x00040000;
+        static final int FLAGS_HAS_URL_SCHEME = 0x00020000;
         static final int FLAGS_HAS_LOCALE_LIST = 0x00010000;
         static final int FLAGS_ALL_CONTROL = 0xfff00000;
 
@@ -829,8 +830,10 @@
             if ((flags&FLAGS_HAS_INPUT_TYPE) != 0) {
                 mInputType = in.readInt();
             }
-            if ((flags&FLAGS_HAS_URL) != 0) {
+            if ((flags&FLAGS_HAS_URL_SCHEME) != 0) {
                 mWebScheme = in.readString();
+            }
+            if ((flags&FLAGS_HAS_URL_DOMAIN) != 0) {
                 mWebDomain = in.readString();
             }
             if ((flags&FLAGS_HAS_LOCALE_LIST) != 0) {
@@ -891,8 +894,11 @@
             if (mInputType != 0) {
                 flags |= FLAGS_HAS_INPUT_TYPE;
             }
-            if (mWebScheme != null || mWebDomain != null) {
-                flags |= FLAGS_HAS_URL;
+            if (mWebScheme != null) {
+                flags |= FLAGS_HAS_URL_SCHEME;
+            }
+            if (mWebDomain != null) {
+                flags |= FLAGS_HAS_URL_DOMAIN;
             }
             if (mLocaleList != null) {
                 flags |= FLAGS_HAS_LOCALE_LIST;
@@ -1055,8 +1061,10 @@
             if ((flags&FLAGS_HAS_INPUT_TYPE) != 0) {
                 out.writeInt(mInputType);
             }
-            if ((flags&FLAGS_HAS_URL) != 0) {
+            if ((flags & FLAGS_HAS_URL_SCHEME) != 0) {
                 out.writeString(mWebScheme);
+            }
+            if ((flags&FLAGS_HAS_URL_DOMAIN) != 0) {
                 out.writeString(mWebDomain);
             }
             if ((flags&FLAGS_HAS_LOCALE_LIST) != 0) {
@@ -1431,13 +1439,18 @@
         public void setWebDomain(@Nullable String domain) {
             if (domain == null) return;
 
-            final Uri uri = Uri.parse(domain);
+            Uri uri = Uri.parse(domain);
             if (uri == null) {
                 // Cannot log domain because it could contain PII;
                 Log.w(TAG, "Failed to parse web domain");
                 return;
             }
+
             mWebScheme = uri.getScheme();
+            if (mWebScheme == null) {
+                uri = Uri.parse("http://" + domain);
+            }
+
             mWebDomain = uri.getHost();
         }
 
diff --git a/core/java/android/app/role/IRoleManager.aidl b/core/java/android/app/role/IRoleManager.aidl
index d8cea28..6d790b3 100644
--- a/core/java/android/app/role/IRoleManager.aidl
+++ b/core/java/android/app/role/IRoleManager.aidl
@@ -19,7 +19,6 @@
 import android.app.role.IOnRoleHoldersChangedListener;
 import android.os.Bundle;
 import android.os.RemoteCallback;
-import android.telephony.IFinancialSmsCallback;
 
 /**
  * @hide
@@ -55,9 +54,4 @@
     List<String> getHeldRolesFromController(in String packageName);
 
     String getDefaultSmsPackage(int userId);
-
-    /**
-     * Get filtered SMS messages for financial app.
-     */
-    void getSmsMessagesForFinancialApp(in String callingPkg, in Bundle params, in IFinancialSmsCallback callback);
 }
diff --git a/core/java/android/app/usage/AppStandbyInfo.java b/core/java/android/app/usage/AppStandbyInfo.java
index ebdbf83..c283702 100644
--- a/core/java/android/app/usage/AppStandbyInfo.java
+++ b/core/java/android/app/usage/AppStandbyInfo.java
@@ -22,6 +22,10 @@
 /**
  * A pair of {package, bucket} to denote the app standby bucket for a given package.
  * Used as a vehicle of data across the binder IPC.
+ *
+ * Note we're not moving this class to the jobscheduler apex, because it's consumed by
+ * UsageStatsManager, which is not updatable anyway, so making this updatable isn't really
+ * beneficial.
  * @hide
  */
 public final class AppStandbyInfo implements Parcelable {
diff --git a/core/java/android/app/usage/UsageStatsManager.java b/core/java/android/app/usage/UsageStatsManager.java
index 656f474..1f13a1e 100644
--- a/core/java/android/app/usage/UsageStatsManager.java
+++ b/core/java/android/app/usage/UsageStatsManager.java
@@ -801,8 +801,8 @@
      *                       {@link #EXTRA_TIME_USED}. Cannot be {@code null} unless the observer is
      *                       being registered with a {@code timeUsed} equal to or greater than
      *                       {@code timeLimit}.
-     * @throws SecurityException if the caller doesn't have both SUSPEND_APPS and OBSERVE_APP_USAGE
-     *                           permissions.
+     * @throws SecurityException if the caller is neither the active supervision app nor does it
+     *                           have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
      * @hide
      */
     @SystemApi
@@ -827,8 +827,8 @@
      * an observer that was already unregistered or never registered will have no effect.
      *
      * @param observerId The id of the observer that was previously registered.
-     * @throws SecurityException if the caller doesn't have both SUSPEND_APPS and OBSERVE_APP_USAGE
-     *                           permissions.
+     * @throws SecurityException if the caller is neither the active supervision app nor does it
+     *                         have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
      * @hide
      */
     @SystemApi
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index 1f48393..7c279fe 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -265,6 +265,7 @@
      * @see #QUERY_ARG_SORT_COLUMNS
      * @see #QUERY_ARG_SORT_DIRECTION
      * @see #QUERY_ARG_SORT_COLLATION
+     * @see #QUERY_ARG_SORT_LOCALE
      */
     public static final String QUERY_ARG_SQL_SELECTION = "android:query-arg-sql-selection";
 
@@ -282,6 +283,7 @@
      * @see #QUERY_ARG_SORT_COLUMNS
      * @see #QUERY_ARG_SORT_DIRECTION
      * @see #QUERY_ARG_SORT_COLLATION
+     * @see #QUERY_ARG_SORT_LOCALE
      */
     public static final String QUERY_ARG_SQL_SELECTION_ARGS =
             "android:query-arg-sql-selection-args";
@@ -297,6 +299,7 @@
      * @see #QUERY_ARG_SORT_COLUMNS
      * @see #QUERY_ARG_SORT_DIRECTION
      * @see #QUERY_ARG_SORT_COLLATION
+     * @see #QUERY_ARG_SORT_LOCALE
      */
     public static final String QUERY_ARG_SQL_SORT_ORDER = "android:query-arg-sql-sort-order";
 
@@ -351,20 +354,22 @@
 
     /**
      * Allows client to specify a hint to the provider declaring which collation
-     * to use when sorting text values.
-     *
-     * <p>Providers may support custom collators. When specifying a custom collator
+     * to use when sorting values.
+     * <p>
+     * Providers may support custom collators. When specifying a custom collator
      * the value is determined by the Provider.
-     *
-     * <li>{@link ContentProvider} implementations: When preparing data in
-     * {@link ContentProvider#query(Uri, String[], Bundle, CancellationSignal)}, if sort collation
-     * is reflected in the returned Cursor, it is  strongly recommended that
-     * {@link #QUERY_ARG_SORT_COLLATION} then be included in the array of honored arguments
-     * reflected in {@link Cursor} extras {@link Bundle} under {@link #EXTRA_HONORED_ARGS}.
-     *
-     * <li>When querying a provider, where no QUERY_ARG_SQL* otherwise exists in the
-     * arguments {@link Bundle}, the Content framework will attempt to synthesize
-     * a QUERY_ARG_SQL* argument using the corresponding QUERY_ARG_SORT* values.
+     * <p>
+     * {@link ContentProvider} implementations: When preparing data in
+     * {@link ContentProvider#query(Uri, String[], Bundle, CancellationSignal)},
+     * if sort collation is reflected in the returned Cursor, it is strongly
+     * recommended that {@link #QUERY_ARG_SORT_COLLATION} then be included in
+     * the array of honored arguments reflected in {@link Cursor} extras
+     * {@link Bundle} under {@link #EXTRA_HONORED_ARGS}.
+     * <p>
+     * When querying a provider, where no QUERY_ARG_SQL* otherwise exists in the
+     * arguments {@link Bundle}, the Content framework will attempt to
+     * synthesize a QUERY_ARG_SQL* argument using the corresponding
+     * QUERY_ARG_SORT* values.
      *
      * @see java.text.Collator#PRIMARY
      * @see java.text.Collator#SECONDARY
@@ -374,6 +379,28 @@
     public static final String QUERY_ARG_SORT_COLLATION = "android:query-arg-sort-collation";
 
     /**
+     * Allows client to specify a hint to the provider declaring which locale to
+     * use when sorting values.
+     * <p>
+     * The value is defined as a RFC 3066 locale ID followed by an optional
+     * keyword list, which is the locale format used to configure ICU through
+     * classes like {@link android.icu.util.ULocale}. This supports requesting
+     * advanced sorting options, such as {@code de@collation=phonebook},
+     * {@code zh@collation=pinyin}, etc.
+     * <p>
+     * {@link ContentProvider} implementations: When preparing data in
+     * {@link ContentProvider#query(Uri, String[], Bundle, CancellationSignal)},
+     * if sort locale is reflected in the returned Cursor, it is strongly
+     * recommended that {@link #QUERY_ARG_SORT_LOCALE} then be included in the
+     * array of honored arguments reflected in {@link Cursor} extras
+     * {@link Bundle} under {@link #EXTRA_HONORED_ARGS}.
+     *
+     * @see java.util.Locale#Locale(String)
+     * @see android.icu.util.ULocale#ULocale(String)
+     */
+    public static final String QUERY_ARG_SORT_LOCALE = "android:query-arg-sort-locale";
+
+    /**
      * Allows provider to report back to client which query keys are honored in a Cursor.
      *
      * <p>Key identifying a {@code String[]} containing all QUERY_ARG_SORT* arguments
@@ -386,6 +413,7 @@
      * @see #QUERY_ARG_SORT_COLUMNS
      * @see #QUERY_ARG_SORT_DIRECTION
      * @see #QUERY_ARG_SORT_COLLATION
+     * @see #QUERY_ARG_SORT_LOCALE
      */
     public static final String EXTRA_HONORED_ARGS = "android.content.extra.HONORED_ARGS";
 
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index b612f1c..08817e0 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -3301,7 +3301,7 @@
      *  <dt> {@link #VIBRATOR_SERVICE} ("vibrator")
      *  <dd> A {@link android.os.Vibrator} for interacting with the vibrator
      *  hardware.
-     *  <dt> {@link #CONNECTIVITY_SERVICE} ("connection")
+     *  <dt> {@link #CONNECTIVITY_SERVICE} ("connectivity")
      *  <dd> A {@link android.net.ConnectivityManager ConnectivityManager} for
      *  handling management of network connections.
      *  <dt> {@link #IPSEC_SERVICE} ("ipsec")
@@ -4708,6 +4708,14 @@
     public static final String DYNAMIC_SYSTEM_SERVICE = "dynamic_system";
 
     /**
+     * Use with {@link #getSystemService(String)} to retrieve an
+     * {@link android.os.telephony.TelephonyRegistryManager}.
+     * @hide
+     */
+    @SystemApi
+    public static final String TELEPHONY_REGISTRY_SERVICE = "telephony_registry";
+
+    /**
      * Determine whether the given permission is allowed for a particular
      * process and user ID running in the system.
      *
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 3418b7b..efb1c6a 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -2025,17 +2025,6 @@
     public static final String EXTRA_RESULT_NEEDED = "android.intent.extra.RESULT_NEEDED";
 
     /**
-     * Intent extra: A {@link Bundle} of extras supplied for the launcher when any packages on
-     * device are suspended. Will be sent with {@link #ACTION_PACKAGES_SUSPENDED}.
-     *
-     * @see PackageManager#isPackageSuspended()
-     * @see #ACTION_PACKAGES_SUSPENDED
-     *
-     * @hide
-     */
-    public static final String EXTRA_LAUNCHER_EXTRAS = "android.intent.extra.LAUNCHER_EXTRAS";
-
-    /**
      * Intent extra: ID of the shortcut used to send the share intent. Will be sent with
      * {@link #ACTION_SEND}.
      *
@@ -4665,6 +4654,59 @@
      */
     @SdkConstant(SdkConstantType.INTENT_CATEGORY)
     public static final String CATEGORY_VR_HOME = "android.intent.category.VR_HOME";
+
+    /**
+     * The accessibility shortcut is a global gesture for users with disabilities to trigger an
+     * important for them accessibility feature to help developers determine whether they want to
+     * make their activity a shortcut target.
+     * <p>
+     * An activity of interest to users with accessibility needs may request to be the target of
+     * the accessibility shortcut. It handles intent {@link #ACTION_MAIN} with this category,
+     * which will be dispatched by the system when the user activates the shortcut when it is
+     * configured to point at this target.
+     * </p>
+     * <p>
+     * An activity declared itself to be a target of the shortcut in AndroidManifest.xml. It must
+     * also do two things:
+     * <ul>
+     *     <ol>
+     *         Specify that it handles the <code>android.intent.action.MAIN</code>
+     *         {@link android.content.Intent}
+     *         with category <code>android.intent.category.ACCESSIBILITY_SHORTCUT_TARGET</code>.
+     *     </ol>
+     *     <ol>
+     *         Provide a meta-data entry <code>android.accessibilityshortcut.target</code> in the
+     *         manifest when declaring the activity.
+     *     </ol>
+     * </ul>
+     * If either of these items is missing, the system will ignore the accessibility shortcut
+     * target. Following is an example declaration:
+     * </p>
+     * <pre>
+     * &lt;activity android:name=".MainActivity"
+     * . . .
+     *   &lt;intent-filter&gt;
+     *       &lt;action android:name="android.intent.action.MAIN" /&gt;
+     *       &lt;category android:name="android.intent.category.ACCESSIBILITY_SHORTCUT_TARGET" /&gt;
+     *   &lt;/intent-filter&gt;
+     *   &lt;meta-data android:name="android.accessibilityshortcut.target"
+     *                   android:resource="@xml/accessibilityshortcut" /&gt;
+     * &lt;/activity&gt;
+     * </pre>
+     * <p> This is a sample XML file configuring a accessibility shortcut target: </p>
+     * <pre>
+     * &lt;accessibility-shortcut-target
+     *     android:description="@string/shortcut_target_description"
+     *     android:summary="@string/shortcut_target_summary" /&gt;
+     * </pre>
+     * <p>
+     * Both description and summary are necessary. The system will ignore the accessibility
+     * shortcut target if they are missing.
+     * </p>
+     */
+    @SdkConstant(SdkConstantType.INTENT_CATEGORY)
+    public static final String CATEGORY_ACCESSIBILITY_SHORTCUT_TARGET =
+            "android.intent.category.ACCESSIBILITY_SHORTCUT_TARGET";
     // ---------------------------------------------------------------------
     // ---------------------------------------------------------------------
     // Application launch intent categories (see addCategory()).
@@ -10004,7 +10046,10 @@
         if (!Objects.equals(this.mData, other.mData)) return false;
         if (!Objects.equals(this.mType, other.mType)) return false;
         if (!Objects.equals(this.mIdentifier, other.mIdentifier)) return false;
-        if (!Objects.equals(this.mPackage, other.mPackage)) return false;
+        if (!(this.hasPackageEquivalentComponent() && other.hasPackageEquivalentComponent())
+                && !Objects.equals(this.mPackage, other.mPackage)) {
+            return false;
+        }
         if (!Objects.equals(this.mComponent, other.mComponent)) return false;
         if (!Objects.equals(this.mCategories, other.mCategories)) return false;
 
@@ -10012,6 +10057,15 @@
     }
 
     /**
+     * Return {@code true} if the component name is not null and is in the same package that this
+     * intent limited to. otherwise return {@code false}.
+     */
+    private boolean hasPackageEquivalentComponent() {
+        return mComponent != null
+            && (mPackage == null || mPackage.equals(mComponent.getPackageName()));
+    }
+
+    /**
      * Generate hash code that matches semantics of filterEquals().
      *
      * @return Returns the hash value of the action, data, type, class, and
diff --git a/core/java/android/content/PermissionChecker.java b/core/java/android/content/PermissionChecker.java
index e24512a..c3daad1 100644
--- a/core/java/android/content/PermissionChecker.java
+++ b/core/java/android/content/PermissionChecker.java
@@ -16,8 +16,6 @@
 
 package android.content;
 
-import static android.app.AppOpsManager.strOpToOp;
-
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -52,6 +50,19 @@
  * permission model for which the user had disabled the "permission"
  * which is achieved by disallowing the corresponding app op.
  * </p>
+ * <p>
+ * This class has two types of methods and you should be careful which
+ * type to call based on whether permission protected data is being
+ * passed to the app or you are just checking whether the app holds a
+ * permission. The reason is that a permission check requires checking
+ * the runtime permission and if it is granted checking the corresponding
+ * app op as for apps not supporting the runtime mode we never revoke
+ * permissions but disable app ops. Since there are two types of app op
+ * checks, one that does not leave a record an action was performed and
+ * another the does, one needs to call the preflight flavor of the checks
+ * named xxxForPreflight only if no private data is being delivered but
+ * a permission check is what is needed and the xxxForDataDelivery where
+ * the permission check is right before private data delivery.
  *
  * @hide
  */
@@ -65,6 +76,9 @@
     /** Permission result: The permission is denied because the app op is not allowed. */
     public static final int PERMISSION_DENIED_APP_OP =  PackageManager.PERMISSION_DENIED  - 1;
 
+    /** Constant when the PID for which we check permissions is unknown. */
+    public static final int PID_UNKNOWN = -1;
+
     /** @hide */
     @IntDef({PERMISSION_GRANTED,
             PERMISSION_DENIED,
@@ -77,33 +91,297 @@
     }
 
     /**
-     * @deprecated Use {@link #checkPermission(Context, String, int, int, String, String)} instead
+     * Checks whether a given package in a UID and PID has a given permission
+     * and whether the app op that corresponds to this permission is allowed.
+     *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * point where you will deliver the permission protected data to clients.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use {@link #checkPermissionForPreflight(Context, String, int, int, String)}
+     * to determine if the app has or may have location permission (if app has only foreground
+     * location the grant state depends on the app's fg/gb state) and this check will not
+     * leave a trace that permission protected data was delivered. When you are about to
+     * deliver the location data to a registered listener you should use this method which
+     * will evaluate the permission access based on the current fg/bg state of the app and
+     * leave a record that the data was accessed.
+     *
+     * @param context Context for accessing resources.
+     * @param permission The permission to check.
+     * @param pid The process id for which to check. Use {@link #PID_UNKNOWN} if the PID
+     *    is not known.
+     * @param uid The uid for which to check.
+     * @param packageName The package name for which to check. If null the
+     *     the first package for the calling UID will be used.
+     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
+     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     * @param message A message describing the reason the permission was checked
+     *
+     * @see #checkPermissionForPreflight(Context, String, int, int, String)
      */
-    @Deprecated
     @PermissionResult
-    public static int checkPermission(@NonNull Context context, @NonNull String permission,
-            int pid, int uid, @Nullable String packageName) {
-        return checkPermission(context, permission, pid, uid, packageName, null);
+    public static int checkPermissionForDataDelivery(@NonNull Context context,
+            @NonNull String permission, int pid, int uid, @Nullable String packageName,
+            @Nullable String message) {
+        return checkPermissionCommon(context, permission, pid, uid, packageName, message,
+                true /*forDataDelivery*/);
     }
 
     /**
      * Checks whether a given package in a UID and PID has a given permission
      * and whether the app op that corresponds to this permission is allowed.
      *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * preflight point where you will not deliver the permission protected data
+     * to clients but schedule permission data delivery, apps register listeners,
+     * etc.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use this method to determine if the app has or may have location
+     * permission (if app has only foreground location the grant state depends on the app's
+     * fg/gb state) and this check will not leave a trace that permission protected data
+     * was delivered. When you are about to deliver the location data to a registered
+     * listener you should use {@link #checkPermissionForDataDelivery(Context, String,
+     * int, int, String, String)} which will evaluate the permission access based on the current
+     * fg/bg state of the app and leave a record that the data was accessed.
+     *
      * @param context Context for accessing resources.
      * @param permission The permission to check.
      * @param pid The process id for which to check.
      * @param uid The uid for which to check.
      * @param packageName The package name for which to check. If null the
      *     the first package for the calling UID will be used.
-     * @param message A message describing the reason the permission was checked
-     *
      * @return The permission check result which is either {@link #PERMISSION_GRANTED}
      *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     *
+     * @see #checkPermissionForDataDelivery(Context, String, int, int, String, String)
      */
     @PermissionResult
-    public static int checkPermission(@NonNull Context context, @NonNull String permission,
-            int pid, int uid, @Nullable String packageName, @Nullable String message) {
+    public static int checkPermissionForPreflight(@NonNull Context context,
+            @NonNull String permission, int pid, int uid, @Nullable String packageName) {
+        return checkPermissionCommon(context, permission, pid, uid, packageName, null /*message*/,
+                false /*forDataDelivery*/);
+    }
+
+    /**
+     * Checks whether your app has a given permission and whether the app op
+     * that corresponds to this permission is allowed.
+     *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * point where you will deliver the permission protected data to clients.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use {@link #checkSelfPermissionForPreflight(Context, String)}
+     * to determine if the app has or may have location permission (if app has only foreground
+     * location the grant state depends on the app's fg/gb state) and this check will not
+     * leave a trace that permission protected data was delivered. When you are about to
+     * deliver the location data to a registered listener you should use this method
+     * which will evaluate the permission access based on the current fg/bg state of the
+     * app and leave a record that the data was accessed.
+     *
+     * <p>This API assumes the the {@link Binder#getCallingUid()} is the same as
+     * {@link Process#myUid()}.
+     *
+     * @param context Context for accessing resources.
+     * @param permission The permission to check.
+     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
+     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     * @param message A message describing the reason the permission was checked
+     *
+     * @see #checkSelfPermissionForPreflight(Context, String)
+     */
+    @PermissionResult
+    public static int checkSelfPermissionForDataDelivery(@NonNull Context context,
+            @NonNull String permission, @Nullable String message) {
+        return checkPermissionForDataDelivery(context, permission, Process.myPid(),
+                Process.myUid(), context.getPackageName(), message);
+    }
+
+    /**
+     * Checks whether your app has a given permission and whether the app op
+     * that corresponds to this permission is allowed.
+     *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * preflight point where you will not deliver the permission protected data
+     * to clients but schedule permission data delivery, apps register listeners,
+     * etc.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use this method to determine if the app has or may have location
+     * permission (if app has only foreground location the grant state depends on the
+     * app's fg/gb state) and this check will not leave a trace that permission protected
+     * data was delivered. When you are about to deliver the location data to a registered
+     * listener you should use this method which will evaluate the permission access based
+     * on the current fg/bg state of the app and leave a record that the data was accessed.
+     *
+     * <p>This API assumes the the {@link Binder#getCallingUid()} is the same as
+     * {@link Process#myUid()}.
+     *
+     * @param context Context for accessing resources.
+     * @param permission The permission to check.
+     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
+     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     *
+     * @see #checkSelfPermissionForDataDelivery(Context, String, String)
+     */
+    @PermissionResult
+    public static int checkSelfPermissionForPreflight(@NonNull Context context,
+            @NonNull String permission) {
+        return checkPermissionForPreflight(context, permission, Process.myPid(),
+                Process.myUid(), context.getPackageName());
+    }
+
+    /**
+     * Checks whether the IPC you are handling has a given permission and whether
+     * the app op that corresponds to this permission is allowed.
+     *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * point where you will deliver the permission protected data to clients.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use {@link #checkCallingPermissionForPreflight(Context, String, String)}
+     * to determine if the app has or may have location permission (if app has only foreground
+     * location the grant state depends on the app's fg/gb state) and this check will not
+     * leave a trace that permission protected data was delivered. When you are about to
+     * deliver the location data to a registered listener you should use this method which
+     * will evaluate the permission access based on the current fg/bg state of the app and
+     * leave a record that the data was accessed.
+     *
+     * @param context Context for accessing resources.
+     * @param permission The permission to check.
+     * @param packageName The package name making the IPC. If null the
+     *     the first package for the calling UID will be used.
+     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
+     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     * @param message A message describing the reason the permission was checked
+     *
+     * @see #checkCallingPermissionForPreflight(Context, String, String)
+     */
+    @PermissionResult
+    public static int checkCallingPermissionForDataDelivery(@NonNull Context context,
+            @NonNull String permission, @Nullable String packageName, @Nullable String message) {
+        if (Binder.getCallingPid() == Process.myPid()) {
+            return PERMISSION_DENIED;
+        }
+        return checkPermissionForDataDelivery(context, permission, Binder.getCallingPid(),
+                Binder.getCallingUid(), packageName, message);
+    }
+
+    /**
+     * Checks whether the IPC you are handling has a given permission and whether
+     * the app op that corresponds to this permission is allowed.
+     *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * preflight point where you will not deliver the permission protected data
+     * to clients but schedule permission data delivery, apps register listeners,
+     * etc.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use this method to determine if the app has or may have location
+     * permission (if app has only foreground location the grant state depends on the app's
+     * fg/gb state) and this check will not leave a trace that permission protected data
+     * was delivered. When you are about to deliver the location data to a registered
+     * listener you should use {@link #checkCallingOrSelfPermissionForDataDelivery(Context,
+     * String, String)} which will evaluate the permission access based on the current fg/bg state
+     * of the app and leave a record that the data was accessed.
+     *
+     * @param context Context for accessing resources.
+     * @param permission The permission to check.
+     * @param packageName The package name making the IPC. If null the
+     *     the first package for the calling UID will be used.
+     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
+     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     *
+     * @see #checkCallingPermissionForDataDelivery(Context, String, String, String)
+     */
+    @PermissionResult
+    public static int checkCallingPermissionForPreflight(@NonNull Context context,
+            @NonNull String permission, @Nullable String packageName) {
+        if (Binder.getCallingPid() == Process.myPid()) {
+            return PERMISSION_DENIED;
+        }
+        return checkPermissionForPreflight(context, permission, Binder.getCallingPid(),
+                Binder.getCallingUid(), packageName);
+    }
+
+    /**
+     * Checks whether the IPC you are handling or your app has a given permission
+     * and whether the app op that corresponds to this permission is allowed.
+     *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * point where you will deliver the permission protected data to clients.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use {@link #checkCallingOrSelfPermissionForPreflight(Context, String)}
+     * to determine if the app has or may have location permission (if app has only foreground
+     * location the grant state depends on the app's fg/gb state) and this check will not
+     * leave a trace that permission protected data was delivered. When you are about to
+     * deliver the location data to a registered listener you should use this method which
+     * will evaluate the permission access based on the current fg/bg state of the app and
+     * leave a record that the data was accessed.
+     *
+     * @param context Context for accessing resources.
+     * @param permission The permission to check.
+     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
+     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     * @param message A message describing the reason the permission was checked
+     *
+     * @see #checkCallingOrSelfPermissionForPreflight(Context, String)
+     */
+    @PermissionResult
+    public static int checkCallingOrSelfPermissionForDataDelivery(@NonNull Context context,
+            @NonNull String permission, @Nullable String message) {
+        String packageName = (Binder.getCallingPid() == Process.myPid())
+                ? context.getPackageName() : null;
+        return checkPermissionForDataDelivery(context, permission, Binder.getCallingPid(),
+                Binder.getCallingUid(), packageName, message);
+    }
+
+    /**
+     * Checks whether the IPC you are handling or your app has a given permission
+     * and whether the app op that corresponds to this permission is allowed.
+     *
+     * <strong>NOTE:</strong> Use this method only for permission checks at the
+     * preflight point where you will not deliver the permission protected data
+     * to clients but schedule permission data delivery, apps register listeners,
+     * etc.
+     *
+     * <p>For example, if an app registers a location listener it should have the location
+     * permission but no data is actually sent to the app at the moment of registration
+     * and you should use this method to determine if the app has or may have location
+     * permission (if app has only foreground location the grant state depends on the
+     * app's fg/gb state) and this check will not leave a trace that permission protected
+     * data was delivered. When you are about to deliver the location data to a registered
+     * listener you should use {@link #checkCallingOrSelfPermissionForDataDelivery(Context,
+     * String, String)} which will evaluate the permission access based on the current fg/bg state
+     * of the app and leave a record that the data was accessed.
+     *
+     * @param context Context for accessing resources.
+     * @param permission The permission to check.
+     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
+     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
+     *
+     * @see #checkCallingOrSelfPermissionForDataDelivery(Context, String, String)
+     */
+    @PermissionResult
+    public static int checkCallingOrSelfPermissionForPreflight(@NonNull Context context,
+            @NonNull String permission) {
+        String packageName = (Binder.getCallingPid() == Process.myPid())
+                ? context.getPackageName() : null;
+        return checkPermissionForPreflight(context, permission, Binder.getCallingPid(),
+                Binder.getCallingUid(), packageName);
+    }
+
+    private static int checkPermissionCommon(@NonNull Context context, @NonNull String permission,
+            int pid, int uid, @Nullable String packageName, @Nullable String message,
+            boolean forDataDelivery) {
         if (context.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_DENIED) {
             return PERMISSION_DENIED;
         }
@@ -122,93 +400,18 @@
             packageName = packageNames[0];
         }
 
-        if (appOpsManager.noteProxyOpNoThrow(strOpToOp(op), packageName, uid, message)
-                != AppOpsManager.MODE_ALLOWED) {
-            return PERMISSION_DENIED_APP_OP;
+        if (forDataDelivery) {
+            if (appOpsManager.noteProxyOpNoThrow(op, packageName, uid, message)
+                    != AppOpsManager.MODE_ALLOWED) {
+                return PERMISSION_DENIED_APP_OP;
+            }
+        } else {
+            final int mode = appOpsManager.unsafeCheckOpRawNoThrow(op, uid, packageName);
+            if (mode != AppOpsManager.MODE_ALLOWED && mode != AppOpsManager.MODE_FOREGROUND) {
+                return PERMISSION_DENIED_APP_OP;
+            }
         }
 
         return PERMISSION_GRANTED;
     }
-
-    /**
-     * Checks whether your app has a given permission and whether the app op
-     * that corresponds to this permission is allowed.
-     *
-     * <p>This API assumes the the {@link Binder#getCallingUid()} is the same as
-     * {@link Process#myUid()}.
-     *
-     * @param context Context for accessing resources.
-     * @param permission The permission to check.
-     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
-     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
-     */
-    @PermissionResult
-    public static int checkSelfPermission(@NonNull Context context,
-            @NonNull String permission) {
-        return checkPermission(context, permission, Process.myPid(),
-                Process.myUid(), context.getPackageName(), null /* self access */);
-    }
-
-    /**
-     * @deprecated Use {@link #checkCallingPermission(Context, String, String, String)} instead
-     */
-    @Deprecated
-    @PermissionResult
-    public static int checkCallingPermission(@NonNull Context context,
-            @NonNull String permission, @Nullable String packageName) {
-        return checkCallingPermission(context, permission, packageName, null);
-    }
-
-    /**
-     * Checks whether the IPC you are handling has a given permission and whether
-     * the app op that corresponds to this permission is allowed.
-     *
-     * @param context Context for accessing resources.
-     * @param permission The permission to check.
-     * @param packageName The package name making the IPC. If null the
-     *     the first package for the calling UID will be used.
-     * @param message A message describing the reason the permission was checked
-     *
-     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
-     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
-     */
-    @PermissionResult
-    public static int checkCallingPermission(@NonNull Context context,
-            @NonNull String permission, @Nullable String packageName, @Nullable String message) {
-        if (Binder.getCallingPid() == Process.myPid()) {
-            return PERMISSION_DENIED;
-        }
-        return checkPermission(context, permission, Binder.getCallingPid(),
-                Binder.getCallingUid(), packageName, message);
-    }
-
-    /**
-     * @deprecated Use {@link #checkCallingOrSelfPermission(Context, String, String)} instead
-     */
-    @Deprecated
-    @PermissionResult
-    public static int checkCallingOrSelfPermission(@NonNull Context context,
-            @NonNull String permission) {
-        return checkCallingOrSelfPermission(context, permission, null);
-    }
-
-    /**
-     * Checks whether the IPC you are handling or your app has a given permission
-     * and whether the app op that corresponds to this permission is allowed.
-     *
-     * @param context Context for accessing resources.
-     * @param permission The permission to check.
-     * @param message A message describing the reason the permission was checked
-     *
-     * @return The permission check result which is either {@link #PERMISSION_GRANTED}
-     *     or {@link #PERMISSION_DENIED} or {@link #PERMISSION_DENIED_APP_OP}.
-     */
-    @PermissionResult
-    public static int checkCallingOrSelfPermission(@NonNull Context context,
-            @NonNull String permission, @Nullable String message) {
-        String packageName = (Binder.getCallingPid() == Process.myPid())
-                ? context.getPackageName() : null;
-        return checkPermission(context, permission, Binder.getCallingPid(),
-                Binder.getCallingUid(), packageName, message);
-    }
-}
+}
\ No newline at end of file
diff --git a/core/java/android/content/om/IOverlayManager.aidl b/core/java/android/content/om/IOverlayManager.aidl
index 43a4fe5..3d7e3be 100644
--- a/core/java/android/content/om/IOverlayManager.aidl
+++ b/core/java/android/content/om/IOverlayManager.aidl
@@ -157,4 +157,10 @@
      * Returns the list of default overlay packages, or an empty array if there are none.
      */
     String[] getDefaultOverlayPackages();
+
+    /**
+     * Invalidates and removes the idmap for an overlay,
+     * @param packageName The name of the overlay package whose idmap should be deleted.
+     */
+    void invalidateCachesForOverlay(in String packageName, in int userIs);
 }
diff --git a/core/java/android/content/om/OverlayManager.java b/core/java/android/content/om/OverlayManager.java
index f2716fe..853e818 100644
--- a/core/java/android/content/om/OverlayManager.java
+++ b/core/java/android/content/om/OverlayManager.java
@@ -21,6 +21,7 @@
 import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
 import android.annotation.SystemService;
+import android.annotation.TestApi;
 import android.content.Context;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -163,4 +164,28 @@
             throw e.rethrowFromSystemServer();
         }
     }
+
+    /**
+     * Returns information about all overlays for the given target package for
+     * the specified user. The returned list is ordered according to the
+     * overlay priority with the highest priority at the end of the list.
+     *
+     * @param targetPackageName The name of the target package.
+     * @param user The user to get the OverlayInfos for.
+     *
+     * @hide
+     */
+    @TestApi
+    @RequiresPermission(anyOf = {
+            "android.permission.INTERACT_ACROSS_USERS",
+    })
+    @NonNull
+    public void invalidateCachesForOverlay(@NonNull final String targetPackageName,
+            @NonNull UserHandle user) {
+        try {
+            mService.invalidateCachesForOverlay(targetPackageName, user.getIdentifier());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
 }
diff --git a/core/java/android/content/pm/AndroidTelephonyCommonUpdater.java b/core/java/android/content/pm/AndroidTelephonyCommonUpdater.java
deleted file mode 100644
index 1a720d5..0000000
--- a/core/java/android/content/pm/AndroidTelephonyCommonUpdater.java
+++ /dev/null
@@ -1,82 +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 android.content.pm;
-
-import static android.content.pm.SharedLibraryNames.ANDROID_TELEPHONY_COMMON;
-
-
-import com.android.internal.compat.IPlatformCompat;
-import android.compat.annotation.ChangeId;
-import android.compat.annotation.EnabledAfter;
-import android.content.pm.PackageParser.Package;
-
-import android.os.Build.VERSION_CODES;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.util.Log;
-import com.android.internal.annotations.VisibleForTesting;
-
-/**
- * Updates a package to ensure that
- * <ul>
- * <li> if apps have target SDK < R, then telephony-common library is included by default to
- * their class path. Even without <uses-library>.</li>
- * <li> if apps with target SDK level >= R && have special permission (or Phone UID):
- * apply <uses-library> on telephony-common should work.</li>
- * <li> Otherwise not allow to use the lib.
- * See {@link PackageSharedLibraryUpdater#removeLibrary(Package, String)}.</li>
- * </ul>
- *
- * @hide
- */
-@VisibleForTesting
-public class AndroidTelephonyCommonUpdater extends PackageSharedLibraryUpdater {
-
-    private static final String TAG = AndroidTelephonyCommonUpdater.class.getSimpleName();
-    /**
-     * Restrict telephony-common lib for apps having target SDK >= R
-     */
-    @ChangeId
-    @EnabledAfter(targetSdkVersion = VERSION_CODES.Q)
-    static final long RESTRICT_TELEPHONY_COMMON_CHANGE_ID = 139318877L;
-
-    private static boolean apkTargetsApiLevelLessThanROrCurrent(Package pkg) {
-        boolean shouldRestrict = false;
-        try {
-            IBinder b = ServiceManager.getService("platform_compat");
-            IPlatformCompat platformCompat = IPlatformCompat.Stub.asInterface(b);
-            shouldRestrict = platformCompat.isChangeEnabled(RESTRICT_TELEPHONY_COMMON_CHANGE_ID,
-                pkg.applicationInfo);
-        } catch (RemoteException ex) {
-            Log.e(TAG, ex.getMessage());
-        }
-        // TODO(b/139318877): remove version check for CUR_DEVELOPEMENT after clean up work.
-        return !shouldRestrict
-            || pkg.applicationInfo.targetSdkVersion == VERSION_CODES.CUR_DEVELOPMENT;
-    }
-
-    @Override
-    public void updatePackage(Package pkg) {
-        // for apps with targetSDKVersion < R include the library for backward compatibility.
-        if (apkTargetsApiLevelLessThanROrCurrent(pkg)) {
-            prefixRequiredLibrary(pkg, ANDROID_TELEPHONY_COMMON);
-        } else if (pkg.mSharedUserId == null || !pkg.mSharedUserId.equals("android.uid.phone")) {
-            // if apps target >= R
-            removeLibrary(pkg, ANDROID_TELEPHONY_COMMON);
-        }
-    }
-}
diff --git a/core/java/android/content/pm/AndroidTestBaseUpdater.java b/core/java/android/content/pm/AndroidTestBaseUpdater.java
index da1a693..8fcfe71 100644
--- a/core/java/android/content/pm/AndroidTestBaseUpdater.java
+++ b/core/java/android/content/pm/AndroidTestBaseUpdater.java
@@ -18,10 +18,17 @@
 import static android.content.pm.SharedLibraryNames.ANDROID_TEST_BASE;
 import static android.content.pm.SharedLibraryNames.ANDROID_TEST_RUNNER;
 
+import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledAfter;
+import android.content.Context;
 import android.content.pm.PackageParser.Package;
 import android.os.Build;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.compat.IPlatformCompat;
 
 /**
  * Updates a package to ensure that if it targets <= Q that the android.test.base library is
@@ -37,10 +44,26 @@
  */
 @VisibleForTesting
 public class AndroidTestBaseUpdater extends PackageSharedLibraryUpdater {
+    private static final String TAG = "AndroidTestBaseUpdater";
 
-    private static boolean apkTargetsApiLevelLessThanOrEqualToQ(Package pkg) {
-        int targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
-        return targetSdkVersion <= Build.VERSION_CODES.Q;
+    /**
+     * Remove android.test.base library for apps that target SDK R or more and do not depend on
+     * android.test.runner (as it depends on classes from the android.test.base library).
+     */
+    @ChangeId
+    @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
+    private static final long REMOVE_ANDROID_TEST_BASE = 133396946L;
+
+    private static boolean isChangeEnabled(Package pkg) {
+        IPlatformCompat platformCompat = IPlatformCompat.Stub.asInterface(
+                ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE));
+        try {
+            return platformCompat.isChangeEnabled(REMOVE_ANDROID_TEST_BASE, pkg.applicationInfo);
+        } catch (RemoteException | NullPointerException e) {
+            Log.e(TAG, "Failed to get a response from PLATFORM_COMPAT_SERVICE", e);
+        }
+        // Fall back to previous behaviour.
+        return pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.Q;
     }
 
     @Override
@@ -48,7 +71,7 @@
         // Packages targeted at <= Q expect the classes in the android.test.base library
         // to be accessible so this maintains backward compatibility by adding the
         // android.test.base library to those packages.
-        if (apkTargetsApiLevelLessThanOrEqualToQ(pkg)) {
+        if (!isChangeEnabled(pkg)) {
             prefixRequiredLibrary(pkg, ANDROID_TEST_BASE);
         } else {
             // If a package already depends on android.test.runner then add a dependency on
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index c6beee2..19d8edf 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -50,6 +50,7 @@
 import android.content.pm.dex.IArtManager;
 import android.graphics.Bitmap;
 import android.net.Uri;
+import android.os.Bundle;
 import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
 import android.content.IntentSender;
@@ -280,7 +281,7 @@
 
     boolean isPackageSuspendedForUser(String packageName, int userId);
 
-    PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId);
+    Bundle getSuspendedPackageAppExtras(String packageName, int userId);
 
     /**
      * Backup/restore support - only the system uid may use these.
@@ -685,6 +686,8 @@
 
     String getSystemCaptionsServicePackageName();
 
+    String getSetupWizardPackageName();
+
     String getIncidentReportApproverPackageName();
 
     boolean isPackageStateProtected(String packageName, int userId);
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index 3933e81..d2a4030 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -248,7 +248,11 @@
          *                      system, {@code null} otherwise.
          * @see PackageManager#isPackageSuspended()
          * @see #getSuspendedPackageLauncherExtras(String, UserHandle)
+         * @deprecated {@code launcherExtras} should be obtained by using
+         * {@link #getSuspendedPackageLauncherExtras(String, UserHandle)}. For all other cases,
+         * {@link #onPackagesSuspended(String[], UserHandle)} should be used.
          */
+        @Deprecated
         public void onPackagesSuspended(String[] packageNames, UserHandle user,
                 @Nullable Bundle launcherExtras) {
             onPackagesSuspended(packageNames, user);
diff --git a/core/java/android/content/pm/PackageBackwardCompatibility.java b/core/java/android/content/pm/PackageBackwardCompatibility.java
index 797ba64b..4331bd4 100644
--- a/core/java/android/content/pm/PackageBackwardCompatibility.java
+++ b/core/java/android/content/pm/PackageBackwardCompatibility.java
@@ -51,8 +51,6 @@
 
         packageUpdaters.add(new AndroidHidlUpdater());
 
-        packageUpdaters.add(new AndroidTelephonyCommonUpdater());
-
         // Add this before adding AndroidTestBaseUpdater so that android.test.base comes before
         // android.test.mock.
         packageUpdaters.add(new AndroidTestRunnerSplitUpdater());
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index 1099d8b..69ce3bd 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -101,19 +101,6 @@
  * <p>
  * The ApiDemos project contains examples of using this API:
  * <code>ApiDemos/src/com/example/android/apis/content/InstallApk*.java</code>.
- * <p>
- * On Android Q or above, an app installed notification will be posted
- * by system after a new app is installed.
- * To customize installer's notification icon, you should declare the following in the manifest
- * &lt;application> as follows: </p>
- * <pre>
- * &lt;meta-data android:name="com.android.packageinstaller.notification.smallIcon"
- * android:resource="@drawable/installer_notification_icon"/>
- * </pre>
- * <pre>
- * &lt;meta-data android:name="com.android.packageinstaller.notification.color"
- * android:resource="@color/installer_notification_color"/>
- * </pre>
  */
 public class PackageInstaller {
     private static final String TAG = "PackageInstaller";
diff --git a/core/java/android/content/pm/PackageList.java b/core/java/android/content/pm/PackageList.java
deleted file mode 100644
index e3eb2c5..0000000
--- a/core/java/android/content/pm/PackageList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 android.content.pm;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.pm.PackageManagerInternal.PackageListObserver;
-
-import com.android.server.LocalServices;
-
-import java.util.List;
-
-/**
- * All of the package name installed on the system.
- * <p>A self observable list that automatically removes the listener when it goes out of scope.
- *
- * @hide Only for use within the system server.
- */
-public class PackageList implements PackageListObserver, AutoCloseable {
-    private final PackageListObserver mWrappedObserver;
-    private final List<String> mPackageNames;
-
-    /**
-     * Create a new object.
-     * <p>Ownership of the given {@link List} transfers to this object and should not
-     * be modified by the caller.
-     */
-    public PackageList(@NonNull List<String> packageNames, @Nullable PackageListObserver observer) {
-        mPackageNames = packageNames;
-        mWrappedObserver = observer;
-    }
-
-    @Override
-    public void onPackageAdded(String packageName, int uid) {
-        if (mWrappedObserver != null) {
-            mWrappedObserver.onPackageAdded(packageName, uid);
-        }
-    }
-
-    @Override
-    public void onPackageChanged(String packageName, int uid) {
-        if (mWrappedObserver != null) {
-            mWrappedObserver.onPackageChanged(packageName, uid);
-        }
-    }
-
-    @Override
-    public void onPackageRemoved(String packageName, int uid) {
-        if (mWrappedObserver != null) {
-            mWrappedObserver.onPackageRemoved(packageName, uid);
-        }
-    }
-
-    @Override
-    public void close() throws Exception {
-        LocalServices.getService(PackageManagerInternal.class).removePackageListObserver(this);
-    }
-
-    /**
-     * Returns the names of packages installed on the system.
-     * <p>The list is a copy-in-time and the actual set of installed packages may differ. Real
-     * time updates to the package list are sent via the {@link PackageListObserver} callback.
-     */
-    public @NonNull List<String> getPackageNames() {
-        return mPackageNames;
-    }
-}
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 8dfe00a..9513ce8 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -917,8 +917,9 @@
     public static final int INSTALL_DRY_RUN = 0x00800000;
 
     /** @hide */
-    @IntDef(flag = true, prefix = { "DONT_KILL_APP" }, value = {
-            DONT_KILL_APP
+    @IntDef(flag = true, value = {
+            DONT_KILL_APP,
+            SYNCHRONOUS
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface EnabledFlags {}
@@ -931,6 +932,14 @@
      */
     public static final int DONT_KILL_APP = 0x00000001;
 
+    /**
+     * Flag parameter for
+     * {@link #setComponentEnabledSetting(android.content.ComponentName, int, int)} to indicate
+     * that the given user's package restrictions state will be serialised to disk after the
+     * component state has been updated.
+     */
+    public static final int SYNCHRONOUS = 0x00000002;
+
     /** @hide */
     @IntDef(prefix = { "INSTALL_REASON_" }, value = {
             INSTALL_REASON_UNKNOWN,
@@ -2849,6 +2858,17 @@
 
     /**
      * Feature for {@link #getSystemAvailableFeatures} and {@link #hasSystemFeature}:
+     * The device supports device-unique Keystore attestations.  Only available on devices that
+     * also support {@link #FEATURE_STRONGBOX_KEYSTORE}, and can only be used by device owner
+     * apps (see {@link android.app.admin.DevicePolicyManager#generateKeyPair}).
+     * @hide
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_DEVICE_UNIQUE_ATTESTATION =
+            "android.hardware.device_unique_attestation";
+
+    /**
+     * Feature for {@link #getSystemAvailableFeatures} and {@link #hasSystemFeature}:
      * The device has a Keymaster implementation that supports Device ID attestation.
      *
      * @see DevicePolicyManager#isDeviceIdAttestationSupported
@@ -3078,8 +3098,11 @@
      * because the app was updated to support runtime permissions, the
      * the permission will be revoked in the upgrade process.
      *
+     * @deprecated Renamed to {@link #FLAG_PERMISSION_REVOKED_COMPAT}.
+     *
      * @hide
      */
+    @Deprecated
     @SystemApi
     @TestApi
     public static final int FLAG_PERMISSION_REVOKE_ON_UPGRADE =  1 << 3;
@@ -3202,6 +3225,18 @@
     public static final int FLAG_PERMISSION_GRANTED_BY_ROLE =  1 << 15;
 
     /**
+     * Permission flag: The permission should have been revoked but is kept granted for
+     * compatibility. The data protected by the permission should be protected by a no-op (empty
+     * list, default error, etc) instead of crashing the client. The permission will be revoked if
+     * the app is upgraded to supports it.
+     *
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    public static final int FLAG_PERMISSION_REVOKED_COMPAT =  FLAG_PERMISSION_REVOKE_ON_UPGRADE;
+
+    /**
      * Permission flags: Bitwise or of all permission flags allowing an
      * exemption for a restricted permission.
      * @hide
@@ -3241,7 +3276,8 @@
             | FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT
             | FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT
             | FLAG_PERMISSION_APPLY_RESTRICTION
-            | FLAG_PERMISSION_GRANTED_BY_ROLE;
+            | FLAG_PERMISSION_GRANTED_BY_ROLE
+            | FLAG_PERMISSION_REVOKED_COMPAT;
 
     /**
      * Injected activity in app that forwards user to setting activity of that app.
@@ -4017,7 +4053,8 @@
             FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT,
             FLAG_PERMISSION_RESTRICTION_INSTALLER_EXEMPT,
             FLAG_PERMISSION_APPLY_RESTRICTION,
-            FLAG_PERMISSION_GRANTED_BY_ROLE
+            FLAG_PERMISSION_GRANTED_BY_ROLE,
+            FLAG_PERMISSION_REVOKED_COMPAT
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface PermissionFlags {}
@@ -7086,7 +7123,6 @@
             case FLAG_PERMISSION_POLICY_FIXED: return "POLICY_FIXED";
             case FLAG_PERMISSION_SYSTEM_FIXED: return "SYSTEM_FIXED";
             case FLAG_PERMISSION_USER_SET: return "USER_SET";
-            case FLAG_PERMISSION_REVOKE_ON_UPGRADE: return "REVOKE_ON_UPGRADE";
             case FLAG_PERMISSION_USER_FIXED: return "USER_FIXED";
             case FLAG_PERMISSION_REVIEW_REQUIRED: return "REVIEW_REQUIRED";
             case FLAG_PERMISSION_REVOKE_WHEN_REQUESTED: return "REVOKE_WHEN_REQUESTED";
@@ -7097,6 +7133,7 @@
             case FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT: return "RESTRICTION_UPGRADE_EXEMPT";
             case FLAG_PERMISSION_APPLY_RESTRICTION: return "APPLY_RESTRICTION";
             case FLAG_PERMISSION_GRANTED_BY_ROLE: return "GRANTED_BY_ROLE";
+            case FLAG_PERMISSION_REVOKED_COMPAT: return "REVOKED_COMPAT";
             default: return Integer.toString(flag);
         }
     }
@@ -7390,6 +7427,17 @@
     }
 
     /**
+     * @return the system defined setup wizard package name, or null if there's none.
+     *
+     * @hide
+     */
+    @Nullable
+    public String getSetupWizardPackageName() {
+        throw new UnsupportedOperationException(
+                "getSetupWizardPackageName not implemented in subclass");
+    }
+
+    /**
      * @return the incident report approver app package name, or null if it's not defined
      * by the OEM.
      *
diff --git a/core/java/android/content/pm/PackageManagerInternal.java b/core/java/android/content/pm/PackageManagerInternal.java
deleted file mode 100644
index 24ee213..0000000
--- a/core/java/android/content/pm/PackageManagerInternal.java
+++ /dev/null
@@ -1,792 +0,0 @@
-/*
- * Copyright (C) 2015 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.content.pm;
-
-import android.annotation.AppIdInt;
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.UserIdInt;
-import android.content.ComponentName;
-import android.content.Intent;
-import android.content.IntentSender;
-import android.content.pm.PackageManager.ApplicationInfoFlags;
-import android.content.pm.PackageManager.ComponentInfoFlags;
-import android.content.pm.PackageManager.PackageInfoFlags;
-import android.content.pm.PackageManager.ResolveInfoFlags;
-import android.os.Bundle;
-import android.os.PersistableBundle;
-import android.util.ArraySet;
-import android.util.SparseArray;
-
-import java.io.IOException;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.List;
-import java.util.function.Consumer;
-
-/**
- * Package manager local system service interface.
- *
- * @hide Only for use within the system server.
- */
-public abstract class PackageManagerInternal {
-    public static final int PACKAGE_SYSTEM = 0;
-    public static final int PACKAGE_SETUP_WIZARD = 1;
-    public static final int PACKAGE_INSTALLER = 2;
-    public static final int PACKAGE_VERIFIER = 3;
-    public static final int PACKAGE_BROWSER = 4;
-    public static final int PACKAGE_SYSTEM_TEXT_CLASSIFIER = 5;
-    public static final int PACKAGE_PERMISSION_CONTROLLER = 6;
-    public static final int PACKAGE_WELLBEING = 7;
-    public static final int PACKAGE_DOCUMENTER = 8;
-    public static final int PACKAGE_CONFIGURATOR = 9;
-    public static final int PACKAGE_INCIDENT_REPORT_APPROVER = 10;
-    public static final int PACKAGE_APP_PREDICTOR = 11;
-    @IntDef(value = {
-        PACKAGE_SYSTEM,
-        PACKAGE_SETUP_WIZARD,
-        PACKAGE_INSTALLER,
-        PACKAGE_VERIFIER,
-        PACKAGE_BROWSER,
-        PACKAGE_SYSTEM_TEXT_CLASSIFIER,
-        PACKAGE_PERMISSION_CONTROLLER,
-        PACKAGE_WELLBEING,
-        PACKAGE_DOCUMENTER,
-        PACKAGE_CONFIGURATOR,
-        PACKAGE_INCIDENT_REPORT_APPROVER,
-        PACKAGE_APP_PREDICTOR,
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface KnownPackage {}
-
-    /** Observer called whenever the list of packages changes */
-    public interface PackageListObserver {
-        /** A package was added to the system. */
-        void onPackageAdded(@NonNull String packageName, int uid);
-        /** A package was changed - either installed for a specific user or updated. */
-        default void onPackageChanged(@NonNull String packageName, int uid) {}
-        /** A package was removed from the system. */
-        void onPackageRemoved(@NonNull String packageName, int uid);
-    }
-
-    /**
-     * Called when the package for the default SMS handler changed
-     *
-     * @param packageName the new sms package
-     * @param userId user for which the change was made
-     */
-    public void onDefaultSmsAppChanged(String packageName, int userId) {}
-
-    /**
-     * Called when the package for the default sim call manager changed
-     *
-     * @param packageName the new sms package
-     * @param userId user for which the change was made
-     */
-    public void onDefaultSimCallManagerAppChanged(String packageName, int userId) {}
-
-    /**
-     * Sets a list of apps to keep in PM's internal data structures and as APKs even if no user has
-     * currently installed it. The apps are not preloaded.
-     * @param packageList List of package names to keep cached.
-     */
-    public abstract void setKeepUninstalledPackages(List<String> packageList);
-
-    /**
-     * Gets whether some of the permissions used by this package require a user
-     * review before any of the app components can run.
-     * @param packageName The package name for which to check.
-     * @param userId The user under which to check.
-     * @return True a permissions review is required.
-     */
-    public abstract boolean isPermissionsReviewRequired(String packageName, int userId);
-
-    /**
-     * Retrieve all of the information we know about a particular package/application.
-     * @param filterCallingUid The results will be filtered in the context of this UID instead
-     * of the calling UID.
-     * @see PackageManager#getPackageInfo(String, int)
-     */
-    public abstract PackageInfo getPackageInfo(String packageName,
-            @PackageInfoFlags int flags, int filterCallingUid, int userId);
-
-    /**
-     * Return a List of all application packages that are installed on the
-     * device, for a specific user. If flag GET_UNINSTALLED_PACKAGES has been
-     * set, a list of all applications including those deleted with
-     * {@code DONT_DELETE_DATA} (partially installed apps with data directory)
-     * will be returned.
-     *
-     * @param flags Additional option flags to modify the data returned.
-     * @param userId The user for whom the installed applications are to be
-     *            listed
-     * @param callingUid The uid of the original caller app
-     * @return A List of ApplicationInfo objects, one for each installed
-     *         application. In the unlikely case there are no installed
-     *         packages, an empty list is returned. If flag
-     *         {@code MATCH_UNINSTALLED_PACKAGES} is set, the application
-     *         information is retrieved from the list of uninstalled
-     *         applications (which includes installed applications as well as
-     *         applications with data directory i.e. applications which had been
-     *         deleted with {@code DONT_DELETE_DATA} flag set).
-     */
-    public abstract List<ApplicationInfo> getInstalledApplications(
-            @ApplicationInfoFlags int flags, @UserIdInt int userId, int callingUid);
-
-    /**
-     * Retrieve launcher extras for a suspended package provided to the system in
-     * {@link PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
-     * PersistableBundle, String)}.
-     *
-     * @param packageName The package for which to return launcher extras.
-     * @param userId The user for which to check.
-     * @return The launcher extras.
-     *
-     * @see PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
-     * PersistableBundle, String)
-     * @see PackageManager#isPackageSuspended()
-     */
-    public abstract Bundle getSuspendedPackageLauncherExtras(String packageName,
-            int userId);
-
-    /**
-     * Internal api to query the suspended state of a package.
-     * @param packageName The package to check.
-     * @param userId The user id to check for.
-     * @return {@code true} if the package is suspended, {@code false} otherwise.
-     * @see PackageManager#isPackageSuspended(String)
-     */
-    public abstract boolean isPackageSuspended(String packageName, int userId);
-
-    /**
-     * Get the name of the package that suspended the given package. Packages can be suspended by
-     * device administrators or apps holding {@link android.Manifest.permission#MANAGE_USERS} or
-     * {@link android.Manifest.permission#SUSPEND_APPS}.
-     *
-     * @param suspendedPackage The package that has been suspended.
-     * @param userId The user for which to check.
-     * @return Name of the package that suspended the given package. Returns {@code null} if the
-     * given package is not currently suspended and the platform package name - i.e.
-     * {@code "android"} - if the package was suspended by a device admin.
-     */
-    public abstract String getSuspendingPackage(String suspendedPackage, int userId);
-
-    /**
-     * Get the information describing the dialog to be shown to the user when they try to launch a
-     * suspended application.
-     *
-     * @param suspendedPackage The package that has been suspended.
-     * @param userId The user for which to check.
-     * @return A {@link SuspendDialogInfo} object describing the dialog to be shown.
-     */
-    @Nullable
-    public abstract SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage, int userId);
-
-    /**
-     * Gets any distraction flags set via
-     * {@link PackageManager#setDistractingPackageRestrictions(String[], int)}
-     *
-     * @param packageName
-     * @param userId
-     * @return A bitwise OR of any of the {@link PackageManager.DistractionRestriction}
-     */
-    public abstract @PackageManager.DistractionRestriction int getDistractingPackageRestrictions(
-            String packageName, int userId);
-
-    /**
-     * Do a straight uid lookup for the given package/application in the given user.
-     * @see PackageManager#getPackageUidAsUser(String, int, int)
-     * @return The app's uid, or < 0 if the package was not found in that user
-     */
-    public abstract int getPackageUid(String packageName,
-            @PackageInfoFlags int flags, int userId);
-
-    /**
-     * Retrieve all of the information we know about a particular package/application.
-     * @param filterCallingUid The results will be filtered in the context of this UID instead
-     * of the calling UID.
-     * @see PackageManager#getApplicationInfo(String, int)
-     */
-    public abstract ApplicationInfo getApplicationInfo(String packageName,
-            @ApplicationInfoFlags int flags, int filterCallingUid, int userId);
-
-    /**
-     * Retrieve all of the information we know about a particular activity class.
-     * @param filterCallingUid The results will be filtered in the context of this UID instead
-     * of the calling UID.
-     * @see PackageManager#getActivityInfo(ComponentName, int)
-     */
-    public abstract ActivityInfo getActivityInfo(ComponentName component,
-            @ComponentInfoFlags int flags, int filterCallingUid, int userId);
-
-    /**
-     * Retrieve all activities that can be performed for the given intent.
-     * @param filterCallingUid The results will be filtered in the context of this UID instead
-     * of the calling UID.
-     * @see PackageManager#queryIntentActivities(Intent, int)
-     */
-    public abstract List<ResolveInfo> queryIntentActivities(Intent intent,
-            @ResolveInfoFlags int flags, int filterCallingUid, int userId);
-
-    /**
-     * Retrieve all services that can be performed for the given intent.
-     * @see PackageManager#queryIntentServices(Intent, int)
-     */
-    public abstract List<ResolveInfo> queryIntentServices(
-            Intent intent, int flags, int callingUid, int userId);
-
-    /**
-     * Interface to {@link com.android.server.pm.PackageManagerService#getHomeActivitiesAsUser}.
-     */
-    public abstract ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
-            int userId);
-
-    /**
-     * @return The default home activity component name.
-     */
-    public abstract ComponentName getDefaultHomeActivity(int userId);
-
-    /**
-     * Called by DeviceOwnerManagerService to set the package names of device owner and profile
-     * owners.
-     */
-    public abstract void setDeviceAndProfileOwnerPackages(
-            int deviceOwnerUserId, String deviceOwner, SparseArray<String> profileOwners);
-
-    /**
-     * Returns {@code true} if a given package can't be wiped. Otherwise, returns {@code false}.
-     */
-    public abstract boolean isPackageDataProtected(int userId, String packageName);
-
-    /**
-     * Returns {@code true} if a given package's state is protected, e.g. it cannot be force
-     * stopped, suspended, disabled or hidden. Otherwise, returns {@code false}.
-     */
-    public abstract boolean isPackageStateProtected(String packageName, int userId);
-
-    /**
-     * Returns {@code true} if a given package is installed as ephemeral. Otherwise, returns
-     * {@code false}.
-     */
-    public abstract boolean isPackageEphemeral(int userId, String packageName);
-
-    /**
-     * Gets whether the package was ever launched.
-     * @param packageName The package name.
-     * @param userId The user for which to check.
-     * @return Whether was launched.
-     * @throws IllegalArgumentException if the package is not found
-     */
-    public abstract boolean wasPackageEverLaunched(String packageName, int userId);
-
-    /**
-     * Retrieve the official name associated with a uid. This name is
-     * guaranteed to never change, though it is possible for the underlying
-     * uid to be changed. That is, if you are storing information about
-     * uids in persistent storage, you should use the string returned
-     * by this function instead of the raw uid.
-     *
-     * @param uid The uid for which you would like to retrieve a name.
-     * @return Returns a unique name for the given uid, or null if the
-     * uid is not currently assigned.
-     */
-    public abstract String getNameForUid(int uid);
-
-    /**
-     * Request to perform the second phase of ephemeral resolution.
-     * @param responseObj The response of the first phase of ephemeral resolution
-     * @param origIntent The original intent that triggered ephemeral resolution
-     * @param resolvedType The resolved type of the intent
-     * @param callingPackage The name of the package requesting the ephemeral application
-     * @param verificationBundle Optional bundle to pass to the installer for additional
-     * verification
-     * @param userId The ID of the user that triggered ephemeral resolution
-     */
-    public abstract void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
-            Intent origIntent, String resolvedType, String callingPackage,
-            Bundle verificationBundle, int userId);
-
-    /**
-     * Grants implicit access based on an interaction between two apps. This grants the target app
-     * access to the calling application's package metadata.
-     * <p>
-     * When an application explicitly tries to interact with another application [via an
-     * activity, service or provider that is either declared in the caller's
-     * manifest via the {@code <queries>} tag or has been exposed via the target apps manifest using
-     * the {@code visibleToInstantApp} attribute], the target application must be able to see
-     * metadata about the calling app. If the calling application uses an implicit intent [ie
-     * action VIEW, category BROWSABLE], it remains hidden from the launched app.
-     * <p>
-     * @param userId the user
-     * @param intent the intent that triggered the grant
-     * @param callingAppId The app ID of the calling application
-     * @param targetAppId The app ID of the target application
-     */
-    public abstract void grantImplicitAccess(
-            @UserIdInt int userId, Intent intent, @AppIdInt int callingAppId,
-            @AppIdInt int targetAppId);
-
-    public abstract boolean isInstantAppInstallerComponent(ComponentName component);
-    /**
-     * Prunes instant apps and state associated with uninstalled
-     * instant apps according to the current platform policy.
-     */
-    public abstract void pruneInstantApps();
-
-    /**
-     * @return The SetupWizard package name.
-     */
-    public abstract String getSetupWizardPackageName();
-
-    public interface ExternalSourcesPolicy {
-
-        int USER_TRUSTED = 0;   // User has trusted the package to install apps
-        int USER_BLOCKED = 1;   // User has blocked the package to install apps
-        int USER_DEFAULT = 2;   // Default code to use when user response is unavailable
-
-        /**
-         * Checks the user preference for whether a package is trusted to request installs through
-         * package installer
-         *
-         * @param packageName The package to check for
-         * @param uid the uid in which the package is running
-         * @return {@link #USER_TRUSTED} if the user has trusted the package, {@link #USER_BLOCKED}
-         * if user has blocked requests from the package, {@link #USER_DEFAULT} if the user response
-         * is not yet available
-         */
-        int getPackageTrustedToInstallApps(String packageName, int uid);
-    }
-
-    public abstract void setExternalSourcesPolicy(ExternalSourcesPolicy policy);
-
-    /**
-     * Return true if the given package is a persistent app process.
-     */
-    public abstract boolean isPackagePersistent(String packageName);
-
-    /**
-     * Returns whether or not the given package represents a legacy system application released
-     * prior to runtime permissions.
-     */
-    public abstract boolean isLegacySystemApp(PackageParser.Package pkg);
-
-    /**
-     * Get all overlay packages for a user.
-     * @param userId The user for which to get the overlays.
-     * @return A list of overlay packages. An empty list is returned if the
-     *         user has no installed overlay packages.
-     */
-    public abstract List<PackageInfo> getOverlayPackages(int userId);
-
-    /**
-     * Get the names of all target packages for a user.
-     * @param userId The user for which to get the package names.
-     * @return A list of target package names. This list includes the "android" package.
-     */
-    public abstract List<String> getTargetPackageNames(int userId);
-
-    /**
-     * Set which overlay to use for a package.
-     * @param userId The user for which to update the overlays.
-     * @param targetPackageName The package name of the package for which to update the overlays.
-     * @param overlayPackageNames The complete list of overlay packages that should be enabled for
-     *                            the target. Previously enabled overlays not specified in the list
-     *                            will be disabled. Pass in null or an empty list to disable
-     *                            all overlays. The order of the items is significant if several
-     *                            overlays modify the same resource.
-     * @return true if all packages names were known by the package manager, false otherwise
-     */
-    public abstract boolean setEnabledOverlayPackages(int userId, String targetPackageName,
-            List<String> overlayPackageNames);
-
-    /**
-     * Resolves an activity intent, allowing instant apps to be resolved.
-     */
-    public abstract ResolveInfo resolveIntent(Intent intent, String resolvedType,
-            int flags, int userId, boolean resolveForStart, int filterCallingUid);
-
-    /**
-    * Resolves a service intent, allowing instant apps to be resolved.
-    */
-    public abstract ResolveInfo resolveService(Intent intent, String resolvedType,
-           int flags, int userId, int callingUid);
-
-   /**
-    * Resolves a content provider intent.
-    */
-    public abstract ProviderInfo resolveContentProvider(String name, int flags, int userId);
-
-    /**
-     * Track the creator of a new isolated uid.
-     * @param isolatedUid The newly created isolated uid.
-     * @param ownerUid The uid of the app that created the isolated process.
-     */
-    public abstract void addIsolatedUid(int isolatedUid, int ownerUid);
-
-    /**
-     * Track removal of an isolated uid.
-     * @param isolatedUid isolated uid that is no longer being used.
-     */
-    public abstract void removeIsolatedUid(int isolatedUid);
-
-    /**
-     * Return the taget SDK version for the app with the given UID.
-     */
-    public abstract int getUidTargetSdkVersion(int uid);
-
-    /**
-     * Return the taget SDK version for the app with the given package name.
-     */
-    public abstract int getPackageTargetSdkVersion(String packageName);
-
-    /** Whether the binder caller can access instant apps. */
-    public abstract boolean canAccessInstantApps(int callingUid, int userId);
-
-    /** Whether the binder caller can access the given component. */
-    public abstract boolean canAccessComponent(int callingUid, ComponentName component, int userId);
-
-    /**
-     * Returns {@code true} if a given package has instant application meta-data.
-     * Otherwise, returns {@code false}. Meta-data is state (eg. cookie, app icon, etc)
-     * associated with an instant app. It may be kept after the instant app has been uninstalled.
-     */
-    public abstract boolean hasInstantApplicationMetadata(String packageName, int userId);
-
-    /**
-     * Updates a package last used time.
-     */
-    public abstract void notifyPackageUse(String packageName, int reason);
-
-    /**
-     * Returns a package object for the given package name.
-     */
-    public abstract @Nullable PackageParser.Package getPackage(@NonNull String packageName);
-
-    /**
-     * Returns a package for the given UID. If the UID is part of a shared user ID, one
-     * of the packages will be chosen to be returned.
-     */
-    public abstract @Nullable PackageParser.Package getPackage(int uid);
-
-    /**
-     * Returns a list without a change observer.
-     *
-     * @see #getPackageList(PackageListObserver)
-     */
-    public @NonNull PackageList getPackageList() {
-        return getPackageList(null);
-    }
-
-    /**
-     * Returns the list of packages installed at the time of the method call.
-     * <p>The given observer is notified when the list of installed packages
-     * changes [eg. a package was installed or uninstalled]. It will not be
-     * notified if a package is updated.
-     * <p>The package list will not be updated automatically as packages are
-     * installed / uninstalled. Any changes must be handled within the observer.
-     */
-    public abstract @NonNull PackageList getPackageList(@Nullable PackageListObserver observer);
-
-    /**
-     * Removes the observer.
-     * <p>Generally not needed. {@link #getPackageList(PackageListObserver)} will automatically
-     * remove the observer.
-     * <p>Does nothing if the observer isn't currently registered.
-     * <p>Observers are notified asynchronously and it's possible for an observer to be
-     * invoked after its been removed.
-     */
-    public abstract void removePackageListObserver(@NonNull PackageListObserver observer);
-
-    /**
-     * Returns a package object for the disabled system package name.
-     */
-    public abstract @Nullable PackageParser.Package getDisabledSystemPackage(
-            @NonNull String packageName);
-
-    /**
-     * Returns the package name for the disabled system package.
-     *
-     * This is equivalent to
-     * {@link #getDisabledSystemPackage(String)}.{@link PackageParser.Package#packageName}
-     */
-    public abstract @Nullable String getDisabledSystemPackageName(@NonNull String packageName);
-
-    /**
-     * Returns whether or not the component is the resolver activity.
-     */
-    public abstract boolean isResolveActivityComponent(@NonNull ComponentInfo component);
-
-    /**
-     * Returns the package name for a known package.
-     */
-    public abstract @Nullable String getKnownPackageName(
-            @KnownPackage int knownPackage, int userId);
-
-    /**
-     * Returns whether the package is an instant app.
-     */
-    public abstract boolean isInstantApp(String packageName, int userId);
-
-    /**
-     * Returns whether the package is an instant app.
-     */
-    public abstract @Nullable String getInstantAppPackageName(int uid);
-
-    /**
-     * Returns whether or not access to the application should be filtered.
-     * <p>
-     * Access may be limited based upon whether the calling or target applications
-     * are instant applications.
-     *
-     * @see #canAccessInstantApps
-     */
-    public abstract boolean filterAppAccess(
-            @NonNull PackageParser.Package pkg, int callingUid, int userId);
-
-    /**
-     * Returns whether or not access to the application should be filtered.
-     *
-     * @see #filterAppAccess(android.content.pm.PackageParser.Package, int, int)
-     */
-    public abstract boolean filterAppAccess(
-            @NonNull String packageName, int callingUid, int userId);
-
-    /** Returns whether the given package was signed by the platform */
-    public abstract boolean isPlatformSigned(String pkg);
-
-    /**
-     * Returns true if it's still safe to restore data backed up from this app's version
-     * that was signed with restoringFromSigHash.
-     */
-    public abstract boolean isDataRestoreSafe(@NonNull byte[] restoringFromSigHash,
-            @NonNull String packageName);
-
-    /**
-     * Returns true if it's still safe to restore data backed up from this app's version
-     * that was signed with restoringFromSig.
-     */
-    public abstract boolean isDataRestoreSafe(@NonNull Signature restoringFromSig,
-            @NonNull String packageName);
-
-    /**
-     * Returns {@code true} if the the signing information for {@code clientUid} is sufficient
-     * to gain access gated by {@code capability}.  This can happen if the two UIDs have the
-     * same signing information, if the signing information {@code clientUid} indicates that
-     * it has the signing certificate for {@code serverUid} in its signing history (if it was
-     * previously signed by it), or if the signing certificate for {@code clientUid} is in the
-     * signing history for {@code serverUid} and with the {@code capability} specified.
-     */
-    public abstract boolean hasSignatureCapability(int serverUid, int clientUid,
-            @PackageParser.SigningDetails.CertCapabilities int capability);
-
-    /**
-     * Get appIds of all available apps which specified android:sharedUserId in the manifest.
-     *
-     * @return a SparseArray mapping from appId to it's sharedUserId.
-     */
-    public abstract SparseArray<String> getAppsWithSharedUserIds();
-
-    /**
-     * Get the value of attribute android:sharedUserId for the given packageName if specified,
-     * otherwise {@code null}.
-     */
-    public abstract String getSharedUserIdForPackage(@NonNull String packageName);
-
-    /**
-     * Get all packages which specified the given sharedUserId as android:sharedUserId attribute
-     * or an empty array if no package specified it.
-     */
-    public abstract String[] getPackagesForSharedUserId(@NonNull String sharedUserId, int userId);
-
-    /**
-     * Return if device is currently in a "core" boot environment, typically
-     * used to support full-disk encryption. Only apps marked with
-     * {@code coreApp} attribute are available.
-     */
-    public abstract boolean isOnlyCoreApps();
-
-    /**
-     * Make a best-effort attempt to provide the requested free disk space by
-     * deleting cached files.
-     *
-     * @throws IOException if the request was unable to be fulfilled.
-     */
-    public abstract void freeStorage(String volumeUuid, long bytes, int storageFlags)
-            throws IOException;
-
-    /** Returns {@code true} if the specified component is enabled and matches the given flags. */
-    public abstract boolean isEnabledAndMatches(@NonNull ComponentInfo info, int flags, int userId);
-
-    /** Returns {@code true} if the given user requires extra badging for icons. */
-    public abstract boolean userNeedsBadging(int userId);
-
-    /**
-     * Perform the given action for each package.
-     * Note that packages lock will be held while performin the actions.
-     *
-     * @param actionLocked action to be performed
-     */
-    public abstract void forEachPackage(Consumer<PackageParser.Package> actionLocked);
-
-    /**
-     * Perform the given action for each installed package for a user.
-     * Note that packages lock will be held while performin the actions.
-     */
-    public abstract void forEachInstalledPackage(
-            @NonNull Consumer<PackageParser.Package> actionLocked, @UserIdInt int userId);
-
-    /** Returns the list of enabled components */
-    public abstract ArraySet<String> getEnabledComponents(String packageName, int userId);
-
-    /** Returns the list of disabled components */
-    public abstract ArraySet<String> getDisabledComponents(String packageName, int userId);
-
-    /** Returns whether the given package is enabled for the given user */
-    public abstract @PackageManager.EnabledState int getApplicationEnabledState(
-            String packageName, int userId);
-
-    /**
-     * Extra field name for the token of a request to enable rollback for a
-     * package.
-     */
-    public static final String EXTRA_ENABLE_ROLLBACK_TOKEN =
-            "android.content.pm.extra.ENABLE_ROLLBACK_TOKEN";
-
-    /**
-     * Extra field name for the installFlags of a request to enable rollback
-     * for a package.
-     */
-    public static final String EXTRA_ENABLE_ROLLBACK_INSTALL_FLAGS =
-            "android.content.pm.extra.ENABLE_ROLLBACK_INSTALL_FLAGS";
-
-    /**
-     * Extra field name for the user id an install is associated with when
-     * enabling rollback.
-     */
-    public static final String EXTRA_ENABLE_ROLLBACK_USER =
-            "android.content.pm.extra.ENABLE_ROLLBACK_USER";
-
-    /**
-     * Used as the {@code enableRollbackCode} argument for
-     * {@link PackageManagerInternal#setEnableRollbackCode} to indicate that
-     * enabling rollback succeeded.
-     */
-    public static final int ENABLE_ROLLBACK_SUCCEEDED = 1;
-
-    /**
-     * Used as the {@code enableRollbackCode} argument for
-     * {@link PackageManagerInternal#setEnableRollbackCode} to indicate that
-     * enabling rollback failed.
-     */
-    public static final int ENABLE_ROLLBACK_FAILED = -1;
-
-    /**
-     * Allows the rollback manager listening to the
-     * {@link Intent#ACTION_PACKAGE_ENABLE_ROLLBACK enable rollback broadcast}
-     * to respond to the package manager. The response must include the
-     * {@code enableRollbackCode} which is one of
-     * {@link PackageManager#ENABLE_ROLLBACK_SUCCEEDED} or
-     * {@link PackageManager#ENABLE_ROLLBACK_FAILED}.
-     *
-     * @param token pending package identifier as passed via the
-     *            {@link PackageManager#EXTRA_ENABLE_ROLLBACK_TOKEN} Intent extra.
-     * @param enableRollbackCode the status code result of enabling rollback
-     * @throws SecurityException if the caller does not have the
-     *            PACKAGE_ROLLBACK_AGENT permission.
-     */
-    public abstract void setEnableRollbackCode(int token, int enableRollbackCode);
-
-    /**
-     * Ask the package manager to compile layouts in the given package.
-     */
-    public abstract boolean compileLayouts(String packageName);
-
-    /*
-     * Inform the package manager that the pending package install identified by
-     * {@code token} can be completed.
-     */
-    public abstract void finishPackageInstall(int token, boolean didLaunch);
-
-    /**
-     * Remove the default browser stored in the legacy package settings.
-     *
-     * @param userId the user id
-     *
-     * @return the package name of the default browser, or {@code null} if none
-     */
-    @Nullable
-    public abstract String removeLegacyDefaultBrowserPackageName(int userId);
-
-    /**
-     * Returns {@code true} if given {@code packageName} is an apex package.
-     */
-    public abstract boolean isApexPackage(String packageName);
-
-    /**
-     * Uninstalls given {@code packageName}.
-     *
-     * @param packageName apex package to uninstall.
-     * @param versionCode version of a package to uninstall.
-     * @param userId user to uninstall apex package for. Must be
-     *               {@link android.os.UserHandle#USER_ALL}, otherwise failure will be reported.
-     * @param intentSender a {@link IntentSender} to send result of an uninstall to.
-     */
-    public abstract void uninstallApex(String packageName, long versionCode, int userId,
-            IntentSender intentSender);
-
-    /**
-     * Get fingerprint of build that updated the runtime permissions for a user.
-     *
-     * @param userId The user to update
-     * @param fingerPrint The fingerprint to set
-     */
-    public abstract void setRuntimePermissionsFingerPrint(@NonNull String fingerPrint,
-            @UserIdInt int userId);
-
-    /**
-     * Migrates legacy obb data to its new location.
-     */
-    public abstract void migrateLegacyObbData();
-
-    /**
-     * Writes all package manager settings to disk. If {@code async} is {@code true}, the
-     * settings are written at some point in the future. Otherwise, the call blocks until
-     * the settings have been written.
-     */
-    public abstract void writeSettings(boolean async);
-
-    /**
-     * Writes all permission settings for the given set of users to disk. If {@code async}
-     * is {@code true}, the settings are written at some point in the future. Otherwise,
-     * the call blocks until the settings have been written.
-     */
-    public abstract void writePermissionSettings(@NonNull @UserIdInt int[] userIds, boolean async);
-
-    /**
-     * Returns {@code true} if the caller is the installer of record for the given package.
-     * Otherwise, {@code false}.
-     */
-    public abstract boolean isCallerInstallerOfRecord(
-            @NonNull PackageParser.Package pkg, int callingUid);
-
-    /** Returns whether or not default runtime permissions are granted for the given user */
-    public abstract boolean areDefaultRuntimePermissionsGranted(@UserIdInt int userId);
-
-    /** Sets the enforcement of reading external storage */
-    public abstract void setReadExternalStorageEnforced(boolean enforced);
-}
diff --git a/core/java/android/content/pm/PackageUserState.java b/core/java/android/content/pm/PackageUserState.java
index 249b691..5c74efb 100644
--- a/core/java/android/content/pm/PackageUserState.java
+++ b/core/java/android/content/pm/PackageUserState.java
@@ -31,6 +31,7 @@
 import android.os.BaseBundle;
 import android.os.Debug;
 import android.os.PersistableBundle;
+import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.DebugUtils;
 import android.util.Slog;
@@ -38,6 +39,11 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.ArrayUtils;
 
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import java.io.IOException;
 import java.util.Arrays;
 import java.util.Objects;
 
@@ -56,10 +62,7 @@
     public boolean hidden; // Is the app restricted by owner / admin
     public int distractionFlags;
     public boolean suspended;
-    public String suspendingPackage;
-    public SuspendDialogInfo dialogInfo;
-    public PersistableBundle suspendedAppExtras;
-    public PersistableBundle suspendedLauncherExtras;
+    public ArrayMap<String, SuspendParams> suspendParams; // Suspending package to suspend params
     public boolean instantApp;
     public boolean virtualPreload;
     public int enabled;
@@ -95,10 +98,7 @@
         hidden = o.hidden;
         distractionFlags = o.distractionFlags;
         suspended = o.suspended;
-        suspendingPackage = o.suspendingPackage;
-        dialogInfo = o.dialogInfo;
-        suspendedAppExtras = o.suspendedAppExtras;
-        suspendedLauncherExtras = o.suspendedLauncherExtras;
+        suspendParams = new ArrayMap<>(o.suspendParams);
         instantApp = o.instantApp;
         virtualPreload = o.virtualPreload;
         enabled = o.enabled;
@@ -231,19 +231,7 @@
             return false;
         }
         if (suspended) {
-            if (suspendingPackage == null
-                    || !suspendingPackage.equals(oldState.suspendingPackage)) {
-                return false;
-            }
-            if (!Objects.equals(dialogInfo, oldState.dialogInfo)) {
-                return false;
-            }
-            if (!BaseBundle.kindofEquals(suspendedAppExtras,
-                    oldState.suspendedAppExtras)) {
-                return false;
-            }
-            if (!BaseBundle.kindofEquals(suspendedLauncherExtras,
-                    oldState.suspendedLauncherExtras)) {
+            if (!Objects.equals(suspendParams, oldState.suspendParams)) {
                 return false;
             }
         }
@@ -308,4 +296,171 @@
         }
         return true;
     }
+
+    @Override
+    public int hashCode() {
+        int hashCode = Long.hashCode(ceDataInode);
+        hashCode = 31 * hashCode + Boolean.hashCode(installed);
+        hashCode = 31 * hashCode + Boolean.hashCode(stopped);
+        hashCode = 31 * hashCode + Boolean.hashCode(notLaunched);
+        hashCode = 31 * hashCode + Boolean.hashCode(hidden);
+        hashCode = 31 * hashCode + distractionFlags;
+        hashCode = 31 * hashCode + Boolean.hashCode(suspended);
+        hashCode = 31 * hashCode + Objects.hashCode(suspendParams);
+        hashCode = 31 * hashCode + Boolean.hashCode(instantApp);
+        hashCode = 31 * hashCode + Boolean.hashCode(virtualPreload);
+        hashCode = 31 * hashCode + enabled;
+        hashCode = 31 * hashCode + Objects.hashCode(lastDisableAppCaller);
+        hashCode = 31 * hashCode + domainVerificationStatus;
+        hashCode = 31 * hashCode + appLinkGeneration;
+        hashCode = 31 * hashCode + categoryHint;
+        hashCode = 31 * hashCode + installReason;
+        hashCode = 31 * hashCode + Objects.hashCode(disabledComponents);
+        hashCode = 31 * hashCode + Objects.hashCode(enabledComponents);
+        hashCode = 31 * hashCode + Objects.hashCode(harmfulAppWarning);
+        return hashCode;
+    }
+
+    /**
+     * Container to describe suspension parameters.
+     */
+    public static final class SuspendParams {
+        private static final String TAG_DIALOG_INFO = "dialog-info";
+        private static final String TAG_APP_EXTRAS = "app-extras";
+        private static final String TAG_LAUNCHER_EXTRAS = "launcher-extras";
+
+        public SuspendDialogInfo dialogInfo;
+        public PersistableBundle appExtras;
+        public PersistableBundle launcherExtras;
+
+        private SuspendParams() {
+        }
+
+        /**
+         * Returns a {@link SuspendParams} object with the given fields. Returns {@code null} if all
+         * the fields are {@code null}.
+         *
+         * @param dialogInfo
+         * @param appExtras
+         * @param launcherExtras
+         * @return A {@link SuspendParams} object or {@code null}.
+         */
+        public static SuspendParams getInstanceOrNull(SuspendDialogInfo dialogInfo,
+                PersistableBundle appExtras, PersistableBundle launcherExtras) {
+            if (dialogInfo == null && appExtras == null && launcherExtras == null) {
+                return null;
+            }
+            final SuspendParams instance = new SuspendParams();
+            instance.dialogInfo = dialogInfo;
+            instance.appExtras = appExtras;
+            instance.launcherExtras = launcherExtras;
+            return instance;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
+            }
+            if (!(obj instanceof SuspendParams)) {
+                return false;
+            }
+            final SuspendParams other = (SuspendParams) obj;
+            if (!Objects.equals(dialogInfo, other.dialogInfo)) {
+                return false;
+            }
+            if (!BaseBundle.kindofEquals(appExtras, other.appExtras)) {
+                return false;
+            }
+            if (!BaseBundle.kindofEquals(launcherExtras, other.launcherExtras)) {
+                return false;
+            }
+            return true;
+        }
+
+        @Override
+        public int hashCode() {
+            int hashCode = Objects.hashCode(dialogInfo);
+            hashCode = 31 * hashCode + ((appExtras != null) ? appExtras.size() : 0);
+            hashCode = 31 * hashCode + ((launcherExtras != null) ? launcherExtras.size() : 0);
+            return hashCode;
+        }
+
+        /**
+         * Serializes this object into an xml format
+         * @param out the {@link XmlSerializer} object
+         * @throws IOException
+         */
+        public void saveToXml(XmlSerializer out) throws IOException {
+            if (dialogInfo != null) {
+                out.startTag(null, TAG_DIALOG_INFO);
+                dialogInfo.saveToXml(out);
+                out.endTag(null, TAG_DIALOG_INFO);
+            }
+            if (appExtras != null) {
+                out.startTag(null, TAG_APP_EXTRAS);
+                try {
+                    appExtras.saveToXml(out);
+                } catch (XmlPullParserException e) {
+                    Slog.e(LOG_TAG, "Exception while trying to write appExtras."
+                            + " Will be lost on reboot", e);
+                }
+                out.endTag(null, TAG_APP_EXTRAS);
+            }
+            if (launcherExtras != null) {
+                out.startTag(null, TAG_LAUNCHER_EXTRAS);
+                try {
+                    launcherExtras.saveToXml(out);
+                } catch (XmlPullParserException e) {
+                    Slog.e(LOG_TAG, "Exception while trying to write launcherExtras."
+                            + " Will be lost on reboot", e);
+                }
+                out.endTag(null, TAG_LAUNCHER_EXTRAS);
+            }
+        }
+
+        /**
+         * Parses this object from the xml format. Returns {@code null} if no object related
+         * information could be read.
+         * @param in the reader
+         * @return
+         */
+        public static SuspendParams restoreFromXml(XmlPullParser in) throws IOException {
+            SuspendDialogInfo readDialogInfo = null;
+            PersistableBundle readAppExtras = null;
+            PersistableBundle readLauncherExtras = null;
+
+            final int currentDepth = in.getDepth();
+            int type;
+            try {
+                while ((type = in.next()) != XmlPullParser.END_DOCUMENT
+                        && (type != XmlPullParser.END_TAG
+                        || in.getDepth() > currentDepth)) {
+                    if (type == XmlPullParser.END_TAG
+                            || type == XmlPullParser.TEXT) {
+                        continue;
+                    }
+                    switch (in.getName()) {
+                        case TAG_DIALOG_INFO:
+                            readDialogInfo = SuspendDialogInfo.restoreFromXml(in);
+                            break;
+                        case TAG_APP_EXTRAS:
+                            readAppExtras = PersistableBundle.restoreFromXml(in);
+                            break;
+                        case TAG_LAUNCHER_EXTRAS:
+                            readLauncherExtras = PersistableBundle.restoreFromXml(in);
+                            break;
+                        default:
+                            Slog.w(LOG_TAG, "Unknown tag " + in.getName()
+                                    + " in SuspendParams. Ignoring");
+                            break;
+                    }
+                }
+            } catch (XmlPullParserException e) {
+                Slog.e(LOG_TAG, "Exception while trying to parse SuspendParams,"
+                        + " some fields may default", e);
+            }
+            return getInstanceOrNull(readDialogInfo, readAppExtras, readLauncherExtras);
+        }
+    }
 }
diff --git a/core/java/android/content/pm/SharedLibraryNames.java b/core/java/android/content/pm/SharedLibraryNames.java
index 4c66fc0..a607a9f 100644
--- a/core/java/android/content/pm/SharedLibraryNames.java
+++ b/core/java/android/content/pm/SharedLibraryNames.java
@@ -33,6 +33,4 @@
     static final String ANDROID_TEST_RUNNER = "android.test.runner";
 
     public static final String ORG_APACHE_HTTP_LEGACY = "org.apache.http.legacy";
-
-    public static final String ANDROID_TELEPHONY_COMMON = "telephony-common";
 }
diff --git a/core/java/android/content/pm/UserInfo.java b/core/java/android/content/pm/UserInfo.java
index e65d761..ccfa184 100644
--- a/core/java/android/content/pm/UserInfo.java
+++ b/core/java/android/content/pm/UserInfo.java
@@ -126,6 +126,13 @@
     public static final int FLAG_SYSTEM = 0x00000800;
 
     /**
+     * Indicates that this user is some sort of profile. Right now, the only profile type is
+     * {@link #FLAG_MANAGED_PROFILE}, but this can include other types of profiles too if any
+     * are created in the future. This is therefore not a flag, but an OR of several flags.
+     */
+    public static final int PROFILE_FLAGS_MASK = FLAG_MANAGED_PROFILE;
+
+    /**
      * @hide
      */
     @IntDef(flag = true, prefix = "FLAG_", value = {
@@ -180,6 +187,18 @@
     @UnsupportedAppUsage
     public boolean guestToRemove;
 
+    /**
+     * This is used to optimize the creation of an user, i.e. OEMs might choose to pre-create a
+     * number of users at the first boot, so the actual creation later is faster.
+     *
+     * <p>A {@code preCreated} user is not a real user yet, so it should not show up on regular
+     * user operations (other than user creation per se).
+     *
+     * <p>Once the pre-created is used to create a "real" user later on, {@code preCreate} is set to
+     * {@code false}.
+     */
+    public boolean preCreated;
+
     @UnsupportedAppUsage
     public UserInfo(int id, String name, int flags) {
         this(id, name, null, flags);
@@ -207,6 +226,13 @@
 
     @UnsupportedAppUsage
     public boolean isGuest() {
+        return isGuest(flags);
+    }
+
+    /**
+     * Checks if the flag denotes a guest user.
+     */
+    public static boolean isGuest(@UserInfoFlag int flags) {
         return (flags & FLAG_GUEST) == FLAG_GUEST;
     }
 
@@ -217,6 +243,13 @@
 
     @UnsupportedAppUsage
     public boolean isManagedProfile() {
+        return isManagedProfile(flags);
+    }
+
+    /**
+     * Checks if the flag denotes a managed profile.
+     */
+    public static boolean isManagedProfile(@UserInfoFlag int flags) {
         return (flags & FLAG_MANAGED_PROFILE) == FLAG_MANAGED_PROFILE;
     }
 
@@ -308,6 +341,7 @@
         lastLoggedInTime = orig.lastLoggedInTime;
         lastLoggedInFingerprint = orig.lastLoggedInFingerprint;
         partial = orig.partial;
+        preCreated = orig.preCreated;
         profileGroupId = orig.profileGroupId;
         restrictedProfileParentId = orig.restrictedProfileParentId;
         guestToRemove = orig.guestToRemove;
@@ -316,7 +350,7 @@
 
     @UnsupportedAppUsage
     public UserHandle getUserHandle() {
-        return new UserHandle(id);
+        return UserHandle.of(id);
     }
 
     @Override
@@ -332,6 +366,8 @@
         return "UserInfo[id=" + id
                 + ", name=" + name
                 + ", flags=" + flagsToString(flags)
+                + (preCreated ? " (pre-created)" : "")
+                + (partial ? " (partial)" : "")
                 + "]";
     }
 
@@ -355,9 +391,10 @@
         dest.writeLong(creationTime);
         dest.writeLong(lastLoggedInTime);
         dest.writeString(lastLoggedInFingerprint);
-        dest.writeInt(partial ? 1 : 0);
+        dest.writeBoolean(partial);
+        dest.writeBoolean(preCreated);
         dest.writeInt(profileGroupId);
-        dest.writeInt(guestToRemove ? 1 : 0);
+        dest.writeBoolean(guestToRemove);
         dest.writeInt(restrictedProfileParentId);
         dest.writeInt(profileBadge);
     }
@@ -382,9 +419,10 @@
         creationTime = source.readLong();
         lastLoggedInTime = source.readLong();
         lastLoggedInFingerprint = source.readString();
-        partial = source.readInt() != 0;
+        partial = source.readBoolean();
+        preCreated = source.readBoolean();
         profileGroupId = source.readInt();
-        guestToRemove = source.readInt() != 0;
+        guestToRemove = source.readBoolean();
         restrictedProfileParentId = source.readInt();
         profileBadge = source.readInt();
     }
diff --git a/core/java/android/content/res/ApkAssets.java b/core/java/android/content/res/ApkAssets.java
index 69462ab..a35ad56 100644
--- a/core/java/android/content/res/ApkAssets.java
+++ b/core/java/android/content/res/ApkAssets.java
@@ -188,7 +188,7 @@
     /**
      * Closes this class and the contained {@link #mStringBlock}.
      */
-    public void close() throws Throwable {
+    public void close() {
         synchronized (this) {
             if (mOpen) {
                 mOpen = false;
diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java
index 2420a61..7d6dc97 100644
--- a/core/java/android/content/res/AssetManager.java
+++ b/core/java/android/content/res/AssetManager.java
@@ -60,7 +60,6 @@
 public final class AssetManager implements AutoCloseable {
     private static final String TAG = "AssetManager";
     private static final boolean DEBUG_REFS = false;
-    private static final boolean FEATURE_FLAG_IDMAP2 = true;
 
     private static final String FRAMEWORK_APK_PATH = "/system/framework/framework-res.apk";
 
@@ -202,20 +201,14 @@
         try {
             final ArrayList<ApkAssets> apkAssets = new ArrayList<>();
             apkAssets.add(ApkAssets.loadFromPath(FRAMEWORK_APK_PATH, true /*system*/));
-            if (FEATURE_FLAG_IDMAP2) {
-                final String[] systemIdmapPaths =
-                    nativeCreateIdmapsForStaticOverlaysTargetingAndroid();
-                if (systemIdmapPaths != null) {
-                    for (String idmapPath : systemIdmapPaths) {
-                        apkAssets.add(ApkAssets.loadOverlayFromPath(idmapPath, true /*system*/));
-                    }
-                } else {
-                    Log.w(TAG, "'idmap2 --scan' failed: no static=\"true\" overlays targeting "
-                            + "\"android\" will be loaded");
+            final String[] systemIdmapPaths = nativeCreateIdmapsForStaticOverlaysTargetingAndroid();
+            if (systemIdmapPaths != null) {
+                for (String idmapPath : systemIdmapPaths) {
+                    apkAssets.add(ApkAssets.loadOverlayFromPath(idmapPath, true /*system*/));
                 }
             } else {
-                nativeVerifySystemIdmaps();
-                loadStaticRuntimeOverlays(apkAssets);
+                Log.w(TAG, "'idmap2 --scan' failed: no static=\"true\" overlays targeting "
+                        + "\"android\" will be loaded");
             }
 
             sSystemApkAssetsSet = new ArraySet<>(apkAssets);
@@ -1376,7 +1369,6 @@
     /**
      * @hide
      */
-    @TestApi
     @GuardedBy("this")
     public @Nullable Map<String, String> getOverlayableMap(String packageName) {
         synchronized (this) {
@@ -1385,6 +1377,18 @@
         }
     }
 
+    /**
+     * @hide
+     */
+    @TestApi
+    @GuardedBy("this")
+    public @Nullable String getOverlayablesToString(String packageName) {
+        synchronized (this) {
+            ensureValidLocked();
+            return nativeGetOverlayablesToString(mObject, packageName);
+        }
+    }
+
     @GuardedBy("this")
     private void incRefsLocked(long id) {
         if (DEBUG_REFS) {
@@ -1504,6 +1508,8 @@
     private static native String[] nativeCreateIdmapsForStaticOverlaysTargetingAndroid();
     private static native @Nullable Map nativeGetOverlayableMap(long ptr,
             @NonNull String packageName);
+    private static native @Nullable String nativeGetOverlayablesToString(long ptr,
+            @NonNull String packageName);
 
     // Global debug native methods.
     /**
diff --git a/core/java/android/content/res/StringBlock.java b/core/java/android/content/res/StringBlock.java
index b7bc822..2ae1932 100644
--- a/core/java/android/content/res/StringBlock.java
+++ b/core/java/android/content/res/StringBlock.java
@@ -175,7 +175,7 @@
         }
     }
 
-    public void close() throws Throwable {
+    public void close() {
         synchronized (this) {
             if (mOpen) {
                 mOpen = false;
diff --git a/core/java/android/hardware/biometrics/Authenticator.java b/core/java/android/hardware/biometrics/Authenticator.java
new file mode 100644
index 0000000..6d7e748
--- /dev/null
+++ b/core/java/android/hardware/biometrics/Authenticator.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 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.hardware.biometrics;
+
+/**
+ * Type of authenticators defined on a granularity that the BiometricManager / BiometricPrompt
+ * supports.
+ * @hide
+ */
+public class Authenticator {
+
+    /**
+     * Device credential, e.g. Pin/Pattern/Password.
+     */
+    public static final int TYPE_CREDENTIAL = 1 << 0;
+    /**
+     * Encompasses all biometrics on the device, e.g. Fingerprint/Iris/Face.
+     */
+    public static final int TYPE_BIOMETRIC = 1 << 1;
+
+}
diff --git a/core/java/android/hardware/biometrics/BiometricManager.java b/core/java/android/hardware/biometrics/BiometricManager.java
index d8110f3..cbe8a05 100644
--- a/core/java/android/hardware/biometrics/BiometricManager.java
+++ b/core/java/android/hardware/biometrics/BiometricManager.java
@@ -201,55 +201,5 @@
         }
     }
 
-    /**
-     * TODO(b/123378871): Remove when moved.
-     * @hide
-     */
-    @RequiresPermission(USE_BIOMETRIC_INTERNAL)
-    public void onConfirmDeviceCredentialSuccess() {
-        if (mService != null) {
-            try {
-                mService.onConfirmDeviceCredentialSuccess();
-            } catch (RemoteException e) {
-                throw e.rethrowFromSystemServer();
-            }
-        } else {
-            Slog.w(TAG, "onConfirmDeviceCredentialSuccess(): Service not connected");
-        }
-    }
-
-    /**
-     * TODO(b/123378871): Remove when moved.
-     * @hide
-     */
-    @RequiresPermission(USE_BIOMETRIC_INTERNAL)
-    public void onConfirmDeviceCredentialError(int error, String message) {
-        if (mService != null) {
-            try {
-                mService.onConfirmDeviceCredentialError(error, message);
-            } catch (RemoteException e) {
-                throw e.rethrowFromSystemServer();
-            }
-        } else {
-            Slog.w(TAG, "onConfirmDeviceCredentialError(): Service not connected");
-        }
-    }
-
-    /**
-     * TODO(b/123378871): Remove when moved.
-     * @hide
-     */
-    @RequiresPermission(USE_BIOMETRIC_INTERNAL)
-    public void registerCancellationCallback(IBiometricConfirmDeviceCredentialCallback callback) {
-        if (mService != null) {
-            try {
-                mService.registerCancellationCallback(callback);
-            } catch (RemoteException e) {
-                throw e.rethrowFromSystemServer();
-            }
-        } else {
-            Slog.w(TAG, "registerCancellationCallback(): Service not connected");
-        }
-    }
 }
 
diff --git a/core/java/android/hardware/biometrics/BiometricPrompt.java b/core/java/android/hardware/biometrics/BiometricPrompt.java
index fb6b231..cf86e251 100644
--- a/core/java/android/hardware/biometrics/BiometricPrompt.java
+++ b/core/java/android/hardware/biometrics/BiometricPrompt.java
@@ -69,24 +69,21 @@
     /**
      * @hide
      */
-    public static final String KEY_POSITIVE_TEXT = "positive_text";
-    /**
-     * @hide
-     */
     public static final String KEY_NEGATIVE_TEXT = "negative_text";
     /**
      * @hide
      */
     public static final String KEY_REQUIRE_CONFIRMATION = "require_confirmation";
     /**
+     * This is deprecated. Internally we should use {@link #KEY_AUTHENTICATORS_ALLOWED}
      * @hide
      */
     public static final String KEY_ALLOW_DEVICE_CREDENTIAL = "allow_device_credential";
     /**
+     * If this key is set, we will ignore {@link #KEY_ALLOW_DEVICE_CREDENTIAL}
      * @hide
      */
-    public static final String KEY_FROM_CONFIRM_DEVICE_CREDENTIAL
-            = "from_confirm_device_credential";
+    public static final String KEY_AUTHENTICATORS_ALLOWED = "authenticators_allowed";
 
     /**
      * Error/help message will show for this amount of time.
@@ -100,7 +97,7 @@
     /**
      * @hide
      */
-    public static final int DISMISSED_REASON_CONFIRMED = 1;
+    public static final int DISMISSED_REASON_BIOMETRIC_CONFIRMED = 1;
 
     /**
      * Dialog is done animating away after user clicked on the button set via
@@ -119,7 +116,7 @@
      * Authenticated, confirmation not required. Dialog animated away.
      * @hide
      */
-    public static final int DISMISSED_REASON_CONFIRM_NOT_REQUIRED = 4;
+    public static final int DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED = 4;
 
     /**
      * Error message shown on SystemUI. When BiometricService receives this, the UI is already
@@ -134,6 +131,11 @@
      */
     public static final int DISMISSED_REASON_SERVER_REQUESTED = 6;
 
+    /**
+     * @hide
+     */
+    public static final int DISMISSED_REASON_CREDENTIAL_CONFIRMED = 7;
+
     private static class ButtonInfo {
         Executor executor;
         DialogInterface.OnClickListener listener;
@@ -203,30 +205,6 @@
         }
 
         /**
-         * Optional: Set the text for the positive button. If not set, the positive button
-         * will not show.
-         * @param text
-         * @return
-         * @hide
-         */
-        @NonNull public Builder setPositiveButton(@NonNull CharSequence text,
-                @NonNull @CallbackExecutor Executor executor,
-                @NonNull DialogInterface.OnClickListener listener) {
-            if (TextUtils.isEmpty(text)) {
-                throw new IllegalArgumentException("Text must be set and non-empty");
-            }
-            if (executor == null) {
-                throw new IllegalArgumentException("Executor must not be null");
-            }
-            if (listener == null) {
-                throw new IllegalArgumentException("Listener must not be null");
-            }
-            mBundle.putCharSequence(KEY_POSITIVE_TEXT, text);
-            mPositiveButtonInfo = new ButtonInfo(executor, listener);
-            return this;
-        }
-
-        /**
          * Required: Set the text for the negative button. This would typically be used as a
          * "Cancel" button, but may be also used to show an alternative method for authentication,
          * such as screen that asks for a backup password.
@@ -298,17 +276,6 @@
         }
 
         /**
-         * TODO(123378871): Remove when moved.
-         * @return
-         * @hide
-         */
-        @RequiresPermission(USE_BIOMETRIC_INTERNAL)
-        @NonNull public Builder setFromConfirmDeviceCredential() {
-            mBundle.putBoolean(KEY_FROM_CONFIRM_DEVICE_CREDENTIAL, true);
-            return this;
-        }
-
-        /**
          * Creates a {@link BiometricPrompt}.
          * @return a {@link BiometricPrompt}
          * @throws IllegalArgumentException if any of the required fields are not set.
@@ -317,15 +284,19 @@
             final CharSequence title = mBundle.getCharSequence(KEY_TITLE);
             final CharSequence negative = mBundle.getCharSequence(KEY_NEGATIVE_TEXT);
             final boolean useDefaultTitle = mBundle.getBoolean(KEY_USE_DEFAULT_TITLE);
-            final boolean enableFallback = mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL);
+            final boolean allowCredential = mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL);
+            final Object authenticatorsAllowed = mBundle.get(KEY_AUTHENTICATORS_ALLOWED);
 
             if (TextUtils.isEmpty(title) && !useDefaultTitle) {
                 throw new IllegalArgumentException("Title must be set and non-empty");
-            } else if (TextUtils.isEmpty(negative) && !enableFallback) {
+            } else if (TextUtils.isEmpty(negative) && !allowCredential) {
                 throw new IllegalArgumentException("Negative text must be set and non-empty");
-            } else if (!TextUtils.isEmpty(negative) && enableFallback) {
+            } else if (!TextUtils.isEmpty(negative) && allowCredential) {
                 throw new IllegalArgumentException("Can't have both negative button behavior"
                         + " and device credential enabled");
+            } else if (authenticatorsAllowed != null && allowCredential) {
+                throw new IllegalArgumentException("setAuthenticatorsAllowed and"
+                        + " setDeviceCredentialAllowed should not be used simultaneously");
             }
             return new BiometricPrompt(mContext, mBundle, mPositiveButtonInfo, mNegativeButtonInfo);
         }
@@ -384,7 +355,7 @@
         @Override
         public void onDialogDismissed(int reason) throws RemoteException {
             // Check the reason and invoke OnClickListener(s) if necessary
-            if (reason == DISMISSED_REASON_CONFIRMED) {
+            if (reason == DISMISSED_REASON_BIOMETRIC_CONFIRMED) {
                 mPositiveButtonInfo.executor.execute(() -> {
                     mPositiveButtonInfo.listener.onClick(null, DialogInterface.BUTTON_POSITIVE);
                 });
@@ -532,8 +503,7 @@
     public void authenticateUser(@NonNull CancellationSignal cancel,
             @NonNull @CallbackExecutor Executor executor,
             @NonNull AuthenticationCallback callback,
-            int userId,
-            IBiometricConfirmDeviceCredentialCallback confirmDeviceCredentialCallback) {
+            int userId) {
         if (cancel == null) {
             throw new IllegalArgumentException("Must supply a cancellation signal");
         }
@@ -543,8 +513,7 @@
         if (callback == null) {
             throw new IllegalArgumentException("Must supply a callback");
         }
-        authenticateInternal(null /* crypto */, cancel, executor, callback, userId,
-                confirmDeviceCredentialCallback);
+        authenticateInternal(null /* crypto */, cancel, executor, callback, userId);
     }
 
     /**
@@ -595,8 +564,7 @@
         if (mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL)) {
             throw new IllegalArgumentException("Device credential not supported with crypto");
         }
-        authenticateInternal(crypto, cancel, executor, callback, mContext.getUserId(),
-                null /* confirmDeviceCredentialCallback */);
+        authenticateInternal(crypto, cancel, executor, callback, mContext.getUserId());
     }
 
     /**
@@ -638,8 +606,7 @@
         if (callback == null) {
             throw new IllegalArgumentException("Must supply a callback");
         }
-        authenticateInternal(null /* crypto */, cancel, executor, callback, mContext.getUserId(),
-                null /* confirmDeviceCredentialCallback */);
+        authenticateInternal(null /* crypto */, cancel, executor, callback, mContext.getUserId());
     }
 
     private void cancelAuthentication() {
@@ -656,8 +623,7 @@
             @NonNull CancellationSignal cancel,
             @NonNull @CallbackExecutor Executor executor,
             @NonNull AuthenticationCallback callback,
-            int userId,
-            IBiometricConfirmDeviceCredentialCallback confirmDeviceCredentialCallback) {
+            int userId) {
         try {
             if (cancel.isCanceled()) {
                 Log.w(TAG, "Authentication already canceled");
@@ -672,7 +638,7 @@
             final long sessionId = crypto != null ? crypto.getOpId() : 0;
             if (BiometricManager.hasBiometrics(mContext)) {
                 mService.authenticate(mToken, sessionId, userId, mBiometricServiceReceiver,
-                        mContext.getOpPackageName(), mBundle, confirmDeviceCredentialCallback);
+                        mContext.getOpPackageName(), mBundle);
             } else {
                 mExecutor.execute(() -> {
                     callback.onAuthenticationError(BiometricPrompt.BIOMETRIC_ERROR_HW_NOT_PRESENT,
diff --git a/core/java/android/hardware/biometrics/IBiometricConfirmDeviceCredentialCallback.aidl b/core/java/android/hardware/biometrics/IBiometricConfirmDeviceCredentialCallback.aidl
deleted file mode 100644
index 8b35852..0000000
--- a/core/java/android/hardware/biometrics/IBiometricConfirmDeviceCredentialCallback.aidl
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2019 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.hardware.biometrics;
-
-/**
- * Communication channel between ConfirmDeviceCredential / ConfirmLock* and BiometricService.
- * @hide
- */
-interface IBiometricConfirmDeviceCredentialCallback {
-    // Invoked when authentication should be canceled.
-    oneway void cancel();
-}
\ No newline at end of file
diff --git a/core/java/android/hardware/biometrics/IBiometricService.aidl b/core/java/android/hardware/biometrics/IBiometricService.aidl
index f0a0b2f..6a3bf38 100644
--- a/core/java/android/hardware/biometrics/IBiometricService.aidl
+++ b/core/java/android/hardware/biometrics/IBiometricService.aidl
@@ -17,7 +17,6 @@
 package android.hardware.biometrics;
 
 import android.os.Bundle;
-import android.hardware.biometrics.IBiometricConfirmDeviceCredentialCallback;
 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
 import android.hardware.biometrics.IBiometricServiceReceiver;
 
@@ -31,10 +30,8 @@
 interface IBiometricService {
     // Requests authentication. The service choose the appropriate biometric to use, and show
     // the corresponding BiometricDialog.
-    // TODO(b/123378871): Remove callback when moved.
     void authenticate(IBinder token, long sessionId, int userId,
-            IBiometricServiceReceiver receiver, String opPackageName, in Bundle bundle,
-            IBiometricConfirmDeviceCredentialCallback callback);
+            IBiometricServiceReceiver receiver, String opPackageName, in Bundle bundle);
 
     // Cancel authentication for the given sessionId
     void cancelAuthentication(IBinder token, String opPackageName);
@@ -57,16 +54,4 @@
 
     // Reset the lockout when user authenticates with strong auth (e.g. PIN, pattern or password)
     void resetLockout(in byte [] token);
-
-    // TODO(b/123378871): Remove when moved.
-    // CDCA needs to send results to BiometricService if it was invoked using BiometricPrompt's
-    // setAllowDeviceCredential method, since there's no way for us to intercept onActivityResult.
-    // CDCA is launched from BiometricService (startActivityAsUser) instead of *ForResult.
-    void onConfirmDeviceCredentialSuccess();
-    // TODO(b/123378871): Remove when moved.
-    void onConfirmDeviceCredentialError(int error, String message);
-    // TODO(b/123378871): Remove when moved.
-    // When ConfirmLock* is invoked from BiometricPrompt, it needs to register a callback so that
-    // it can receive the cancellation signal.
-    void registerCancellationCallback(IBiometricConfirmDeviceCredentialCallback callback);
 }
diff --git a/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl b/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl
index ca6114e..66b6e89 100644
--- a/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl
+++ b/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl
@@ -38,4 +38,6 @@
     void onDialogDismissed(int reason);
     // Notifies that the user has pressed the "try again" button on SystemUI
     void onTryAgainPressed();
+    // Notifies that the user has pressed the "use password" button on SystemUI
+    void onDeviceCredentialPressed();
 }
diff --git a/core/java/android/hardware/camera2/CameraManager.java b/core/java/android/hardware/camera2/CameraManager.java
index c8276b2..fc90096 100644
--- a/core/java/android/hardware/camera2/CameraManager.java
+++ b/core/java/android/hardware/camera2/CameraManager.java
@@ -21,6 +21,7 @@
 import android.annotation.Nullable;
 import android.annotation.RequiresPermission;
 import android.annotation.SystemService;
+import android.annotation.TestApi;
 import android.content.Context;
 import android.hardware.CameraInfo;
 import android.hardware.CameraStatus;
@@ -47,6 +48,7 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Comparator;
+import java.util.Set;
 import java.util.concurrent.Executor;
 import java.util.concurrent.Executors;
 import java.util.concurrent.RejectedExecutionException;
@@ -109,6 +111,21 @@
     }
 
     /**
+     * Similar to getCameraIdList(). However, getCamerIdListNoLazy() necessarily communicates with
+     * cameraserver in order to get the list of camera ids. This is to faciliate testing since some
+     * camera ids may go 'offline' without callbacks from cameraserver because of changes in
+     * SYSTEM_CAMERA permissions (though this is not a changeable permission, tests may call
+     * adopt(drop)ShellPermissionIdentity() and effectively change their permissions). This call
+     * affects the camera ids returned by getCameraIdList() as well. Tests which do adopt shell
+     * permission identity should not mix getCameraIdList() and getCameraListNoLazyCalls().
+     */
+    /** @hide */
+    @TestApi
+    public String[] getCameraIdListNoLazy() throws CameraAccessException {
+        return CameraManagerGlobal.get().getCameraIdListNoLazy();
+    }
+
+    /**
      * Register a callback to be notified about camera device availability.
      *
      * <p>Registering the same callback again will replace the handler with the
@@ -995,35 +1012,27 @@
                 // Camera service is now down, leave mCameraService as null
             }
         }
-
-        /**
-         * Get a list of all camera IDs that are at least PRESENT; ignore devices that are
-         * NOT_PRESENT or ENUMERATING, since they cannot be used by anyone.
-         */
-        public String[] getCameraIdList() {
+        private String[] extractCameraIdListLocked() {
             String[] cameraIds = null;
-            synchronized(mLock) {
-                // Try to make sure we have an up-to-date list of camera devices.
-                connectCameraServiceLocked();
-
-                int idCount = 0;
-                for (int i = 0; i < mDeviceStatus.size(); i++) {
-                    int status = mDeviceStatus.valueAt(i);
-                    if (status == ICameraServiceListener.STATUS_NOT_PRESENT ||
-                            status == ICameraServiceListener.STATUS_ENUMERATING) continue;
-                    idCount++;
-                }
-                cameraIds = new String[idCount];
-                idCount = 0;
-                for (int i = 0; i < mDeviceStatus.size(); i++) {
-                    int status = mDeviceStatus.valueAt(i);
-                    if (status == ICameraServiceListener.STATUS_NOT_PRESENT ||
-                            status == ICameraServiceListener.STATUS_ENUMERATING) continue;
-                    cameraIds[idCount] = mDeviceStatus.keyAt(i);
-                    idCount++;
-                }
+            int idCount = 0;
+            for (int i = 0; i < mDeviceStatus.size(); i++) {
+                int status = mDeviceStatus.valueAt(i);
+                if (status == ICameraServiceListener.STATUS_NOT_PRESENT
+                        || status == ICameraServiceListener.STATUS_ENUMERATING) continue;
+                idCount++;
             }
-
+            cameraIds = new String[idCount];
+            idCount = 0;
+            for (int i = 0; i < mDeviceStatus.size(); i++) {
+                int status = mDeviceStatus.valueAt(i);
+                if (status == ICameraServiceListener.STATUS_NOT_PRESENT
+                        || status == ICameraServiceListener.STATUS_ENUMERATING) continue;
+                cameraIds[idCount] = mDeviceStatus.keyAt(i);
+                idCount++;
+            }
+            return cameraIds;
+        }
+        private static void sortCameraIds(String[] cameraIds) {
             // The sort logic must match the logic in
             // libcameraservice/common/CameraProviderManager.cpp::getAPI1CompatibleCameraDeviceIds
             Arrays.sort(cameraIds, new Comparator<String>() {
@@ -1054,6 +1063,89 @@
                             return s1.compareTo(s2);
                         }
                     }});
+
+        }
+
+        public static boolean cameraStatusesContains(CameraStatus[] cameraStatuses, String id) {
+            for (CameraStatus c : cameraStatuses) {
+                if (c.cameraId.equals(id)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        public String[] getCameraIdListNoLazy() {
+            CameraStatus[] cameraStatuses;
+            ICameraServiceListener.Stub testListener = new ICameraServiceListener.Stub() {
+                @Override
+                public void onStatusChanged(int status, String id) throws RemoteException {
+                }
+                @Override
+                public void onTorchStatusChanged(int status, String id) throws RemoteException {
+                }
+                @Override
+                public void onCameraAccessPrioritiesChanged() {
+                }};
+
+            String[] cameraIds = null;
+            synchronized (mLock) {
+                connectCameraServiceLocked();
+                try {
+                    // The purpose of the addListener, removeListener pair here is to get a fresh
+                    // list of camera ids from cameraserver. We do this since for in test processes,
+                    // changes can happen w.r.t non-changeable permissions (eg: SYSTEM_CAMERA
+                    // permissions can be effectively changed by calling
+                    // adopt(drop)ShellPermissionIdentity()).
+                    // Camera devices, which have their discovery affected by these permission
+                    // changes, will not have clients get callbacks informing them about these
+                    // devices going offline (in real world scenarios, these permissions aren't
+                    // changeable). Future calls to getCameraIdList() will reflect the changes in
+                    // the camera id list after getCameraIdListNoLazy() is called.
+                    cameraStatuses = mCameraService.addListener(testListener);
+                    mCameraService.removeListener(testListener);
+                    for (CameraStatus c : cameraStatuses) {
+                        onStatusChangedLocked(c.status, c.cameraId);
+                    }
+                    Set<String> deviceCameraIds = mDeviceStatus.keySet();
+                    ArrayList<String> deviceIdsToRemove = new ArrayList<String>();
+                    for (String deviceCameraId : deviceCameraIds) {
+                        // Its possible that a device id was removed without a callback notifying
+                        // us. This may happen in case a process 'drops' system camera permissions
+                        // (even though the permission isn't a changeable one, tests may call
+                        // adoptShellPermissionIdentity() and then dropShellPermissionIdentity().
+                        if (!cameraStatusesContains(cameraStatuses, deviceCameraId)) {
+                            deviceIdsToRemove.add(deviceCameraId);
+                        }
+                    }
+                    for (String id : deviceIdsToRemove) {
+                        onStatusChangedLocked(ICameraServiceListener.STATUS_NOT_PRESENT, id);
+                    }
+                } catch (ServiceSpecificException e) {
+                    // Unexpected failure
+                    throw new IllegalStateException("Failed to register a camera service listener",
+                            e);
+                } catch (RemoteException e) {
+                    // Camera service is now down, leave mCameraService as null
+                }
+                cameraIds = extractCameraIdListLocked();
+            }
+            sortCameraIds(cameraIds);
+            return cameraIds;
+        }
+
+        /**
+         * Get a list of all camera IDs that are at least PRESENT; ignore devices that are
+         * NOT_PRESENT or ENUMERATING, since they cannot be used by anyone.
+         */
+        public String[] getCameraIdList() {
+            String[] cameraIds = null;
+            synchronized (mLock) {
+                // Try to make sure we have an up-to-date list of camera devices.
+                connectCameraServiceLocked();
+                cameraIds = extractCameraIdListLocked();
+            }
+            sortCameraIds(cameraIds);
             return cameraIds;
         }
 
diff --git a/core/java/android/hardware/input/IInputManager.aidl b/core/java/android/hardware/input/IInputManager.aidl
index 0daf30f25..638d81b 100644
--- a/core/java/android/hardware/input/IInputManager.aidl
+++ b/core/java/android/hardware/input/IInputManager.aidl
@@ -76,6 +76,9 @@
     // Registers a tablet mode change listener
     void registerTabletModeChangedListener(ITabletModeChangedListener listener);
 
+    // Queries whether the device's microphone is muted by switch
+    int isMicMuted();
+
     // Input device vibrator control.
     void vibrate(int deviceId, in long[] pattern, int repeat, IBinder token);
     void cancelVibrate(int deviceId, IBinder token);
diff --git a/core/java/android/hardware/input/InputManager.java b/core/java/android/hardware/input/InputManager.java
index 2a59be2..0c0f248 100644
--- a/core/java/android/hardware/input/InputManager.java
+++ b/core/java/android/hardware/input/InputManager.java
@@ -520,6 +520,22 @@
     }
 
     /**
+     * Queries whether the device's microphone is muted
+     *
+     * @return The mic mute switch state which is one of {@link #SWITCH_STATE_UNKNOWN},
+     * {@link #SWITCH_STATE_OFF} or {@link #SWITCH_STATE_ON}.
+     * @hide
+     */
+    @SwitchState
+    public int isMicMuted() {
+        try {
+            return mIm.isMicMuted();
+        } catch (RemoteException ex) {
+            throw ex.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Gets information about all supported keyboard layouts.
      * <p>
      * The input manager consults the built-in keyboard layouts as well
diff --git a/core/java/android/hardware/location/ContextHubClientCallback.java b/core/java/android/hardware/location/ContextHubClientCallback.java
index cc2fe65..20fa753 100644
--- a/core/java/android/hardware/location/ContextHubClientCallback.java
+++ b/core/java/android/hardware/location/ContextHubClientCallback.java
@@ -66,7 +66,9 @@
     public void onNanoAppAborted(ContextHubClient client, long nanoAppId, int abortCode) {}
 
     /**
-     * Callback invoked when a nanoapp is loaded at the attached Context Hub.
+     * Callback invoked when a nanoapp is dynamically loaded at the attached Context Hub through
+     * the {@link android.hardware.location.ContextHubManager}. This callback is not invoked for a
+     * nanoapp that is loaded internally by CHRE (e.g. nanoapps that are preloaded by the system).
      *
      * @param client the client that is associated with this callback
      * @param nanoAppId the ID of the nanoapp that had been loaded
@@ -74,7 +76,8 @@
     public void onNanoAppLoaded(ContextHubClient client, long nanoAppId) {}
 
     /**
-     * Callback invoked when a nanoapp is unloaded from the attached Context Hub.
+     * Callback invoked when a nanoapp is dynamically unloaded from the attached Context Hub through
+     * the {@link android.hardware.location.ContextHubManager}.
      *
      * @param client the client that is associated with this callback
      * @param nanoAppId the ID of the nanoapp that had been unloaded
@@ -82,7 +85,8 @@
     public void onNanoAppUnloaded(ContextHubClient client, long nanoAppId) {}
 
     /**
-     * Callback invoked when a nanoapp is enabled at the attached Context Hub.
+     * Callback invoked when a nanoapp is dynamically enabled at the attached Context Hub through
+     * the {@link android.hardware.location.ContextHubManager}.
      *
      * @param client the client that is associated with this callback
      * @param nanoAppId the ID of the nanoapp that had been enabled
@@ -90,7 +94,8 @@
     public void onNanoAppEnabled(ContextHubClient client, long nanoAppId) {}
 
     /**
-     * Callback invoked when a nanoapp is disabled at the attached Context Hub.
+     * Callback invoked when a nanoapp is dynamically disabled at the attached Context Hub through
+     * the {@link android.hardware.location.ContextHubManager}.
      *
      * @param client the client that is associated with this callback
      * @param nanoAppId the ID of the nanoapp that had been disabled
diff --git a/core/java/android/hardware/usb/UsbDevice.java b/core/java/android/hardware/usb/UsbDevice.java
index 08c9eea..11f4ffb 100644
--- a/core/java/android/hardware/usb/UsbDevice.java
+++ b/core/java/android/hardware/usb/UsbDevice.java
@@ -60,6 +60,9 @@
     private final int mClass;
     private final int mSubclass;
     private final int mProtocol;
+    private final boolean mHasAudioPlayback;
+    private final boolean mHasAudioCapture;
+    private final boolean mHasMidi;
 
     /** All interfaces on the device. Initialized on first call to getInterfaceList */
     @UnsupportedAppUsage
@@ -73,7 +76,8 @@
     private UsbDevice(@NonNull String name, int vendorId, int productId, int Class, int subClass,
             int protocol, @Nullable String manufacturerName, @Nullable String productName,
             @NonNull String version, @NonNull UsbConfiguration[] configurations,
-            @NonNull IUsbSerialReader serialNumberReader) {
+            @NonNull IUsbSerialReader serialNumberReader,
+            boolean hasAudioPlayback, boolean hasAudioCapture, boolean hasMidi) {
         mName = Preconditions.checkNotNull(name);
         mVendorId = vendorId;
         mProductId = productId;
@@ -85,6 +89,9 @@
         mVersion = Preconditions.checkStringNotEmpty(version);
         mConfigurations = Preconditions.checkArrayElementsNotNull(configurations, "configurations");
         mSerialNumberReader = Preconditions.checkNotNull(serialNumberReader);
+        mHasAudioPlayback = hasAudioPlayback;
+        mHasAudioCapture = hasAudioCapture;
+        mHasMidi = hasMidi;
 
         // Make sure the binder belongs to the system
         if (ActivityThread.isSystem()) {
@@ -214,6 +221,21 @@
         return mConfigurations.length;
     }
 
+    /** @hide */
+    public boolean getHasAudioPlayback() {
+        return mHasAudioPlayback;
+    }
+
+    /** @hide */
+    public boolean getHasAudioCapture() {
+        return mHasAudioCapture;
+    }
+
+    /** @hide */
+    public boolean getHasMidi() {
+        return mHasMidi;
+    }
+
     /**
      * Returns the {@link UsbConfiguration} at the given index.
      *
@@ -286,12 +308,15 @@
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder("UsbDevice[mName=" + mName +
-                ",mVendorId=" + mVendorId + ",mProductId=" + mProductId +
-                ",mClass=" + mClass + ",mSubclass=" + mSubclass + ",mProtocol=" + mProtocol +
-                ",mManufacturerName=" + mManufacturerName + ",mProductName=" + mProductName +
-                ",mVersion=" + mVersion + ",mSerialNumberReader=" + mSerialNumberReader
-                + ",mConfigurations=[");
+        StringBuilder builder = new StringBuilder("UsbDevice[mName=" + mName
+                + ",mVendorId=" + mVendorId + ",mProductId=" + mProductId
+                + ",mClass=" + mClass + ",mSubclass=" + mSubclass + ",mProtocol=" + mProtocol
+                + ",mManufacturerName=" + mManufacturerName + ",mProductName=" + mProductName
+                + ",mVersion=" + mVersion + ",mSerialNumberReader=" + mSerialNumberReader
+                + ", mHasAudioPlayback=" + mHasAudioPlayback
+                + ", mHasAudioCapture=" + mHasAudioCapture
+                + ", mHasMidi=" + mHasMidi
+                + ", mConfigurations=[");
         for (int i = 0; i < mConfigurations.length; i++) {
             builder.append("\n");
             builder.append(mConfigurations[i].toString());
@@ -316,9 +341,15 @@
                     IUsbSerialReader.Stub.asInterface(in.readStrongBinder());
             UsbConfiguration[] configurations = in.readParcelableArray(
                     UsbConfiguration.class.getClassLoader(), UsbConfiguration.class);
+            // Capabilities
+            boolean hasAudioPlayback = in.readInt() == 1;
+            boolean hasAudioCapture = in.readInt() == 1;
+            boolean hasMidi = in.readInt() == 1;
+
             UsbDevice device = new UsbDevice(name, vendorId, productId, clasz, subClass, protocol,
-                                 manufacturerName, productName, version, configurations,
-                    serialNumberReader);
+                    manufacturerName, productName, version, configurations, serialNumberReader,
+                    hasAudioPlayback, hasAudioCapture, hasMidi);
+
             return device;
         }
 
@@ -343,7 +374,10 @@
         parcel.writeString(mVersion);
         parcel.writeStrongBinder(mSerialNumberReader.asBinder());
         parcel.writeParcelableArray(mConfigurations, 0);
-   }
+        parcel.writeInt(mHasAudioPlayback ? 1 : 0);
+        parcel.writeInt(mHasAudioCapture ? 1 : 0);
+        parcel.writeInt(mHasMidi ? 1 : 0);
+    }
 
     public static int getDeviceId(String name) {
         return native_get_device_id(name);
@@ -370,6 +404,9 @@
         private final @Nullable String mProductName;
         private final @NonNull String mVersion;
         private final @NonNull UsbConfiguration[] mConfigurations;
+        private final boolean mHasAudioPlayback;
+        private final boolean mHasAudioCapture;
+        private final boolean mHasMidi;
 
         // Temporary storage for serial number. Serial number reader need to be wrapped in a
         // IUsbSerialReader as they might be used as PII.
@@ -378,7 +415,8 @@
         public Builder(@NonNull String name, int vendorId, int productId, int Class, int subClass,
                 int protocol, @Nullable String manufacturerName, @Nullable String productName,
                 @NonNull String version, @NonNull UsbConfiguration[] configurations,
-                @Nullable String serialNumber) {
+                @Nullable String serialNumber,
+                boolean hasAudioPlayback, boolean hasAudioCapture, boolean hasMidi) {
             mName = Preconditions.checkNotNull(name);
             mVendorId = vendorId;
             mProductId = productId;
@@ -390,6 +428,9 @@
             mVersion = Preconditions.checkStringNotEmpty(version);
             mConfigurations = configurations;
             this.serialNumber = serialNumber;
+            mHasAudioPlayback = hasAudioPlayback;
+            mHasAudioCapture = hasAudioCapture;
+            mHasMidi = hasMidi;
         }
 
         /**
@@ -401,7 +442,8 @@
          */
         public UsbDevice build(@NonNull IUsbSerialReader serialReader) {
             return new UsbDevice(mName, mVendorId, mProductId, mClass, mSubclass, mProtocol,
-                    mManufacturerName, mProductName, mVersion, mConfigurations, serialReader);
+                    mManufacturerName, mProductName, mVersion, mConfigurations, serialReader,
+                    mHasAudioPlayback, mHasAudioCapture, mHasMidi);
         }
     }
 }
diff --git a/core/java/android/net/LinkProperties.java b/core/java/android/net/LinkProperties.java
index d3f48ac..3ec0aea 100644
--- a/core/java/android/net/LinkProperties.java
+++ b/core/java/android/net/LinkProperties.java
@@ -68,6 +68,7 @@
     // in the format "rmem_min,rmem_def,rmem_max,wmem_min,wmem_def,wmem_max"
     private String mTcpBufferSizes;
     private IpPrefix mNat64Prefix;
+    private boolean mWakeOnLanSupported;
 
     private static final int MIN_MTU    = 68;
     private static final int MIN_MTU_V6 = 1280;
@@ -193,6 +194,7 @@
             setMtu(source.mMtu);
             mTcpBufferSizes = source.mTcpBufferSizes;
             mNat64Prefix = source.mNat64Prefix;
+            mWakeOnLanSupported = source.mWakeOnLanSupported;
         }
     }
 
@@ -852,6 +854,7 @@
         mMtu = 0;
         mTcpBufferSizes = null;
         mNat64Prefix = null;
+        mWakeOnLanSupported = false;
     }
 
     /**
@@ -913,6 +916,10 @@
         resultJoiner.add("MTU:");
         resultJoiner.add(Integer.toString(mMtu));
 
+        if (mWakeOnLanSupported) {
+            resultJoiner.add("WakeOnLanSupported: true");
+        }
+
         if (mTcpBufferSizes != null) {
             resultJoiner.add("TcpBufferSizes:");
             resultJoiner.add(mTcpBufferSizes);
@@ -1425,6 +1432,37 @@
     }
 
     /**
+     * Compares this {@code LinkProperties} WakeOnLan supported against the target.
+     *
+     * @param target LinkProperties to compare.
+     * @return {@code true} if both are identical, {@code false} otherwise.
+     * @hide
+     */
+    public boolean isIdenticalWakeOnLan(LinkProperties target) {
+        return isWakeOnLanSupported() == target.isWakeOnLanSupported();
+    }
+
+    /**
+     * Set whether the network interface supports WakeOnLAN
+     *
+     * @param supported WakeOnLAN supported value
+     *
+     * @hide
+     */
+    public void setWakeOnLanSupported(boolean supported) {
+        mWakeOnLanSupported = supported;
+    }
+
+    /**
+     * Returns whether the network interface supports WakeOnLAN
+     *
+     * @return {@code true} if interface supports WakeOnLAN, {@code false} otherwise.
+     */
+    public boolean isWakeOnLanSupported() {
+        return mWakeOnLanSupported;
+    }
+
+    /**
      * Compares this {@code LinkProperties} instance against the target
      * LinkProperties in {@code obj}. Two LinkPropertieses are equal if
      * all their fields are equal in values.
@@ -1461,7 +1499,8 @@
                 && isIdenticalStackedLinks(target)
                 && isIdenticalMtu(target)
                 && isIdenticalTcpBufferSizes(target)
-                && isIdenticalNat64Prefix(target);
+                && isIdenticalNat64Prefix(target)
+                && isIdenticalWakeOnLan(target);
     }
 
     /**
@@ -1577,7 +1616,8 @@
                 + (mUsePrivateDns ? 57 : 0)
                 + mPcscfs.size() * 67
                 + ((null == mPrivateDnsServerName) ? 0 : mPrivateDnsServerName.hashCode())
-                + Objects.hash(mNat64Prefix);
+                + Objects.hash(mNat64Prefix)
+                + (mWakeOnLanSupported ? 71 : 0);
     }
 
     /**
@@ -1622,6 +1662,8 @@
 
         ArrayList<LinkProperties> stackedLinks = new ArrayList<>(mStackedLinks.values());
         dest.writeList(stackedLinks);
+
+        dest.writeBoolean(mWakeOnLanSupported);
     }
 
     /**
@@ -1677,6 +1719,7 @@
                 for (LinkProperties stackedLink: stackedLinks) {
                     netProp.addStackedLink(stackedLink);
                 }
+                netProp.setWakeOnLanSupported(in.readBoolean());
                 return netProp;
             }
 
diff --git a/core/java/android/net/MacAddress.java b/core/java/android/net/MacAddress.java
index a809b28..2cf2a65 100644
--- a/core/java/android/net/MacAddress.java
+++ b/core/java/android/net/MacAddress.java
@@ -85,6 +85,9 @@
     private static final long OUI_MASK = MacAddress.fromString("ff:ff:ff:0:0:0").mAddr;
     private static final long NIC_MASK = MacAddress.fromString("0:0:0:ff:ff:ff").mAddr;
     private static final MacAddress BASE_GOOGLE_MAC = MacAddress.fromString("da:a1:19:0:0:0");
+    /** Default wifi MAC address used for a special purpose **/
+    private static final MacAddress DEFAULT_MAC_ADDRESS =
+            MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
 
     // Internal representation of the MAC address as a single 8 byte long.
     // The encoding scheme sets the two most significant bytes to 0. The 6 bytes of the
@@ -361,16 +364,7 @@
      * @hide
      */
     public static @NonNull MacAddress createRandomUnicastAddress() {
-        SecureRandom r = new SecureRandom();
-        long addr = r.nextLong() & VALID_LONG_MASK;
-        addr |= LOCALLY_ASSIGNED_MASK;
-        addr &= ~MULTICAST_MASK;
-        MacAddress mac = new MacAddress(addr);
-        // WifiInfo.DEFAULT_MAC_ADDRESS is being used for another purpose, so do not use it here.
-        if (mac.toString().equals(WifiInfo.DEFAULT_MAC_ADDRESS)) {
-            return createRandomUnicastAddress();
-        }
-        return mac;
+        return createRandomUnicastAddress(null, new SecureRandom());
     }
 
     /**
@@ -380,18 +374,23 @@
      * The locally assigned bit is always set to 1. The multicast bit is always set to 0.
      *
      * @param base a base MacAddress whose OUI is used for generating the random address.
+     *             If base == null then the OUI will also be randomized.
      * @param r a standard Java Random object used for generating the random address.
      * @return a random locally assigned MacAddress.
      *
      * @hide
      */
     public static @NonNull MacAddress createRandomUnicastAddress(MacAddress base, Random r) {
-        long addr = (base.mAddr & OUI_MASK) | (NIC_MASK & r.nextLong());
+        long addr;
+        if (base == null) {
+            addr = r.nextLong() & VALID_LONG_MASK;
+        } else {
+            addr = (base.mAddr & OUI_MASK) | (NIC_MASK & r.nextLong());
+        }
         addr |= LOCALLY_ASSIGNED_MASK;
         addr &= ~MULTICAST_MASK;
         MacAddress mac = new MacAddress(addr);
-        // WifiInfo.DEFAULT_MAC_ADDRESS is being used for another purpose, so do not use it here.
-        if (mac.toString().equals(WifiInfo.DEFAULT_MAC_ADDRESS)) {
+        if (mac.equals(DEFAULT_MAC_ADDRESS)) {
             return createRandomUnicastAddress(base, r);
         }
         return mac;
diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java
index b3125d8..6a709b5 100755
--- a/core/java/android/os/Build.java
+++ b/core/java/android/os/Build.java
@@ -243,7 +243,8 @@
         public static final String BASE_OS = SystemProperties.get("ro.build.version.base_os", "");
 
         /**
-         * The user-visible security patch level.
+         * The user-visible security patch level. This value represents the date when the device
+         * most recently applied a security patch.
          */
         public static final String SECURITY_PATCH = SystemProperties.get(
                 "ro.build.version.security_patch", "");
diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java
index 3cc2819..bc32df4 100644
--- a/core/java/android/os/Debug.java
+++ b/core/java/android/os/Debug.java
@@ -278,11 +278,13 @@
         /** @hide */
         public static final int OTHER_DALVIK_OTHER_ACCOUNTING = 22;
         /** @hide */
-        public static final int OTHER_DALVIK_OTHER_CODE_CACHE = 23;
+        public static final int OTHER_DALVIK_OTHER_ZYGOTE_CODE_CACHE = 23;
         /** @hide */
-        public static final int OTHER_DALVIK_OTHER_COMPILER_METADATA = 24;
+        public static final int OTHER_DALVIK_OTHER_APP_CODE_CACHE = 24;
         /** @hide */
-        public static final int OTHER_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE = 25;
+        public static final int OTHER_DALVIK_OTHER_COMPILER_METADATA = 25;
+        /** @hide */
+        public static final int OTHER_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE = 26;
         /** @hide */
         public static final int OTHER_DVK_STAT_DALVIK_OTHER_START =
                 OTHER_DALVIK_OTHER_LINEARALLOC - NUM_OTHER_STATS;
@@ -292,11 +294,11 @@
 
         // Dex subsections (Boot vdex, App dex, and App vdex).
         /** @hide */
-        public static final int OTHER_DEX_BOOT_VDEX = 26;
+        public static final int OTHER_DEX_BOOT_VDEX = 27;
         /** @hide */
-        public static final int OTHER_DEX_APP_DEX = 27;
+        public static final int OTHER_DEX_APP_DEX = 28;
         /** @hide */
-        public static final int OTHER_DEX_APP_VDEX = 28;
+        public static final int OTHER_DEX_APP_VDEX = 29;
         /** @hide */
         public static final int OTHER_DVK_STAT_DEX_START = OTHER_DEX_BOOT_VDEX - NUM_OTHER_STATS;
         /** @hide */
@@ -304,9 +306,9 @@
 
         // Art subsections (App image, boot image).
         /** @hide */
-        public static final int OTHER_ART_APP = 29;
+        public static final int OTHER_ART_APP = 30;
         /** @hide */
-        public static final int OTHER_ART_BOOT = 30;
+        public static final int OTHER_ART_BOOT = 31;
         /** @hide */
         public static final int OTHER_DVK_STAT_ART_START = OTHER_ART_APP - NUM_OTHER_STATS;
         /** @hide */
@@ -314,7 +316,7 @@
 
         /** @hide */
         @UnsupportedAppUsage
-        public static final int NUM_DVK_STATS = 14;
+        public static final int NUM_DVK_STATS = OTHER_ART_BOOT + 1 - OTHER_DALVIK_NORMAL;
 
         /** @hide */
         public static final int NUM_CATEGORIES = 9;
@@ -540,7 +542,8 @@
                 case OTHER_DALVIK_NON_MOVING: return ".NonMoving";
                 case OTHER_DALVIK_OTHER_LINEARALLOC: return ".LinearAlloc";
                 case OTHER_DALVIK_OTHER_ACCOUNTING: return ".GC";
-                case OTHER_DALVIK_OTHER_CODE_CACHE: return ".JITCache";
+                case OTHER_DALVIK_OTHER_ZYGOTE_CODE_CACHE: return ".ZygoteJIT";
+                case OTHER_DALVIK_OTHER_APP_CODE_CACHE: return ".AppJIT";
                 case OTHER_DALVIK_OTHER_COMPILER_METADATA: return ".CompilerMetadata";
                 case OTHER_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE: return ".IndirectRef";
                 case OTHER_DEX_BOOT_VDEX: return ".Boot vdex";
@@ -722,7 +725,9 @@
               + getOtherPrivate(OTHER_APK)
               + getOtherPrivate(OTHER_TTF)
               + getOtherPrivate(OTHER_DEX)
-              + getOtherPrivate(OTHER_OAT);
+                + getOtherPrivate(OTHER_OAT)
+                + getOtherPrivate(OTHER_DALVIK_OTHER_ZYGOTE_CODE_CACHE)
+                + getOtherPrivate(OTHER_DALVIK_OTHER_APP_CODE_CACHE);
         }
 
         /**
@@ -813,7 +818,9 @@
                 + getOtherRss(OTHER_APK)
                 + getOtherRss(OTHER_TTF)
                 + getOtherRss(OTHER_DEX)
-                + getOtherRss(OTHER_OAT);
+                + getOtherRss(OTHER_OAT)
+                + getOtherRss(OTHER_DALVIK_OTHER_ZYGOTE_CODE_CACHE)
+                + getOtherRss(OTHER_DALVIK_OTHER_APP_CODE_CACHE);
         }
 
         /**
diff --git a/core/java/android/os/Handler.java b/core/java/android/os/Handler.java
index 9af9eda..45a9cf5 100644
--- a/core/java/android/os/Handler.java
+++ b/core/java/android/os/Handler.java
@@ -295,6 +295,10 @@
     /** {@hide} */
     @NonNull
     public String getTraceName(@NonNull Message message) {
+        if (message.callback instanceof TraceNameSupplier) {
+            return ((TraceNameSupplier) message.callback).getTraceName();
+        }
+
         final StringBuilder sb = new StringBuilder();
         sb.append(getClass().getName()).append(": ");
         if (message.callback != null) {
diff --git a/core/java/android/os/HwParcel.java b/core/java/android/os/HwParcel.java
index cfb582e..5e8929c 100644
--- a/core/java/android/os/HwParcel.java
+++ b/core/java/android/os/HwParcel.java
@@ -23,6 +23,8 @@
 import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 
+import dalvik.annotation.optimization.FastNative;
+
 import libcore.util.NativeAllocationRegistry;
 
 import java.lang.annotation.Retention;
@@ -72,46 +74,54 @@
 
     /**
      * Writes an interface token into the parcel used to verify that
-     * a transaction has made it to the write type of interface.
+     * a transaction has made it to the right type of interface.
      *
      * @param interfaceName fully qualified name of interface message
      *     is being sent to.
      */
+    @FastNative
     public native final void writeInterfaceToken(String interfaceName);
     /**
      * Writes a boolean value to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     public native final void writeBool(boolean val);
     /**
      * Writes a byte value to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     public native final void writeInt8(byte val);
     /**
      * Writes a short value to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     public native final void writeInt16(short val);
     /**
      * Writes a int value to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     public native final void writeInt32(int val);
     /**
      * Writes a long value to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     public native final void writeInt64(long val);
     /**
      * Writes a float value to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     public native final void writeFloat(float val);
     /**
      * Writes a double value to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     public native final void writeDouble(double val);
     /**
      * Writes a String value to the end of the parcel.
@@ -120,6 +130,7 @@
      *
      * @param val to write
      */
+    @FastNative
     public native final void writeString(String val);
     /**
      * Writes a native handle (without duplicating the underlying
@@ -127,42 +138,50 @@
      *
      * @param val to write
      */
+    @FastNative
     public native final void writeNativeHandle(@Nullable NativeHandle val);
 
     /**
      * Writes an array of boolean values to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     private native final void writeBoolVector(boolean[] val);
     /**
      * Writes an array of byte values to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     private native final void writeInt8Vector(byte[] val);
     /**
      * Writes an array of short values to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     private native final void writeInt16Vector(short[] val);
     /**
      * Writes an array of int values to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     private native final void writeInt32Vector(int[] val);
     /**
      * Writes an array of long values to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     private native final void writeInt64Vector(long[] val);
     /**
      * Writes an array of float values to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     private native final void writeFloatVector(float[] val);
     /**
      * Writes an array of double values to the end of the parcel.
      * @param val to write
      */
+    @FastNative
     private native final void writeDoubleVector(double[] val);
     /**
      * Writes an array of String values to the end of the parcel.
@@ -171,6 +190,7 @@
      *
      * @param val to write
      */
+    @FastNative
     private native final void writeStringVector(String[] val);
     /**
      * Writes an array of native handles to the end of the parcel.
@@ -179,6 +199,7 @@
      *
      * @param val array of {@link NativeHandle} objects to write
      */
+    @FastNative
     private native final void writeNativeHandleVector(NativeHandle[] val);
 
     /**
@@ -299,6 +320,7 @@
      * Write a hwbinder object to the end of the parcel.
      * @param binder value to write
      */
+    @FastNative
     public native final void writeStrongBinder(IHwBinder binder);
 
     /**
@@ -314,48 +336,56 @@
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final boolean readBool();
     /**
      * Reads a byte value from the current location in the parcel.
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final byte readInt8();
     /**
      * Reads a short value from the current location in the parcel.
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final short readInt16();
     /**
      * Reads a int value from the current location in the parcel.
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final int readInt32();
     /**
      * Reads a long value from the current location in the parcel.
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final long readInt64();
     /**
      * Reads a float value from the current location in the parcel.
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final float readFloat();
     /**
      * Reads a double value from the current location in the parcel.
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final double readDouble();
     /**
      * Reads a String value from the current location in the parcel.
      * @return value parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final String readString();
     /**
      * Reads a native handle (without duplicating the underlying file
@@ -366,6 +396,7 @@
      * @return a {@link NativeHandle} instance parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final @Nullable NativeHandle readNativeHandle();
     /**
      * Reads an embedded native handle (without duplicating the underlying
@@ -379,6 +410,7 @@
      * @return a {@link NativeHandle} instance parsed from the parcel
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final @Nullable NativeHandle readEmbeddedNativeHandle(
             long parentHandle, long offset);
 
@@ -387,54 +419,63 @@
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final boolean[] readBoolVectorAsArray();
     /**
      * Reads an array of byte values from the parcel.
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final byte[] readInt8VectorAsArray();
     /**
      * Reads an array of short values from the parcel.
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final short[] readInt16VectorAsArray();
     /**
      * Reads an array of int values from the parcel.
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final int[] readInt32VectorAsArray();
     /**
      * Reads an array of long values from the parcel.
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final long[] readInt64VectorAsArray();
     /**
      * Reads an array of float values from the parcel.
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final float[] readFloatVectorAsArray();
     /**
      * Reads an array of double values from the parcel.
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final double[] readDoubleVectorAsArray();
     /**
      * Reads an array of String values from the parcel.
      * @return array of parsed values
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final String[] readStringVectorAsArray();
     /**
      * Reads an array of native handles from the parcel.
      * @return array of {@link NativeHandle} objects
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     private native final NativeHandle[] readNativeHandleAsArray();
 
     /**
@@ -537,6 +578,7 @@
      * @return binder object read from parcel or null if no binder can be read
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final IHwBinder readStrongBinder();
 
     /**
@@ -544,6 +586,7 @@
      * @return blob of size expectedSize
      * @throws IllegalArgumentException if the parcel has no more data
      */
+    @FastNative
     public native final HwBlob readBuffer(long expectedSize);
 
     /**
@@ -559,6 +602,7 @@
      * @throws NullPointerException if the transaction specified the blob to be null
      *    but nullable is false
      */
+    @FastNative
     public native final HwBlob readEmbeddedBuffer(
             long expectedSize, long parentHandle, long offset,
             boolean nullable);
@@ -567,26 +611,31 @@
      * Write a buffer into the transaction.
      * @param blob blob to write into the parcel.
      */
+    @FastNative
     public native final void writeBuffer(HwBlob blob);
     /**
      * Write a status value into the blob.
      * @param status value to write
      */
+    @FastNative
     public native final void writeStatus(int status);
     /**
      * @throws IllegalArgumentException if a success vaue cannot be read
      * @throws RemoteException if success value indicates a transaction error
      */
+    @FastNative
     public native final void verifySuccess();
     /**
      * Should be called to reduce memory pressure when this object no longer needs
      * to be written to.
      */
+    @FastNative
     public native final void releaseTemporaryStorage();
     /**
      * Should be called when object is no longer needed to reduce possible memory
      * pressure if the Java GC does not get to this object in time.
      */
+    @FastNative
     public native final void release();
 
     /**
@@ -597,6 +646,7 @@
     // Returns address of the "freeFunction".
     private static native final long native_init();
 
+    @FastNative
     private native final void native_setup(boolean allocate);
 
     static {
diff --git a/core/java/android/os/IUserManager.aidl b/core/java/android/os/IUserManager.aidl
index 63641e5..c30491a 100644
--- a/core/java/android/os/IUserManager.aidl
+++ b/core/java/android/os/IUserManager.aidl
@@ -41,6 +41,7 @@
      */
 
     UserInfo createUser(in String name, int flags);
+    UserInfo preCreateUser(int flags);
     UserInfo createProfileForUser(in String name, int flags, int userHandle,
             in String[] disallowedPackages);
     UserInfo createRestrictedProfile(String name, int parentUserHandle);
@@ -53,7 +54,7 @@
     void setUserIcon(int userHandle, in Bitmap icon);
     ParcelFileDescriptor getUserIcon(int userHandle);
     UserInfo getPrimaryUser();
-    List<UserInfo> getUsers(boolean excludeDying);
+    List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying, boolean excludePreCreated);
     List<UserInfo> getProfiles(int userHandle, boolean enabledOnly);
     int[] getProfileIds(int userId, boolean enabledOnly);
     boolean canAddMoreManagedProfiles(int userHandle, boolean allowedToRemoveOne);
@@ -92,6 +93,7 @@
     boolean someUserHasSeedAccount(in String accountName, in String accountType);
     boolean isManagedProfile(int userId);
     boolean isDemoUser(int userId);
+    boolean isPreCreated(int userId);
     UserInfo createProfileForUserEvenWhenDisallowed(in String name, int flags, int userHandle,
             in String[] disallowedPackages);
     boolean isUserUnlockingOrUnlocked(int userId);
diff --git a/core/java/android/os/OWNERS b/core/java/android/os/OWNERS
index b568f15..e371df0 100644
--- a/core/java/android/os/OWNERS
+++ b/core/java/android/os/OWNERS
@@ -1,2 +1,4 @@
 # Zygote
 per-file ZygoteProcess.java = chriswailes@google.com, ngeoffray@google.com, sehr@google.com, narayan@google.com, maco@google.com
+
+per-file GraphicsEnvironment.java = chrisforbes@google.com, cnorthrop@google.com, lpy@google.com, timvp@google.com, zzyiwei@google.com
diff --git a/core/java/android/os/Parcel.java b/core/java/android/os/Parcel.java
index 50487e9..783ab44 100644
--- a/core/java/android/os/Parcel.java
+++ b/core/java/android/os/Parcel.java
@@ -305,8 +305,11 @@
     private static native void nativeWriteFloat(long nativePtr, float val);
     @FastNative
     private static native void nativeWriteDouble(long nativePtr, double val);
+    @FastNative
     static native void nativeWriteString(long nativePtr, String val);
+    @FastNative
     private static native void nativeWriteStrongBinder(long nativePtr, IBinder val);
+    @FastNative
     private static native long nativeWriteFileDescriptor(long nativePtr, FileDescriptor val);
 
     private static native byte[] nativeCreateByteArray(long nativePtr);
@@ -320,8 +323,11 @@
     private static native float nativeReadFloat(long nativePtr);
     @CriticalNative
     private static native double nativeReadDouble(long nativePtr);
+    @FastNative
     static native String nativeReadString(long nativePtr);
+    @FastNative
     private static native IBinder nativeReadStrongBinder(long nativePtr);
+    @FastNative
     private static native FileDescriptor nativeReadFileDescriptor(long nativePtr);
 
     private static native long nativeCreate();
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 76e728a..43b9c67 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -420,10 +420,9 @@
      * Background thread group - All threads in
      * this group are scheduled with a reduced share of the CPU.
      * Value is same as constant SP_BACKGROUND of enum SchedPolicy.
-     * FIXME rename to THREAD_GROUP_BACKGROUND.
      * @hide
      */
-    public static final int THREAD_GROUP_BG_NONINTERACTIVE = 0;
+    public static final int THREAD_GROUP_BACKGROUND = 0;
 
     /**
      * Foreground thread group - All threads in
@@ -809,7 +808,7 @@
      *
      * group == THREAD_GROUP_DEFAULT means to move all non-background priority
      * threads to the foreground scheduling group, but to leave background
-     * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
+     * priority threads alone.  group == THREAD_GROUP_BACKGROUND moves all
      * threads, regardless of priority, to the background scheduling group.
      * group == THREAD_GROUP_FOREGROUND is not allowed.
      *
diff --git a/core/java/android/os/SystemProperties.java b/core/java/android/os/SystemProperties.java
index b6af829..d4abf28 100644
--- a/core/java/android/os/SystemProperties.java
+++ b/core/java/android/os/SystemProperties.java
@@ -39,6 +39,13 @@
  * Gives access to the system properties store.  The system properties
  * store contains a list of string key-value pairs.
  *
+ * <p>Use this class only for the system properties that are local. e.g., within
+ * an app, a partition, or a module. For system properties used across the
+ * boundaries, formally define them in <code>*.sysprop</code> files and use the
+ * auto-generated methods. For more information, see <a href=
+ * "https://source.android.com/devices/architecture/sysprops-apis">Implementing
+ * System Properties as APIs</a>.</p>
+ *
  * {@hide}
  */
 @SystemApi
diff --git a/core/java/android/os/TraceNameSupplier.java b/core/java/android/os/TraceNameSupplier.java
new file mode 100644
index 0000000..e4b3a4e
--- /dev/null
+++ b/core/java/android/os/TraceNameSupplier.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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.os;
+
+import android.annotation.NonNull;
+
+/**
+ * Supplier for custom trace messages.
+ *
+ * @hide
+ */
+public interface TraceNameSupplier {
+
+    /**
+     * Gets the name used for trace messages.
+     */
+    @NonNull String getTraceName();
+}
diff --git a/core/java/android/os/UpdateEngine.java b/core/java/android/os/UpdateEngine.java
index dd5e20e..a9ddffe 100644
--- a/core/java/android/os/UpdateEngine.java
+++ b/core/java/android/os/UpdateEngine.java
@@ -22,8 +22,6 @@
 import android.os.IUpdateEngineCallback;
 import android.os.RemoteException;
 
-import java.io.FileDescriptor;
-
 /**
  * UpdateEngine handles calls to the update engine which takes care of A/B OTA
  * updates. It wraps up the update engine Binder APIs and exposes them as
@@ -315,16 +313,16 @@
     }
 
     /**
-     * Applies the payload passed as file descriptor {@code fd} instead of
+     * Applies the payload passed as ParcelFileDescriptor {@code pfd} instead of
      * using the {@code file://} scheme.
      *
      * <p>See {@link #applyPayload(String)} for {@code offset}, {@code size} and
      * {@code headerKeyValuePairs} parameters.
      */
-    public void applyPayload(@NonNull FileDescriptor fd, long offset, long size,
+    public void applyPayload(@NonNull ParcelFileDescriptor pfd, long offset, long size,
             @NonNull String[] headerKeyValuePairs) {
         try {
-            mUpdateEngine.applyPayloadFd(fd, offset, size, headerKeyValuePairs);
+            mUpdateEngine.applyPayloadFd(pfd, offset, size, headerKeyValuePairs);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/os/UserHandle.java b/core/java/android/os/UserHandle.java
index 0754dc7..3558fcd 100644
--- a/core/java/android/os/UserHandle.java
+++ b/core/java/android/os/UserHandle.java
@@ -39,6 +39,7 @@
 
     /** @hide A user id to indicate all users on the device */
     @UnsupportedAppUsage
+    @TestApi
     public static final @UserIdInt int USER_ALL = -1;
 
     /** @hide A user handle to indicate all users on the device */
@@ -69,8 +70,11 @@
 
     /** @hide An undefined user id */
     @UnsupportedAppUsage
+    @TestApi
     public static final @UserIdInt int USER_NULL = -10000;
 
+    private static final @NonNull UserHandle NULL = new UserHandle(USER_NULL);
+
     /**
      * @hide A user id constant to indicate the "owner" user of the device
      * @deprecated Consider using either {@link UserHandle#USER_SYSTEM} constant or
@@ -91,6 +95,7 @@
 
     /** @hide A user id constant to indicate the "system" user of the device */
     @UnsupportedAppUsage
+    @TestApi
     public static final @UserIdInt int USER_SYSTEM = 0;
 
     /** @hide A user serial constant to indicate the "system" user of the device */
@@ -110,6 +115,27 @@
     public static final boolean MU_ENABLED = true;
 
     /** @hide */
+    @TestApi
+    public static final int MIN_SECONDARY_USER_ID = 10;
+
+    /**
+     * Arbitrary user handle cache size. We use the cache even when {@link #MU_ENABLED} is false
+     * anyway, so we can always assume in CTS that UserHandle.of(10) returns a cached instance
+     * even on non-multiuser devices.
+     */
+    private static final int NUM_CACHED_USERS = 4;
+
+    private static final UserHandle[] CACHED_USER_INFOS = new UserHandle[NUM_CACHED_USERS];
+
+    static {
+        // Not lazily initializing the cache, so that we can share them across processes.
+        // (We'll create them in zygote.)
+        for (int i = 0; i < CACHED_USER_INFOS.length; i++) {
+            CACHED_USER_INFOS[i] = new UserHandle(MIN_SECONDARY_USER_ID + i);
+        }
+    }
+
+    /** @hide */
     @UnsupportedAppUsage
     public static final int ERR_GID = -1;
     /** @hide */
@@ -209,6 +235,7 @@
      * @hide
      */
     @UnsupportedAppUsage
+    @TestApi
     public static @UserIdInt int getUserId(int uid) {
         if (MU_ENABLED) {
             return uid / PER_USER_RANGE;
@@ -229,9 +256,31 @@
     }
 
     /** @hide */
+    @TestApi
     @SystemApi
     public static UserHandle of(@UserIdInt int userId) {
-        return userId == USER_SYSTEM ? SYSTEM : new UserHandle(userId);
+        if (userId == USER_SYSTEM) {
+            return SYSTEM; // Most common.
+        }
+        // These are sequential; so use a switch. Maybe they'll be optimized to a table lookup.
+        switch (userId) {
+            case USER_ALL:
+                return ALL;
+
+            case USER_CURRENT:
+                return CURRENT;
+
+            case USER_CURRENT_OR_SELF:
+                return CURRENT_OR_SELF;
+        }
+        if (userId >= MIN_SECONDARY_USER_ID
+                && userId < (MIN_SECONDARY_USER_ID + CACHED_USER_INFOS.length)) {
+            return CACHED_USER_INFOS[userId - MIN_SECONDARY_USER_ID];
+        }
+        if (userId == USER_NULL) { // Not common.
+            return NULL;
+        }
+        return new UserHandle(userId);
     }
 
     /**
@@ -239,6 +288,7 @@
      * @hide
      */
     @UnsupportedAppUsage
+    @TestApi
     public static int getUid(@UserIdInt int userId, @AppIdInt int appId) {
         if (MU_ENABLED) {
             return userId * PER_USER_RANGE + (appId % PER_USER_RANGE);
@@ -404,6 +454,7 @@
      * @hide
      */
     @SystemApi
+    @TestApi
     public static @UserIdInt int myUserId() {
         return getUserId(Process.myUid());
     }
@@ -513,7 +564,9 @@
     public static final @android.annotation.NonNull Parcelable.Creator<UserHandle> CREATOR
             = new Parcelable.Creator<UserHandle>() {
         public UserHandle createFromParcel(Parcel in) {
-            return new UserHandle(in);
+            // Try to avoid allocation; use of() here. Keep this and the constructor below
+            // in sync.
+            return UserHandle.of(in.readInt());
         }
 
         public UserHandle[] newArray(int size) {
@@ -532,6 +585,6 @@
      * positioned at the location in the buffer where it was written.
      */
     public UserHandle(Parcel in) {
-        mHandle = in.readInt();
+        mHandle = in.readInt(); // Keep this and createFromParcel() in sync.
     }
 }
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index af574da..3296f11 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -37,6 +37,7 @@
 import android.content.IntentFilter;
 import android.content.IntentSender;
 import android.content.pm.UserInfo;
+import android.content.pm.UserInfo.UserInfoFlag;
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.graphics.Bitmap;
@@ -2013,18 +2014,20 @@
 
     /**
      * Creates a user with the specified name and options. For non-admin users, default user
-     * restrictions are going to be applied.
-     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
+     * restrictions will be applied.
+     *
+     * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
      *
      * @param name the user's name
-     * @param flags flags that identify the type of user and other properties.
+     * @param flags UserInfo flags that identify the type of user and other properties.
      * @see UserInfo
      *
-     * @return the UserInfo object for the created user, or null if the user could not be created.
+     * @return the UserInfo object for the created user, or {@code null} if the user could not be
+     * created.
      * @hide
      */
     @UnsupportedAppUsage
-    public UserInfo createUser(String name, int flags) {
+    public @Nullable UserInfo createUser(@Nullable String name, @UserInfoFlag int flags) {
         UserInfo user = null;
         try {
             user = mService.createUser(name, flags);
@@ -2041,6 +2044,36 @@
     }
 
     /**
+     * Pre-creates a user with the specified name and options. For non-admin users, default user
+     * restrictions will be applied.
+     *
+     * <p>This method can be used by OEMs to "warm" up the user creation by pre-creating some users
+     * at the first boot, so they when the "real" user is created (for example,
+     * by {@link #createUser(String, int)} or {@link #createGuest(Context, String)}), it takes
+     * less time.
+     *
+     * <p>Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
+     *
+     * @param flags UserInfo flags that identify the type of user and other properties.
+     * @see UserInfo
+     *
+     * @return the UserInfo object for the created user, or {@code null} if the user could not be
+     * created.
+     *
+     * @throw {@link IllegalArgumentException} if {@code flags} contains
+     * {@link UserInfo#FLAG_MANAGED_PROFILE}.
+     *
+     * @hide
+     */
+    public @Nullable UserInfo preCreateUser(@UserInfoFlag int flags) {
+        try {
+            return mService.preCreateUser(flags);
+        } catch (RemoteException re) {
+            throw re.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Creates a guest user and configures it.
      * @param context an application context
      * @param name the name to set for the user
@@ -2356,15 +2389,26 @@
     /**
      * Returns information for all users on this device, including ones marked for deletion.
      * To retrieve only users that are alive, use {@link #getUsers(boolean)}.
-     * <p>
-     * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
+     *
      * @return the list of users that exist on the device.
      * @hide
      */
     @UnsupportedAppUsage
+    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
     public List<UserInfo> getUsers() {
+        return getUsers(/* excludeDying= */ false);
+    }
+
+    /**
+     * Returns information for all users on this device, based on the filtering parameters.
+     *
+     * @hide
+     */
+    @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
+    public List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
+            boolean excludePreCreated) {
         try {
-            return mService.getUsers(false);
+            return mService.getUsers(excludePartial, excludeDying, excludePreCreated);
         } catch (RemoteException re) {
             throw re.rethrowFromSystemServer();
         }
@@ -2380,16 +2424,12 @@
     @SystemApi
     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
     public long[] getSerialNumbersOfUsers(boolean excludeDying) {
-        try {
-            List<UserInfo> users = mService.getUsers(excludeDying);
-            long[] result = new long[users.size()];
-            for (int i = 0; i < result.length; i++) {
-                result[i] = users.get(i).serialNumber;
-            }
-            return result;
-        } catch (RemoteException re) {
-            throw re.rethrowFromSystemServer();
+        List<UserInfo> users = getUsers(excludeDying);
+        long[] result = new long[users.size()];
+        for (int i = 0; i < result.length; i++) {
+            result[i] = users.get(i).serialNumber;
         }
+        return result;
     }
 
     /**
@@ -2773,11 +2813,8 @@
      */
     @UnsupportedAppUsage
     public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
-        try {
-            return mService.getUsers(excludeDying);
-        } catch (RemoteException re) {
-            throw re.rethrowFromSystemServer();
-        }
+        return getUsers(/*excludePartial= */ true, excludeDying,
+                /* excludePreCreated= */ true);
     }
 
     /**
diff --git a/core/java/android/os/UserManagerInternal.java b/core/java/android/os/UserManagerInternal.java
index a5b71f6..59fb3d9 100644
--- a/core/java/android/os/UserManagerInternal.java
+++ b/core/java/android/os/UserManagerInternal.java
@@ -86,12 +86,22 @@
     public abstract void setDeviceManaged(boolean isManaged);
 
     /**
+     * Returns whether the device is managed by device owner.
+     */
+    public abstract boolean isDeviceManaged();
+
+    /**
      * Called by {@link com.android.server.devicepolicy.DevicePolicyManagerService} to update
      * whether the user is managed by profile owner.
      */
     public abstract void setUserManaged(int userId, boolean isManaged);
 
     /**
+     * whether a profile owner manages this user.
+     */
+    public abstract boolean isUserManaged(int userId);
+
+    /**
      * Called by {@link com.android.server.devicepolicy.DevicePolicyManagerService} to omit
      * restriction check, because DevicePolicyManager must always be able to set user icon
      * regardless of any restriction.
diff --git a/core/java/android/os/ZygoteProcess.java b/core/java/android/os/ZygoteProcess.java
index eaf9929..907eae8 100644
--- a/core/java/android/os/ZygoteProcess.java
+++ b/core/java/android/os/ZygoteProcess.java
@@ -576,6 +576,8 @@
             argsForZygote.add("--mount-external-installer");
         } else if (mountExternal == Zygote.MOUNT_EXTERNAL_LEGACY) {
             argsForZygote.add("--mount-external-legacy");
+        } else if (mountExternal == Zygote.MOUNT_EXTERNAL_PASS_THROUGH) {
+            argsForZygote.add("--mount-external-pass-through");
         }
 
         argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
@@ -756,6 +758,7 @@
                 ZygoteState state = openZygoteSocketIfNeeded(abi);
                 state.mZygoteOutputWriter.write("1\n--boot-completed\n");
                 state.mZygoteOutputWriter.flush();
+                state.mZygoteInputStream.readInt();
             }
         } catch (Exception ex) {
             throw new RuntimeException("Failed to inform zygote of boot_completed", ex);
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 5b9205d..2d8af83 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -153,6 +153,11 @@
     public static final String PROP_ISOLATED_STORAGE = "persist.sys.isolated_storage";
     /** {@hide} */
     public static final String PROP_ISOLATED_STORAGE_SNAPSHOT = "sys.isolated_storage_snapshot";
+    /** {@hide} */
+    public static final String PROP_FUSE = "persist.sys.fuse";
+    /** {@hide} */
+    public static final String PROP_FUSE_SNAPSHOT = "sys.fuse_snapshot";
+
 
     /** {@hide} */
     public static final String UUID_PRIVATE_INTERNAL = null;
@@ -1575,7 +1580,14 @@
 
     /** {@hide} */
     public static boolean hasAdoptable() {
-        return SystemProperties.getBoolean(PROP_HAS_ADOPTABLE, false);
+        switch (SystemProperties.get(PROP_ADOPTABLE)) {
+            case "force_on":
+                return true;
+            case "force_off":
+                return false;
+            default:
+                return SystemProperties.getBoolean(PROP_HAS_ADOPTABLE, false);
+        }
     }
 
     /**
diff --git a/core/java/android/os/telephony/TelephonyRegistryManager.java b/core/java/android/os/telephony/TelephonyRegistryManager.java
new file mode 100644
index 0000000..1332331
--- /dev/null
+++ b/core/java/android/os/telephony/TelephonyRegistryManager.java
@@ -0,0 +1,549 @@
+/*
+ * Copyright (C) 2019 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.os.telephony;
+
+import android.annotation.SystemApi;
+import android.net.LinkProperties;
+import android.net.NetworkCapabilities;
+import android.os.Bundle;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.telephony.Annotation.ApnType;
+import android.telephony.Annotation.CallState;
+import android.telephony.Annotation.DataActivityType;
+import android.telephony.Annotation.DataFailureCause;
+import android.telephony.Annotation.DataState;
+import android.telephony.Annotation.NetworkType;
+import android.telephony.Annotation.PreciseCallStates;
+import android.telephony.Annotation.RadioPowerState;
+import android.telephony.Annotation.SimActivationState;
+import android.telephony.Annotation.SrvccState;
+import android.telephony.CallQuality;
+import android.telephony.CellInfo;
+import android.telephony.DisconnectCause;
+import android.telephony.PhoneCapability;
+import android.telephony.ServiceState;
+import android.telephony.SignalStrength;
+import android.telephony.TelephonyManager;
+import android.telephony.data.ApnSetting;
+import android.telephony.ims.ImsReasonInfo;
+import com.android.internal.telephony.ITelephonyRegistry;
+import java.util.List;
+
+/**
+ * A centralized place to notify telephony related status changes, e.g, {@link ServiceState} update
+ * or {@link PhoneCapability} changed. This might trigger callback from applications side through
+ * {@link android.telephony.PhoneStateListener}
+ *
+ * TODO: limit API access to only carrier apps with certain permissions or apps running on
+ * privileged UID.
+ *
+ * @hide
+ */
+@SystemApi
+public class TelephonyRegistryManager {
+
+    private static final String TAG = "TelephonyRegistryManager";
+    private static ITelephonyRegistry sRegistry;
+
+    /** @hide **/
+    public TelephonyRegistryManager() {
+        if (sRegistry == null) {
+            sRegistry = ITelephonyRegistry.Stub.asInterface(
+                ServiceManager.getService("telephony.registry"));
+        }
+    }
+
+    /**
+     * Informs the system of an intentional upcoming carrier network change by a carrier app.
+     * This call only used to allow the system to provide alternative UI while telephony is
+     * performing an action that may result in intentional, temporary network lack of connectivity.
+     * <p>
+     * Based on the active parameter passed in, this method will either show or hide the alternative
+     * UI. There is no timeout associated with showing this UX, so a carrier app must be sure to
+     * call with active set to false sometime after calling with it set to {@code true}.
+     * <p>
+     * Requires Permission: calling app has carrier privileges.
+     *
+     * @param active Whether the carrier network change is or shortly will be
+     * active. Set this value to true to begin showing alternative UI and false to stop.
+     * @see TelephonyManager#hasCarrierPrivileges
+     */
+    public void notifyCarrierNetworkChange(boolean active) {
+        try {
+            sRegistry.notifyCarrierNetworkChange(active);
+        } catch (RemoteException ex) {
+            // system server crash
+        }
+    }
+
+    /**
+     * Notify call state changed on certain subscription.
+     *
+     * @param subId for which call state changed.
+     * @param slotIndex for which call state changed. Can be derived from subId except when subId is
+     * invalid.
+     * @param state latest call state. e.g, offhook, ringing
+     * @param incomingNumer incoming phone number.
+     *
+     * @hide
+     */
+    public void notifyCallStateChanged(int subId, int slotIndex, @CallState int state,
+        String incomingNumer) {
+        try {
+            sRegistry.notifyCallState(slotIndex, subId, state, incomingNumer);
+        } catch (RemoteException ex) {
+            // system server crash
+        }
+    }
+
+    /**
+     * Notify {@link ServiceState} update on certain subscription.
+     *
+     * @param subId for which the service state changed.
+     * @param slotIndex for which the service state changed. Can be derived from subId except
+     * subId is invalid.
+     * @param state service state e.g, in service, out of service or roaming status.
+     *
+     * @hide
+     */
+    public void notifyServiceStateChanged(int subId, int slotIndex, ServiceState state) {
+        try {
+            sRegistry.notifyServiceStateForPhoneId(slotIndex, subId, state);
+        } catch (RemoteException ex) {
+            // system server crash
+        }
+    }
+
+    /**
+     * Notify {@link SignalStrength} update on certain subscription.
+     *
+     * @param subId for which the signalstrength changed.
+     * @param slotIndex for which the signalstrength changed. Can be derived from subId except when
+     * subId is invalid.
+     * @param signalStrength e.g, signalstrength level {@see SignalStrength#getLevel()}
+     *
+     * @hide
+     */
+    public void notifySignalStrengthChanged(int subId, int slotIndex,
+        SignalStrength signalStrength) {
+        try {
+            sRegistry.notifySignalStrengthForPhoneId(slotIndex, subId, signalStrength);
+        } catch (RemoteException ex) {
+            // system server crash
+        }
+    }
+
+    /**
+     * Notify changes to the message-waiting indicator on certain subscription. e.g, The status bar
+     * uses message waiting indicator to determine when to display the voicemail icon.
+     *
+     * @param subId for which message waiting indicator changed.
+     * @param slotIndex for which message waiting indicator changed. Can be derived from subId
+     * except when subId is invalid.
+     * @param msgWaitingInd {@code true} indicates there is message-waiting indicator, {@code false}
+     * otherwise.
+     *
+     * @hide
+     */
+    public void notifyMessageWaitingChanged(int subId, int slotIndex, boolean msgWaitingInd) {
+        try {
+            sRegistry.notifyMessageWaitingChangedForPhoneId(slotIndex, subId, msgWaitingInd);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify changes to the call-forwarding status on certain subscription.
+     *
+     * @param subId for which call forwarding status changed.
+     * @param callForwardInd {@code true} indicates there is call forwarding, {@code false}
+     * otherwise.
+     *
+     * @hide
+     */
+    public void notifyCallForwardingChanged(int subId, boolean callForwardInd) {
+        try {
+            sRegistry.notifyCallForwardingChangedForSubscriber(subId, callForwardInd);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify changes to activity state changes on certain subscription.
+     *
+     * @param subId for which data activity state changed.
+     * @param dataActivityType indicates the latest data activity type e.g, {@link
+     * TelephonyManager#DATA_ACTIVITY_IN}
+     *
+     * @hide
+     */
+    public void notifyDataActivityChanged(int subId, @DataActivityType int dataActivityType) {
+        try {
+            sRegistry.notifyDataActivityForSubscriber(subId, dataActivityType);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify changes to default (Internet) data connection state on certain subscription.
+     *
+     * @param subId for which data connection state changed.
+     * @param slotIndex for which data connections state changed. Can be derived from subId except
+     * when subId is invalid.
+     * @param state latest data connection state, e.g,
+     * @param isDataConnectivityPossible indicates if data is allowed
+     * @param apn the APN {@link ApnSetting#getApnName()} of this data connection.
+     * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN.
+     * @param linkProperties {@link LinkProperties} associated with this data connection.
+     * @param networkCapabilities {@link NetworkCapabilities} associated with this data connection.
+     * @param networkType associated with this data connection.
+     * @param roaming {@code true} indicates in roaming, {@false} otherwise.
+     * @see TelephonyManager#DATA_DISCONNECTED
+     * @see TelephonyManager#isDataConnectivityPossible()
+     *
+     * @hide
+     */
+    public void notifyDataConnectionForSubscriber(int slotIndex, int subId, @DataState int state,
+        boolean isDataConnectivityPossible,
+        @ApnType String apn, String apnType, LinkProperties linkProperties,
+        NetworkCapabilities networkCapabilities, int networkType, boolean roaming) {
+        try {
+            sRegistry.notifyDataConnectionForSubscriber(slotIndex, subId, state,
+                isDataConnectivityPossible,
+                apn, apnType, linkProperties, networkCapabilities, networkType, roaming);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify {@link CallQuality} change on certain subscription.
+     *
+     * @param subId for which call quality state changed.
+     * @param slotIndex for which call quality state changed. Can be derived from subId except when
+     * subId is invalid.
+     * @param callQuality Information about call quality e.g, call quality level
+     * @param networkType associated with this data connection. e.g, LTE
+     *
+     * @hide
+     */
+    public void notifyCallQualityChanged(int subId, int slotIndex, CallQuality callQuality,
+        @NetworkType int networkType) {
+        try {
+            sRegistry.notifyCallQualityChanged(callQuality, slotIndex, subId, networkType);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify emergency number list changed on certain subscription.
+     *
+     * @param subId for which emergency number list changed.
+     * @param slotIndex for which emergency number list changed. Can be derived from subId except
+     * when subId is invalid.
+     *
+     * @hide
+     */
+    public void notifyEmergencyNumberList(int subId, int slotIndex) {
+        try {
+            sRegistry.notifyEmergencyNumberList(slotIndex, subId);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify radio power state changed on certain subscription.
+     *
+     * @param subId for which radio power state changed.
+     * @param slotIndex for which radio power state changed. Can be derived from subId except when
+     * subId is invalid.
+     * @param radioPowerState the current modem radio state.
+     *
+     * @hide
+     */
+    public void notifyRadioPowerStateChanged(int subId, int slotIndex,
+        @RadioPowerState int radioPowerState) {
+        try {
+            sRegistry.notifyRadioPowerStateChanged(slotIndex, subId, radioPowerState);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify {@link PhoneCapability} changed.
+     *
+     * @param phoneCapability the capability of the modem group.
+     *
+     * @hide
+     */
+    public void notifyPhoneCapabilityChanged(PhoneCapability phoneCapability) {
+        try {
+            sRegistry.notifyPhoneCapabilityChanged(phoneCapability);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify data activation state changed on certain subscription.
+     * @see TelephonyManager#getDataActivationState()
+     *
+     * @param subId for which data activation state changed.
+     * @param slotIndex for which data activation state changed. Can be derived from subId except
+     * when subId is invalid.
+     * @param activationState sim activation state e.g, activated.
+     *
+     * @hide
+     */
+    public void notifyDataActivationStateChanged(int subId, int slotIndex,
+        @SimActivationState int activationState) {
+        try {
+            sRegistry.notifySimActivationStateChangedForPhoneId(slotIndex, subId,
+                TelephonyManager.SIM_ACTIVATION_TYPE_DATA, activationState);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify voice activation state changed on certain subscription.
+     * @see TelephonyManager#getVoiceActivationState()
+     *
+     * @param subId for which voice activation state changed.
+     * @param slotIndex for which voice activation state changed. Can be derived from subId except
+     * subId is invalid.
+     * @param activationState sim activation state e.g, activated.
+     *
+     * @hide
+     */
+    public void notifyVoiceActivationStateChanged(int subId, int slotIndex,
+        @SimActivationState int activationState) {
+        try {
+            sRegistry.notifySimActivationStateChangedForPhoneId(slotIndex, subId,
+                TelephonyManager.SIM_ACTIVATION_TYPE_VOICE, activationState);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify User mobile data state changed on certain subscription. e.g, mobile data is enabled
+     * or disabled.
+     *
+     * @param subId for which mobile data state has changed.
+     * @param slotIndex for which mobile data state has changed. Can be derived from subId except
+     * when subId is invalid.
+     * @param state {@code true} indicates mobile data is enabled/on. {@code false} otherwise.
+     *
+     * @hide
+     */
+    public void notifyUserMobileDataStateChanged(int slotIndex, int subId, boolean state) {
+        try {
+            sRegistry.notifyUserMobileDataStateChangedForPhoneId(slotIndex, subId, state);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * TODO: this is marked as deprecated, can we move this one safely?
+     *
+     * @param subId
+     * @param slotIndex
+     * @param rawData
+     *
+     * @hide
+     */
+    public void notifyOemHookRawEventForSubscriber(int subId, int slotIndex, byte[] rawData) {
+        try {
+            sRegistry.notifyOemHookRawEventForSubscriber(slotIndex, subId, rawData);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify IMS call disconnect causes which contains {@link android.telephony.ims.ImsReasonInfo}.
+     *
+     * @param subId for which ims call disconnect.
+     * @param imsReasonInfo the reason for ims call disconnect.
+     *
+     * @hide
+     */
+    public void notifyImsDisconnectCause(int subId, ImsReasonInfo imsReasonInfo) {
+        try {
+            sRegistry.notifyImsDisconnectCause(subId, imsReasonInfo);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify precise data connection failed cause on certain subscription.
+     *
+     * @param subId for which data connection failed.
+     * @param slotIndex for which data conenction failed. Can be derived from subId except when
+     * subId is invalid.
+     * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN.
+     * @param apn the APN {@link ApnSetting#getApnName()} of this data connection.
+     * @param failCause data fail cause.
+     *
+     * @hide
+     */
+    public void notifyPreciseDataConnectionFailed(int subId, int slotIndex, String apnType,
+        String apn, @DataFailureCause int failCause) {
+        try {
+            sRegistry.notifyPreciseDataConnectionFailed(slotIndex, subId, apnType, apn, failCause);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify single Radio Voice Call Continuity (SRVCC) state change for the currently active call
+     * on certain subscription.
+     *
+     * @param subId for which srvcc state changed.
+     * @param state srvcc state
+     *
+     * @hide
+     */
+    public void notifySrvccStateChanged(int subId, @SrvccState int state) {
+        try {
+            sRegistry.notifySrvccStateChanged(subId, state);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify over the air sim provisioning(OTASP) mode changed on certain subscription.
+     *
+     * @param subId for which otasp mode changed.
+     * @param otaspMode latest mode for OTASP e.g, OTASP needed.
+     *
+     * @hide
+     */
+    public void notifyOtaspChanged(int subId, int otaspMode) {
+        try {
+            sRegistry.notifyOtaspChanged(subId, otaspMode);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify precise call state changed on certain subscription, including foreground, background
+     * and ringcall states.
+     *
+     * @param subId for which precise call state changed.
+     * @param slotIndex for which precise call state changed. Can be derived from subId except when
+     * subId is invalid.
+     * @param ringCallPreciseState ringCall state.
+     * @param foregroundCallPreciseState foreground call state.
+     * @param backgroundCallPreciseState background call state.
+     *
+     * @hide
+     */
+    public void notifyPreciseCallState(int subId, int slotIndex,
+        @PreciseCallStates int ringCallPreciseState,
+        @PreciseCallStates int foregroundCallPreciseState,
+        @PreciseCallStates int backgroundCallPreciseState) {
+        try {
+            sRegistry.notifyPreciseCallState(slotIndex, subId, ringCallPreciseState,
+                foregroundCallPreciseState, backgroundCallPreciseState);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify call disconnect causes which contains {@link DisconnectCause} and {@link
+     * android.telephony.PreciseDisconnectCause}.
+     *
+     * @param subId for which call disconnected.
+     * @param slotIndex for which call disconnected. Can be derived from subId except when subId is
+     * invalid.
+     * @param cause {@link DisconnectCause} for the disconnected call.
+     * @param preciseCause {@link android.telephony.PreciseDisconnectCause} for the disconnected
+     * call.
+     *
+     * @hide
+     */
+    public void notifyDisconnectCause(int slotIndex, int subId, int cause, int preciseCause) {
+        try {
+            sRegistry.notifyDisconnectCause(slotIndex, subId, cause, preciseCause);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify data connection failed on certain subscription.
+     *
+     * @param subId for which data connection failed.
+     * @param slotIndex for which data conenction faled. Can be derived from subId except when subId
+     * is invalid.
+     * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN. Note each data
+     * connection can support multiple anyTypes.
+     *
+     * @hide
+     */
+    public void notifyDataConnectionFailed(int subId, int slotIndex, String apnType) {
+        try {
+            sRegistry.notifyDataConnectionFailedForSubscriber(slotIndex, subId, apnType);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * TODO change from bundle to CellLocation?
+     * @hide
+     */
+    public void notifyCellLocation(int subId, Bundle cellLocation) {
+        try {
+            sRegistry.notifyCellLocationForSubscriber(subId, cellLocation);
+        } catch (RemoteException ex) {
+            // system process is dead
+        }
+    }
+
+    /**
+     * Notify {@link CellInfo} changed on certain subscription. e.g, when an observed cell info has
+     * changed or new cells have been added or removed on the given subscription.
+     *
+     * @param subId for which cellinfo changed.
+     * @param cellInfo A list of cellInfo associated with the given subscription.
+     *
+     * @hide
+     */
+    public void notifyCellInfoChanged(int subId, List<CellInfo> cellInfo) {
+        try {
+            sRegistry.notifyCellInfoForSubscriber(subId, cellInfo);
+        } catch (RemoteException ex) {
+
+        }
+    }
+
+}
diff --git a/core/java/android/preference/SeekBarVolumizer.java b/core/java/android/preference/SeekBarVolumizer.java
index 2b3a2ab..4dd9bab 100644
--- a/core/java/android/preference/SeekBarVolumizer.java
+++ b/core/java/android/preference/SeekBarVolumizer.java
@@ -151,7 +151,7 @@
                 .PRIORITY_CATEGORY_ALARMS) != 0;
         mAllowMedia = (mNotificationPolicy.priorityCategories & NotificationManager.Policy
                 .PRIORITY_CATEGORY_MEDIA) != 0;
-        mAllowRinger = !ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(
+        mAllowRinger = !ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(
                 mNotificationPolicy);
         mStreamType = streamType;
         mAffectedByRingerMode = mAudioManager.isStreamAffectedByRingerMode(mStreamType);
@@ -571,7 +571,7 @@
                         .PRIORITY_CATEGORY_ALARMS) != 0;
                 mAllowMedia = (mNotificationPolicy.priorityCategories
                         & NotificationManager.Policy.PRIORITY_CATEGORY_MEDIA) != 0;
-                mAllowRinger = !ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(
+                mAllowRinger = !ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(
                         mNotificationPolicy);
                 updateSlider();
             }
diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java
index 5e201e4..fd1381a 100644
--- a/core/java/android/provider/DeviceConfig.java
+++ b/core/java/android/provider/DeviceConfig.java
@@ -257,10 +257,20 @@
     /**
      * Namespace for storage-related features.
      *
+     * @deprecated Replace storage namespace with storage_native_boot.
+     * @hide
+     */
+    @Deprecated
+    @SystemApi
+    public static final String NAMESPACE_STORAGE = "storage";
+
+    /**
+     * Namespace for storage-related features, including native and boot.
+     *
      * @hide
      */
     @SystemApi
-    public static final String NAMESPACE_STORAGE = "storage";
+    public static final String NAMESPACE_STORAGE_NATIVE_BOOT = "storage_native_boot";
 
     /**
      * Namespace for System UI related features.
diff --git a/core/java/android/provider/SearchIndexablesContract.java b/core/java/android/provider/SearchIndexablesContract.java
index 5f8266d..298628e 100644
--- a/core/java/android/provider/SearchIndexablesContract.java
+++ b/core/java/android/provider/SearchIndexablesContract.java
@@ -84,9 +84,9 @@
     /**
      * Last path segment for Preference Key, Slice Uri pair.
      * <p>
-     *     The (Key, Slice Uri) pairs are a mapping between the primary key of the search result and
-     *     a Uri for a Slice that represents the same data. Thus, an app can specify a list of Uris
-     *     for Slices that replace regular intent-based search results with inline content.
+     * The (Key, Slice Uri) pairs are a mapping between the primary key of the search result and
+     * a Uri for a Slice that represents the same data. Thus, an app can specify a list of Uris
+     * for Slices that replace regular intent-based search results with inline content.
      * </p>
      */
     public static final String SLICE_URI_PAIRS = "slice_uri_pairs";
@@ -96,6 +96,22 @@
      */
     public static final String SLICE_URI_PAIRS_PATH = SETTINGS + "/" + SLICE_URI_PAIRS;
 
+
+    /**
+     * Dynamic indexable raw data names.
+     *
+     * @hide
+     */
+    public static final String DYNAMIC_INDEXABLES_RAW = "dynamic_indexables_raw";
+
+    /**
+     * ContentProvider path for dynamic indexable raw data.
+     *
+     * @hide
+     */
+    public static final String DYNAMIC_INDEXABLES_RAW_PATH =
+            SETTINGS + "/" + DYNAMIC_INDEXABLES_RAW;
+
     /**
      * Indexable xml resources columns.
      */
@@ -212,7 +228,7 @@
      * Cursor schema for SliceUriPairs.
      */
     @NonNull
-    public static final String[] SLICE_URI_PAIRS_COLUMNS = new String[]{
+    public static final String[] SLICE_URI_PAIRS_COLUMNS = new String[] {
             SliceUriPairColumns.KEY,
             SliceUriPairColumns.SLICE_URI
     };
diff --git a/core/java/android/provider/SearchIndexablesProvider.java b/core/java/android/provider/SearchIndexablesProvider.java
index da29e2e..68284b4 100644
--- a/core/java/android/provider/SearchIndexablesProvider.java
+++ b/core/java/android/provider/SearchIndexablesProvider.java
@@ -77,6 +77,7 @@
     private static final int MATCH_NON_INDEXABLE_KEYS_CODE = 3;
     private static final int MATCH_SITE_MAP_PAIRS_CODE = 4;
     private static final int MATCH_SLICE_URI_PAIRS_CODE = 5;
+    private static final int MATCH_DYNAMIC_RAW_CODE = 6;
 
     /**
      * Implementation is provided by the parent class.
@@ -96,6 +97,8 @@
                 MATCH_SITE_MAP_PAIRS_CODE);
         mMatcher.addURI(mAuthority, SearchIndexablesContract.SLICE_URI_PAIRS_PATH,
                 MATCH_SLICE_URI_PAIRS_CODE);
+        mMatcher.addURI(mAuthority, SearchIndexablesContract.DYNAMIC_INDEXABLES_RAW_PATH,
+                MATCH_DYNAMIC_RAW_CODE);
 
         // Sanity check our setup
         if (!info.exported) {
@@ -126,6 +129,8 @@
                     return querySiteMapPairs();
                 case MATCH_SLICE_URI_PAIRS_CODE:
                     return querySliceUriPairs();
+                case MATCH_DYNAMIC_RAW_CODE:
+                    return queryDynamicRawData(null);
                 default:
                     throw new UnsupportedOperationException("Unknown Uri " + uri);
             }
@@ -191,12 +196,30 @@
         return null;
     }
 
+    /**
+     * Returns all {@link android.provider.SearchIndexablesContract.RawData}.
+     *
+     * Those are the dynamic raw indexable data.
+     *
+     * @param projection list of {@link android.provider.SearchIndexablesContract.RawData} columns
+     *                   to put into the cursor. If {@code null} all supported columns should be
+     *                   included.
+     *
+     * @hide
+     */
+    @Nullable
+    public Cursor queryDynamicRawData(String[] projection) {
+        // By default no-op;
+        return null;
+    }
+
     @Override
     public String getType(Uri uri) {
         switch (mMatcher.match(uri)) {
             case MATCH_RES_CODE:
                 return SearchIndexablesContract.XmlResource.MIME_TYPE;
             case MATCH_RAW_CODE:
+            case MATCH_DYNAMIC_RAW_CODE:
                 return SearchIndexablesContract.RawData.MIME_TYPE;
             case MATCH_NON_INDEXABLE_KEYS_CODE:
                 return SearchIndexablesContract.NonIndexableKey.MIME_TYPE;
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 8b20f0b..e4e8bf7 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -7631,6 +7631,19 @@
                 "face_unlock_always_require_confirmation";
 
         /**
+         * Whether or not a user should re enroll their face.
+         *
+         * Face unlock re enroll.
+         *  0 = No re enrollment.
+         *  1 = Re enrollment is suggested.
+         *  2 = Re enrollment is required after a set time period.
+         *  3 = Re enrollment is required immediately.
+         *
+         * @hide
+         */
+        public static final String FACE_UNLOCK_RE_ENROLL = "face_unlock_re_enroll";
+
+        /**
          * Whether or not debugging is enabled.
          * @hide
          */
@@ -7881,14 +7894,6 @@
         public static final String DEVICE_PAIRED = "device_paired";
 
         /**
-         * Integer state indicating whether package verifier is enabled.
-         * TODO(b/34259924): Remove this setting.
-         *
-         * @hide
-         */
-        public static final String PACKAGE_VERIFIER_STATE = "package_verifier_state";
-
-        /**
          * Specifies additional package name for broadcasting the CMAS messages.
          * @hide
          */
@@ -7903,16 +7908,6 @@
         public static final String NOTIFICATION_BADGING = "notification_badging";
 
         /**
-         * Whether the notification bubbles are globally enabled
-         * The value is boolean (1 or 0).
-         * @hide
-         * @deprecated use {@link Global#NOTIFICATION_BUBBLES} instead.
-         */
-        @TestApi
-        @Deprecated
-        public static final String NOTIFICATION_BUBBLES = "notification_bubbles";
-
-        /**
          * Whether notifications are dismissed by a right-to-left swipe (instead of a left-to-right
          * swipe).
          *
diff --git a/core/java/android/service/autofill/AutofillFieldClassificationService.java b/core/java/android/service/autofill/AutofillFieldClassificationService.java
index 320dcec6..28842a7 100644
--- a/core/java/android/service/autofill/AutofillFieldClassificationService.java
+++ b/core/java/android/service/autofill/AutofillFieldClassificationService.java
@@ -93,6 +93,13 @@
      */
     public static final String REQUIRED_ALGORITHM_EXACT_MATCH = "EXACT_MATCH";
 
+    /**
+     * Field classification algorithm that compares a credit card string to known last four digits.
+     *
+     * <p>Service implementation must provide this algorithm.</p>
+     */
+    public static final String REQUIRED_ALGORITHM_CREDIT_CARD = "CREDIT_CARD";
+
     /** {@hide} **/
     public static final String EXTRA_SCORES = "scores";
 
diff --git a/core/java/android/service/carrier/CarrierService.java b/core/java/android/service/carrier/CarrierService.java
index aeb186b..9184d6d 100644
--- a/core/java/android/service/carrier/CarrierService.java
+++ b/core/java/android/service/carrier/CarrierService.java
@@ -16,17 +16,15 @@
 
 import android.annotation.CallSuper;
 import android.app.Service;
+import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.PersistableBundle;
-import android.os.RemoteException;
 import android.os.ResultReceiver;
-import android.os.ServiceManager;
+import android.os.telephony.TelephonyRegistryManager;
 import android.util.Log;
 
-import com.android.internal.telephony.ITelephonyRegistry;
-
 /**
  * A service that exposes carrier-specific functionality to the system.
  * <p>
@@ -55,16 +53,10 @@
 
     public static final String CARRIER_SERVICE_INTERFACE = "android.service.carrier.CarrierService";
 
-    private static ITelephonyRegistry sRegistry;
-
     private final ICarrierService.Stub mStubWrapper;
 
     public CarrierService() {
         mStubWrapper = new ICarrierServiceWrapper();
-        if (sRegistry == null) {
-            sRegistry = ITelephonyRegistry.Stub.asInterface(
-                    ServiceManager.getService("telephony.registry"));
-        }
     }
 
     /**
@@ -122,9 +114,12 @@
      * @see android.telephony.TelephonyManager#hasCarrierPrivileges
      */
     public final void notifyCarrierNetworkChange(boolean active) {
-        try {
-            if (sRegistry != null) sRegistry.notifyCarrierNetworkChange(active);
-        } catch (RemoteException | NullPointerException ex) {}
+        TelephonyRegistryManager telephonyRegistryMgr =
+            (TelephonyRegistryManager) this.getSystemService(
+                Context.TELEPHONY_REGISTRY_SERVICE);
+        if (telephonyRegistryMgr != null) {
+            telephonyRegistryMgr.notifyCarrierNetworkChange(active);
+        }
     }
 
     /**
diff --git a/core/java/android/service/euicc/EuiccService.java b/core/java/android/service/euicc/EuiccService.java
index ff8b135..8a9f689 100644
--- a/core/java/android/service/euicc/EuiccService.java
+++ b/core/java/android/service/euicc/EuiccService.java
@@ -15,6 +15,8 @@
  */
 package android.service.euicc;
 
+import static android.telephony.euicc.EuiccCardManager.ResetOption;
+
 import android.annotation.CallSuper;
 import android.annotation.IntDef;
 import android.annotation.NonNull;
@@ -503,7 +505,7 @@
             String nickname);
 
     /**
-     * Erase all of the subscriptions on the device.
+     * Erase all operational subscriptions on the device.
      *
      * <p>This is intended to be used for device resets. As such, the reset should be performed even
      * if an active SIM must be deactivated in order to access the eUICC.
@@ -512,10 +514,31 @@
      * @return the result of the erase operation. May be one of the predefined {@code RESULT_}
      *     constants or any implementation-specific code starting with {@link #RESULT_FIRST_USER}.
      * @see android.telephony.euicc.EuiccManager#eraseSubscriptions
+     *
+     * @deprecated From R, callers should specify a flag for specific set of subscriptions to erase
+     * and use @link{onEraseSubscriptionsWithOptions} instead
      */
+    @Deprecated
     public abstract int onEraseSubscriptions(int slotId);
 
     /**
+     * Erase specific subscriptions on the device.
+     *
+     * <p>This is intended to be used for device resets. As such, the reset should be performed even
+     * if an active SIM must be deactivated in order to access the eUICC.
+     *
+     * @param slotIndex index of the SIM slot to use for the operation.
+     * @param options flag for specific group of subscriptions to erase
+     * @return the result of the erase operation. May be one of the predefined {@code RESULT_}
+     *     constants or any implementation-specific code starting with {@link #RESULT_FIRST_USER}.
+     * @see android.telephony.euicc.EuiccManager#eraseSubscriptionsWithOptions
+     */
+    public int onEraseSubscriptionsWithOptions(int slotIndex, @ResetOption int options) {
+        throw new UnsupportedOperationException(
+                "This method must be overridden to enable the ResetOption parameter");
+    }
+
+    /**
      * Ensure that subscriptions will be retained on the next factory reset.
      *
      * <p>Called directly before a factory reset. Assumes that a normal factory reset will lead to
@@ -751,6 +774,23 @@
         }
 
         @Override
+        public void eraseSubscriptionsWithOptions(
+                int slotIndex, @ResetOption int options, IEraseSubscriptionsCallback callback) {
+            mExecutor.execute(new Runnable() {
+                @Override
+                public void run() {
+                    int result = EuiccService.this.onEraseSubscriptionsWithOptions(
+                            slotIndex, options);
+                    try {
+                        callback.onComplete(result);
+                    } catch (RemoteException e) {
+                        // Can't communicate with the phone process; ignore.
+                    }
+                }
+            });
+        }
+
+        @Override
         public void retainSubscriptionsForFactoryReset(int slotId,
                 IRetainSubscriptionsForFactoryResetCallback callback) {
             mExecutor.execute(new Runnable() {
diff --git a/core/java/android/service/euicc/IEuiccService.aidl b/core/java/android/service/euicc/IEuiccService.aidl
index c2cdf09..2acc47a 100644
--- a/core/java/android/service/euicc/IEuiccService.aidl
+++ b/core/java/android/service/euicc/IEuiccService.aidl
@@ -52,6 +52,8 @@
     void updateSubscriptionNickname(int slotId, String iccid, String nickname,
             in IUpdateSubscriptionNicknameCallback callback);
     void eraseSubscriptions(int slotId, in IEraseSubscriptionsCallback callback);
+    void eraseSubscriptionsWithOptions(
+            int slotIndex, int options, in IEraseSubscriptionsCallback callback);
     void retainSubscriptionsForFactoryReset(
             int slotId, in IRetainSubscriptionsForFactoryResetCallback callback);
 }
\ No newline at end of file
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java
index 937990f7..1f2c872 100644
--- a/core/java/android/service/notification/ZenModeConfig.java
+++ b/core/java/android/service/notification/ZenModeConfig.java
@@ -1904,10 +1904,10 @@
     }
 
     /**
-     * Determines whether dnd behavior should mute all notification/ringer sounds
-     * (sounds associated with ringer volume discluding system)
+     * Determines whether dnd behavior should mute all ringer-controlled sounds
+     * This includes notification, ringer and system sounds
      */
-    public static boolean areAllPriorityOnlyNotificationZenSoundsMuted(NotificationManager.Policy
+    public static boolean areAllPriorityOnlyRingerSoundsMuted(NotificationManager.Policy
             policy) {
         boolean allowReminders = (policy.priorityCategories
                 & NotificationManager.Policy.PRIORITY_CATEGORY_REMINDERS) != 0;
@@ -1920,20 +1920,19 @@
         boolean allowRepeatCallers = (policy.priorityCategories
                 & NotificationManager.Policy.PRIORITY_CATEGORY_REPEAT_CALLERS) != 0;
         boolean areChannelsBypassingDnd = (policy.state & Policy.STATE_CHANNELS_BYPASSING_DND) != 0;
+        boolean allowSystem =  (policy.priorityCategories & Policy.PRIORITY_CATEGORY_SYSTEM) != 0;
         return !allowReminders && !allowCalls && !allowMessages && !allowEvents
-                && !allowRepeatCallers && !areChannelsBypassingDnd;
+                && !allowRepeatCallers && !areChannelsBypassingDnd && !allowSystem;
     }
 
     /**
-     * Determines whether dnd behavior should mute all sounds controlled by ringer
+     * Determines whether dnd behavior should mute all sounds
      */
     public static boolean areAllZenBehaviorSoundsMuted(NotificationManager.Policy
             policy) {
         boolean allowAlarms = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_ALARMS) != 0;
         boolean allowMedia = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_MEDIA) != 0;
-        boolean allowSystem = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_SYSTEM) != 0;
-        return !allowAlarms && !allowMedia && !allowSystem
-                && areAllPriorityOnlyNotificationZenSoundsMuted(policy);
+        return !allowAlarms && !allowMedia && areAllPriorityOnlyRingerSoundsMuted(policy);
     }
 
     /**
@@ -1943,24 +1942,25 @@
         return zen == Global.ZEN_MODE_NO_INTERRUPTIONS
                 || zen == Global.ZEN_MODE_ALARMS
                 || (zen == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS
-                && ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(consolidatedPolicy));
+                && ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(consolidatedPolicy));
     }
 
     /**
-     * Determines whether dnd behavior should mute all sounds controlled by ringer
+     * Determines whether dnd behavior should mute all ringer-controlled sounds
+     * This includes notification, ringer and system sounds
      */
-    public static boolean areAllPriorityOnlyNotificationZenSoundsMuted(ZenModeConfig config) {
+    public static boolean areAllPriorityOnlyRingerSoundsMuted(ZenModeConfig config) {
         return !config.allowReminders && !config.allowCalls && !config.allowMessages
                 && !config.allowEvents && !config.allowRepeatCallers
-                && !config.areChannelsBypassingDnd;
+                && !config.areChannelsBypassingDnd && !config.allowSystem;
     }
 
     /**
-     * Determines whether all dnd mutes all sounds
+     * Determines whether dnd mutes all sounds
      */
     public static boolean areAllZenBehaviorSoundsMuted(ZenModeConfig config) {
-        return !config.allowAlarms  && !config.allowMedia && !config.allowSystem
-                && areAllPriorityOnlyNotificationZenSoundsMuted(config);
+        return !config.allowAlarms  && !config.allowMedia
+                && areAllPriorityOnlyRingerSoundsMuted(config);
     }
 
     /**
diff --git a/core/java/android/service/textclassifier/TextClassifierService.java b/core/java/android/service/textclassifier/TextClassifierService.java
index 5143f18..2470d19 100644
--- a/core/java/android/service/textclassifier/TextClassifierService.java
+++ b/core/java/android/service/textclassifier/TextClassifierService.java
@@ -58,8 +58,8 @@
  * Abstract base class for the TextClassifier service.
  *
  * <p>A TextClassifier service provides text classification related features for the system.
- * The system's default TextClassifierService is configured in
- * {@code config_defaultTextClassifierService}. If this config has no value, a
+ * The system's default TextClassifierService provider is configured in
+ * {@code config_defaultTextClassifierPackage}. If this config has no value, a
  * {@link android.view.textclassifier.TextClassifierImpl} is loaded in the calling app's process.
  *
  * <p>See: {@link TextClassifier}.
diff --git a/core/java/android/speech/RecognitionService.java b/core/java/android/speech/RecognitionService.java
index 70dfef5..dfc5c82 100644
--- a/core/java/android/speech/RecognitionService.java
+++ b/core/java/android/speech/RecognitionService.java
@@ -170,13 +170,23 @@
      * Checks whether the caller has sufficient permissions
      * 
      * @param listener to send the error message to in case of error
+     * @param forDataDelivery If the permission check is for delivering the sensitive data.
      * @return {@code true} if the caller has enough permissions, {@code false} otherwise
      */
-    private boolean checkPermissions(IRecognitionListener listener) {
+    private boolean checkPermissions(IRecognitionListener listener, boolean forDataDelivery) {
         if (DBG) Log.d(TAG, "checkPermissions");
-        if (PermissionChecker.checkCallingOrSelfPermission(this,
-                android.Manifest.permission.RECORD_AUDIO) == PermissionChecker.PERMISSION_GRANTED) {
-            return true;
+        if (forDataDelivery) {
+            if (PermissionChecker.checkCallingOrSelfPermissionForDataDelivery(this,
+                    android.Manifest.permission.RECORD_AUDIO, null /*message*/)
+                             == PermissionChecker.PERMISSION_GRANTED) {
+                return true;
+            }
+        } else {
+            if (PermissionChecker.checkCallingOrSelfPermissionForPreflight(this,
+                    android.Manifest.permission.RECORD_AUDIO)
+                            == PermissionChecker.PERMISSION_GRANTED) {
+                return true;
+            }
         }
         try {
             Log.e(TAG, "call for recognition service without RECORD_AUDIO permissions");
@@ -342,7 +352,7 @@
         public void startListening(Intent recognizerIntent, IRecognitionListener listener) {
             if (DBG) Log.d(TAG, "startListening called by:" + listener.asBinder());
             final RecognitionService service = mServiceRef.get();
-            if (service != null && service.checkPermissions(listener)) {
+            if (service != null && service.checkPermissions(listener, true /*forDataDelivery*/)) {
                 service.mHandler.sendMessage(Message.obtain(service.mHandler,
                         MSG_START_LISTENING, service.new StartListeningArgs(
                                 recognizerIntent, listener, Binder.getCallingUid())));
@@ -353,7 +363,7 @@
         public void stopListening(IRecognitionListener listener) {
             if (DBG) Log.d(TAG, "stopListening called by:" + listener.asBinder());
             final RecognitionService service = mServiceRef.get();
-            if (service != null && service.checkPermissions(listener)) {
+            if (service != null && service.checkPermissions(listener, false /*forDataDelivery*/)) {
                 service.mHandler.sendMessage(Message.obtain(service.mHandler,
                         MSG_STOP_LISTENING, listener));
             }
@@ -363,7 +373,7 @@
         public void cancel(IRecognitionListener listener) {
             if (DBG) Log.d(TAG, "cancel called by:" + listener.asBinder());
             final RecognitionService service = mServiceRef.get();
-            if (service != null && service.checkPermissions(listener)) {
+            if (service != null && service.checkPermissions(listener, false /*forDataDelivery*/)) {
                 service.mHandler.sendMessage(Message.obtain(service.mHandler,
                         MSG_CANCEL, listener));
             }
diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java
index 81643e9..5bda867 100644
--- a/core/java/android/text/TextUtils.java
+++ b/core/java/android/text/TextUtils.java
@@ -36,6 +36,7 @@
 import android.sysprop.DisplayProperties;
 import android.text.style.AbsoluteSizeSpan;
 import android.text.style.AccessibilityClickableSpan;
+import android.text.style.AccessibilityReplacementSpan;
 import android.text.style.AccessibilityURLSpan;
 import android.text.style.AlignmentSpan;
 import android.text.style.BackgroundColorSpan;
@@ -735,6 +736,8 @@
     /** @hide */
     public static final int LINE_HEIGHT_SPAN = 28;
     /** @hide */
+    public static final int ACCESSIBILITY_REPLACEMENT_SPAN = 29;
+    /** @hide */
     public static final int LAST_SPAN = LINE_HEIGHT_SPAN;
 
     /**
@@ -860,7 +863,7 @@
 
                 case LEADING_MARGIN_SPAN:
                     readSpan(p, sp, new LeadingMarginSpan.Standard(p));
-                break;
+                    break;
 
                 case URL_SPAN:
                     readSpan(p, sp, new URLSpan(p));
@@ -933,7 +936,11 @@
                 case LINE_HEIGHT_SPAN:
                     readSpan(p, sp, new LineHeightSpan.Standard(p));
                     break;
-                    
+
+                case ACCESSIBILITY_REPLACEMENT_SPAN:
+                    readSpan(p, sp, new AccessibilityReplacementSpan(p));
+                    break;
+
                 default:
                     throw new RuntimeException("bogus span encoding " + kind);
                 }
diff --git a/core/java/android/text/style/AccessibilityReplacementSpan.java b/core/java/android/text/style/AccessibilityReplacementSpan.java
new file mode 100644
index 0000000..07b0975
--- /dev/null
+++ b/core/java/android/text/style/AccessibilityReplacementSpan.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2019 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.text.style;
+
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.text.ParcelableSpan;
+import android.text.TextUtils;
+
+/**
+ * This class serves as a parcelable placeholder for the ReplacementSpans.
+ *
+ * This span contains content description of original span to let Accessibility service to do the
+ * substitution for it.
+ *
+ * @hide
+ */
+public class AccessibilityReplacementSpan extends ReplacementSpan
+        implements ParcelableSpan {
+    // The content description of the span this one replaces
+    private CharSequence mContentDescription;
+
+    /**
+     * @param contentDescription The content description of the span this one replaces
+     */
+    public AccessibilityReplacementSpan(CharSequence contentDescription) {
+        this.setContentDescription(contentDescription);
+        mContentDescription = contentDescription;
+    }
+
+    public AccessibilityReplacementSpan(Parcel p) {
+        mContentDescription = p.readCharSequence();
+    }
+
+    @Override
+    public int getSpanTypeId() {
+        return getSpanTypeIdInternal();
+    }
+
+    @Override
+    public int getSpanTypeIdInternal() {
+        return TextUtils.ACCESSIBILITY_REPLACEMENT_SPAN;
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        writeToParcelInternal(dest, flags);
+    }
+
+    @Override
+    public void writeToParcelInternal(Parcel dest, int flags) {
+        dest.writeCharSequence(mContentDescription);
+    }
+
+    @Override
+    public int getSize(Paint paint, CharSequence text, int start, int end,
+            Paint.FontMetricsInt fm) {
+        return 0;
+    }
+
+    @Override
+    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y,
+            int bottom, Paint paint) {
+    }
+
+    public static final @android.annotation.NonNull
+    Parcelable.Creator<AccessibilityReplacementSpan> CREATOR =
+            new Parcelable.Creator<AccessibilityReplacementSpan>() {
+        @Override
+        public AccessibilityReplacementSpan createFromParcel(Parcel parcel) {
+            return new AccessibilityReplacementSpan(parcel);
+        }
+
+        @Override
+        public AccessibilityReplacementSpan[] newArray(int size) {
+            return new AccessibilityReplacementSpan[size];
+        }
+    };
+}
diff --git a/core/java/android/text/style/ReplacementSpan.java b/core/java/android/text/style/ReplacementSpan.java
index 5f94ad0..0553232 100644
--- a/core/java/android/text/style/ReplacementSpan.java
+++ b/core/java/android/text/style/ReplacementSpan.java
@@ -25,6 +25,8 @@
 
 public abstract class ReplacementSpan extends MetricAffectingSpan {
 
+    private CharSequence mContentDescription = null;
+
     /**
      * Returns the width of the span. Extending classes can set the height of the span by updating
      * attributes of {@link android.graphics.Paint.FontMetricsInt}. If the span covers the whole
@@ -61,6 +63,27 @@
                               int top, int y, int bottom, @NonNull Paint paint);
 
     /**
+     * Gets a brief description of this ImageSpan for use in accessibility support.
+     *
+     * @return The content description.
+     */
+    @Nullable
+    public CharSequence getContentDescription() {
+        return mContentDescription;
+    }
+
+    /**
+     * Sets the specific content description into ImageSpan.
+     * ReplacementSpans are shared with accessibility services,
+     * but only the content description is available from them.
+     *
+     * @param contentDescription content description. The default value is null.
+     */
+    public void setContentDescription(@Nullable CharSequence contentDescription) {
+        mContentDescription = contentDescription;
+    }
+
+    /**
      * This method does nothing, since ReplacementSpans are measured
      * explicitly instead of affecting Paint properties.
      */
diff --git a/core/java/android/util/ArraySet.java b/core/java/android/util/ArraySet.java
index 44c5af2..4dda709 100644
--- a/core/java/android/util/ArraySet.java
+++ b/core/java/android/util/ArraySet.java
@@ -16,6 +16,7 @@
 
 package android.util;
 
+import android.annotation.Nullable;
 import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 
@@ -329,6 +330,18 @@
     }
 
     /**
+     * Create a new ArraySet with items from the given array
+     */
+    public ArraySet(@Nullable E[] array) {
+        this();
+        if (array != null) {
+            for (E value : array) {
+                add(value);
+            }
+        }
+    }
+
+    /**
      * Make the array map empty.  All storage is released.
      */
     @Override
diff --git a/core/java/android/util/FeatureFlagUtils.java b/core/java/android/util/FeatureFlagUtils.java
index b66764e..1be57dd 100644
--- a/core/java/android/util/FeatureFlagUtils.java
+++ b/core/java/android/util/FeatureFlagUtils.java
@@ -59,6 +59,7 @@
         DEFAULT_FLAGS.put("settings_wifi_details_datausage_header", "false");
         DEFAULT_FLAGS.put("settings_skip_direction_mutable", "true");
         DEFAULT_FLAGS.put(SETTINGS_WIFITRACKER2, "false");
+        DEFAULT_FLAGS.put("settings_work_profile", "false");
     }
 
     /**
diff --git a/core/java/android/util/OWNERS b/core/java/android/util/OWNERS
index 98297fb..8f3d9f6 100644
--- a/core/java/android/util/OWNERS
+++ b/core/java/android/util/OWNERS
@@ -1,3 +1,3 @@
 per-file FeatureFlagUtils.java = sbasi@google.com
-per-file FeatureFlagUtils.java = zhfan@google.com
+per-file FeatureFlagUtils.java = tmfang@google.com
 per-file FeatureFlagUtils.java = asapperstein@google.com
diff --git a/core/java/android/util/StatsEvent.java b/core/java/android/util/StatsEvent.java
new file mode 100644
index 0000000..91a5ec0
--- /dev/null
+++ b/core/java/android/util/StatsEvent.java
@@ -0,0 +1,331 @@
+/*
+ * Copyright (C) 2019 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 static java.nio.charset.StandardCharsets.UTF_8;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+
+import com.android.internal.annotations.GuardedBy;
+
+/**
+ * StatsEvent builds and stores the buffer sent over the statsd socket.
+ * This class defines and encapsulates the socket protocol.
+ * @hide
+ **/
+public final class StatsEvent implements AutoCloseable {
+    private static final int POS_NUM_ELEMENTS = 1;
+    private static final int POS_TIMESTAMP = POS_NUM_ELEMENTS + 1;
+
+    private static final int LOGGER_ENTRY_MAX_PAYLOAD = 4068;
+
+    // Max payload size is 4 KB less 4 bytes which are reserved for statsEventTag.
+    // See android_util_StatsLog.cpp.
+    private static final int MAX_EVENT_PAYLOAD = LOGGER_ENTRY_MAX_PAYLOAD - 4;
+
+    private static final byte INT_TYPE = 0;
+    private static final byte LONG_TYPE = 1;
+    private static final byte STRING_TYPE = 2;
+    private static final byte LIST_TYPE = 3;
+    private static final byte FLOAT_TYPE = 4;
+
+    private static final int INT_TYPE_SIZE = 5;
+    private static final int FLOAT_TYPE_SIZE = 5;
+    private static final int LONG_TYPE_SIZE = 9;
+
+    private static final int STRING_TYPE_OVERHEAD = 5;
+    private static final int LIST_TYPE_OVERHEAD = 2;
+
+    public static final int SUCCESS = 0;
+    public static final int ERROR_BUFFER_LIMIT_EXCEEDED = -1;
+    public static final int ERROR_NO_TIMESTAMP = -2;
+    public static final int ERROR_TIMESTAMP_ALREADY_WRITTEN = -3;
+    public static final int ERROR_NO_ATOM_ID = -4;
+    public static final int ERROR_ATOM_ID_ALREADY_WRITTEN = -5;
+    public static final int ERROR_UID_TAG_COUNT_MISMATCH = -6;
+
+    private static Object sLock = new Object();
+
+    @GuardedBy("sLock")
+    private static StatsEvent sPool;
+
+    private final byte[] mBuffer = new byte[MAX_EVENT_PAYLOAD];
+    private int mPos;
+    private int mNumElements;
+    private int mAtomId;
+
+    private StatsEvent() {
+        // Write LIST_TYPE to buffer
+        mBuffer[0] = LIST_TYPE;
+        reset();
+    }
+
+    private void reset() {
+        // Reset state.
+        mPos = POS_TIMESTAMP;
+        mNumElements = 0;
+        mAtomId = 0;
+    }
+
+    /**
+     * Returns a StatsEvent object from the pool.
+     **/
+    @NonNull
+    public static StatsEvent obtain() {
+        final StatsEvent statsEvent;
+        synchronized (sLock) {
+            statsEvent = null == sPool ? new StatsEvent() : sPool;
+            sPool = null;
+        }
+        statsEvent.reset();
+        return statsEvent;
+    }
+
+    @Override
+    public void close() {
+        synchronized (sLock) {
+            if (null == sPool) {
+                sPool = this;
+            }
+        }
+    }
+
+    /**
+     * Writes the event timestamp to the buffer.
+     **/
+    public int writeTimestampNs(final long timestampNs) {
+        if (hasTimestamp()) {
+            return ERROR_TIMESTAMP_ALREADY_WRITTEN;
+        }
+        return writeLong(timestampNs);
+    }
+
+    private boolean hasTimestamp() {
+        return mPos > POS_TIMESTAMP;
+    }
+
+    private boolean hasAtomId() {
+        return mAtomId != 0;
+    }
+
+    /**
+     * Writes the atom id to the buffer.
+     **/
+    public int writeAtomId(final int atomId) {
+        if (!hasTimestamp()) {
+            return ERROR_NO_TIMESTAMP;
+        } else if (hasAtomId()) {
+            return ERROR_ATOM_ID_ALREADY_WRITTEN;
+        }
+
+        final int writeResult = writeInt(atomId);
+        if (SUCCESS == writeResult) {
+            mAtomId = atomId;
+        }
+        return writeResult;
+    }
+
+    /**
+     * Appends the given int to the StatsEvent buffer.
+     **/
+    public int writeInt(final int value) {
+        if (!hasTimestamp()) {
+            return ERROR_NO_TIMESTAMP;
+        } else if (!hasAtomId()) {
+            return ERROR_NO_ATOM_ID;
+        } else if (mPos + INT_TYPE_SIZE > MAX_EVENT_PAYLOAD) {
+            return ERROR_BUFFER_LIMIT_EXCEEDED;
+        }
+
+        mBuffer[mPos] = INT_TYPE;
+        copyInt(mBuffer, mPos + 1, value);
+        mPos += INT_TYPE_SIZE;
+        mNumElements++;
+        return SUCCESS;
+    }
+
+    /**
+     * Appends the given long to the StatsEvent buffer.
+     **/
+    public int writeLong(final long value) {
+        if (!hasTimestamp()) {
+            return ERROR_NO_TIMESTAMP;
+        } else if (!hasAtomId()) {
+            return ERROR_NO_ATOM_ID;
+        } else if (mPos + LONG_TYPE_SIZE > MAX_EVENT_PAYLOAD) {
+            return ERROR_BUFFER_LIMIT_EXCEEDED;
+        }
+
+        mBuffer[mPos] = LONG_TYPE;
+        copyLong(mBuffer, mPos + 1, value);
+        mPos += LONG_TYPE_SIZE;
+        mNumElements++;
+        return SUCCESS;
+    }
+
+    /**
+     * Appends the given float to the StatsEvent buffer.
+     **/
+    public int writeFloat(final float value) {
+        if (!hasTimestamp()) {
+            return ERROR_NO_TIMESTAMP;
+        } else if (!hasAtomId()) {
+            return ERROR_NO_ATOM_ID;
+        } else if (mPos + FLOAT_TYPE_SIZE > MAX_EVENT_PAYLOAD) {
+            return ERROR_BUFFER_LIMIT_EXCEEDED;
+        }
+
+        mBuffer[mPos] = FLOAT_TYPE;
+        copyInt(mBuffer, mPos + 1, Float.floatToIntBits(value));
+        mPos += FLOAT_TYPE_SIZE;
+        mNumElements++;
+        return SUCCESS;
+    }
+
+    /**
+     * Appends the given boolean to the StatsEvent buffer.
+     **/
+    public int writeBoolean(final boolean value) {
+        return writeInt(value ? 1 : 0);
+    }
+
+    /**
+     * Appends the given byte array to the StatsEvent buffer.
+     **/
+    public int writeByteArray(@NonNull final byte[] value) {
+        if (!hasTimestamp()) {
+            return ERROR_NO_TIMESTAMP;
+        } else if (!hasAtomId()) {
+            return ERROR_NO_ATOM_ID;
+        } else if (mPos + STRING_TYPE_OVERHEAD + value.length > MAX_EVENT_PAYLOAD) {
+            return ERROR_BUFFER_LIMIT_EXCEEDED;
+        }
+
+        mBuffer[mPos] = STRING_TYPE;
+        copyInt(mBuffer, mPos + 1, value.length);
+        System.arraycopy(value, 0, mBuffer, mPos + STRING_TYPE_OVERHEAD, value.length);
+        mPos += STRING_TYPE_OVERHEAD + value.length;
+        mNumElements++;
+        return SUCCESS;
+    }
+
+    /**
+     * Appends the given String to the StatsEvent buffer.
+     **/
+    public int writeString(@NonNull final String value) {
+        final byte[] valueBytes = stringToBytes(value);
+        return writeByteArray(valueBytes);
+    }
+
+    /**
+     * Appends the AttributionNode specified as array of uids and array of tags.
+     **/
+    public int writeAttributionNode(@NonNull final int[] uids, @NonNull final String[] tags) {
+        if (!hasTimestamp()) {
+            return ERROR_NO_TIMESTAMP;
+        } else if (!hasAtomId()) {
+            return ERROR_NO_ATOM_ID;
+        } else if (mPos + LIST_TYPE_OVERHEAD > MAX_EVENT_PAYLOAD) {
+            return ERROR_BUFFER_LIMIT_EXCEEDED;
+        }
+
+        final int numTags = tags.length;
+        final int numUids = uids.length;
+        if (numTags != numUids) {
+            return ERROR_UID_TAG_COUNT_MISMATCH;
+        }
+
+        int pos = mPos;
+        mBuffer[pos] = LIST_TYPE;
+        mBuffer[pos + 1] = (byte) numTags;
+        pos += LIST_TYPE_OVERHEAD;
+        for (int i = 0; i < numTags; i++) {
+            final byte[] tagBytes = stringToBytes(tags[i]);
+
+            if (pos + LIST_TYPE_OVERHEAD + INT_TYPE_SIZE
+                    + STRING_TYPE_OVERHEAD + tagBytes.length > MAX_EVENT_PAYLOAD) {
+                return ERROR_BUFFER_LIMIT_EXCEEDED;
+            }
+
+            mBuffer[pos] = LIST_TYPE;
+            mBuffer[pos + 1] = 2;
+            pos += LIST_TYPE_OVERHEAD;
+            mBuffer[pos] = INT_TYPE;
+            copyInt(mBuffer, pos + 1, uids[i]);
+            pos += INT_TYPE_SIZE;
+            mBuffer[pos] = STRING_TYPE;
+            copyInt(mBuffer, pos + 1, tagBytes.length);
+            System.arraycopy(tagBytes, 0, mBuffer, pos + STRING_TYPE_OVERHEAD, tagBytes.length);
+            pos += STRING_TYPE_OVERHEAD + tagBytes.length;
+        }
+        mPos = pos;
+        mNumElements++;
+        return SUCCESS;
+    }
+
+    /**
+     * Returns the byte array containing data in the statsd socket format.
+     * @hide
+     **/
+    @NonNull
+    public byte[] getBuffer() {
+        // Encode number of elements in the buffer.
+        mBuffer[POS_NUM_ELEMENTS] = (byte) mNumElements;
+        return mBuffer;
+    }
+
+    /**
+     * Returns number of bytes used by the buffer.
+     * @hide
+     **/
+    public int size() {
+        return mPos;
+    }
+
+    /**
+     * Getter for atom id.
+     * @hide
+     **/
+    public int getAtomId() {
+        return mAtomId;
+    }
+
+    @NonNull
+    private static byte[] stringToBytes(@Nullable final String value) {
+        return (null == value ? "" : value).getBytes(UTF_8);
+    }
+
+    // Helper methods for copying primitives
+    private static void copyInt(@NonNull byte[] buff, int pos, int value) {
+        buff[pos] = (byte) (value);
+        buff[pos + 1] = (byte) (value >> 8);
+        buff[pos + 2] = (byte) (value >> 16);
+        buff[pos + 3] = (byte) (value >> 24);
+    }
+
+    private static void copyLong(@NonNull byte[] buff, int pos, long value) {
+        buff[pos] = (byte) (value);
+        buff[pos + 1] = (byte) (value >> 8);
+        buff[pos + 2] = (byte) (value >> 16);
+        buff[pos + 3] = (byte) (value >> 24);
+        buff[pos + 4] = (byte) (value >> 32);
+        buff[pos + 5] = (byte) (value >> 40);
+        buff[pos + 6] = (byte) (value >> 48);
+        buff[pos + 7] = (byte) (value >> 56);
+    }
+}
diff --git a/core/java/android/view/CompositionSamplingListener.java b/core/java/android/view/CompositionSamplingListener.java
index 368445c..677a559 100644
--- a/core/java/android/view/CompositionSamplingListener.java
+++ b/core/java/android/view/CompositionSamplingListener.java
@@ -28,7 +28,7 @@
  */
 public abstract class CompositionSamplingListener {
 
-    private final long mNativeListener;
+    private long mNativeListener;
     private final Executor mExecutor;
 
     public CompositionSamplingListener(Executor executor) {
@@ -36,13 +36,19 @@
         mNativeListener = nativeCreate(this);
     }
 
+    public void destroy() {
+        if (mNativeListener == 0) {
+            return;
+        }
+        unregister(this);
+        nativeDestroy(mNativeListener);
+        mNativeListener = 0;
+    }
+
     @Override
     protected void finalize() throws Throwable {
         try {
-            if (mNativeListener != 0) {
-                unregister(this);
-                nativeDestroy(mNativeListener);
-            }
+            destroy();
         } finally {
             super.finalize();
         }
@@ -58,6 +64,9 @@
      */
     public static void register(CompositionSamplingListener listener,
             int displayId, SurfaceControl stopLayer, Rect samplingArea) {
+        if (listener.mNativeListener == 0) {
+            return;
+        }
         Preconditions.checkArgument(displayId == Display.DEFAULT_DISPLAY,
                 "default display only for now");
         long nativeStopLayerObject = stopLayer != null ? stopLayer.mNativeObject : 0;
@@ -69,6 +78,9 @@
      * Unregisters a sampling listener.
      */
     public static void unregister(CompositionSamplingListener listener) {
+        if (listener.mNativeListener == 0) {
+            return;
+        }
         nativeUnregister(listener.mNativeListener);
     }
 
diff --git a/core/java/android/view/DragAndDropPermissions.java b/core/java/android/view/DragAndDropPermissions.java
index e72ff38..d47604d 100644
--- a/core/java/android/view/DragAndDropPermissions.java
+++ b/core/java/android/view/DragAndDropPermissions.java
@@ -37,7 +37,7 @@
  * View.startDragAndDrop} by the app that started the drag operation.
  * </p>
  * <p>
- * The life cycle of the permissions is bound to the activity used to call {@link
+ * The lifecycle of the permissions is bound to the activity used to call {@link
  * android.app.Activity#requestDragAndDropPermissions(DragEvent) requestDragAndDropPermissions}. The
  * permissions are revoked when this activity is destroyed, or when {@link #release()} is called,
  * whichever occurs first.
@@ -49,6 +49,10 @@
  * {@link Activity#onSaveInstanceState} bundle and later retrieved in order to manually release
  * the permissions once they are no longer needed.
  * </p>
+ * <p>
+ * Learn more about <a href="/guide/topics/ui/drag-drop#DragPermissionsMultiWindow">drag permissions
+ * in multi-window mode</a>.
+ * </p>
  */
 public final class DragAndDropPermissions implements Parcelable {
 
diff --git a/core/java/android/view/IPinnedStackListener.aidl b/core/java/android/view/IPinnedStackListener.aidl
index 806d81e..f4bee57 100644
--- a/core/java/android/view/IPinnedStackListener.aidl
+++ b/core/java/android/view/IPinnedStackListener.aidl
@@ -55,14 +55,6 @@
     void onImeVisibilityChanged(boolean imeVisible, int imeHeight);
 
     /**
-     * Called when window manager decides to adjust the pinned stack bounds because of the shelf, or
-     * when the listener is first registered to allow the listener to synchronized its state with
-     * the controller.  This call will always be followed by a onMovementBoundsChanged() call
-     * with fromShelfAdjustment set to {@code true}.
-     */
-    void onShelfVisibilityChanged(boolean shelfVisible, int shelfHeight);
-
-    /**
      * Called when window manager decides to adjust the minimized state, or when the listener
      * is first registered to allow the listener to synchronized its state with the controller.
      */
diff --git a/core/java/android/view/IWindow.aidl b/core/java/android/view/IWindow.aidl
index f34f9e6..4b872d3 100644
--- a/core/java/android/view/IWindow.aidl
+++ b/core/java/android/view/IWindow.aidl
@@ -73,6 +73,14 @@
      */
     void insetsControlChanged(in InsetsState insetsState, in InsetsSourceControl[] activeControls);
 
+    /**
+     * Called when a set of insets source window should be shown by policy.
+     *
+     * @param types internal inset types (WindowInsets.Type.InsetType) to show
+     * @param fromIme true if this request originated from IME (InputMethodService).
+     */
+    void showInsets(int types, boolean fromIme);
+
     void moved(int newX, int newY);
     void dispatchAppVisibility(boolean visible);
     void dispatchGetNewSurface();
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index 1c32948..35cfe9e 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -326,12 +326,6 @@
     oneway void setPipVisibility(boolean visible);
 
     /**
-     * Called by System UI to notify of changes to the visibility and height of the shelf.
-     */
-    @UnsupportedAppUsage
-    void setShelfHeight(boolean visible, int shelfHeight);
-
-    /**
      * Called by System UI to enable or disable haptic feedback on the navigation bar buttons.
      */
     @UnsupportedAppUsage
@@ -650,4 +644,16 @@
      * Enables/disables SurfaceFlinger layer tracing.
      */
     void setLayerTracing(boolean enabled);
+
+    /**
+     * Mirrors a specified display. The root of the mirrored hierarchy will be stored in
+     * outSurfaceControl.
+     * Requires the ACCESS_SURFACE_FLINGER permission.
+     *
+     * @param displayId The id of the display to mirror
+     * @param outSurfaceControl The SurfaceControl for the root of the mirrored hierarchy.
+     *
+     * @return true if the display was successfully mirrored.
+     */
+    boolean mirrorDisplay(int displayId, out SurfaceControl outSurfaceControl);
 }
diff --git a/core/java/android/view/InputMonitor.java b/core/java/android/view/InputMonitor.java
index bbd27dc..1a1d7e6 100644
--- a/core/java/android/view/InputMonitor.java
+++ b/core/java/android/view/InputMonitor.java
@@ -21,6 +21,8 @@
 import android.os.Parcelable;
 import android.os.RemoteException;
 
+import com.android.internal.util.DataClass;
+
 /**
  * An {@code InputMonitor} allows privileged applications and components to monitor streams of
  * {@link InputEvent}s without having to be the designated recipient for the event.
@@ -31,57 +33,19 @@
  *
  * @hide
  */
+@DataClass(genToString = true)
 public final class InputMonitor implements Parcelable {
     private static final String TAG = "InputMonitor";
 
     private static final boolean DEBUG = false;
 
-    public static final Parcelable.Creator<InputMonitor> CREATOR =
-            new Parcelable.Creator<InputMonitor>() {
-
-            public InputMonitor createFromParcel(Parcel source) {
-                return new InputMonitor(source);
-            }
-
-            public InputMonitor[] newArray(int size) {
-                return new InputMonitor[size];
-            }
-    };
-
     @NonNull
     private final String mName;
     @NonNull
-    private final InputChannel mChannel;
+    private final InputChannel mInputChannel;
     @NonNull
     private final IInputMonitorHost mHost;
 
-    public InputMonitor(@NonNull String name, @NonNull InputChannel channel,
-            @NonNull IInputMonitorHost host) {
-        mName = name;
-        mChannel = channel;
-        mHost = host;
-    }
-
-    public InputMonitor(Parcel in) {
-        mName = in.readString();
-        mChannel = in.readParcelable(null);
-        mHost = IInputMonitorHost.Stub.asInterface(in.readStrongBinder());
-    }
-
-    /**
-     * Get the {@link InputChannel} corresponding to this InputMonitor
-     */
-    public InputChannel getInputChannel() {
-        return mChannel;
-    }
-
-    /**
-     * Get the name of this channel.
-     */
-    public String getName() {
-        return mName;
-    }
-
 
     /**
      * Takes all of the current pointer events streams that are currently being sent to this
@@ -107,7 +71,7 @@
      * no longer be used.
      */
     public void dispose() {
-        mChannel.dispose();
+        mInputChannel.dispose();
         try {
             mHost.dispose();
         } catch (RemoteException e) {
@@ -115,20 +79,108 @@
         }
     }
 
-    @Override
-    public void writeToParcel(Parcel out, int flags) {
-        out.writeString(mName);
-        out.writeParcelable(mChannel, flags);
-        out.writeStrongBinder(mHost.asBinder());
+
+
+    // Code below generated by codegen v1.0.1.
+    //
+    // DO NOT MODIFY!
+    //
+    // To regenerate run:
+    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/view/InputMonitor.java
+    //
+    // CHECKSTYLE:OFF Generated code
+
+    @DataClass.Generated.Member
+    public InputMonitor(
+            @NonNull String name,
+            @NonNull InputChannel inputChannel,
+            @NonNull IInputMonitorHost host) {
+        this.mName = name;
+        com.android.internal.util.AnnotationValidations.validate(
+                NonNull.class, null, mName);
+        this.mInputChannel = inputChannel;
+        com.android.internal.util.AnnotationValidations.validate(
+                NonNull.class, null, mInputChannel);
+        this.mHost = host;
+        com.android.internal.util.AnnotationValidations.validate(
+                NonNull.class, null, mHost);
+
+        // onConstructed(); // You can define this method to get a callback
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull String getName() {
+        return mName;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull InputChannel getInputChannel() {
+        return mInputChannel;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull IInputMonitorHost getHost() {
+        return mHost;
     }
 
     @Override
-    public int describeContents() {
-        return 0;
-    }
-
-    @Override
+    @DataClass.Generated.Member
     public String toString() {
-        return "InputMonitor{mName=" + mName + ", mChannel=" + mChannel + ", mHost=" + mHost + "}";
+        // You can override field toString logic by defining methods like:
+        // String fieldNameToString() { ... }
+
+        return "InputMonitor { " +
+                "name = " + mName + ", " +
+                "inputChannel = " + mInputChannel + ", " +
+                "host = " + mHost +
+        " }";
     }
+
+    @Override
+    @DataClass.Generated.Member
+    public void writeToParcel(Parcel dest, int flags) {
+        // You can override field parcelling by defining methods like:
+        // void parcelFieldName(Parcel dest, int flags) { ... }
+
+        dest.writeString(mName);
+        dest.writeTypedObject(mInputChannel, flags);
+        dest.writeStrongInterface(mHost);
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public int describeContents() { return 0; }
+
+    @DataClass.Generated.Member
+    public static final @NonNull Parcelable.Creator<InputMonitor> CREATOR
+            = new Parcelable.Creator<InputMonitor>() {
+        @Override
+        public InputMonitor[] newArray(int size) {
+            return new InputMonitor[size];
+        }
+
+        @Override
+        @SuppressWarnings({"unchecked", "RedundantCast"})
+        public InputMonitor createFromParcel(Parcel in) {
+            // You can override field unparcelling by defining methods like:
+            // static FieldType unparcelFieldName(Parcel in) { ... }
+
+            String name = in.readString();
+            InputChannel inputChannel = (InputChannel) in.readTypedObject(InputChannel.CREATOR);
+            IInputMonitorHost host = IInputMonitorHost.Stub.asInterface(in.readStrongBinder());
+            return new InputMonitor(
+                    name,
+                    inputChannel,
+                    host);
+        }
+    };
+
+    @DataClass.Generated(
+            time = 1569871940995L,
+            codegenVersion = "1.0.1",
+            sourceFile = "frameworks/base/core/java/android/view/InputMonitor.java",
+            inputSignatures = "private static final  java.lang.String TAG\nprivate static final  boolean DEBUG\nprivate final @android.annotation.NonNull java.lang.String mName\nprivate final @android.annotation.NonNull android.view.InputChannel mInputChannel\nprivate final @android.annotation.NonNull android.view.IInputMonitorHost mHost\npublic  void pilferPointers()\npublic  void dispose()\nclass InputMonitor extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true)")
+    @Deprecated
+    private void __metadata() {}
+
 }
diff --git a/core/java/android/view/InsetsController.java b/core/java/android/view/InsetsController.java
index c798d85..5a8636d 100644
--- a/core/java/android/view/InsetsController.java
+++ b/core/java/android/view/InsetsController.java
@@ -224,7 +224,7 @@
         show(types, false /* fromIme */);
     }
 
-    private void show(@InsetType int types, boolean fromIme) {
+    void show(@InsetType int types, boolean fromIme) {
         // TODO: Support a ResultReceiver for IME.
         // TODO(b/123718661): Make show() work for multi-session IME.
         int typesReady = 0;
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index d5559aa..6637c5b0 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -91,7 +91,7 @@
             boolean captureSecureLayers);
     private static native ScreenshotGraphicBuffer nativeCaptureLayers(IBinder displayToken,
             long layerObject, Rect sourceCrop, float frameScale, long[] excludeLayerObjects);
-
+    private static native long nativeMirrorSurface(long mirrorOfObject);
     private static native long nativeCreateTransaction();
     private static native long nativeGetNativeTransactionFinalizer();
     private static native void nativeApplyTransaction(long transactionObj, boolean sync);
@@ -181,14 +181,12 @@
     private static native void nativeSeverChildren(long transactionObj, long nativeObject);
     private static native void nativeSetOverrideScalingMode(long transactionObj, long nativeObject,
             int scalingMode);
-    private static native boolean nativeGetTransformToDisplayInverse(long nativeObject);
 
     private static native Display.HdrCapabilities nativeGetHdrCapabilities(IBinder displayToken);
 
     private static native void nativeSetInputWindowInfo(long transactionObj, long nativeObject,
             InputWindowHandle handle);
-    private static native void nativeTransferTouchFocus(long transactionObj, IBinder fromToken,
-            IBinder toToken);
+
     private static native boolean nativeGetProtectedContentSupport();
     private static native void nativeSetMetadata(long transactionObj, long nativeObject, int key,
             Parcel data);
@@ -304,8 +302,8 @@
     /**
      * Surface creation flag: Creates a Dim surface.
      * Everything behind this surface is dimmed by the amount specified
-     * in {@link #setAlpha}.  It is an error to lock a Dim surface, since it
-     * doesn't have a backing store.
+     * in {@link Transaction#setAlpha(SurfaceControl, float)}.  It is an error to lock a Dim
+     * surface, since it doesn't have a backing store.
      *
      * @hide
      */
@@ -741,20 +739,20 @@
      * <p>
      * Good practice is to first create the surface with the {@link #HIDDEN} flag
      * specified, open a transaction, set the surface layer, layer stack, alpha,
-     * and position, call {@link #show} if appropriate, and close the transaction.
+     * and position, call {@link Transaction#show(SurfaceControl)} if appropriate, and close the
+     * transaction.
      * <p>
      * Bounds of the surface is determined by its crop and its buffer size. If the
      * surface has no buffer or crop, the surface is boundless and only constrained
      * by the size of its parent bounds.
      *
-     * @param session The surface session, must not be null.
-     * @param name The surface name, must not be null.
-     * @param w The surface initial width.
-     * @param h The surface initial height.
-     * @param flags The surface creation flags.  Should always include {@link #HIDDEN}
-     * in the creation flags.
+     * @param session  The surface session, must not be null.
+     * @param name     The surface name, must not be null.
+     * @param w        The surface initial width.
+     * @param h        The surface initial height.
+     * @param flags    The surface creation flags.  Should always include {@link #HIDDEN}
+     *                 in the creation flags.
      * @param metadata Initial metadata.
-     *
      * @throws throws OutOfResourcesException If the SurfaceControl cannot be created.
      */
     private SurfaceControl(SurfaceSession session, String name, int w, int h, int format, int flags,
@@ -1015,15 +1013,6 @@
     /**
      * @hide
      */
-    public void deferTransactionUntil(Surface barrier, long frame) {
-        synchronized(SurfaceControl.class) {
-            sGlobalTransaction.deferTransactionUntilSurface(this, barrier, frame);
-        }
-    }
-
-    /**
-     * @hide
-     */
     public void reparentChildren(SurfaceControl newParent) {
         synchronized(SurfaceControl.class) {
             sGlobalTransaction.reparentChildren(this, newParent);
@@ -1033,15 +1022,6 @@
     /**
      * @hide
      */
-    public void reparent(SurfaceControl newParent) {
-        synchronized(SurfaceControl.class) {
-            sGlobalTransaction.reparent(this, newParent);
-        }
-    }
-
-    /**
-     * @hide
-     */
     public void detachChildren() {
         synchronized(SurfaceControl.class) {
             sGlobalTransaction.detachChildren(this);
@@ -1061,15 +1041,6 @@
     /**
      * @hide
      */
-    public static void setAnimationTransaction() {
-        synchronized (SurfaceControl.class) {
-            sGlobalTransaction.setAnimationTransaction();
-        }
-    }
-
-    /**
-     * @hide
-     */
     @UnsupportedAppUsage
     public void setLayer(int zorder) {
         checkNotReleased();
@@ -1081,16 +1052,6 @@
     /**
      * @hide
      */
-    public void setRelativeLayer(SurfaceControl relativeTo, int zorder) {
-        checkNotReleased();
-        synchronized(SurfaceControl.class) {
-            sGlobalTransaction.setRelativeLayer(this, relativeTo, zorder);
-        }
-    }
-
-    /**
-     * @hide
-     */
     @UnsupportedAppUsage
     public void setPosition(float x, float y) {
         checkNotReleased();
@@ -1184,16 +1145,6 @@
     /**
      * @hide
      */
-    public void setColor(@Size(3) float[] color) {
-        checkNotReleased();
-        synchronized (SurfaceControl.class) {
-            sGlobalTransaction.setColor(this, color);
-        }
-    }
-
-    /**
-     * @hide
-     */
     public void setMatrix(float dsdx, float dtdx, float dtdy, float dsdy) {
         checkNotReleased();
         synchronized(SurfaceControl.class) {
@@ -1202,36 +1153,6 @@
     }
 
     /**
-     * Sets the transform and position of a {@link SurfaceControl} from a 3x3 transformation matrix.
-     *
-     * @param matrix The matrix to apply.
-     * @param float9 An array of 9 floats to be used to extract the values from the matrix.
-     * @hide
-     */
-    public void setMatrix(Matrix matrix, float[] float9) {
-        checkNotReleased();
-        matrix.getValues(float9);
-        synchronized (SurfaceControl.class) {
-            sGlobalTransaction.setMatrix(this, float9[MSCALE_X], float9[MSKEW_Y],
-                    float9[MSKEW_X], float9[MSCALE_Y]);
-            sGlobalTransaction.setPosition(this, float9[MTRANS_X], float9[MTRANS_Y]);
-        }
-    }
-
-    /**
-     * Sets the color transform for the Surface.
-     * @param matrix A float array with 9 values represents a 3x3 transform matrix
-     * @param translation A float array with 3 values represents a translation vector
-     * @hide
-     */
-    public void setColorTransform(@Size(9) float[] matrix, @Size(3) float[] translation) {
-        checkNotReleased();
-        synchronized (SurfaceControl.class) {
-            sGlobalTransaction.setColorTransform(this, matrix, translation);
-        }
-    }
-
-    /**
      * Sets the Surface to be color space agnostic. If a surface is color space agnostic,
      * the color can be interpreted in any color space.
      * @param agnostic A boolean to indicate whether the surface is color space agnostic
@@ -1261,43 +1182,6 @@
     }
 
     /**
-     * Same as {@link SurfaceControl#setWindowCrop(Rect)} but sets the crop rect top left at 0, 0.
-     *
-     * @param width width of crop rect
-     * @param height height of crop rect
-     * @hide
-     */
-    public void setWindowCrop(int width, int height) {
-        checkNotReleased();
-        synchronized (SurfaceControl.class) {
-            sGlobalTransaction.setWindowCrop(this, width, height);
-        }
-    }
-
-    /**
-     * Sets the corner radius of a {@link SurfaceControl}.
-     *
-     * @param cornerRadius Corner radius in pixels.
-     * @hide
-     */
-    public void setCornerRadius(float cornerRadius) {
-        checkNotReleased();
-        synchronized (SurfaceControl.class) {
-            sGlobalTransaction.setCornerRadius(this, cornerRadius);
-        }
-    }
-
-    /**
-     * @hide
-     */
-    public void setLayerStack(int layerStack) {
-        checkNotReleased();
-        synchronized(SurfaceControl.class) {
-            sGlobalTransaction.setLayerStack(this, layerStack);
-        }
-    }
-
-    /**
      * @hide
      */
     public void setOpaque(boolean isOpaque) {
@@ -2035,6 +1919,28 @@
         return nativeSetDisplayBrightness(displayToken, brightness);
     }
 
+    /**
+     * Creates a mirrored hierarchy for the mirrorOf {@link SurfaceControl}
+     *
+     * Real Hierarchy    Mirror
+     *                     SC (value that's returned)
+     *                      |
+     *      A               A'
+     *      |               |
+     *      B               B'
+     *
+     * @param mirrorOf The root of the hierarchy that should be mirrored.
+     * @return A SurfaceControl that's the parent of the root of the mirrored hierarchy.
+     *
+     * @hide
+     */
+    public static SurfaceControl mirrorSurface(SurfaceControl mirrorOf) {
+        long nativeObj = nativeMirrorSurface(mirrorOf.mNativeObject);
+        SurfaceControl sc = new SurfaceControl();
+        sc.assignNativeObject(nativeObj);
+        return sc;
+    }
+
      /**
      * An atomic set of changes to a set of SurfaceControl.
      */
@@ -2239,22 +2145,6 @@
         }
 
         /**
-         * Transfers touch focus from one window to another. It is possible for multiple windows to
-         * have touch focus if they support split touch dispatch
-         * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
-         * method only transfers touch focus of the specified window without affecting
-         * other windows that may also have touch focus at the same time.
-         * @param fromToken The token of a window that currently has touch focus.
-         * @param toToken The token of the window that should receive touch focus in
-         * place of the first.
-         * @hide
-         */
-        public Transaction transferTouchFocus(IBinder fromToken, IBinder toToken) {
-            nativeTransferTouchFocus(mNativeObject, fromToken, toToken);
-            return this;
-        }
-
-        /**
          * Waits until any changes to input windows have been sent from SurfaceFlinger to
          * InputFlinger before returning.
          *
@@ -2297,6 +2187,12 @@
         }
 
         /**
+         * Sets the transform and position of a {@link SurfaceControl} from a 3x3 transformation
+         * matrix.
+         *
+         * @param sc     SurfaceControl to set matrix of
+         * @param matrix The matrix to apply.
+         * @param float9 An array of 9 floats to be used to extract the values from the matrix.
          * @hide
          */
         @UnsupportedAppUsage
@@ -2310,7 +2206,9 @@
 
         /**
          * Sets the color transform for the Surface.
-         * @param matrix A float array with 9 values represents a 3x3 transform matrix
+         *
+         * @param sc          SurfaceControl to set color transform of
+         * @param matrix      A float array with 9 values represents a 3x3 transform matrix
          * @param translation A float array with 3 values represents a translation vector
          * @hide
          */
@@ -2334,6 +2232,13 @@
         }
 
         /**
+         * Bounds the surface and its children to the bounds specified. Size of the surface will be
+         * ignored and only the crop and buffer size will be used to determine the bounds of the
+         * surface. If no crop is specified and the surface has no buffer, the surface bounds is
+         * only constrained by the size of its parent bounds.
+         *
+         * @param sc   SurfaceControl to set crop of.
+         * @param crop Bounds of the crop to apply.
          * @hide
          */
         @UnsupportedAppUsage
@@ -2350,6 +2255,12 @@
         }
 
         /**
+         * Same as {@link Transaction#setWindowCrop(SurfaceControl, Rect)} but sets the crop rect
+         * top left at 0, 0.
+         *
+         * @param sc     SurfaceControl to set crop of.
+         * @param width  width of crop rect
+         * @param height height of crop rect
          * @hide
          */
         public Transaction setWindowCrop(SurfaceControl sc, int width, int height) {
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 90e69f3..2f0a4eb 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -136,6 +136,7 @@
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
     boolean mIsCreating = false;
     private volatile boolean mRtHandlingPositionUpdates = false;
+    private volatile boolean mRtReleaseSurfaces = false;
 
     private final ViewTreeObserver.OnScrollChangedListener mScrollChangedListener =
             this::updateSurface;
@@ -166,6 +167,7 @@
 
     boolean mUseAlpha = false;
     float mSurfaceAlpha = 1f;
+    boolean mClipSurfaceToBounds;
 
     @UnsupportedAppUsage
     boolean mHaveFrame = false;
@@ -416,12 +418,7 @@
                     Log.d(TAG, System.identityHashCode(this)
                             + " updateSurfaceAlpha: set alpha=" + alpha);
                 }
-                SurfaceControl.openTransaction();
-                try {
-                    mSurfaceControl.setAlpha(alpha);
-                } finally {
-                    SurfaceControl.closeTransaction();
-                }
+                mTmpTransaction.setAlpha(mSurfaceControl, alpha).apply();
             }
             mSurfaceAlpha = alpha;
         }
@@ -554,9 +551,52 @@
         super.dispatchDraw(canvas);
     }
 
+    /**
+     * Control whether the surface is clipped to the same bounds as the View. If true, then
+     * the bounds set by {@link #setClipBounds(Rect)} are applied to the surface as window-crop.
+     *
+     * @param enabled whether to enable surface clipping
+     * @hide
+     */
+    public void setEnableSurfaceClipping(boolean enabled) {
+        mClipSurfaceToBounds = enabled;
+        invalidate();
+    }
+
+    @Override
+    public void setClipBounds(Rect clipBounds) {
+        super.setClipBounds(clipBounds);
+
+        if (!mClipSurfaceToBounds) {
+            return;
+        }
+
+        // When cornerRadius is non-zero, a draw() is required to update
+        // the viewport (rounding the corners of the clipBounds).
+        if (mCornerRadius > 0f && !isAboveParent()) {
+            invalidate();
+        }
+
+        if (mSurfaceControl != null) {
+            if (mClipBounds != null) {
+                mTmpRect.set(mClipBounds);
+            } else {
+                mTmpRect.set(0, 0, mSurfaceWidth, mSurfaceHeight);
+            }
+            SyncRtSurfaceTransactionApplier applier = new SyncRtSurfaceTransactionApplier(this);
+            applier.scheduleApply(
+                    new SyncRtSurfaceTransactionApplier.SurfaceParams.Builder(mSurfaceControl)
+                            .withWindowCrop(mTmpRect)
+                            .build());
+        }
+    }
+
     private void clearSurfaceViewPort(Canvas canvas) {
         if (mCornerRadius > 0f) {
             canvas.getClipBounds(mTmpRect);
+            if (mClipSurfaceToBounds && mClipBounds != null) {
+                mTmpRect.intersect(mClipBounds);
+            }
             canvas.drawRoundRect(mTmpRect.left, mTmpRect.top, mTmpRect.right, mTmpRect.bottom,
                     mCornerRadius, mCornerRadius, mRoundedViewportPaint);
         } else {
@@ -582,6 +622,16 @@
     }
 
     /**
+     * Returns the corner radius for the SurfaceView.
+
+     * @return the radius of the corners in pixels
+     * @hide
+     */
+    public float getCornerRadius() {
+        return mCornerRadius;
+    }
+
+    /**
      * Control whether the surface view's surface is placed on top of another
      * regular surface view in the window (but still behind the window itself).
      * This is typically used to place overlays on top of an underlying media
@@ -646,19 +696,27 @@
         }
     }
 
-    private void updateBackgroundVisibilityInTransaction() {
+    private void updateBackgroundVisibility(Transaction t) {
         if (mBackgroundControl == null) {
             return;
         }
         if ((mSubLayer < 0) && ((mSurfaceFlags & SurfaceControl.OPAQUE) != 0)) {
-            mBackgroundControl.show();
+            t.show(mBackgroundControl);
         } else {
-            mBackgroundControl.hide();
+            t.hide(mBackgroundControl);
         }
     }
 
+
     private void releaseSurfaces() {
+        mSurfaceAlpha = 1f;
+
         synchronized (mSurfaceControlLock) {
+            if (mRtHandlingPositionUpdates) {
+                mRtReleaseSurfaces = true;
+                return;
+            }
+
             if (mSurfaceControl != null) {
                 mTmpTransaction.remove(mSurfaceControl);
                 mSurfaceControl = null;
@@ -667,9 +725,9 @@
                 mTmpTransaction.remove(mBackgroundControl);
                 mBackgroundControl = null;
             }
+            mSurface.release();
             mTmpTransaction.apply();
         }
-        mSurfaceAlpha = 1f;
     }
 
     /** @hide */
@@ -791,56 +849,60 @@
                     if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
                             + "Cur surface: " + mSurface);
 
-                    SurfaceControl.openTransaction();
-                    try {
-                        // If we are creating the surface control or the parent surface has not
-                        // changed, then set relative z. Otherwise allow the parent
-                        // SurfaceChangedCallback to update the relative z. This is needed so that
-                        // we do not change the relative z before the server is ready to swap the
-                        // parent surface.
-                        if (creating || (mParentSurfaceGenerationId
-                                == viewRoot.mSurface.getGenerationId())) {
-                            SurfaceControl.mergeToGlobalTransaction(updateRelativeZ());
-                        }
-                        mParentSurfaceGenerationId = viewRoot.mSurface.getGenerationId();
-
-                        if (mViewVisibility) {
-                            mSurfaceControl.show();
-                        } else {
-                            mSurfaceControl.hide();
-                        }
-                        updateBackgroundVisibilityInTransaction();
-                        if (mUseAlpha) {
-                            mSurfaceControl.setAlpha(alpha);
-                            mSurfaceAlpha = alpha;
-                        }
-
-                        // While creating the surface, we will set it's initial
-                        // geometry. Outside of that though, we should generally
-                        // leave it to the RenderThread.
-                        //
-                        // There is one more case when the buffer size changes we aren't yet
-                        // prepared to sync (as even following the transaction applying
-                        // we still need to latch a buffer).
-                        // b/28866173
-                        if (sizeChanged || creating || !mRtHandlingPositionUpdates) {
-                            mSurfaceControl.setPosition(mScreenRect.left, mScreenRect.top);
-                            mSurfaceControl.setMatrix(mScreenRect.width() / (float) mSurfaceWidth,
-                                    0.0f, 0.0f,
-                                    mScreenRect.height() / (float) mSurfaceHeight);
-                            // Set a window crop when creating the surface or changing its size to
-                            // crop the buffer to the surface size since the buffer producer may
-                            // use SCALING_MODE_SCALE and submit a larger size than the surface
-                            // size.
-                            mSurfaceControl.setWindowCrop(mSurfaceWidth, mSurfaceHeight);
-                        }
-                        mSurfaceControl.setCornerRadius(mCornerRadius);
-                        if (sizeChanged && !creating) {
-                            mSurfaceControl.setBufferSize(mSurfaceWidth, mSurfaceHeight);
-                        }
-                    } finally {
-                        SurfaceControl.closeTransaction();
+                    // If we are creating the surface control or the parent surface has not
+                    // changed, then set relative z. Otherwise allow the parent
+                    // SurfaceChangedCallback to update the relative z. This is needed so that
+                    // we do not change the relative z before the server is ready to swap the
+                    // parent surface.
+                    if (creating || (mParentSurfaceGenerationId
+                            == viewRoot.mSurface.getGenerationId())) {
+                        updateRelativeZ(mTmpTransaction);
                     }
+                    mParentSurfaceGenerationId = viewRoot.mSurface.getGenerationId();
+
+                    if (mViewVisibility) {
+                        mTmpTransaction.show(mSurfaceControl);
+                    } else {
+                        mTmpTransaction.hide(mSurfaceControl);
+                    }
+                    updateBackgroundVisibility(mTmpTransaction);
+                    if (mUseAlpha) {
+                        mTmpTransaction.setAlpha(mSurfaceControl, alpha);
+                        mSurfaceAlpha = alpha;
+                    }
+
+                    // While creating the surface, we will set it's initial
+                    // geometry. Outside of that though, we should generally
+                    // leave it to the RenderThread.
+                    //
+                    // There is one more case when the buffer size changes we aren't yet
+                    // prepared to sync (as even following the transaction applying
+                    // we still need to latch a buffer).
+                    // b/28866173
+                    if (sizeChanged || creating || !mRtHandlingPositionUpdates) {
+                        mTmpTransaction.setPosition(mSurfaceControl, mScreenRect.left,
+                                mScreenRect.top);
+                        mTmpTransaction.setMatrix(mSurfaceControl,
+                                mScreenRect.width() / (float) mSurfaceWidth, 0.0f, 0.0f,
+                                mScreenRect.height() / (float) mSurfaceHeight);
+                        // Set a window crop when creating the surface or changing its size to
+                        // crop the buffer to the surface size since the buffer producer may
+                        // use SCALING_MODE_SCALE and submit a larger size than the surface
+                        // size.
+                        if (mClipSurfaceToBounds && mClipBounds != null) {
+                            mTmpTransaction.setWindowCrop(mSurfaceControl, mClipBounds);
+                        } else {
+                            mTmpTransaction.setWindowCrop(mSurfaceControl, mSurfaceWidth,
+                                    mSurfaceHeight);
+                        }
+                    }
+                    mTmpTransaction.setCornerRadius(mSurfaceControl, mCornerRadius);
+                    if (sizeChanged && !creating) {
+                        mTmpTransaction.setBufferSize(mSurfaceControl, mSurfaceWidth,
+                                mSurfaceHeight);
+                    }
+
+                    mTmpTransaction.apply();
 
                     if (sizeChanged || creating) {
                         redrawNeeded = true;
@@ -955,7 +1017,6 @@
                 } finally {
                     mIsCreating = false;
                     if (mSurfaceControl != null && !mSurfaceCreated) {
-                        mSurface.release();
                         releaseSurfaces();
                     }
                 }
@@ -1084,7 +1145,9 @@
             // the synchronization would violate the rule that RT must never block
             // on the UI thread which would open up potential deadlocks. The risk of
             // a single-frame desync is therefore preferable for now.
-            mRtHandlingPositionUpdates = true;
+            synchronized(mSurfaceControlLock) {
+                mRtHandlingPositionUpdates = true;
+            }
             if (mRTLastReportedPosition.left == left
                     && mRTLastReportedPosition.top == top
                     && mRTLastReportedPosition.right == right
@@ -1119,13 +1182,27 @@
                 return;
             }
 
-            if (frameNumber > 0) {
-                final ViewRootImpl viewRoot = getViewRootImpl();
-
-                mRtTransaction.deferTransactionUntilSurface(mSurfaceControl, viewRoot.mSurface,
-                        frameNumber);
+            final ViewRootImpl viewRoot = getViewRootImpl();
+            if (frameNumber > 0 && viewRoot !=  null) {
+                if (viewRoot.mSurface.isValid()) {
+                    mRtTransaction.deferTransactionUntilSurface(mSurfaceControl, viewRoot.mSurface,
+                            frameNumber);
+                }
             }
             mRtTransaction.hide(mSurfaceControl);
+
+            synchronized (mSurfaceControlLock) {
+                if (mRtReleaseSurfaces) {
+                    mRtReleaseSurfaces = false;
+                    mRtTransaction.remove(mSurfaceControl);
+                    mRtTransaction.remove(mBackgroundControl);
+                    mSurfaceControl = null;
+                    mBackgroundControl = null;
+                    mSurface.release();
+                }
+                mRtHandlingPositionUpdates = false;
+            }
+
             mRtTransaction.apply();
         }
     };
@@ -1179,12 +1256,7 @@
         final float[] colorComponents = new float[] { Color.red(bgColor) / 255.f,
                 Color.green(bgColor) / 255.f, Color.blue(bgColor) / 255.f };
 
-        SurfaceControl.openTransaction();
-        try {
-            mBackgroundControl.setColor(colorComponents);
-        } finally {
-            SurfaceControl.closeTransaction();
-        }
+        mTmpTransaction.setColor(mBackgroundControl, colorComponents).apply();
     }
 
     @UnsupportedAppUsage
@@ -1399,15 +1471,13 @@
     @Override
     public void surfaceReplaced(Transaction t) {
         if (mSurfaceControl != null && mBackgroundControl != null) {
-            t.merge(updateRelativeZ());
+            updateRelativeZ(t);
         }
     }
 
-    private Transaction updateRelativeZ() {
-        Transaction t = new Transaction();
+    private void updateRelativeZ(Transaction t) {
         SurfaceControl viewRoot = getViewRootImpl().getSurfaceControl();
         t.setRelativeLayer(mBackgroundControl, viewRoot, Integer.MIN_VALUE);
         t.setRelativeLayer(mSurfaceControl, viewRoot, mSubLayer);
-        return t;
     }
 }
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 82a5fa9..853a302 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -2615,7 +2615,9 @@
                     || actionMasked == MotionEvent.ACTION_CANCEL;
 
             // Update list of touch targets for pointer down, if needed.
-            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
+            final boolean isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
+            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
+                    && !isMouseEvent;
             TouchTarget newTouchTarget = null;
             boolean alreadyDispatchedToNewTouchTarget = false;
             if (!canceled && !intercepted) {
@@ -2632,8 +2634,10 @@
 
                     final int childrenCount = mChildrenCount;
                     if (newTouchTarget == null && childrenCount != 0) {
-                        final float x = ev.getX(actionIndex);
-                        final float y = ev.getY(actionIndex);
+                        final float x =
+                                isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
+                        final float y =
+                                isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex);
                         // Find a child that can receive the event.
                         // Scan children from front to back.
                         final ArrayList<View> preorderedList = buildTouchDispatchChildList();
diff --git a/core/java/android/view/ViewPropertyAnimator.java b/core/java/android/view/ViewPropertyAnimator.java
index 957673d..859e9a4 100644
--- a/core/java/android/view/ViewPropertyAnimator.java
+++ b/core/java/android/view/ViewPropertyAnimator.java
@@ -1138,6 +1138,12 @@
 
             boolean hardwareAccelerated = mView.isHardwareAccelerated();
 
+            // alpha requires slightly different treatment than the other (transform) properties.
+            // The logic in setAlpha() is not simply setting mAlpha, plus the invalidation
+            // logic is dependent on how the view handles an internal call to onSetAlpha().
+            // We track what kinds of properties are set, and how alpha is handled when it is
+            // set, and perform the invalidation steps appropriately.
+            boolean alphaHandled = false;
             if (!hardwareAccelerated) {
                 mView.invalidateParentCaches();
             }
@@ -1152,7 +1158,11 @@
                 for (int i = 0; i < count; ++i) {
                     NameValuesHolder values = valueList.get(i);
                     float value = values.mFromValue + fraction * values.mDeltaValue;
-                    setValue(values.mNameConstant, value);
+                    if (values.mNameConstant == ALPHA) {
+                        alphaHandled = mView.setAlphaNoInvalidation(value);
+                    } else {
+                        setValue(values.mNameConstant, value);
+                    }
                 }
             }
             if ((propertyMask & TRANSFORM_MASK) != 0) {
@@ -1160,8 +1170,13 @@
                     mView.mPrivateFlags |= View.PFLAG_DRAWN; // force another invalidation
                 }
             }
-
-            mView.invalidateViewProperty(false, false);
+            // invalidate(false) in all cases except if alphaHandled gets set to true
+            // via the call to setAlphaNoInvalidation(), above
+            if (alphaHandled) {
+                mView.invalidate(true);
+            } else {
+                mView.invalidateViewProperty(false, false);
+            }
             if (mUpdateListener != null) {
                 mUpdateListener.onAnimationUpdate(animation);
             }
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 3756a7d..fedd6fb 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -91,6 +91,7 @@
 import android.view.View.AttachInfo;
 import android.view.View.FocusDirection;
 import android.view.View.MeasureSpec;
+import android.view.WindowInsets.Type.InsetType;
 import android.view.WindowManager.LayoutParams.SoftInputModeFlags;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityManager;
@@ -4528,6 +4529,8 @@
     private static final int MSG_INSETS_CONTROL_CHANGED = 31;
     private static final int MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED = 32;
     private static final int MSG_LOCATION_IN_PARENT_DISPLAY_CHANGED = 33;
+    private static final int MSG_SHOW_INSETS = 34;
+
 
     final class ViewRootHandler extends Handler {
         @Override
@@ -4591,6 +4594,8 @@
                     return "MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED";
                 case MSG_LOCATION_IN_PARENT_DISPLAY_CHANGED:
                     return "MSG_LOCATION_IN_PARENT_DISPLAY_CHANGED";
+                case MSG_SHOW_INSETS:
+                    return "MSG_SHOW_INSETS";
             }
             return super.getMessageName(message);
         }
@@ -4705,6 +4710,10 @@
                     mInsetsController.onStateChanged((InsetsState) args.arg1);
                     break;
                 }
+                case MSG_SHOW_INSETS: {
+                    mInsetsController.show(msg.arg1, msg.arg2 == 1);
+                    break;
+                }
                 case MSG_WINDOW_MOVED:
                     if (mAdded) {
                         final int w = mWinFrame.width();
@@ -7484,6 +7493,10 @@
         mHandler.obtainMessage(MSG_INSETS_CONTROL_CHANGED, args).sendToTarget();
     }
 
+    private void showInsets(@InsetType int types, boolean fromIme) {
+        mHandler.obtainMessage(MSG_SHOW_INSETS, types, fromIme ? 1 : 0).sendToTarget();
+    }
+
     public void dispatchMoved(int newX, int newY) {
         if (DEBUG_LAYOUT) Log.v(mTag, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
         if (mTranslator != null) {
@@ -8599,6 +8612,14 @@
         }
 
         @Override
+        public void showInsets(@InsetType int types, boolean fromIme) {
+            final ViewRootImpl viewAncestor = mViewAncestor.get();
+            if (viewAncestor != null) {
+                viewAncestor.showInsets(types, fromIme);
+            }
+        }
+
+        @Override
         public void moved(int newX, int newY) {
             final ViewRootImpl viewAncestor = mViewAncestor.get();
             if (viewAncestor != null) {
diff --git a/core/java/android/view/ViewStructure.java b/core/java/android/view/ViewStructure.java
index 5f3ce33..606e8f9 100644
--- a/core/java/android/view/ViewStructure.java
+++ b/core/java/android/view/ViewStructure.java
@@ -230,6 +230,8 @@
     /**
      * Sets the identifier used to set the hint associated with this view.
      *
+     * <p>Used as metadata for fingerprinting view nodes/structures.
+     *
      * <p>Should only be set when the node is used for autofill purposes - it will be ignored
      * when used for Assist.
      */
diff --git a/core/java/android/view/WindowlessViewRoot.java b/core/java/android/view/WindowlessViewRoot.java
index b76e1fa..c2500b8 100644
--- a/core/java/android/view/WindowlessViewRoot.java
+++ b/core/java/android/view/WindowlessViewRoot.java
@@ -41,4 +41,12 @@
     public void addView(View view, WindowManager.LayoutParams attrs) {
         mViewRoot.setView(view, attrs, null);
     }
+
+    public void relayout(WindowManager.LayoutParams attrs) {
+        mViewRoot.setLayoutParams(attrs, false);
+        mViewRoot.setReportNextDraw();
+        mWm.setCompletionCallback(mViewRoot.mWindow.asBinder(), (SurfaceControl.Transaction t) -> {
+            t.apply();
+        });
+    }
 }
diff --git a/core/java/android/view/WindowlessWindowManager.java b/core/java/android/view/WindowlessWindowManager.java
index 430fb6d..f4f7d0b 100644
--- a/core/java/android/view/WindowlessWindowManager.java
+++ b/core/java/android/view/WindowlessWindowManager.java
@@ -39,11 +39,27 @@
 class WindowlessWindowManager implements IWindowSession {
     private final static String TAG = "WindowlessWindowManager";
 
+    private class State {
+        SurfaceControl mSurfaceControl;
+        WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
+        State(SurfaceControl sc, WindowManager.LayoutParams p) {
+            mSurfaceControl = sc;
+            mParams.copyFrom(p);
+        }
+    };
     /**
      * Used to store SurfaceControl we've built for clients to
      * reconfigure them if relayout is called.
      */
-    final HashMap<IBinder, SurfaceControl> mScForWindow = new HashMap<IBinder, SurfaceControl>();
+    final HashMap<IBinder, State> mStateForWindow = new HashMap<IBinder, State>();
+
+    public interface ResizeCompleteCallback {
+        public void finished(SurfaceControl.Transaction completion);
+    }
+
+    final HashMap<IBinder, ResizeCompleteCallback> mResizeCompletionForWindow =
+        new HashMap<IBinder, ResizeCompleteCallback>();
+
     final SurfaceSession mSurfaceSession = new SurfaceSession();
     final SurfaceControl mRootSurface;
     final Configuration mConfiguration;
@@ -58,6 +74,19 @@
         mRealWm = WindowManagerGlobal.getWindowSession();
     }
 
+    /**
+     * Utility API.
+     */
+    void setCompletionCallback(IBinder window, ResizeCompleteCallback callback) {
+        if (mResizeCompletionForWindow.get(window) != null) {
+            Log.w(TAG, "Unsupported overlapping resizes");
+        }
+        mResizeCompletionForWindow.put(window, callback);
+    }
+
+    /**
+     * IWindowSession implementation.
+     */
     public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
             int viewVisibility, int displayId, Rect outFrame, Rect outContentInsets,
             Rect outStableInsets, Rect outOutsets,
@@ -68,7 +97,7 @@
             .setName(attrs.getTitle().toString());
         final SurfaceControl sc = b.build();
         synchronized (this) {
-            mScForWindow.put(window.asBinder(), sc);
+            mStateForWindow.put(window.asBinder(), new State(sc, attrs));
         }
 
         if ((attrs.inputFeatures &
@@ -104,34 +133,40 @@
     }
 
     @Override
-    public int relayout(IWindow window, int seq, WindowManager.LayoutParams attrs,
+    public int relayout(IWindow window, int seq, WindowManager.LayoutParams inAttrs,
             int requestedWidth, int requestedHeight, int viewFlags, int flags, long frameNumber,
             Rect outFrame, Rect outOverscanInsets, Rect outContentInsets, Rect outVisibleInsets,
             Rect outStableInsets, Rect outsets, Rect outBackdropFrame,
             DisplayCutout.ParcelableWrapper cutout, MergedConfiguration mergedConfiguration,
             SurfaceControl outSurfaceControl, InsetsState outInsetsState) {
-        SurfaceControl sc = null;
+        State state = null;
         synchronized (this) {
-            sc = mScForWindow.get(window.asBinder());
+            state = mStateForWindow.get(window.asBinder());
         }
-        if (sc == null) {
+        if (state == null) {
             throw new IllegalArgumentException(
                     "Invalid window token (never added or removed already)");
         }
+        SurfaceControl sc = state.mSurfaceControl;
         SurfaceControl.Transaction t = new SurfaceControl.Transaction();
 
+        if (inAttrs != null) {
+            state.mParams.copyFrom(inAttrs);
+        }
+        WindowManager.LayoutParams attrs = state.mParams;
+
         final Rect surfaceInsets = attrs.surfaceInsets;
         int width = surfaceInsets != null ?
-                requestedWidth + surfaceInsets.left + surfaceInsets.right : requestedWidth;
+                attrs.width + surfaceInsets.left + surfaceInsets.right : attrs.width;
         int height = surfaceInsets != null ?
-                requestedHeight + surfaceInsets.top + surfaceInsets.bottom : requestedHeight;
+                attrs.height + surfaceInsets.top + surfaceInsets.bottom : attrs.height;
 
         t.show(sc)
             .setBufferSize(sc, width, height)
             .setOpaque(sc, isOpaque(attrs))
             .apply();
         outSurfaceControl.copyFrom(sc);
-        outFrame.set(0, 0, requestedWidth, requestedHeight);
+        outFrame.set(0, 0, attrs.width, attrs.height);
 
         mergedConfiguration.setConfiguration(mConfiguration, mConfiguration);
 
@@ -165,6 +200,17 @@
     @Override
     public void finishDrawing(android.view.IWindow window,
             android.view.SurfaceControl.Transaction postDrawTransaction) {
+        synchronized (this) {
+            final ResizeCompleteCallback c =
+                mResizeCompletionForWindow.get(window.asBinder());
+            if (c == null) {
+                // No one wanted the callback, but it wasn't necessarily unexpected.
+                postDrawTransaction.apply();
+                return;
+            }
+            c.finished(postDrawTransaction);
+            mResizeCompletionForWindow.remove(window.asBinder());
+        }
     }
 
     @Override
diff --git a/core/java/android/view/accessibility/AccessibilityInteractionClient.java b/core/java/android/view/accessibility/AccessibilityInteractionClient.java
index d9fa9f2..bb10ef1 100644
--- a/core/java/android/view/accessibility/AccessibilityInteractionClient.java
+++ b/core/java/android/view/accessibility/AccessibilityInteractionClient.java
@@ -259,23 +259,38 @@
     }
 
     /**
-     * Gets the info for all windows.
+     * Gets the info for all windows of the default display.
      *
      * @param connectionId The id of a connection for interacting with the system.
      * @return The {@link AccessibilityWindowInfo} list.
      */
     public List<AccessibilityWindowInfo> getWindows(int connectionId) {
+        final SparseArray<List<AccessibilityWindowInfo>> windows =
+                getWindowsOnAllDisplays(connectionId);
+        if (windows.size() > 0) {
+            return windows.valueAt(Display.DEFAULT_DISPLAY);
+        }
+        return Collections.emptyList();
+    }
+
+    /**
+     * Gets the info for all windows of all displays.
+     *
+     * @param connectionId The id of a connection for interacting with the system.
+     * @return The SparseArray of {@link AccessibilityWindowInfo} list.
+     *         The key of SparseArray is display ID.
+     */
+    public SparseArray<List<AccessibilityWindowInfo>> getWindowsOnAllDisplays(int connectionId) {
         try {
             IAccessibilityServiceConnection connection = getConnection(connectionId);
             if (connection != null) {
-                SparseArray<List<AccessibilityWindowInfo>> allWindows =
+                SparseArray<List<AccessibilityWindowInfo>> windows =
                         sAccessibilityCache.getWindowsOnAllDisplays();
-                List<AccessibilityWindowInfo> windows;
-                if (allWindows != null) {
+                if (windows != null) {
                     if (DEBUG) {
                         Log.i(LOG_TAG, "Windows cache hit");
                     }
-                    return allWindows.valueAt(Display.DEFAULT_DISPLAY);
+                    return windows;
                 }
                 if (DEBUG) {
                     Log.i(LOG_TAG, "Windows cache miss");
@@ -287,9 +302,7 @@
                     Binder.restoreCallingIdentity(identityToken);
                 }
                 if (windows != null) {
-                    allWindows = new SparseArray<>();
-                    allWindows.put(Display.DEFAULT_DISPLAY, windows);
-                    sAccessibilityCache.setWindowsOnAllDisplays(allWindows);
+                    sAccessibilityCache.setWindowsOnAllDisplays(windows);
                     return windows;
                 }
             } else {
@@ -298,9 +311,11 @@
                 }
             }
         } catch (RemoteException re) {
-            Log.e(LOG_TAG, "Error while calling remote getWindows", re);
+            Log.e(LOG_TAG, "Error while calling remote getWindowsOnAllDisplays", re);
         }
-        return Collections.emptyList();
+
+        final SparseArray<List<AccessibilityWindowInfo>> emptyWindows = new SparseArray<>();
+        return emptyWindows;
     }
 
     /**
diff --git a/core/java/android/view/accessibility/AccessibilityManager.java b/core/java/android/view/accessibility/AccessibilityManager.java
index 2e9d881..0817452 100644
--- a/core/java/android/view/accessibility/AccessibilityManager.java
+++ b/core/java/android/view/accessibility/AccessibilityManager.java
@@ -21,6 +21,7 @@
 import android.Manifest;
 import android.accessibilityservice.AccessibilityServiceInfo;
 import android.accessibilityservice.AccessibilityServiceInfo.FeedbackType;
+import android.accessibilityservice.AccessibilityShortcutInfo;
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -30,9 +31,13 @@
 import android.annotation.SystemService;
 import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
+import android.annotation.UserIdInt;
 import android.content.ComponentName;
 import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
 import android.content.pm.ServiceInfo;
 import android.content.res.Resources;
 import android.os.Binder;
@@ -56,6 +61,9 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.IntPair;
 
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
@@ -1257,6 +1265,64 @@
         return null;
     }
 
+    /**
+     * Returns the {@link AccessibilityShortcutInfo}s of the installed accessibility shortcut
+     * targets, for specific user.
+     *
+     * @param context The context of the application.
+     * @param userId The user id.
+     * @return A list with {@link AccessibilityShortcutInfo}s.
+     * @hide
+     */
+    @NonNull
+    public List<AccessibilityShortcutInfo> getInstalledAccessibilityShortcutListAsUser(
+            @NonNull Context context, @UserIdInt int userId) {
+        final List<AccessibilityShortcutInfo> shortcutInfos = new ArrayList<>();
+        final int flags = PackageManager.GET_ACTIVITIES
+                | PackageManager.GET_META_DATA
+                | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
+                | PackageManager.MATCH_DIRECT_BOOT_AWARE
+                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
+        final Intent actionMain = new Intent(Intent.ACTION_MAIN);
+        actionMain.addCategory(Intent.CATEGORY_ACCESSIBILITY_SHORTCUT_TARGET);
+
+        final PackageManager packageManager = context.getPackageManager();
+        final List<ResolveInfo> installedShortcutList =
+                packageManager.queryIntentActivitiesAsUser(actionMain, flags, userId);
+        for (int i = 0; i < installedShortcutList.size(); i++) {
+            final AccessibilityShortcutInfo shortcutInfo =
+                    getShortcutInfo(context, installedShortcutList.get(i));
+            if (shortcutInfo != null) {
+                shortcutInfos.add(shortcutInfo);
+            }
+        }
+        return shortcutInfos;
+    }
+
+    /**
+     * Returns an {@link AccessibilityShortcutInfo} according to the given {@link ResolveInfo} of
+     * an activity.
+     *
+     * @param context The context of the application.
+     * @param resolveInfo The resolve info of an activity.
+     * @return The AccessibilityShortcutInfo.
+     */
+    @Nullable
+    private AccessibilityShortcutInfo getShortcutInfo(@NonNull Context context,
+            @NonNull ResolveInfo resolveInfo) {
+        final ActivityInfo activityInfo = resolveInfo.activityInfo;
+        if (activityInfo == null || activityInfo.metaData == null
+                || activityInfo.metaData.getInt(AccessibilityShortcutInfo.META_DATA) == 0) {
+            return null;
+        }
+        try {
+            return new AccessibilityShortcutInfo(context, activityInfo);
+        } catch (XmlPullParserException | IOException exp) {
+            Log.e(LOG_TAG, "Error while initializing AccessibilityShortcutInfo", exp);
+        }
+        return null;
+    }
+
     private IAccessibilityManager getServiceLocked() {
         if (mService == null) {
             tryConnectToServiceLocked(null);
diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfo.java b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
index cf29ed7..06e9d0d 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
@@ -39,8 +39,10 @@
 import android.text.Spanned;
 import android.text.TextUtils;
 import android.text.style.AccessibilityClickableSpan;
+import android.text.style.AccessibilityReplacementSpan;
 import android.text.style.AccessibilityURLSpan;
 import android.text.style.ClickableSpan;
+import android.text.style.ReplacementSpan;
 import android.text.style.URLSpan;
 import android.util.ArrayMap;
 import android.util.ArraySet;
@@ -2641,37 +2643,86 @@
     public void setText(CharSequence text) {
         enforceNotSealed();
         mOriginalText = text;
-        // Replace any ClickableSpans in mText with placeholders
         if (text instanceof Spanned) {
-            ClickableSpan[] spans =
-                    ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
-            if (spans.length > 0) {
-                Spannable spannable = new SpannableStringBuilder(text);
-                for (int i = 0; i < spans.length; i++) {
-                    ClickableSpan span = spans[i];
-                    if ((span instanceof AccessibilityClickableSpan)
-                            || (span instanceof AccessibilityURLSpan)) {
-                        // We've already done enough
-                        break;
-                    }
-                    int spanToReplaceStart = spannable.getSpanStart(span);
-                    int spanToReplaceEnd = spannable.getSpanEnd(span);
-                    int spanToReplaceFlags = spannable.getSpanFlags(span);
-                    spannable.removeSpan(span);
-                    ClickableSpan replacementSpan = (span instanceof URLSpan)
-                            ? new AccessibilityURLSpan((URLSpan) span)
-                            : new AccessibilityClickableSpan(span.getId());
-                    spannable.setSpan(replacementSpan, spanToReplaceStart, spanToReplaceEnd,
-                            spanToReplaceFlags);
-                }
-                mText = spannable;
-                return;
-            }
+            CharSequence tmpText = text;
+            tmpText = replaceClickableSpan(tmpText);
+            tmpText = replaceReplacementSpan(tmpText);
+            mText = tmpText;
+            return;
         }
         mText = (text == null) ? null : text.subSequence(0, text.length());
     }
 
     /**
+     * Replaces any ClickableSpans in mText with placeholders.
+     *
+     * @param text The text.
+     *
+     * @return The spannable with ClickableSpan replacement.
+     */
+    private CharSequence replaceClickableSpan(CharSequence text) {
+        ClickableSpan[] clickableSpans =
+                ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
+        Spannable spannable = new SpannableStringBuilder(text);
+        if (clickableSpans.length == 0) {
+            return text;
+        }
+        for (int i = 0; i < clickableSpans.length; i++) {
+            ClickableSpan span = clickableSpans[i];
+            if ((span instanceof AccessibilityClickableSpan)
+                    || (span instanceof AccessibilityURLSpan)) {
+                // We've already done enough
+                break;
+            }
+            int spanToReplaceStart = spannable.getSpanStart(span);
+            int spanToReplaceEnd = spannable.getSpanEnd(span);
+            int spanToReplaceFlags = spannable.getSpanFlags(span);
+            spannable.removeSpan(span);
+            ClickableSpan replacementSpan = (span instanceof URLSpan)
+                    ? new AccessibilityURLSpan((URLSpan) span)
+                    : new AccessibilityClickableSpan(span.getId());
+            spannable.setSpan(replacementSpan, spanToReplaceStart, spanToReplaceEnd,
+                    spanToReplaceFlags);
+        }
+        return spannable;
+    }
+
+    /**
+     * Replace any ImageSpans in mText with its content description.
+     *
+     * @param text The text.
+     *
+     * @return The spannable with ReplacementSpan replacement.
+     */
+    private CharSequence replaceReplacementSpan(CharSequence text) {
+        ReplacementSpan[] replacementSpans =
+                ((Spanned) text).getSpans(0, text.length(), ReplacementSpan.class);
+        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
+        if (replacementSpans.length == 0) {
+            return text;
+        }
+        for (int i = 0; i < replacementSpans.length; i++) {
+            ReplacementSpan span = replacementSpans[i];
+            CharSequence replacementText = span.getContentDescription();
+            if (span instanceof AccessibilityReplacementSpan) {
+                // We've already done enough
+                break;
+            }
+            if (replacementText == null) {
+                continue;
+            }
+            int spanToReplaceStart = spannable.getSpanStart(span);
+            int spanToReplaceEnd = spannable.getSpanEnd(span);
+            int spanToReplaceFlags = spannable.getSpanFlags(span);
+            spannable.removeSpan(span);
+            ReplacementSpan replacementSpan = new AccessibilityReplacementSpan(replacementText);
+            spannable.setSpan(replacementSpan, spanToReplaceStart, spanToReplaceEnd,
+                    spanToReplaceFlags);
+        }
+        return spannable;
+    }
+
+    /**
      * Gets the hint text of this node. Only applies to nodes where text can be entered.
      *
      * @return The hint text.
diff --git a/core/java/android/view/accessibility/AccessibilityNodeProvider.java b/core/java/android/view/accessibility/AccessibilityNodeProvider.java
index 4b25378..f4c7b96 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeProvider.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeProvider.java
@@ -44,28 +44,126 @@
  * View itself. Similarly the returned instance is responsible for performing accessibility
  * actions on any virtual view or the root view itself. For example:
  * </p>
- * <pre>
- *     getAccessibilityNodeProvider(
- *         if (mAccessibilityNodeProvider == null) {
- *             mAccessibilityNodeProvider = new AccessibilityNodeProvider() {
- *                 public boolean performAction(int action, int virtualDescendantId) {
- *                     // Implementation.
+ * <div>
+ * <div class="ds-selector-tabs"><section><h3 id="kotlin">Kotlin</h3>
+ * <pre class="prettyprint lang-kotlin">
+ * // "view" is the View instance on which this class performs accessibility functions.
+ * class MyCalendarViewAccessibilityDelegate(
+ *       private var view: MyCalendarView) : AccessibilityDelegate() {
+ *     override fun getAccessibilityNodeProvider(host: View): AccessibilityNodeProvider {
+ *         return object : AccessibilityNodeProvider() {
+ *             override fun createAccessibilityNodeInfo(virtualViewId: Int):
+ *                     AccessibilityNodeInfo? {
+ *                 when (virtualViewId) {
+ *                     <var>host-view-id</var> -&gt; {
+ *                         val node = AccessibilityNodeInfo.obtain(view)
+ *                         node.addChild(view, <var>child-view-id</var>)
+ *                         // Set other attributes like screenReaderFocusable
+ *                         // and contentDescription.
+ *                         return node
+ *                     }
+ *                     <var>child-view-id</var> -&gt; {
+ *                         val node = AccessibilityNodeInfo
+ *                                 .obtain(view, virtualViewId)
+ *                         node.setParent(view)
+ *                         node.addAction(ACTION_SCROLL_UP)
+ *                         node.addAction(ACTION_SCROLL_DOWN)
+ *                         // Set other attributes like focusable and visibleToUser.
+ *                         node.setBoundsInScreen(
+ *                                 Rect(<var>coords-of-edges-relative-to-screen</var>))
+ *                         return node
+ *                     }
+ *                     else -&gt; return null
+ *                 }
+ *             }
+ *
+ *             override fun performAction(
+ *                 virtualViewId: Int,
+ *                 action: Int,
+ *                 arguments: Bundle
+ *             ): Boolean {
+ *                 if (virtualViewId == <var>host-view-id</var>) {
+ *                     return view.performAccessibilityAction(action, arguments)
+ *                 }
+ *                 when (action) {
+ *                     ACTION_SCROLL_UP.id -&gt; {
+ *                         // Implement logic in a separate method.
+ *                         navigateToPreviousMonth()
+ *
+ *                         return true
+ *                     }
+ *                     ACTION_SCROLL_DOWN.id -&gt;
+ *                         // Implement logic in a separate method.
+ *                         navigateToNextMonth()
+ *
+ *                         return true
+ *                     else -&gt; return false
+ *                 }
+ *             }
+ *         }
+ *     }
+ * }
+ * </pre>
+ * </section><section><h3 id="java">Java</h3>
+ * <pre class="prettyprint lang-java">
+ * final class MyCalendarViewAccessibilityDelegate extends AccessibilityDelegate {
+ *     // The View instance on which this class performs accessibility functions.
+ *     private final MyCalendarView view;
+ *
+ *     MyCalendarViewAccessibilityDelegate(MyCalendarView view) {
+ *         this.view = view;
+ *     }
+ *
+ *     &#64;Override
+ *     public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
+ *         return new AccessibilityNodeProvider() {
+ *             &#64;Override
+ *             &#64;Nullable
+ *             public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) {
+ *                 if (virtualViewId == <var>host-view-id</var>) {
+ *                     AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain(view);
+ *                     node.addChild(view, <var>child-view-id</var>);
+ *                     // Set other attributes like screenReaderFocusable and contentDescription.
+ *                     return node;
+ *                 } else if (virtualViewId == <var>child-view-id</var>) {
+ *                     AccessibilityNodeInfo node =
+ *                         AccessibilityNodeInfo.obtain(view, virtualViewId);
+ *                     node.setParent(view);
+ *                     node.addAction(ACTION_SCROLL_UP);
+ *                     node.addAction(ACTION_SCROLL_DOWN);
+ *                     // Set other attributes like focusable and visibleToUser.
+ *                     node.setBoundsInScreen(
+ *                         new Rect(<var>coordinates-of-edges-relative-to-screen</var>));
+ *                     return node;
+ *                 } else {
+ *                     return null;
+ *                 }
+ *             }
+ *
+ *             &#64;Override
+ *             public boolean performAction(int virtualViewId, int action, Bundle arguments) {
+ *                 if (virtualViewId == <var>host-view-id</var>) {
+ *                     return view.performAccessibilityAction(action, arguments);
+ *                 }
+ *
+ *                 if (action == ACTION_SCROLL_UP.getId()) {
+ *                     // Implement logic in a separate method.
+ *                     navigateToPreviousMonth();
+ *
+ *                     return true;
+ *                 } else if (action == ACTION_SCROLL_DOWN.getId()) {
+ *                     // Implement logic in a separate method.
+ *                     navigateToNextMonth();
+ *
+ *                     return true;
+ *                 } else {
  *                     return false;
  *                 }
- *
- *                 public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText(String text,
- *                         int virtualDescendantId) {
- *                     // Implementation.
- *                     return null;
- *                 }
- *
- *                 public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualDescendantId) {
- *                     // Implementation.
- *                     return null;
- *                 }
- *             });
- *     return mAccessibilityNodeProvider;
- * </pre>
+ *             }
+ *         };
+ *     }
+ * }
+ * </pre></section></div></div>
  */
 public abstract class AccessibilityNodeProvider {
 
diff --git a/core/java/android/view/accessibility/AccessibilityWindowInfo.aidl b/core/java/android/view/accessibility/AccessibilityWindowInfo.aidl
index fdb25fb..c36c4aa 100644
--- a/core/java/android/view/accessibility/AccessibilityWindowInfo.aidl
+++ b/core/java/android/view/accessibility/AccessibilityWindowInfo.aidl
@@ -17,3 +17,4 @@
 package android.view.accessibility;
 
 parcelable AccessibilityWindowInfo;
+parcelable AccessibilityWindowInfo.WindowListSparseArray;
diff --git a/core/java/android/view/accessibility/AccessibilityWindowInfo.java b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
index 6a3af34..5fa8a6e 100644
--- a/core/java/android/view/accessibility/AccessibilityWindowInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
@@ -26,9 +26,12 @@
 import android.text.TextUtils;
 import android.util.LongArray;
 import android.util.Pools.SynchronizedPool;
+import android.util.SparseArray;
 import android.view.Display;
 import android.view.accessibility.AccessibilityEvent.WindowsChangeTypes;
 
+import java.util.ArrayList;
+import java.util.List;
 import java.util.Objects;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -797,4 +800,49 @@
             return new AccessibilityWindowInfo[size];
         }
     };
+
+    /**
+     * Transfers a sparsearray with lists having {@link AccessibilityWindowInfo}s across an IPC.
+     * The key of this sparsearray is display Id.
+     *
+     * @hide
+     */
+    public static final class WindowListSparseArray
+            extends SparseArray<List<AccessibilityWindowInfo>> implements Parcelable {
+
+        @Override
+        public int describeContents() {
+            return 0;
+        }
+
+        @Override
+        public void writeToParcel(Parcel dest, int flags) {
+            final int count = size();
+            dest.writeInt(count);
+            for (int i = 0; i < count; i++) {
+                dest.writeParcelableList(valueAt(i), 0);
+                dest.writeInt(keyAt(i));
+            }
+        }
+
+        public static final Parcelable.Creator<WindowListSparseArray> CREATOR =
+                new Parcelable.Creator<WindowListSparseArray>() {
+            public WindowListSparseArray createFromParcel(
+                    Parcel source) {
+                final WindowListSparseArray array = new WindowListSparseArray();
+                final ClassLoader loader = array.getClass().getClassLoader();
+                final int count = source.readInt();
+                for (int i = 0; i < count; i++) {
+                    List<AccessibilityWindowInfo> windows = new ArrayList<>();
+                    source.readParcelableList(windows, loader);
+                    array.put(source.readInt(), windows);
+                }
+                return array;
+            }
+
+            public WindowListSparseArray[] newArray(int size) {
+                return new WindowListSparseArray[size];
+            }
+        };
+    }
 }
diff --git a/core/java/android/view/contentcapture/ChildContentCaptureSession.java b/core/java/android/view/contentcapture/ChildContentCaptureSession.java
index 5e02de4..7487ec4 100644
--- a/core/java/android/view/contentcapture/ChildContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/ChildContentCaptureSession.java
@@ -89,8 +89,13 @@
     }
 
     @Override
-    public void internalNotifySessionLifecycle(boolean started) {
-        getMainCaptureSession().notifySessionLifecycle(mId, started);
+    void internalNotifySessionResumed() {
+        getMainCaptureSession().notifySessionResumed();
+    }
+
+    @Override
+    void internalNotifySessionPaused() {
+        getMainCaptureSession().notifySessionPaused();
     }
 
     @Override
diff --git a/core/java/android/view/contentcapture/ContentCaptureManager.java b/core/java/android/view/contentcapture/ContentCaptureManager.java
index d22fac9..6040abd 100644
--- a/core/java/android/view/contentcapture/ContentCaptureManager.java
+++ b/core/java/android/view/contentcapture/ContentCaptureManager.java
@@ -404,14 +404,14 @@
     @UiThread
     public void onActivityResumed() {
         if (mOptions.lite) return;
-        getMainContentCaptureSession().notifySessionLifecycle(/* started= */ true);
+        getMainContentCaptureSession().notifySessionResumed();
     }
 
     /** @hide */
     @UiThread
     public void onActivityPaused() {
         if (mOptions.lite) return;
-        getMainContentCaptureSession().notifySessionLifecycle(/* started= */ false);
+        getMainContentCaptureSession().notifySessionPaused();
     }
 
     /** @hide */
diff --git a/core/java/android/view/contentcapture/ContentCaptureSession.java b/core/java/android/view/contentcapture/ContentCaptureSession.java
index cf08c18..232d96b 100644
--- a/core/java/android/view/contentcapture/ContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/ContentCaptureSession.java
@@ -439,17 +439,26 @@
     public abstract void internalNotifyViewTreeEvent(boolean started);
 
     /**
-     * Notifies the Content Capture Service that a session has paused/resumed.
-     *
-     * @param started whether session has resumed.
+     * Notifies the Content Capture Service that a session has resumed.
      */
-    public final void notifySessionLifecycle(boolean started) {
+    public final void notifySessionResumed() {
         if (!isContentCaptureEnabled()) return;
 
-        internalNotifySessionLifecycle(started);
+        internalNotifySessionResumed();
     }
 
-    abstract void internalNotifySessionLifecycle(boolean started);
+    abstract void internalNotifySessionResumed();
+
+    /**
+     * Notifies the Content Capture Service that a session has paused.
+     */
+    public final void notifySessionPaused() {
+        if (!isContentCaptureEnabled()) return;
+
+        internalNotifySessionPaused();
+    }
+
+    abstract void internalNotifySessionPaused();
 
     /**
      * Creates a {@link ViewStructure} for a "standard" view.
diff --git a/core/java/android/view/contentcapture/MainContentCaptureSession.java b/core/java/android/view/contentcapture/MainContentCaptureSession.java
index 349ef09..96f224f 100644
--- a/core/java/android/view/contentcapture/MainContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/MainContentCaptureSession.java
@@ -583,8 +583,13 @@
     }
 
     @Override
-    public void internalNotifySessionLifecycle(boolean started) {
-        notifySessionLifecycle(mId, started);
+    public void internalNotifySessionResumed() {
+        notifySessionResumed(mId);
+    }
+
+    @Override
+    public void internalNotifySessionPaused() {
+        notifySessionPaused(mId);
     }
 
     @Override
@@ -642,9 +647,12 @@
         sendEvent(new ContentCaptureEvent(sessionId, type), FORCE_FLUSH);
     }
 
-    void notifySessionLifecycle(int sessionId, boolean started) {
-        final int type = started ? TYPE_SESSION_RESUMED : TYPE_SESSION_PAUSED;
-        sendEvent(new ContentCaptureEvent(sessionId, type), FORCE_FLUSH);
+    void notifySessionResumed(int sessionId) {
+        sendEvent(new ContentCaptureEvent(sessionId, TYPE_SESSION_RESUMED), FORCE_FLUSH);
+    }
+
+    void notifySessionPaused(int sessionId) {
+        sendEvent(new ContentCaptureEvent(sessionId, TYPE_SESSION_PAUSED), FORCE_FLUSH);
     }
 
     void notifyContextUpdated(int sessionId, @Nullable ContentCaptureContext context) {
diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java
index 032af1c..6420d71 100644
--- a/core/java/android/view/inputmethod/InputMethodManager.java
+++ b/core/java/android/view/inputmethod/InputMethodManager.java
@@ -525,16 +525,16 @@
         final InputMethodManager fallbackImm =
                 viewRootImpl.mContext.getSystemService(InputMethodManager.class);
         if (fallbackImm == null) {
-            Log.e(TAG, "b/117267690: Failed to get non-null fallback IMM. view=" + view);
+            Log.v(TAG, "b/117267690: Failed to get non-null fallback IMM. view=" + view);
             return null;
         }
         if (fallbackImm.mDisplayId != viewRootDisplayId) {
-            Log.e(TAG, "b/117267690: Failed to get fallback IMM with expected displayId="
+            Log.v(TAG, "b/117267690: Failed to get fallback IMM with expected displayId="
                     + viewRootDisplayId + " actual IMM#displayId=" + fallbackImm.mDisplayId
                     + " view=" + view);
             return null;
         }
-        Log.w(TAG, "b/117267690: Display ID mismatch found."
+        Log.v(TAG, "b/117267690: Display ID mismatch found."
                 + " ViewRootImpl displayId=" + viewRootDisplayId
                 + " InputMethodManager displayId=" + mDisplayId
                 + ". Use the right InputMethodManager instance to avoid performance overhead.",
diff --git a/core/java/android/webkit/MimeTypeMap.java b/core/java/android/webkit/MimeTypeMap.java
index fc23c54..358fdc7 100644
--- a/core/java/android/webkit/MimeTypeMap.java
+++ b/core/java/android/webkit/MimeTypeMap.java
@@ -19,7 +19,7 @@
 import android.annotation.Nullable;
 import android.text.TextUtils;
 
-import libcore.net.MimeMap;
+import libcore.content.type.MimeMap;
 
 import java.util.regex.Pattern;
 
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 18d4d69..7282008 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -193,26 +193,24 @@
     }
 
     /**
-     * Used with {@link #setMixedContentMode}
-     *
      * In this mode, the WebView will allow a secure origin to load content from any other origin,
      * even if that origin is insecure. This is the least secure mode of operation for the WebView,
      * and where possible apps should not set this mode.
+     *
+     * @see #setMixedContentMode
      */
     public static final int MIXED_CONTENT_ALWAYS_ALLOW = 0;
 
     /**
-     * Used with {@link #setMixedContentMode}
-     *
      * In this mode, the WebView will not allow a secure origin to load content from an insecure
      * origin. This is the preferred and most secure mode of operation for the WebView and apps are
      * strongly advised to use this mode.
+     *
+     * @see #setMixedContentMode
      */
     public static final int MIXED_CONTENT_NEVER_ALLOW = 1;
 
     /**
-     * Used with {@link #setMixedContentMode}
-     *
      * In this mode, the WebView will attempt to be compatible with the approach of a modern web
      * browser with regard to mixed content. Some insecure content may be allowed to be loaded by
      * a secure origin and other types of content will be blocked. The types of content are allowed
@@ -221,6 +219,8 @@
      * This mode is intended to be used by apps that are not in control of the content that they
      * render but desire to operate in a reasonably secure environment. For highest security, apps
      * are recommended to use {@link #MIXED_CONTENT_NEVER_ALLOW}.
+     *
+     * @see #setMixedContentMode
      */
     public static final int MIXED_CONTENT_COMPATIBILITY_MODE = 2;
 
@@ -234,30 +234,30 @@
     public @interface ForceDark {}
 
     /**
-     * Used with {@link #setForceDark}
-     *
      * Disable force dark, irrespective of the force dark mode of the WebView parent. In this mode,
      * WebView content will always be rendered as-is, regardless of whether native views are being
      * automatically darkened.
+     *
+     * @see #setForceDark
      */
     public static final int FORCE_DARK_OFF = 0;
 
     /**
-     * Used with {@link #setForceDark}
-     *
      * Enable force dark dependent on the state of the WebView parent view. If the WebView parent
      * view is being automatically force darkened
      * (see: {@link android.view.View#setForceDarkAllowed}), then WebView content will be rendered
      * so as to emulate a dark theme. WebViews that are not attached to the view hierarchy will not
      * be inverted.
+     *
+     * @see #setForceDark
      */
     public static final int FORCE_DARK_AUTO = 1;
 
     /**
-     * Used with {@link #setForceDark}
-     *
      * Unconditionally enable force dark. In this mode WebView content will always be rendered so
      * as to emulate a dark theme.
+     *
+     * @see #setForceDark
      */
     public static final int FORCE_DARK_ON = 2;
 
@@ -1471,6 +1471,7 @@
      * Set the force dark mode for this WebView.
      *
      * @param forceDark the force dark mode to set.
+     * @see #getForceDark
      */
     public void setForceDark(@ForceDark int forceDark) {
         // Stub implementation to satisfy Roboelectrc shadows that don't override this yet.
@@ -1478,10 +1479,10 @@
 
     /**
      * Get the force dark mode for this WebView.
-     *
-     * The default force dark mode is {@link #FORCE_DARK_AUTO}
+     * The default force dark mode is {@link #FORCE_DARK_AUTO}.
      *
      * @return the currently set force dark mode.
+     * @see #setForceDark
      */
     public @ForceDark int getForceDark() {
         // Stub implementation to satisfy Roboelectrc shadows that don't override this yet.
@@ -1516,34 +1517,34 @@
     public abstract @MenuItemFlags int getDisabledActionModeMenuItems();
 
     /**
-     * Used with {@link #setDisabledActionModeMenuItems}.
-     *
      * No menu items should be disabled.
+     *
+     * @see #setDisabledActionModeMenuItems
      */
     public static final int MENU_ITEM_NONE = 0;
 
     /**
-     * Used with {@link #setDisabledActionModeMenuItems}.
-     *
      * Disable menu item "Share".
+     *
+     * @see #setDisabledActionModeMenuItems
      */
     public static final int MENU_ITEM_SHARE = 1 << 0;
 
     /**
-     * Used with {@link #setDisabledActionModeMenuItems}.
-     *
      * Disable menu item "Web Search".
+     *
+     * @see #setDisabledActionModeMenuItems
      */
     public static final int MENU_ITEM_WEB_SEARCH = 1 << 1;
 
     /**
-     * Used with {@link #setDisabledActionModeMenuItems}.
-     *
      * Disable all the action mode menu items for text processing.
      * By default WebView searches for activities that are able to handle
      * {@link android.content.Intent#ACTION_PROCESS_TEXT} and show them in the
      * action mode menu. If this flag is set via {@link
      * #setDisabledActionModeMenuItems}, these menu items will be disabled.
+     *
+     * @see #setDisabledActionModeMenuItems
      */
     public static final int MENU_ITEM_PROCESS_TEXT = 1 << 2;
 }
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index fe88a91..6d60366 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -2569,7 +2569,8 @@
 
         if (isItemClickable(view)) {
             addAccessibilityActionIfEnabled(info, isItemEnabled, AccessibilityAction.ACTION_CLICK);
-            info.setClickable(true);
+            // A disabled item is a separator which should not be clickable.
+            info.setClickable(isItemEnabled);
         }
 
         if (isLongClickable()) {
diff --git a/core/java/android/widget/SimpleMonthView.java b/core/java/android/widget/SimpleMonthView.java
index 80de6fc..562cc4f 100644
--- a/core/java/android/widget/SimpleMonthView.java
+++ b/core/java/android/widget/SimpleMonthView.java
@@ -1103,6 +1103,7 @@
             }
 
             node.setEnabled(isDayEnabled);
+            node.setClickable(true);
 
             if (virtualViewId == mActivatedDay) {
                 // TODO: This should use activated once that's supported.
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index f997d68..31f5055 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -23,6 +23,7 @@
 import static android.view.inputmethod.CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
 
 import android.R;
+import android.annotation.CallSuper;
 import android.annotation.CheckResult;
 import android.annotation.ColorInt;
 import android.annotation.DrawableRes;
@@ -10446,10 +10447,15 @@
     /**
      * This method is called when the selection has changed, in case any
      * subclasses would like to know.
+     * </p>
+     * <p class="note"><strong>Note:</strong> Always call the super implementation, which informs
+     * the accessibility subsystem about the selection change.
+     * </p>
      *
      * @param selStart The new selection start location.
      * @param selEnd The new selection end location.
      */
+    @CallSuper
     protected void onSelectionChanged(int selStart, int selEnd) {
         sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
     }
diff --git a/core/java/com/android/internal/app/ResolverListController.java b/core/java/com/android/internal/app/ResolverListController.java
index 5f92cdd..a390611 100644
--- a/core/java/com/android/internal/app/ResolverListController.java
+++ b/core/java/com/android/internal/app/ResolverListController.java
@@ -115,14 +115,6 @@
                 flags |= PackageManager.MATCH_INSTANT;
             }
             final List<ResolveInfo> infos = mpm.queryIntentActivities(intent, flags);
-            // Remove any activities that are not exported.
-            int totalSize = infos.size();
-            for (int j = totalSize - 1; j >= 0 ; j--) {
-                ResolveInfo info = infos.get(j);
-                if (info.activityInfo != null && !info.activityInfo.exported) {
-                    infos.remove(j);
-                }
-            }
             if (infos != null) {
                 if (resolvedComponents == null) {
                     resolvedComponents = new ArrayList<>();
diff --git a/core/java/com/android/internal/compat/ChangeReporter.java b/core/java/com/android/internal/compat/ChangeReporter.java
index 1ce071b..8283eb7 100644
--- a/core/java/com/android/internal/compat/ChangeReporter.java
+++ b/core/java/com/android/internal/compat/ChangeReporter.java
@@ -16,14 +16,88 @@
 
 package com.android.internal.compat;
 
+import android.util.Log;
+import android.util.Slog;
 import android.util.StatsLog;
 
+import com.android.internal.annotations.GuardedBy;
+
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Set;
+
 /**
  * A helper class to report changes to stats log.
  *
  * @hide
  */
 public final class ChangeReporter {
+    private static final String TAG = "CompatibilityChangeReporter";
+    private int mSource;
+
+    private final class ChangeReport {
+        int mUid;
+        long mChangeId;
+        int mState;
+
+        ChangeReport(int uid, long changeId, int state) {
+            mUid = uid;
+            mChangeId = changeId;
+            mState = state;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            ChangeReport that = (ChangeReport) o;
+            return mUid == that.mUid
+                    && mChangeId == that.mChangeId
+                    && mState == that.mState;
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(mUid, mChangeId, mState);
+        }
+    }
+
+    @GuardedBy("mReportedChanges")
+    private Set<ChangeReport> mReportedChanges =  new HashSet<>();
+
+    public ChangeReporter(int source) {
+        mSource = source;
+    }
+
+    /**
+     * Report the change to stats log.
+     *
+     * @param uid      affected by the change
+     * @param changeId the reported change id
+     * @param state    of the reported change - enabled/disabled/only logged
+     */
+    public void reportChange(int uid, long changeId, int state) {
+        ChangeReport report = new ChangeReport(uid, changeId, state);
+        synchronized (mReportedChanges) {
+            if (!mReportedChanges.contains(report)) {
+                debugLog(uid, changeId, state);
+                StatsLog.write(StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED, uid, changeId,
+                        state, mSource);
+                mReportedChanges.add(report);
+            }
+        }
+    }
+
+    private void debugLog(int uid, long changeId, int state) {
+        String message = String.format("Compat change id reported: %d; UID %d; state: %s", changeId,
+                uid, stateToString(state));
+        if (mSource == StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__SOURCE__SYSTEM_SERVER) {
+            Slog.d(TAG, message);
+        } else {
+            Log.d(TAG, message);
+        }
+
+    }
 
     /**
      * Transforms StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__STATE enum to a string.
@@ -43,31 +117,4 @@
                 return "UNKNOWN";
         }
     }
-
-    /**
-     * Constructs and returns a string to be logged to logcat when a change is reported.
-     *
-     * @param uid      affected by the change
-     * @param changeId the reported change id
-     * @param state    of the reported change - enabled/disabled/only logged
-     * @return string to log
-     */
-    public static String createLogString(int uid, long changeId, int state) {
-        return String.format("Compat change id reported: %d; UID %d; state: %s", changeId, uid,
-                stateToString(state));
-    }
-
-    /**
-     * Report the change to stats log.
-     *
-     * @param uid      affected by the change
-     * @param changeId the reported change id
-     * @param state    of the reported change - enabled/disabled/only logged
-     * @param source   of the logging - app process or system server
-     */
-    public void reportChange(int uid, long changeId, int state, int source) {
-        //TODO(b/138374585): Implement rate limiting for stats log.
-        StatsLog.write(StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED, uid, changeId,
-                state, source);
-    }
 }
diff --git a/core/java/com/android/internal/compat/IPlatformCompat.aidl b/core/java/com/android/internal/compat/IPlatformCompat.aidl
index 9049c3a..4d8378a 100644
--- a/core/java/com/android/internal/compat/IPlatformCompat.aidl
+++ b/core/java/com/android/internal/compat/IPlatformCompat.aidl
@@ -33,15 +33,36 @@
      * Reports that a compatibility change is affecting an app process now.
      *
      * <p>Note: for changes that are gated using {@link #isChangeEnabled(long, ApplicationInfo)},
-     * you do not need to call this API directly. The change will be reported for you in the case
-     * that {@link #isChangeEnabled(long, ApplicationInfo)} returns {@code true}.
+     * you do not need to call this API directly. The change will be reported for you.
      *
      * @param changeId The ID of the compatibility change taking effect.
-     * @param appInfo Representing the affected app.
+     * @param appInfo  Representing the affected app.
      */
     void reportChange(long changeId, in ApplicationInfo appInfo);
 
     /**
+     * Reports that a compatibility change is affecting an app process now.
+     *
+     * <p>Note: for changes that are gated using {@link #isChangeEnabled(long, String)},
+     * you do not need to call this API directly. The change will be reported for you.
+     *
+     * @param changeId    The ID of the compatibility change taking effect.
+     * @param packageName The package name of the app in question.
+     */
+     void reportChangeByPackageName(long changeId, in String packageName);
+
+    /**
+     * Reports that a compatibility change is affecting an app process now.
+     *
+     * <p>Note: for changes that are gated using {@link #isChangeEnabled(long, int)},
+     * you do not need to call this API directly. The change will be reported for you.
+     *
+     * @param changeId The ID of the compatibility change taking effect.
+     * @param uid      The UID of the app in question.
+     */
+    void reportChangeByUid(long changeId, int uid);
+
+    /**
      * Query if a given compatibility change is enabled for an app process. This method should
      * be called when implementing functionality on behalf of the affected app.
      *
@@ -49,13 +70,59 @@
      * change, resulting in differing behaviour compared to earlier releases. If this method returns
      * {@code false}, the calling code should behave as it did in earlier releases.
      *
-     * <p>When this method returns {@code true}, it will also report the change as
-     * {@link #reportChange(long, ApplicationInfo)} would, so there is no need to call that method
-     * directly.
+     * <p>It will also report the change as {@link #reportChange(long, ApplicationInfo)} would, so
+     * there is no need to call that method directly.
      *
      * @param changeId The ID of the compatibility change in question.
-     * @param appInfo Representing the app in question.
+     * @param appInfo  Representing the app in question.
      * @return {@code true} if the change is enabled for the current app.
      */
     boolean isChangeEnabled(long changeId, in ApplicationInfo appInfo);
+
+    /**
+     * Query if a given compatibility change is enabled for an app process. This method should
+     * be called when implementing functionality on behalf of the affected app.
+     *
+     * <p>Same as {@link #isChangeEnabled(long, ApplicationInfo)}, except it receives a package name
+     * instead of an {@link ApplicationInfo}
+     * object, and finds an app info object based on the package name. Returns {@code true} if
+     * there is no installed package by that name.
+     *
+     * <p>If this method returns {@code true}, the calling code should implement the compatibility
+     * change, resulting in differing behaviour compared to earlier releases. If this method
+     * returns
+     * {@code false}, the calling code should behave as it did in earlier releases.
+     *
+     * <p>It will also report the change as {@link #reportChange(long, String)} would, so there is
+     * no need to call that method directly.
+     *
+     * @param changeId    The ID of the compatibility change in question.
+     * @param packageName The package name of the app in question.
+     * @return {@code true} if the change is enabled for the current app.
+     */
+    boolean isChangeEnabledByPackageName(long changeId, in String packageName);
+
+    /**
+     * Query if a given compatibility change is enabled for an app process. This method should
+     * be called when implementing functionality on behalf of the affected app.
+     *
+     * <p>Same as {@link #isChangeEnabled(long, ApplicationInfo)}, except it receives a uid
+     * instead of an {@link ApplicationInfo} object, and finds an app info object based on the
+     * uid (or objects if there's more than one package associated with the UID).
+     * Returns {@code true} if there are no installed packages for the required UID, or if the
+     * change is enabled for ALL of the installed packages associated with the provided UID. Please
+     * use a more specific API if you want a different behaviour for multi-package UIDs.
+     *
+     * <p>If this method returns {@code true}, the calling code should implement the compatibility
+     * change, resulting in differing behaviour compared to earlier releases. If this method
+     * returns {@code false}, the calling code should behave as it did in earlier releases.
+     *
+     * <p>It will also report the change as {@link #reportChange(long, int)} would, so there is
+     * no need to call that method directly.
+     *
+     * @param changeId The ID of the compatibility change in question.
+     * @param uid      The UID of the app in question.
+     * @return {@code true} if the change is enabled for the current app.
+     */
+    boolean isChangeEnabledByUid(long changeId, int uid);
 }
\ No newline at end of file
diff --git a/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
index 5142d3c..033e9b2 100644
--- a/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
+++ b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
@@ -239,6 +239,13 @@
     public static final String ASSIST_TRANSCRIPTION_MIN_DURATION =
             "assist_transcription_min_duration";
 
+    /**
+     * (boolean) Whether or not to enable an extra section in the notification shade which
+     * filters for "people" related messages.
+     */
+    public static final String NOTIFICATIONS_USE_PEOPLE_FILTERING =
+            "notifications_use_people_filtering";
+
     // Flags related to brightline falsing
 
     /**
diff --git a/core/java/com/android/internal/content/PackageMonitor.java b/core/java/com/android/internal/content/PackageMonitor.java
index c928f3f..d6dcb29 100644
--- a/core/java/com/android/internal/content/PackageMonitor.java
+++ b/core/java/com/android/internal/content/PackageMonitor.java
@@ -22,11 +22,11 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.net.Uri;
-import android.os.Bundle;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.UserHandle;
 import android.util.Slog;
+
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.Preconditions;
 
@@ -203,10 +203,6 @@
     public void onPackagesSuspended(String[] packages) {
     }
 
-    public void onPackagesSuspended(String[] packages, Bundle launcherExtras) {
-        onPackagesSuspended(packages);
-    }
-
     public void onPackagesUnsuspended(String[] packages) {
     }
 
@@ -446,9 +442,8 @@
             }
         } else if (Intent.ACTION_PACKAGES_SUSPENDED.equals(action)) {
             String[] pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
-            final Bundle launcherExtras = intent.getBundleExtra(Intent.EXTRA_LAUNCHER_EXTRAS);
             mSomePackagesChanged = true;
-            onPackagesSuspended(pkgList, launcherExtras);
+            onPackagesSuspended(pkgList);
         } else if (Intent.ACTION_PACKAGES_UNSUSPENDED.equals(action)) {
             String[] pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
             mSomePackagesChanged = true;
diff --git a/core/java/com/android/internal/infra/ServiceConnector.java b/core/java/com/android/internal/infra/ServiceConnector.java
index d6862f0..98d679e 100644
--- a/core/java/com/android/internal/infra/ServiceConnector.java
+++ b/core/java/com/android/internal/infra/ServiceConnector.java
@@ -32,6 +32,7 @@
 import android.util.DebugUtils;
 import android.util.Log;
 
+import com.android.internal.util.Preconditions;
 import com.android.internal.util.function.pooled.PooledLambda;
 
 import java.io.PrintWriter;
@@ -351,7 +352,7 @@
         @Override
         public <R> CompletionAwareJob<I, R> postForResult(@NonNull Job<I, R> job) {
             CompletionAwareJob<I, R> task = new CompletionAwareJob<>();
-            task.mDelegate = job;
+            task.mDelegate = Preconditions.checkNotNull(job);
             enqueue(task);
             return task;
         }
@@ -359,7 +360,7 @@
         @Override
         public <R> AndroidFuture<R> postAsync(@NonNull Job<I, CompletableFuture<R>> job) {
             CompletionAwareJob<I, R> task = new CompletionAwareJob<>();
-            task.mDelegate = (Job) job;
+            task.mDelegate = Preconditions.checkNotNull((Job) job);
             task.mAsync = true;
             enqueue(task);
             return task;
diff --git a/core/java/com/android/internal/os/KernelWakelockReader.java b/core/java/com/android/internal/os/KernelWakelockReader.java
index e09e0e6..cffb0ad 100644
--- a/core/java/com/android/internal/os/KernelWakelockReader.java
+++ b/core/java/com/android/internal/os/KernelWakelockReader.java
@@ -29,6 +29,7 @@
 
 import java.io.File;
 import java.io.FileInputStream;
+import java.util.Arrays;
 import java.util.Iterator;
 
 /**
@@ -66,6 +67,7 @@
     private final String[] mProcWakelocksName = new String[3];
     private final long[] mProcWakelocksData = new long[3];
     private ISuspendControlService mSuspendControlService = null;
+    private byte[] mKernelWakelockBuffer = new byte[32 * 1024];
 
     /**
      * Reads kernel wakelock stats and updates the staleStats with the new information.
@@ -84,7 +86,7 @@
             }
             return removeOldStats(staleStats);
         } else {
-            byte[] buffer = new byte[32*1024];
+            Arrays.fill(mKernelWakelockBuffer, (byte) 0);
             int len = 0;
             boolean wakeup_sources;
             final long startTime = SystemClock.uptimeMillis();
@@ -107,7 +109,8 @@
                 }
 
                 int cnt;
-                while ((cnt = is.read(buffer, len, buffer.length - len)) > 0) {
+                while ((cnt = is.read(mKernelWakelockBuffer, len,
+                                mKernelWakelockBuffer.length - len)) > 0) {
                     len += cnt;
                 }
 
@@ -125,12 +128,13 @@
             }
 
             if (len > 0) {
-                if (len >= buffer.length) {
-                    Slog.wtf(TAG, "Kernel wake locks exceeded buffer size " + buffer.length);
+                if (len >= mKernelWakelockBuffer.length) {
+                    Slog.wtf(TAG, "Kernel wake locks exceeded mKernelWakelockBuffer size "
+                            + mKernelWakelockBuffer.length);
                 }
                 int i;
                 for (i=0; i<len; i++) {
-                    if (buffer[i] == '\0') {
+                    if (mKernelWakelockBuffer[i] == '\0') {
                         len = i;
                         break;
                     }
@@ -143,7 +147,7 @@
                 Slog.w(TAG, "Failed to get Native wakelock stats from SystemSuspend");
             }
             // Get kernel wakelock stats
-            parseProcWakelocks(buffer, len, wakeup_sources, staleStats);
+            parseProcWakelocks(mKernelWakelockBuffer, len, wakeup_sources, staleStats);
             return removeOldStats(staleStats);
         }
     }
diff --git a/core/java/com/android/internal/os/RuntimeInit.java b/core/java/com/android/internal/os/RuntimeInit.java
index 1de2e72..fd3cd42 100644
--- a/core/java/com/android/internal/os/RuntimeInit.java
+++ b/core/java/com/android/internal/os/RuntimeInit.java
@@ -20,6 +20,7 @@
 import android.app.ActivityManager;
 import android.app.ActivityThread;
 import android.app.ApplicationErrorReport;
+import android.content.type.DefaultMimeMapFactory;
 import android.os.Build;
 import android.os.DeadObjectException;
 import android.os.Debug;
@@ -33,6 +34,9 @@
 import com.android.server.NetworkManagementSocketTagger;
 import dalvik.system.RuntimeHooks;
 import dalvik.system.VMRuntime;
+
+import libcore.content.type.MimeMap;
+
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
@@ -192,6 +196,24 @@
         }
     }
 
+    /**
+     * Common initialization that (unlike {@link #commonInit()} should happen prior to
+     * the Zygote fork.
+     */
+    public static void preForkInit() {
+        if (DEBUG) Slog.d(TAG, "Entered preForkInit.");
+        RuntimeInit.enableDdms();
+        // TODO(b/142019040#comment13): Decide whether to load the default instance eagerly, i.e.
+        // MimeMap.setDefault(DefaultMimeMapFactory.create());
+        /*
+         * Replace libcore's minimal default mapping between MIME types and file
+         * extensions with a mapping that's suitable for Android. Android's mapping
+         * contains many more entries that are derived from IANA registrations but
+         * with several customizations (extensions, overrides).
+         */
+        MimeMap.setDefaultSupplier(DefaultMimeMapFactory::create);
+    }
+
     @UnsupportedAppUsage
     protected static final void commonInit() {
         if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");
@@ -324,7 +346,7 @@
 
     @UnsupportedAppUsage
     public static final void main(String[] argv) {
-        enableDdms();
+        preForkInit();
         if (argv.length == 2 && argv[1].equals("application")) {
             if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application");
             redirectLogStreams();
@@ -418,7 +440,7 @@
     /**
      * Enable DDMS.
      */
-    static final void enableDdms() {
+    private static void enableDdms() {
         // Register handlers for DDM messages.
         android.ddm.DdmRegister.registerHandlers();
     }
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index 9d4cdc7..3ce3838 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -135,6 +135,9 @@
     /** Read-write external storage should be mounted instead of package sandbox */
     public static final int MOUNT_EXTERNAL_FULL = IVold.REMOUNT_MODE_FULL;
 
+    /** The lower file system should be bind mounted directly on external storage */
+    public static final int MOUNT_EXTERNAL_PASS_THROUGH = IVold.REMOUNT_MODE_PASS_THROUGH;
+
     /** Number of bytes sent to the Zygote over USAP pipes or the pool event FD */
     static final int USAP_MANAGEMENT_MESSAGE_BYTES = 8;
 
diff --git a/core/java/com/android/internal/os/ZygoteArguments.java b/core/java/com/android/internal/os/ZygoteArguments.java
index abc4160..a23e659 100644
--- a/core/java/com/android/internal/os/ZygoteArguments.java
+++ b/core/java/com/android/internal/os/ZygoteArguments.java
@@ -362,6 +362,8 @@
                 mMountExternal = Zygote.MOUNT_EXTERNAL_INSTALLER;
             }  else if (arg.equals("--mount-external-legacy")) {
                 mMountExternal = Zygote.MOUNT_EXTERNAL_LEGACY;
+            } else if (arg.equals("--mount-external-pass-through")) {
+                mMountExternal = Zygote.MOUNT_EXTERNAL_PASS_THROUGH;
             } else if (arg.equals("--query-abi-list")) {
                 mAbiListQuery = true;
             } else if (arg.equals("--get-pid")) {
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index b3ec5f5..a14b093 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -306,6 +306,12 @@
     }
 
     private void handleBootCompleted() {
+        try {
+            mSocketOutStream.writeInt(0);
+        } catch (IOException ioe) {
+            throw new IllegalStateException("Error writing to command socket", ioe);
+        }
+
         VMRuntime.bootCompleted();
     }
 
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index 3be1a1a..158700b 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -847,7 +847,7 @@
             TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag,
                     Trace.TRACE_TAG_DALVIK);
             bootTimingsTraceLog.traceBegin("ZygoteInit");
-            RuntimeInit.enableDdms();
+            RuntimeInit.preForkInit();
 
             boolean startSystemServer = false;
             String zygoteSocketName = "zygote";
diff --git a/core/java/com/android/internal/policy/KeyInterceptionInfo.java b/core/java/com/android/internal/policy/KeyInterceptionInfo.java
new file mode 100644
index 0000000..964be01
--- /dev/null
+++ b/core/java/com/android/internal/policy/KeyInterceptionInfo.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 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.internal.policy;
+
+
+/**
+ * Stores a snapshot of window information used to decide whether to intercept a key event.
+ */
+public class KeyInterceptionInfo {
+    // Window layout params attributes.
+    public final int layoutParamsType;
+    public final int layoutParamsPrivateFlags;
+    // Debug friendly name to help identify the window
+    public final String windowTitle;
+
+    public KeyInterceptionInfo(int type, int flags, String title) {
+        layoutParamsType = type;
+        layoutParamsPrivateFlags = flags;
+        windowTitle = title;
+    }
+}
diff --git a/core/java/com/android/internal/statusbar/IStatusBar.aidl b/core/java/com/android/internal/statusbar/IStatusBar.aidl
index 9441825..c8ba52a 100644
--- a/core/java/com/android/internal/statusbar/IStatusBar.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBar.aidl
@@ -151,17 +151,17 @@
 
     void showShutdownUi(boolean isReboot, String reason);
 
-    // Used to show the dialog when BiometricService starts authentication
-    void showBiometricDialog(in Bundle bundle, IBiometricServiceReceiverInternal receiver, int type,
-            boolean requireConfirmation, int userId, String opPackageName);
-    // Used to hide the dialog when a biometric is authenticated
+    // Used to show the authentication dialog (Biometrics, Device Credential)
+    void showAuthenticationDialog(in Bundle bundle, IBiometricServiceReceiverInternal receiver,
+            int biometricModality, boolean requireConfirmation, int userId, String opPackageName);
+    // Used to notify the authentication dialog that a biometric has been authenticated or rejected
     void onBiometricAuthenticated(boolean authenticated, String failureReason);
     // Used to set a temporary message, e.g. fingerprint not recognized, finger moved too fast, etc
     void onBiometricHelp(String message);
     // Used to set a message - the dialog will dismiss after a certain amount of time
-    void onBiometricError(String error);
-    // Used to hide the biometric dialog when the AuthenticationClient is stopped
-    void hideBiometricDialog();
+    void onBiometricError(int errorCode, String error);
+    // Used to hide the authentication dialog, e.g. when the application cancels authentication
+    void hideAuthenticationDialog();
 
     /**
      * Notifies System UI that the display is ready to show system decorations.
diff --git a/core/java/com/android/internal/statusbar/IStatusBarService.aidl b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
index 4c3a177..a845b58 100644
--- a/core/java/com/android/internal/statusbar/IStatusBarService.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
@@ -99,15 +99,15 @@
     void showPinningEnterExitToast(boolean entering);
     void showPinningEscapeToast();
 
-    // Used to show the dialog when BiometricService starts authentication
-    void showBiometricDialog(in Bundle bundle, IBiometricServiceReceiverInternal receiver, int type,
-            boolean requireConfirmation, int userId, String opPackageName);
-    // Used to hide the dialog when a biometric is authenticated
+    // Used to show the authentication dialog (Biometrics, Device Credential)
+    void showAuthenticationDialog(in Bundle bundle, IBiometricServiceReceiverInternal receiver,
+            int biometricModality, boolean requireConfirmation, int userId, String opPackageName);
+    // Used to notify the authentication dialog that a biometric has been authenticated or rejected
     void onBiometricAuthenticated(boolean authenticated, String failureReason);
     // Used to set a temporary message, e.g. fingerprint not recognized, finger moved too fast, etc
     void onBiometricHelp(String message);
     // Used to set a message - the dialog will dismiss after a certain amount of time
-    void onBiometricError(String error);
-    // Used to hide the biometric dialog when the AuthenticationClient is stopped
-    void hideBiometricDialog();
+    void onBiometricError(int errorCode, String error);
+    // Used to hide the authentication dialog, e.g. when the application cancels authentication
+    void hideAuthenticationDialog();
 }
diff --git a/core/java/com/android/internal/util/MimeIconUtils.java b/core/java/com/android/internal/util/MimeIconUtils.java
index 2230c31..31ea5b2 100644
--- a/core/java/com/android/internal/util/MimeIconUtils.java
+++ b/core/java/com/android/internal/util/MimeIconUtils.java
@@ -27,7 +27,7 @@
 import com.android.internal.R;
 import com.android.internal.annotations.GuardedBy;
 
-import libcore.net.MimeMap;
+import libcore.content.type.MimeMap;
 
 import java.util.Locale;
 import java.util.Objects;
diff --git a/core/java/com/android/internal/util/function/DecConsumer.java b/core/java/com/android/internal/util/function/DecConsumer.java
new file mode 100644
index 0000000..0abb785
--- /dev/null
+++ b/core/java/com/android/internal/util/function/DecConsumer.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.internal.util.function;
+
+import java.util.function.Consumer;
+
+/**
+ * A 10-argument {@link Consumer}
+ *
+ * @hide
+ */
+public interface DecConsumer<A, B, C, D, E, F, G, H, I, J> {
+    void accept(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j);
+}
diff --git a/core/java/com/android/internal/util/function/DecFunction.java b/core/java/com/android/internal/util/function/DecFunction.java
new file mode 100644
index 0000000..59fc5e6
--- /dev/null
+++ b/core/java/com/android/internal/util/function/DecFunction.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.internal.util.function;
+
+import java.util.function.Function;
+
+/**
+ * A 10-argument {@link Function}
+ *
+ * @hide
+ */
+public interface DecFunction<A, B, C, D, E, F, G, H, I, J, R> {
+    R apply(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j);
+}
diff --git a/core/java/com/android/internal/util/function/DecPredicate.java b/core/java/com/android/internal/util/function/DecPredicate.java
new file mode 100644
index 0000000..975993d
--- /dev/null
+++ b/core/java/com/android/internal/util/function/DecPredicate.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.internal.util.function;
+
+import java.util.function.Predicate;
+
+/**
+ * A 10-argument {@link Predicate}
+ *
+ * @hide
+ */
+public interface DecPredicate<A, B, C, D, E, F, G, H, I, J> {
+    boolean test(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j);
+}
diff --git a/core/java/com/android/internal/util/function/UndecConsumer.java b/core/java/com/android/internal/util/function/UndecConsumer.java
new file mode 100644
index 0000000..1a1d4ca
--- /dev/null
+++ b/core/java/com/android/internal/util/function/UndecConsumer.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.internal.util.function;
+
+import java.util.function.Consumer;
+
+/**
+ * A 11-argument {@link Consumer}
+ *
+ * @hide
+ */
+public interface UndecConsumer<A, B, C, D, E, F, G, H, I, J, K> {
+    void accept(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j, K k);
+}
diff --git a/core/java/com/android/internal/util/function/UndecFunction.java b/core/java/com/android/internal/util/function/UndecFunction.java
new file mode 100644
index 0000000..5cd324c
--- /dev/null
+++ b/core/java/com/android/internal/util/function/UndecFunction.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.internal.util.function;
+
+import java.util.function.Function;
+
+/**
+ * A 11-argument {@link Function}
+ *
+ * @hide
+ */
+public interface UndecFunction<A, B, C, D, E, F, G, H, I, J, K, R> {
+    R apply(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j, K k);
+}
diff --git a/core/java/com/android/internal/util/function/UndecPredicate.java b/core/java/com/android/internal/util/function/UndecPredicate.java
new file mode 100644
index 0000000..c09193e
--- /dev/null
+++ b/core/java/com/android/internal/util/function/UndecPredicate.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.internal.util.function;
+
+import java.util.function.Predicate;
+
+/**
+ * A 11-argument {@link Predicate}
+ *
+ * @hide
+ */
+public interface UndecPredicate<A, B, C, D, E, F, G, H, I, J, K> {
+    boolean test(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j, K k);
+}
diff --git a/core/java/com/android/internal/util/function/pooled/OmniFunction.java b/core/java/com/android/internal/util/function/pooled/OmniFunction.java
index d74e715..7a17253 100755
--- a/core/java/com/android/internal/util/function/pooled/OmniFunction.java
+++ b/core/java/com/android/internal/util/function/pooled/OmniFunction.java
@@ -18,6 +18,8 @@
 
 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
 import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
+import com.android.internal.util.function.DecConsumer;
+import com.android.internal.util.function.DecFunction;
 import com.android.internal.util.function.HeptConsumer;
 import com.android.internal.util.function.HeptFunction;
 import com.android.internal.util.function.HexConsumer;
@@ -32,6 +34,8 @@
 import com.android.internal.util.function.QuintFunction;
 import com.android.internal.util.function.TriConsumer;
 import com.android.internal.util.function.TriFunction;
+import com.android.internal.util.function.UndecConsumer;
+import com.android.internal.util.function.UndecFunction;
 
 import java.util.function.BiConsumer;
 import java.util.function.BiFunction;
@@ -43,62 +47,65 @@
  *
  * @hide
  */
-abstract class OmniFunction<A, B, C, D, E, F, G, H, I, R> implements
+abstract class OmniFunction<A, B, C, D, E, F, G, H, I, J, K, R> implements
         PooledFunction<A, R>, BiFunction<A, B, R>, TriFunction<A, B, C, R>,
         QuadFunction<A, B, C, D, R>, QuintFunction<A, B, C, D, E, R>,
         HexFunction<A, B, C, D, E, F, R>, HeptFunction<A, B, C, D, E, F, G, R>,
         OctFunction<A, B, C, D, E, F, G, H, R>, NonaFunction<A, B, C, D, E, F, G, H, I, R>,
+        DecFunction<A, B, C, D, E, F, G, H, I, J, R>,
+        UndecFunction<A, B, C, D, E, F, G, H, I, J, K, R>,
         PooledConsumer<A>, BiConsumer<A, B>, TriConsumer<A, B, C>, QuadConsumer<A, B, C, D>,
         QuintConsumer<A, B, C, D, E>, HexConsumer<A, B, C, D, E, F>,
         HeptConsumer<A, B, C, D, E, F, G>, OctConsumer<A, B, C, D, E, F, G, H>,
-        NonaConsumer<A, B, C, D, E, F, G, H, I>, PooledPredicate<A>, BiPredicate<A, B>,
-        PooledSupplier<R>, PooledRunnable, ThrowingRunnable, ThrowingSupplier<R>,
-        PooledSupplier.OfInt, PooledSupplier.OfLong, PooledSupplier.OfDouble {
+        NonaConsumer<A, B, C, D, E, F, G, H, I>, DecConsumer<A, B, C, D, E, F, G, H, I, J>,
+        UndecConsumer<A, B, C, D, E, F, G, H, I, J, K>,
+        PooledPredicate<A>, BiPredicate<A, B>, PooledSupplier<R>, PooledRunnable, ThrowingRunnable,
+        ThrowingSupplier<R>, PooledSupplier.OfInt, PooledSupplier.OfLong, PooledSupplier.OfDouble {
 
-    abstract R invoke(A a, B b, C c, D d, E e, F f, G g, H h, I i);
+    abstract R invoke(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j, K k);
 
     @Override
     public R apply(A o, B o2) {
-        return invoke(o, o2, null, null, null, null, null, null, null);
+        return invoke(o, o2, null, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public R apply(A o) {
-        return invoke(o, null, null, null, null, null, null, null, null);
+        return invoke(o, null, null, null, null, null, null, null, null, null, null);
     }
 
-    public abstract <V> OmniFunction<A, B, C, D, E, F, G, H, I, V> andThen(
+    public abstract <V> OmniFunction<A, B, C, D, E, F, G, H, I, J, K, V> andThen(
             Function<? super R, ? extends V> after);
-    public abstract OmniFunction<A, B, C, D, E, F, G, H, I, R> negate();
+    public abstract OmniFunction<A, B, C, D, E, F, G, H, I, J, K, R> negate();
 
     @Override
     public void accept(A o, B o2) {
-        invoke(o, o2, null, null, null, null, null, null, null);
+        invoke(o, o2, null, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public void accept(A o) {
-        invoke(o, null, null, null, null, null, null, null, null);
+        invoke(o, null, null, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public void run() {
-        invoke(null, null, null, null, null, null, null, null, null);
+        invoke(null, null, null, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public R get() {
-        return invoke(null, null, null, null, null, null, null, null, null);
+        return invoke(null, null, null, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public boolean test(A o, B o2) {
-        return (Boolean) invoke(o, o2, null, null, null, null, null, null, null);
+        return (Boolean) invoke(o, o2, null, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public boolean test(A o) {
-        return (Boolean) invoke(o, null, null, null, null, null, null, null, null);
+        return (Boolean) invoke(o, null, null, null, null, null, null, null, null, null, null);
     }
 
     @Override
@@ -113,72 +120,92 @@
 
     @Override
     public R apply(A a, B b, C c) {
-        return invoke(a, b, c, null, null, null, null, null, null);
+        return invoke(a, b, c, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public void accept(A a, B b, C c) {
-        invoke(a, b, c, null, null, null, null, null, null);
+        invoke(a, b, c, null, null, null, null, null, null, null, null);
     }
 
     @Override
     public R apply(A a, B b, C c, D d) {
-        return invoke(a, b, c, d, null, null, null, null, null);
+        return invoke(a, b, c, d, null, null, null, null, null, null, null);
     }
 
     @Override
     public R apply(A a, B b, C c, D d, E e) {
-        return invoke(a, b, c, d, e, null, null, null, null);
+        return invoke(a, b, c, d, e, null, null, null, null, null, null);
     }
 
     @Override
     public R apply(A a, B b, C c, D d, E e, F f) {
-        return invoke(a, b, c, d, e, f, null, null, null);
+        return invoke(a, b, c, d, e, f, null, null, null, null, null);
     }
 
     @Override
     public R apply(A a, B b, C c, D d, E e, F f, G g) {
-        return invoke(a, b, c, d, e, f, g, null, null);
+        return invoke(a, b, c, d, e, f, g, null, null, null, null);
     }
 
     @Override
     public R apply(A a, B b, C c, D d, E e, F f, G g, H h) {
-        return invoke(a, b, c, d, e, f, g, h, null);
+        return invoke(a, b, c, d, e, f, g, h, null, null, null);
     }
 
     @Override
     public R apply(A a, B b, C c, D d, E e, F f, G g, H h, I i) {
-        return invoke(a, b, c, d, e, f, g, h, i);
+        return invoke(a, b, c, d, e, f, g, h, i, null, null);
+    }
+
+    @Override
+    public R apply(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j) {
+        return invoke(a, b, c, d, e, f, g, h, i, j, null);
+    }
+
+    @Override
+    public R apply(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j, K k) {
+        return invoke(a, b, c, d, e, f, g, h, i, j, k);
     }
 
     @Override
     public void accept(A a, B b, C c, D d) {
-        invoke(a, b, c, d, null, null, null, null, null);
+        invoke(a, b, c, d, null, null, null, null, null, null, null);
     }
 
     @Override
     public void accept(A a, B b, C c, D d, E e) {
-        invoke(a, b, c, d, e, null, null, null, null);
+        invoke(a, b, c, d, e, null, null, null, null, null, null);
     }
 
     @Override
     public void accept(A a, B b, C c, D d, E e, F f) {
-        invoke(a, b, c, d, e, f, null, null, null);
+        invoke(a, b, c, d, e, f, null, null, null, null, null);
     }
 
     @Override
     public void accept(A a, B b, C c, D d, E e, F f, G g) {
-        invoke(a, b, c, d, e, f, g, null, null);
+        invoke(a, b, c, d, e, f, g, null, null, null, null);
     }
 
     @Override
     public void accept(A a, B b, C c, D d, E e, F f, G g, H h) {
-        invoke(a, b, c, d, e, f, g, h, null);
+        invoke(a, b, c, d, e, f, g, h, null, null, null);
     }
 
     @Override
     public void accept(A a, B b, C c, D d, E e, F f, G g, H h, I i) {
-        invoke(a, b, c, d, e, f, g, h, i);
+        invoke(a, b, c, d, e, f, g, h, i, null, null);
+    }
+
+    @Override
+    public void accept(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j) {
+        invoke(a, b, c, d, e, f, g, h, i, j, null);
+    }
+
+    @Override
+    public void accept(A a, B b, C c, D d, E e, F f, G g, H h, I i, J j, K k) {
+        invoke(a, b, c, d, e, f, g, h, i, j, k);
     }
 
     @Override
@@ -192,5 +219,5 @@
     }
 
     @Override
-    public abstract OmniFunction<A, B, C, D, E, F, G, H, I, R> recycleOnUse();
+    public abstract OmniFunction<A, B, C, D, E, F, G, H, I, J, K, R> recycleOnUse();
 }
diff --git a/core/java/com/android/internal/util/function/pooled/PooledLambda.java b/core/java/com/android/internal/util/function/pooled/PooledLambda.java
index c00932e..b9bf933 100755
--- a/core/java/com/android/internal/util/function/pooled/PooledLambda.java
+++ b/core/java/com/android/internal/util/function/pooled/PooledLambda.java
@@ -21,6 +21,8 @@
 
 import android.os.Message;
 
+import com.android.internal.util.function.DecConsumer;
+import com.android.internal.util.function.DecFunction;
 import com.android.internal.util.function.HeptConsumer;
 import com.android.internal.util.function.HeptFunction;
 import com.android.internal.util.function.HexConsumer;
@@ -35,6 +37,8 @@
 import com.android.internal.util.function.QuintFunction;
 import com.android.internal.util.function.TriConsumer;
 import com.android.internal.util.function.TriFunction;
+import com.android.internal.util.function.UndecConsumer;
+import com.android.internal.util.function.UndecFunction;
 import com.android.internal.util.function.pooled.PooledLambdaImpl.LambdaType.ReturnType;
 
 import java.util.function.BiConsumer;
@@ -181,7 +185,7 @@
             A arg1) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 1, 0, ReturnType.VOID, arg1, null, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -198,7 +202,7 @@
             A arg1) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 1, 0, ReturnType.BOOLEAN, arg1, null, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -215,7 +219,7 @@
             A arg1) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 1, 0, ReturnType.OBJECT, arg1, null, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -246,7 +250,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 1, 0, ReturnType.VOID, arg1, null, null, null, null, null, null, null,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -266,7 +270,7 @@
             A arg1, B arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 0, ReturnType.VOID, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -284,7 +288,7 @@
             A arg1, B arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 0, ReturnType.BOOLEAN, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -302,7 +306,7 @@
             A arg1, B arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 0, ReturnType.OBJECT, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -320,7 +324,7 @@
             ArgumentPlaceholder<A> arg1, B arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 1, ReturnType.VOID, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -338,7 +342,7 @@
             ArgumentPlaceholder<A> arg1, B arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 1, ReturnType.BOOLEAN, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -356,7 +360,7 @@
             ArgumentPlaceholder<A> arg1, B arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 1, ReturnType.OBJECT, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -374,7 +378,7 @@
             A arg1, ArgumentPlaceholder<B> arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 1, ReturnType.VOID, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -392,7 +396,7 @@
             A arg1, ArgumentPlaceholder<B> arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 1, ReturnType.BOOLEAN, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -410,7 +414,7 @@
             A arg1, ArgumentPlaceholder<B> arg2) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 2, 1, ReturnType.OBJECT, arg1, arg2, null, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -442,7 +446,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 2, 0, ReturnType.VOID, arg1, arg2, null, null, null, null, null, null,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -463,7 +467,7 @@
             A arg1, B arg2, C arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 0, ReturnType.VOID, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -482,7 +486,7 @@
             A arg1, B arg2, C arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 0, ReturnType.OBJECT, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -501,7 +505,7 @@
             ArgumentPlaceholder<A> arg1, B arg2, C arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 1, ReturnType.VOID, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -520,7 +524,7 @@
             ArgumentPlaceholder<A> arg1, B arg2, C arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 1, ReturnType.OBJECT, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -539,7 +543,7 @@
             A arg1, ArgumentPlaceholder<B> arg2, C arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 1, ReturnType.VOID, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -558,7 +562,7 @@
             A arg1, ArgumentPlaceholder<B> arg2, C arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 1, ReturnType.OBJECT, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -577,7 +581,7 @@
             A arg1, B arg2, ArgumentPlaceholder<C> arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 1, ReturnType.VOID, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -596,7 +600,7 @@
             A arg1, B arg2, ArgumentPlaceholder<C> arg3) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 3, 1, ReturnType.OBJECT, arg1, arg2, arg3, null, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -629,7 +633,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 3, 0, ReturnType.VOID, arg1, arg2, arg3, null, null, null, null, null,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -651,7 +655,7 @@
             A arg1, B arg2, C arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -671,7 +675,7 @@
             A arg1, B arg2, C arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -691,7 +695,7 @@
             ArgumentPlaceholder<A> arg1, B arg2, C arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.VOID, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -711,7 +715,7 @@
             ArgumentPlaceholder<A> arg1, B arg2, C arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.OBJECT, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -731,7 +735,7 @@
             A arg1, ArgumentPlaceholder<B> arg2, C arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.VOID, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -751,7 +755,7 @@
             A arg1, ArgumentPlaceholder<B> arg2, C arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.OBJECT, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -771,7 +775,7 @@
             A arg1, B arg2, ArgumentPlaceholder<C> arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.VOID, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -791,7 +795,7 @@
             A arg1, B arg2, ArgumentPlaceholder<C> arg3, D arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.OBJECT, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -811,7 +815,7 @@
             A arg1, B arg2, C arg3, ArgumentPlaceholder<D> arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.VOID, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -831,7 +835,7 @@
             A arg1, B arg2, C arg3, ArgumentPlaceholder<D> arg4) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 4, 1, ReturnType.OBJECT, arg1, arg2, arg3, arg4, null, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -865,7 +869,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 4, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, null, null, null, null,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -888,7 +892,7 @@
             A arg1, B arg2, C arg3, D arg4, E arg5) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 5, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -909,7 +913,7 @@
                     function, A arg1, B arg2, C arg3, D arg4, E arg5) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 5, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, arg5, null, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -945,7 +949,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 5, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, null, null, null,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -969,7 +973,7 @@
             A arg1, B arg2, C arg3, D arg4, E arg5, F arg6) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 6, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -991,7 +995,7 @@
                     ? extends R> function, A arg1, B arg2, C arg3, D arg4, E arg5, F arg6) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 6, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, arg5, arg6, null, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -1028,7 +1032,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 6, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, null, null,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -1053,7 +1057,7 @@
                     ? super G> function, A arg1, B arg2, C arg3, D arg4, E arg5, F arg6, G arg7) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 7, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -1077,7 +1081,7 @@
             A arg1, B arg2, C arg3, D arg4, E arg5, F arg6, G arg7) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 7, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, arg5, arg6, arg7, null,
-                null);
+                null, null, null);
     }
 
     /**
@@ -1115,7 +1119,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 7, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, null,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -1142,7 +1146,7 @@
             H arg8) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 8, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
-                null);
+                null, null, null);
     }
 
     /**
@@ -1167,7 +1171,7 @@
             A arg1, B arg2, C arg3, D arg4, E arg5, F arg6, G arg7, H arg8) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 8, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
-                null);
+                null, null, null);
     }
 
     /**
@@ -1207,7 +1211,7 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 8, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
-                    null);
+                    null, null, null);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
@@ -1235,7 +1239,7 @@
             E arg5, F arg6, G arg7, H arg8, I arg9) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 9, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
-                arg9);
+                arg9, null, null);
     }
 
     /**
@@ -1261,7 +1265,7 @@
             A arg1, B arg2, C arg3, D arg4, E arg5, F arg6, G arg7, H arg8, I arg9) {
         return acquire(PooledLambdaImpl.sPool,
                 function, 9, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
-                arg9);
+                arg9, null, null);
     }
 
     /**
@@ -1302,7 +1306,209 @@
         synchronized (Message.sPoolSync) {
             PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
                     function, 9, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
-                    arg9);
+                    arg9, null, null);
+            return Message.obtain().setCallback(callback.recycleOnUse());
+        }
+    }
+
+    /**
+     * {@link PooledRunnable} factory
+     *
+     * @param function non-capturing lambda(typically an unbounded method reference)
+     *                 to be invoked on call
+     * @param arg1 parameter supplied to {@code function} on call
+     * @param arg2 parameter supplied to {@code function} on call
+     * @param arg3 parameter supplied to {@code function} on call
+     * @param arg4 parameter supplied to {@code function} on call
+     * @param arg5 parameter supplied to {@code function} on call
+     * @param arg6 parameter supplied to {@code function} on call
+     * @param arg7 parameter supplied to {@code function} on call
+     * @param arg8 parameter supplied to {@code function} on call
+     * @param arg9 parameter supplied to {@code function} on call
+     * @param arg10 parameter supplied to {@code function} on call
+     * @return a {@link PooledRunnable}, equivalent to lambda:
+     *         {@code () -> function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) }
+     */
+    static <A, B, C, D, E, F, G, H, I, J> PooledRunnable obtainRunnable(
+            DecConsumer<? super A, ? super B, ? super C, ? super D, ? super E, ? super F,
+                    ? super G, ? super H, ? super I, ? super J> function, A arg1, B arg2, C arg3,
+            D arg4, E arg5, F arg6, G arg7, H arg8, I arg9, J arg10) {
+        return acquire(PooledLambdaImpl.sPool,
+                function, 10, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
+                arg9, arg10, null);
+    }
+
+    /**
+     * {@link PooledSupplier} factory
+     *
+     * @param function non-capturing lambda(typically an unbounded method reference)
+     *                 to be invoked on call
+     * @param arg1 parameter supplied to {@code function} on call
+     * @param arg2 parameter supplied to {@code function} on call
+     * @param arg3 parameter supplied to {@code function} on call
+     * @param arg4 parameter supplied to {@code function} on call
+     * @param arg5 parameter supplied to {@code function} on call
+     * @param arg6 parameter supplied to {@code function} on call
+     * @param arg7 parameter supplied to {@code function} on call
+     * @param arg8 parameter supplied to {@code function} on call
+     * @param arg9 parameter supplied to {@code function} on call
+     * @param arg10 parameter supplied to {@code function} on call
+     * @return a {@link PooledSupplier}, equivalent to lambda:
+     *         {@code () -> function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) }
+     */
+    static <A, B, C, D, E, F, G, H, I, J, R> PooledSupplier<R> obtainSupplier(
+            DecFunction<? super A, ? super B, ? super C, ? super D, ? super E, ? super F,
+                                ? super G, ? super H, ? super I, ? super J, ? extends R> function,
+            A arg1, B arg2, C arg3, D arg4, E arg5, F arg6, G arg7, H arg8, I arg9, J arg10) {
+        return acquire(PooledLambdaImpl.sPool,
+                function, 10, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
+                arg9, arg10, null);
+    }
+
+    /**
+     * Factory of {@link Message}s that contain an
+     * ({@link PooledLambda#recycleOnUse auto-recycling}) {@link PooledRunnable} as its
+     * {@link Message#getCallback internal callback}.
+     *
+     * The callback is equivalent to one obtainable via
+     * {@link #obtainRunnable(QuintConsumer, Object, Object, Object, Object, Object)}
+     *
+     * Note that using this method with {@link android.os.Handler#handleMessage}
+     * is more efficient than the alternative of {@link android.os.Handler#post}
+     * with a {@link PooledRunnable} due to the lack of 2 separate synchronization points
+     * when obtaining {@link Message} and {@link PooledRunnable} from pools separately
+     *
+     * You may optionally set a {@link Message#what} for the message if you want to be
+     * able to cancel it via {@link android.os.Handler#removeMessages}, but otherwise
+     * there's no need to do so
+     *
+     * @param function non-capturing lambda(typically an unbounded method reference)
+     *                 to be invoked on call
+     * @param arg1 parameter supplied to {@code function} on call
+     * @param arg2 parameter supplied to {@code function} on call
+     * @param arg3 parameter supplied to {@code function} on call
+     * @param arg4 parameter supplied to {@code function} on call
+     * @param arg5 parameter supplied to {@code function} on call
+     * @param arg6 parameter supplied to {@code function} on call
+     * @param arg7 parameter supplied to {@code function} on call
+     * @param arg8 parameter supplied to {@code function} on call
+     * @param arg9 parameter supplied to {@code function} on call
+     * @param arg10 parameter supplied to {@code function} on call
+     * @return a {@link Message} invoking {@code function(arg1, arg2, arg3, arg4, arg5, arg6,
+     * arg7, arg8, arg9, arg10) } when handled
+     */
+    static <A, B, C, D, E, F, G, H, I, J> Message obtainMessage(
+            DecConsumer<? super A, ? super B, ? super C, ? super D, ? super E, ? super F,
+                    ? super G, ? super H, ? super I, ? super J> function, A arg1, B arg2, C arg3,
+            D arg4, E arg5, F arg6, G arg7, H arg8, I arg9, J arg10) {
+        synchronized (Message.sPoolSync) {
+            PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
+                    function, 10, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7,
+                    arg8, arg9, arg10, null);
+            return Message.obtain().setCallback(callback.recycleOnUse());
+        }
+    }
+
+    /**
+     * {@link PooledRunnable} factory
+     *
+     * @param function non-capturing lambda(typically an unbounded method reference)
+     *                 to be invoked on call
+     * @param arg1 parameter supplied to {@code function} on call
+     * @param arg2 parameter supplied to {@code function} on call
+     * @param arg3 parameter supplied to {@code function} on call
+     * @param arg4 parameter supplied to {@code function} on call
+     * @param arg5 parameter supplied to {@code function} on call
+     * @param arg6 parameter supplied to {@code function} on call
+     * @param arg7 parameter supplied to {@code function} on call
+     * @param arg8 parameter supplied to {@code function} on call
+     * @param arg9 parameter supplied to {@code function} on call
+     * @param arg10 parameter supplied to {@code function} on call
+     * @param arg11 parameter supplied to {@code function} on call
+     * @return a {@link PooledRunnable}, equivalent to lambda:
+     *         {@code () -> function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10,
+     *         arg11) }
+     */
+    static <A, B, C, D, E, F, G, H, I, J, K> PooledRunnable obtainRunnable(
+            UndecConsumer<? super A, ? super B, ? super C, ? super D, ? super E, ? super F,
+                    ? super G, ? super H, ? super I, ? super J, ? super K> function, A arg1, B arg2,
+            C arg3, D arg4, E arg5, F arg6, G arg7, H arg8, I arg9, J arg10, K arg11) {
+        return acquire(PooledLambdaImpl.sPool,
+                function, 11, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
+                arg9, arg10, arg11);
+    }
+
+    /**
+     * {@link PooledSupplier} factory
+     *
+     * @param function non-capturing lambda(typically an unbounded method reference)
+     *                 to be invoked on call
+     * @param arg1 parameter supplied to {@code function} on call
+     * @param arg2 parameter supplied to {@code function} on call
+     * @param arg3 parameter supplied to {@code function} on call
+     * @param arg4 parameter supplied to {@code function} on call
+     * @param arg5 parameter supplied to {@code function} on call
+     * @param arg6 parameter supplied to {@code function} on call
+     * @param arg7 parameter supplied to {@code function} on call
+     * @param arg8 parameter supplied to {@code function} on call
+     * @param arg9 parameter supplied to {@code function} on call
+     * @param arg10 parameter supplied to {@code function} on call
+     * @param arg11 parameter supplied to {@code function} on call
+     * @return a {@link PooledSupplier}, equivalent to lambda:
+     *         {@code () -> function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10,
+     *         arg11) }
+     */
+    static <A, B, C, D, E, F, G, H, I, J, K, R> PooledSupplier<R> obtainSupplier(
+            UndecFunction<? super A, ? super B, ? super C, ? super D, ? super E, ? super F,
+                    ? super G, ? super H, ? super I, ? super J, ? super K, ? extends R> function,
+            A arg1, B arg2, C arg3, D arg4, E arg5, F arg6, G arg7, H arg8, I arg9, J arg10,
+            K arg11) {
+        return acquire(PooledLambdaImpl.sPool,
+                function, 11, 0, ReturnType.OBJECT, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,
+                arg9, arg10, arg11);
+    }
+
+    /**
+     * Factory of {@link Message}s that contain an
+     * ({@link PooledLambda#recycleOnUse auto-recycling}) {@link PooledRunnable} as its
+     * {@link Message#getCallback internal callback}.
+     *
+     * The callback is equivalent to one obtainable via
+     * {@link #obtainRunnable(QuintConsumer, Object, Object, Object, Object, Object)}
+     *
+     * Note that using this method with {@link android.os.Handler#handleMessage}
+     * is more efficient than the alternative of {@link android.os.Handler#post}
+     * with a {@link PooledRunnable} due to the lack of 2 separate synchronization points
+     * when obtaining {@link Message} and {@link PooledRunnable} from pools separately
+     *
+     * You may optionally set a {@link Message#what} for the message if you want to be
+     * able to cancel it via {@link android.os.Handler#removeMessages}, but otherwise
+     * there's no need to do so
+     *
+     * @param function non-capturing lambda(typically an unbounded method reference)
+     *                 to be invoked on call
+     * @param arg1 parameter supplied to {@code function} on call
+     * @param arg2 parameter supplied to {@code function} on call
+     * @param arg3 parameter supplied to {@code function} on call
+     * @param arg4 parameter supplied to {@code function} on call
+     * @param arg5 parameter supplied to {@code function} on call
+     * @param arg6 parameter supplied to {@code function} on call
+     * @param arg7 parameter supplied to {@code function} on call
+     * @param arg8 parameter supplied to {@code function} on call
+     * @param arg9 parameter supplied to {@code function} on call
+     * @param arg10 parameter supplied to {@code function} on call
+     * @param arg11 parameter supplied to {@code function} on call
+     * @return a {@link Message} invoking {@code function(arg1, arg2, arg3, arg4, arg5, arg6,
+     * arg7, arg8, arg9, arg10, arg11) } when handled
+     */
+    static <A, B, C, D, E, F, G, H, I, J, K> Message obtainMessage(
+            UndecConsumer<? super A, ? super B, ? super C, ? super D, ? super E, ? super F,
+                    ? super G, ? super H, ? super I, ? super J, ? super K> function, A arg1, B arg2,
+            C arg3, D arg4, E arg5, F arg6, G arg7, H arg8, I arg9, J arg10, K arg11) {
+        synchronized (Message.sPoolSync) {
+            PooledRunnable callback = acquire(PooledLambdaImpl.sMessageCallbacksPool,
+                    function, 11, 0, ReturnType.VOID, arg1, arg2, arg3, arg4, arg5, arg6, arg7,
+                    arg8, arg9, arg10, arg11);
             return Message.obtain().setCallback(callback.recycleOnUse());
         }
     }
diff --git a/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java b/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
index 1fdb1f3..c7502ef 100755
--- a/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
+++ b/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
@@ -16,6 +16,7 @@
 
 package com.android.internal.util.function.pooled;
 
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.os.Message;
 import android.text.TextUtils;
@@ -25,6 +26,9 @@
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.BitUtils;
 import com.android.internal.util.Preconditions;
+import com.android.internal.util.function.DecConsumer;
+import com.android.internal.util.function.DecFunction;
+import com.android.internal.util.function.DecPredicate;
 import com.android.internal.util.function.HeptConsumer;
 import com.android.internal.util.function.HeptFunction;
 import com.android.internal.util.function.HeptPredicate;
@@ -46,6 +50,9 @@
 import com.android.internal.util.function.TriConsumer;
 import com.android.internal.util.function.TriFunction;
 import com.android.internal.util.function.TriPredicate;
+import com.android.internal.util.function.UndecConsumer;
+import com.android.internal.util.function.UndecFunction;
+import com.android.internal.util.function.UndecPredicate;
 
 import java.util.Arrays;
 import java.util.Objects;
@@ -62,12 +69,12 @@
  * @hide
  */
 final class PooledLambdaImpl<R> extends OmniFunction<Object,
-        Object, Object, Object, Object, Object, Object, Object, Object, R> {
+        Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, R> {
 
     private static final boolean DEBUG = false;
     private static final String LOG_TAG = "PooledLambdaImpl";
 
-    private static final int MAX_ARGS = 9;
+    private static final int MAX_ARGS = 11;
 
     private static final int MAX_POOL_SIZE = 50;
 
@@ -133,7 +140,7 @@
 
     /**
      * Bit schema:
-     * AAAAAAAAABCDEEEEEEFFFFFF
+     * AAAAAAAAAAABCDEEEEEEFFFFFF
      *
      * Where:
      * A - whether {@link #mArgs arg} at corresponding index was specified at
@@ -170,18 +177,18 @@
 
     @Override
     R invoke(Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7,
-            Object a8, Object a9) {
+            Object a8, Object a9, Object a10, Object a11) {
         checkNotRecycled();
         if (DEBUG) {
             Log.i(LOG_TAG, this + ".invoke("
                     + commaSeparateFirstN(
-                            new Object[] { a1, a2, a3, a4, a5, a6, a7, a8, a9 },
+                            new Object[] { a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11 },
                             LambdaType.decodeArgCount(getFlags(MASK_EXPOSED_AS)))
                     + ")");
         }
         final boolean notUsed = fillInArg(a1) && fillInArg(a2) && fillInArg(a3) && fillInArg(a4)
                 && fillInArg(a5) && fillInArg(a6) && fillInArg(a7) && fillInArg(a8)
-                && fillInArg(a9);
+                && fillInArg(a9) && fillInArg(a10) && fillInArg(a11);
         int argCount = LambdaType.decodeArgCount(getFlags(MASK_FUNC_TYPE));
         if (argCount != LambdaType.MASK_ARG_COUNT) {
             for (int i = 0; i < argCount; i++) {
@@ -409,6 +416,48 @@
                     }
                 }
             } break;
+
+            case 10: {
+                switch (returnType) {
+                    case LambdaType.ReturnType.VOID: {
+                        ((DecConsumer) mFunc).accept(popArg(0), popArg(1),
+                                popArg(2), popArg(3), popArg(4), popArg(5),
+                                popArg(6), popArg(7), popArg(8), popArg(9));
+                        return null;
+                    }
+                    case LambdaType.ReturnType.BOOLEAN: {
+                        return (R) (Object) ((DecPredicate) mFunc).test(popArg(0),
+                                popArg(1), popArg(2), popArg(3), popArg(4),
+                                popArg(5), popArg(6), popArg(7), popArg(8), popArg(9));
+                    }
+                    case LambdaType.ReturnType.OBJECT: {
+                        return (R) ((DecFunction) mFunc).apply(popArg(0), popArg(1),
+                                popArg(2), popArg(3), popArg(4), popArg(5),
+                                popArg(6), popArg(7), popArg(8), popArg(9));
+                    }
+                }
+            } break;
+
+            case 11: {
+                switch (returnType) {
+                    case LambdaType.ReturnType.VOID: {
+                        ((UndecConsumer) mFunc).accept(popArg(0), popArg(1),
+                                popArg(2), popArg(3), popArg(4), popArg(5),
+                                popArg(6), popArg(7), popArg(8), popArg(9), popArg(10));
+                        return null;
+                    }
+                    case LambdaType.ReturnType.BOOLEAN: {
+                        return (R) (Object) ((UndecPredicate) mFunc).test(popArg(0),
+                                popArg(1), popArg(2), popArg(3), popArg(4),
+                                popArg(5), popArg(6), popArg(7), popArg(8), popArg(9), popArg(10));
+                    }
+                    case LambdaType.ReturnType.OBJECT: {
+                        return (R) ((UndecFunction) mFunc).apply(popArg(0), popArg(1),
+                                popArg(2), popArg(3), popArg(4), popArg(5),
+                                popArg(6), popArg(7), popArg(8), popArg(9), popArg(10));
+                    }
+                }
+            } break;
         }
         throw new IllegalStateException("Unknown function type: " + LambdaType.toString(funcType));
     }
@@ -474,7 +523,7 @@
      */
     static <E extends PooledLambda> E acquire(Pool pool, Object func,
             int fNumArgs, int numPlaceholders, int fReturnType, Object a, Object b, Object c,
-            Object d, Object e, Object f, Object g, Object h, Object i) {
+            Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) {
         PooledLambdaImpl r = acquire(pool);
         if (DEBUG) {
             Log.i(LOG_TAG,
@@ -492,6 +541,8 @@
                             + ", g = " + g
                             + ", h = " + h
                             + ", i = " + i
+                            + ", j = " + j
+                            + ", k = " + k
                             + ")");
         }
         r.mFunc = Preconditions.checkNotNull(func);
@@ -507,6 +558,8 @@
         setIfInBounds(r.mArgs, 6, g);
         setIfInBounds(r.mArgs, 7, h);
         setIfInBounds(r.mArgs, 8, i);
+        setIfInBounds(r.mArgs, 9, j);
+        setIfInBounds(r.mArgs, 10, k);
         return (E) r;
     }
 
@@ -527,19 +580,49 @@
         return r;
     }
 
+    // TODO: add unit test
+    @NonNull
+    private static String getFriendlyName(@NonNull Object function) {
+        // Full function has one of the following formats:
+        //   package-$$Lambda$class$randomId
+        //   package-$$Lambda$randomId
+        //
+        // We just want just package.class$Lambda (or package$Lambda) respectively
+
+        final String fullFunction = function.toString();
+
+        final int endPkgIdx = fullFunction.indexOf("-$$");
+        if (endPkgIdx == -1) return fullFunction;
+
+        // firstDollarIdx could be either beginning of class or beginning of the random id
+        final int firstDollarIdx = fullFunction.indexOf('$', endPkgIdx + 3);
+        if (firstDollarIdx == -1) return fullFunction;
+
+        final int endClassIdx = fullFunction.indexOf('$', firstDollarIdx + 1);
+        if (endClassIdx == -1) {
+            // Just package
+            return fullFunction.substring(0, endPkgIdx - 1) + "$Lambda";
+        }
+
+        // Package + class
+        return fullFunction.substring(0, endPkgIdx)
+                + fullFunction.substring(firstDollarIdx + 1, endClassIdx)
+                + "$Lambda";
+    }
+
     private static void setIfInBounds(Object[] array, int i, Object a) {
         if (i < ArrayUtils.size(array)) array[i] = a;
     }
 
     @Override
     public OmniFunction<Object, Object, Object, Object, Object, Object, Object, Object, Object,
-            R> negate() {
+            Object, Object, R> negate() {
         throw new UnsupportedOperationException();
     }
 
     @Override
     public <V> OmniFunction<Object, Object, Object, Object, Object, Object, Object, Object, Object,
-            V> andThen(Function<? super R, ? extends V> after) {
+            Object, Object, V> andThen(Function<? super R, ? extends V> after) {
         throw new UnsupportedOperationException();
     }
 
@@ -560,12 +643,17 @@
 
     @Override
     public OmniFunction<Object, Object, Object, Object, Object, Object, Object, Object, Object,
-            R> recycleOnUse() {
+            Object, Object, R> recycleOnUse() {
         if (DEBUG) Log.i(LOG_TAG, this + ".recycleOnUse()");
         mFlags |= FLAG_RECYCLE_ON_USE;
         return this;
     }
 
+    @Override
+    public String getTraceName() {
+        return getFriendlyName(mFunc);
+    }
+
     private boolean isRecycled() {
         return (mFlags & FLAG_RECYCLED) != 0;
     }
@@ -647,6 +735,8 @@
                 case 7: return "Hept";
                 case 8: return "Oct";
                 case 9: return "Nona";
+                case 10: return "Dec";
+                case 11: return "Undec";
                 default: return "" + argCount + "arg";
             }
         }
diff --git a/core/java/com/android/internal/util/function/pooled/PooledRunnable.java b/core/java/com/android/internal/util/function/pooled/PooledRunnable.java
index 89ca82e..f0bc2ca 100644
--- a/core/java/com/android/internal/util/function/pooled/PooledRunnable.java
+++ b/core/java/com/android/internal/util/function/pooled/PooledRunnable.java
@@ -16,6 +16,8 @@
 
 package com.android.internal.util.function.pooled;
 
+import android.os.TraceNameSupplier;
+
 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
 
 /**
@@ -24,7 +26,8 @@
  * @see PooledLambda
  * @hide
  */
-public interface PooledRunnable extends PooledLambda, Runnable, ThrowingRunnable {
+public interface PooledRunnable
+        extends PooledLambda, Runnable, ThrowingRunnable, TraceNameSupplier {
     /** @inheritDoc */
     PooledRunnable recycleOnUse();
 }
diff --git a/core/java/com/android/internal/view/BaseIWindow.java b/core/java/com/android/internal/view/BaseIWindow.java
index cc468f4..0e078dd 100644
--- a/core/java/com/android/internal/view/BaseIWindow.java
+++ b/core/java/com/android/internal/view/BaseIWindow.java
@@ -30,6 +30,7 @@
 import android.view.InsetsSourceControl;
 import android.view.InsetsState;
 import android.view.PointerIcon;
+import android.view.WindowInsets.Type.InsetType;
 
 import com.android.internal.os.IResultReceiver;
 
@@ -75,6 +76,10 @@
     }
 
     @Override
+    public void showInsets(@InsetType int types, boolean fromIme)  throws RemoteException {
+    }
+
+    @Override
     public void moved(int newX, int newY) {
     }
 
diff --git a/core/java/com/android/server/SystemConfig.java b/core/java/com/android/server/SystemConfig.java
index 7cd3e95..697825d 100644
--- a/core/java/com/android/server/SystemConfig.java
+++ b/core/java/com/android/server/SystemConfig.java
@@ -35,6 +35,7 @@
 import android.util.SparseArray;
 import android.util.Xml;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.XmlUtils;
 
 import libcore.io.IoUtils;
@@ -50,6 +51,7 @@
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 /**
  * Loads global system configuration info.
@@ -209,6 +211,10 @@
 
     private final ArraySet<String> mBugreportWhitelistedPackages = new ArraySet<>();
 
+    // Map of packagesNames to userTypes. Stored temporarily until cleared by UserManagerService().
+    private ArrayMap<String, Set<String>> mPackageToUserTypeWhitelist = new ArrayMap<>();
+    private ArrayMap<String, Set<String>> mPackageToUserTypeBlacklist = new ArrayMap<>();
+
     public static SystemConfig getInstance() {
         if (!isSystemProcess()) {
             Slog.wtf(TAG, "SystemConfig is being accessed by a process other than "
@@ -359,7 +365,48 @@
         return mBugreportWhitelistedPackages;
     }
 
+    /**
+     * Gets map of packagesNames to userTypes, dictating on which user types each package should be
+     * initially installed, and then removes this map from SystemConfig.
+     * Called by UserManagerService when it is constructed.
+     */
+    public ArrayMap<String, Set<String>> getAndClearPackageToUserTypeWhitelist() {
+        ArrayMap<String, Set<String>> r = mPackageToUserTypeWhitelist;
+        mPackageToUserTypeWhitelist = new ArrayMap<>(0);
+        return r;
+    }
+
+    /**
+     * Gets map of packagesNames to userTypes, dictating on which user types each package should NOT
+     * be initially installed, even if they are whitelisted, and then removes this map from
+     * SystemConfig.
+     * Called by UserManagerService when it is constructed.
+     */
+    public ArrayMap<String, Set<String>> getAndClearPackageToUserTypeBlacklist() {
+        ArrayMap<String, Set<String>> r = mPackageToUserTypeBlacklist;
+        mPackageToUserTypeBlacklist = new ArrayMap<>(0);
+        return r;
+    }
+
+    /**
+     * Only use for testing. Do NOT use in production code.
+     * @param readPermissions false to create an empty SystemConfig; true to read the permissions.
+     */
+    @VisibleForTesting
+    protected SystemConfig(boolean readPermissions) {
+        if (readPermissions) {
+            Slog.w(TAG, "Constructing a test SystemConfig");
+            readAllPermissions();
+        } else {
+            Slog.w(TAG, "Constructing an empty test SystemConfig");
+        }
+    }
+
     SystemConfig() {
+        readAllPermissions();
+    }
+
+    private void readAllPermissions() {
         // Read configuration from system
         readPermissions(Environment.buildPath(
                 Environment.getRootDirectory(), "etc", "sysconfig"), ALLOW_ALL);
@@ -419,7 +466,8 @@
                 Environment.getSystemExtDirectory(), "etc", "permissions"), ALLOW_ALL);
     }
 
-    void readPermissions(File libraryDir, int permissionFlag) {
+    @VisibleForTesting
+    public void readPermissions(File libraryDir, int permissionFlag) {
         // Read permissions from given directory.
         if (!libraryDir.exists() || !libraryDir.isDirectory()) {
             if (permissionFlag == ALLOW_ALL) {
@@ -954,6 +1002,11 @@
                         }
                         XmlUtils.skipCurrentTag(parser);
                     } break;
+                    case "install-in-user-type": {
+                        // NB: We allow any directory permission to declare install-in-user-type.
+                        readInstallInUserType(parser,
+                                mPackageToUserTypeWhitelist, mPackageToUserTypeBlacklist);
+                    } break;
                     default: {
                         Slog.w(TAG, "Tag " + name + " is unknown in "
                                 + permFile + " at " + parser.getPositionDescription());
@@ -1091,6 +1144,53 @@
         }
     }
 
+    private void readInstallInUserType(XmlPullParser parser,
+            Map<String, Set<String>> doInstallMap,
+            Map<String, Set<String>> nonInstallMap)
+            throws IOException, XmlPullParserException {
+        final String packageName = parser.getAttributeValue(null, "package");
+        if (TextUtils.isEmpty(packageName)) {
+            Slog.w(TAG, "package is required for <install-in-user-type> in "
+                    + parser.getPositionDescription());
+            return;
+        }
+
+        Set<String> userTypesYes = doInstallMap.get(packageName);
+        Set<String> userTypesNo = nonInstallMap.get(packageName);
+        final int depth = parser.getDepth();
+        while (XmlUtils.nextElementWithin(parser, depth)) {
+            final String name = parser.getName();
+            if ("install-in".equals(name)) {
+                final String userType = parser.getAttributeValue(null, "user-type");
+                if (TextUtils.isEmpty(userType)) {
+                    Slog.w(TAG, "user-type is required for <install-in-user-type> in "
+                            + parser.getPositionDescription());
+                    continue;
+                }
+                if (userTypesYes == null) {
+                    userTypesYes = new ArraySet<>();
+                    doInstallMap.put(packageName, userTypesYes);
+                }
+                userTypesYes.add(userType);
+            } else if ("do-not-install-in".equals(name)) {
+                final String userType = parser.getAttributeValue(null, "user-type");
+                if (TextUtils.isEmpty(userType)) {
+                    Slog.w(TAG, "user-type is required for <install-in-user-type> in "
+                            + parser.getPositionDescription());
+                    continue;
+                }
+                if (userTypesNo == null) {
+                    userTypesNo = new ArraySet<>();
+                    nonInstallMap.put(packageName, userTypesNo);
+                }
+                userTypesNo.add(userType);
+            } else {
+                Slog.w(TAG, "unrecognized tag in <install-in-user-type> in "
+                        + parser.getPositionDescription());
+            }
+        }
+    }
+
     void readOemPermissions(XmlPullParser parser) throws IOException, XmlPullParserException {
         final String packageName = parser.getAttributeValue(null, "package");
         if (TextUtils.isEmpty(packageName)) {
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index 5a0f16e..0feab7f 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -54,6 +54,8 @@
 
     whole_static_libs: ["libandroid_graphics"],
 
+    export_static_lib_headers: ["libandroid_graphics"],
+
     shared_libs: [
         "libbase",
         "libcutils",
@@ -108,7 +110,6 @@
                 "android_view_InputEventReceiver.cpp",
                 "android_view_InputEventSender.cpp",
                 "android_view_InputQueue.cpp",
-                "android_view_FrameMetricsObserver.cpp",
                 "android_view_KeyCharacterMap.cpp",
                 "android_view_KeyEvent.cpp",
                 "android_view_MotionEvent.cpp",
@@ -256,8 +257,6 @@
                 "libnativeloader_lazy",
                 "libmemunreachable",
                 "libhidlbase",
-                "libhidltransport",
-                "libhwbinder",
                 "libvintf",
                 "libnativewindow",
                 "libdl",
@@ -337,7 +336,9 @@
     cppflags: ["-Wno-conversion-null"],
 
     srcs: [
+        "android/graphics/apex/android_bitmap.cpp",
         "android/graphics/apex/android_region.cpp",
+        "android/graphics/apex/android_paint.cpp",
 
         "android_graphics_Canvas.cpp",
         "android_graphics_ColorSpace.cpp",
@@ -390,7 +391,6 @@
     ],
 
     export_include_dirs: [
-        ".",
         "android/graphics/apex/include",
     ],
 
@@ -420,7 +420,9 @@
         android: {
             srcs: [ // sources that depend on android only libraries
                 "android/graphics/apex/android_canvas.cpp",
+                "android/graphics/apex/jni_runtime.cpp",
 
+                "android_view_FrameMetricsObserver.cpp",
                 "android_view_TextureLayer.cpp",
                 "android_view_ThreadedRenderer.cpp",
                 "android/graphics/BitmapRegionDecoder.cpp",
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index c12940a..d476d2d 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -22,6 +22,7 @@
 
 #include <android-base/macros.h>
 #include <android-base/properties.h>
+#include <android/graphics/jni_runtime.h>
 #include <binder/IBinder.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
@@ -33,8 +34,6 @@
 #include <cutils/properties.h>
 #include <server_configurable_flags/get_flags.h>
 
-#include <SkGraphics.h>
-
 #include "jni.h"
 #include <nativehelper/JNIHelp.h>
 #include <nativehelper/JniInvocation.h>
@@ -56,24 +55,7 @@
 
 extern int register_android_os_Binder(JNIEnv* env);
 extern int register_android_os_Process(JNIEnv* env);
-extern int register_android_graphics_Bitmap(JNIEnv*);
-extern int register_android_graphics_BitmapFactory(JNIEnv*);
-extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
-extern int register_android_graphics_ByteBufferStreamAdaptor(JNIEnv* env);
-extern int register_android_graphics_Camera(JNIEnv* env);
-extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env);
 extern int register_android_graphics_GraphicBuffer(JNIEnv* env);
-extern int register_android_graphics_Graphics(JNIEnv* env);
-extern int register_android_graphics_ImageDecoder(JNIEnv*);
-extern int register_android_graphics_drawable_AnimatedImageDrawable(JNIEnv*);
-extern int register_android_graphics_Interpolator(JNIEnv* env);
-extern int register_android_graphics_MaskFilter(JNIEnv* env);
-extern int register_android_graphics_Movie(JNIEnv* env);
-extern int register_android_graphics_NinePatch(JNIEnv*);
-extern int register_android_graphics_PathEffect(JNIEnv* env);
-extern int register_android_graphics_Shader(JNIEnv* env);
-extern int register_android_graphics_Typeface(JNIEnv* env);
-extern int register_android_graphics_YuvImage(JNIEnv* env);
 
 extern int register_com_google_android_gles_jni_EGLImpl(JNIEnv* env);
 extern int register_com_google_android_gles_jni_GLImpl(JNIEnv* env);
@@ -130,46 +112,18 @@
 extern int register_android_util_StatsLogInternal(JNIEnv* env);
 extern int register_android_util_Log(JNIEnv* env);
 extern int register_android_util_MemoryIntArray(JNIEnv* env);
-extern int register_android_util_PathParser(JNIEnv* env);
 extern int register_android_content_StringBlock(JNIEnv* env);
 extern int register_android_content_XmlBlock(JNIEnv* env);
 extern int register_android_content_res_ApkAssets(JNIEnv* env);
-extern int register_android_graphics_Canvas(JNIEnv* env);
-extern int register_android_graphics_CanvasProperty(JNIEnv* env);
-extern int register_android_graphics_ColorFilter(JNIEnv* env);
-extern int register_android_graphics_ColorSpace(JNIEnv* env);
-extern int register_android_graphics_DrawFilter(JNIEnv* env);
-extern int register_android_graphics_FontFamily(JNIEnv* env);
-extern int register_android_graphics_Matrix(JNIEnv* env);
-extern int register_android_graphics_Paint(JNIEnv* env);
-extern int register_android_graphics_Path(JNIEnv* env);
-extern int register_android_graphics_PathMeasure(JNIEnv* env);
-extern int register_android_graphics_Picture(JNIEnv*);
-extern int register_android_graphics_Region(JNIEnv* env);
-extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
-extern int register_android_graphics_drawable_AnimatedVectorDrawable(JNIEnv* env);
-extern int register_android_graphics_drawable_VectorDrawable(JNIEnv* env);
-extern int register_android_graphics_fonts_Font(JNIEnv* env);
-extern int register_android_graphics_fonts_FontFamily(JNIEnv* env);
-extern int register_android_graphics_pdf_PdfDocument(JNIEnv* env);
-extern int register_android_graphics_pdf_PdfEditor(JNIEnv* env);
-extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env);
-extern int register_android_graphics_text_MeasuredText(JNIEnv* env);
-extern int register_android_graphics_text_LineBreaker(JNIEnv *env);
 extern int register_android_view_DisplayEventReceiver(JNIEnv* env);
-extern int register_android_view_DisplayListCanvas(JNIEnv* env);
-extern int register_android_view_FrameMetricsObserver(JNIEnv* env);
 extern int register_android_view_InputApplicationHandle(JNIEnv* env);
 extern int register_android_view_InputWindowHandle(JNIEnv* env);
-extern int register_android_view_TextureLayer(JNIEnv* env);
-extern int register_android_view_RenderNode(JNIEnv* env);
 extern int register_android_view_RenderNodeAnimator(JNIEnv* env);
 extern int register_android_view_Surface(JNIEnv* env);
 extern int register_android_view_SurfaceControl(JNIEnv* env);
 extern int register_android_view_SurfaceSession(JNIEnv* env);
 extern int register_android_view_CompositionSamplingListener(JNIEnv* env);
 extern int register_android_view_TextureView(JNIEnv* env);
-extern int register_android_view_ThreadedRenderer(JNIEnv* env);
 extern int register_com_android_internal_view_animation_NativeInterpolatorFactoryHelper(JNIEnv *env);
 extern int register_android_database_CursorWindow(JNIEnv* env);
 extern int register_android_database_SQLiteConnection(JNIEnv* env);
@@ -314,7 +268,7 @@
         mArgBlockStart(argBlockStart),
         mArgBlockLength(argBlockLength)
 {
-    SkGraphics::Init();
+    init_android_graphics();
 
     // Pre-allocate enough space to hold a fair number of options.
     mOptions.setCapacity(20);
@@ -696,26 +650,32 @@
     // Read if we are using the profile configuration, do this at the start since the last ART args
     // take precedence.
     property_get("dalvik.vm.profilebootclasspath", propBuf, "");
-    std::string profile_boot_class_path = propBuf;
+    std::string profile_boot_class_path_flag = propBuf;
     // Empty means the property is unset and we should default to the phenotype property.
     // The possible values are {"true", "false", ""}
-    if (profile_boot_class_path.empty()) {
-        profile_boot_class_path = server_configurable_flags::GetServerConfigurableFlag(
+    if (profile_boot_class_path_flag.empty()) {
+        profile_boot_class_path_flag = server_configurable_flags::GetServerConfigurableFlag(
                 RUNTIME_NATIVE_BOOT_NAMESPACE,
                 PROFILE_BOOT_CLASS_PATH,
                 /*default_value=*/ "");
     }
-    if (profile_boot_class_path == "true") {
+    const bool profile_boot_class_path = (profile_boot_class_path_flag == "true");
+    if (profile_boot_class_path) {
+        addOption("-Xcompiler-option");
+        addOption("--count-hotness-in-compiled-code");
         addOption("-Xps-profile-boot-class-path");
         addOption("-Xps-profile-aot-code");
         addOption("-Xjitsaveprofilinginfo");
     }
 
-    std::string use_apex_image =
+    std::string use_apex_image_flag =
         server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
                                                              ENABLE_APEX_IMAGE,
                                                              /*default_value=*/ "");
-    if (use_apex_image == "true") {
+    // Use the APEX boot image for boot class path profiling to get JIT samples on BCP methods.
+    // Also use the APEX boot image if it's explicitly enabled via configuration flag.
+    const bool use_apex_image = profile_boot_class_path || (use_apex_image_flag == "true");
+    if (use_apex_image) {
         addOption(kApexImageOption);
         ALOGI("Using Apex boot image: '%s'\n", kApexImageOption);
     } else if (parseRuntimeOption("dalvik.vm.boot-image", bootImageBuf, "-Ximage:")) {
@@ -1163,9 +1123,15 @@
         setenv("ANDROID_ROOT", rootDir, 1);
     }
 
-    const char* runtimeRootDir = getenv("ANDROID_RUNTIME_ROOT");
-    if (runtimeRootDir == NULL) {
-        LOG_FATAL("No runtime directory specified with ANDROID_RUNTIME_ROOT environment variable.");
+    const char* artRootDir = getenv("ANDROID_ART_ROOT");
+    if (artRootDir == NULL) {
+        LOG_FATAL("No ART directory specified with ANDROID_ART_ROOT environment variable.");
+        return;
+    }
+
+    const char* i18nRootDir = getenv("ANDROID_I18N_ROOT");
+    if (i18nRootDir == NULL) {
+        LOG_FATAL("No runtime directory specified with ANDROID_I18N_ROOT environment variable.");
         return;
     }
 
@@ -1445,7 +1411,6 @@
     REG_JNI(register_android_util_EventLog),
     REG_JNI(register_android_util_Log),
     REG_JNI(register_android_util_MemoryIntArray),
-    REG_JNI(register_android_util_PathParser),
     REG_JNI(register_android_util_StatsLog),
     REG_JNI(register_android_util_StatsLogInternal),
     REG_JNI(register_android_app_admin_SecurityLog),
@@ -1469,20 +1434,10 @@
     REG_JNI(register_android_os_NativeHandle),
     REG_JNI(register_android_os_VintfObject),
     REG_JNI(register_android_os_VintfRuntimeInfo),
-    REG_JNI(register_android_graphics_Canvas),
-    // This needs to be before register_android_graphics_Graphics, or the latter
-    // will not be able to find the jmethodID for ColorSpace.get().
-    REG_JNI(register_android_graphics_ColorSpace),
-    REG_JNI(register_android_graphics_Graphics),
     REG_JNI(register_android_view_DisplayEventReceiver),
-    REG_JNI(register_android_view_RenderNode),
     REG_JNI(register_android_view_RenderNodeAnimator),
-    REG_JNI(register_android_view_DisplayListCanvas),
-    REG_JNI(register_android_view_FrameMetricsObserver),
     REG_JNI(register_android_view_InputApplicationHandle),
     REG_JNI(register_android_view_InputWindowHandle),
-    REG_JNI(register_android_view_TextureLayer),
-    REG_JNI(register_android_view_ThreadedRenderer),
     REG_JNI(register_android_view_Surface),
     REG_JNI(register_android_view_SurfaceControl),
     REG_JNI(register_android_view_SurfaceSession),
@@ -1504,43 +1459,8 @@
     REG_JNI(register_android_opengl_jni_GLES31Ext),
     REG_JNI(register_android_opengl_jni_GLES32),
 
-    REG_JNI(register_android_graphics_Bitmap),
-    REG_JNI(register_android_graphics_BitmapFactory),
-    REG_JNI(register_android_graphics_BitmapRegionDecoder),
-    REG_JNI(register_android_graphics_ByteBufferStreamAdaptor),
-    REG_JNI(register_android_graphics_Camera),
-    REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
-    REG_JNI(register_android_graphics_CanvasProperty),
-    REG_JNI(register_android_graphics_ColorFilter),
-    REG_JNI(register_android_graphics_DrawFilter),
-    REG_JNI(register_android_graphics_FontFamily),
+    REG_JNI(register_android_graphics_classes),
     REG_JNI(register_android_graphics_GraphicBuffer),
-    REG_JNI(register_android_graphics_ImageDecoder),
-    REG_JNI(register_android_graphics_drawable_AnimatedImageDrawable),
-    REG_JNI(register_android_graphics_Interpolator),
-    REG_JNI(register_android_graphics_MaskFilter),
-    REG_JNI(register_android_graphics_Matrix),
-    REG_JNI(register_android_graphics_Movie),
-    REG_JNI(register_android_graphics_NinePatch),
-    REG_JNI(register_android_graphics_Paint),
-    REG_JNI(register_android_graphics_Path),
-    REG_JNI(register_android_graphics_PathMeasure),
-    REG_JNI(register_android_graphics_PathEffect),
-    REG_JNI(register_android_graphics_Picture),
-    REG_JNI(register_android_graphics_Region),
-    REG_JNI(register_android_graphics_Shader),
-    REG_JNI(register_android_graphics_SurfaceTexture),
-    REG_JNI(register_android_graphics_Typeface),
-    REG_JNI(register_android_graphics_YuvImage),
-    REG_JNI(register_android_graphics_drawable_AnimatedVectorDrawable),
-    REG_JNI(register_android_graphics_drawable_VectorDrawable),
-    REG_JNI(register_android_graphics_fonts_Font),
-    REG_JNI(register_android_graphics_fonts_FontFamily),
-    REG_JNI(register_android_graphics_pdf_PdfDocument),
-    REG_JNI(register_android_graphics_pdf_PdfEditor),
-    REG_JNI(register_android_graphics_pdf_PdfRenderer),
-    REG_JNI(register_android_graphics_text_MeasuredText),
-    REG_JNI(register_android_graphics_text_LineBreaker),
 
     REG_JNI(register_android_database_CursorWindow),
     REG_JNI(register_android_database_SQLiteConnection),
diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp
index 18a1b43..89c12f8 100755
--- a/core/jni/android/graphics/Bitmap.cpp
+++ b/core/jni/android/graphics/Bitmap.cpp
@@ -265,6 +265,20 @@
             info->format = ANDROID_BITMAP_FORMAT_NONE;
             break;
     }
+    switch (imageInfo.alphaType()) {
+        case kUnknown_SkAlphaType:
+            LOG_ALWAYS_FATAL("Bitmap has no alpha type");
+            break;
+        case kOpaque_SkAlphaType:
+            info->flags |= ANDROID_BITMAP_FLAGS_ALPHA_OPAQUE;
+            break;
+        case kPremul_SkAlphaType:
+            info->flags |= ANDROID_BITMAP_FLAGS_ALPHA_PREMUL;
+            break;
+        case kUnpremul_SkAlphaType:
+            info->flags |= ANDROID_BITMAP_FLAGS_ALPHA_UNPREMUL;
+            break;
+    }
 }
 
 void* lockPixels(JNIEnv* env, jobject bitmap) {
diff --git a/core/jni/android/graphics/Bitmap.h b/core/jni/android/graphics/Bitmap.h
index 06e31a1..59adbb2 100644
--- a/core/jni/android/graphics/Bitmap.h
+++ b/core/jni/android/graphics/Bitmap.h
@@ -39,8 +39,6 @@
             jobject ninePatchInsets = nullptr, int density = -1);
 
 
-void toSkBitmap(jlong bitmapHandle, SkBitmap* outBitmap);
-
 Bitmap& toBitmap(JNIEnv* env, jobject bitmap);
 Bitmap& toBitmap(jlong bitmapHandle);
 
diff --git a/core/jni/android/graphics/ByteBufferStreamAdaptor.cpp b/core/jni/android/graphics/ByteBufferStreamAdaptor.cpp
index 173818b..d443fd8 100644
--- a/core/jni/android/graphics/ByteBufferStreamAdaptor.cpp
+++ b/core/jni/android/graphics/ByteBufferStreamAdaptor.cpp
@@ -1,6 +1,7 @@
 #include "ByteBufferStreamAdaptor.h"
 #include "core_jni_helpers.h"
 #include "Utils.h"
+#include <jni.h>
 
 #include <SkStream.h>
 
@@ -9,6 +10,24 @@
 static jmethodID gByteBuffer_getMethodID;
 static jmethodID gByteBuffer_setPositionMethodID;
 
+/**
+ * Helper method for accessing the JNI interface pointer.
+ *
+ * Image decoding (which this supports) is started on a thread that is already
+ * attached to the Java VM. But an AnimatedImageDrawable continues decoding on
+ * the AnimatedImageThread, which is not attached. This will attach if
+ * necessary.
+ */
+static JNIEnv* requireEnv(JavaVM* jvm) {
+    JNIEnv* env;
+    if (jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+        if (jvm->AttachCurrentThreadAsDaemon(&env, nullptr) != JNI_OK) {
+            LOG_ALWAYS_FATAL("Failed to AttachCurrentThread!");
+        }
+    }
+    return env;
+}
+
 class ByteBufferStream : public SkStreamAsset {
 private:
     ByteBufferStream(JavaVM* jvm, jobject jbyteBuffer, size_t initialPosition, size_t length,
@@ -46,7 +65,7 @@
     }
 
     ~ByteBufferStream() override {
-        auto* env = get_env_or_die(mJvm);
+        auto* env = requireEnv(mJvm);
         env->DeleteGlobalRef(mByteBuffer);
         env->DeleteGlobalRef(mStorage);
     }
@@ -63,7 +82,7 @@
             return this->setPosition(mPosition + size) ? size : 0;
         }
 
-        auto* env = get_env_or_die(mJvm);
+        auto* env = requireEnv(mJvm);
         size_t bytesRead = 0;
         do {
             const size_t requested = (size > kStorageSize) ? kStorageSize : size;
@@ -146,7 +165,7 @@
 
     // Range has already been checked by the caller.
     bool setPosition(size_t newPosition) {
-        auto* env = get_env_or_die(mJvm);
+        auto* env = requireEnv(mJvm);
         env->CallObjectMethod(mByteBuffer, gByteBuffer_setPositionMethodID,
                               newPosition + mInitialPosition);
         if (env->ExceptionCheck()) {
@@ -185,7 +204,7 @@
     }
 
     ~ByteArrayStream() override {
-        auto* env = get_env_or_die(mJvm);
+        auto* env = requireEnv(mJvm);
         env->DeleteGlobalRef(mByteArray);
     }
 
@@ -197,7 +216,7 @@
             return 0;
         }
 
-        auto* env = get_env_or_die(mJvm);
+        auto* env = requireEnv(mJvm);
         if (buffer) {
             env->GetByteArrayRegion(mByteArray, mPosition + mOffset, size,
                                     reinterpret_cast<jbyte*>(buffer));
diff --git a/core/jni/android/graphics/apex/TypeCast.h b/core/jni/android/graphics/apex/TypeCast.h
new file mode 100644
index 0000000..96721d0
--- /dev/null
+++ b/core/jni/android/graphics/apex/TypeCast.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_GRAPHICS_TYPECAST_H
+#define ANDROID_GRAPHICS_TYPECAST_H
+
+struct ABitmap;
+struct ACanvas;
+struct APaint;
+
+namespace android {
+
+    class Bitmap;
+    class Canvas;
+    class Paint;
+
+    class TypeCast {
+    public:
+        static inline Bitmap& toBitmapRef(const ABitmap* bitmap) {
+            return const_cast<Bitmap&>(reinterpret_cast<const Bitmap&>(*bitmap));
+        }
+
+        static inline Bitmap* toBitmap(ABitmap* bitmap) {
+            return reinterpret_cast<Bitmap*>(bitmap);
+        }
+
+        static inline ABitmap* toABitmap(Bitmap* bitmap) {
+            return reinterpret_cast<ABitmap*>(bitmap);
+        }
+
+        static inline Canvas* toCanvas(ACanvas* canvas) {
+            return reinterpret_cast<Canvas*>(canvas);
+        }
+
+        static inline ACanvas* toACanvas(Canvas* canvas) {
+            return reinterpret_cast<ACanvas *>(canvas);
+        }
+
+        static inline const Paint& toPaintRef(const APaint* paint) {
+            return reinterpret_cast<const Paint&>(*paint);
+        }
+
+        static inline const Paint* toPaint(const APaint* paint) {
+            return reinterpret_cast<const Paint*>(paint);
+        }
+
+        static inline Paint* toPaint(APaint* paint) {
+            return reinterpret_cast<Paint*>(paint);
+        }
+
+        static inline APaint* toAPaint(Paint* paint) {
+            return reinterpret_cast<APaint*>(paint);
+        }
+    };
+}; // namespace android
+
+#endif // ANDROID_GRAPHICS_TYPECAST_H
diff --git a/core/jni/android/graphics/apex/android_bitmap.cpp b/core/jni/android/graphics/apex/android_bitmap.cpp
new file mode 100644
index 0000000..96cc5db
--- /dev/null
+++ b/core/jni/android/graphics/apex/android_bitmap.cpp
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "android/graphics/bitmap.h"
+#include "Bitmap.h"
+#include "TypeCast.h"
+
+#include <hwui/Bitmap.h>
+
+using namespace android;
+
+ABitmap* ABitmap_acquireBitmapFromJava(JNIEnv* env, jobject bitmapObj) {
+    Bitmap& bitmap = android::bitmap::toBitmap(env, bitmapObj);
+    bitmap.ref();
+    return TypeCast::toABitmap(&bitmap);
+}
+
+void ABitmap_acquireRef(ABitmap* bitmap) {
+    SkSafeRef(TypeCast::toBitmap(bitmap));
+}
+
+void ABitmap_releaseRef(ABitmap* bitmap) {
+    SkSafeUnref(TypeCast::toBitmap(bitmap));
+}
+
+static AndroidBitmapFormat getFormat(Bitmap* bitmap) {
+    switch (bitmap->colorType()) {
+        case kN32_SkColorType:
+            return ANDROID_BITMAP_FORMAT_RGBA_8888;
+        case kRGB_565_SkColorType:
+            return ANDROID_BITMAP_FORMAT_RGB_565;
+        case kARGB_4444_SkColorType:
+            return ANDROID_BITMAP_FORMAT_RGBA_4444;
+        case kAlpha_8_SkColorType:
+            return ANDROID_BITMAP_FORMAT_A_8;
+        case kRGBA_F16_SkColorType:
+            return ANDROID_BITMAP_FORMAT_RGBA_F16;
+        default:
+            return ANDROID_BITMAP_FORMAT_NONE;
+    }
+}
+
+static SkColorType getColorType(AndroidBitmapFormat format) {
+    switch (format) {
+        case ANDROID_BITMAP_FORMAT_RGBA_8888:
+            return kN32_SkColorType;
+        case ANDROID_BITMAP_FORMAT_RGB_565:
+            return kRGB_565_SkColorType;
+        case ANDROID_BITMAP_FORMAT_RGBA_4444:
+            return kARGB_4444_SkColorType;
+        case ANDROID_BITMAP_FORMAT_A_8:
+            return kAlpha_8_SkColorType;
+        case ANDROID_BITMAP_FORMAT_RGBA_F16:
+            return kRGBA_F16_SkColorType;
+        default:
+            return kUnknown_SkColorType;
+    }
+}
+
+ABitmap* ABitmap_copy(ABitmap* srcBitmapHandle, AndroidBitmapFormat dstFormat) {
+    SkColorType dstColorType = getColorType(dstFormat);
+    if (srcBitmapHandle && dstColorType != kUnknown_SkColorType) {
+        SkBitmap srcBitmap;
+        TypeCast::toBitmap(srcBitmapHandle)->getSkBitmap(&srcBitmap);
+
+        sk_sp<Bitmap> dstBitmap =
+                Bitmap::allocateHeapBitmap(srcBitmap.info().makeColorType(dstColorType));
+        if (dstBitmap && srcBitmap.readPixels(dstBitmap->info(), dstBitmap->pixels(),
+                                              dstBitmap->rowBytes(), 0, 0)) {
+            return TypeCast::toABitmap(dstBitmap.release());
+        }
+    }
+    return nullptr;
+}
+
+AndroidBitmapInfo ABitmap_getInfo(ABitmap* bitmapHandle) {
+    Bitmap* bitmap = TypeCast::toBitmap(bitmapHandle);
+
+    AndroidBitmapInfo info;
+    info.width = bitmap->width();
+    info.height = bitmap->height();
+    info.stride = bitmap->rowBytes();
+    info.format = getFormat(bitmap);
+    return info;
+}
+
+void* ABitmap_getPixels(ABitmap* bitmapHandle) {
+    Bitmap* bitmap = TypeCast::toBitmap(bitmapHandle);
+    if (bitmap->isHardware()) {
+        return nullptr;
+    }
+    return bitmap->pixels();
+}
diff --git a/core/jni/android/graphics/apex/android_canvas.cpp b/core/jni/android/graphics/apex/android_canvas.cpp
index 7a4495f..527a745 100644
--- a/core/jni/android/graphics/apex/android_canvas.cpp
+++ b/core/jni/android/graphics/apex/android_canvas.cpp
@@ -16,6 +16,7 @@
 
 #include "android/graphics/canvas.h"
 
+#include "TypeCast.h"
 #include "GraphicsJNI.h"
 
 #include <hwui/Canvas.h>
@@ -25,14 +26,6 @@
 
 using namespace android;
 
-static inline Canvas* toCanvas(ACanvas* aCanvas) {
-    return reinterpret_cast<Canvas*>(aCanvas);
-}
-
-static inline ACanvas* toACanvas(Canvas* canvas) {
-    return reinterpret_cast<ACanvas*>(canvas);
-}
-
 bool ACanvas_isSupportedPixelFormat(int32_t bufferFormat) {
     ANativeWindow_Buffer buffer { 0, 0, 0, bufferFormat, nullptr, {0} };
     const SkColorType colorType = uirenderer::ANativeWindowToImageInfo(buffer, nullptr).colorType();
@@ -40,11 +33,11 @@
 }
 
 ACanvas* ACanvas_getNativeHandleFromJava(JNIEnv* env, jobject canvasObj) {
-    return toACanvas(GraphicsJNI::getNativeCanvas(env, canvasObj));
+    return TypeCast::toACanvas(GraphicsJNI::getNativeCanvas(env, canvasObj));
 }
 
-void ACanvas_setBuffer(ACanvas* canvas, const ANativeWindow_Buffer* buffer,
-                       int32_t /*android_dataspace_t*/ dataspace) {
+static SkBitmap convert(const ANativeWindow_Buffer* buffer,
+                        int32_t /*android_dataspace_t*/ dataspace) {
     SkBitmap bitmap;
     if (buffer != nullptr && buffer->width > 0 && buffer->height > 0) {
         sk_sp<SkColorSpace> cs(uirenderer::DataSpaceToColorSpace((android_dataspace)dataspace));
@@ -53,18 +46,44 @@
         bitmap.setInfo(imageInfo, rowBytes);
         bitmap.setPixels(buffer->bits);
     }
-
-    toCanvas(canvas)->setBitmap(bitmap);
+    return bitmap;
 }
 
-void ACanvas_clipRect(ACanvas* canvas, const ARect& clipRect, bool /*doAA*/) {
-    //TODO update Canvas to take antialias param
-    toCanvas(canvas)->clipRect(clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
-                               SkClipOp::kIntersect);
+ACanvas* ACanvas_createCanvas(const ANativeWindow_Buffer* buffer,
+                              int32_t /*android_dataspace_t*/ dataspace) {
+    return TypeCast::toACanvas(Canvas::create_canvas(convert(buffer, dataspace)));
 }
 
-void ACanvas_clipOutRect(ACanvas* canvas, const ARect& clipRect, bool /*doAA*/) {
+void ACanvas_destroyCanvas(ACanvas* canvas) {
+    delete TypeCast::toCanvas(canvas);
+}
+
+void ACanvas_setBuffer(ACanvas* canvas, const ANativeWindow_Buffer* buffer,
+                       int32_t /*android_dataspace_t*/ dataspace) {
+
+
+    TypeCast::toCanvas(canvas)->setBitmap(convert(buffer, dataspace));
+}
+
+void ACanvas_clipRect(ACanvas* canvas, const ARect* clipRect, bool /*doAA*/) {
     //TODO update Canvas to take antialias param
-    toCanvas(canvas)->clipRect(clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
-                               SkClipOp::kDifference);
+    TypeCast::toCanvas(canvas)->clipRect(clipRect->left, clipRect->top, clipRect->right,
+                                         clipRect->bottom, SkClipOp::kIntersect);
+}
+
+void ACanvas_clipOutRect(ACanvas* canvas, const ARect* clipRect, bool /*doAA*/) {
+    //TODO update Canvas to take antialias param
+    TypeCast::toCanvas(canvas)->clipRect(clipRect->left, clipRect->top, clipRect->right,
+                                         clipRect->bottom, SkClipOp::kDifference);
+}
+
+void ACanvas_drawRect(ACanvas* canvas, const ARect* rect, const APaint* paint) {
+    TypeCast::toCanvas(canvas)->drawRect(rect->left, rect->top, rect->right, rect->bottom,
+                                         TypeCast::toPaintRef(paint));
+}
+
+void ACanvas_drawBitmap(ACanvas* canvas, const ABitmap* bitmap, float left, float top,
+                        const APaint* paint) {
+    TypeCast::toCanvas(canvas)->drawBitmap(TypeCast::toBitmapRef(bitmap), left, top,
+                                           TypeCast::toPaint(paint));
 }
diff --git a/core/jni/android/graphics/apex/android_paint.cpp b/core/jni/android/graphics/apex/android_paint.cpp
new file mode 100644
index 0000000..70bd085
--- /dev/null
+++ b/core/jni/android/graphics/apex/android_paint.cpp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "android/graphics/paint.h"
+
+#include "TypeCast.h"
+
+#include <hwui/Paint.h>
+
+using namespace android;
+
+
+APaint* APaint_createPaint() {
+    return TypeCast::toAPaint(new Paint());
+}
+
+void APaint_destroyPaint(APaint* paint) {
+    delete TypeCast::toPaint(paint);
+}
+
+static SkBlendMode convertBlendMode(ABlendMode blendMode) {
+    switch (blendMode) {
+        case ABLEND_MODE_CLEAR:
+            return SkBlendMode::kClear;
+        case ABLEND_MODE_SRC_OVER:
+            return SkBlendMode::kSrcOver;
+        case ABLEND_MODE_SRC:
+            return SkBlendMode::kSrc;
+    }
+}
+
+void APaint_setBlendMode(APaint* paint, ABlendMode blendMode) {
+    TypeCast::toPaint(paint)->setBlendMode(convertBlendMode(blendMode));
+}
diff --git a/core/jni/android/graphics/apex/include/android/graphics/bitmap.h b/core/jni/android/graphics/apex/include/android/graphics/bitmap.h
new file mode 100644
index 0000000..bfa4c8d
--- /dev/null
+++ b/core/jni/android/graphics/apex/include/android/graphics/bitmap.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+#ifndef ANDROID_GRAPHICS_BITMAP_H
+#define ANDROID_GRAPHICS_BITMAP_H
+
+#include <android/bitmap.h>
+#include <jni.h>
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+
+/**
+ * Opaque handle for a native graphics bitmap.
+ */
+typedef struct ABitmap ABitmap;
+
+ABitmap* ABitmap_acquireBitmapFromJava(JNIEnv* env, jobject bitmapObj);
+
+ABitmap* ABitmap_copy(ABitmap* srcBitmap, AndroidBitmapFormat dstFormat);
+
+void ABitmap_acquireRef(ABitmap* bitmap);
+void ABitmap_releaseRef(ABitmap* bitmap);
+
+AndroidBitmapInfo ABitmap_getInfo(ABitmap* bitmap);
+
+void* ABitmap_getPixels(ABitmap* bitmap);
+
+__END_DECLS
+
+#ifdef	__cplusplus
+namespace android {
+namespace graphics {
+    class Bitmap {
+    public:
+        Bitmap() : mBitmap(nullptr) {}
+        Bitmap(JNIEnv* env, jobject bitmapObj) :
+                mBitmap(ABitmap_acquireBitmapFromJava(env, bitmapObj)) {}
+        Bitmap(const Bitmap& src) : mBitmap(src.mBitmap) { ABitmap_acquireRef(src.mBitmap); }
+        ~Bitmap() { ABitmap_releaseRef(mBitmap); }
+
+        // copy operator
+        Bitmap& operator=(const Bitmap& other) {
+            if (&other != this) {
+                ABitmap_releaseRef(mBitmap);
+                mBitmap = other.mBitmap;
+                ABitmap_acquireRef(mBitmap);
+            }
+            return *this;
+        }
+
+        // move operator
+        Bitmap& operator=(Bitmap&& other) {
+            if (&other != this) {
+                ABitmap_releaseRef(mBitmap);
+                mBitmap = other.mBitmap;
+                other.mBitmap = nullptr;
+            }
+            return *this;
+        }
+
+        Bitmap copy(AndroidBitmapFormat dstFormat) const {
+            return Bitmap(ABitmap_copy(mBitmap, dstFormat));
+        }
+
+        bool isValid() const { return mBitmap != nullptr; }
+        bool isEmpty() const {
+            AndroidBitmapInfo info = getInfo();
+            return info.width <= 0 || info.height <= 0;
+        }
+        void reset() {
+            ABitmap_releaseRef(mBitmap);
+            mBitmap = nullptr;
+        }
+
+        const ABitmap* get() const { return mBitmap; }
+
+        AndroidBitmapInfo getInfo() const { return ABitmap_getInfo(mBitmap); }
+        void* getPixels() const { return ABitmap_getPixels(mBitmap); }
+    private:
+        // takes ownership of the provided ABitmap
+        Bitmap(ABitmap* bitmap) : mBitmap(bitmap) {}
+
+        ABitmap* mBitmap;
+    };
+}; // namespace graphics
+}; // namespace android
+#endif // __cplusplus
+
+#endif // ANDROID_GRAPHICS_BITMAP_H
\ No newline at end of file
diff --git a/core/jni/android/graphics/apex/include/android/graphics/canvas.h b/core/jni/android/graphics/apex/include/android/graphics/canvas.h
index c35a7d6..190aba4 100644
--- a/core/jni/android/graphics/apex/include/android/graphics/canvas.h
+++ b/core/jni/android/graphics/apex/include/android/graphics/canvas.h
@@ -16,6 +16,8 @@
 #ifndef ANDROID_GRAPHICS_CANVAS_H
 #define ANDROID_GRAPHICS_CANVAS_H
 
+#include <android/graphics/bitmap.h>
+#include <android/graphics/paint.h>
 #include <android/native_window.h>
 #include <android/rect.h>
 #include <jni.h>
@@ -23,8 +25,8 @@
 __BEGIN_DECLS
 
 /**
-* Opaque handle for a native graphics canvas.
-*/
+ * Opaque handle for a native graphics canvas.
+ */
 typedef struct ACanvas ACanvas;
 
 //  One of AHardwareBuffer_Format.
@@ -33,34 +35,104 @@
 /**
  * Returns a native handle to a Java android.graphics.Canvas
  *
- * @param env
- * @param canvas
  * @return ACanvas* that is only valid for the life of the jobject.
  */
 ACanvas* ACanvas_getNativeHandleFromJava(JNIEnv* env, jobject canvas);
 
 /**
+ * Creates a canvas that wraps the buffer
+ *
+ * @param buffer required
+ */
+ACanvas* ACanvas_createCanvas(const ANativeWindow_Buffer* buffer,
+                              int32_t /*android_dataspace_t*/ dataspace);
+
+void ACanvas_destroyCanvas(ACanvas* canvas);
+
+/**
  * Updates the canvas to render into the pixels in the provided buffer
  *
- * @param canvas
  * @param buffer The buffer that will provide the backing store for this canvas.  The buffer must
  *               remain valid until the this method is called again with either another active
  *               buffer or nullptr.  If nullptr is given the canvas will release the previous buffer
  *               and set an empty backing store.
- * @param dataspace
  */
 void ACanvas_setBuffer(ACanvas* canvas, const ANativeWindow_Buffer* buffer,
                        int32_t /*android_dataspace_t*/ dataspace);
 
 /**
  * Clips operations on the canvas to the intersection of the current clip and the provided clipRect.
+ *
+ * @param clipRect required
  */
-void ACanvas_clipRect(ACanvas* canvas, const ARect& clipRect, bool doAntiAlias = false);
+void ACanvas_clipRect(ACanvas* canvas, const ARect* clipRect, bool doAntiAlias = false);
 
 /**
  * Clips operations on the canvas to the difference of the current clip and the provided clipRect.
+ *
+ * @param clipRect required
  */
-void ACanvas_clipOutRect(ACanvas* canvas, const ARect& clipRect, bool doAntiAlias = false);
+void ACanvas_clipOutRect(ACanvas* canvas, const ARect* clipRect, bool doAntiAlias = false);
+
+/**
+ *
+ * @param rect required
+ * @param paint required
+ */
+void ACanvas_drawRect(ACanvas* canvas, const ARect* rect, const APaint* paint);
+
+/**
+ *
+ * @param bitmap required
+ * @param left
+ * @param top
+ * @param paint
+ */
+void ACanvas_drawBitmap(ACanvas* canvas, const ABitmap* bitmap, float left, float top,
+                        const APaint* paint);
 
 __END_DECLS
+
+#ifdef	__cplusplus
+namespace android {
+namespace graphics {
+    class Canvas {
+    public:
+        Canvas(JNIEnv* env, jobject canvasObj) :
+                mCanvas(ACanvas_getNativeHandleFromJava(env, canvasObj)),
+                mOwnedPtr(false) {}
+        Canvas(const ANativeWindow_Buffer& buffer, int32_t /*android_dataspace_t*/ dataspace) :
+                mCanvas(ACanvas_createCanvas(&buffer, dataspace)),
+                mOwnedPtr(true) {}
+        ~Canvas() {
+            if (mOwnedPtr) {
+                ACanvas_destroyCanvas(mCanvas);
+            }
+        }
+
+        void setBuffer(const ANativeWindow_Buffer* buffer,
+                       int32_t /*android_dataspace_t*/ dataspace) {
+            ACanvas_setBuffer(mCanvas, buffer, dataspace);
+        }
+
+        void clipRect(const ARect& clipRect, bool doAntiAlias = false) {
+            ACanvas_clipRect(mCanvas, &clipRect, doAntiAlias);
+        }
+
+        void drawRect(const ARect& rect, const Paint& paint) {
+            ACanvas_drawRect(mCanvas, &rect, &paint.get());
+        }
+        void drawBitmap(const Bitmap& bitmap, float left, float top, const Paint* paint) {
+            const APaint* aPaint = (paint) ? &paint->get() : nullptr;
+            ACanvas_drawBitmap(mCanvas, bitmap.get(), left, top, aPaint);
+        }
+
+    private:
+        ACanvas* mCanvas;
+        const bool mOwnedPtr;
+    };
+}; // namespace graphics
+}; // namespace android
+#endif // __cplusplus
+
 #endif // ANDROID_GRAPHICS_CANVAS_H
\ No newline at end of file
diff --git a/core/jni/android/graphics/apex/include/android/graphics/jni_runtime.h b/core/jni/android/graphics/apex/include/android/graphics/jni_runtime.h
new file mode 100644
index 0000000..872a949
--- /dev/null
+++ b/core/jni/android/graphics/apex/include/android/graphics/jni_runtime.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+#ifndef ANDROID_GRAPHICS_JNI_RUNTIME_H
+#define ANDROID_GRAPHICS_JNI_RUNTIME_H
+
+#include <jni.h>
+
+__BEGIN_DECLS
+
+void init_android_graphics();
+
+int register_android_graphics_classes(JNIEnv* env);
+
+void zygote_preload_graphics();
+
+__END_DECLS
+
+
+#endif // ANDROID_GRAPHICS_JNI_RUNTIME_H
\ No newline at end of file
diff --git a/core/jni/android/graphics/apex/include/android/graphics/paint.h b/core/jni/android/graphics/apex/include/android/graphics/paint.h
new file mode 100644
index 0000000..5895e00
--- /dev/null
+++ b/core/jni/android/graphics/apex/include/android/graphics/paint.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+#ifndef ANDROID_GRAPHICS_PAINT_H
+#define ANDROID_GRAPHICS_PAINT_H
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+
+/**
+ * Opaque handle for a native graphics canvas.
+ */
+typedef struct APaint APaint;
+
+/** Bitmap pixel format. */
+enum ABlendMode {
+    /** replaces destination with zero: fully transparent */
+    ABLEND_MODE_CLEAR    = 0,
+    /** source over destination */
+    ABLEND_MODE_SRC_OVER = 1,
+    /** replaces destination **/
+    ABLEND_MODE_SRC      = 2,
+};
+
+APaint* APaint_createPaint();
+
+void APaint_destroyPaint(APaint* paint);
+
+void APaint_setBlendMode(APaint* paint, ABlendMode blendMode);
+
+__END_DECLS
+
+#ifdef	__cplusplus
+namespace android {
+namespace graphics {
+    class Paint {
+    public:
+        Paint() : mPaint(APaint_createPaint()) {}
+        ~Paint() { APaint_destroyPaint(mPaint); }
+
+        void setBlendMode(ABlendMode blendMode) { APaint_setBlendMode(mPaint, blendMode); }
+
+        const APaint& get() const { return *mPaint; }
+
+    private:
+        APaint* mPaint;
+    };
+}; // namespace graphics
+}; // namespace android
+#endif // __cplusplus
+
+
+#endif // ANDROID_GRAPHICS_PAINT_H
\ No newline at end of file
diff --git a/core/jni/android/graphics/apex/jni_runtime.cpp b/core/jni/android/graphics/apex/jni_runtime.cpp
new file mode 100644
index 0000000..7f9bac0
--- /dev/null
+++ b/core/jni/android/graphics/apex/jni_runtime.cpp
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "android/graphics/jni_runtime.h"
+
+#include <android/log.h>
+#include <nativehelper/JNIHelp.h>
+#include <sys/cdefs.h>
+
+#include <EGL/egl.h>
+#include <Properties.h>
+#include <SkGraphics.h>
+
+#define LOG_TAG "AndroidGraphicsJNI"
+
+extern int register_android_graphics_Bitmap(JNIEnv*);
+extern int register_android_graphics_BitmapFactory(JNIEnv*);
+extern int register_android_graphics_BitmapRegionDecoder(JNIEnv*);
+extern int register_android_graphics_ByteBufferStreamAdaptor(JNIEnv* env);
+extern int register_android_graphics_Camera(JNIEnv* env);
+extern int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env);
+extern int register_android_graphics_Graphics(JNIEnv* env);
+extern int register_android_graphics_ImageDecoder(JNIEnv*);
+extern int register_android_graphics_drawable_AnimatedImageDrawable(JNIEnv*);
+extern int register_android_graphics_Interpolator(JNIEnv* env);
+extern int register_android_graphics_MaskFilter(JNIEnv* env);
+extern int register_android_graphics_Movie(JNIEnv* env);
+extern int register_android_graphics_NinePatch(JNIEnv*);
+extern int register_android_graphics_PathEffect(JNIEnv* env);
+extern int register_android_graphics_Shader(JNIEnv* env);
+extern int register_android_graphics_Typeface(JNIEnv* env);
+extern int register_android_graphics_YuvImage(JNIEnv* env);
+
+namespace android {
+
+extern int register_android_graphics_Canvas(JNIEnv* env);
+extern int register_android_graphics_CanvasProperty(JNIEnv* env);
+extern int register_android_graphics_ColorFilter(JNIEnv* env);
+extern int register_android_graphics_ColorSpace(JNIEnv* env);
+extern int register_android_graphics_DrawFilter(JNIEnv* env);
+extern int register_android_graphics_FontFamily(JNIEnv* env);
+extern int register_android_graphics_Matrix(JNIEnv* env);
+extern int register_android_graphics_Paint(JNIEnv* env);
+extern int register_android_graphics_Path(JNIEnv* env);
+extern int register_android_graphics_PathMeasure(JNIEnv* env);
+extern int register_android_graphics_Picture(JNIEnv*);
+extern int register_android_graphics_Region(JNIEnv* env);
+extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
+extern int register_android_graphics_drawable_AnimatedVectorDrawable(JNIEnv* env);
+extern int register_android_graphics_drawable_VectorDrawable(JNIEnv* env);
+extern int register_android_graphics_fonts_Font(JNIEnv* env);
+extern int register_android_graphics_fonts_FontFamily(JNIEnv* env);
+extern int register_android_graphics_pdf_PdfDocument(JNIEnv* env);
+extern int register_android_graphics_pdf_PdfEditor(JNIEnv* env);
+extern int register_android_graphics_pdf_PdfRenderer(JNIEnv* env);
+extern int register_android_graphics_text_MeasuredText(JNIEnv* env);
+extern int register_android_graphics_text_LineBreaker(JNIEnv *env);
+
+extern int register_android_util_PathParser(JNIEnv* env);
+extern int register_android_view_DisplayListCanvas(JNIEnv* env);
+extern int register_android_view_FrameMetricsObserver(JNIEnv* env);
+extern int register_android_view_RenderNode(JNIEnv* env);
+extern int register_android_view_TextureLayer(JNIEnv* env);
+extern int register_android_view_ThreadedRenderer(JNIEnv* env);
+
+#ifdef NDEBUG
+    #define REG_JNI(name)      { name }
+    struct RegJNIRec {
+        int (*mProc)(JNIEnv*);
+    };
+#else
+    #define REG_JNI(name)      { name, #name }
+    struct RegJNIRec {
+        int (*mProc)(JNIEnv*);
+        const char* mName;
+    };
+#endif
+
+static const RegJNIRec gRegJNI[] = {
+    REG_JNI(register_android_graphics_Canvas),
+    // This needs to be before register_android_graphics_Graphics, or the latter
+    // will not be able to find the jmethodID for ColorSpace.get().
+    REG_JNI(register_android_graphics_ColorSpace),
+    REG_JNI(register_android_graphics_Graphics),
+    REG_JNI(register_android_graphics_Bitmap),
+    REG_JNI(register_android_graphics_BitmapFactory),
+    REG_JNI(register_android_graphics_BitmapRegionDecoder),
+    REG_JNI(register_android_graphics_ByteBufferStreamAdaptor),
+    REG_JNI(register_android_graphics_Camera),
+    REG_JNI(register_android_graphics_CreateJavaOutputStreamAdaptor),
+    REG_JNI(register_android_graphics_CanvasProperty),
+    REG_JNI(register_android_graphics_ColorFilter),
+    REG_JNI(register_android_graphics_DrawFilter),
+    REG_JNI(register_android_graphics_FontFamily),
+    REG_JNI(register_android_graphics_ImageDecoder),
+    REG_JNI(register_android_graphics_drawable_AnimatedImageDrawable),
+    REG_JNI(register_android_graphics_Interpolator),
+    REG_JNI(register_android_graphics_MaskFilter),
+    REG_JNI(register_android_graphics_Matrix),
+    REG_JNI(register_android_graphics_Movie),
+    REG_JNI(register_android_graphics_NinePatch),
+    REG_JNI(register_android_graphics_Paint),
+    REG_JNI(register_android_graphics_Path),
+    REG_JNI(register_android_graphics_PathMeasure),
+    REG_JNI(register_android_graphics_PathEffect),
+    REG_JNI(register_android_graphics_Picture),
+    REG_JNI(register_android_graphics_Region),
+    REG_JNI(register_android_graphics_Shader),
+    REG_JNI(register_android_graphics_SurfaceTexture),
+    REG_JNI(register_android_graphics_Typeface),
+    REG_JNI(register_android_graphics_YuvImage),
+    REG_JNI(register_android_graphics_drawable_AnimatedVectorDrawable),
+    REG_JNI(register_android_graphics_drawable_VectorDrawable),
+    REG_JNI(register_android_graphics_fonts_Font),
+    REG_JNI(register_android_graphics_fonts_FontFamily),
+    REG_JNI(register_android_graphics_pdf_PdfDocument),
+    REG_JNI(register_android_graphics_pdf_PdfEditor),
+    REG_JNI(register_android_graphics_pdf_PdfRenderer),
+    REG_JNI(register_android_graphics_text_MeasuredText),
+    REG_JNI(register_android_graphics_text_LineBreaker),
+
+    REG_JNI(register_android_util_PathParser),
+    REG_JNI(register_android_view_RenderNode),
+    REG_JNI(register_android_view_DisplayListCanvas),
+    REG_JNI(register_android_view_FrameMetricsObserver),
+    REG_JNI(register_android_view_TextureLayer),
+    REG_JNI(register_android_view_ThreadedRenderer),
+};
+
+} // namespace android
+
+void init_android_graphics() {
+    SkGraphics::Init();
+}
+
+int register_android_graphics_classes(JNIEnv *env) {
+    for (size_t i = 0; i < NELEM(android::gRegJNI); i++) {
+        if (android::gRegJNI[i].mProc(env) < 0) {
+#ifndef NDEBUG
+            __android_log_print(ANDROID_LOG_FATAL, LOG_TAG, "JNI Error!!! %s failed to load\n",
+                                android::gRegJNI[i].mName);
+#endif
+            return -1;
+        }
+    }
+    return 0;
+}
+
+using android::uirenderer::Properties;
+using android::uirenderer::RenderPipelineType;
+
+void zygote_preload_graphics() {
+    if (Properties::peekRenderPipelineType() == RenderPipelineType::SkiaGL) {
+        eglGetDisplay(EGL_DEFAULT_DISPLAY);
+    }
+}
\ No newline at end of file
diff --git a/core/jni/android/opengl/util.cpp b/core/jni/android/opengl/util.cpp
index 58c5871..82601ba 100644
--- a/core/jni/android/opengl/util.cpp
+++ b/core/jni/android/opengl/util.cpp
@@ -24,15 +24,13 @@
 #include <assert.h>
 #include <dlfcn.h>
 
+#include <android/graphics/bitmap.h>
 #include <GLES2/gl2.h>
 #include <GLES2/gl2ext.h>
 #include <GLES3/gl3.h>
 #include <ETC1/etc1.h>
 
-#include <SkBitmap.h>
-
 #include "core_jni_helpers.h"
-#include "android/graphics/Bitmap.h"
 
 #undef LOG_TAG
 #define LOG_TAG "OpenGLUtil"
@@ -628,31 +626,27 @@
 
 // The internal format is no longer the same as pixel format, per Table 2 in
 // https://www.khronos.org/registry/OpenGL-Refpages/es3.1/html/glTexImage2D.xhtml
-static int checkInternalFormat(SkColorType colorType, int internalformat,
-    int type)
+static bool checkInternalFormat(int32_t bitmapFormat, int internalformat, int type)
 {
-    switch(colorType) {
-        case kN32_SkColorType:
-            return (type == GL_UNSIGNED_BYTE &&
-                    internalformat == GL_RGBA) ||
-                (type == GL_UNSIGNED_BYTE &&
-                 internalformat == GL_SRGB8_ALPHA8) ? 0 : -1;
-        case kAlpha_8_SkColorType:
-            return (type == GL_UNSIGNED_BYTE &&
-                internalformat == GL_ALPHA) ? 0 : -1;
-        case kARGB_4444_SkColorType:
-            return (type == GL_UNSIGNED_SHORT_4_4_4_4 &&
-                internalformat == GL_RGBA) ? 0 : -1;
-        case kRGB_565_SkColorType:
-            return (type == GL_UNSIGNED_SHORT_5_6_5 &&
-                internalformat == GL_RGB) ? 0 : -1;
-        case kRGBA_F16_SkColorType:
-            return (type == GL_HALF_FLOAT &&
-                internalformat == GL_RGBA16F) ? 0 : -1;
+    if (internalformat == GL_PALETTE8_RGBA8_OES) {
+        return false;
+    }
+    switch(bitmapFormat) {
+        case ANDROID_BITMAP_FORMAT_RGBA_8888:
+            return (type == GL_UNSIGNED_BYTE && internalformat == GL_RGBA) ||
+                   (type == GL_UNSIGNED_BYTE && internalformat == GL_SRGB8_ALPHA8);
+        case ANDROID_BITMAP_FORMAT_A_8:
+            return (type == GL_UNSIGNED_BYTE && internalformat == GL_ALPHA);
+        case ANDROID_BITMAP_FORMAT_RGBA_4444:
+            return (type == GL_UNSIGNED_SHORT_4_4_4_4 && internalformat == GL_RGBA);
+        case ANDROID_BITMAP_FORMAT_RGB_565:
+            return (type == GL_UNSIGNED_SHORT_5_6_5 && internalformat == GL_RGB);
+        case ANDROID_BITMAP_FORMAT_RGBA_F16:
+            return (type == GL_HALF_FLOAT && internalformat == GL_RGBA16F);
         default:
             break;
     }
-    return -1;
+    return false;
 }
 
 // The internal format is no longer the same as pixel format, per Table 2 in
@@ -670,107 +664,92 @@
     }
 }
 
-static int getInternalFormat(SkColorType colorType)
-{
-    switch(colorType) {
-        case kAlpha_8_SkColorType:
+static int getInternalFormat(int32_t bitmapFormat) {
+    switch(bitmapFormat) {
+        case ANDROID_BITMAP_FORMAT_A_8:
             return GL_ALPHA;
-        case kARGB_4444_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGBA_4444:
             return GL_RGBA;
-        case kN32_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGBA_8888:
             return GL_RGBA;
-        case kRGB_565_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGB_565:
             return GL_RGB;
-        case kRGBA_F16_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGBA_F16:
             return GL_RGBA16F;
         default:
             return -1;
     }
 }
 
-static int getType(SkColorType colorType)
-{
-    switch(colorType) {
-        case kAlpha_8_SkColorType:
+static int getType(int32_t bitmapFormat) {
+    switch(bitmapFormat) {
+        case ANDROID_BITMAP_FORMAT_A_8:
             return GL_UNSIGNED_BYTE;
-        case kARGB_4444_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGBA_4444:
             return GL_UNSIGNED_SHORT_4_4_4_4;
-        case kN32_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGBA_8888:
             return GL_UNSIGNED_BYTE;
-        case kRGB_565_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGB_565:
             return GL_UNSIGNED_SHORT_5_6_5;
-        case kRGBA_F16_SkColorType:
+        case ANDROID_BITMAP_FORMAT_RGBA_F16:
             return GL_HALF_FLOAT;
         default:
             return -1;
     }
 }
 
-static jint util_getInternalFormat(JNIEnv *env, jclass clazz,
-        jlong bitmapPtr)
+static jint util_getInternalFormat(JNIEnv *env, jclass clazz, jobject bitmapObj)
 {
-    SkBitmap nativeBitmap;
-    bitmap::toSkBitmap(bitmapPtr, &nativeBitmap);
-    return getInternalFormat(nativeBitmap.colorType());
+    graphics::Bitmap bitmap(env, bitmapObj);
+    return getInternalFormat(bitmap.getInfo().format);
 }
 
-static jint util_getType(JNIEnv *env, jclass clazz,
-        jlong bitmapPtr)
+static jint util_getType(JNIEnv *env, jclass clazz, jobject bitmapObj)
 {
-    SkBitmap nativeBitmap;
-    bitmap::toSkBitmap(bitmapPtr, &nativeBitmap);
-    return getType(nativeBitmap.colorType());
+    graphics::Bitmap bitmap(env, bitmapObj);
+    return getType(bitmap.getInfo().format);
 }
 
-static jint util_texImage2D(JNIEnv *env, jclass clazz,
-        jint target, jint level, jint internalformat,
-        jlong bitmapPtr, jint type, jint border)
+static jint util_texImage2D(JNIEnv *env, jclass clazz, jint target, jint level,
+        jint internalformat, jobject bitmapObj, jint type, jint border)
 {
-    SkBitmap bitmap;
-    bitmap::toSkBitmap(bitmapPtr, &bitmap);
-    SkColorType colorType = bitmap.colorType();
+    graphics::Bitmap bitmap(env, bitmapObj);
+    AndroidBitmapInfo bitmapInfo = bitmap.getInfo();
+
     if (internalformat < 0) {
-        internalformat = getInternalFormat(colorType);
+        internalformat = getInternalFormat(bitmapInfo.format);
     }
     if (type < 0) {
-        type = getType(colorType);
+        type = getType(bitmapInfo.format);
     }
-    int err = checkInternalFormat(colorType, internalformat, type);
-    if (err)
-        return err;
-    const int w = bitmap.width();
-    const int h = bitmap.height();
-    const void* p = bitmap.getPixels();
-    if (internalformat == GL_PALETTE8_RGBA8_OES) {
-        err = -1;
-    } else {
-        glTexImage2D(target, level, internalformat, w, h, border,
-                     getPixelFormatFromInternalFormat(internalformat), type, p);
+
+    if (checkInternalFormat(bitmapInfo.format, internalformat, type)) {
+        glTexImage2D(target, level, internalformat, bitmapInfo.width, bitmapInfo.height, border,
+                     getPixelFormatFromInternalFormat(internalformat), type, bitmap.getPixels());
+        return 0;
     }
-    return err;
+    return -1;
 }
 
-static jint util_texSubImage2D(JNIEnv *env, jclass clazz,
-        jint target, jint level, jint xoffset, jint yoffset,
-        jlong bitmapPtr, jint format, jint type)
+static jint util_texSubImage2D(JNIEnv *env, jclass clazz, jint target, jint level,
+        jint xoffset, jint yoffset, jobject bitmapObj, jint format, jint type)
 {
-    SkBitmap bitmap;
-    bitmap::toSkBitmap(bitmapPtr, &bitmap);
-    SkColorType colorType = bitmap.colorType();
-    int internalFormat = getInternalFormat(colorType);
+    graphics::Bitmap bitmap(env, bitmapObj);
+    AndroidBitmapInfo bitmapInfo = bitmap.getInfo();
+
+    int internalFormat = getInternalFormat(bitmapInfo.format);
     if (format < 0) {
         format = getPixelFormatFromInternalFormat(internalFormat);
         if (format == GL_PALETTE8_RGBA8_OES)
             return -1; // glCompressedTexSubImage2D() not supported
     }
-    int err = checkInternalFormat(colorType, internalFormat, type);
-    if (err)
-        return err;
-    const int w = bitmap.width();
-    const int h = bitmap.height();
-    const void* p = bitmap.getPixels();
-    glTexSubImage2D(target, level, xoffset, yoffset, w, h, format, type, p);
-    return 0;
+
+    if (checkInternalFormat(bitmapInfo.format, internalFormat, type)) {
+        glTexSubImage2D(target, level, xoffset, yoffset, bitmapInfo.width, bitmapInfo.height,
+                        format, type, bitmap.getPixels());
+        return 0;
+    }
+    return -1;
 }
 
 /*
@@ -1036,10 +1015,10 @@
 };
 
 static const JNINativeMethod gUtilsMethods[] = {
-    { "native_getInternalFormat", "(J)I", (void*) util_getInternalFormat },
-    { "native_getType", "(J)I", (void*) util_getType },
-    { "native_texImage2D", "(IIIJII)I", (void*)util_texImage2D },
-    { "native_texSubImage2D", "(IIIIJII)I", (void*)util_texSubImage2D },
+    { "native_getInternalFormat", "(Landroid/graphics/Bitmap;)I", (void*) util_getInternalFormat },
+    { "native_getType", "(Landroid/graphics/Bitmap;)I", (void*) util_getType },
+    { "native_texImage2D", "(IIILandroid/graphics/Bitmap;II)I", (void*)util_texImage2D },
+    { "native_texSubImage2D", "(IIIILandroid/graphics/Bitmap;II)I", (void*)util_texSubImage2D },
 };
 
 static const JNINativeMethod gEtc1Methods[] = {
diff --git a/core/jni/android_graphics_GraphicBuffer.cpp b/core/jni/android_graphics_GraphicBuffer.cpp
index 43d22eb..b6d5089 100644
--- a/core/jni/android_graphics_GraphicBuffer.cpp
+++ b/core/jni/android_graphics_GraphicBuffer.cpp
@@ -178,9 +178,9 @@
     nativeBuffer.format = AHardwareBuffer_convertFromPixelFormat(buffer->getPixelFormat());
     nativeBuffer.bits = bits;
 
-    ACanvas* canvas = ACanvas_getNativeHandleFromJava(env, canvasObj);
-    ACanvas_setBuffer(canvas, &nativeBuffer, ADATASPACE_UNKNOWN);
-    ACanvas_clipRect(canvas, {rect.left, rect.top, rect.right, rect.bottom});
+    graphics::Canvas canvas(env, canvasObj);
+    canvas.setBuffer(&nativeBuffer, ADATASPACE_UNKNOWN);
+    canvas.clipRect({rect.left, rect.top, rect.right, rect.bottom});
 
     if (dirtyRect) {
         INVOKEV(dirtyRect, gRectClassInfo.set,
@@ -193,8 +193,8 @@
 static jboolean android_graphics_GraphicBuffer_unlockCanvasAndPost(JNIEnv* env, jobject,
         jlong wrapperHandle, jobject canvasObj) {
     // release the buffer from the canvas
-    ACanvas* canvas = ACanvas_getNativeHandleFromJava(env, canvasObj);
-    ACanvas_setBuffer(canvas, nullptr, ADATASPACE_UNKNOWN);
+    graphics::Canvas canvas(env, canvasObj);
+    canvas.setBuffer(nullptr, ADATASPACE_UNKNOWN);
 
     GraphicBufferWrapper* wrapper =
                 reinterpret_cast<GraphicBufferWrapper*>(wrapperHandle);
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index 9c52a64..9445319 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -85,7 +85,8 @@
     // Dalvik other extra sections.
     HEAP_DALVIK_OTHER_LINEARALLOC,
     HEAP_DALVIK_OTHER_ACCOUNTING,
-    HEAP_DALVIK_OTHER_CODE_CACHE,
+    HEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE,
+    HEAP_DALVIK_OTHER_APP_CODE_CACHE,
     HEAP_DALVIK_OTHER_COMPILER_METADATA,
     HEAP_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE,
 
@@ -257,6 +258,8 @@
             which_heap = HEAP_NATIVE;
         } else if (base::StartsWith(name, "[anon:libc_malloc]")) {
             which_heap = HEAP_NATIVE;
+        } else if (base::StartsWith(name, "[anon:scudo:")) {
+            which_heap = HEAP_NATIVE;
         } else if (base::StartsWith(name, "[stack")) {
             which_heap = HEAP_STACK;
         } else if (base::StartsWith(name, "[anon:stack_and_tls:")) {
@@ -280,9 +283,10 @@
             is_swappable = true;
         } else if (base::EndsWith(name, ".vdex")) {
             which_heap = HEAP_DEX;
-            // Handle system@framework@boot and system/framework/boot
+            // Handle system@framework@boot and system/framework/boot|apex
             if ((strstr(name.c_str(), "@boot") != nullptr) ||
-                    (strstr(name.c_str(), "/boot"))) {
+                    (strstr(name.c_str(), "/boot") != nullptr) ||
+                    (strstr(name.c_str(), "/apex") != nullptr)) {
                 sub_heap = HEAP_DEX_BOOT_VDEX;
             } else {
                 sub_heap = HEAP_DEX_APP_VDEX;
@@ -293,9 +297,10 @@
             is_swappable = true;
         } else if (base::EndsWith(name, ".art") || base::EndsWith(name, ".art]")) {
             which_heap = HEAP_ART;
-            // Handle system@framework@boot* and system/framework/boot*
+            // Handle system@framework@boot* and system/framework/boot|apex*
             if ((strstr(name.c_str(), "@boot") != nullptr) ||
-                    (strstr(name.c_str(), "/boot"))) {
+                    (strstr(name.c_str(), "/boot") != nullptr) ||
+                    (strstr(name.c_str(), "/apex") != nullptr)) {
                 sub_heap = HEAP_ART_BOOT;
             } else {
                 sub_heap = HEAP_ART_APP;
@@ -307,9 +312,18 @@
                 which_heap = HEAP_GL_DEV;
             } else if (base::StartsWith(name, "/dev/ashmem/CursorWindow")) {
                 which_heap = HEAP_CURSOR;
+            } else if (base::StartsWith(name, "/dev/ashmem/jit-zygote-cache")) {
+                which_heap = HEAP_DALVIK_OTHER;
+                sub_heap = HEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE;
             } else if (base::StartsWith(name, "/dev/ashmem")) {
                 which_heap = HEAP_ASHMEM;
             }
+        } else if (base::StartsWith(name, "/memfd:jit-cache")) {
+          which_heap = HEAP_DALVIK_OTHER;
+          sub_heap = HEAP_DALVIK_OTHER_APP_CODE_CACHE;
+        } else if (base::StartsWith(name, "/memfd:jit-zygote-cache")) {
+          which_heap = HEAP_DALVIK_OTHER;
+          sub_heap = HEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE;
         } else if (base::StartsWith(name, "[anon:")) {
             which_heap = HEAP_UNKNOWN;
             if (base::StartsWith(name, "[anon:dalvik-")) {
@@ -337,7 +351,7 @@
                     sub_heap = HEAP_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE;
                 } else if (base::StartsWith(name, "[anon:dalvik-jit-code-cache") ||
                         base::StartsWith(name, "[anon:dalvik-data-code-cache")) {
-                    sub_heap = HEAP_DALVIK_OTHER_CODE_CACHE;
+                    sub_heap = HEAP_DALVIK_OTHER_APP_CODE_CACHE;
                 } else if (base::StartsWith(name, "[anon:dalvik-CompilerMetadata")) {
                     sub_heap = HEAP_DALVIK_OTHER_COMPILER_METADATA;
                 } else {
diff --git a/core/jni/android_os_Parcel.cpp b/core/jni/android_os_Parcel.cpp
index d80c071..483b455 100644
--- a/core/jni/android_os_Parcel.cpp
+++ b/core/jni/android_os_Parcel.cpp
@@ -721,8 +721,11 @@
     {"nativeWriteFloat",          "(JF)V", (void*)android_os_Parcel_writeFloat},
     // @FastNative
     {"nativeWriteDouble",         "(JD)V", (void*)android_os_Parcel_writeDouble},
+    // @FastNative
     {"nativeWriteString",         "(JLjava/lang/String;)V", (void*)android_os_Parcel_writeString},
+    // @FastNative
     {"nativeWriteStrongBinder",   "(JLandroid/os/IBinder;)V", (void*)android_os_Parcel_writeStrongBinder},
+    // @FastNative
     {"nativeWriteFileDescriptor", "(JLjava/io/FileDescriptor;)J", (void*)android_os_Parcel_writeFileDescriptor},
 
     {"nativeCreateByteArray",     "(J)[B", (void*)android_os_Parcel_createByteArray},
@@ -736,8 +739,11 @@
     {"nativeReadFloat",           "(J)F", (void*)android_os_Parcel_readFloat},
     // @CriticalNative
     {"nativeReadDouble",          "(J)D", (void*)android_os_Parcel_readDouble},
+    // @FastNative
     {"nativeReadString",          "(J)Ljava/lang/String;", (void*)android_os_Parcel_readString},
+    // @FastNative
     {"nativeReadStrongBinder",    "(J)Landroid/os/IBinder;", (void*)android_os_Parcel_readStrongBinder},
+    // @FastNative
     {"nativeReadFileDescriptor",  "(J)Ljava/io/FileDescriptor;", (void*)android_os_Parcel_readFileDescriptor},
 
     {"nativeCreate",              "()J", (void*)android_os_Parcel_create},
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index bf4ffc7..daf33f6 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -352,7 +352,7 @@
 }
 
 static jobject NativeGetOverlayableMap(JNIEnv* env, jclass /*clazz*/, jlong ptr,
-                                        jstring package_name) {
+                                       jstring package_name) {
   ScopedLock<AssetManager2> assetmanager(AssetManagerFromLong(ptr));
   const ScopedUtfChars package_name_utf8(env, package_name);
   CHECK(package_name_utf8.c_str() != nullptr);
@@ -397,6 +397,21 @@
   return array_map;
 }
 
+static jstring NativeGetOverlayablesToString(JNIEnv* env, jclass /*clazz*/, jlong ptr,
+                                             jstring package_name) {
+  ScopedLock<AssetManager2> assetmanager(AssetManagerFromLong(ptr));
+  const ScopedUtfChars package_name_utf8(env, package_name);
+  CHECK(package_name_utf8.c_str() != nullptr);
+  const std::string std_package_name(package_name_utf8.c_str());
+
+  std::string result;
+  if (!assetmanager->GetOverlayablesToString(std_package_name, &result)) {
+    return nullptr;
+  }
+
+  return env->NewStringUTF(result.c_str());
+}
+
 #ifdef __ANDROID__ // Layoutlib does not support parcel
 static jobject ReturnParcelFileDescriptor(JNIEnv* env, std::unique_ptr<Asset> asset,
                                           jlongArray out_offsets) {
@@ -1608,6 +1623,8 @@
      (void*)NativeCreateIdmapsForStaticOverlaysTargetingAndroid},
     {"nativeGetOverlayableMap", "(JLjava/lang/String;)Ljava/util/Map;",
      (void*)NativeGetOverlayableMap},
+    {"nativeGetOverlayablesToString", "(JLjava/lang/String;)Ljava/lang/String;",
+     (void*)NativeGetOverlayablesToString},
 
     // Global management/debug methods.
     {"getGlobalAssetCount", "()I", (void*)NativeGetGlobalAssetCount},
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 0afbaa0e..e406e22 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -697,6 +697,9 @@
 // same IBinder, and the original BinderProxy is still alive, return the same BinderProxy.
 jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
 {
+    // N.B. This function is called from a @FastNative JNI method, so don't take locks around
+    // calls to Java code or block the calling thread for a long time for any reason.
+
     if (val == NULL) return NULL;
 
     if (val->checkSubclass(&gBinderOffsets)) {
diff --git a/core/jni/android_util_Process.cpp b/core/jni/android_util_Process.cpp
index 8aa6f86..0fada1b 100644
--- a/core/jni/android_util_Process.cpp
+++ b/core/jni/android_util_Process.cpp
@@ -35,6 +35,7 @@
 #include <limits>
 #include <memory>
 #include <string>
+#include <unordered_map>
 #include <vector>
 
 #include "core_jni_helpers.h"
@@ -81,6 +82,25 @@
 static pthread_key_t gBgKey = -1;
 #endif
 
+/*
+ *  cpuset/sched aggregate profile mappings
+ */
+static const std::unordered_map<int, std::string> kCpusetProfileMap = {
+    {SP_DEFAULT, "CPUSET_SP_DEFAULT"}, {SP_BACKGROUND, "CPUSET_SP_BACKGROUND"},
+    {SP_FOREGROUND, "CPUSET_SP_FOREGROUND"},{SP_SYSTEM, "CPUSET_SP_SYSTEM"},
+    {SP_AUDIO_APP, "CPUSET_SP_FOREGROUND"}, {SP_AUDIO_SYS, "CPUSET_SP_FOREGROUND"},
+    {SP_TOP_APP, "CPUSET_SP_TOP_APP"}, {SP_RT_APP, "CPUSET_SP_DEFAULT"},
+    {SP_RESTRICTED, "CPUSET_SP_RESTRICTED"}
+};
+
+static const std::unordered_map<int, std::string> kSchedProfileMap = {
+    {SP_DEFAULT, "SCHED_SP_DEFAULT"}, {SP_BACKGROUND, "SCHED_SP_BACKGROUND"},
+    {SP_FOREGROUND, "SCHED_SP_FOREGROUND"}, {SP_SYSTEM, "SCHED_SP_DEFAULT"},
+    {SP_AUDIO_APP, "SCHED_SP_FOREGROUND"}, {SP_AUDIO_SYS, "SCHED_SP_FOREGROUND"},
+    {SP_TOP_APP, "SCHED_SP_TOP_APP"}, {SP_RT_APP, "SCHED_SP_RT_APP"},
+    {SP_RESTRICTED, "SCHED_SP_DEFAULT"}
+};
+
 // For both of these, err should be in the errno range (positive), not a status_t (negative)
 static void signalExceptionForError(JNIEnv* env, int err, int tid) {
     switch (err) {
@@ -191,11 +211,24 @@
     return -1;
 }
 
+static bool verifyGroup(JNIEnv* env, int grp)
+{
+    if (grp < SP_DEFAULT || grp  >= SP_CNT) {
+        signalExceptionForError(env, EINVAL, grp);
+        return false;
+    }
+    return true;
+}
+
 void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int tid, jint grp)
 {
     ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
-    SchedPolicy sp = (SchedPolicy) grp;
-    int res = set_sched_policy(tid, sp);
+    if (!verifyGroup(env, grp)) {
+        return;
+    }
+
+    int res = SetTaskProfiles(tid, {kSchedProfileMap.at(grp)}, true) ? 0 : -1;
+
     if (res != NO_ERROR) {
         signalExceptionForGroupError(env, -res, tid);
     }
@@ -204,14 +237,12 @@
 void android_os_Process_setThreadGroupAndCpuset(JNIEnv* env, jobject clazz, int tid, jint grp)
 {
     ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
-    SchedPolicy sp = (SchedPolicy) grp;
-    int res = set_sched_policy(tid, sp);
-
-    if (res != NO_ERROR) {
-        signalExceptionForGroupError(env, -res, tid);
+    if (!verifyGroup(env, grp)) {
+        return;
     }
 
-    res = set_cpuset_policy(tid, sp);
+    int res = SetTaskProfiles(tid, {kCpusetProfileMap.at(grp)}, true) ? 0 : -1;
+
     if (res != NO_ERROR) {
         signalExceptionForGroupError(env, -res, tid);
     }
@@ -224,7 +255,11 @@
     char proc_path[255];
     struct dirent *de;
 
-    if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
+    if (!verifyGroup(env, grp)) {
+        return;
+    }
+
+    if (grp == SP_FOREGROUND) {
         signalExceptionForGroupError(env, EINVAL, pid);
         return;
     }
@@ -234,7 +269,6 @@
         grp = SP_FOREGROUND;
         isDefault = true;
     }
-    SchedPolicy sp = (SchedPolicy) grp;
 
     if (kDebugPolicy) {
         char cmdline[32];
@@ -250,7 +284,7 @@
             close(fd);
         }
 
-        if (sp == SP_BACKGROUND) {
+        if (grp == SP_BACKGROUND) {
             ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
         } else {
             ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
@@ -268,6 +302,7 @@
     while ((de = readdir(d))) {
         int t_pid;
         int t_pri;
+        int err;
 
         if (de->d_name[0] == '.')
             continue;
@@ -293,28 +328,16 @@
             if (t_pri >= ANDROID_PRIORITY_BACKGROUND) {
                 // This task wants to stay at background
                 // update its cpuset so it doesn't only run on bg core(s)
-                if (cpusets_enabled()) {
-                    int err = set_cpuset_policy(t_pid, sp);
-                    if (err != NO_ERROR) {
-                        signalExceptionForGroupError(env, -err, t_pid);
-                        break;
-                    }
+                err = SetTaskProfiles(t_pid, {kCpusetProfileMap.at(grp)}, true) ? 0 : -1;
+                if (err != NO_ERROR) {
+                    signalExceptionForGroupError(env, -err, t_pid);
+                    break;
                 }
                 continue;
             }
         }
-        int err;
 
-        if (cpusets_enabled()) {
-            // set both cpuset and cgroup for general threads
-            err = set_cpuset_policy(t_pid, sp);
-            if (err != NO_ERROR) {
-                signalExceptionForGroupError(env, -err, t_pid);
-                break;
-            }
-        }
-
-        err = set_sched_policy(t_pid, sp);
+        err = SetTaskProfiles(t_pid, {kCpusetProfileMap.at(grp)}, true) ? 0 : -1;
         if (err != NO_ERROR) {
             signalExceptionForGroupError(env, -err, t_pid);
             break;
diff --git a/core/jni/android_view_InputEventReceiver.cpp b/core/jni/android_view_InputEventReceiver.cpp
index c380fd5..59dab0c8 100644
--- a/core/jni/android_view_InputEventReceiver.cpp
+++ b/core/jni/android_view_InputEventReceiver.cpp
@@ -148,7 +148,7 @@
         mFdEvents = events;
         int fd = mInputConsumer.getChannel()->getFd();
         if (events) {
-            mMessageQueue->getLooper()->addFd(fd, 0, events, this, NULL);
+            mMessageQueue->getLooper()->addFd(fd, 0, events, this, nullptr);
         } else {
             mMessageQueue->getLooper()->removeFd(fd);
         }
@@ -169,7 +169,7 @@
 
     if (events & ALOOPER_EVENT_INPUT) {
         JNIEnv* env = AndroidRuntime::getJNIEnv();
-        status_t status = consumeEvents(env, false /*consumeBatches*/, -1, NULL);
+        status_t status = consumeEvents(env, false /*consumeBatches*/, -1, nullptr);
         mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
         return status == OK || status == NO_MEMORY ? 1 : 0;
     }
@@ -230,7 +230,7 @@
         *outConsumedBatch = false;
     }
 
-    ScopedLocalRef<jobject> receiverObj(env, NULL);
+    ScopedLocalRef<jobject> receiverObj(env, nullptr);
     bool skipCallbacks = false;
     for (;;) {
         uint32_t seq;
@@ -305,7 +305,7 @@
 
             default:
                 assert(false); // InputConsumer should prevent this from ever happening
-                inputEventObj = NULL;
+                inputEventObj = nullptr;
             }
 
             if (inputEventObj) {
@@ -337,13 +337,13 @@
         jobject inputChannelObj, jobject messageQueueObj) {
     sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
             inputChannelObj);
-    if (inputChannel == NULL) {
+    if (inputChannel == nullptr) {
         jniThrowRuntimeException(env, "InputChannel is not initialized.");
         return 0;
     }
 
     sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
-    if (messageQueue == NULL) {
+    if (messageQueue == nullptr) {
         jniThrowRuntimeException(env, "MessageQueue is not initialized.");
         return 0;
     }
diff --git a/core/jni/android_view_PointerIcon.cpp b/core/jni/android_view_PointerIcon.cpp
index 4f79790..ed2ce50 100644
--- a/core/jni/android_view_PointerIcon.cpp
+++ b/core/jni/android_view_PointerIcon.cpp
@@ -23,7 +23,7 @@
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
 #include <utils/Log.h>
-#include <android/graphics/GraphicsJNI.h>
+#include <android/graphics/bitmap.h>
 #include <nativehelper/ScopedLocalRef.h>
 
 #include "core_jni_helpers.h"
@@ -88,7 +88,7 @@
     ScopedLocalRef<jobject> bitmapObj(
             env, env->GetObjectField(pointerIconObj, gPointerIconClassInfo.mBitmap));
     if (bitmapObj.get()) {
-        GraphicsJNI::getSkBitmap(env, bitmapObj.get(), &(outPointerIcon->bitmap));
+        outPointerIcon->bitmap = graphics::Bitmap(env, bitmapObj.get());
     }
 
     ScopedLocalRef<jobjectArray> bitmapFramesObj(env, reinterpret_cast<jobjectArray>(
@@ -100,7 +100,7 @@
         outPointerIcon->bitmapFrames.resize(size);
         for (jsize i = 0; i < size; ++i) {
             ScopedLocalRef<jobject> bitmapObj(env, env->GetObjectArrayElement(bitmapFramesObj.get(), i));
-            GraphicsJNI::getSkBitmap(env, bitmapObj.get(), &(outPointerIcon->bitmapFrames[i]));
+            outPointerIcon->bitmapFrames[i] = graphics::Bitmap(env, bitmapObj.get());
         }
     }
 
diff --git a/core/jni/android_view_PointerIcon.h b/core/jni/android_view_PointerIcon.h
index 00bdfb4..908948ea 100644
--- a/core/jni/android_view_PointerIcon.h
+++ b/core/jni/android_view_PointerIcon.h
@@ -21,8 +21,8 @@
 
 #include <vector>
 
+#include <android/graphics/bitmap.h>
 #include <utils/Errors.h>
-#include <SkBitmap.h>
 
 namespace android {
 
@@ -68,10 +68,10 @@
     }
 
     int32_t style;
-    SkBitmap bitmap;
+    graphics::Bitmap bitmap;
     float hotSpotX;
     float hotSpotY;
-    std::vector<SkBitmap> bitmapFrames;
+    std::vector<graphics::Bitmap> bitmapFrames;
     int32_t durationPerFrame;
 
     inline bool isNullIcon() {
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index 4c2e91f..058a4c8 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -237,12 +237,11 @@
         return 0;
     }
 
-    ACanvas* canvas = ACanvas_getNativeHandleFromJava(env, canvasObj);
-    ACanvas_setBuffer(canvas, &buffer, static_cast<int32_t>(surface->getBuffersDataSpace()));
+    graphics::Canvas canvas(env, canvasObj);
+    canvas.setBuffer(&buffer, static_cast<int32_t>(surface->getBuffersDataSpace()));
 
     if (dirtyRectPtr) {
-        ACanvas_clipRect(canvas, {dirtyRect.left, dirtyRect.top,
-                                  dirtyRect.right, dirtyRect.bottom});
+        canvas.clipRect({dirtyRect.left, dirtyRect.top, dirtyRect.right, dirtyRect.bottom});
     }
 
     if (dirtyRectObj) {
@@ -268,8 +267,8 @@
     }
 
     // detach the canvas from the surface
-    ACanvas* canvas = ACanvas_getNativeHandleFromJava(env, canvasObj);
-    ACanvas_setBuffer(canvas, nullptr, ADATASPACE_UNKNOWN);
+    graphics::Canvas canvas(env, canvasObj);
+    canvas.setBuffer(nullptr, ADATASPACE_UNKNOWN);
 
     // unlock surface
     status_t err = surface->unlockAndPost();
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index bf0f10e..d5cd278 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -458,15 +458,6 @@
     transaction->setInputWindowInfo(ctrl, *handle->getInfo());
 }
 
-static void nativeTransferTouchFocus(JNIEnv* env, jclass clazz, jlong transactionObj,
-        jobject fromTokenObj, jobject toTokenObj) {
-    auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
-
-    sp<IBinder> fromToken(ibinderForJavaObject(env, fromTokenObj));
-    sp<IBinder> toToken(ibinderForJavaObject(env, toTokenObj));
-    transaction->transferTouchFocus(fromToken, toToken);
-}
-
 static void nativeSyncInputWindows(JNIEnv* env, jclass clazz, jlong transactionObj) {
     auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
     transaction->syncInputWindows();
@@ -1253,6 +1244,15 @@
     return reinterpret_cast<jlong>(transaction.release());
 }
 
+static jlong nativeMirrorSurface(JNIEnv* env, jclass clazz, jlong mirrorOfObj) {
+    sp<SurfaceComposerClient> client = SurfaceComposerClient::getDefault();
+    SurfaceControl *mirrorOf = reinterpret_cast<SurfaceControl*>(mirrorOfObj);
+    sp<SurfaceControl> surface = client->mirrorSurface(mirrorOf);
+
+    surface->incStrong((void *)nativeCreate);
+    return reinterpret_cast<jlong>(surface.get());
+}
+
 // ----------------------------------------------------------------------------
 
 static const JNINativeMethod sSurfaceControlMethods[] = {
@@ -1381,8 +1381,6 @@
             (void*)nativeCaptureLayers },
     {"nativeSetInputWindowInfo", "(JJLandroid/view/InputWindowHandle;)V",
             (void*)nativeSetInputWindowInfo },
-    {"nativeTransferTouchFocus", "(JLandroid/os/IBinder;Landroid/os/IBinder;)V",
-            (void*)nativeTransferTouchFocus },
     {"nativeSetMetadata", "(JJILandroid/os/Parcel;)V",
             (void*)nativeSetMetadata },
     {"nativeGetDisplayedContentSamplingAttributes",
@@ -1405,6 +1403,8 @@
             (void*)nativeReadTransactionFromParcel },
     {"nativeWriteTransactionToParcel", "(JLandroid/os/Parcel;)V",
             (void*)nativeWriteTransactionToParcel },
+    {"nativeMirrorSurface", "(J)J",
+            (void*)nativeMirrorSurface },
 };
 
 int register_android_view_SurfaceControl(JNIEnv* env)
diff --git a/core/jni/android_view_TextureLayer.cpp b/core/jni/android_view_TextureLayer.cpp
index 1ccb6a8..8a3f540 100644
--- a/core/jni/android_view_TextureLayer.cpp
+++ b/core/jni/android_view_TextureLayer.cpp
@@ -26,10 +26,7 @@
 #include <gui/GLConsumer.h>
 #include <hwui/Paint.h>
 
-#include <SkBitmap.h>
-#include <SkCanvas.h>
 #include <SkMatrix.h>
-#include <SkBlendMode.h>
 
 #include <DeferredLayerUpdater.h>
 #include <Rect.h>
diff --git a/core/jni/android_view_TextureView.cpp b/core/jni/android_view_TextureView.cpp
index 1f69c8b..391f515 100644
--- a/core/jni/android_view_TextureView.cpp
+++ b/core/jni/android_view_TextureView.cpp
@@ -124,9 +124,9 @@
     int32_t status = native_window_lock(window.get(), &outBuffer, &rect);
     if (status) return JNI_FALSE;
 
-    ACanvas* canvas = ACanvas_getNativeHandleFromJava(env, canvasObj);
-    ACanvas_setBuffer(canvas, &outBuffer, ANativeWindow_getBuffersDataSpace(window.get()));
-    ACanvas_clipRect(canvas, {rect.left, rect.top, rect.right, rect.bottom});
+    graphics::Canvas canvas(env, canvasObj);
+    canvas.setBuffer(&outBuffer, ANativeWindow_getBuffersDataSpace(window.get()));
+    canvas.clipRect({rect.left, rect.top, rect.right, rect.bottom});
 
     if (dirtyRect) {
         INVOKEV(dirtyRect, gRectClassInfo.set,
@@ -140,8 +140,8 @@
         jlong nativeWindow, jobject canvasObj) {
 
     // release the buffer from the canvas
-    ACanvas* canvas = ACanvas_getNativeHandleFromJava(env, canvasObj);
-    ACanvas_setBuffer(canvas, nullptr, ADATASPACE_UNKNOWN);
+    graphics::Canvas canvas(env, canvasObj);
+    canvas.setBuffer(nullptr, ADATASPACE_UNKNOWN);
 
     if (nativeWindow) {
         sp<ANativeWindow> window((ANativeWindow*) nativeWindow);
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index d42a48a..3516dce 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -74,7 +74,6 @@
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <bionic/malloc.h>
-#include <cutils/ashmem.h>
 #include <cutils/fs.h>
 #include <cutils/multiuser.h>
 #include <cutils/sockets.h>
@@ -303,7 +302,8 @@
   MOUNT_EXTERNAL_LEGACY = 4,
   MOUNT_EXTERNAL_INSTALLER = 5,
   MOUNT_EXTERNAL_FULL = 6,
-  MOUNT_EXTERNAL_COUNT = 7
+  MOUNT_EXTERNAL_PASS_THROUGH = 7,
+  MOUNT_EXTERNAL_COUNT = 8
 };
 
 // The order of entries here must be kept in sync with MountExternalKind enum values.
@@ -708,15 +708,14 @@
 
   const userid_t user_id = multiuser_get_user_id(uid);
   const std::string user_source = StringPrintf("/mnt/user/%d", user_id);
+  const std::string pass_through_source = StringPrintf("/mnt/pass_through/%d", user_id);
   bool isFuse = GetBoolProperty(kPropFuse, false);
 
   CreateDir(user_source, 0751, AID_ROOT, AID_ROOT, fail_fn);
 
   if (isFuse) {
-    // TODO(b/135341433): Bind mount the appropriate storage view for the app given its permissions
-    // media and media_location permission access. This should prevent the kernel from incorrectly
-    // sharing a cache across permission buckets
-    BindMount(user_source, "/storage", fail_fn);
+    BindMount(mount_mode == MOUNT_EXTERNAL_PASS_THROUGH ? pass_through_source : user_source,
+              "/storage", fail_fn);
   } else {
     const std::string& storage_source = ExternalStorageViews[mount_mode];
     BindMount(storage_source, "/storage", fail_fn);
@@ -1657,11 +1656,6 @@
   if (!SetTaskProfiles(0, {})) {
     ZygoteFailure(env, "zygote", nullptr, "Zygote SetTaskProfiles failed");
   }
-
-  /*
-   * ashmem initialization to avoid dlopen overhead
-   */
-  ashmem_init();
 }
 
 /**
diff --git a/core/jni/com_android_internal_os_ZygoteInit.cpp b/core/jni/com_android_internal_os_ZygoteInit.cpp
index c2a5ee43..a5152b6 100644
--- a/core/jni/com_android_internal_os_ZygoteInit.cpp
+++ b/core/jni/com_android_internal_os_ZygoteInit.cpp
@@ -16,17 +16,13 @@
 
 #define LOG_TAG "Zygote"
 
-#include <EGL/egl.h>
-#include <Properties.h>
+#include <android/graphics/jni_runtime.h>
 #include <ui/GraphicBufferMapper.h>
 
 #include "core_jni_helpers.h"
 
 namespace {
 
-using android::uirenderer::Properties;
-using android::uirenderer::RenderPipelineType;
-
 // Shadow call stack (SCS) is a security mitigation that uses a separate stack
 // (the SCS) for return addresses. In versions of Android newer than P, the
 // compiler cooperates with the system to ensure that the SCS address is always
@@ -64,9 +60,7 @@
 
 void android_internal_os_ZygoteInit_nativePreloadGraphicsDriver(JNIEnv* env, jclass) {
     ScopedSCSExit x;
-    if (Properties::peekRenderPipelineType() == RenderPipelineType::SkiaGL) {
-        eglGetDisplay(EGL_DEFAULT_DISPLAY);
-    }
+    zygote_preload_graphics();
 }
 
 const JNINativeMethod gMethods[] = {
diff --git a/core/proto/Android.bp b/core/proto/Android.bp
index e199dab..6119d71 100644
--- a/core/proto/Android.bp
+++ b/core/proto/Android.bp
@@ -30,9 +30,9 @@
 }
 
 java_library_host {
-    name: "windowmanager-log-proto",
+    name: "protolog-proto",
     srcs: [
-        "android/server/windowmanagerlog.proto"
+        "android/server/protolog.proto"
     ],
     proto: {
         type: "full",
diff --git a/core/proto/android/server/activitymanagerservice.proto b/core/proto/android/server/activitymanagerservice.proto
index d54b6b0..d01a45c 100644
--- a/core/proto/android/server/activitymanagerservice.proto
+++ b/core/proto/android/server/activitymanagerservice.proto
@@ -118,13 +118,15 @@
 message ActivityRecordProto {
     option (.android.msg_privacy).dest = DEST_AUTOMATIC;
 
-    optional .com.android.server.wm.ConfigurationContainerProto configuration_container = 1;
+    // To be removed soon.
+    optional .com.android.server.wm.ConfigurationContainerProto configuration_container = 1 [deprecated=true];
     optional .com.android.server.wm.IdentifierProto identifier = 2;
     optional string state = 3;
     optional bool visible = 4;
     optional bool front_of_task = 5;
     optional int32 proc_id = 6;
     optional bool translucent = 7;
+    optional .com.android.server.wm.AppWindowTokenProto app_window_token = 8;
 }
 
 message KeyguardControllerProto {
diff --git a/core/proto/android/server/jobscheduler.proto b/core/proto/android/server/jobscheduler.proto
index 79167ab..15b98af 100644
--- a/core/proto/android/server/jobscheduler.proto
+++ b/core/proto/android/server/jobscheduler.proto
@@ -48,6 +48,13 @@
 
     repeated int32 started_users = 2;
 
+    message JobRestriction {
+        option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+        optional .android.app.job.StopReasonEnum reason = 1;
+        optional bool is_restricting = 2;
+    }
+
     message RegisteredJob {
         option (.android.msg_privacy).dest = DEST_AUTOMATIC;
 
@@ -56,20 +63,22 @@
 
         optional bool is_job_ready_to_be_executed = 10;
         // A job is ready to be executed if:
-        // is_job_ready && are_users_started && !is_job_thermal_constrained && !is_job_pending &&
+        // is_job_ready && are_users_started && !is_job_restricted && !is_job_pending &&
         // !is_job_currently_active && !is_uid_backing_up &&
         // is_component_usable.
         optional bool is_job_ready = 3;
         optional bool are_users_started = 4;
-        optional bool is_job_thermal_constrained = 11;
+        optional bool is_job_restricted = 11;
         optional bool is_job_pending = 5;
         optional bool is_job_currently_active = 6;
         optional bool is_uid_backing_up = 7;
         optional bool is_component_usable = 8;
 
+        repeated JobRestriction restrictions = 12;
+
         reserved 9; // last_run_heartbeat
 
-        // Next tag: 12
+        // Next tag: 13
     }
     repeated RegisteredJob registered_jobs = 3;
 
diff --git a/core/proto/android/server/protolog.proto b/core/proto/android/server/protolog.proto
new file mode 100644
index 0000000..3512c0a
--- /dev/null
+++ b/core/proto/android/server/protolog.proto
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+syntax = "proto2";
+
+package com.android.server.protolog;
+
+option java_multiple_files = true;
+
+/* represents a single log entry */
+message ProtoLogMessage {
+    /* log statement identifier, created from message string and log level. */
+    optional sfixed32 message_hash = 1;
+    /* log time, relative to the elapsed system time clock. */
+    optional fixed64 elapsed_realtime_nanos = 2;
+    /* string parameters passed to the log call. */
+    repeated string str_params = 3;
+    /* integer parameters passed to the log call. */
+    repeated sint64 sint64_params = 4 [packed=true];
+    /* floating point parameters passed to the log call. */
+    repeated double double_params = 5 [packed=true];
+    /* boolean parameters passed to the log call. */
+    repeated bool boolean_params = 6 [packed=true];
+}
+
+/* represents a log file containing ProtoLog log entries.
+   Encoded, it should start with 0x9 0x50 0x52 0x4f 0x54 0x4f 0x4c 0x4f 0x47 (.PROTOLOG), such
+   that they can be easily identified. */
+message ProtoLogFileProto {
+    /* constant; MAGIC_NUMBER = (long) MAGIC_NUMBER_H << 32 | MagicNumber.MAGIC_NUMBER_L
+       (this is needed because enums have to be 32 bits and there's no nice way to put 64bit
+        constants into .proto files. */
+    enum MagicNumber {
+        INVALID = 0;
+        MAGIC_NUMBER_L = 0x544f5250; /* PROT (little-endian ASCII) */
+        MAGIC_NUMBER_H = 0x474f4c4f; /* OLOG (little-endian ASCII) */
+    }
+
+    /* the magic number header */
+    optional fixed64 magic_number = 1;
+    /* log proto version. */
+    optional string version = 2;
+    /* offset between real-time clock and elapsed system time clock in miliseconds.
+       Calculated as: (System.currentTimeMillis() - (SystemClock.elapsedRealtimeNanos() / 1000000) */
+    optional fixed64 realTimeToElapsedTimeOffsetMillis = 3;
+    /* log entries */
+    repeated ProtoLogMessage log = 4;
+}
diff --git a/core/proto/android/server/windowmanagerlog.proto b/core/proto/android/server/windowmanagerlog.proto
deleted file mode 100644
index 5bee1bd..0000000
--- a/core/proto/android/server/windowmanagerlog.proto
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-syntax = "proto2";
-
-package com.android.server.wm;
-
-option java_multiple_files = true;
-
-/* represents a single log entry */
-message ProtoLogMessage {
-    /* log statement identifier, created from message string and log level. */
-    optional fixed32 message_hash = 1;
-    /* log time, relative to the elapsed system time clock. */
-    optional fixed64 elapsed_realtime_nanos = 2;
-    /* string parameters passed to the log call. */
-    repeated string str_params = 3;
-    /* integer parameters passed to the log call. */
-    repeated sint64 sint64_params = 4 [packed=true];
-    /* floating point parameters passed to the log call. */
-    repeated double double_params = 5 [packed=true];
-    /* boolean parameters passed to the log call. */
-    repeated bool boolean_params = 6 [packed=true];
-}
-
-/* represents a log file containing window manager log entries.
-   Encoded, it should start with 0x9 0x57 0x49 0x4e 0x44 0x4f 0x4c 0x4f 0x47 (.WINDOLOG), such
-   that they can be easily identified. */
-message WindowManagerLogFileProto {
-    /* constant; MAGIC_NUMBER = (long) MAGIC_NUMBER_H << 32 | MagicNumber.MAGIC_NUMBER_L
-       (this is needed because enums have to be 32 bits and there's no nice way to put 64bit
-        constants into .proto files. */
-    enum MagicNumber {
-        INVALID = 0;
-        MAGIC_NUMBER_L = 0x444e4957; /* WIND (little-endian ASCII) */
-        MAGIC_NUMBER_H = 0x474f4c4f; /* OLOG (little-endian ASCII) */
-    }
-
-    /* the magic number header */
-    optional fixed64 magic_number = 1;
-    /* log proto version. */
-    optional string version = 2;
-    /* offset between real-time clock and elapsed system time clock in miliseconds.
-       Calculated as: (System.currentTimeMillis() - (SystemClock.elapsedRealtimeNanos() / 1000000) */
-    optional fixed64 realTimeToElapsedTimeOffsetMillis = 3;
-    /* log entries */
-    repeated ProtoLogMessage log = 4;
-}
diff --git a/core/proto/android/service/package.proto b/core/proto/android/service/package.proto
index 6ffa0c9..301fa13 100644
--- a/core/proto/android/service/package.proto
+++ b/core/proto/android/service/package.proto
@@ -110,7 +110,7 @@
         optional bool is_launched = 6;
         optional EnabledState enabled_state = 7;
         optional string last_disabled_app_caller = 8;
-        optional string suspending_package = 9;
+        repeated string suspending_package = 9;
         optional int32 distraction_flags = 10;
     }
 
diff --git a/core/proto/android/telecomm/enums.proto b/core/proto/android/telecomm/enums.proto
index 7a2ba62..5ca4a85 100644
--- a/core/proto/android/telecomm/enums.proto
+++ b/core/proto/android/telecomm/enums.proto
@@ -110,6 +110,24 @@
      * {@link android.telecom.Connection#CAPABILITY_CAN_PULL_CALL}.
      */
     PULLING = 10;
+
+    /**
+     * Indicates that an incoming call has been answered by the in-call UI, but Telephony hasn't yet
+     * set the call to active.
+     */
+    ANSWERED = 11;
+
+    /**
+     * Indicates that the call is undergoing audio processing by a different app in the background.
+     * @see android.telecom.Call#STATE_AUDIO_PROCESSING
+     */
+    AUDIO_PROCESSING = 12;
+
+    /**
+     * Indicates that the call is in a fake ringing state.
+     * @see android.telecom.Call#STATE_SIMULATED_RINGING
+     */
+    SIMULATED_RINGING = 13;
 }
 
 // Disconnect causes for a call. Primarily used by android/telecom/DisconnectCause.java
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index e23c75e..b030b33 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -643,6 +643,7 @@
     <!-- Grouping for platform runtime permissions is not accessible to apps
          @hide
          @SystemApi
+         @TestApi
     -->
     <permission-group android:name="android.permission-group.UNDEFINED"
         android:priority="100" />
@@ -793,6 +794,18 @@
         android:permissionFlags="hardRestricted"
         android:protectionLevel="dangerous" />
 
+    <!-- @SystemApi @TestApi Allows an application to forward cell broadcast messages to the cell
+         broadcast module. This is required in order to bind to the cell broadcast service, and
+         ensures that only the system can forward messages to it.
+
+         <p>Protection level: signature
+
+         @hide -->
+    <permission android:name="android.permission.BIND_CELL_BROADCAST_SERVICE"
+        android:label="@string/permlab_bindCellBroadcastService"
+        android:description="@string/permdesc_bindCellBroadcastService"
+        android:protectionLevel="signature" />
+
     <!-- @SystemApi @TestApi Allows an application to read previously received cell broadcast
          messages and to register a content observer to get notifications when
          a cell broadcast has been received and added to the database. For
diff --git a/core/res/TEST_MAPPING b/core/res/TEST_MAPPING
index ccd91a4..9185bae 100644
--- a/core/res/TEST_MAPPING
+++ b/core/res/TEST_MAPPING
@@ -5,6 +5,9 @@
             "options": [
                 {
                     "include-filter": "android.permission2.cts.PermissionPolicyTest#platformPermissionPolicyIsUnaltered"
+                },
+                {
+                    "include-filter": "android.permission2.cts.RuntimePermissionProperties"
                 }
             ]
         }
diff --git a/core/res/res/anim/screen_rotate_0_exit.xml b/core/res/res/anim/screen_rotate_0_exit.xml
index f1df2de..37d5a411 100644
--- a/core/res/res/anim/screen_rotate_0_exit.xml
+++ b/core/res/res/anim/screen_rotate_0_exit.xml
@@ -19,7 +19,4 @@
 
 <set xmlns:android="http://schemas.android.com/apk/res/android"
         android:shareInterpolator="false">
-    <alpha android:fromAlpha="1.0" android:toAlpha="0"
-            android:interpolator="@interpolator/decelerate_quint"
-            android:duration="@android:integer/config_shortAnimTime" />
 </set>
diff --git a/core/res/res/anim/screen_rotate_180_exit.xml b/core/res/res/anim/screen_rotate_180_exit.xml
index 1eb6361..58a1868 100644
--- a/core/res/res/anim/screen_rotate_180_exit.xml
+++ b/core/res/res/anim/screen_rotate_180_exit.xml
@@ -25,7 +25,4 @@
             android:fillEnabled="true"
             android:fillBefore="true" android:fillAfter="true"
             android:duration="@android:integer/config_mediumAnimTime" />
-    <alpha android:fromAlpha="1.0" android:toAlpha="0"
-            android:interpolator="@interpolator/decelerate_cubic"
-            android:duration="@android:integer/config_mediumAnimTime"/>
 </set>
\ No newline at end of file
diff --git a/core/res/res/anim/screen_rotate_alpha.xml b/core/res/res/anim/screen_rotate_alpha.xml
new file mode 100644
index 0000000..c49ef9c
--- /dev/null
+++ b/core/res/res/anim/screen_rotate_alpha.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+** Copyright 2012, 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.
+*/
+-->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android"
+        android:shareInterpolator="false">
+    <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
+           android:interpolator="@interpolator/decelerate_quint"
+           android:fillEnabled="true"
+           android:fillBefore="true" android:fillAfter="true"
+           android:duration="@android:integer/config_mediumAnimTime" />
+</set>
diff --git a/core/res/res/anim/screen_rotate_minus_90_exit.xml b/core/res/res/anim/screen_rotate_minus_90_exit.xml
index 9b38939..0927dd3 100644
--- a/core/res/res/anim/screen_rotate_minus_90_exit.xml
+++ b/core/res/res/anim/screen_rotate_minus_90_exit.xml
@@ -40,9 +40,4 @@
             android:fillEnabled="true"
             android:fillBefore="true" android:fillAfter="true"
             android:duration="@android:integer/config_mediumAnimTime" />
-    <alpha android:fromAlpha="1.0" android:toAlpha="0"
-            android:interpolator="@interpolator/decelerate_quint"
-            android:fillEnabled="true"
-            android:fillBefore="true" android:fillAfter="true"
-            android:duration="@android:integer/config_mediumAnimTime" />
 </set>
diff --git a/core/res/res/anim/screen_rotate_minus_90_frame.xml b/core/res/res/anim/screen_rotate_minus_90_frame.xml
deleted file mode 100644
index 2d198f3..0000000
--- a/core/res/res/anim/screen_rotate_minus_90_frame.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-        android:shareInterpolator="false">
-    <rotate android:fromDegrees="0" android:toDegrees="90"
-            android:pivotX="50%" android:pivotY="50%"
-            android:interpolator="@interpolator/decelerate_quint"
-            android:fillEnabled="true"
-            android:fillBefore="true" android:fillAfter="true"
-            android:duration="@android:integer/config_longAnimTime" />
-</set>
diff --git a/core/res/res/anim/screen_rotate_plus_90_exit.xml b/core/res/res/anim/screen_rotate_plus_90_exit.xml
index fa34533..fd786f9 100644
--- a/core/res/res/anim/screen_rotate_plus_90_exit.xml
+++ b/core/res/res/anim/screen_rotate_plus_90_exit.xml
@@ -40,9 +40,4 @@
             android:fillEnabled="true"
             android:fillBefore="true" android:fillAfter="true"
             android:duration="@android:integer/config_mediumAnimTime" />
-    <alpha android:fromAlpha="1.0" android:toAlpha="0"
-            android:interpolator="@interpolator/decelerate_quint"
-            android:fillEnabled="true"
-            android:fillBefore="true" android:fillAfter="true"
-            android:duration="@android:integer/config_mediumAnimTime" />
 </set>
diff --git a/core/res/res/anim/screen_rotate_plus_90_frame.xml b/core/res/res/anim/screen_rotate_plus_90_frame.xml
deleted file mode 100644
index cd20050..0000000
--- a/core/res/res/anim/screen_rotate_plus_90_frame.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-        android:shareInterpolator="false">
-    <rotate android:fromDegrees="0" android:toDegrees="-90"
-            android:pivotX="50%" android:pivotY="50%"
-            android:interpolator="@interpolator/decelerate_quint"
-            android:fillEnabled="true"
-            android:fillBefore="true" android:fillAfter="true"
-            android:duration="@android:integer/config_longAnimTime" />
-</set>
diff --git a/core/res/res/drawable-hdpi/ic_launcher_android.png b/core/res/res/drawable-hdpi/ic_launcher_android.png
index 2e9b196..8fed953 100644
--- a/core/res/res/drawable-hdpi/ic_launcher_android.png
+++ b/core/res/res/drawable-hdpi/ic_launcher_android.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_launcher_android.png b/core/res/res/drawable-mdpi/ic_launcher_android.png
index baacd4f..16b66a1 100644
--- a/core/res/res/drawable-mdpi/ic_launcher_android.png
+++ b/core/res/res/drawable-mdpi/ic_launcher_android.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_launcher_android.png b/core/res/res/drawable-xhdpi/ic_launcher_android.png
index 00b69a5..824794a 100644
--- a/core/res/res/drawable-xhdpi/ic_launcher_android.png
+++ b/core/res/res/drawable-xhdpi/ic_launcher_android.png
Binary files differ
diff --git a/core/res/res/drawable-xxhdpi/ic_launcher_android.png b/core/res/res/drawable-xxhdpi/ic_launcher_android.png
index ad05cd5..81268b3 100644
--- a/core/res/res/drawable-xxhdpi/ic_launcher_android.png
+++ b/core/res/res/drawable-xxhdpi/ic_launcher_android.png
Binary files differ
diff --git a/core/res/res/drawable-xxxhdpi/ic_launcher_android.png b/core/res/res/drawable-xxxhdpi/ic_launcher_android.png
new file mode 100644
index 0000000..eedc9f9
--- /dev/null
+++ b/core/res/res/drawable-xxxhdpi/ic_launcher_android.png
Binary files differ
diff --git a/core/res/res/values-af/strings.xml b/core/res/res/values-af/strings.xml
index 9ba0481..dd9eafe 100644
--- a/core/res/res/values-af/strings.xml
+++ b/core/res/res/values-af/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Laat die program toe om SMS-boodskappe te ontvang en te verwerk. Dit beteken dat die program boodskappe wat na jou toestel gestuur is, kan monitor of uitvee, sonder dat jy dit gesien het."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ontvang teksboodskappe (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Laat die program toe om MMS-boodskappe te ontvang en te verwerk. Dit beteken dat die program boodskappe wat na jou toestel gestuur is kan monitor of uitvee, sonder dat jy dit gesien het."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lees seluitsending-boodskappe"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Laat die program toe om seluitsending-boodskappe te lees wat deur jou toestel ontvang word. Seluitsending-waarskuwings word in sommige plekke afgelewer om jou van noodsituasies te waarsku. Kwaadwillige programme mag inmeng met die prestasie of die werking van jou toestel wanneer \'n noodgeval se seluitsending ontvang word."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lees ingetekende nuus"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Laat die program toe om Moenie Steur Nie-opstelling te lees en skryf."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"begin kyk van toestemminggebruik"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Laat die houer toe om die toestemminggebruik vir \'n program te begin. Behoort nooit vir normale programme nodig te wees nie."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"toeganklikheidkortpadteiken"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Laat \'n program toe om die toeganklikheidkortpadteiken te definieer."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Stel wagwoordreëls"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Beheer die lengte en die karakters wat in skermslotwagwoorde en -PIN\'e toegelaat word."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitor pogings om skerm te ontsluit"</string>
@@ -1075,7 +1081,7 @@
     <string name="Midnight" msgid="5630806906897892201">"Middernag"</string>
     <string name="elapsed_time_short_format_mm_ss" msgid="4431555943828711473">"<xliff:g id="MINUTES">%1$02d</xliff:g>:<xliff:g id="SECONDS">%2$02d</xliff:g>"</string>
     <string name="elapsed_time_short_format_h_mm_ss" msgid="1846071997616654124">"<xliff:g id="HOURS">%1$d</xliff:g>:<xliff:g id="MINUTES">%2$02d</xliff:g>:<xliff:g id="SECONDS">%3$02d</xliff:g>"</string>
-    <string name="selectAll" msgid="6876518925844129331">"Kies alle"</string>
+    <string name="selectAll" msgid="6876518925844129331">"Kies alles"</string>
     <string name="cut" msgid="3092569408438626261">"Sny"</string>
     <string name="copy" msgid="2681946229533511987">"Kopieer"</string>
     <string name="failed_to_copy_to_clipboard" msgid="1833662432489814471">"Kon nie na knipbord toe kopieer nie"</string>
@@ -1356,11 +1362,13 @@
     <string name="usb_power_notification_message" msgid="4647527153291917218">"Laai tans gekoppelde toestel. Tik vir meer opsies."</string>
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Analoë oudiobykomstigheid bespeur"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"Die aangehegde toestel is nie met hierdie foon versoenbaar nie. Tik om meer te wete te kom."</string>
-    <string name="adb_active_notification_title" msgid="6729044778949189918">"USB-ontfouter gekoppel"</string>
+    <string name="adb_active_notification_title" msgid="6729044778949189918">"USB-ontfouting gekoppel"</string>
     <string name="adb_active_notification_message" msgid="7463062450474107752">"Tik om USB-ontfouting af te skakel"</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Kies om USB-ontfouting te deaktiveer."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Toetsraamwerkmodus is geaktiveer"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Voer \'n fabriekterugstelling uit om Toetsraamwerkmodus te deaktiveer."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Reekskonsole is geaktiveer"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Werkverrigting word beïnvloed. Gaan selflaaiprogram na om te deaktiveer."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Vloeistof of vuilgoed in USB-poort"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-poort is outomaties gedeaktiveer. Tik om meer te wete te kom."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"OK om USB-poort te gebruik"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Ongekategoriseer"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Jy stel die belangrikheid van hierdie kennisgewings."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Dit is belangrik as gevolg van die mense wat betrokke is."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Laat <xliff:g id="APP">%1$s</xliff:g> toe om \'n nuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> te skep?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Laat <xliff:g id="APP">%1$s</xliff:g> toe om \'n nuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> te skep (\'n gebruiker met hierdie rekening bestaan reeds)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Laat <xliff:g id="APP">%1$s</xliff:g> toe om \'n nuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> te skep (\'n gebruiker met hierdie rekening bestaan reeds)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Laat <xliff:g id="APP">%1$s</xliff:g> toe om \'n nuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> te skep?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Voeg \'n taal by"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Streekvoorkeur"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Voer taalnaam in"</string>
diff --git a/core/res/res/values-am/strings.xml b/core/res/res/values-am/strings.xml
index 013537c..a007c9d 100644
--- a/core/res/res/values-am/strings.xml
+++ b/core/res/res/values-am/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"መተግበሪያው የኤስ.ኤም.ኤስ. መልዕክቶችን እንዲያነብ እና እንዲያካሂድ ይፈቅዳል። ይህ ማለት መተግበሪያው ወደ መሳሪያህ የተላኩ መልዕክቶችን ላንተ ሳያሳይህ ሊቆጣጠር ወይም ሊሰርዝ ይችላል።"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"የፅሁፍ መልዕክቶችን ተቀበል (ኤም.ኤም.ኤስ.)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"መተግበሪያው የኤም.ኤም.ኤስ. መልዕክቶችን እንዲያነብ እና እንዲያካሂድ ይፈቅዳል። ይህ ማለት መተግበሪያው ወደ መሳሪያህ የተላኩ መልዕክቶችን ላንተ ሳያሳይህ ሊቆጣጠር ወይም ሊሰርዝ ይችላል።"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"የህዋስ ስርጭት መልዕክቶችን አንብብ"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"መሣሪያህ የህዋስ ስርጭት መልዕክቶች ሲቀበል መተግበሪያው እንዲያነበው ይፈቅድለታል። የህዋስ ስርጭት ማንቂያዎች አስቸኳይ ሁኔታዎች ሲያጋጥሙ አንዳንድ አካባቢዎች ላይ የሚላኩ ናቸው። የህዋስ ስርጭት ሲደርስ ተንኮል አዘል መተግበሪያዎች በመሣሪያህ አፈጻጸም ወይም አሰራር ላይ ጣልቃ ሊገቡ ይችላሉ።"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"የምዝገባ መግቦች አንበብ"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"መተግበሪያው የአትረብሽ ውቅረትን እንዲያነብብ እና እንዲጸፍ ይፈቅዳል።"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"የእይታ ፈቃድ መጠቀምን መጀመር"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ያዢው ለአንድ መተግበሪያ የፈቃድ አጠቃቀሙን እንዲያስጀምር ያስችለዋል። ለመደበኛ መተግበሪያዎች በጭራሽ ሊያስፈልግ አይገባም።"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"የተደራሽነት አቋራጭ ዒላማ"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"መተግበሪያ የተደራሽነት አቋራጭ ዒላማን ለመግለጽ እንዲችል ይፈቅድለታል።"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"የይለፍ ቃል ደንቦች አዘጋጅ"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"በማያ ገጽ መቆለፊያ የይለፍ ቃሎች እና ፒኖች ውስጥ የሚፈቀዱ ቁምፊዎችን እና ርዝመታቸውን ተቆጣጠር።"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"የማሳያ-ክፈት ሙከራዎችን ክትትል ያድርጉባቸው"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ማረሚያ ላለማንቃት ምረጥ።"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"የሙከራ ጥቅል ሁነታ ነቅቷል"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"የመሞከሪያ ጥቅል ሁነታን ለማሰናከል የፋብሪካ ዳግም ቅንብርን ይሞክሩ።"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"ተከታታይ ኮንሶል ነቅቷል"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"አፈጻጸም ተጽዕኖ አርፎበታል። ለማሰናከል፣ bootloader ን ይፈትሹ።"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"በዩኤስቢ ወደብ ውስጥ ፈሳሽ ወይም ፍርስራሽ"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"የዩኤስቢ ወደብ በራስ-ሰር ተሰናክሏል። የበለጠ ለመረዳት መታ ያድርጉ።"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"የዩኤስቢ ወደቡን መጠቀም ችግር የለውም"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"ያልተመደቡ"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"የእነዚህን ማሳወቂያዎች አስፈላጊነት አዘጋጅተዋል።"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ይሄ በሚሳተፉ ሰዎች ምክንያት አስፈላጊ ነው።"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> በ<xliff:g id="ACCOUNT">%2$s</xliff:g> አዲስ ተጠቃሚ እንዲፈጥር ይፈቀድለት?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> በ<xliff:g id="ACCOUNT">%2$s</xliff:g> አዲስ ተጠቃሚ እንዲፈጥር ይፈቀድለት (ይህ መለያ ያለው ተጠቃሚ አስቀድሞ አለ)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> በ<xliff:g id="ACCOUNT">%2$s</xliff:g> አዲስ ተጠቃሚ እንዲፈጥር ይፈቀድለት (ይህ መለያ ያለው ተጠቃሚ አስቀድሞ አለ)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> አዲስ ተጠቃሚ ከ <xliff:g id="ACCOUNT">%2$s</xliff:g> ጋር መፍጠር እንዲችል ይፍቀዱ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ቋንቋ ያክሉ"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"የክልል ምርጫ"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"የቋንቋ ስም ይተይቡ"</string>
diff --git a/core/res/res/values-ar/strings.xml b/core/res/res/values-ar/strings.xml
index 2bef980..2e272ee 100644
--- a/core/res/res/values-ar/strings.xml
+++ b/core/res/res/values-ar/strings.xml
@@ -356,6 +356,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"‏للسماح للتطبيق بتلقي ومعالجة الرسائل القصيرة SMS. وهذا يعني أنه يمكن للتطبيق مراقبة الرسائل التي يتم إرسالها إلى جهازك أو حذفها بدون عرضها لك."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"تلقي رسائل نصية (رسائل وسائط متعددة)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"للسماح للتطبيق بتلقي ومعالجة رسائل الوسائط المتعددة. وهذا يعني أنه يمكن للتطبيق مراقبة الرسائل التي يتم إرسالها لجهازك أو حذفها بدون عرضها لك."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"قراءة رسائل بث الخلية"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"السماح للتطبيق بقراءة رسائل بث الخلية التي يتلقاها هذا الجهاز. يتم تسليم اشعارات بث الخلية في بعض المواقع لتحذيرك من حالات طارئة. يمكن أن تتداخل التطبيقات الضارة مع أداء أو تشغيل الجهاز عندما يتم تلقي بث خلية طارئ."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"قراءة الخلاصات المشتركة"</string>
@@ -474,7 +478,7 @@
     <string name="permdesc_transmitIr" product="tablet" msgid="5358308854306529170">"للسماح للتطبيق باستخدام مرسل الأشعة تحت الحمراء الخاص بالجهاز اللوحي."</string>
     <string name="permdesc_transmitIr" product="tv" msgid="2752076865253892198">"‏للسماح للتطبيق باستخدام مُرسِل الأشعة تحت الحمراء في جهاز Android TV."</string>
     <string name="permdesc_transmitIr" product="default" msgid="7957763745020300725">"للسماح للتطبيق باستخدام مرسل الأشعة تحت الحمراء الخاص بالهاتف."</string>
-    <string name="permlab_setWallpaper" msgid="6627192333373465143">"تعيين الخلفية"</string>
+    <string name="permlab_setWallpaper" msgid="6627192333373465143">"ضبط الخلفية"</string>
     <string name="permdesc_setWallpaper" msgid="7373447920977624745">"للسماح للتطبيق بتعيين خلفية النظام."</string>
     <string name="permlab_setWallpaperHints" msgid="3278608165977736538">"تعديل حجم الخلفية"</string>
     <string name="permdesc_setWallpaperHints" msgid="8235784384223730091">"للسماح للتطبيق بتعيين تلميحات حجم خلفية النظام."</string>
@@ -536,7 +540,7 @@
     <string name="permdesc_imagesWrite" msgid="7073662756617474375">"للسماح للتطبيق بتعديل مجموعة صورك."</string>
     <string name="permlab_mediaLocation" msgid="8675148183726247864">"قراءة المواقع من مجموعة الوسائط التابعة لك"</string>
     <string name="permdesc_mediaLocation" msgid="2237023389178865130">"للسماح للتطبيق بقراءة المواقع من مجموعة الوسائط التابعة لك."</string>
-    <string name="biometric_dialog_default_title" msgid="881952973720613213">"التحقق من هويتك"</string>
+    <string name="biometric_dialog_default_title" msgid="881952973720613213">"إثبات هويتك"</string>
     <string name="biometric_error_hw_unavailable" msgid="645781226537551036">"معدّات المقاييس الحيوية غير متاحة."</string>
     <string name="biometric_error_user_canceled" msgid="2260175018114348727">"تم إلغاء المصادقة."</string>
     <string name="biometric_not_recognized" msgid="5770511773560736082">"لم يتم التعرف عليها."</string>
@@ -667,6 +671,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"للسماح للتطبيق بقراءة تهيئة \"عدم الإزعاج\" وكتابتها."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"بدء استخدام إذن العرض"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"للسماح للمالك ببدء استخدام الإذن لأحد التطبيقات. ولن تكون هناك حاجة إليه مطلقًا مع التطبيقات العادية."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"هدف اختصار أدوات تمكين الوصول"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"للسماح للتطبيق بتحديد هدف اختصار أدوات تمكين الوصول."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"تعيين قواعد كلمة المرور"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"للتحكم في الطول والأحرف المسموح بها في كلمات المرور وأرقام التعريف الشخصي في قفل الشاشة."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"مراقبة محاولات إلغاء قفل الشاشة"</string>
@@ -1155,7 +1161,7 @@
     <string name="Midnight" msgid="5630806906897892201">"منتصف الليل"</string>
     <string name="elapsed_time_short_format_mm_ss" msgid="4431555943828711473">"<xliff:g id="MINUTES">%1$02d</xliff:g>:<xliff:g id="SECONDS">%2$02d</xliff:g>"</string>
     <string name="elapsed_time_short_format_h_mm_ss" msgid="1846071997616654124">"<xliff:g id="HOURS">%1$d</xliff:g>:<xliff:g id="MINUTES">%2$02d</xliff:g>:<xliff:g id="SECONDS">%3$02d</xliff:g>"</string>
-    <string name="selectAll" msgid="6876518925844129331">"تحديد الكل"</string>
+    <string name="selectAll" msgid="6876518925844129331">"اختيار الكل"</string>
     <string name="cut" msgid="3092569408438626261">"قص"</string>
     <string name="copy" msgid="2681946229533511987">"نسخ"</string>
     <string name="failed_to_copy_to_clipboard" msgid="1833662432489814471">"تعذّر النسخ في الحافظة"</string>
@@ -1346,7 +1352,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"اتصال"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"جميع الشبكات"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"‏هل تريد السماح لشبكات Wi‑Fi المقترحة؟"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> الشبكات المقترحة. قد يتم توصيل الجهاز تلقائيًا."</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"شبكات <xliff:g id="NAME">%s</xliff:g> المقترحة - قد يتم توصيل الجهاز تلقائيًا."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"سماح"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"لا، شكرًا"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"‏سيتم تشغيل شبكة Wi-Fi تلقائيًا."</string>
@@ -1444,11 +1450,13 @@
     <string name="usb_power_notification_message" msgid="4647527153291917218">"جارٍ شحن الجهاز المتصل. انقر لعرض خيارات أكثر."</string>
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"تم اكتشاف ملحق صوتي تناظري"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"الجهاز الذي تم توصيله بالهاتف غير متوافق معه. انقر للحصول على المزيد من المعلومات."</string>
-    <string name="adb_active_notification_title" msgid="6729044778949189918">"‏تم توصيل تصحيح أخطاء USB"</string>
-    <string name="adb_active_notification_message" msgid="7463062450474107752">"‏انقر لإيقاف تصحيح أخطاء USB."</string>
+    <string name="adb_active_notification_title" msgid="6729044778949189918">"‏تم توصيل تصحيح أخطاء الجهاز عبر USB"</string>
+    <string name="adb_active_notification_message" msgid="7463062450474107752">"‏انقر لإيقاف تصحيح أخطاء الجهاز عبر USB."</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"‏اختيار إيقاف تصحيح أخطاء USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"تم تفعيل وضع \"مفعّل الاختبار\""</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"يمكنك إجراء إعادة ضبط على إعدادات المصنع لإيقاف وضع \"مفعِّل اختبار\"."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"وحدة التحكّم التسلسلية مفعّلة"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"الأداء متأثر. لإيقاف وحدة التحكّم، تحقّق من برنامج الإقلاع."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"‏السوائل والشوائب في منفذ USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"‏تمّ إيقاف منفذ USB تلقائيًا. انقُر لمعرفة المزيد من المعلومات."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"‏مسموح باستخدام منفذ USB"</string>
@@ -2026,8 +2034,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"غير مصنفة"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"لقد عيَّنت أهمية هذه الإشعارات."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"هذه الرسالة مهمة نظرًا لأهمية الأشخاص المعنيين."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"هل تسمح لـ <xliff:g id="APP">%1$s</xliff:g> بإنشاء مستخدم جديد باستخدام <xliff:g id="ACCOUNT">%2$s</xliff:g>؟"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"هل تسمح لـ <xliff:g id="APP">%1$s</xliff:g> بإنشاء مستخدم جديد باستخدام <xliff:g id="ACCOUNT">%2$s</xliff:g> (يوجد مستخدم بهذا الحساب مسبقًا)؟"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"هل تسمح لتطبيق <xliff:g id="APP">%1$s</xliff:g> بإنشاء مستخدم جديد باستخدام <xliff:g id="ACCOUNT">%2$s</xliff:g> (يوجد مستخدم بهذا الحساب مسبقًا)؟"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"هل تسمح لتطبيق <xliff:g id="APP">%1$s</xliff:g> بإنشاء مستخدم جديد باستخدام <xliff:g id="ACCOUNT">%2$s</xliff:g> ؟"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"إضافة لغة"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"تفضيل المنطقة"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"اكتب اسم اللغة"</string>
diff --git a/core/res/res/values-as/strings.xml b/core/res/res/values-as/strings.xml
index 446575b..70d9713 100644
--- a/core/res/res/values-as/strings.xml
+++ b/core/res/res/values-as/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"এপটোক এছএমএছ বাৰ্তাবোৰ পাবলৈ আৰু প্ৰক্ৰিয়া সম্পন্ন কৰিবলৈ অনুমতি দিয়ে৷ ইয়াৰ অৰ্থ এইটোৱেই যে এপটোৱে আপোনাক বাৰ্তাবোৰ নেদেখুৱাকৈয়ে আপোনাৰ ডিভাইচলৈ পঠিওৱা বাৰ্তাবোৰ নিৰীক্ষণ কৰিব বা মচিব পাৰে৷"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"পাঠ বার্তা (এমএমএছ) বোৰ লাভ কৰক"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"এমএমএছ বার্তাবোৰ লাভ আৰু ইয়াৰ প্ৰক্ৰিয়া সম্পন্ন কৰিবলৈ এপক অনুমতি দিয়ে। ইয়াৰ অৰ্থ হৈছে এই এপে আপোনাৰ ডিভাইচলৈ প্ৰেৰণ কৰা বার্তাসমূহ আপোনাক নেদেখুৱাকৈয়ে পৰ্যবেক্ষণ আৰু মচিব পাৰে।"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"চেল সম্প্ৰচাৰৰ বার্তাবোৰ পঢ়ক"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"আপোনাৰ ডিভাইচে লাভ কৰা চেল সম্প্ৰচাৰৰ বার্তাবোৰ পঢ়িবলৈ এপক অনুমতি দিয়ে। আপোনাক জৰুৰীকালীন পৰিস্থিতিবোৰত সর্তক কৰিবলৈ চেল সম্প্ৰচাৰৰ বার্তাবোৰ প্ৰেৰণ কৰা হয়। জৰুৰীকালীন চেল সম্প্ৰচাৰ লাভ কৰাৰ সময়ত আপোনাৰ ডিভাইচৰ কাৰ্যদক্ষতা বা কাৰ্যপ্ৰণালীত ক্ষতিকাৰক এপবোৰে হস্তক্ষেপ কৰিব পাৰে।"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"আপুনি সদস্যভুক্ত হোৱা ফীডসমূহ পঢ়ক"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"অসুবিধা নিদিবৰ কনফিগাৰেশ্বনক পঢ়িবলৈ আৰু সালসলনি কৰিবলৈ এপটোক অনুমতি দিয়ে।"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"চোৱাৰ অনুমতিৰ ব্যৱহাৰ আৰম্ভ কৰক"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ধাৰকক কোনো এপৰ বাবে অনুমতিৰ ব্যৱহাৰ আৰম্ভ কৰিবলৈ দিয়ে। সাধাৰণ এপ্‌সমূহৰ বাবে কেতিয়াও প্ৰয়োজন হ’ব নালাগে।"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"সাধ্য সুবিধাসমূহৰ শ্বৰ্টকাট লক্ষ্য"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"সাধ্য সুবিধাসমূহৰ শ্বৰ্টকাট লক্ষ্য নির্ধাৰণ কৰিবলৈ এটা এপক অনুমতি দিয়ে।"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"পাছৱর্ডৰ নিয়ম ছেট কৰক"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"স্ক্ৰীণ লক পাছৱৰ্ড আৰু পিনৰ দৈর্ঘ্য আৰু কি কি আখৰ ব্যৱহাৰ কৰিব পাৰে তাক নিয়ন্ত্ৰণ কৰক।"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"স্ক্ৰীণ আনলক কৰা প্ৰয়াসবোৰ পৰ্যবেক্ষণ কৰিব পাৰে"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"ইউএছবি ডিবাগিং অক্ষম কৰিবলৈ বাছনি কৰক।"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"টেষ্ট হাৰনেছ ম’ড সক্ষম কৰা আছে"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"টেষ্ট হাৰনেছ ম’ড অক্ষম কৰিবলৈ ফেক্টৰী ৰিছেট কৰক।"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"ক্ৰমিক কনছ’ল সক্ষম কৰা আছে"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"কাৰ্যক্ষমতা প্ৰভাৱিত হৈছে। অক্ষম কৰিবলৈ বুটল’ডাৰ পৰীক্ষা কৰক।"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"ইউএছবি প’ৰ্টত তৰল বা ধূলি-মাকতি আছে"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"ইউএছবি প’ৰ্ট স্বয়ংক্ৰিয়ভাৱে অক্ষম কৰা হয়। অধিক জানিবৰ বাবে টিপক।"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"ইউএছবি প’ৰ্ট ব্যৱহাৰ কৰাত সমস্যা নাই"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"শ্ৰেণীবদ্ধ নকৰা"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"এই জাননীবোৰৰ গুৰুত্ব আপুনি ছেট কৰব লাগিব।"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"এই কার্যৰ সৈতে জড়িত থকা লোকসকলক ভিত্তি কৰি এইয়া গুৰুত্বপূর্ণ বুলি বিবেচনা কৰা হৈছ।"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> ক <xliff:g id="ACCOUNT">%2$s</xliff:g>ৰ জৰিয়তে নতুন ব্য়ৱহাৰকাৰী সৃষ্টি কৰিবলৈ অনুমতি দিবনে?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g>ক <xliff:g id="ACCOUNT">%2$s</xliff:g>ৰ (এই একাউন্টৰ এজন ব্য়ৱহাৰকাৰী ইতিমধ্যে আছে) জৰিয়তে নতুন ব্য়ৱহাৰকাৰী সৃষ্টি কৰিবলৈ অনুমতি দিবনে?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g>ক <xliff:g id="ACCOUNT">%2$s</xliff:g>ৰ (এই একাউণ্টটোৰ এজন ব্যৱহাৰকাৰী ইতিমধ্যে আছে) জৰিয়তে এজন নতুন ব্যৱহাৰকাৰী সৃষ্টি কৰিবলৈ অনুমতি দিবনে ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g>ক <xliff:g id="ACCOUNT">%2$s</xliff:g>ৰ জৰিয়তে এজন নতুন ব্যৱহাৰকাৰী সৃষ্টি কৰিবলৈ অনুমতি দিবনে?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ভাষা যোগ কৰক"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"অঞ্চলৰ অগ্ৰাধিকাৰ"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ভাষাৰ নাম লিখক"</string>
diff --git a/core/res/res/values-az/strings.xml b/core/res/res/values-az/strings.xml
index 6e93a97..5d09250 100644
--- a/core/res/res/values-az/strings.xml
+++ b/core/res/res/values-az/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Tətbiqə MMS mesajlarını almaq və emal etmək icazəsi verir. Bu o deməkdir ki, tətbiq sizin mesajlarınızı sizə göstərmədən monitorinq edə və ya silə bilər."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"mətn mesajlarını qəbul edir (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Tətbiqə MMS mesajlarını qəbul və emal üçün imkan verir. Bu o deməkdir ki, bu tətbiq sizə göstərmədən cihazınıza göndərilən mesajları silə bilər."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"mobil yayım mesajlarını oxuyur"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Tətbiqə telefonunuz tərəfindən alınmış yayım mesajlarını oxuma icazəsi verir. Telefon yayımı bəzi məkanlarda olan fövqəladə hadisələrlə bağlı sizi xəbərdar etmək üçün qəbul edilir. Zərərli tətbiqlər təcili mobil yayım qəbul edildiyi zaman telefonunun performansına və əməliyyatına müdaxilə edə bilər."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"abunə olunmuş xəbərləri oxuyur"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Tətbiqə \"Narahat Etməyin\" konfiqurasiyasını oxumağa və yazmağa icazə verin."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"Baxış icazəsinin istifadəsinə başlayın"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Sahibinə tətbiqin icazədən istifadəsinə başlamağa imkan verir. Adi tətbiqlər üçün heç vaxt tələb edilmir."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"əlçatımlılıq qısayolunun hədəfi"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Tətbiqə əlçatımlılıq qısayolunun hədəfini müəyyən etməyə imkan verir."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Parol qaydalarını təyin edin"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Ekran kilidinin parolu və PINlərində icazə verilən uzunluq və simvollara nəzarət edin."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Ekranı kiliddən çıxarmaq üçün edilən cəhdlərə nəzarət edin"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USb debaqı deaktivasiya etməyi seçin."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test Rejimi aktivdir"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Test Rejimini deaktiv etmək üçün fabrika ayarlarına sıfırlayın."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Ardıcıl konsol aktiv edildi"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performansa təsir edir. Deaktiv etmək üçün yükləyicini yoxlayın."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB portuna maye sızıb və ya qırılıb"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB portu avtomatik deaktiv edildi. Ətraflı məlumat üçün klikləyin."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB portundan istifadə etmək üçün OK"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Kateqoriyasız"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Bildirişlərin əhəmiyyətini Siz ayarlaryırsınız."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"İnsanlar cəlb olunduğu üçün bu vacibdir."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> tətbiqinə <xliff:g id="ACCOUNT">%2$s</xliff:g> hesabı ilə yeni İstifadəçi yaratmağa icazə verilsin?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> tətbiqinə<xliff:g id="ACCOUNT">%2$s</xliff:g> (bu hesab ilə İstifadəçi artıq mövcuddur) hesabı ilə yeni İstifadəçi yaratmağa icazə verilsin?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> tətbiqinə <xliff:g id="ACCOUNT">%2$s</xliff:g> (artıq bu hesabı olan İstifadəçi mövcuddur) ilə yeni İstifadəçi yaratmağa icazə verilsin?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> tətbiqinə <xliff:g id="ACCOUNT">%2$s</xliff:g> ilə yeni İstifadəçi yartmağa icazə verilsin?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Dil əlavə edin"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Region seçimi"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Dil adını daxil edin"</string>
diff --git a/core/res/res/values-b+sr+Latn/strings.xml b/core/res/res/values-b+sr+Latn/strings.xml
index e14139c..5891bae 100644
--- a/core/res/res/values-b+sr+Latn/strings.xml
+++ b/core/res/res/values-b+sr+Latn/strings.xml
@@ -27,7 +27,7 @@
     <string name="terabyteShort" msgid="231613018159186962">"TB"</string>
     <string name="petabyteShort" msgid="5637816680144990219">"PB"</string>
     <string name="fileSizeSuffix" msgid="8897567456150907538">"<xliff:g id="NUMBER">%1$s</xliff:g> <xliff:g id="UNIT">%2$s</xliff:g>"</string>
-    <string name="untitled" msgid="4638956954852782576">"&lt;Bez naslova&gt;"</string>
+    <string name="untitled" msgid="4638956954852782576">"&lt;Bez imena&gt;"</string>
     <string name="emptyPhoneNumber" msgid="7694063042079676517">"(Nema broja telefona)"</string>
     <string name="unknownName" msgid="6867811765370350269">"Nepoznato"</string>
     <string name="defaultVoiceMailAlphaTag" msgid="2660020990097733077">"Glasovna pošta"</string>
@@ -347,6 +347,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Dozvoljava aplikaciji da prima i obrađuje SMS poruke. To znači da aplikacija može da nadgleda ili briše poruke koje se šalju uređaju, a da vam ih ne prikaže."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"prijem tekstualnih poruka (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Dozvoljava aplikaciji da prima i obrađuje MMS poruke. To znači da aplikacija može da nadgleda ili briše poruke koje se šalju uređaju, a da vam ih ne prikaže."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"čitanje poruka info servisa"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Omogućava aplikaciji da čita poruke info servisa koje uređaj prima. Upozorenja info servisa se na nekim lokacijama primaju kao upozorenja na hitne slučajeve. Zlonamerne aplikacije mogu da utiču na učinak ili ometaju funkcionisanje uređaja kada se primi poruka info servisa o hitnom slučaju."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"čitanje prijavljenih fidova"</string>
@@ -658,6 +662,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Dozvoljava aplikaciji da čita i upisuje konfiguraciju podešavanja Ne uznemiravaj."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"početak korišćenja dozvole za pregled"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Dozvoljava vlasniku da započne korišćenje dozvole za aplikaciju. Nikada ne bi trebalo da bude potrebna za uobičajene aplikacije."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cilj prečice za pristupačnost"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Dozvoljava aplikaciji da definiše cilj prečice za pristupačnost."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Podešavanje pravila za lozinku"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontroliše dužinu i znakove dozvoljene u lozinkama i PIN-ovima za zaključavanje ekrana."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Nadgledajte pokušaje otključavanja ekrana"</string>
@@ -1383,6 +1389,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Izaberite da biste onemogućili otklanjanja grešaka sa USB-a."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Omogućen je režim probnog korišćenja"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Obavite resetovanje na fabrička podešavanja da biste onemogućili režim probnog korišćenja."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serijska konzola je omogućena"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Učinak je smanjen. Da biste onemogući konzolu, proverite pokretački program."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Tečnost ili nečistoća u USB portu"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB port je automatski isključen. Dodirnite da biste saznali više."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Korišćenje USB porta je dozvoljeno"</string>
@@ -1924,8 +1932,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Nekategorizovano"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Vi podešavate važnost ovih obaveštenja."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ovo je važno zbog ljudi koji učestvuju."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Želite li da dozvolite aplikaciji <xliff:g id="APP">%1$s</xliff:g> da napravi novog korisnika za <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Želite li da dozvolite aplikaciji <xliff:g id="APP">%1$s</xliff:g> da napravi novog korisnika za <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik sa ovim nalogom već postoji)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Želite li da dozvolite da <xliff:g id="APP">%1$s</xliff:g> napravi novog korisnika sa nalogom <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik sa tim nalogom već postoji)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Želite li da dozvolite da <xliff:g id="APP">%1$s</xliff:g> napravi novog korisnika sa nalogom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Dodajte jezik"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Podešavanje regiona"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Unesite naziv jezika"</string>
diff --git a/core/res/res/values-be/strings.xml b/core/res/res/values-be/strings.xml
index a71eef0..6fdc8f1 100644
--- a/core/res/res/values-be/strings.xml
+++ b/core/res/res/values-be/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Дазваляе прыкладанням атрымліваць і апрацоўваць SMS-паведамленні. Гэта значыць, што прыкладанне можа кантраляваць або выдаляць паведамленні, адпраўленыя на прыладу, не паказваючы іх вам."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"атрыманне тэкставых паведамленняў (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Дазваляе прыкладанням атрымліваць і апрацоўваць MMS-паведамленнi. Гэта значыць, што прыкладанне можа кантраляваць або выдаляць паведамленні, адпраўленыя на прыладу, не паказваючы іх вам."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"чытаць паведамленні базавай станцыі"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Дазваляе прыкладанню чытаць паведамленні базавай станцыі, атрыманыя прыладай. Папярэджанні базавай станцыі дасылаюцца ў некаторыя месцы, каб папярэдзіць вас аб надзвычайных сітуацыях. Шкоднасныя прыкладанні могуць уплываць на прадукцыйнасць ці працу прылады пры атрыманні паведамлення базавай станцыі аб надзвычайнай сітуацыі."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"чытаць падпісаныя каналы"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Дазваляе праграме чытаць і выконваць запіс у канфігурацыю рэжыму «Не турбаваць»."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"запусціць выкарыстанне дазволаў на прагляд"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Дазваляе трымальніку запусціць выкарыстанне дазволаў праграмай. Не патрэбна для звычайных праграм."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"Аб\'екты хуткага доступу да спецыяльных магчымасцей"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Праграма зможа вызначаць аб\'екты хуткага доступу да спецыяльных магчымасцей."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Устанавіць правілы паролю"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Кіраваць даўжынёй і сімваламі, дазволенымі пры ўводзе пароляў і PIN-кодаў блакіроўкі экрана."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Сачыць за спробамі разблакіроўкі экрана"</string>
@@ -1302,7 +1308,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Падключыцца"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Усе сеткі"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Дазволіць падключэнне да прапанаваных сетак Wi‑Fi?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Праграма \"<xliff:g id="NAME">%s</xliff:g>\" прапанавала сеткі. Прылада можа падключыцца аўтаматычна."</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Праграма \"<xliff:g id="NAME">%s</xliff:g>\" прапанавала сеткі. Прылада можа падключыцца да ніх аўтаматычна."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Дазволіць"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Не, дзякуй"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi уключыцца аўтаматычна"</string>
@@ -1389,7 +1395,7 @@
     <string name="no_permissions" msgid="7283357728219338112">"Дазволу не патрабуецца"</string>
     <string name="perm_costs_money" msgid="4902470324142151116">"за гэта можа спаганяцца плата"</string>
     <string name="dlg_ok" msgid="7376953167039865701">"ОК"</string>
-    <string name="usb_charging_notification_title" msgid="1595122345358177163">"Зарадка гэтай прылады праз USB"</string>
+    <string name="usb_charging_notification_title" msgid="1595122345358177163">"Прылада зараджаецца праз USB"</string>
     <string name="usb_supplying_notification_title" msgid="4631045789893086181">"Зарадка падключанай прылады праз USB"</string>
     <string name="usb_mtp_notification_title" msgid="4238227258391151029">"Перадача файлаў праз USB"</string>
     <string name="usb_ptp_notification_title" msgid="5425857879922006878">"Перадача фота (PTP) праз USB"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Выберыце, каб адключыць адладку USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Тэставы рэжым уключаны"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Каб выключыць тэставы рэжым, скіньце налады да заводскіх значэнняў."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Паслядоўная кансоль уключана"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Паказчык эфектыўнасці змяніўся. Каб выключыць кансоль, праверце загрузчык."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Вадкасць або смецце ў порце USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Порт USB аўтаматычна адключаны. Каб даведацца больш, націсніце тут."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Порт USB можна выкарыстоўваць"</string>
@@ -1720,8 +1728,8 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"<xliff:g id="SERVICE_NAME">%1$s</xliff:g> быў адключаны з дапамогай камбінацыі хуткага доступу для спецыяльных магчымасцей"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Каб карыстацца сэрвісам \"<xliff:g id="SERVICE_NAME">%1$s</xliff:g>\", націсніце і ўтрымлівайце на працягу трох секунд абедзве клавішы гучнасці"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Выберыце службу для выкарыстання пры націску кнопкі \"Спецыяльныя магчымасці\":"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"З дапамогай жэста спецыяльных магчымасцей (правесці двума пальцамі па экране знізу ўверх) выберыце службу для выкарыстання:"</string>
-    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"З дапамогай жэста спецыяльных магчымасцей (правесці трыма пальцамі па экране знізу ўверх) выберыце службу для выкарыстання:"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Выберыце службу, дзе будзе выкарыстоўвацца жэст спецыяльных магчымасцей (правесці двума пальцамі па экране знізу ўверх):"</string>
+    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Выберыце службу, дзе будзе выкарыстоўвацца жэст спецыяльных магчымасцей (правесці двума пальцамі па экране знізу ўверх):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Каб пераключыцца на другую службу, націсніце і ўтрымлівайце кнопку спецыяльных магчымасцей."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Каб пераключыцца на другую службу, правядзіце ўверх двума пальцамі, утрымліваючы іх на экране."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Каб пераключыцца на іншую службу, правядзіце ўверх трыма пальцамі, утрымліваючы іх на экране."</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Некатэгарызаванае"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Вы задалі важнасць гэтых апавяшчэнняў."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Гэта важна, бо з гэтым звязаны пэўныя людзі."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Дазволіць <xliff:g id="APP">%1$s</xliff:g> стварыць новага Карыстальніка з уліковым запісам <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Дазволіць <xliff:g id="APP">%1$s</xliff:g> стварыць новага Карыстальніка з уліковым запісам <xliff:g id="ACCOUNT">%2$s</xliff:g> (Карыстальнік з гэтым уліковым запісам ужо існуе)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Дазволіць праграме \"<xliff:g id="APP">%1$s</xliff:g>\" стварыць новага Карыстальніка з уліковым запісам <xliff:g id="ACCOUNT">%2$s</xliff:g> (Карыстальнік з гэтым уліковым запісам ужо існуе)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Дазволіць праграме \"<xliff:g id="APP">%1$s</xliff:g>\" стварыць новага Карыстальніка з уліковым запісам <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Дадаць мову"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Параметры рэгіёна"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Увядзіце назву мовы"</string>
diff --git a/core/res/res/values-bg/strings.xml b/core/res/res/values-bg/strings.xml
index 2c6550d..e5fb7e8 100644
--- a/core/res/res/values-bg/strings.xml
+++ b/core/res/res/values-bg/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Разрешава на приложението да получава и обработва SMS съобщения. Това означава, че то може да наблюдава или изтрива изпратените до устройството ви, без да ви ги покаже."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"получаване на текстови съобщения (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Разрешава на приложението да получава и обработва MMS съобщения. Това означава, че то може да наблюдава или изтрива изпратените до устройството ви, без да ви ги покаже."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"четене на съобщения с клетъчно излъчване"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Разрешава на приложението да чете съобщения с клетъчно излъчване, получени от устройството ви. Сигналите с клетъчно излъчване се получават на някои местоположения, за да ви предупредят за спешни ситуации. Злонамерените приложения могат да възпрепятстват изпълнението или работата на устройството ви при получаване на такова спешно излъчване."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"четене на емисиите с абонамент"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Предоставя на приложението достъп за четене и запис до конфигурацията на „Не безпокойте“."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"стартиране на прегледа на използваните разрешения"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Разрешава на притежателя да стартира прегледа на използваните разрешения за дадено приложение. Нормалните приложения би трябвало никога да не се нуждаят от това."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"цел на прекия път към функцията за достъпност"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Разрешава на приложението да определя целта на прекия път към функцията за достъпност."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Задаване на правила за паролата"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Контролира дължината и разрешените знаци за паролите и ПИН кодовете за заключване на екрана."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Наблюдаване на опитите за отключване на екрана"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Изберете, за да деактивирате отстраняването на грешки през USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Режимът за тестова среда е активиран"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Възстановете фабричните настройки, за да деактивирате режима за тестова среда."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Серийната конзола е активирана"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Ефективността е засегната. За да деактивирате, проверете програмата за първоначално зареждане."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Течност или замърсяване в USB порта"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB портът е деактивиран автоматично. Докоснете, за да научите повече."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Можете да използвате USB порта"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Некатегоризирани"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Зададохте важността на тези известия."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Това е важно заради участващите хора."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Да се разреши ли на <xliff:g id="APP">%1$s</xliff:g> да създаде нов потребител с профила <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Да се разреши ли на <xliff:g id="APP">%1$s</xliff:g> да създаде нов потребител с профила <xliff:g id="ACCOUNT">%2$s</xliff:g> (вече съществува потребител с този профил)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Да се разреши ли на <xliff:g id="APP">%1$s</xliff:g> да създаде нов потребител с профила <xliff:g id="ACCOUNT">%2$s</xliff:g> (вече съществува потребител с този профил)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Да се разреши ли на <xliff:g id="APP">%1$s</xliff:g> да създаде нов потребител с профила <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Добавяне на език"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Предпочитание за региона"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Въведете име на език"</string>
diff --git a/core/res/res/values-bn/strings.xml b/core/res/res/values-bn/strings.xml
index 7f5a3cc..651ed4d 100644
--- a/core/res/res/values-bn/strings.xml
+++ b/core/res/res/values-bn/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"অ্যাপ্লিকেশানটিকে এসএমএস প্রাপ্ত করার এবং প্রক্রিয়া করার অনুমতি দেয়৷ এর মানে হল অ্যাপ্লিকেশানটি আপনার ডিভাইস থেকে পাঠানো বার্তাগুলিকে পর্যবেক্ষণ করতে পারে এবং মুছতে পারে সেগুলিকে আপনাকে না দেখিয়ে৷"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"টেক্সট মেসেজ পান (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"অ্যাপ্লিকেশানটিকে MMS মেসেজ প্রাপ্ত করার এবং প্রক্রিয়া করার অনুমতি দেয়৷ এর মানে হল অ্যাপ্লিকেশানটি আপনার ডিভাইস থেকে পাঠানো মেসেজগুলিকে পর্যবেক্ষণ করতে পারে এবং মুছতে পারে সেগুলিকে আপনাকে না দেখিয়ে৷"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"সেল সম্প্রচার মেসেজ পড়ুন"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"আপনার ডিভাইস দ্বারা প্রাপ্ত সেল সম্প্রচার পড়তে অ্যাপ্লিকেশানটিকে অনুমতি দেয়৷ কয়েকটি স্থানে আপনাকে জরুরি অবস্থার জন্য সতর্ক করতে জরুরি সতর্কতাগুলি বিতরণ করা হয়৷ যখন একটি জরুরি সেল সম্প্রচার প্রাপ্ত হয় তখন ক্ষতিকারক অ্যাপ্লিকেশানগুলি আপনার ডিভাইসের কার্য সম্পাদনা বা কার্যকলাপে প্রতিবন্ধকতার সৃষ্টি করতে পারে৷"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"গ্রাহক হিসেবে নেওয়া ফিডগুলি পড়ে"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"অ্যাপটিকে \'বিরক্ত করবে না\' কনফিগারেশন পড়া এবং লেখার অনুমতি দেয়।"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"দেখার অনুমতি কাজে লাগানো শুরু করুন"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"কোনও অ্যাপের কোনও নির্দিষ্ট অনুমতির ব্যবহার শুরু করার ক্ষেত্রে হোল্ডারকে সাহায্য করে। সাধারণ অ্যাপের জন্য এটির পরিবর্তন হওয়ার কথা নয়।"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"অ্যাক্সেসিবিলিটির শর্টকাটের টার্গেট"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"এটি একটি অ্যাপকে অ্যাক্সেসিবিলিটির শর্টকাটের টার্গেটকে ব্যাখ্যা করতে অনুমতি দেয়।"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"পাসওয়ার্ড নিয়মগুলি সেট করে"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"স্ক্রিন লক করার পাসওয়ার্ডগুলিতে অনুমতিপ্রাপ্ত অক্ষর এবং দৈর্ঘ্য নিয়ন্ত্রণ করে৷"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"স্ক্রিন আনলক করার প্রচেষ্টাগুলির উপরে নজর রাখুন"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ডিবাগিং অক্ষম করতে বেছে নিন।"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"টেস্ট হারনেস মোড চালু আছে"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"টেস্ট হারনেস মোড বন্ধ করতে ফ্যাক্টরি রিসেট করুন।"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"সিরিয়াল কনসোল চালু করা হয়েছে"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"পারফর্ম্যান্সে এর প্রভাব পড়বে। চালানো বন্ধ করতে \'বুটলোডার\' প্রোগ্রামে এটিকে চেক করে দেখুন।"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"ইউএসবি পোর্টে তরল পদার্থ অথবা ধুলো কণা"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"ইউএসবি পোর্ট নিজে থেকে বন্ধ করা হবে। আরও জানতে ট্যাপ করুন।"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"ইউএসবি পোর্ট ব্যবহার করা যেতে পারে"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"বিভাগ নির্ধারিত নয়"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"আপনি এই বিজ্ঞপ্তিগুলির গুরুত্ব সেট করেছেন।"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"লোকজন জড়িত থাকার কারণে এটি গুরুত্বপূর্ণ।"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> কে <xliff:g id="ACCOUNT">%2$s</xliff:g> এর সাথে একজন নতুন ব্যবহারকারী তৈরি করার অনুমতি দেবেন কি?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> কে <xliff:g id="ACCOUNT">%2$s</xliff:g> (একজন ব্যবহারকারী এই অ্যাকাউন্টে ইতিমধ্যেই বিদ্যমান আছেন) এর সাথে একজন নতুন ব্যবহারকারী তৈরি করার অনুমতি দেবেন কি?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g>-এ (একজন ব্যবহারকারী এই অ্যাকাউন্টে আগে থেকেই রয়েছেন) একজন নতুন ব্যবহারকারী তৈরি করার অনুমতি <xliff:g id="APP">%1$s</xliff:g>-কে দেবেন?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g>-এ একজন নতুন ব্যবহারকারী তৈরি করার অনুমতি <xliff:g id="APP">%1$s</xliff:g>-কে দেবেন?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"একটি ভাষা যোগ করুন"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"পছন্দের অঞ্চল"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ভাষার নাম লিখুন"</string>
diff --git a/core/res/res/values-bs/strings.xml b/core/res/res/values-bs/strings.xml
index bc84e93..0695fb8 100644
--- a/core/res/res/values-bs/strings.xml
+++ b/core/res/res/values-bs/strings.xml
@@ -295,7 +295,7 @@
     <string name="permgrouprequest_calendar" msgid="289900767793189421">"Dozvoliti aplikaciji &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; da pristupi vašem kalendaru?"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"šalje i pregleda SMS poruke"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Dozvoliti aplikaciji &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; slanje i pregled SMS poruka?"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Dozvoliti aplikaciji &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; da šalje i pregleda SMS poruke?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Pohrana"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"pristupa slikama, medijskim fajlovima i fajlovima na vašem uređaju"</string>
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"Dozvoliti aplikaciji &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; da pristupa fotografijama, medijima i fajlovima na vašem uređaju?"</string>
@@ -347,6 +347,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Omogućava aplikaciji primanje i obradu SMS poruka. Ovo znači da aplikacija može pratiti ili brisati poruke poslane na vaš uređaj, a da vam ih pritom ne prikazuje."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"primanje tekstualnih poruka (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Omogućava aplikaciji prijem i obradu MMS poruka. Ovo znači da aplikacija može pratiti ili brisati poruke poslane na vaš uređaj, a da vam ih pritom ne prikazuje."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"čitanje poruka info servisa"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Omogućava aplikaciji čitanje poruka info servisa koje je primio vaš uređaj. Upozorenja koja emitira info servis se isporučuju na nekim lokacijama kako bi vas upozorila na vanredne situacije. Zlonamjerne aplikacije mogu ometati performanse ili rad vašeg uređaja kada primite informaciju o vanrednoj situaciji od info servisa."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"čitanje sadržaja na koje ste pretplaćeni"</string>
@@ -658,6 +662,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Omogućava aplikaciji da čita i upisuje konfiguraciju načina rada Ne ometaj."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"pokrenuti korištenje odobrenja za pregled"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Dozvoljava vlasniku da pokrene korištenje odobrenja za aplikaciju. Ne bi trebalo biti potrebno za obične aplikacije."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cilj prečice pristupačnosti"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Omogućava aplikaciji da definira cilj prečice pristupačnosti."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Postavljanje pravila za lozinke"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontrolira dužinu i znakove koji su dozvoljeni u lozinkama za zaključavanje ekrana i PIN-ovima."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Prati pokušaje otključavanja ekrana"</string>
@@ -1380,11 +1386,13 @@
     <string name="usb_power_notification_message" msgid="4647527153291917218">"Punjenje povezanog uređaja. Dodirnite za više opcija."</string>
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Otkriven je analogni periferni uređaj"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"Priključeni uređaj nije kompatibilan s ovim telefonom. Dodirnite da saznate više."</string>
-    <string name="adb_active_notification_title" msgid="6729044778949189918">"Otklanjanje grešaka putem uređaja spojenog na USB je uspostavljeno"</string>
+    <string name="adb_active_notification_title" msgid="6729044778949189918">"Otklanjanje grešaka putem USB-a je uspostavljeno"</string>
     <string name="adb_active_notification_message" msgid="7463062450474107752">"Dodirnite da isključite otklanjanje grešaka putem USB-a"</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Odaberite da onemogućite ispravljanje grešaka koristeći USB"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Omogućen način rada okvira za testiranje"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Izvršite vraćanje na fabričke postavke da onemogućite način rada okvira za testiranje."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serijska konzola omogućena"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Izvedba je otežana. Da onemogućite, provjerite program za učitavanje operativnog sistema."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Tečnost ili nečistoće u USB priključku"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB priključak je automatski onemogućen. Dodirnite da saznate više."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB priključak je sada sigurno koristiti"</string>
@@ -1926,8 +1934,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Nije kategorizirano"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Vi određujete značaj ovih obavještenja."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ovo je značajno zbog osoba koje su uključene."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Da li dozvoljavate aplikaciji <xliff:g id="APP">%1$s</xliff:g> da kreira novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Da li dozvoljavate da <xliff:g id="APP">%1$s</xliff:g> kreira novog korisnika za <xliff:g id="ACCOUNT">%2$s</xliff:g> (Korisnik sa ovim nalogom već postoji)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Dozvoliti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da kreira novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik s ovim računom već postoji)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Dozvoliti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da kreira novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Dodajte jezik"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Izbor regije"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Upišite ime jezika"</string>
diff --git a/core/res/res/values-ca/strings.xml b/core/res/res/values-ca/strings.xml
index 8334eca..8ef9a17 100644
--- a/core/res/res/values-ca/strings.xml
+++ b/core/res/res/values-ca/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permet que l\'aplicació rebi i processi missatges SMS. Això vol dir que l\'aplicació pot controlar o suprimir missatges que s\'han enviat al teu dispositiu sense mostrar-te\'ls."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"recepció de missatges de text (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permet que l\'aplicació rebi i processi missatges MMS. Això vol dir que l\'aplicació pot controlar o suprimir missatges que s\'han enviat al teu dispositiu sense mostrar-te\'ls."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"llegir missatges de difusió mòbil"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permet que l\'aplicació llegeixi missatges de difusió mòbil rebuts pel dispositiu. Les alertes de difusió mòbil s\'entreguen en algunes ubicacions per alertar de situacions d\'emergència. És possible que les aplicacions malicioses interfereixin en el rendiment o en el funcionament del dispositiu quan es rep una difusió mòbil d\'emergència."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"llegir els feeds als quals esteu subscrit"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permet que l\'aplicació llegeixi la configuració No molestis i hi escrigui."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"comença a utilitzar el permís de visualització"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permet que un propietari comenci a utilitzar el permís amb una aplicació. No s\'hauria de necessitar mai per a les aplicacions normals."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"objectiu de la drecera d\'accessibilitat"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permet a una aplicació definir l\'objectiu de la drecera d\'accessibilitat."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Definir les normes de contrasenya"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Permet controlar la longitud i el nombre de caràcters permesos a les contrasenyes i als PIN del bloqueig de pantalla."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Supervisar els intents de desbloqueig de la pantalla"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Selecciona per desactivar la depuració per USB"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"S\'ha activat el mode Agent de prova"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Si vols desactivar el mode Agent de prova, restableix les dades de fàbrica."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"S\'ha activat la consola de sèrie"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"El rendiment s\'ha vist afectat. Per desactivar-la, comprova el bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Hi ha líquid o pols al port USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"El port USB es desactiva automàticament. Toca per obtenir més informació."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Ja pots utilitzar el port USB"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sense classificar"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Has definit la importància d\'aquestes notificacions."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Aquest missatge és important per les persones implicades."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Concedeixes permís a <xliff:g id="APP">%1$s</xliff:g> per crear un usuari amb el compte <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Concedeixes permís a <xliff:g id="APP">%1$s</xliff:g> per crear un usuari amb el compte <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Ja hi ha un usuari amb aquest compte.)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Concedeixes permís a <xliff:g id="APP">%1$s</xliff:g> per crear un usuari amb el compte <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Ja hi ha un usuari amb aquest compte.)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Concedeixes permís a <xliff:g id="APP">%1$s</xliff:g> per crear un usuari amb el compte <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Afegeix un idioma"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferència de regió"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Nom de l\'idioma"</string>
diff --git a/core/res/res/values-cs/strings.xml b/core/res/res/values-cs/strings.xml
index 0d05709..72e7a86 100644
--- a/core/res/res/values-cs/strings.xml
+++ b/core/res/res/values-cs/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Umožňuje aplikaci přijmout a zpracovat zprávy SMS. Znamená to, že aplikace může sledovat zprávy odeslané do vašeho zařízení nebo je smazat, aniž by se vám zobrazily."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"příjem textových zpráv (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Umožňuje aplikaci přijmout a zpracovat zprávy MMS. Znamená to, že aplikace může sledovat zprávy odeslané do vašeho zařízení nebo je smazat, aniž by se vám zobrazily."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"čtení zpráv informačních služeb"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Umožňuje aplikaci číst zprávy informačních služeb přijaté ve vašem zařízení. Výstražná upozornění informačních služeb jsou v některých oblastech odesílána za účelem varování před výjimečnými událostmi. Škodlivé aplikace mohou narušit výkon či provoz vašeho zařízení během přijímání zpráv informačních služeb."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"čtení zdrojů přihlášených k odběru"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Umožňuje aplikaci číst a zapisovat konfiguraci režimu Nerušit."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"zahájení zobrazení využití oprávnění"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Umožňuje přístup zahájit využití oprávnění jiné aplikace. Běžné aplikace by toto oprávnění neměly nikdy požadovat."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cíl zkratky přístupnosti"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Umožňuje aplikaci definovat cíl zkratky přístupnosti."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Nastavit pravidla pro heslo"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Ovládání délky a znaků povolených v heslech a kódech PIN zámku obrazovky."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Sledovat pokusy o odemknutí obrazovky"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Vyberte, chcete-li zakázat ladění přes USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Režim správce testů je aktivní"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Chcete-li deaktivovat režim správce testů, restartujte zařízení do továrního nastavení."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Je zapnutá sériová konzole"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Toto má dopad na výkon. Chcete-li ji vypnout, zkontrolujte bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Kapalina nebo nečistota v portu USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Port USB byl automaticky deaktivován. Klepnutím zobrazíte další informace."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Port USB lze bezpečně použít"</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Neklasifikováno"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Důležitost oznámení určujete vy."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Tato zpráva je důležitá kvůli lidem zapojeným do konverzace."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Povolit aplikaci <xliff:g id="APP">%1$s</xliff:g> vytvořit nového uživatele s účtem <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Povolit aplikaci <xliff:g id="APP">%1$s</xliff:g> vytvořit nového uživatele s účtem <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Uživatel s tímto účtem již existuje.)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Povolit aplikaci <xliff:g id="APP">%1$s</xliff:g> vytvořit nového uživatele s účtem <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Uživatel s tímto účtem již existuje.)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Povolit aplikaci <xliff:g id="APP">%1$s</xliff:g> vytvořit nového uživatele s účtem <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Přidat jazyk"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferovaná oblast"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Zadejte název jazyka"</string>
diff --git a/core/res/res/values-da/strings.xml b/core/res/res/values-da/strings.xml
index 70a4646..88900a0 100644
--- a/core/res/res/values-da/strings.xml
+++ b/core/res/res/values-da/strings.xml
@@ -226,7 +226,7 @@
     <string name="global_actions" product="default" msgid="2406416831541615258">"Indstillinger for telefon"</string>
     <string name="global_action_lock" msgid="2844945191792119712">"Skærmlås"</string>
     <string name="global_action_power_off" msgid="4471879440839879722">"Sluk"</string>
-    <string name="global_action_emergency" msgid="7112311161137421166">"Nødopkald"</string>
+    <string name="global_action_emergency" msgid="7112311161137421166">"Nødsituation"</string>
     <string name="global_action_bug_report" msgid="7934010578922304799">"Fejlrapport"</string>
     <string name="global_action_logout" msgid="935179188218826050">"Afslut sessionen"</string>
     <string name="global_action_screenshot" msgid="8329831278085426283">"Screenshot"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Tillader, at appen kan modtage og behandle sms-beskeder. Det betyder, at appen kan overvåge eller slette de beskeder, der sendes til din enhed, uden at vise dem til dig."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"modtage tekstbeskeder (mms)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Tillader, at appen kan modtage og behandle mms-beskeder. Det betyder, at appen kan overvåge eller slette de beskeder, der sendes til din enhed, uden at vise dem til dig."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"læse Cell Broadcast-meddelelser"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Tillader, at appen læser Cell Broadcast-underretninger, der modtages af din enhed. I nogle områder sendes der Cell Broadcast-underretninger for at advare om nødsituationer. Ondsindede apps kan forstyrre ydelsen eller driften af ​din ​enhed, når der modtages en Cell Broadcast-meddelelse om en nødsituation."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"læse feeds, jeg abonnerer på"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Giver appen tilladelse til at læse og redigere konfigurationen af Forstyr ikke."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"start brugen at tilladelsesvisning"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Tillader, at brugeren kan bruge en tilladelse for en app. Dette bør aldrig være nødvendigt for almindelige apps."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"mål for hjælpefunktionsgenvej"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Tillader, at en app definerer målet for en hjælpefunktionsgenvej."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Angiv regler for adgangskoder"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Tjek længden samt tilladte tegn i adgangskoder og pinkoder til skærmlåsen."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Overvåg forsøg på oplåsning af skærm"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Vælg for at deaktivere USB-fejlretning."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Tilstanden Testsele er aktiveret"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Gendan fabriksindstillingerne for at deaktivere tilstanden Testsele."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Seriekonsollen er aktiveret"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Effektiviteten er påvirket. Deaktiver via bootloaderen."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Væske eller snavs i USB-porten"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-porten deaktiveres automatisk. Tryk for at få flere oplysninger."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB-porten kan bruges"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Uden kategori"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Du angiver, hvor vigtige disse notifikationer er."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Dette er vigtigt på grund af de personer, det handler om."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Vil du give <xliff:g id="APP">%1$s</xliff:g> tilladelse til at oprette en ny bruger med <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Vil du give <xliff:g id="APP">%1$s</xliff:g> tilladelse til at oprette en ny bruger med <xliff:g id="ACCOUNT">%2$s</xliff:g> (der findes allerede en bruger med denne konto)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Vil du give <xliff:g id="APP">%1$s</xliff:g> tilladelse til at oprette en ny bruger med <xliff:g id="ACCOUNT">%2$s</xliff:g> (der findes allerede en bruger med denne konto)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Vil du give <xliff:g id="APP">%1$s</xliff:g> tilladelse til at oprette en nye bruger med <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Tilføj et sprog"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Områdeindstilling"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Angiv sprog"</string>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index c7e381c..6bf5404 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"Zulassen, dass &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; auf deine Kontakte zugreift?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Standort"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"auf den Standort deines Geräts zugreifen"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"Zulassen, dass &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; den Gerätestandort abruft?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"Zulassen, dass die App &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; den Gerätestandort abruft?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"Die App hat nur Zugriff auf den Gerätestandort, solange du sie verwendest"</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"Zulassen, dass &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; &lt;b&gt;ständig&lt;/b&gt; auf deinen Standort zugreift?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"Die App hat gegenwärtig nur dann Zugriff auf den Gerätestandort, wenn du sie verwendest"</string>
@@ -292,7 +292,7 @@
     <string name="permgrouprequest_calendar" msgid="289900767793189421">"Zulassen, dass &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; auf deinen Kalender zugreift?"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"SMS senden und abrufen"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Zulassen, dass &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; SMS sendet und aufruft?"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Zulassen, dass die App &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; SMS sendet und aufruft?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Speicher"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"auf Fotos, Medien und Dateien auf deinem Gerät zugreifen"</string>
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"Zulassen, dass &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; auf Fotos, Medien und Dateien auf deinem Gerät zugreift?"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Ermöglicht der App, SMS zu empfangen und zu verarbeiten. Das bedeutet, dass die App an dein Gerät gesendete Nachrichten überwachen und löschen kann, ohne sie dir anzuzeigen."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"MMS empfangen"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Ermöglicht der App, MMS zu empfangen und zu verarbeiten. Das bedeutet, dass die App an dein Gerät gesendete Nachrichten überwachen und löschen kann, ohne sie dir anzuzeigen."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"Cell Broadcast-Nachrichten lesen"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Ermöglicht der App, von deinem Gerät empfangene Cell Broadcast-Nachrichten zu lesen. Cell Broadcast-Benachrichtigungen werden an einigen Standorten gesendet, um dich über Notfallsituationen zu informieren. Schädliche Apps können die Leistung oder den Betrieb deines Geräts beeinträchtigen, wenn eine Cell Broadcast-Notfallbenachrichtigung eingeht."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"Abonnierte Feeds lesen"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Ermöglicht der App Lese- und Schreibzugriff auf die \"Bitte nicht stören\"-Konfiguration"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"Mit der Verwendung der Anzeigeberechtigung beginnen"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Ermöglicht dem Inhaber, die Berechtigungsnutzung für eine App zu beginnen. Sollte für normale Apps nie benötigt werden."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"Ziel der Verknüpfung für Bedienungshilfen"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Ermöglicht einer App, das Ziel der Verknüpfung für Bedienungshilfen zu definieren."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Passwortregeln festlegen"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Zulässige Länge und Zeichen für Passwörter für die Displaysperre festlegen"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Versuche zum Entsperren des Displays überwachen"</string>
@@ -1361,7 +1367,9 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB-Debugging deaktivieren: auswählen"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test-Harnischmodus aktiviert"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Setz das Gerät auf die Werkseinstellungen zurück, um den Test-Harnischmodus zu deaktivieren."</string>
-    <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Flüssigkeiten oder Fremdkörper im USB-Port"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serielle Konsole aktiviert"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Leistung wird beeinflusst. Überprüfe Bootloader zum Deaktivieren."</string>
+    <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Flüssigkeit oder Fremdkörper im USB-Port"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Der USB-Port wird automatisch deaktiviert. Für weitere Informationen tippen."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB-Port kann wieder verwendet werden"</string>
     <string name="usb_contaminant_not_detected_message" msgid="2415791798244545292">"Das Smartphone erkennt keine Flüssigkeiten oder Fremdkörper mehr."</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Unkategorisiert"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Du hast die Wichtigkeit dieser Benachrichtigungen festgelegt."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Diese Benachrichtigung ist aufgrund der beteiligten Personen wichtig."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Möchtest du zulassen, dass <xliff:g id="APP">%1$s</xliff:g> einen neuen Nutzer mit <xliff:g id="ACCOUNT">%2$s</xliff:g> erstellt?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Möchtest du zulassen, dass <xliff:g id="APP">%1$s</xliff:g> einen neuen Nutzer mit <xliff:g id="ACCOUNT">%2$s</xliff:g> erstellt? Dieses Konto wird jedoch bereits von einem anderen Nutzer verwendet."</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Es gibt bereits einen Nutzer mit <xliff:g id="ACCOUNT">%2$s</xliff:g>. Möchtest du zulassen, dass <xliff:g id="APP">%1$s</xliff:g> einen neuen Nutzer mit diesem Konto erstellt?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Möchtest du zulassen, dass <xliff:g id="APP">%1$s</xliff:g> einen neuen Nutzer mit <xliff:g id="ACCOUNT">%2$s</xliff:g> erstellt?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Sprache hinzufügen"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Region auswählen"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Sprache eingeben"</string>
diff --git a/core/res/res/values-el/strings.xml b/core/res/res/values-el/strings.xml
index 18af40d..3570fc1 100644
--- a/core/res/res/values-el/strings.xml
+++ b/core/res/res/values-el/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Επιτρέπει στην εφαρμογή τη λήψη και την επεξεργασία μηνυμάτων SMS. Αυτό σημαίνει ότι η εφαρμογή θα μπορούσε να παρακολουθήσει ή να διαγράψει τα μηνύματα που αποστέλλονται στη συσκευή σας χωρίς αυτά να εμφανιστούν σε εσάς."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"λαμβάνει μηνύματα κειμένου (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Επιτρέπει στην εφαρμογή τη λήψη και την επεξεργασία μηνυμάτων MMS. Αυτό σημαίνει ότι η εφαρμογή θα μπορούσε να παρακολουθήσει ή να διαγράψει τα μηνύματα που αποστέλλονται στη συσκευή σας χωρίς αυτά να εμφανιστούν σε εσάς."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"διαβάζει μηνύματα που έχουν μεταδοθεί μέσω κινητού τηλεφώνου"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Επιτρέπει στην εφαρμογή την ανάγνωση μηνυμάτων που έχουν μεταδοθεί μέσω κινητού τηλεφώνου και έχουν ληφθεί από τη συσκευή σας. Ειδοποιήσεις που μεταδίδονται μέσω κινητού παραδίδονται σε ορισμένες τοποθεσίες για να σας προειδοποιήσουν για καταστάσεις έκτακτης ανάγκης. Κακόβουλες εφαρμογές ενδέχεται να παρεμποδίσουν την απόδοση ή τη λειτουργία της συσκευής σας κατά τη λήψη μετάδοσης μέσω κινητού σχετικά με μια επείγουσα κατάσταση."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"διαβάζει ροές δεδομένων στις οποίες έχετε εγγραφεί"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Επιτρέπει στην εφαρμογή την εγγραφή και τη σύνταξη διαμόρφωσης για τη λειτουργία \"Μην ενοχλείτε\"."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"έναρξη χρήσης άδειας προβολής"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Επιτρέπει στον κάτοχο να ξεκινήσει τη χρήση της άδειας για μια εφαρμογή. Δεν απαιτείται ποτέ για κανονικές εφαρμογές."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"στόχος συντόμευσης προσβασιμότητας"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Επιτρέπει σε μια εφαρμογή να καθορίσει τον στόχο της συντόμευσης προσβασιμότητας."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Ορισμός κανόνων κωδικού πρόσβασης"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Ελέγξτε την έκταση και τους επιτρεπόμενους χαρακτήρες σε κωδικούς πρόσβασης κλειδώματος οθόνης και PIN."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Παρακολούθηση προσπαθειών ξεκλειδώματος οθόνης"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Επιλογή για απενεργοποίηση του εντοπισμού σφαλμάτων USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Η λειτουργία περιβάλλοντος δοκιμών ενεργοποιήθηκε"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Εκτελέστε επαναφορά εργοστασιακών ρυθμίσεων για να απενεργοποιήσετε τη λειτουργία περιβάλλοντος δοκιμών."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Η σειριακή κονσόλα ενεργοποιήθηκε"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Η απόδοση επηρεάζεται. Για απενεργοποίηση, επιλέξτε το πρόγραμμα φόρτωσης εκκίνησης."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Υγρασία ή ακαθαρσίες στη θύρα USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Η θύρα USB απενεργοποιείται αυτόματα. Πατήστε για να μάθετε περισσότερα."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Αποδεκτή η χρήση της θύρας USB"</string>
@@ -1675,7 +1683,7 @@
     <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Επιλέξτε μια υπηρεσία που θα χρησιμοποιείται με την κίνηση προσβασιμότητας (σύρετε με δύο δάχτυλα προς τα επάνω από το κάτω μέρος της οθόνης):"</string>
     <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Επιλέξτε μια υπηρεσία που θα χρησιμοποιείται με την κίνηση προσβασιμότητας (σύρετε με τρία δάχτυλα προς τα επάνω από το κάτω μέρος της οθόνης):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Για εναλλαγή μεταξύ υπηρεσιών, αγγίξτε παρατεταμένα το κουμπί προσβασιμότητας."</string>
-    <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Για εναλλαγή μεταξύ υπηρεσιών, σύρετε παρατεταμένα με δύο δάχτυλα προς τα επάνω."</string>
+    <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Για εναλλαγή μεταξύ υπηρεσιών, σύρετε παρατεταμένα με δύο δάχτυλα προς τα επάνω και μην τα απομακρύνετε από την οθόνη."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Για εναλλαγή μεταξύ υπηρεσιών, σύρετε παρατεταμένα με τρία δάχτυλα προς τα επάνω."</string>
     <string name="accessibility_magnification_chooser_text" msgid="1227146738764986237">"Μεγιστοποίηση"</string>
     <string name="user_switched" msgid="3768006783166984410">"Τρέχων χρήστης <xliff:g id="NAME">%1$s</xliff:g>."</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Μη κατηγοριοποιημένο"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Μπορείτε να ρυθμίσετε τη βαρύτητα αυτών των ειδοποιήσεων."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Αυτό είναι σημαντικό λόγω των ατόμων που συμμετέχουν."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Να επιτραπεί στην εφαρμογή <xliff:g id="APP">%1$s</xliff:g> να δημιουργήσει έναν νέο χρήστη με το λογαριασμό <xliff:g id="ACCOUNT">%2$s</xliff:g>;"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Να επιτραπεί στην εφαρμογή <xliff:g id="APP">%1$s</xliff:g> να δημιουργήσει έναν νέο χρήστη με το λογαριασμό <xliff:g id="ACCOUNT">%2$s</xliff:g> (υπάρχει ήδη χρήστης με αυτόν το λογαριασμό);"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Επιτρέπετε στην εφαρμογή <xliff:g id="APP">%1$s</xliff:g> να δημιουργήσει έναν νέο χρήστη με τον λογαριασμό <xliff:g id="ACCOUNT">%2$s</xliff:g> (υπάρχει ήδη χρήστης με αυτόν τον λογαριασμό);"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Επιτρέπετε στην εφαρμογή <xliff:g id="APP">%1$s</xliff:g> να δημιουργήσει έναν νέο χρήστη με τον λογαριασμό <xliff:g id="ACCOUNT">%2$s</xliff:g>;"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Προσθήκη γλώσσας"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Προτίμηση περιοχής"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Εισαγ. όνομα γλώσσας"</string>
diff --git a/core/res/res/values-en-rAU/strings.xml b/core/res/res/values-en-rAU/strings.xml
index 2db3771..e1d9875 100644
--- a/core/res/res/values-en-rAU/strings.xml
+++ b/core/res/res/values-en-rAU/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Allows the app to receive and process SMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"receive text messages (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Allows the app to receive and process MMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"read mobile broadcast messages"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Allows the app to read mobile broadcast messages received by your device. Cell broadcast alerts are delivered in some locations to warn you of emergency situations. Malicious apps may interfere with the performance or operation of your device when an emergency mobile broadcast is received."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"read subscribed feeds"</string>
@@ -554,10 +558,10 @@
   <string-array name="fingerprint_error_vendor">
   </string-array>
     <string name="fingerprint_icon_content_description" msgid="2340202869968465936">"Fingerprint icon"</string>
-    <string name="permlab_manageFace" msgid="7262837876352591553">"manage Face Unlock hardware"</string>
+    <string name="permlab_manageFace" msgid="7262837876352591553">"manage face unlock hardware"</string>
     <string name="permdesc_manageFace" msgid="8919637120670185330">"Allows the app to invoke methods to add and delete facial templates for use."</string>
-    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use Face Unlock hardware"</string>
-    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use Face Unlock hardware for authentication"</string>
+    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use face unlock hardware"</string>
+    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use face unlock hardware for authentication"</string>
     <string name="face_recalibrate_notification_name" msgid="1913676850645544352">"Face unlock"</string>
     <string name="face_recalibrate_notification_title" msgid="4087620069451499365">"Re-enrol your face"</string>
     <string name="face_recalibrate_notification_content" msgid="5530308842361499835">"To improve recognition, please re-enrol your face"</string>
@@ -584,15 +588,15 @@
   <string-array name="face_acquired_vendor">
   </string-array>
     <string name="face_error_hw_not_available" msgid="396883585636963908">"Can’t verify face. Hardware not available."</string>
-    <string name="face_error_timeout" msgid="981512090365729465">"Try Face Unlock again."</string>
+    <string name="face_error_timeout" msgid="981512090365729465">"Try face unlock again."</string>
     <string name="face_error_no_space" msgid="2712120617457553825">"Can’t store new face data. Delete an old one first."</string>
     <string name="face_error_canceled" msgid="283945501061931023">"Face operation cancelled."</string>
-    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face Unlock cancelled by user."</string>
+    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face unlock cancelled by user."</string>
     <string name="face_error_lockout" msgid="3407426963155388504">"Too many attempts. Try again later."</string>
-    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face Unlock disabled."</string>
+    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face unlock disabled."</string>
     <string name="face_error_unable_to_process" msgid="4940944939691171539">"Can’t verify face. Try again."</string>
-    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up Face Unlock."</string>
-    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face Unlock is not supported on this device."</string>
+    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up face unlock."</string>
+    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face unlock is not supported on this device."</string>
     <string name="face_name_template" msgid="7004562145809595384">"Face <xliff:g id="FACEID">%d</xliff:g>"</string>
   <string-array name="face_error_vendor">
   </string-array>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Allows the app to read and write Do Not Disturb configuration."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"start view permission usage"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Allows the holder to start the permission usage for an app. Should never be needed for normal apps."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"accessibility shortcut target"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Allows an app to define the accessibility shortcut target."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Set password rules"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Control the length and the characters allowed in screen lock passwords and PINs."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitor screen unlock attempts"</string>
@@ -821,7 +827,7 @@
     <string name="lockscreen_pattern_wrong" msgid="4317955014948108794">"Try again"</string>
     <string name="lockscreen_password_wrong" msgid="5737815393253165301">"Try again"</string>
     <string name="lockscreen_storage_locked" msgid="9167551160010625200">"Unlock for all features and data"</string>
-    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum Face Unlock attempts exceeded"</string>
+    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum face unlock attempts exceeded"</string>
     <string name="lockscreen_missing_sim_message_short" msgid="5099439277819215399">"No SIM card"</string>
     <string name="lockscreen_missing_sim_message" product="tablet" msgid="151659196095791474">"No SIM card in tablet."</string>
     <string name="lockscreen_missing_sim_message" product="tv" msgid="3360993527792167595">"No SIM card in your Android TV device."</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Select to disable USB debugging."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test Harness Mode enabled"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Perform a factory reset to disable Test Harness Mode."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serial console enabled"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performance is impacted. To disable, check bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Liquid or debris in USB port"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB port is automatically disabled. Tap to learn more."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"OK to use USB port"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Uncategorised"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"You set the importance of these notifications."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"This is important because of the people involved."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Add a language"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Region preference"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Type language name"</string>
diff --git a/core/res/res/values-en-rCA/strings.xml b/core/res/res/values-en-rCA/strings.xml
index 839aaac..56b54d9 100644
--- a/core/res/res/values-en-rCA/strings.xml
+++ b/core/res/res/values-en-rCA/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Allows the app to receive and process SMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"receive text messages (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Allows the app to receive and process MMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"read mobile broadcast messages"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Allows the app to read mobile broadcast messages received by your device. Cell broadcast alerts are delivered in some locations to warn you of emergency situations. Malicious apps may interfere with the performance or operation of your device when an emergency mobile broadcast is received."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"read subscribed feeds"</string>
@@ -554,10 +558,10 @@
   <string-array name="fingerprint_error_vendor">
   </string-array>
     <string name="fingerprint_icon_content_description" msgid="2340202869968465936">"Fingerprint icon"</string>
-    <string name="permlab_manageFace" msgid="7262837876352591553">"manage Face Unlock hardware"</string>
+    <string name="permlab_manageFace" msgid="7262837876352591553">"manage face unlock hardware"</string>
     <string name="permdesc_manageFace" msgid="8919637120670185330">"Allows the app to invoke methods to add and delete facial templates for use."</string>
-    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use Face Unlock hardware"</string>
-    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use Face Unlock hardware for authentication"</string>
+    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use face unlock hardware"</string>
+    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use face unlock hardware for authentication"</string>
     <string name="face_recalibrate_notification_name" msgid="1913676850645544352">"Face unlock"</string>
     <string name="face_recalibrate_notification_title" msgid="4087620069451499365">"Re-enrol your face"</string>
     <string name="face_recalibrate_notification_content" msgid="5530308842361499835">"To improve recognition, please re-enrol your face"</string>
@@ -584,15 +588,15 @@
   <string-array name="face_acquired_vendor">
   </string-array>
     <string name="face_error_hw_not_available" msgid="396883585636963908">"Can’t verify face. Hardware not available."</string>
-    <string name="face_error_timeout" msgid="981512090365729465">"Try Face Unlock again."</string>
+    <string name="face_error_timeout" msgid="981512090365729465">"Try face unlock again."</string>
     <string name="face_error_no_space" msgid="2712120617457553825">"Can’t store new face data. Delete an old one first."</string>
     <string name="face_error_canceled" msgid="283945501061931023">"Face operation cancelled."</string>
-    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face Unlock cancelled by user."</string>
+    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face unlock cancelled by user."</string>
     <string name="face_error_lockout" msgid="3407426963155388504">"Too many attempts. Try again later."</string>
-    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face Unlock disabled."</string>
+    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face unlock disabled."</string>
     <string name="face_error_unable_to_process" msgid="4940944939691171539">"Can’t verify face. Try again."</string>
-    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up Face Unlock."</string>
-    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face Unlock is not supported on this device."</string>
+    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up face unlock."</string>
+    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face unlock is not supported on this device."</string>
     <string name="face_name_template" msgid="7004562145809595384">"Face <xliff:g id="FACEID">%d</xliff:g>"</string>
   <string-array name="face_error_vendor">
   </string-array>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Allows the app to read and write Do Not Disturb configuration."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"start view permission usage"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Allows the holder to start the permission usage for an app. Should never be needed for normal apps."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"accessibility shortcut target"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Allows an app to define the accessibility shortcut target."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Set password rules"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Control the length and the characters allowed in screen lock passwords and PINs."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitor screen unlock attempts"</string>
@@ -821,7 +827,7 @@
     <string name="lockscreen_pattern_wrong" msgid="4317955014948108794">"Try again"</string>
     <string name="lockscreen_password_wrong" msgid="5737815393253165301">"Try again"</string>
     <string name="lockscreen_storage_locked" msgid="9167551160010625200">"Unlock for all features and data"</string>
-    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum Face Unlock attempts exceeded"</string>
+    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum face unlock attempts exceeded"</string>
     <string name="lockscreen_missing_sim_message_short" msgid="5099439277819215399">"No SIM card"</string>
     <string name="lockscreen_missing_sim_message" product="tablet" msgid="151659196095791474">"No SIM card in tablet."</string>
     <string name="lockscreen_missing_sim_message" product="tv" msgid="3360993527792167595">"No SIM card in your Android TV device."</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Select to disable USB debugging."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test Harness Mode enabled"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Perform a factory reset to disable Test Harness Mode."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serial console enabled"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performance is impacted. To disable, check bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Liquid or debris in USB port"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB port is automatically disabled. Tap to learn more."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"OK to use USB port"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Uncategorised"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"You set the importance of these notifications."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"This is important because of the people involved."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Add a language"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Region preference"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Type language name"</string>
diff --git a/core/res/res/values-en-rGB/strings.xml b/core/res/res/values-en-rGB/strings.xml
index 2db3771..e1d9875 100644
--- a/core/res/res/values-en-rGB/strings.xml
+++ b/core/res/res/values-en-rGB/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Allows the app to receive and process SMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"receive text messages (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Allows the app to receive and process MMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"read mobile broadcast messages"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Allows the app to read mobile broadcast messages received by your device. Cell broadcast alerts are delivered in some locations to warn you of emergency situations. Malicious apps may interfere with the performance or operation of your device when an emergency mobile broadcast is received."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"read subscribed feeds"</string>
@@ -554,10 +558,10 @@
   <string-array name="fingerprint_error_vendor">
   </string-array>
     <string name="fingerprint_icon_content_description" msgid="2340202869968465936">"Fingerprint icon"</string>
-    <string name="permlab_manageFace" msgid="7262837876352591553">"manage Face Unlock hardware"</string>
+    <string name="permlab_manageFace" msgid="7262837876352591553">"manage face unlock hardware"</string>
     <string name="permdesc_manageFace" msgid="8919637120670185330">"Allows the app to invoke methods to add and delete facial templates for use."</string>
-    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use Face Unlock hardware"</string>
-    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use Face Unlock hardware for authentication"</string>
+    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use face unlock hardware"</string>
+    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use face unlock hardware for authentication"</string>
     <string name="face_recalibrate_notification_name" msgid="1913676850645544352">"Face unlock"</string>
     <string name="face_recalibrate_notification_title" msgid="4087620069451499365">"Re-enrol your face"</string>
     <string name="face_recalibrate_notification_content" msgid="5530308842361499835">"To improve recognition, please re-enrol your face"</string>
@@ -584,15 +588,15 @@
   <string-array name="face_acquired_vendor">
   </string-array>
     <string name="face_error_hw_not_available" msgid="396883585636963908">"Can’t verify face. Hardware not available."</string>
-    <string name="face_error_timeout" msgid="981512090365729465">"Try Face Unlock again."</string>
+    <string name="face_error_timeout" msgid="981512090365729465">"Try face unlock again."</string>
     <string name="face_error_no_space" msgid="2712120617457553825">"Can’t store new face data. Delete an old one first."</string>
     <string name="face_error_canceled" msgid="283945501061931023">"Face operation cancelled."</string>
-    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face Unlock cancelled by user."</string>
+    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face unlock cancelled by user."</string>
     <string name="face_error_lockout" msgid="3407426963155388504">"Too many attempts. Try again later."</string>
-    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face Unlock disabled."</string>
+    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face unlock disabled."</string>
     <string name="face_error_unable_to_process" msgid="4940944939691171539">"Can’t verify face. Try again."</string>
-    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up Face Unlock."</string>
-    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face Unlock is not supported on this device."</string>
+    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up face unlock."</string>
+    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face unlock is not supported on this device."</string>
     <string name="face_name_template" msgid="7004562145809595384">"Face <xliff:g id="FACEID">%d</xliff:g>"</string>
   <string-array name="face_error_vendor">
   </string-array>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Allows the app to read and write Do Not Disturb configuration."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"start view permission usage"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Allows the holder to start the permission usage for an app. Should never be needed for normal apps."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"accessibility shortcut target"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Allows an app to define the accessibility shortcut target."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Set password rules"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Control the length and the characters allowed in screen lock passwords and PINs."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitor screen unlock attempts"</string>
@@ -821,7 +827,7 @@
     <string name="lockscreen_pattern_wrong" msgid="4317955014948108794">"Try again"</string>
     <string name="lockscreen_password_wrong" msgid="5737815393253165301">"Try again"</string>
     <string name="lockscreen_storage_locked" msgid="9167551160010625200">"Unlock for all features and data"</string>
-    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum Face Unlock attempts exceeded"</string>
+    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum face unlock attempts exceeded"</string>
     <string name="lockscreen_missing_sim_message_short" msgid="5099439277819215399">"No SIM card"</string>
     <string name="lockscreen_missing_sim_message" product="tablet" msgid="151659196095791474">"No SIM card in tablet."</string>
     <string name="lockscreen_missing_sim_message" product="tv" msgid="3360993527792167595">"No SIM card in your Android TV device."</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Select to disable USB debugging."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test Harness Mode enabled"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Perform a factory reset to disable Test Harness Mode."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serial console enabled"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performance is impacted. To disable, check bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Liquid or debris in USB port"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB port is automatically disabled. Tap to learn more."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"OK to use USB port"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Uncategorised"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"You set the importance of these notifications."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"This is important because of the people involved."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Add a language"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Region preference"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Type language name"</string>
diff --git a/core/res/res/values-en-rIN/strings.xml b/core/res/res/values-en-rIN/strings.xml
index 2db3771..e1d9875 100644
--- a/core/res/res/values-en-rIN/strings.xml
+++ b/core/res/res/values-en-rIN/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Allows the app to receive and process SMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"receive text messages (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Allows the app to receive and process MMS messages. This means that the app could monitor or delete messages sent to your device without showing them to you."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"read mobile broadcast messages"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Allows the app to read mobile broadcast messages received by your device. Cell broadcast alerts are delivered in some locations to warn you of emergency situations. Malicious apps may interfere with the performance or operation of your device when an emergency mobile broadcast is received."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"read subscribed feeds"</string>
@@ -554,10 +558,10 @@
   <string-array name="fingerprint_error_vendor">
   </string-array>
     <string name="fingerprint_icon_content_description" msgid="2340202869968465936">"Fingerprint icon"</string>
-    <string name="permlab_manageFace" msgid="7262837876352591553">"manage Face Unlock hardware"</string>
+    <string name="permlab_manageFace" msgid="7262837876352591553">"manage face unlock hardware"</string>
     <string name="permdesc_manageFace" msgid="8919637120670185330">"Allows the app to invoke methods to add and delete facial templates for use."</string>
-    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use Face Unlock hardware"</string>
-    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use Face Unlock hardware for authentication"</string>
+    <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"use face unlock hardware"</string>
+    <string name="permdesc_useFaceAuthentication" msgid="4712947955047607722">"Allows the app to use face unlock hardware for authentication"</string>
     <string name="face_recalibrate_notification_name" msgid="1913676850645544352">"Face unlock"</string>
     <string name="face_recalibrate_notification_title" msgid="4087620069451499365">"Re-enrol your face"</string>
     <string name="face_recalibrate_notification_content" msgid="5530308842361499835">"To improve recognition, please re-enrol your face"</string>
@@ -584,15 +588,15 @@
   <string-array name="face_acquired_vendor">
   </string-array>
     <string name="face_error_hw_not_available" msgid="396883585636963908">"Can’t verify face. Hardware not available."</string>
-    <string name="face_error_timeout" msgid="981512090365729465">"Try Face Unlock again."</string>
+    <string name="face_error_timeout" msgid="981512090365729465">"Try face unlock again."</string>
     <string name="face_error_no_space" msgid="2712120617457553825">"Can’t store new face data. Delete an old one first."</string>
     <string name="face_error_canceled" msgid="283945501061931023">"Face operation cancelled."</string>
-    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face Unlock cancelled by user."</string>
+    <string name="face_error_user_canceled" msgid="5317030072349668946">"Face unlock cancelled by user."</string>
     <string name="face_error_lockout" msgid="3407426963155388504">"Too many attempts. Try again later."</string>
-    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face Unlock disabled."</string>
+    <string name="face_error_lockout_permanent" msgid="4723594314443097159">"Too many attempts. Face unlock disabled."</string>
     <string name="face_error_unable_to_process" msgid="4940944939691171539">"Can’t verify face. Try again."</string>
-    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up Face Unlock."</string>
-    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face Unlock is not supported on this device."</string>
+    <string name="face_error_not_enrolled" msgid="4016937174832839540">"You haven’t set up face unlock."</string>
+    <string name="face_error_hw_not_present" msgid="8302690289757559738">"Face unlock is not supported on this device."</string>
     <string name="face_name_template" msgid="7004562145809595384">"Face <xliff:g id="FACEID">%d</xliff:g>"</string>
   <string-array name="face_error_vendor">
   </string-array>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Allows the app to read and write Do Not Disturb configuration."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"start view permission usage"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Allows the holder to start the permission usage for an app. Should never be needed for normal apps."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"accessibility shortcut target"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Allows an app to define the accessibility shortcut target."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Set password rules"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Control the length and the characters allowed in screen lock passwords and PINs."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitor screen unlock attempts"</string>
@@ -821,7 +827,7 @@
     <string name="lockscreen_pattern_wrong" msgid="4317955014948108794">"Try again"</string>
     <string name="lockscreen_password_wrong" msgid="5737815393253165301">"Try again"</string>
     <string name="lockscreen_storage_locked" msgid="9167551160010625200">"Unlock for all features and data"</string>
-    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum Face Unlock attempts exceeded"</string>
+    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"Maximum face unlock attempts exceeded"</string>
     <string name="lockscreen_missing_sim_message_short" msgid="5099439277819215399">"No SIM card"</string>
     <string name="lockscreen_missing_sim_message" product="tablet" msgid="151659196095791474">"No SIM card in tablet."</string>
     <string name="lockscreen_missing_sim_message" product="tv" msgid="3360993527792167595">"No SIM card in your Android TV device."</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Select to disable USB debugging."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test Harness Mode enabled"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Perform a factory reset to disable Test Harness Mode."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serial console enabled"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performance is impacted. To disable, check bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Liquid or debris in USB port"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB port is automatically disabled. Tap to learn more."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"OK to use USB port"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Uncategorised"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"You set the importance of these notifications."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"This is important because of the people involved."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Add a language"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Region preference"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Type language name"</string>
diff --git a/core/res/res/values-en-rXC/strings.xml b/core/res/res/values-en-rXC/strings.xml
index 7961a86..c4d3157 100644
--- a/core/res/res/values-en-rXC/strings.xml
+++ b/core/res/res/values-en-rXC/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‎‏‎‎‏‎‏‎‎‎‎‎‎‎‎‎‏‎‏‎‎‏‏‏‏‏‏‏‏‎‎‏‏‎‎‎‏‎‏‏‎‎‏‏‎‏‏‎‎‎‏‏‎‏‏‎‏‏‎Allows the app to receive and process SMS messages. This means the app could monitor or delete messages sent to your device without showing them to you.‎‏‎‎‏‎"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‎‏‎‏‎‎‎‏‏‎‏‎‎‏‏‏‏‎‎‏‏‏‏‎‎‏‏‎‏‎‏‎‎‎‎‎‏‏‎‏‎‏‏‎‎‎‏‎‏‏‎‏‎‎‏‎‏‎‎receive text messages (MMS)‎‏‎‎‏‎"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‎‏‏‏‏‏‎‏‏‎‎‏‎‏‏‎‏‎‏‎‏‎‎‏‎‏‏‎‏‎‏‎‏‎‏‎‎‎‎‏‏‏‎‎‏‏‏‏‎‎‏‏‏‎‏‏‏‎‎‏‎‎‎Allows the app to receive and process MMS messages. This means the app could monitor or delete messages sent to your device without showing them to you.‎‏‎‎‏‎"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‎‏‏‎‎‎‏‎‏‏‏‎‎‏‏‎‎‏‏‏‏‎‎‏‏‏‎‏‎‏‏‎‏‏‏‎‎‎‏‏‎‏‎‏‏‎‏‏‏‎‏‎‏‏‎‏‎‏‏‎‎read cell broadcast messages‎‏‎‎‏‎"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‎‎‎‏‎‎‏‎‏‎‎‏‎‎‎‏‎‎‏‎‎‎‏‎‎‎‎‏‎‏‏‏‎‎‏‏‏‏‏‎‏‏‎‏‎‎‎‏‎‎‏‏‏‎‎‎‏‏‎Allows the app to read cell broadcast messages received by your device. Cell broadcast alerts are delivered in some locations to warn you of emergency situations. Malicious apps may interfere with the performance or operation of your device when an emergency cell broadcast is received.‎‏‎‎‏‎"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‎‏‎‎‎‎‎‎‎‏‎‏‏‎‏‏‏‏‏‎‏‎‎‎‎‏‏‎‏‏‎‎‏‏‏‏‏‎‎‎‎‏‏‏‏‎‎‏‏‎‏‎‏‏‎‎‏‏‎‎read subscribed feeds‎‏‎‎‏‎"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‏‎‏‏‏‎‎‎‎‎‎‏‎‏‏‎‎‏‏‏‎‎‏‎‎‏‏‏‏‏‏‎‎‎‎‏‏‏‎‏‎‏‏‏‏‎‎‎‎‎‎‏‎‎‎‏‏‎‎‎Allows the app to read and write Do Not Disturb configuration.‎‏‎‎‏‎"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‏‏‎‎‎‎‎‏‏‏‎‏‏‎‏‎‏‎‏‏‏‎‎‏‏‎‎‎‎‎‏‏‏‏‏‏‏‎‎‏‏‏‎‎‎‎‏‎‏‎‏‎‎‏‏‏‏‎‎‎‎start view permission usage‎‏‎‎‏‎"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‎‏‎‏‎‏‏‏‎‏‎‏‎‏‎‏‏‎‏‎‎‎‏‏‎‎‏‏‎‏‏‏‎‏‏‏‎‎‎‏‎‎‏‏‏‏‏‎‏‏‎‏‎‏‏‏‏‎‎‎Allows the holder to start the permission usage for an app. Should never be needed for normal apps.‎‏‎‎‏‎"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‎‎‏‏‎‎‏‏‏‎‏‏‏‏‎‏‎‎‎‎‎‎‎‎‏‏‎‏‎‎‏‎‏‏‏‏‎‏‏‏‎‎‎‎‏‎‏‎‎‎‏‏‏‎‎‏‏‎‎‏‎accessibility shortcut target‎‏‎‎‏‎"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‎‏‏‏‏‏‏‏‎‎‏‏‏‏‎‏‎‎‏‎‏‎‏‏‏‏‎‏‎‎‏‏‏‏‎‏‏‎‏‏‎‎‏‏‏‎‎‏‏‎‏‏‎‎‏‏‏‏‎‎‎‎‎Allows an app to define the accessibility shortcut target.‎‏‎‎‏‎"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‏‎‎‏‏‎‏‎‏‎‎‎‎‎‏‏‎‎‎‏‎‏‎‎‏‏‎‎‎‏‎‏‎‏‎‎‎‎‏‎‎‎‏‏‏‎‏‎‎‎‎‏‏‏‏‏‏‏‎Set password rules‎‏‎‎‏‎"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‏‎‏‎‏‏‏‎‎‎‏‏‏‏‎‏‏‏‎‏‎‎‎‎‏‎‎‏‏‏‏‎‏‏‏‎‎‏‏‎‎‏‏‎‎‏‎‎‏‏‎‎‎‏‏‎‎‎‎Control the length and the characters allowed in screen lock passwords and PINs.‎‏‎‎‏‎"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‏‏‎‏‎‏‎‏‎‎‎‎‏‎‎‏‏‎‏‎‎‎‏‎‎‏‏‏‏‎‎‎‎‎‎‏‎‎‎‎‏‎‎‏‎‎‏‏‏‏‏‎‏‏‏‏‏‏‎‎Monitor screen unlock attempts‎‏‎‎‏‎"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‏‎‏‏‎‎‎‏‏‎‎‏‎‎‎‏‎‏‎‎‎‎‏‎‏‎‎‎‎‏‎‎‎‏‏‎‎‎‏‏‏‎‎‏‎‎‎‎‎‏‎‏‎‏‏‏‏‎‎‎Select to disable USB debugging.‎‏‎‎‏‎"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‏‏‎‏‏‎‎‎‎‏‎‎‎‎‏‎‏‏‏‎‏‏‏‎‎‎‏‎‏‏‏‎‎‏‎‎‎‎‎‏‏‎‏‎‎‏‎‏‎‏‏‏‎‎‏‎‎‏‏‎Test Harness Mode enabled‎‏‎‎‏‎"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‎‎‏‎‏‎‏‎‎‎‏‏‏‏‏‏‏‏‏‎‏‎‏‏‎‏‏‎‎‏‎‏‏‎‏‏‎‎‏‏‎‏‏‏‏‎‎‎‎‎‎‏‏‏‎‎‏‏‏‏‎Perform a factory reset to disable Test Harness Mode.‎‏‎‎‏‎"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‏‎‎‏‏‎‎‎‏‎‏‎‎‏‏‏‏‏‏‎‏‎‎‎‎‏‎‎‎‎‏‏‏‏‏‏‎‎‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‏‎‏‏‎‎Serial console enabled‎‏‎‎‏‎"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‎‎‏‎‎‏‏‏‏‏‎‎‎‎‏‏‎‎‏‏‎‎‏‏‏‏‏‎‏‎‏‎‎‏‏‎‏‏‏‎‏‎‏‏‎‏‏‏‏‏‎‎‏‎‏‏‏‎‎‏‎Performance is impacted. To disable, check bootloader.‎‏‎‎‏‎"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‎‎‏‏‎‎‎‎‏‎‎‏‏‎‎‏‎‏‏‎‏‎‎‏‎‎‎‎‏‏‏‎‏‎‏‎‏‏‎‎‏‏‎‏‏‎‎‎‏‏‎‏‏‏‏‎‏‏‎‏‎Liquid or debris in USB port‎‏‎‎‏‎"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‏‏‏‎‎‎‏‏‎‏‎‎‎‎‏‏‏‎‎‎‏‎‎‏‎‏‏‎‏‎‏‎‎‏‏‏‎‏‎‏‏‏‏‏‏‎‎‏‏‎‎‎‎‏‎‎‏‎‎USB port is automatically disabled. Tap to learn more.‎‏‎‎‏‎"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‏‎‏‎‏‏‏‏‏‎‎‏‎‏‎‏‎‎‎‎‏‏‎‏‎‏‏‏‏‎‎‏‎‏‏‎‎‎‏‎‎‏‏‏‏‎‏‎‎‎‎‏‎‎‎‏‎‏‎‏‎OK to use USB port‎‏‎‎‏‎"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‎‏‎‎‏‎‎‏‎‏‎‎‏‏‎‎‏‎‏‏‎‎‏‎‏‏‏‏‏‎‎‏‏‎‎‎‏‎‎‎‎‏‎‏‏‏‏‏‎‏‏‏‎‎‏‏‏‏‎‎Uncategorized‎‏‎‎‏‎"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‎‏‎‏‏‎‎‏‎‎‏‎‎‎‏‎‎‏‏‏‏‎‎‎‏‎‎‏‏‏‎‏‎‏‏‎‎‎‎‏‏‎‏‎‏‎‏‎‎‎‏‎‏‎‏‎‏‎‏‏‎You set the importance of these notifications.‎‏‎‎‏‎"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‏‏‏‏‎‎‎‏‏‏‏‏‎‏‎‏‎‏‎‎‏‏‏‏‏‎‎‏‎‏‏‎‎‏‏‏‏‏‏‏‏‎‏‎‏‎‎‎‎‎‎‎‏‎‏‏‏‎‎‎‎This is important because of the people involved.‎‏‎‎‏‎"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‏‎‏‏‏‏‎‏‎‏‏‎‎‎‎‏‏‎‎‎‎‎‏‎‏‎‎‏‏‎‏‎‏‎‎‎‏‏‏‎‎‎‏‏‎‏‏‏‎‎‎‎‏‏‏‎‎‏‎Allow ‎‏‎‎‏‏‎<xliff:g id="APP">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to create a new User with ‎‏‎‎‏‏‎<xliff:g id="ACCOUNT">%2$s</xliff:g>‎‏‎‎‏‏‏‎ ?‎‏‎‎‏‎"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‏‎‎‎‏‏‎‏‎‏‏‎‎‏‏‎‎‏‏‏‎‎‎‎‎‎‎‎‏‎‎‎‏‏‎‏‎‎‏‎‏‏‎‎‏‏‎‏‏‎‏‏‏‏‏‏‎‏‎Allow ‎‏‎‎‏‏‎<xliff:g id="APP">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to create a new User with ‎‏‎‎‏‏‎<xliff:g id="ACCOUNT">%2$s</xliff:g>‎‏‎‎‏‏‏‎ (a User with this account already exists) ?‎‏‎‎‏‎"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‏‏‎‎‎‎‎‏‏‏‏‏‏‏‎‎‎‏‏‎‏‎‏‏‏‎‏‎‏‎‎‎‏‎‏‏‏‎‏‎‎‎‏‎‏‎‎‏‏‏‏‎‎‏‎‎‏‏‎Allow ‎‏‎‎‏‏‎<xliff:g id="APP">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to create a new User with ‎‏‎‎‏‏‎<xliff:g id="ACCOUNT">%2$s</xliff:g>‎‏‎‎‏‏‏‎ (a User with this account already exists) ?‎‏‎‎‏‎"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‏‏‏‎‎‎‏‎‎‎‏‏‎‎‏‎‏‏‏‎‎‎‎‏‏‎‏‏‏‏‏‎‏‎‏‎‏‎‎‏‏‎‏‏‎‏‏‎‏‎‏‏‏‎‏‎‎‎‏‏‎Allow ‎‏‎‎‏‏‎<xliff:g id="APP">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to create a new User with ‎‏‎‎‏‏‎<xliff:g id="ACCOUNT">%2$s</xliff:g>‎‏‎‎‏‏‏‎ ?‎‏‎‎‏‎"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‏‎‏‎‎‏‏‎‎‏‏‏‎‏‎‏‏‎‏‏‏‎‎‏‎‎‎‎‎‎‏‏‎‏‎‎‎‏‎‎‏‎‏‎‎‎‏‏‎‏‏‏‏‎‎‎‎‎‎‎Add a language‎‏‎‎‏‎"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‎‎‏‎‎‎‎‎‎‎‏‏‏‎‎‎‏‎‏‎‎‎‎‎‎‎‏‏‎‏‏‎‎‏‎‏‏‏‏‏‎‏‏‎‏‏‎‎‏‏‎‏‏‎‏‏‎‎‏‎Region preference‎‏‎‎‏‎"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‎‎‎‏‏‎‏‏‏‎‏‎‏‎‎‏‎‎‏‎‏‏‏‏‏‏‏‏‎‎‏‎‏‏‏‏‎‏‎‎‏‏‎‏‎‏‏‎‎‎‏‏‏‏‎‏‏‏‏‎‎Type language name‎‏‎‎‏‎"</string>
diff --git a/core/res/res/values-es-rUS/strings.xml b/core/res/res/values-es-rUS/strings.xml
index 0229cf5..30f8ba7 100644
--- a/core/res/res/values-es-rUS/strings.xml
+++ b/core/res/res/values-es-rUS/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite que la aplicación reciba y procese mensajes SMS, lo que significa que podría controlar o eliminar mensajes enviados al dispositivo sin mostrártelos."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"recibir mensajes de texto (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite que la aplicación reciba y procese mensajes MMS, lo que significa que podría controlar o eliminar mensajes enviados al dispositivo sin mostrártelos."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"Leer mensajes de difusión móvil"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite a la aplicación leer los mensajes de difusión móvil que recibe tu dispositivo. En algunas ubicaciones, las alertas de difusión móvil se envían para informar situaciones de emergencia. Las aplicaciones maliciosas pueden afectar el rendimiento o funcionamiento de tu dispositivo cuando se recibe un un mensaje de difusión móvil de emergencia."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"leer canales suscritos"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permite que la aplicación lea y modifique la configuración de la función No interrumpir."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"iniciar uso de permiso de vista"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permite que el propietario inicie el uso de permisos para una app. No debería requerirse para apps normales."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"orientación del acceso directo de accesibilidad"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permite que una app defina la orientación del acceso directo de accesibilidad."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Establecer reglas de contraseña"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controlar la longitud y los caracteres permitidos en las contraseñas y los PIN para el bloqueo de pantalla."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Supervisa los intentos para desbloquear la pantalla"</string>
@@ -1357,10 +1363,12 @@
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Se detectó un accesorio de audio analógico"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"El dispositivo adjunto no es compatible con este teléfono. Presiona para obtener más información."</string>
     <string name="adb_active_notification_title" msgid="6729044778949189918">"Depuración por USB conectada"</string>
-    <string name="adb_active_notification_message" msgid="7463062450474107752">"Presiona para desactivar la depuración USB"</string>
+    <string name="adb_active_notification_message" msgid="7463062450474107752">"Presiona para desactivar la depuración por USB"</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Seleccionar para desactivar la depuración por USB"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Se habilitó el modo de agente de prueba"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Restablece la configuración de fábrica para inhabilitar el modo de agente de prueba."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Se habilitó la consola en serie"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Afecta el rendimiento. Para inhabilitarla, verifica bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Hay líquido o suciedad en el puerto USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"El puerto USB se inhabilitó automáticamente. Presiona para obtener más información."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Se puede usar el puerto USB"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sin categoría"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Estableciste la importancia de estas notificaciones."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Es importante debido a las personas involucradas."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"¿Quieres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario nuevo con <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"¿Quieres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario nuevo con <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Ya existe un usuario con esta cuenta)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"¿Quieres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario nuevo con <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Ya existe un usuario con esta cuenta)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"¿Deseas permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario nuevo con <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Agregar un idioma"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferencia de región"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Nombre del idioma"</string>
diff --git a/core/res/res/values-es/strings.xml b/core/res/res/values-es/strings.xml
index d9864fb..15e662c 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite que la aplicación reciba y procese mensajes MMS, lo que significa que podría utilizar este permiso para controlar o eliminar mensajes enviados al dispositivo sin mostrárselos al usuario."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"recibir mensajes de texto (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite que la aplicación reciba y procese mensajes MMS, lo que significa que podría utilizar este permiso para controlar o eliminar mensajes enviados al dispositivo sin mostrárselos al usuario."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"leer mensajes de difusión móvil"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite que la aplicación lea mensajes de difusión móvil que haya recibido el dispositivo. Las alertas de difusión móvil se envían en algunas ubicaciones para avisar de situaciones de emergencia. Es posible que las aplicaciones malintencionadas interfieran en el rendimiento o en el funcionamiento del dispositivo si se recibe una alerta de difusión móvil de emergencia."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"leer feeds a los que está suscrito el usuario"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permite que la aplicación lea y modifique la configuración de No molestar."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"iniciar uso de permiso de visualización"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permite que el titular inicie el uso de permisos de una aplicación. Las aplicaciones normales no deberían necesitar nunca este permiso."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"objetivo de atajo de accesibilidad"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permite que una aplicación defina el objetivo de un atajo de accesibilidad."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Establecimiento de reglas de contraseña"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controla la longitud y los caracteres permitidos en los PIN y en las contraseñas de bloqueo de pantalla."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Supervisar los intentos de desbloqueo de pantalla"</string>
@@ -1357,10 +1363,12 @@
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Se ha detectado un accesorio de audio analógico"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"El dispositivo adjunto no es compatible con este teléfono. Toca para obtener más información."</string>
     <string name="adb_active_notification_title" msgid="6729044778949189918">"Depuración USB habilitada"</string>
-    <string name="adb_active_notification_message" msgid="7463062450474107752">"Toca para desactivar la depuración USB."</string>
+    <string name="adb_active_notification_message" msgid="7463062450474107752">"Tocar para desactivar depuración USB"</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Seleccionar para inhabilitar la depuración USB"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Modo de agente de prueba habilitado"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Restablece los ajustes de fábrica para inhabilitar el modo de agente de prueba."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Se ha habilitado la consola en serie"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Afecta al rendimiento. Para inhabilitarlo, comprueba el bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Se ha detectado líquido o suciedad en el puerto USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"El puerto USB se ha inhabilitado automáticamente. Toca para obtener más información."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Se puede utilizar el puerto USB"</string>
@@ -1672,8 +1680,8 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"El acceso directo a accesibilidad ha desactivado <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Para utilizar <xliff:g id="SERVICE_NAME">%1$s</xliff:g>, mantén pulsadas ambas teclas de volumen durante 3 segundos"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Selecciona el servicio que se utilizará cuando toques el botón Accesibilidad:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Elige el servicio que se utilizará con el gesto de accesibilidad (desliza dos dedos hacia arriba desde la parte inferior de la pantalla):"</string>
-    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Elige el servicio que se utilizará con el gesto de accesibilidad (desliza tres dedos hacia arriba desde la parte inferior de la pantalla):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Elige el servicio que se utilizará con el gesto de accesibilidad (deslizar dos dedos hacia arriba desde la parte inferior de la pantalla):"</string>
+    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Elige el servicio que se utilizará con el gesto de accesibilidad (deslizar tres dedos hacia arriba desde la parte inferior de la pantalla):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Para cambiar de un servicio a otro, mantén pulsado el botón de accesibilidad."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Para cambiar de un servicio a otro, desliza dos dedos hacia arriba y mantén pulsada la pantalla."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Para cambiar de un servicio a otro, desliza tres dedos hacia arriba y mantén pulsada la pantalla."</string>
@@ -1890,9 +1898,9 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sin clasificar"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Tú determinas la importancia de estas notificaciones."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Esto es importante por los usuarios implicados."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"¿Permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario con la cuenta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"¿Permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario con la cuenta <xliff:g id="ACCOUNT">%2$s</xliff:g> (ya existe un usuario con esta cuenta)?"</string>
-    <string name="language_selection_title" msgid="2680677278159281088">"Añade un idioma"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"¿Permitir que <xliff:g id="APP">%1$s</xliff:g> cree otro usuario con la cuenta <xliff:g id="ACCOUNT">%2$s</xliff:g>, que ya tiene uno?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"¿Permitir que <xliff:g id="APP">%1$s</xliff:g> cree otro usuario con la cuenta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
+    <string name="language_selection_title" msgid="2680677278159281088">"Añadir un idioma"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferencia de región"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Nombre de idioma"</string>
     <string name="language_picker_section_suggested" msgid="8414489646861640885">"Sugeridos"</string>
diff --git a/core/res/res/values-et/strings.xml b/core/res/res/values-et/strings.xml
index afa8453..093f7d7 100644
--- a/core/res/res/values-et/strings.xml
+++ b/core/res/res/values-et/strings.xml
@@ -243,7 +243,7 @@
     <string name="global_action_toggle_silent_mode" msgid="8219525344246810925">"Hääletu režiim"</string>
     <string name="global_action_silent_mode_on_status" msgid="3289841937003758806">"Heli on VÄLJAS"</string>
     <string name="global_action_silent_mode_off_status" msgid="1506046579177066419">"Heli on SEES"</string>
-    <string name="global_actions_toggle_airplane_mode" msgid="5884330306926307456">"Lennurežiim"</string>
+    <string name="global_actions_toggle_airplane_mode" msgid="5884330306926307456">"Lennukirežiim"</string>
     <string name="global_actions_airplane_mode_on_status" msgid="2719557982608919750">"Lennurežiim on SEES"</string>
     <string name="global_actions_airplane_mode_off_status" msgid="5075070442854490296">"Lennurežiim on VÄLJAS"</string>
     <string name="global_action_settings" msgid="1756531602592545966">"Seaded"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Võimaldab rakendusel vastu võtta ja töödelda SMS-sõnumeid. See tähendab, et rakendus võib jälgida või kustutada teie seadmele saadetud sõnumeid neid teile näitamata."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"võtke vastu tekstisõnumeid (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Võimaldab rakendusel vastu võtta ja töödelda multimeediumsõnumeid. See tähendab, et rakendus võib jälgida või kustutada teie seadmele saadetud sõnumeid neid teile näitamata."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"mobiilsidesõnumite lugemine"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Võimaldab rakendusel lugeda seadme vastu võetud mobiilsidesõnumeid. Mobiilsidemärguandeid edastatakse mõnes asukohas eriolukorrast teavitamiseks. Pahatahtlikud rakendused võivad segada seadme toimivust või tööd eriolukorra sõnumi vastuvõtmisel."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"loe tellitud kanaleid"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Võimaldab rakendusel lugeda ja kirjutada funktsiooni Mitte segada seadistusi."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"vaatamisloa kasutamise alustamine"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Võimaldab omanikul rakenduse puhul alustada loa kasutamist. Tavarakenduste puhul ei peaks seda kunagi vaja minema."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"juurdepääsetavuse otsetee sihtmärk"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Lubab rakendusel määrata juurdepääsetavuse otsetee sihtmärgi."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Parooli reeglite määramine"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Juhitakse ekraaniluku paroolide ja PIN-koodide pikkusi ning lubatud tähemärkide seadeid."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Ekraani avamiskatsete jälgimine"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Valige USB silumise keelamiseks"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Testrakendirežiim on lubatud"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Testrakendirežiimi keelamiseks taastage tehaseseaded."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Seeriakonsool on lubatud"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"See mõjutab toimivust. Keelamiseks kontrollige käivituslaadurit."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB-pordis on vedelik või mustus"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-port on automaatselt keelatud. Puudutage lisateabe saamiseks."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB-porti tohib kasutada"</string>
@@ -1672,7 +1680,7 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"Juurdepääsetavuse otsetee lülitas teenuse <xliff:g id="SERVICE_NAME">%1$s</xliff:g> välja"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Teenuse <xliff:g id="SERVICE_NAME">%1$s</xliff:g> kasutamiseks hoidke kolm sekundit all mõlemat helitugevuse klahvi"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Valige, millist teenust kasutada, kui puudutate juurdepääsetavuse nuppu:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Valige, millist teenust kasutada koos juurdepääsetavuse liigutusega (pühkige kahe sõrmega ekraanikuval alt üles):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Valige, millist teenust kasutada koos juurdepääsetavuse liigutusega (kahe sõrmega ekraanikuval alt üles pühkimine):"</string>
     <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Valige, millist teenust kasutada koos juurdepääsetavuse liigutusega (kolme sõrmega ekraanikuval alt üles pühkimine):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Teenuste vahel vahetamiseks vajutage pikalt juurdepääsetavuse nuppu."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Teenuste vahel vahetamiseks pühkige kahe sõrmega üles ja hoidke."</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Kategoriseerimata"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Teie määrasite nende märguannete tähtsuse."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"See on tähtis osalevate inimeste tõttu."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Kas lubada rakendusel <xliff:g id="APP">%1$s</xliff:g> luua uus kasutaja kontoga <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Kas lubada rakendusel <xliff:g id="APP">%1$s</xliff:g> luua uus kasutaja kontoga <xliff:g id="ACCOUNT">%2$s</xliff:g> (selle kontoga kasutaja on juba olemas)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Kas lubada rakendusel <xliff:g id="APP">%1$s</xliff:g> luua uus kasutaja kontoga <xliff:g id="ACCOUNT">%2$s</xliff:g> (selle kontoga kasutaja on juba olemas)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Kas lubada rakendusel <xliff:g id="APP">%1$s</xliff:g> luua uus kasutaja kontoga <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Keele lisamine"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Piirkonnaeelistus"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Sisestage keele nimi"</string>
diff --git a/core/res/res/values-eu/strings.xml b/core/res/res/values-eu/strings.xml
index 9932fdf..53b1a38 100644
--- a/core/res/res/values-eu/strings.xml
+++ b/core/res/res/values-eu/strings.xml
@@ -280,37 +280,37 @@
     <string name="managed_profile_label" msgid="8947929265267690522">"Aldatu laneko profilera"</string>
     <string name="permgrouplab_contacts" msgid="3657758145679177612">"Kontaktuak"</string>
     <string name="permgroupdesc_contacts" msgid="6951499528303668046">"atzitu kontaktuak"</string>
-    <string name="permgrouprequest_contacts" msgid="6032805601881764300">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari kontaktuak atzitzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_contacts" msgid="6032805601881764300">"Kontaktuak atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Kokapena"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"atzitu gailuaren kokapena"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari gailuaren kokapena atzitzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"Gailuaren kokapena atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"Hura erabiltzen ari zarenean soilik atzituko du aplikazioak kokapena"</string>
-    <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari gailuaren kokapena &lt;b&gt;beti&lt;/b&gt; atzitzeko baimena eman nahi diozu?"</string>
+    <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"Gailuaren kokapena &lt;b&gt;beti&lt;/b&gt; atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"Aplikazioak hura darabilzunean atzi dezake kokapena"</string>
     <string name="permgrouplab_calendar" msgid="5863508437783683902">"Egutegia"</string>
     <string name="permgroupdesc_calendar" msgid="3889615280211184106">"atzitu egutegia"</string>
-    <string name="permgrouprequest_calendar" msgid="289900767793189421">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari egutegia atzitzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_calendar" msgid="289900767793189421">"Egutegia atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS mezuak"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"bidali eta ikusi SMS mezuak"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari SMS mezuak bidaltzeko eta ikusteko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"SMS mezuak bidaltzeko eta ikusteko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Memoria"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"atzitu gailuko argazkiak, multimedia-edukia eta fitxategiak"</string>
-    <string name="permgrouprequest_storage" msgid="7885942926944299560">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari gailuko argazkiak, multimedia-edukia eta fitxategiak atzitzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_storage" msgid="7885942926944299560">"Gailuko argazkiak, multimedia-edukia eta fitxategiak atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_microphone" msgid="171539900250043464">"Mikrofonoa"</string>
     <string name="permgroupdesc_microphone" msgid="4988812113943554584">"grabatu audioa"</string>
-    <string name="permgrouprequest_microphone" msgid="9167492350681916038">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari audioa grabatzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_microphone" msgid="9167492350681916038">"Audioa grabatzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_activityRecognition" msgid="1565108047054378642">"Ariketa fisikoa"</string>
     <string name="permgroupdesc_activityRecognition" msgid="6949472038320473478">"ariketa fisikoak atzitu"</string>
     <string name="permgrouprequest_activityRecognition" msgid="7626438016904799383">"Zure ariketa fisikoak atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_camera" msgid="4820372495894586615">"Kamera"</string>
     <string name="permgroupdesc_camera" msgid="3250611594678347720">"atera argazkiak eta grabatu bideoak"</string>
-    <string name="permgrouprequest_camera" msgid="1299833592069671756">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari argazkiak ateratzeko eta bideoak grabatzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_camera" msgid="1299833592069671756">"Argazkiak ateratzeko eta bideoak grabatzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_calllog" msgid="8798646184930388160">"Deien erregistroa"</string>
     <string name="permgroupdesc_calllog" msgid="3006237336748283775">"irakurri telefonoko deien erregistroa eta idatzi bertan"</string>
-    <string name="permgrouprequest_calllog" msgid="8487355309583773267">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari telefonoko deien erregistroa atzitzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_calllog" msgid="8487355309583773267">"Telefonoko deien erregistroa atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_phone" msgid="5229115638567440675">"Telefonoa"</string>
     <string name="permgroupdesc_phone" msgid="6234224354060641055">"egin eta kudeatu telefono-deiak"</string>
-    <string name="permgrouprequest_phone" msgid="9166979577750581037">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari telefono-deiak egiteko eta kudeatzeko baimena eman nahi diozu?"</string>
+    <string name="permgrouprequest_phone" msgid="9166979577750581037">"Telefono-deiak egiteko eta kudeatzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
     <string name="permgrouplab_sensors" msgid="4838614103153567532">"Gorputz-sentsoreak"</string>
     <string name="permgroupdesc_sensors" msgid="7147968539346634043">"atzitu bizi-konstanteei buruzko sentsorearen datuak"</string>
     <string name="permgrouprequest_sensors" msgid="6349806962814556786">"Bizi-konstanteei buruzko sentsorearen datuak atzitzeko baimena eman nahi diozu &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; aplikazioari?"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS mezuak jasotzeko eta prozesatzeko baimena ematen die aplikazioei. Horrela, aplikazioak gailura bidalitako mezuak kontrola eta ezaba ditzake zuri erakutsi gabe."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"jaso testu-mezuak (MMSak)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS mezuak jasotzeko eta prozesatzeko baimena ematen die aplikazioei. Horrela, aplikazioak gailura bidalitako mezuak kontrola eta ezaba ditzake zuri erakutsi gabe."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"irakurri sare mugikor bidezko igorpen-mezuak"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Gailuak jasotako sare mugikor bidezko igorpenen mezuak irakurtzeko baimena ematen die aplikazioei. Sare mugikor bidezko igorpen-alertak kokapen batzuetan ematen dira larrialdi-egoeren berri emateko. Aplikazio gaiztoek gailuaren errendimendua edo funtzionamendua oztopa dezakete larrialdi-igorpen horietako bat jasotzen denean."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"irakurri harpidetutako jarioak"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"\"Ez molestatu\" konfigurazioa irakurtzeko eta bertan idazteko baimena ematen die aplikazioei."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"hasi ikusteko baimena erabiltzen"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Aplikazioaren baimena erabiltzen hasteko baimena ematen die titularrei. Aplikazio normalek ez lukete beharko."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"erabilerraztasun-lasterbidearen helburua"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Erabilerraztasun-lasterbidearen helburua zehazteko baimena ematen dio aplikazioari."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Ezarri pasahitzen arauak"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontrolatu pantaila blokeoaren pasahitzen eta PINen luzera eta onartutako karaktereak."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Gainbegiratu pantaila desblokeatzeko saiakerak"</string>
@@ -1260,7 +1266,7 @@
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Iradokitako wifi-sareak baimendu nahi dituzu?"</string>
     <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> aplikazioak sare batzuk iradoki ditu. Baliteke gailua automatikoki konektatzea."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Baimendu"</string>
-    <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Ez. Eskerrik asko."</string>
+    <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Ez, eskerrik asko"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi konexioa automatikoki aktibatuko da"</string>
     <string name="wifi_wakeup_onboarding_subtext" msgid="3989697580301186973">"Gordeta daukazun kalitate handiko sare batetik gertu zaudenean"</string>
     <string name="wifi_wakeup_onboarding_action_disable" msgid="838648204200836028">"Ez aktibatu berriro"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Hautatu USB arazketa desgaitzeko."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Proba-materialeko modua gaitu da"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Proba-materialaren modua desgaitzeko, berrezarri jatorrizko datuak."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serie-kontsola gaituta dago"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Funtzionamenduari eragiten dio. Desgaitzeko, joan abiarazlera."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Likidoa edo zikinkeriak daude USB atakan"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB ataka automatikoki desgaitu da. Informazio gehiago lortzeko, sakatu hau."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Erabiltzeko moduan dago USB ataka"</string>
@@ -1638,7 +1646,7 @@
     <string name="kg_password_wrong_pin_code" msgid="1139324887413846912">"PIN kode okerra."</string>
     <string name="kg_invalid_sim_pin_hint" msgid="8795159358110620001">"Idatzi 4 eta 8 zenbaki arteko PINa."</string>
     <string name="kg_invalid_sim_puk_hint" msgid="6025069204539532000">"PUK kodeak 8 zenbaki izan behar ditu."</string>
-    <string name="kg_invalid_puk" msgid="3638289409676051243">"Idatzi berriro PUK kode zuzena. Hainbat saiakera oker eginez gero, betirako desgaituko da SIMa."</string>
+    <string name="kg_invalid_puk" msgid="3638289409676051243">"Idatzi berriro PUK kode zuzena. Hainbat saiakera oker eginez gero, betiko desgaituko da SIMa."</string>
     <string name="kg_invalid_confirm_pin_hint" product="default" msgid="7003469261464593516">"PIN kodeak ez datoz bat"</string>
     <string name="kg_login_too_many_attempts" msgid="6486842094005698475">"Eredua marrazteko saiakera gehiegi egin dira"</string>
     <string name="kg_login_instructions" msgid="1100551261265506448">"Desblokeatzeko, hasi saioa Google kontuarekin."</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Kategoriarik gabea"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Zuk ezarri duzu jakinarazpen hauen garrantzia."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Garrantzitsua da eragiten dien pertsonengatik."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> aplikazioari <xliff:g id="ACCOUNT">%2$s</xliff:g> kontua duen erabiltzailea sortzeko baimena eman nahi diozu?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> aplikazioari <xliff:g id="ACCOUNT">%2$s</xliff:g> kontua duen erabiltzailea sortzeko baimena eman nahi diozu? (Badago kontu hori duen erabiltzaile bat)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g> kontua duen erabiltzailea sortzeko baimena eman nahi diozu <xliff:g id="APP">%1$s</xliff:g> aplikazioari? (Badago kontu hori duen erabiltzaile bat)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> kontua duen erabiltzailea sortzeko baimena eman nahi diozu <xliff:g id="APP">%1$s</xliff:g> aplikazioari?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Gehitu hizkuntza"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Lurralde-hobespena"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Adierazi hizkuntza"</string>
diff --git a/core/res/res/values-fa/strings.xml b/core/res/res/values-fa/strings.xml
index cf7f37c..2b849d5 100644
--- a/core/res/res/values-fa/strings.xml
+++ b/core/res/res/values-fa/strings.xml
@@ -292,7 +292,7 @@
     <string name="permgrouprequest_calendar" msgid="289900767793189421">"‏به &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; اجازه داده شود به تقویم شما دسترسی پیدا کند؟"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"پیامک"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"ارسال و مشاهده پیامک‌ها"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"‏به &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;b&gt; اجازه داده شود پیامک‌ها را ارسال و مشاهده کند؟"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"‏به «&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;b&gt;» اجازه داده شود پیامک ارسال و مشاهده کند؟"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"حافظه"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"دسترسی به عکس‌ها، رسانه‌ها و فایل‌های روی دستگاهتان"</string>
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"‏به برنامه &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;b&gt; اجازه داده شود به عکس‌ها، رسانه، و فایل‌های موجود در دستگاهتان دسترسی داشته باشد؟"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"به برنامه اجازه می‌دهد پیامک‌ها را دریافت و پردازش کند. این یعنی برنامه می‌تواند پیام‌های ارسالی به دستگاه شما را بدون نمایش آن‌ها به شما حذف یا کنترل کند."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"دریافت پیام‌های نوشتاری (فراپیام)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"به برنامه اجازه می‌دهد پیام‌های فراپیام را دریافت و پردازش کند. این یعنی برنامه می‌تواند پیام‌های ارسالی به دستگاه شما را بدون نمایش آن‌ها به شما حذف یا کنترل کند."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"خواندن پیام‌های پخش سلولی"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"‏به برنامه اجازه می‎دهد پیام‌های پخش سلولی دستگاه شما را بخواند. هشدارهای پخش سلولی در برخی از موقعیت‌های مکانی تحویل داده می‎شوند تا موقعیت‌های اضطراری را به شما اعلام کنند. وقتی پخش سلولی دریافت می‎شود، ممکن است برنامه‎های مخرب در عملکرد یا کارکرد دستگاه شما اختلال ایجاد کنند."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"خواندن فیدهای مشترک"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"به برنامه امکان می‌دهد پیکربندی «مزاحم نشوید» را بخواند و بنویسد."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"شروع مشاهده استفاده از مجوز"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"به دارنده اجازه شروع استفاده از مجوز را برای برنامه می‌دهد. هرگز برای برنامه‌های معمول نیاز نیست."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"مقصد میان‌بر دسترس‌پذیری"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"به برنامه اجازه می‌دهد مقصد میانبر دسترس‌پذیری را تعریف کند."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"تنظیم قوانین گذرواژه"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"کنترل طول و نوع نویسه‌هایی که در گذرواژه و پین قفل صفحه مجاز است."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"پایش تلاش‌های باز کردن قفل صفحه"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"‏انتخاب کنید تا رفع عیب USB غیرفعال شود."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"«حالت مجموعه داده‌های تست» فعال شد"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"برای غیرفعال کردن «حالت مجموعه داده‌های تست»، بازنشانی کارخانه‌ای کنید."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"کنسول سریال فعال است"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"‏عملکرد تحت‌تأثیر قرار گرفته است. برای غیرفعال کردن، bootloader را بررسی کنید."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"‏مایعات یا خاکروبه در درگاه USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"‏درگاه USB به‌طور خودکار غیرفعال شده است. برای اطلاعات بیشتر، ضربه بزنید."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"‏می‌توان از درگاه USB استفاده کرد"</string>
@@ -1810,8 +1818,8 @@
     <string name="package_updated_device_owner" msgid="1847154566357862089">"توسط سرپرست سیستم به‌روزرسانی شد"</string>
     <string name="package_deleted_device_owner" msgid="2307122077550236438">"توسط سرپرست سیستم حذف شد"</string>
     <string name="confirm_battery_saver" msgid="639106420541753635">"تأیید"</string>
-    <string name="battery_saver_description_with_learn_more" msgid="2108984221113106294">"بهینه‌سازی باتری فعالیت پس‌زمینه، برخی جلوه‌های دیداری، و سایر ویژگی‌های با مصرف بالای نیرو را خاموش یا محدود می‌کند تا عمر باتری افزایش یابد. "<annotation id="url">"بیشتر بدانید"</annotation></string>
-    <string name="battery_saver_description" msgid="6413346684861241431">"بهینه‌سازی باتری فعالیت پس‌زمینه، برخی جلوه‌های دیداری، و سایر ویژگی‌های با مصرف بالای نیرو را خاموش یا محدود می‌کند تا عمر باتری افزایش یابد."</string>
+    <string name="battery_saver_description_with_learn_more" msgid="2108984221113106294">"«بهینه‌سازی باتری» فعالیت پس‌زمینه، برخی جلوه‌های دیداری، و سایر ویژگی‌های پرمصرف نیرو را خاموش یا محدود می‌کند تا عمر باتری افزایش یابد. "<annotation id="url">"بیشتر بدانید"</annotation></string>
+    <string name="battery_saver_description" msgid="6413346684861241431">"«بهینه‌سازی باتری» فعالیت پس‌زمینه، برخی جلوه‌های دیداری، و سایر ویژگی‌های پرمصرف نیرو را خاموش یا محدود می‌کند تا عمر باتری افزایش یابد."</string>
     <string name="data_saver_description" msgid="6015391409098303235">"برای کمک به کاهش مصرف داده، «صرفه‌جویی داده» از ارسال و دریافت داده در پس‌زمینه ازطرف بعضی برنامه‌ها جلوگیری می‌کند. برنامه‌ای که درحال‌حاضر استفاده می‌کنید می‌تواند به داده‌ها دسترسی داشته باشد اما دفعات دسترسی آن محدود است.این یعنی، برای مثال، تصاویر تا زمانی که روی آن‌ها ضربه نزنید نشان داده نمی‌شوند."</string>
     <string name="data_saver_enable_title" msgid="4674073932722787417">"صرفه‌جویی داده روشن شود؟"</string>
     <string name="data_saver_enable_button" msgid="7147735965247211818">"روشن کردن"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"دسته‌بندی‌نشده"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"شما اهمیت این اعلان‌ها را تنظیم می‌کنید."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"به دلیل افراد درگیر مهم است."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"به <xliff:g id="APP">%1$s</xliff:g> امکان داده شود کاربر جدیدی با <xliff:g id="ACCOUNT">%2$s</xliff:g> اضافه کند؟"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"به <xliff:g id="APP">%1$s</xliff:g> امکان داده شود کاربر جدیدی با <xliff:g id="ACCOUNT">%2$s</xliff:g> ایجاد کند (کاربری با این حساب از قبل وجود دارد)؟"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"به<xliff:g id="APP">%1$s</xliff:g> اجازه می‌دهید با <xliff:g id="ACCOUNT">%2$s</xliff:g> (کاربری با این حساب درحال‌حاضر وجود دارد) کاربری جدید ایجاد کند؟"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"به <xliff:g id="APP">%1$s</xliff:g> اجازه می‌دهید با <xliff:g id="ACCOUNT">%2$s</xliff:g> کاربری جدید ایجاد کند؟"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"افزودن زبان"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"اولویت‌های منطقه"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"نام زبان را تایپ کنید"</string>
@@ -2006,15 +2014,15 @@
     <string name="notification_appops_overlay_active" msgid="633813008357934729">"نمایش روی برنامه‌های دیگر در صفحه‌نمایش"</string>
     <string name="dynamic_mode_notification_channel_name" msgid="2348803891571320452">"اعلان اطلاعات حالت روال معمول"</string>
     <string name="dynamic_mode_notification_title" msgid="508815255807182035">"ممکن است شارژ باتری قبل از شارژ معمول تمام شود"</string>
-    <string name="dynamic_mode_notification_summary" msgid="2541166298550402690">"جهت افزایش عمر باتری، بهینه‌سازی باتری فعال شد"</string>
+    <string name="dynamic_mode_notification_summary" msgid="2541166298550402690">"جهت افزایش عمر باتری، «بهینه‌سازی باتری» فعال شد"</string>
     <string name="battery_saver_notification_channel_name" msgid="2083316159716201806">"بهینه‌سازی باتری"</string>
-    <string name="battery_saver_sticky_disabled_notification_title" msgid="6376147579378764641">"تا وقتی شارژ باتری دوباره به سطح پایین نرسد، بهینه‌سازی باتری مجدداً فعال نخواهد شد"</string>
-    <string name="battery_saver_sticky_disabled_notification_summary" msgid="8090192609249817945">"باتری تا سطحی کافی شارژ شده است. تا وقتی شارژ باتری دوباره به سطح پایین نرسد، بهینه‌سازی باتری مجدداً فعال نخواهد شد."</string>
+    <string name="battery_saver_sticky_disabled_notification_title" msgid="6376147579378764641">"تا وقتی شارژ باتری دوباره به سطح پایین نرسد، «بهینه‌سازی باتری» مجدداً فعال نخواهد شد"</string>
+    <string name="battery_saver_sticky_disabled_notification_summary" msgid="8090192609249817945">"باتری درحد کافی شارژ شده است. تا وقتی شارژ باتری دوباره به سطح پایین نرسد، «بهینه‌سازی باتری» مجدداً فعال نخواهد شد."</string>
     <string name="battery_saver_charged_notification_title" product="default" msgid="2960978289873161288">"تلفن <xliff:g id="CHARGE_LEVEL">%1$s</xliff:g> شارژ شد"</string>
     <string name="battery_saver_charged_notification_title" product="tablet" msgid="7555713825806482451">"رایانه لوحی <xliff:g id="CHARGE_LEVEL">%1$s</xliff:g> شارژ شد"</string>
     <string name="battery_saver_charged_notification_title" product="device" msgid="5954873381559605660">"دستگاه <xliff:g id="CHARGE_LEVEL">%1$s</xliff:g> شارژ شد"</string>
-    <string name="battery_saver_off_notification_summary" msgid="1374222493681267143">"بهینه‌سازی باتری خاموش است. ویژگی‌ها دیگر محدود نمی‌شوند."</string>
-    <string name="battery_saver_off_alternative_notification_summary" msgid="4340727818546508436">"بهینه‌سازی باتری خاموش شد. ویژگی‌ها دیگر محدود نمی‌شوند."</string>
+    <string name="battery_saver_off_notification_summary" msgid="1374222493681267143">"«بهینه‌سازی باتری» خاموش است. ویژگی‌ها دیگر محدود نمی‌شوند."</string>
+    <string name="battery_saver_off_alternative_notification_summary" msgid="4340727818546508436">"«بهینه‌سازی باتری» خاموش شد. ویژگی‌ها دیگر محدود نمی‌شوند."</string>
     <string name="mime_type_folder" msgid="7111951698626315204">"پوشه"</string>
     <string name="mime_type_apk" msgid="5518003630972506900">"‏برنامه Android"</string>
     <string name="mime_type_generic" msgid="6833871596845900027">"فایل"</string>
diff --git a/core/res/res/values-fi/strings.xml b/core/res/res/values-fi/strings.xml
index d39bdc7..c18e5bf 100644
--- a/core/res/res/values-fi/strings.xml
+++ b/core/res/res/values-fi/strings.xml
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"Saako &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; yhteystietojesi käyttöoikeuden?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Sijainti"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"käyttää laitteen sijaintia"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"Saako &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; tämän laitteen sijainnin käyttöoikeuden?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"Saako &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; oikeuden nähdä tämän laitteen sijainnin?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"Sovellus saa sijainnin käyttöoikeuden vain silloin, kun käytät sovellusta"</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"Saako &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; käyttää laitteen sijaintia &lt;b&gt;aina&lt;/b&gt;?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"Sovellus saa tällä hetkellä sijainnin käyttöoikeuden vain, jos käytät sovellusta"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Antaa sovelluksen vastaanottaa ja käsitellä tekstiviestejä. Sovellus voi valvoa tai poistaa laitteeseesi lähetettyjä viestejä näyttämättä niitä sinulle."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"vastaanota tekstiviestejä (multimedia)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Antaa sovelluksen vastaanottaa ja käsitellä multimediaviestejä. Sovellus voi valvoa tai poistaa laitteeseesi lähetettyjä viestejä näyttämättä niitä sinulle."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lue tiedotteita"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Antaa sovelluksen lukea laitteesi vastaanottamia tiedotteita. Tiedotteiden avulla ilmoitetaan hätätilanteista joissakin paikoissa. Haitalliset sovellukset voivat häiritä laitteen toimintaa laitteen vastaanottaessa hätätiedotteen."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lukea tilattuja syötteitä"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Sallii sovelluksen lukea ja muokata Älä häiritse -tilan asetuksia."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"aloita katseluoikeuksien käyttö"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Antaa luvanhaltijan käynnistää sovelluksen käyttöoikeuksien käytön. Ei tavallisten sovelluksien käyttöön."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"esteettömyystilan pikakuvakkeen kohde"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Sallii sovelluksen määrittää kohteen esteettömystilan pikakuvakkeelle."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Asentaa salasanasäännöt"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Hallinnoida ruudun lukituksen salasanoissa ja PIN-koodeissa sallittuja merkkejä ja niiden pituutta."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Tarkkailla näytön avaamisyrityksiä"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Poista USB-vianetsintä käytöstä valitsemalla tämä."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Testikehystila käytössä"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Palauta tehdasasetukset, niin voit poistaa testikehystilan käytöstä."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Sarjakonsoli käytössä"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Tämä vaikuttaa suorituskykyyn. Jos haluat poistaa toiminnon käytöstä, tarkista käynnistysohjelma."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Nestettä tai likaa USB-portissa"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-portti poistetaan käytöstä automaattisesti. Napauta nähdäksesi lisätietoja."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB-portin käyttö on sallittu"</string>
@@ -1629,7 +1637,7 @@
     <string name="kg_pattern_instructions" msgid="398978611683075868">"Piirrä kuvio"</string>
     <string name="kg_sim_pin_instructions" msgid="2319508550934557331">"Anna SIM-kortin PIN-koodi"</string>
     <string name="kg_pin_instructions" msgid="2377242233495111557">"Anna PIN-koodi"</string>
-    <string name="kg_password_instructions" msgid="5753646556186936819">"Anna salasana"</string>
+    <string name="kg_password_instructions" msgid="5753646556186936819">"Lisää salasana"</string>
     <string name="kg_puk_enter_puk_hint" msgid="453227143861735537">"SIM-kortti on nyt poistettu käytöstä. Jatka antamalla PUK-koodi. Saat lisätietoja ottamalla yhteyttä operaattoriin."</string>
     <string name="kg_puk_enter_pin_hint" msgid="7871604527429602024">"Anna haluamasi PIN-koodi"</string>
     <string name="kg_enter_confirm_pin_hint" msgid="325676184762529976">"Vahvista haluamasi PIN-koodi"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Luokittelematon"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Voit valita näiden ilmoitusten tärkeyden."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Tämä on tärkeää siihen liittyvien ihmisten perusteella."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Myönnetäänkö sovellukselle <xliff:g id="APP">%1$s</xliff:g> oikeus luoda käyttäjä tilille <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Myönnetäänkö sovellukselle <xliff:g id="APP">%1$s</xliff:g> oikeus luoda käyttäjä tilille <xliff:g id="ACCOUNT">%2$s</xliff:g> (tilillä on jo käyttäjä)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Saako <xliff:g id="APP">%1$s</xliff:g> luoda uuden käyttäjän (<xliff:g id="ACCOUNT">%2$s</xliff:g>) – tällä käyttäjällä on jo tili?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Saako <xliff:g id="APP">%1$s</xliff:g> luoda uuden käyttäjän (<xliff:g id="ACCOUNT">%2$s</xliff:g>)?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Lisää kieli"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Alueasetus"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Anna kielen nimi"</string>
diff --git a/core/res/res/values-fr-rCA/strings.xml b/core/res/res/values-fr-rCA/strings.xml
index 4eae9ba..3bd5c23 100644
--- a/core/res/res/values-fr-rCA/strings.xml
+++ b/core/res/res/values-fr-rCA/strings.xml
@@ -100,7 +100,7 @@
     <string name="peerTtyModeHco" msgid="5728602160669216784">"Mode TTY HCO demandé par un pair"</string>
     <string name="peerTtyModeVco" msgid="1742404978686538049">"Mode TTY VCO demandé par un pair"</string>
     <string name="peerTtyModeOff" msgid="3280819717850602205">"Mode TTY DÉSACTIVÉ demandé par un pair"</string>
-    <string name="serviceClassVoice" msgid="1258393812335258019">"Google Voice"</string>
+    <string name="serviceClassVoice" msgid="1258393812335258019">"Voix"</string>
     <string name="serviceClassData" msgid="872456782077937893">"Données"</string>
     <string name="serviceClassFAX" msgid="5566624998840486475">"Télécopie"</string>
     <string name="serviceClassSMS" msgid="2015460373701527489">"SMS"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permet à l\'application de recevoir et de traiter les messages texte. Cette autorisation lui donne la possibilité de surveiller ou de supprimer les messages envoyés à votre appareil sans vous les montrer."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"recevoir des messages multimédias"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permet à l\'application de recevoir et de traiter les messages multimédias. Cette autorisation lui donne la possibilité de surveiller ou de supprimer les messages envoyés à votre appareil sans vous les montrer."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lire les messages de diffusion cellulaire"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permet à l\'application de lire les messages de diffusion cellulaire que votre appareil reçoit. Dans certaines zones géographiques, des alertes vous sont envoyées afin de vous prévenir en cas de situation d\'urgence. Des applications malveillantes peuvent venir perturber les performances ou le fonctionnement de votre appareil lors de la réception d\'un message de diffusion cellulaire."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lire les flux auxquels vous êtes abonné"</string>
@@ -530,9 +534,9 @@
     <string name="biometric_not_recognized" msgid="5770511773560736082">"Données biométriques non reconnues"</string>
     <string name="biometric_error_canceled" msgid="349665227864885880">"Authentification annulée"</string>
     <string name="biometric_error_device_not_secured" msgid="6583143098363528349">"Aucun NIP, schéma ou mot de passe défini"</string>
-    <string name="fingerprint_acquired_partial" msgid="735082772341716043">"Empreinte digitale partielle détectée. Veuillez essayer de nouveau."</string>
+    <string name="fingerprint_acquired_partial" msgid="735082772341716043">"Empreinte digitale partielle détectée. Veuillez réessayer."</string>
     <string name="fingerprint_acquired_insufficient" msgid="4596546021310923214">"Impossible de reconnaître l\'empreinte digitale. Veuillez réessayer."</string>
-    <string name="fingerprint_acquired_imager_dirty" msgid="1087209702421076105">"Le capteur d\'empreintes digitales est sale. Veuillez le nettoyer et essayer de nouveau."</string>
+    <string name="fingerprint_acquired_imager_dirty" msgid="1087209702421076105">"Le capteur d\'empreintes digitales est sale. Veuillez le nettoyer et réessayer."</string>
     <string name="fingerprint_acquired_too_fast" msgid="6470642383109155969">"Vous avez déplacé votre doigt trop rapidement. Veuillez réessayer."</string>
     <string name="fingerprint_acquired_too_slow" msgid="59250885689661653">"Vous avez déplacé votre doigt trop lentement. Veuillez réessayer."</string>
   <string-array name="fingerprint_acquired_vendor">
@@ -540,10 +544,10 @@
     <string name="fingerprint_authenticated" msgid="5309333983002526448">"Empreinte digitale authentifiée"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="4018680978348659031">"Visage authentifié"</string>
     <string name="face_authenticated_confirmation_required" msgid="8778347003507633610">"Visage authentifié, veuillez appuyer sur le bouton Confirmer"</string>
-    <string name="fingerprint_error_hw_not_available" msgid="7955921658939936596">"Matériel d\'empreinte numérique indisponible."</string>
+    <string name="fingerprint_error_hw_not_available" msgid="7955921658939936596">"Matériel d\'empreinte digitale numérique indisponible."</string>
     <string name="fingerprint_error_no_space" msgid="1055819001126053318">"L\'empreinte digitale ne peut pas être enregistrée. Veuillez supprimer une empreinte existante."</string>
-    <string name="fingerprint_error_timeout" msgid="3927186043737732875">"Le temps attribué pour lire l\'empreinte est écoulé. Veuillez essayer de nouveau."</string>
-    <string name="fingerprint_error_canceled" msgid="4402024612660774395">"Opération d\'empreinte numérique annulée."</string>
+    <string name="fingerprint_error_timeout" msgid="3927186043737732875">"Le temps attribué pour lire l\'empreinte digitale est écoulé. Veuillez réessayer."</string>
+    <string name="fingerprint_error_canceled" msgid="4402024612660774395">"Opération d\'empreinte digitale numérique annulée."</string>
     <string name="fingerprint_error_user_canceled" msgid="7999639584615291494">"L\'opération d\'empreinte digitale a été annulée par l\'utilisateur."</string>
     <string name="fingerprint_error_lockout" msgid="5536934748136933450">"Trop de tentatives. Veuillez réessayer plus tard."</string>
     <string name="fingerprint_error_lockout_permanent" msgid="5033251797919508137">"Trop de tentatives. Capteur d\'empreintes digitales désactivé."</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permet à l\'application de consulter et de modifier la configuration du mode Ne pas déranger."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"démarrer l\'affichage de l\'usage des autorisations"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permet au détenteur de démarrer l\'usage des autorisations pour une application. Cette fonctionnalité ne devrait pas être nécessaire pour les applications standards."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cible du raccourci d\'accessibilité"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permet à une application de définir la cible du raccourci d\'accessibilité."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Définir les règles du mot de passe"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Gérer le nombre et le type de caractères autorisés dans les mots de passe et les NIP de verrouillage de l\'écran."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Gérer les tentatives de déverrouillage de l\'écran"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Sélectionnez cette option pour désactiver le débogage USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Mode Logiciel de test activé"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Effectuez une réinitialisation pour désactiver le mode Logiciel de test."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"La console série est activée"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"La performance est réduite. Pour désactiver cette fonction, vérifier le programme d\'amorçage."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Liquide ou débris dans le port USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Le port USB est désactivé automatiquement. Touchez ici pour en savoir plus."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Autorisation d\'utiliser le port USB"</string>
@@ -1579,8 +1587,8 @@
     <string name="expires_on" msgid="3676242949915959821">"Expire le :"</string>
     <string name="serial_number" msgid="758814067660862493">"Numéro de série :"</string>
     <string name="fingerprints" msgid="4516019619850763049">"Empreintes :"</string>
-    <string name="sha256_fingerprint" msgid="4391271286477279263">"Empreinte SHA-256 :"</string>
-    <string name="sha1_fingerprint" msgid="7930330235269404581">"Empreinte SHA-1 :"</string>
+    <string name="sha256_fingerprint" msgid="4391271286477279263">"Empreinte digitale SHA-256 :"</string>
+    <string name="sha1_fingerprint" msgid="7930330235269404581">"Empreinte digitale SHA-1 :"</string>
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Tout afficher"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Sélectionnez une activité"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Partagez avec"</string>
@@ -1672,10 +1680,10 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"Le raccourci d\'accessibilité a désactivé la fonction <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Maintenez enfoncées les deux touches de volume pendant trois secondes pour utiliser <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Choisissez un service à utiliser lorsque vous touchez le bouton d\'accessibilité :"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Choisissez un service à utiliser lorsque vous utilisez le geste d\'accessibilité (balayer deux doigts du bas de l\'écran vers le haut) :"</string>
-    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Choisissez un service à utiliser lorsque vous utilisez le geste d\'accessibilité (balayer trois doigts du bas de l\'écran vers le haut) :"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Choisissez un service à utiliser lorsque vous utilisez le geste d\'accessibilité (balayer l\'écran de bas en haut avec deux doigts) :"</string>
+    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Choisissez un service à utiliser lorsque vous utilisez le geste d\'accessibilité (balayer l\'écran de bas en haut avec trois doigts) :"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Pour basculer entre les services, maintenez le doigt sur le bouton d\'accessibilité."</string>
-    <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Pour basculer entre les services, balayez deux doigts vers le haut et maintenez-les sur l\'écran."</string>
+    <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Pour basculer entre les services, balayez l\'écrfan vers le haut avec deux doigts et maintenez-les-y."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Pour changer de service, balayez trois doigts vers le haut et maintenez-les sur l\'écran."</string>
     <string name="accessibility_magnification_chooser_text" msgid="1227146738764986237">"Zoom"</string>
     <string name="user_switched" msgid="3768006783166984410">"Utilisateur actuel : <xliff:g id="NAME">%1$s</xliff:g>"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sans catégorie"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Vous définissez l\'importance de ces notifications."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ces notifications sont importantes en raison des participants."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil d\'utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil d\'utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Un utilisateur associé à ce compte existe déjà.)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un utilisateur <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Un utilisateur est déjà associé à ce compte)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil d\'utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Ajouter une langue"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Préférences régionales"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Entrez la langue"</string>
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index 1fd552e..8520c13 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -292,7 +292,7 @@
     <string name="permgrouprequest_calendar" msgid="289900767793189421">"Permettre à &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; d\'accéder à votre agenda ?"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"envoyer et consulter des SMS"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Permettre à &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; d\'envoyer et d\'afficher des SMS ?"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Autoriser l\'application &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; à envoyer et afficher des SMS ?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Stockage"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"accéder aux photos, contenus multimédias et fichiers sur votre appareil"</string>
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"Autoriser l\'appli &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; à accéder aux photos, contenus multimédias et fichiers sur votre appareil ?"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permet à l\'application de recevoir et de traiter les SMS. Cette autorisation lui donne la possibilité de surveiller ou supprimer les messages envoyés à votre appareil sans vous les montrer."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"recevoir des messages texte (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permet à l\'application de recevoir et de traiter les MMS. Cette autorisation lui donne la possibilité de surveiller ou supprimer les messages envoyés à votre appareil sans vous les montrer."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lire les messages reçus via un canal de diffusion cellulaire"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permet à l\'application de lire les messages que votre appareil reçoit via un canal de diffusion cellulaire. Dans certaines zones géographiques, des alertes vous sont envoyées afin de vous prévenir en cas de situation d\'urgence. Les applications malveillantes peuvent venir perturber les performances ou le fonctionnement de votre appareil lorsqu\'un message est reçu via un canal de diffusion cellulaire."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lire les flux auxquels vous êtes abonné"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permet à l\'application de consulter et de modifier la configuration du mode Ne pas déranger."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"activer l\'utilisation de l\'autorisation d\'affichage"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permet à l\'application autorisée d\'activer l\'utilisation de l\'autorisation pour une application. Cette fonctionnalité ne devrait pas être nécessaire pour les applications standards."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cible du raccourci d\'accessibilité"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Autorise une application à définir la cible du raccourci d\'accessibilité."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Définir les règles du mot de passe"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Gérer le nombre et le type de caractères autorisés dans les mots de passe et les codes d\'accès de verrouillage de l\'écran"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Gérer les tentatives de déverrouillage de l\'écran"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Sélectionnez cette option pour désactiver le débogage USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Mode Atelier de test activé"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Rétablissez la configuration d\'usine pour désactiver le mode Atelier de test."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Console série activée"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Les performances sont affectées. Pour désactiver la console série, vérifiez le bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Présence de liquide ou de saletés dans le port USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Le port USB est désactivé automatiquement. Appuyez sur cette notification pour en savoir plus."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Le port USB peut être utilisé"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sans catégorie"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Vous définissez l\'importance de ces notifications."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ces notifications sont importantes en raison des participants."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g> (un utilisateur associé à ce compte existe déjà) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g> (un utilisateur associé à ce compte existe déjà) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Ajouter une langue"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Préférences régionales"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Saisissez la langue"</string>
diff --git a/core/res/res/values-gl/strings.xml b/core/res/res/values-gl/strings.xml
index 919a13d..78c7d03 100644
--- a/core/res/res/values-gl/strings.xml
+++ b/core/res/res/values-gl/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite á aplicación recibir e procesar mensaxes SMS. Isto significa que a aplicación pode supervisar ou eliminar mensaxes enviadas ao teu dispositivo sen mostrarchas."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"recibir mensaxes de texto (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite á aplicación recibir e procesar mensaxes MMS. Isto significa que a aplicación pode supervisar ou eliminar mensaxes enviadas ao teu dispositivo sen mostrarchas."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ler mensaxes de difusión móbil"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite á aplicación ler mensaxes de difusión móbil recibidas polo teu dispositivo. As alertas de difusión móbil envíanse nalgunhas localizacións para avisar de situacións de emerxencia. É posible que aplicacións maliciosas afecten ao rendemento ou funcionamento do teu dispositivo cando se recibe unha difusión móbil de emerxencia."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ler feeds subscritos"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permite á aplicación ler e escribir a configuración do modo Non molestar."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"iniciar uso de permiso de vista"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permite ao propietario iniciar o uso de permisos dunha aplicación. As aplicacións normais non deberían precisalo nunca."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"obxectivo do atallo de accesibilidade"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permite que unha aplicación defina o obxectivo do atallo de accesibilidade."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Establecer as normas de contrasinal"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controla a lonxitude e os caracteres permitidos nos contrasinais e nos PIN de bloqueo da pantalla."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Controlar os intentos de desbloqueo da pantalla"</string>
@@ -1094,27 +1100,27 @@
     <string name="inputMethod" msgid="1653630062304567879">"Método de introdución de texto"</string>
     <string name="editTextMenuTitle" msgid="4909135564941815494">"Accións de texto"</string>
     <string name="email" msgid="4560673117055050403">"Correo electrónico"</string>
-    <string name="email_desc" msgid="3638665569546416795">"Envía un correo electrónico ao enderezo seleccionado"</string>
+    <string name="email_desc" msgid="3638665569546416795">"Enviar un correo electrónico ao enderezo seleccionado"</string>
     <string name="dial" msgid="1253998302767701559">"Chamar"</string>
-    <string name="dial_desc" msgid="6573723404985517250">"Chama ao número de teléfono seleccionado"</string>
+    <string name="dial_desc" msgid="6573723404985517250">"Chamar ao número de teléfono seleccionado"</string>
     <string name="map" msgid="5441053548030107189">"Mapa"</string>
-    <string name="map_desc" msgid="1836995341943772348">"Localiza o enderezo seleccionado"</string>
+    <string name="map_desc" msgid="1836995341943772348">"Localizar o enderezo seleccionado"</string>
     <string name="browse" msgid="1245903488306147205">"Abrir"</string>
-    <string name="browse_desc" msgid="8220976549618935044">"Abre o URL seleccionado"</string>
+    <string name="browse_desc" msgid="8220976549618935044">"Abrir o URL seleccionado"</string>
     <string name="sms" msgid="4560537514610063430">"Enviar SMS"</string>
-    <string name="sms_desc" msgid="7526588350969638809">"Envía unha mensaxe ao número de teléfono seleccionado"</string>
+    <string name="sms_desc" msgid="7526588350969638809">"Enviar unha mensaxe ao número de teléfono seleccionado"</string>
     <string name="add_contact" msgid="7867066569670597203">"Engadir"</string>
-    <string name="add_contact_desc" msgid="4830217847004590345">"Engade o elemento aos contactos"</string>
+    <string name="add_contact_desc" msgid="4830217847004590345">"Engadir o elemento aos contactos"</string>
     <string name="view_calendar" msgid="979609872939597838">"Ver"</string>
-    <string name="view_calendar_desc" msgid="5828320291870344584">"Consulta a hora seleccionada no calendario"</string>
+    <string name="view_calendar_desc" msgid="5828320291870344584">"Consultar a hora seleccionada no calendario"</string>
     <string name="add_calendar_event" msgid="1953664627192056206">"Programar"</string>
-    <string name="add_calendar_event_desc" msgid="4326891793260687388">"Programa un evento para a data seleccionada"</string>
+    <string name="add_calendar_event_desc" msgid="4326891793260687388">"Programar un evento para a data seleccionada"</string>
     <string name="view_flight" msgid="7691640491425680214">"Realizar seguimento"</string>
-    <string name="view_flight_desc" msgid="3876322502674253506">"Fai un seguimento do voo seleccionado"</string>
+    <string name="view_flight_desc" msgid="3876322502674253506">"Facer un seguimento do voo seleccionado"</string>
     <string name="translate" msgid="9218619809342576858">"Traducir"</string>
-    <string name="translate_desc" msgid="4502367770068777202">"Traduce o texto seleccionado"</string>
+    <string name="translate_desc" msgid="4502367770068777202">"Traducir o texto seleccionado"</string>
     <string name="define" msgid="7394820043869954211">"Definir"</string>
-    <string name="define_desc" msgid="7910883642444919726">"Define o texto seleccionado"</string>
+    <string name="define_desc" msgid="7910883642444919726">"Definir o texto seleccionado"</string>
     <string name="low_internal_storage_view_title" msgid="5576272496365684834">"Estase esgotando o espazo de almacenamento"</string>
     <string name="low_internal_storage_view_text" msgid="6640505817617414371">"É posible que algunhas funcións do sistema non funcionen"</string>
     <string name="low_internal_storage_view_text_no_boot" msgid="6935190099204693424">"Non hai almacenamento suficiente para o sistema. Asegúrate de ter un espazo libre de 250 MB e reinicia o dispositivo."</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Selecciona a opción para desactivar a depuración por USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Activouse o modo de axente de proba"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Restablece a configuración de fábrica para desactivar o modo de axente de proba."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"A consola de serie está activada"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"O rendemento vese afectado. Para desactivar a consola, comproba o cargador de arranque."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Hai líquido ou residuos no porto USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"O porto USB desactivouse automaticamente. Toca para obter máis información."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Pódese utilizar o porto USB"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sen clasificar"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ti defines a importancia destas notificacións."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"É importante polas persoas involucradas."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Queres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario novo con <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Queres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario novo con <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Xa existe un usuario con esta conta)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Queres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario novo con <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Xa existe un usuario con esta conta)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Queres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario novo con <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Engadir un idioma"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferencia de rexión"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Nome do idioma"</string>
diff --git a/core/res/res/values-gu/strings.xml b/core/res/res/values-gu/strings.xml
index ecf717a..340245a 100644
--- a/core/res/res/values-gu/strings.xml
+++ b/core/res/res/values-gu/strings.xml
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને તમારા સંપર્કોને ઍક્સેસ કરવાની મંજૂરી આપીએ?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"સ્થાન"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"આ ઉપકરણના સ્થાનને ઍક્સેસ કરવાની"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને આ ઉપકરણના સ્થાનને ઍક્સેસ કરવાની મંજૂરી આપીએ?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને આ ડિવાઇસના સ્થાનને ઍક્સેસ કરવાની મંજૂરી આપીએ?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"જ્યારે તમે ઍપનો ઉપયોગ કરી રહ્યા હશો માત્ર ત્યારે જ ઍપ સ્થાનને ઍક્સેસ કરી શકશે"</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને આ ડિવાઇસનું સ્થાન &lt;b&gt;હંમેશાં&lt;/b&gt; ઍક્સેસ કરવાની મંજૂરી આપીએ?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"હાલમાં માત્ર જ્યારે તમે ઍપનો ઉપયોગ કરી રહ્યા હશો હોય ત્યારે જ ઍપ સ્થાનને ઍક્સેસ કરી શકશે"</string>
@@ -295,10 +295,10 @@
     <string name="permgrouprequest_sms" msgid="7168124215838204719">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને SMS સંદેશા મોકલવા અને જોવાની મંજૂરી આપીએ?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"સ્ટોરેજ"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"તમારા ઉપકરણ પર ફોટો, મીડિયા અને ફાઇલો ઍક્સેસ કરવાની"</string>
-    <string name="permgrouprequest_storage" msgid="7885942926944299560">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને તમારા ઉપકરણ પર ફોટા, મીડિયા અને ફાઇલોને ઍક્સેસ કરવાની મંજૂરી આપીએ?"</string>
+    <string name="permgrouprequest_storage" msgid="7885942926944299560">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને તમારા ડિવાઇસ પર ફોટા, મીડિયા અને ફાઇલોને ઍક્સેસ કરવાની મંજૂરી આપીએ?"</string>
     <string name="permgrouplab_microphone" msgid="171539900250043464">"માઇક્રોફોન"</string>
     <string name="permgroupdesc_microphone" msgid="4988812113943554584">"ઑડિઓ રેકોર્ડ કરવાની"</string>
-    <string name="permgrouprequest_microphone" msgid="9167492350681916038">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને ઑડિઓ રેકૉર્ડ કરવાની મંજૂરી આપીએ?"</string>
+    <string name="permgrouprequest_microphone" msgid="9167492350681916038">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને ઑડિયો રેકૉર્ડ કરવાની મંજૂરી આપીએ?"</string>
     <string name="permgrouplab_activityRecognition" msgid="1565108047054378642">"શારીરિક પ્રવૃત્તિ"</string>
     <string name="permgroupdesc_activityRecognition" msgid="6949472038320473478">"તમારી શારીરિક પ્રવૃત્તિને ઍક્સેસ કરવી"</string>
     <string name="permgrouprequest_activityRecognition" msgid="7626438016904799383">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ને તમારી શારીરિક પ્રવૃત્તિને ઍક્સેસ કરવાની મંજૂરી આપવી છે?"</string>
@@ -325,7 +325,7 @@
     <string name="capability_title_canPerformGestures" msgid="7418984730362576862">"હાવભાવ કરો"</string>
     <string name="capability_desc_canPerformGestures" msgid="8296373021636981249">"ટૅપ, સ્વાઇપ, પિંચ કરી અને અન્ય હાવભાવ કરી શકે છે."</string>
     <string name="capability_title_canCaptureFingerprintGestures" msgid="6309568287512278670">"ફિંગરપ્રિન્ટ સંકેતો"</string>
-    <string name="capability_desc_canCaptureFingerprintGestures" msgid="4386487962402228670">"ઉપકરણના ફિંગરપ્રિન્ટ સેન્સર પર કરવામાં આવેલા સંકેતો કૅપ્ચર કરી શકે છે."</string>
+    <string name="capability_desc_canCaptureFingerprintGestures" msgid="4386487962402228670">"ડિવાઇસના ફિંગરપ્રિન્ટ સેન્સર પર કરવામાં આવેલા સંકેતો કૅપ્ચર કરી શકે છે."</string>
     <string name="permlab_statusBar" msgid="7417192629601890791">"સ્ટેટસ બારને અક્ષમ કરો અથવા તેમાં ફેરફાર કરો"</string>
     <string name="permdesc_statusBar" msgid="8434669549504290975">"ઍપ્લિકેશનને સ્ટેટસ બાર અક્ષમ કરવાની અથવા સિસ્ટમ આયકન્સ ઉમેરવા અને દૂર કરવાની મંજૂરી આપે છે."</string>
     <string name="permlab_statusBarService" msgid="4826835508226139688">"સ્ટેટસ બારમાં બતાવો"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"ઍપ્લિકેશનને SMS સંદેશા પ્રાપ્ત કરવાની અને તેના પર પ્રક્રિયા કરવાની મંજૂરી આપે છે. આનો અર્થ એ કે ઍપ્લિકેશન તમને દર્શાવ્યા વિના તમારા ઉપકરણ પર મોકલેલ સંદેશાઓનું નિરીક્ષણ કરી શકે છે અથવા કાઢી નાખી શકે છે."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ટેક્સ્ટ સંદેશા (MMS) પ્રાપ્ત કરો"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"ઍપ્લિકેશનને MMS સંદેશા પ્રાપ્ત કરવાની અને તેના પર પ્રક્રિયા કરવાની મંજૂરી આપે છે. આનો અર્થ એ કે ઍપ્લિકેશન તમને દર્શાવ્યા વિના તમારા ઉપકરણ પર મોકલેલ સંદેશાઓનું નિરીક્ષણ કરી શકે છે અથવા કાઢી નાખી શકે છે."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"સેલ બ્રોડકાસ્ટ સંદેશા વાંચો"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"એપ્લિકેશનને તમારા ઉપકરણ દ્વારા પ્રાપ્ત થયેલ સેલ બ્રોડકાસ્ટ સંદેશાને વાંચવાની મંજૂરી આપે છે. સેલ બ્રોડકાસ્ટ ચેતવણીઓ તમને કટોકટીની સ્થિતિઓ અંગે ચેતવવા માટે કેટલાક સ્થાનોમાં વિતરિત થાય છે. જ્યારે કટોકટીનો સેલ બ્રોડકાસ્ટ પ્રાપ્ત થાય ત્યારે દુર્ભાવનાપૂર્ણ ઍપ્લિકેશનો તમારા ઉપકરણના પ્રદર્શન અથવા ઓપરેશનમાં હસ્તક્ષેપ કરી શકે છે."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"સબ્સ્ક્રાઇબ કરેલ ફીડ્સ વાંચો"</string>
@@ -513,9 +517,9 @@
     <string name="permlab_useBiometric" msgid="8837753668509919318">"બાયોમેટ્રિક હાર્ડવેરનો ઉપયોગ કરો"</string>
     <string name="permdesc_useBiometric" msgid="8389855232721612926">"ઍપને પ્રમાણીકરણ માટે બાયોમેટ્રિક હાર્ડવેરનો ઉપયોગ કરવાની મંજૂરી આપે છે"</string>
     <string name="permlab_manageFingerprint" msgid="5640858826254575638">"ફિંગરપ્રિન્ટ હાર્ડવેરને સંચાલિત કરો"</string>
-    <string name="permdesc_manageFingerprint" msgid="178208705828055464">"એપ્લિકેશનને ઉપયોગ માટે ફિંગરપ્રિન્ટ નમૂના ઉમેરવા અને કાઢી નાખવા માટે પદ્ધતિઓની વિનંતી કરવાની મંજૂરી આપે છે."</string>
+    <string name="permdesc_manageFingerprint" msgid="178208705828055464">"ઍપને ઉપયોગ માટે ફિંગરપ્રિન્ટ નમૂના ઉમેરવા અને કાઢી નાખવા માટે પદ્ધતિઓની વિનંતી કરવાની મંજૂરી આપે છે."</string>
     <string name="permlab_useFingerprint" msgid="3150478619915124905">"ફિંગરપ્રિન્ટ હાર્ડવેરનો ઉપયોગ કરો"</string>
-    <string name="permdesc_useFingerprint" msgid="9165097460730684114">"એપ્લિકેશનને પ્રમાણીકરણ માટે ફિંગરપ્રિન્ટ હાર્ડવેરનો ઉપયોગ કરવાની મંજૂરી આપે છે"</string>
+    <string name="permdesc_useFingerprint" msgid="9165097460730684114">"ઍપને પ્રમાણીકરણ માટે ફિંગરપ્રિન્ટ હાર્ડવેરનો ઉપયોગ કરવાની મંજૂરી આપે છે"</string>
     <string name="permlab_audioWrite" msgid="2661772059799779292">"આપનો સંગીત સંગ્રહ સંશોધિત કરવો"</string>
     <string name="permdesc_audioWrite" msgid="8888544708166230494">"એપને તમારો સંગીત સંગ્રહ સંશોધિત કરવાની મંજૂરી આપે છે."</string>
     <string name="permlab_videoWrite" msgid="128769316366746446">"આપનો વિડિઓ સંગ્રહ સંશોધિત કરવો"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"એપ્લિકેશનને ખલેલ પાડશો નહીં ગોઠવણી વાંચવા અને લખવાની મંજૂરી આપે છે."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"પરવાનગી વપરાશ જુઓને શરૂ કરો"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"કોઈ ઍપ માટે પરવાનગી વપરાશ શરૂ કરવાની ધારકને મંજૂરી આપે છે. સામાન્ય ઍપ માટે ક્યારેય જરૂર પડી ન શકે."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ઍક્સેસિબિલિટી શૉર્ટકટ ટાર્ગેટ"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ઍપને ઍક્સેસિબિલિટી શૉર્ટકટ ટાર્ગેટ વ્યાખ્યાતિત કરવાની મંજૂરી આપે છે."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"પાસવર્ડ નિયમો સેટ કરો"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"સ્ક્રીન લૉક પાસવર્ડ અને પિનમાં મંજૂર લંબાઈ અને અક્ષરોને નિયંત્રિત કરો."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"સ્ક્રીનને અનલૉક કરવાના પ્રયત્નોનું નિયમન કરો"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ડિબગીંગને અક્ષમ કરવા માટે પસંદ કરો."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"ટેસ્ટ હાર્નેસ મોડ ચાલુ કર્યો"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"ટેસ્ટ હાર્નેસ મોડ બંધ કરવા માટે ફૅક્ટરી રીસેટ કરો."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"સિરીયલ કન્સોલ ચાલુ થયો"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"કાર્યપ્રદર્શનને અસર થાય છે. બંધ કરવા માટે, બૂટલોડર ચેક કરો."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB પોર્ટમાં પ્રવાહી કે ધૂળ"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB પોર્ટ ઑટોમૅટિક રીતે બંધ કરવામાં આવ્યો છે. વધુ જાણવા માટે ટૅપ કરો."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB પોર્ટનો ઉપયોગ કરવો યોગ્ય છે"</string>
@@ -1580,8 +1588,8 @@
     <string name="expires_on" msgid="3676242949915959821">"આ રોજ સમાપ્ત:"</string>
     <string name="serial_number" msgid="758814067660862493">"શૃંખલા ક્રમાંક:"</string>
     <string name="fingerprints" msgid="4516019619850763049">"ફિંગરપ્રિંટ્સ:"</string>
-    <string name="sha256_fingerprint" msgid="4391271286477279263">"SHA-256 ફિંગરપ્રિંટ:"</string>
-    <string name="sha1_fingerprint" msgid="7930330235269404581">"SHA-1 ફિંગરપ્રિંટ:"</string>
+    <string name="sha256_fingerprint" msgid="4391271286477279263">"SHA-256 ફિંગરપ્રિન્ટ:"</string>
+    <string name="sha1_fingerprint" msgid="7930330235269404581">"SHA-1 ફિંગરપ્રિન્ટ:"</string>
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"બધું જુઓ"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"પ્રવૃત્તિ પસંદ કરો"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"આની સાથે શેર કરો"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"અવર્ગીકૃત"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"તમે આ સૂચનાઓનું મહત્વ સેટ કર્યું છે."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"શામેલ થયેલ લોકોને કારણે આ મહત્વપૂર્ણ છે."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> ને <xliff:g id="ACCOUNT">%2$s</xliff:g> સાથે એક નવા વપરાશકર્તાને બનાવવાની મંજૂરી આપીએ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g> સાથે <xliff:g id="APP">%1$s</xliff:g> ને એક નવા વપરાશકર્તાને બનાવવાની મંજૂરી આપીએ (આ એકાઉન્ટ સાથેના એક વપરાશકર્તા પહેલાંથી અસ્તિત્વમાં છે)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g>ને <xliff:g id="ACCOUNT">%2$s</xliff:g> માટે એક નવા વપરાશકર્તા બનાવવાની મંજૂરી આપીએ (આ એકાઉન્ટ માટે એક વપરાશકર્તા પહેલાંથી અસ્તિત્વમાં છે) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g>ને <xliff:g id="ACCOUNT">%2$s</xliff:g> માટે એક નવા વપરાશકર્તા બનાવવાની મંજૂરી આપીએ ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ભાષા ઉમેરો"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"પ્રદેશ પસંદગી"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ભાષાનું નામ ટાઇપ કરો"</string>
diff --git a/core/res/res/values-hi/strings.xml b/core/res/res/values-hi/strings.xml
index 53e9217..8f78f95 100644
--- a/core/res/res/values-hi/strings.xml
+++ b/core/res/res/values-hi/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"एप्लिकेशन को मैसेज (एसएमएस) पाने और प्रोसेस करने देता है. इसका मतलब है कि एप्लिकेशन आपके डिवाइस पर भेजे गए मैसेज की निगरानी आपको दिखाए बिना कर सकता है और उन्‍हें हटा सकता है."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"मैसेज (एमएमएस) पाएं"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"ऐप को मल्टीमीडिया मैसेज (एमएमएस) को पाने और उन पर कार्रवाई करने देता है. इसका मतलब है कि ऐप आपके डिवाइस पर भेजे गए मैसेज की निगरानी आपको दिखाए बिना कर सकता है और उन्‍हें हटा सकता है."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"सेल ब्रॉडकास्ट (CBC) मैसेज पढ़ें"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ऐप को, वो सेल ब्रॉडकास्ट (CBC) मैसेज पढ़ने देता है जो आपके डिवाइस को मिले हैं. सेल ब्रॉडकास्ट (CBC) अलर्ट कुछ स्थानों (लोकेशन) पर आपको आपातकालीन स्‍थितियों की चेतावनी देने के लिए दिए जाते हैं. आपातकालीन सेल ब्रॉडकास्ट (CBC) मिलने पर, धोखा देने वाले ऐप आपके डिवाइस के परफ़ॉर्मेंस या कार्यवाही में दखल दे सकते हैं."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"सदस्यता वाली फ़ीड पढ़ें"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"ऐप को परेशान न करें कॉन्फ़िगरेशन पढ़ने और लिखने देती है."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"देखने की अनुमतियां चालू करें"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"इस्तेमाल करने वाले को किसी ऐप्लिकेशन के लिए अनुमतियों का इस्तेमाल शुरू करने देता है. सामान्य ऐप्लिकेशन के लिए इसकी ज़रूरत कभी नहीं पड़ती."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"सुलभता शॉर्टकट टारगेट"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"सुलभता शॉर्टकट टारगेट के बारे में बताने के लिए ऐप्लिकेशन को मंज़ूरी दें."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"पासवर्ड नियम सेट करना"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"स्‍क्रीन लॉक पासवर्ड और पिन की लंबाई और उनमें स्वीकृत वर्णों को नियंत्रित करना."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"स्‍क्रीन अनलॉक करने के की कोशिशों पर नज़र रखना"</string>
@@ -1155,7 +1161,7 @@
     <string name="whichImageCaptureApplicationNamed" msgid="8619384150737825003">"%1$s के साथ चित्र कैप्चर करें"</string>
     <string name="whichImageCaptureApplicationLabel" msgid="6390303445371527066">"चित्र कैप्चर करें"</string>
     <string name="alwaysUse" msgid="4583018368000610438">"इस कार्रवाई के लिए डिफ़ॉल्‍ट के तौर पर इस्तेमाल करें"</string>
-    <string name="use_a_different_app" msgid="8134926230585710243">"किसी भिन्न ऐप्स का उपयोग करें"</string>
+    <string name="use_a_different_app" msgid="8134926230585710243">"किसी दूसरे ऐप्लिकेशन का इस्तेमाल करें"</string>
     <string name="clearDefaultHintMsg" msgid="3252584689512077257">"सिस्‍टम सेटिंग और डाउनलोड किए गए ऐप में डिफ़ॉल्‍ट साफ़ करें."</string>
     <string name="chooseActivity" msgid="7486876147751803333">"कोई कार्रवाई चुनें"</string>
     <string name="chooseUsbActivity" msgid="6894748416073583509">"USB डिवाइस के लिए कोई ऐप्स  चुनें"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB डीबग करना अक्षम करने के लिए चुनें."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"टेस्ट हार्नेस मोड चालू किया गया"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"टेस्ट हार्नेस मोड बंद करने के लिए फ़ैक्ट्री रीसेट करें."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"सीरियल कंसोल को चालू करें"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"परफ़ॉर्मेंस पर असर पड़ा है. बंद करने के लिए बूटलोडर चुनें."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"यूएसबी पोर्ट में तरल चीज़ या कचरा है"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"यूएसबी पोर्ट अपने आप बंद हो गया है. ज़्यादा जानने के लिए टैप करें."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"यूएसबी पोर्ट का इस्तेमाल करना सुरक्षित है"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"बिना किसी श्रेणी के"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"आपने इन सूचनाओं की अहमियत सेट की है."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"यह मौजूद व्यक्तियों के कारण महत्वपूर्ण है."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> को <xliff:g id="ACCOUNT">%2$s</xliff:g> के ज़रिये एक नया उपयोगकर्ता बनाने दें?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> को <xliff:g id="ACCOUNT">%2$s</xliff:g> के ज़रिये एक नया उपयोगकर्ता बनाने दें (इस खाते वाले एक उपयोगकर्ता पहले से मौजूद हैं)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> को <xliff:g id="ACCOUNT">%2$s</xliff:g> के नाम से एक नया उपयोगकर्ता बनाने की अनुमति दें (इस नाम से एक खाता पहले से मौजूद है)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"भाषा जोड़ें"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"क्षेत्र प्राथमिकता"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"भाषा का नाम लिखें"</string>
diff --git a/core/res/res/values-hr/strings.xml b/core/res/res/values-hr/strings.xml
index 4908780..8ddd5f8 100644
--- a/core/res/res/values-hr/strings.xml
+++ b/core/res/res/values-hr/strings.xml
@@ -347,6 +347,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Aplikaciji omogućuje primanje i obradu SMS poruka. To znači da aplikacija može nadzirati ili izbrisati poruke poslane na vaš uređaj, a da vam ih ne prikaže."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"primanje tekstnih poruka (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Aplikaciji omogućuje primanje i obradu MMS poruka. To znači da aplikacija može nadzirati ili izbrisati poruke poslane na vaš uređaj, a da vam ih ne prikaže."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"čitaj poruke koje se emitiraju unutar mobilne mreže"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Omogućuje aplikaciji čitanje poruka emitiranih unutar mobilne mreže koje prima vaš uređaj. Upozorenja koja se emitiraju na području mobilne mreže dostavljaju se na nekim lokacijama kako bi upozorila korisnike na hitne situacije. Zlonamjerne aplikacije mogu ometati izvršavanje ili rad vašeg uređaja kada stigne hitno upozorenje koje se emitira unutar mobilne mreže."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"čitanje pretplaćenih feedova"</string>
@@ -658,6 +662,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Omogućuje aplikaciji čitanje i pisanje konfiguracije opcije Ne ometaj."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"pokrenuti upotrebu dopuštenja za pregled"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Dopušta nositelju pokretanje upotrebe dopuštenja za aplikaciju. Ne bi smjelo biti potrebno za uobičajene aplikacije."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cilj prečaca pristupačnosti"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Aplikaciji omogućuje da definira cilj prečaca pristupačnosti."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Postavi pravila zaporke"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Upravlja duljinom i znakovima koji su dopušteni u zaporkama i PIN-ovima zaključavanja zaslona."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Nadziri pokušaje otključavanja zaslona"</string>
@@ -1383,6 +1389,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Odaberite da biste onemogućili rješavanje programske pogreške na USB-u."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Omogućen je način testnog okvira"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Vratite na tvorničke postavke da biste onemogućili način testnog okvira."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serijska konzola omogućena"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Izvedba je otežana. Provjerite početni program za pokretanje da biste onemogućili konzolu."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Tekućina ili prljavština u USB priključku"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB priključak automatski je onemogućen. Dodirnite da biste saznali više."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Možete koristiti USB priključak"</string>
@@ -1696,7 +1704,7 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"Prečac pristupačnosti isključio je uslugu <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Pritisnite i zadržite tipke za glasnoću na tri sekunde da biste koristili uslugu <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Odaberite uslugu koju ćete upotrebljavati kad dodirnete gumb pristupačnosti:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Odaberite uslugu koju ćete upotrebljavati uz pokret pristupačnosti (prelazak s dva prsta prema gore od dna zaslona):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Odaberite za što će se upotrebljavati pokret pristupačnosti (prelazak s dva prsta prema gore od dna zaslona):"</string>
     <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Odaberite uslugu koju ćete upotrebljavati uz pokret pristupačnosti (prelazak s tri prsta prema gore od dna zaslona):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Da biste prešli na neku drugu uslugu, dodirnite i zadržite gumb pristupačnosti."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Da biste prešli na neku drugu uslugu, prijeđite s dva prsta prema gore i zadržite."</string>
@@ -1924,8 +1932,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Nema kategorije"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Postavili ste važnost tih obavijesti."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Važno je zbog uključenih osoba."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Želite li dopustiti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da izradi novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Želite li dopustiti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da izradi novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik s tim računom već postoji)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Dopustiti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da izradi novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik s ovim računom već postoji)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Dopustiti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da izradi novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Dodavanje jezika"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Postavke regije"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Unesite naziv jezika"</string>
diff --git a/core/res/res/values-hu/strings.xml b/core/res/res/values-hu/strings.xml
index e32457a..d910025 100644
--- a/core/res/res/values-hu/strings.xml
+++ b/core/res/res/values-hu/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Lehetővé teszi az alkalmazás számára, hogy SMS-eket fogadjon és dolgozzon fel. Ez azt jelenti, hogy az alkalmazás megfigyelheti vagy törölheti a beérkező üzeneteket anélkül, hogy Ön látná azokat."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"szöveges üzenetek (MMS) fogadása"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Lehetővé teszi az alkalmazás számára, hogy MMS-eket fogadjon és dolgozzon fel. Ez azt jelenti, hogy az alkalmazás megfigyelheti vagy törölheti a beérkező üzeneteket anélkül, hogy Ön látná azokat."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"cellán belüli üzenetek olvasása"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Lehetővé teszi az alkalmazás számára az eszközre érkező cellán belüli üzenetek olvasását. Bizonyos helyeken figyelmeztető üzeneteket kaphat a cellán belül a vészhelyzetekről. A rosszindulatú alkalmazások befolyásolhatják az eszköz  teljesítményét vagy működését vészhelyzeti cellaüzenet érkezésekor."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"feliratkozott hírcsatornák olvasása"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Az alkalmazás olvashatja és szerkesztheti a „Ne zavarjanak” funkció beállításait."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"engedélyhasználat megtekintésének elindítása"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Lehetővé teszi a felhasználó számára, hogy elindítsa az alkalmazás engedélyhasználatát. A normál alkalmazásoknak erre soha nincs szükségük."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"A kisegítő lehetőségek gyorsparancs célja"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Engedélyezi az alkalmazásoknak a kisegítő lehetőségek gyorsparancs céljának meghatározását."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Jelszavakkal kapcsolatos szabályok beállítása"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"A képernyőzár jelszavaiban és PIN kódjaiban engedélyezett karakterek és hosszúság vezérlése."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Képernyőzár-feloldási kísérletek figyelése"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Válassza ezt az USB hibakeresés kikapcsolásához."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Tesztelési alapkörnyezet mód engedélyezve"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"A Tesztelési alapkörnyezet mód kikapcsolásához állítsa vissza a gyári beállításokat."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Soros konzol engedélyezve"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Ez hatással van a teljesítményre. A letiltáshoz ellenőrizze a rendszerindítót."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Folyadék vagy szennyeződés az USB-portban"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-port automatikusan letiltva. Koppintson, ha további információra van szüksége."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Az USB-port rendben használható"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Nincs kategóriába sorolva"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ön állította be ezen értesítések fontossági szintjét."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ez az üzenet a résztvevők miatt fontos."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Engedélyezi a(z) <xliff:g id="APP">%1$s</xliff:g> számára, hogy új felhasználót hozzon létre a(z) <xliff:g id="ACCOUNT">%2$s</xliff:g> fiókkal?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Engedélyezi a(z) <xliff:g id="APP">%1$s</xliff:g> számára, hogy új felhasználót hozzon létre a(z) <xliff:g id="ACCOUNT">%2$s</xliff:g> fiókkal? (Már létezik felhasználó ezzel a fiókkal.)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Engedélyezi a(z) <xliff:g id="APP">%1$s</xliff:g> számára, hogy új felhasználót hozzon létre a(z) <xliff:g id="ACCOUNT">%2$s</xliff:g> fiókkal? (Már létezik felhasználó ezzel a fiókkal.)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Engedélyezi a(z) <xliff:g id="APP">%1$s</xliff:g> számára, hogy új felhasználót hozzon létre a(z) <xliff:g id="ACCOUNT">%2$s</xliff:g> fiókkal?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Nyelv hozzáadása"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Régió beállítása"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Adja meg a nyelvet"</string>
diff --git a/core/res/res/values-hy/strings.xml b/core/res/res/values-hy/strings.xml
index 5af2235..6f5507f 100644
--- a/core/res/res/values-hy/strings.xml
+++ b/core/res/res/values-hy/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Թույլ է տալիս հավելվածին ստանալ և մշակել SMS հաղորդագրությունները: Սա նշանակում է, որ հավելվածը կարող է ստուգել կամ ջնջել ձեր սարքին ուղարկված հաղորդագրությունները` առանց դրանք ձեզ ցուցադրելու:"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ստանալ տեքստային հաղորդագրություններ (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Թույլ է տալիս հավելվածին ստանալ և մշակել MMS հաղորդագրությունները: Սա նշանակում է, որ հավելվածը կարող է ստուգել կամ ջնջել ձեր սարքին ուղարկված հաղորդագրությունները` առանց դրանք ձեզ ցուցադրելու:"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"կարդալ բջջային զեկուցվող հաղորդագրությունները"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Թույլ է տալիս հավելվածին կարդալ ձեր սարքի կողմից ստացված բջջային հեռարձակվող հաղորդագրությունները: Բջջային հեռարձակվող զգուշացումները ուղարկվում են որոշ վայրերում` արտակարգ իրավիճակների մասին ձեզ զգուշացնելու համար: Վնասարար հավելվածները կարող են խանգարել ձեր սարքի արդյունավետությանը կամ շահագործմանը, երբ ստացվում է արտակարգ իրավիճակի մասին բջջային հաղորդում:"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"կարդալ բաժանորդագրված հոսքերը"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Թույլ է տալիս հավելվածին փոփոխել «Չանհանգստացնել» գործառույթի կազմաձևումը:"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"թույլտվությունների մասին տվյալների հասանելիություն"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Հավելվածին հասանելի կդառնան թույլտվությունների մասին տվյալները։ Այս թույլտվությունն անհրաժեշտ չէ սովորական հավելվածներին։"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"հատուկ գործառույթների դյուրանցումն օգտագործելու նպատակը"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Հավելվածին թույլ է տալիս որոշել հատուկ գործառույթների դյուրանցումն օգտագործելու նպատակը։"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Սահմանել գաղտնաբառի կանոնները"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Կառավարել էկրանի ապակողպման գաղտնաբառերի և PIN կոդերի թույլատրելի երկարությունն ու գրանշանները:"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Վերահսկել էկրանի ապակողպման փորձերը"</string>
@@ -1356,11 +1362,13 @@
     <string name="usb_power_notification_message" msgid="4647527153291917218">"Միացված սարքի լիցքավորում: Հպեք՝ ավելի շատ ընտրանքների համար:"</string>
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Հայտնաբերված է անալոգային աուդիո լրասարք"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"Կցված սարքը համատեղելի չէ այս հեռախոսի հետ: Հպեք` ավելին իմանալու համար:"</string>
-    <string name="adb_active_notification_title" msgid="6729044778949189918">"USB վրիպազերծումը միացված է"</string>
-    <string name="adb_active_notification_message" msgid="7463062450474107752">"Հպեք՝ USB վրիպազերծումն անջատելու համար"</string>
-    <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Ընտրել` USB կարգաբերումը կասեցնելու համար:"</string>
+    <string name="adb_active_notification_title" msgid="6729044778949189918">"USB-ով վրիպազերծումը միացված է"</string>
+    <string name="adb_active_notification_message" msgid="7463062450474107752">"Հպեք՝ USB-ով վրիպազերծումն անջատելու համար"</string>
+    <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Սեղմեք՝ USB-ով վրիպազերծումն անջատելու համար:"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Թեստային ռեժիմը միացված է"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Թեստային ռեժիմն անջատելու համար զրոյացրեք կարգավորումները։"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Սերիական վահանակը միացված է"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Աշխատանքի արդյունավետությունը նվազում է։ Վահանակն անջատելու համար ստուգեք օպերացիոն համակարգի բեռնիչը։"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB միացքում ջուր կամ աղտ է հայտնաբերվել"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB միացքն ավտոմատ անջատվել է: Հպեք՝ ավելին իմանալու համար:"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB միացքը կարող է օգտագործվել"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Չդասակարգված"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Դուք սահմանել եք այս ծանուցումների կարևորությունը:"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Կարևոր է, քանի որ որոշակի մարդիկ են ներգրավված:"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Թույլատրե՞լ <xliff:g id="APP">%1$s</xliff:g> հավելվածին <xliff:g id="ACCOUNT">%2$s</xliff:g> հաշվով նոր Օգտատեր ստեղծել:"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Թույլատրե՞լ <xliff:g id="APP">%1$s</xliff:g> հավելվածին <xliff:g id="ACCOUNT">%2$s</xliff:g> հաշվով նոր Օգտատեր ստեղծել (նման հաշվով Օգտատեր արդեն գոյություն ունի):"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Թույլատրե՞լ <xliff:g id="APP">%1$s</xliff:g> հավելվածին <xliff:g id="ACCOUNT">%2$s</xliff:g> հաշվով նոր Օգտատեր ստեղծել (նման հաշվով Օգտատեր արդեն գոյություն ունի):"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Թույլատրե՞լ <xliff:g id="APP">%1$s</xliff:g> հավելվածին <xliff:g id="ACCOUNT">%2$s</xliff:g> հաշվով նոր Օգտատեր ստեղծել:"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Ավելացնել լեզու"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Նախընտրելի տարածաշրջան"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Մուտքագրեք լեզուն"</string>
@@ -1930,7 +1938,7 @@
     <string name="app_category_maps" msgid="5878491404538024367">"Քարտեզներ և նավարկում"</string>
     <string name="app_category_productivity" msgid="3742083261781538852">"Արդյունավետություն"</string>
     <string name="device_storage_monitor_notification_channel" msgid="3295871267414816228">"Սարքի հիշողություն"</string>
-    <string name="adb_debugging_notification_channel_tv" msgid="5537766997350092316">"USB վրիպազերծում"</string>
+    <string name="adb_debugging_notification_channel_tv" msgid="5537766997350092316">"USB-ով վրիպազերծում"</string>
     <string name="time_picker_hour_label" msgid="2979075098868106450">"ժամ"</string>
     <string name="time_picker_minute_label" msgid="5168864173796598399">"րոպե"</string>
     <string name="time_picker_header_text" msgid="143536825321922567">"Ժամը"</string>
diff --git a/core/res/res/values-in/strings.xml b/core/res/res/values-in/strings.xml
index 0ebabaf..88e396c 100644
--- a/core/res/res/values-in/strings.xml
+++ b/core/res/res/values-in/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Memungkinkan aplikasi menerima dan memproses pesan SMS. Ini artinya aplikasi dapat memantau atau menghapus pesan yang dikirim ke perangkat Anda tanpa menunjukkannya kepada Anda."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"terima pesan teks (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Memungkinkan aplikasi menerima dan memproses pesan MMS. Ini artinya aplikasi dapat memantau atau menghapus pesan yang dikirim ke perangkat Anda tanpa menunjukkannya kepada Anda."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"membaca pesan siaran seluler"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Mengizinkan aplikasi membaca pesan siaran seluler yang diterima perangkat Anda. Notifikasi siaran seluler dikirimkan di beberapa lokasi untuk memperingatkan Anda tentang situasi darurat. Aplikasi berbahaya dapat mengganggu kinerja atau operasi perangkat Anda saat siaran seluler darurat diterima."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"baca feed langganan"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Mengizinkan aplikasi membaca dan menulis konfigurasi status Jangan Ganggu."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"mulai melihat penggunaan izin"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Memungkinkan pemegang memulai penggunaan izin untuk aplikasi. Tidak diperlukan untuk aplikasi normal."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"target pintasan aksesibilitas"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Mengizinkan aplikasi menentukan target pintasan aksesibilitas."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Setel aturan sandi"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Mengontrol panjang dan karakter yang diizinkan dalam sandi dan PIN kunci layar."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Pantau upaya pembukaan kunci layar"</string>
@@ -1258,7 +1264,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Hubungkan"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Semua jaringan"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Izinkan jaringan Wi-Fi yang disarankan?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> jaringan yang disarankan. Perangkat dapat terhubung secara otomatis."</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Jaringan yang disarankan <xliff:g id="NAME">%s</xliff:g>. Perangkat dapat terhubung secara otomatis."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Izinkan"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Lain kali"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi akan aktif otomatis"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Pilih untuk menonaktifkan debugging USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Mode Tes Otomatis diaktifkan"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Lakukan reset ke setelan pabrik untuk menonaktifkan Mode Tes Otomatis."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Konsol serial diaktifkan"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performa terpengaruh. Untuk menonaktifkan, periksa bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Cairan atau kotoran di port USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Port USB otomatis dinonaktifkan. Ketuk untuk mempelajari lebih lanjut."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Boleh menggunakan port USB"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Belum dikategorikan"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Anda menyetel nilai penting notifikasi ini."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ini penting karena orang-orang yang terlibat."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Izinkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baru dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Izinkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baru dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> (Pengguna dengan akun ini sudah ada) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Izinkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baru dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> (Pengguna dengan akun ini sudah ada) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Izinkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baru dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Tambahkan bahasa"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferensi wilayah"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Ketik nama bahasa"</string>
diff --git a/core/res/res/values-is/strings.xml b/core/res/res/values-is/strings.xml
index 296e4414..32461d3 100644
--- a/core/res/res/values-is/strings.xml
+++ b/core/res/res/values-is/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Leyfir forriti að taka á móti og vinna úr SMS-skilaboðum. Þetta þýðir að forritið getur fylgst með eða eytt skilaboðum sem send eru í tækið án þess að birta þér þau."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"taka á móti textaskilaboðum (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Leyfir forriti að taka á móti og vinna úr MMS-skilaboðum. Þetta þýðir að forritið getur fylgst með eða eytt skilaboðum sem send eru í tækið án þess að birta þér þau."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lesa skilaboð frá endurvarpa"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Leyfir forriti að lesa skilaboð frá endurvarpa sem tækið móttekur. Viðvaranir frá endurvarpa berast á tilteknum stöðum til að vara þig við neyðarástandi. Spilliforrit geta truflað afköst eða virkni tækisins þegar neyðarboð berast frá endurvarpa."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lesa strauma í áskrift"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Leyfir forriti að lesa og skrifa í grunnstillingu „Ónáðið ekki“."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"heimildanotkun upphafsyfirlits"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Leyfir handhafa að byrja heimildanotkun fyrir forrit. Ætti aldrei að þurfa fyrir venjuleg forrit."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"áfangastaður aðgengisflýtileiðar"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Leyfir forriti að skilgreina áfangastað aðgengisflýtileiðar."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Setja reglur um aðgangsorð"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Stjórna lengd og fjölda stafa í aðgangsorðum og PIN-númerum skjáláss."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Fylgjast með tilraunum til að taka skjáinn úr lás"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Veldu til að gera USB-villuleit óvirka."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Kveikt á stillingu prófunarvangs"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Núllstilltu til að slökkva á stillingu prófunarvangs."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Raðstjórnborð virkjað"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Þetta hefur áhrif á afköst. Athugaðu ræsiforritið ef þú vilt gera þetta óvirkt."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Vökvi eða óhreinindi í USB-tengi"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-tengi er gert óvirkt sjálfkrafa. Ýttu til að fá frekari upplýsingar."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Óhætt að nota USB-tengi"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Óflokkað"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Þú stilltir mikilvægi þessara tilkynninga."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Þetta er mikilvægt vegna fólksins sem tekur þátt í þessu."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Leyfa <xliff:g id="APP">%1$s</xliff:g> að stofna nýjan notanda með <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Leyfa <xliff:g id="APP">%1$s</xliff:g> að stofna nýjan notanda með <xliff:g id="ACCOUNT">%2$s</xliff:g> (notandi með þennan reikning er þegar fyrir hendi)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Viltu leyfa <xliff:g id="APP">%1$s</xliff:g> að stofna nýjan notanda með <xliff:g id="ACCOUNT">%2$s</xliff:g> (notandi með þennan reikning er þegar fyrir hendi)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Leyfa <xliff:g id="APP">%1$s</xliff:g> að stofna nýjan notanda með <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Bæta við tungumáli"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Svæðisval"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Sláðu inn heiti tungumáls"</string>
diff --git a/core/res/res/values-it/strings.xml b/core/res/res/values-it/strings.xml
index 501ef1a..6e25563 100644
--- a/core/res/res/values-it/strings.xml
+++ b/core/res/res/values-it/strings.xml
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"Consentire all\'app &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; di accedere ai tuoi contatti?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Geolocalizz."</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"accedere alla posizione di questo dispositivo"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"Consentire all\'app &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; di accedere alla posizione di questo dispositivo?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"Consentire all\'app &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; di accedere alla posizione del dispositivo?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"L\'app avrà accesso alla posizione soltanto quando la usi"</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"Consentire a &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; di accedere &lt;b&gt;sempre&lt;/b&gt; alla posizione di questo dispositivo?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"L\'app al momento può accedere alla posizione soltanto mentre la usi"</string>
@@ -324,8 +324,8 @@
     <string name="capability_desc_canControlMagnification" msgid="4791858203568383773">"Controlla il livello di zoom e la posizione del display."</string>
     <string name="capability_title_canPerformGestures" msgid="7418984730362576862">"Eseguire gesti"</string>
     <string name="capability_desc_canPerformGestures" msgid="8296373021636981249">"Consente di toccare, far scorrere, pizzicare ed eseguire altri gesti."</string>
-    <string name="capability_title_canCaptureFingerprintGestures" msgid="6309568287512278670">"Gesti con sensore di impronte digitali"</string>
-    <string name="capability_desc_canCaptureFingerprintGestures" msgid="4386487962402228670">"È in grado di rilevare i gesti compiuti con il sensore di impronte digitali dei dispositivi."</string>
+    <string name="capability_title_canCaptureFingerprintGestures" msgid="6309568287512278670">"Gesti con sensore di impronte"</string>
+    <string name="capability_desc_canCaptureFingerprintGestures" msgid="4386487962402228670">"È in grado di rilevare i gesti compiuti con il sensore di impronte dei dispositivi."</string>
     <string name="permlab_statusBar" msgid="7417192629601890791">"disattivazione o modifica della barra di stato"</string>
     <string name="permdesc_statusBar" msgid="8434669549504290975">"Consente all\'applicazione di disattivare la barra di stato o di aggiungere e rimuovere icone di sistema."</string>
     <string name="permlab_statusBarService" msgid="4826835508226139688">"ruolo di barra di stato"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Consente all\'applicazione di ricevere ed elaborare messaggi SMS. Significa che l\'applicazione potrebbe monitorare o eliminare i messaggi inviati al tuo dispositivo senza mostrarteli."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ricezione messaggi di testo (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Consente all\'applicazione di ricevere ed elaborare messaggi MMS. Significa che l\'applicazione potrebbe monitorare o eliminare i messaggi inviati al tuo dispositivo senza mostrarteli."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lettura di messaggi cell broadcast"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Consente all\'applicazione di leggere i messaggi cell broadcast ricevuti dal dispositivo. Gli avvisi cell broadcast vengono trasmessi in alcune località per avvertire di eventuali situazioni di emergenza. Le applicazioni dannose potrebbero interferire con il rendimento o con il funzionamento del dispositivo quando si riceve un messaggio cell broadcast di emergenza."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lettura feed sottoscritti"</string>
@@ -512,10 +516,10 @@
     <string name="permdesc_requestPasswordComplexity" msgid="4730994229754212347">"Consente all\'app di conoscere il livello di complessità del blocco schermo (alto, medio, basso o nessuno), che indica l\'intervallo di caratteri possibile e il tipo di blocco schermo. L\'app può inoltre suggerire agli utenti di aggiornare il blocco schermo a un livello specifico di complessità, ma gli utenti possono ignorare liberamente il suggerimento e uscire. Tieni presente che il blocco schermo non viene memorizzato come testo non crittografato, quindi l\'app non conosce la password esatta."</string>
     <string name="permlab_useBiometric" msgid="8837753668509919318">"utilizzo di hardware biometrico"</string>
     <string name="permdesc_useBiometric" msgid="8389855232721612926">"Consente all\'app di utilizzare hardware biometrico per eseguire l\'autenticazione"</string>
-    <string name="permlab_manageFingerprint" msgid="5640858826254575638">"gestione di hardware per il riconoscimento delle impronte digitali"</string>
-    <string name="permdesc_manageFingerprint" msgid="178208705828055464">"Consente all\'app di richiamare metodi per aggiungere e rimuovere modelli di impronte digitali da utilizzare."</string>
-    <string name="permlab_useFingerprint" msgid="3150478619915124905">"utilizzo di hardware per il riconoscimento delle impronte digitali"</string>
-    <string name="permdesc_useFingerprint" msgid="9165097460730684114">"Consente all\'app di utilizzare l\'hardware per il riconoscimento delle impronte digitali per eseguire l\'autenticazione"</string>
+    <string name="permlab_manageFingerprint" msgid="5640858826254575638">"gestione di hardware per il riconoscimento delle impronte"</string>
+    <string name="permdesc_manageFingerprint" msgid="178208705828055464">"Consente all\'app di richiamare metodi per aggiungere e rimuovere modelli di impronte da utilizzare."</string>
+    <string name="permlab_useFingerprint" msgid="3150478619915124905">"utilizzo di hardware per il riconoscimento delle impronte"</string>
+    <string name="permdesc_useFingerprint" msgid="9165097460730684114">"Consente all\'app di utilizzare l\'hardware per il riconoscimento delle impronte per eseguire l\'autenticazione"</string>
     <string name="permlab_audioWrite" msgid="2661772059799779292">"modifica della tua raccolta musicale"</string>
     <string name="permdesc_audioWrite" msgid="8888544708166230494">"Consente all\'app di modificare la tua raccolta musicale."</string>
     <string name="permlab_videoWrite" msgid="128769316366746446">"modifica della tua raccolta di video"</string>
@@ -530,30 +534,30 @@
     <string name="biometric_not_recognized" msgid="5770511773560736082">"Non riconosciuto"</string>
     <string name="biometric_error_canceled" msgid="349665227864885880">"Autenticazione annullata"</string>
     <string name="biometric_error_device_not_secured" msgid="6583143098363528349">"Non hai impostato PIN, sequenza o password"</string>
-    <string name="fingerprint_acquired_partial" msgid="735082772341716043">"Rilevata impronta digitale parziale. Riprova."</string>
-    <string name="fingerprint_acquired_insufficient" msgid="4596546021310923214">"Impossibile elaborare l\'impronta digitale. Riprova."</string>
-    <string name="fingerprint_acquired_imager_dirty" msgid="1087209702421076105">"Il sensore di impronte digitali è sporco. Puliscilo e riprova."</string>
+    <string name="fingerprint_acquired_partial" msgid="735082772341716043">"Rilevata impronta parziale. Riprova."</string>
+    <string name="fingerprint_acquired_insufficient" msgid="4596546021310923214">"Impossibile elaborare l\'impronta. Riprova."</string>
+    <string name="fingerprint_acquired_imager_dirty" msgid="1087209702421076105">"Il sensore di impronte è sporco. Puliscilo e riprova."</string>
     <string name="fingerprint_acquired_too_fast" msgid="6470642383109155969">"Movimento del dito troppo rapido. Riprova."</string>
     <string name="fingerprint_acquired_too_slow" msgid="59250885689661653">"Movimento del dito troppo lento. Riprova."</string>
   <string-array name="fingerprint_acquired_vendor">
   </string-array>
-    <string name="fingerprint_authenticated" msgid="5309333983002526448">"Impronta digitale autenticata"</string>
+    <string name="fingerprint_authenticated" msgid="5309333983002526448">"Impronta autenticata"</string>
     <string name="face_authenticated_no_confirmation_required" msgid="4018680978348659031">"Volto autenticato"</string>
     <string name="face_authenticated_confirmation_required" msgid="8778347003507633610">"Volto autenticato, premi Conferma"</string>
-    <string name="fingerprint_error_hw_not_available" msgid="7955921658939936596">"Hardware per l\'impronta digitale non disponibile."</string>
-    <string name="fingerprint_error_no_space" msgid="1055819001126053318">"Impossibile memorizzare l\'impronta digitale. Rimuovi un\'impronta esistente."</string>
-    <string name="fingerprint_error_timeout" msgid="3927186043737732875">"Timeout impronta digitale. Riprova."</string>
-    <string name="fingerprint_error_canceled" msgid="4402024612660774395">"Operazione associata all\'impronta digitale annullata."</string>
-    <string name="fingerprint_error_user_canceled" msgid="7999639584615291494">"Operazione di autenticazione dell\'impronta digitale annullata dall\'utente."</string>
+    <string name="fingerprint_error_hw_not_available" msgid="7955921658939936596">"Hardware per l\'impronta non disponibile."</string>
+    <string name="fingerprint_error_no_space" msgid="1055819001126053318">"Impossibile memorizzare l\'impronta. Rimuovi un\'impronta esistente."</string>
+    <string name="fingerprint_error_timeout" msgid="3927186043737732875">"Timeout impronta. Riprova."</string>
+    <string name="fingerprint_error_canceled" msgid="4402024612660774395">"Operazione associata all\'impronta annullata."</string>
+    <string name="fingerprint_error_user_canceled" msgid="7999639584615291494">"Operazione di autenticazione dell\'impronta annullata dall\'utente."</string>
     <string name="fingerprint_error_lockout" msgid="5536934748136933450">"Troppi tentativi. Riprova più tardi."</string>
-    <string name="fingerprint_error_lockout_permanent" msgid="5033251797919508137">"Troppi tentativi. Sensore di impronte digitali disattivato."</string>
+    <string name="fingerprint_error_lockout_permanent" msgid="5033251797919508137">"Troppi tentativi. Sensore di impronte disattivato."</string>
     <string name="fingerprint_error_unable_to_process" msgid="6107816084103552441">"Riprova."</string>
     <string name="fingerprint_error_no_fingerprints" msgid="7654382120628334248">"Nessuna impronta digitale registrata."</string>
-    <string name="fingerprint_error_hw_not_present" msgid="409523969613176352">"Questo dispositivo non dispone di sensore di impronte digitali."</string>
+    <string name="fingerprint_error_hw_not_present" msgid="409523969613176352">"Questo dispositivo non dispone di sensore di impronte."</string>
     <string name="fingerprint_name_template" msgid="5870957565512716938">"Dito <xliff:g id="FINGERID">%d</xliff:g>"</string>
   <string-array name="fingerprint_error_vendor">
   </string-array>
-    <string name="fingerprint_icon_content_description" msgid="2340202869968465936">"Icona dell\'impronta digitale"</string>
+    <string name="fingerprint_icon_content_description" msgid="2340202869968465936">"Icona dell\'impronta"</string>
     <string name="permlab_manageFace" msgid="7262837876352591553">"gestione dell\'hardware per Sblocco col sorriso"</string>
     <string name="permdesc_manageFace" msgid="8919637120670185330">"Consente all\'app di richiamare i metodi per aggiungere e rimuovere i modelli di volti."</string>
     <string name="permlab_useFaceAuthentication" msgid="2565716575739037572">"utilizzo dell\'hardware per Sblocco col sorriso"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Consente all\'app di leggere e modificare la configurazione della funzione Non disturbare."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"avvio dell\'uso dell\'autorizzazione di visualizzazione"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Consente al titolare di avviare l\'uso delle autorizzazioni per un\'app. Non dovrebbe essere mai necessaria per le normali applicazioni."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"target della scorciatoia Accessibilità"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Consente a un\'app di definire il target della scorciatoia Accessibilità"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Impostare regole per le password"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controlla la lunghezza e i caratteri ammessi nelle password e nei PIN del blocco schermo."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitorare tentativi di sblocco dello schermo"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Seleziona per disattivare il debug USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Modalità test harness attivata"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Ripristina le impostazioni di fabbrica per disattivare la modalità test harness."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Console seriale attivata"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Ci sono conseguenze sulle prestazioni. Per disattivare, seleziona il bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Liquidi o detriti nella porta USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"La porta USB viene disattivata automaticamente. Tocca per avere ulteriori informazioni."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Utilizzo porta USB consentito"</string>
@@ -1579,8 +1587,8 @@
     <string name="expires_on" msgid="3676242949915959821">"Scade il:"</string>
     <string name="serial_number" msgid="758814067660862493">"Numero di serie:"</string>
     <string name="fingerprints" msgid="4516019619850763049">"Fingerprint:"</string>
-    <string name="sha256_fingerprint" msgid="4391271286477279263">"Fingerprint SHA-256:"</string>
-    <string name="sha1_fingerprint" msgid="7930330235269404581">"Fingerprint SHA-1:"</string>
+    <string name="sha256_fingerprint" msgid="4391271286477279263">"Impronta SHA-256:"</string>
+    <string name="sha1_fingerprint" msgid="7930330235269404581">"Impronta SHA-1:"</string>
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Mostra tutto"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Scegli attività"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Condividi con"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Senza categoria"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Stabilisci tu l\'importanza di queste notifiche."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Importante a causa delle persone coinvolte."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Consentire a <xliff:g id="APP">%1$s</xliff:g> di creare un nuovo utente con <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Consentire a <xliff:g id="APP">%1$s</xliff:g> di creare un nuovo utente con <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Esiste già un utente con questo account)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Consentire a <xliff:g id="APP">%1$s</xliff:g> di creare un nuovo utente con l\'account <xliff:g id="ACCOUNT">%2$s</xliff:g> (esiste già un utente con questo account)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Consentire a <xliff:g id="APP">%1$s</xliff:g> di creare un nuovo utente con l\'account <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Aggiungi una lingua"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Area geografica preferita"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Digita nome lingua"</string>
diff --git a/core/res/res/values-iw/strings.xml b/core/res/res/values-iw/strings.xml
index a2031f8..6e61213 100644
--- a/core/res/res/values-iw/strings.xml
+++ b/core/res/res/values-iw/strings.xml
@@ -102,7 +102,7 @@
     <string name="peerTtyModeHco" msgid="5728602160669216784">"‏העמית ביקש TTY במצב HCO"</string>
     <string name="peerTtyModeVco" msgid="1742404978686538049">"‏העמית ביקש TTY במצב VCO"</string>
     <string name="peerTtyModeOff" msgid="3280819717850602205">"‏העמית ביקש TTY במצב OFF"</string>
-    <string name="serviceClassVoice" msgid="1258393812335258019">"Google Voice"</string>
+    <string name="serviceClassVoice" msgid="1258393812335258019">"קול"</string>
     <string name="serviceClassData" msgid="872456782077937893">"Google Data"</string>
     <string name="serviceClassFAX" msgid="5566624998840486475">"פקס"</string>
     <string name="serviceClassSMS" msgid="2015460373701527489">"SMS"</string>
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"‏מאפשר לאפליקציה לקבל ולעבד הודעות SMS. משמעות הדבר היא שהאפליקציה יכולה לעקוב אחר הודעות שנשלחו למכשיר או למחוק אותן מבלי להציג לך אותן."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"‏קבלת הודעות טקסט (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"‏מאפשר לאפליקציה לקבל ולעבד הודעות MMS. משמעות הדבר היא שהאפליקציה יכולה לעקוב אחר הודעות שנשלחו למכשיר או למחוק אותן מבלי להציג לך אותן."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"קריאת הודעות שידור סלולרי"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"מאפשר לאפליקציה לקרוא הודעות שידור סלולרי שהתקבלו במכשיר שלך. התראות שידור סלולרי נשלחות במקומות מסוימים על מנת להזהיר אותך מפני מצבי חירום. אפליקציות זדוניות עשויות להפריע לביצועים או לפעולה של המכשיר שלך כאשר מתקבל שידור חירום סלולרי."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"קרא עדכוני מנויים"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"מאפשר לאפליקציה לקרוא ולכתוב את התצורה של \'נא לא להפריע\'."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"התחלת צפייה בהרשאות השימוש"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"מאפשרת לבעלים להפעיל את השימוש בהרשאות עבור אפליקציה מסוימת. הרשאה זו אף פעם לא נדרשת עבור אפליקציות רגילות."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"קיצור דרך ליעד של פעולת נגישות"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"מאפשרת לאפליקציה להגדיר את קיצור הדרך ליעד של פעולת נגישות."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"הגדר כללי סיסמה"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"קביעת האורך הנדרש והתווים המותרים בסיסמאות ובקודי הגישה של מסך הנעילה."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"מעקב אחר ניסיונות לביטול של נעילת המסך"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"‏בחר להשבית ניפוי באגים ב-USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"מצב מסגרת בדיקה הופעל"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"כדי להשבית את מצב מסגרת בדיקה צריך לאפס להגדרות היצרן."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"קונסולה סדרתית מופעלת"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"קיימת השפעה על הביצועים. כדי להשבית, יש לבדוק את תוכנת האתחול."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"‏יש נוזלים או חלקיקים ביציאת ה-USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"‏יציאת ה-USB הושבתה באופן אוטומטי. יש להקיש לקבלת מידע נוסף."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"‏ניתן להשתמש ביציאת ה-USB"</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"ללא שיוך לקטגוריה"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"עליך להגדיר את החשיבות של ההתראות האלה."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ההודעה חשובה בשל האנשים המעורבים."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"האם לאפשר ל-<xliff:g id="APP">%1$s</xliff:g> ליצור משתמש חדש לחשבון <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"האם לאפשר ל-<xliff:g id="APP">%1$s</xliff:g> ליצור משתמש חדש לחשבון <xliff:g id="ACCOUNT">%2$s</xliff:g> (כבר קיים משתמש לחשבון הזה) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"האם לאפשר לאפליקציה <xliff:g id="APP">%1$s</xliff:g> ליצור משתמש חדש באמצעות <xliff:g id="ACCOUNT">%2$s</xliff:g> (כבר קיים משתמש לחשבון הזה) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"האם לאפשר לאפליקציה <xliff:g id="APP">%1$s</xliff:g> ליצור משתמש חדש באמצעות <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"הוספת שפה"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"העדפת אזור"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"הקלד שם שפה"</string>
diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml
index a54d0ec..15e10e4 100644
--- a/core/res/res/values-ja/strings.xml
+++ b/core/res/res/values-ja/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMSメッセージの受信と処理をアプリに許可します。これにより、アプリがデバイスに届いたメッセージを表示することなく監視または削除できるようになります。"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"テキストメッセージ(MMS)の受信"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMSメッセージの受信と処理をアプリに許可します。これにより、アプリがデバイスに届いたメッセージを表示することなく監視または削除できるようになります。"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"緊急速報メール SMS の読み取り"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"デバイスで受信した緊急速報メール SMS の読み取りをアプリに許可します。緊急速報メールは、緊急事態を警告する目的で一部の地域に配信されます。緊急速報メールの受信時に、悪意のあるアプリによってデバイスの動作や処理が妨害される恐れがあります。"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"登録したフィードの読み取り"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"サイレント モード設定の読み取りと書き込みをアプリに許可します。"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"表示権限の使用の開始"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"アプリの権限使用の開始を所有者に許可します。通常のアプリでは不要です。"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ユーザー補助ショートカットのターゲット"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ユーザー補助ショートカットのターゲットの定義付けをアプリに許可します。"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"パスワードルールの設定"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"画面ロックのパスワードとPINの長さと使用できる文字を制御します。"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"画面ロック解除試行の監視"</string>
@@ -1258,7 +1264,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"接続"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"すべてのネットワーク"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Wi‑Fi ネットワーク候補を許可しますか?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> からのネットワーク候補にデバイスが自動的に接続される可能性があります。"</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> からのネットワーク候補に、デバイスが自動的に接続される可能性があります。"</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"許可"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"許可しない"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi-Fi は自動的にオンになります"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USBデバッグを無効にする場合に選択します。"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"テストハーネス モード有効"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"出荷時設定にリセットしてテストハーネス モードを無効にしてください。"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"シリアル コンソールは有効です"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"シリアル コンソールを有効にすると、パフォーマンスに影響します。無効にするには、ブートローダーをチェックしてください。"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB ポート内の液体やゴミ"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB ポートが自動的に無効になりました。タップして詳細をご確認ください。"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB ポートを安全に使用できます"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"カテゴリなし"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"このような通知の重要度を設定します。"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"関係するユーザーのため、この設定は重要です。"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> が <xliff:g id="ACCOUNT">%2$s</xliff:g> で新しいユーザーを作成できるようにしますか?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> が <xliff:g id="ACCOUNT">%2$s</xliff:g> で新しいユーザーを作成できるようにしますか?(このアカウントのユーザーはすでに存在します)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> が <xliff:g id="ACCOUNT">%2$s</xliff:g> で新しいユーザーを作成できるようにしますか?(このアカウントのユーザーはすでに存在します)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> が <xliff:g id="ACCOUNT">%2$s</xliff:g> で新しいユーザーを作成できるようにしますか?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"言語を追加"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"地域設定"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"言語名を入力"</string>
diff --git a/core/res/res/values-ka/strings.xml b/core/res/res/values-ka/strings.xml
index 0376336..a66d897 100644
--- a/core/res/res/values-ka/strings.xml
+++ b/core/res/res/values-ka/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"აპს შეეძლება SMS შეტყობინებების მიღება და დამუშავება. ეს ნიშნავს, რომ აპს შეეძლება თქვენ მოწყობილობაზე გამოგზავნილი შეტყობინებების მონიტორინგი და მათი წაშლა თქვენთვის ჩვენების გარეშე."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ტექსტური შეტყობინებების (MMS) მიღება"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"აპს შეეძლება MMS შეტყობინებების მიღება და დამუშავება. ეს ნიშნავს, რომ აპს შეეძლება შეტყობინებების მონიტორინგი და მათი წაშლა თქვენთვის ჩვენების გარეშე."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"მასიური დაგზავნის შეტყობინებების წაკითხვა"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"აპს შეეძლება, წაიკითხოს თქვენს მოწყობილობაზე გამოგზავნილი ქსელის სამაუწყებლო შეტყობინებები. სამაუწყებლო გაფრთხილებები მოგეწოდებათ ზოგიერთ ადგილზე ექსტრემალური სიტუაციების შესახებ გასაფრთხილებლად. ქსელის გადაუდებელი შეტყონიბენის მიღების დროს მავნე აპებმა შეიძლება ხელი შეუშალონ თქვენი მოწყობილობის ფუნქციონირებას ან ოპერაციებს."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"გამოწერილი არხების წაკითხვა"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"საშუალებას აძლევს აპს, წაიკითხოს და დაწეროს კონფიგურაცია „არ შემაწუხოთ“."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"ნახვის ნებართვის გამოყენების დაწყება"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"მფლობელს საშუალებას აძლევს, დაიწყოს აპის ნებართვის გამოყენება. ჩვეულებრივი აპებისთვის არასოდეს უნდა იყოს საჭირო."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"მარტივი წვდომის მალსახმობის სამიზნე"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"აპს აძლევს მარტივი წვდომის მალსახმობის სამიზნის განსაზღვრის საშუალებას."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"პაროლის წესების დაყენება"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"აკონტროლეთ ეკრანის ბლოკირების პაროლებისა და PIN-ების სიმბოლოების სიგრძე."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"ეკრანის განბლოკვის მცდელობების მონიტორინგი"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"მონიშნეთ რათა შეწყვიტოთ USB-ის გამართვა"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"რეჟიმი „გარემო ტესტირებისთვის“ ჩართულია"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"დააბრუნეთ ქარხნული პარამეტრები „გარემო ტესტირებისთვის“ რეჟიმის გასათიშად."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"სერიული კონსოლი ჩართულია"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"მუშაობა შეფერხებულია. გასათიშად მონიშნეთ ჩამტვირთავი."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB პორტში აღმოჩენილია სითხე ან ჭუჭყი"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB პორტი ავტომატურად გათიშულია. შეეხეთ დამატებითი ინფორმაციისთვის."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"თანხმობა USB პორტის გამოყენებაზე"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"კატეგორიის გარეშე"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ამ შეტყობინებების მნიშვნელობის დონე განისაზღვრა თქვენ მიერ."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"მნიშვნელოვანია ჩართული მომხმარებლების გამო."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"მიეცეს უფლება <xliff:g id="APP">%1$s</xliff:g>-ს, <xliff:g id="ACCOUNT">%2$s</xliff:g>-ის მეშვეობით ახალი მომხმარებელი შექმნას ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"მიეცეს უფლება <xliff:g id="APP">%1$s</xliff:g>-ს, <xliff:g id="ACCOUNT">%2$s</xliff:g>-ის მეშვეობით ახალი მომხმარებელი შექმნას (ამ ანგარიშის მქონე მომხმარებელი უკვე არსებობს) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"მიეცეს უფლება <xliff:g id="APP">%1$s</xliff:g>-ს <xliff:g id="ACCOUNT">%2$s</xliff:g>-ის მეშვეობით ახალი მომხმარებელი შექმნას (ამ ანგარიშის მქონე მომხმარებელი უკვე არსებობს)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"მიეცეს უფლება <xliff:g id="APP">%1$s</xliff:g>-ს <xliff:g id="ACCOUNT">%2$s</xliff:g>-ის მეშვეობით ახალი მომხმარებელი შექმნას?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ენის დამატება"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"რეგიონის პარამეტრები"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"აკრიფეთ ენის სახელი"</string>
diff --git a/core/res/res/values-kk/strings.xml b/core/res/res/values-kk/strings.xml
index 68d63c7..af6b788 100644
--- a/core/res/res/values-kk/strings.xml
+++ b/core/res/res/values-kk/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Қолданбаға SMS хабарларын алу және өңдеу мүмкіндігін береді. Бұл қолданба құрылғыңызға жіберілген хабарларды сізге көрсетпестен қабылдай және жоя алады дегенді білдіреді."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"мәтін хабарларын алу (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Қолданбаға MMS хабарларын алу және өңдеу мүмкіндігін береді. Бұл қолданба құрылғыңызға жіберілген хабарларды сізге көрсетпестен қабылдай және жоя алады дегенді білдіреді."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ұялы хабар тарату хабарларын оқу"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Қолданбаға ұялы таратылым хабарларын оқу мүмкіндігін береді. Ұялы таратылым дабылдары кейбір аймақтарда төтенше жағдай туралы ескерту үшін қолданылады. Төтенше ұялы хабарлар келгенде залалды қолданбалар құрылғының жұмысына кедергі жасауы мүмкін."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"жазылған ағындарды оқу"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Қолданбаға «Мазаламау» конфигурациясын оқу және жазу мүмкіндігін береді."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"рұқсаттарды пайдалану туралы деректерді көру"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Пайдаланушы қолданбаға берілетін рұқсаттарды басқара алады. Ондай рұқсаттар әдеттегі қолданбаларға керек емес."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"арнайы мүмкіндіктер таңбашасының мақсаты"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Қолданбаға арнайы мүмкіндіктер таңбашасының мақсатын анықтауға мүмкіндік береді."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Құпия сөз ережелерін тағайындау"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Экран бекітпесінің құпия сөздерінің және PIN кодтарының ұзындығын және оларда рұқсат етілген таңбаларды басқару."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Экран құлпын ашу әркеттерін бақылау"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB түзетуін өшіру үшін таңдаңыз."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Сынақ бағдарламасы режимі қосылды"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Сынақ бағдарламасы режимін өшіру үшін зауыттық күйіне қайтарыңыз."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Сериялық консоль қосылды"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Өнімділікке әсер етеді. Өшіру үшін жүктегішті тексеріңіз."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB портына сұйықтық немесе қоқыс кірді"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB порты автоматты түрде өшірілді. Толығырақ ақпарат алу үшін түртіңіз."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB портын пайдалана беруге болады"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Санатқа жатқызылмаған"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Сіз осы хабарландырулардың маңыздылығын орнатасыз."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Қатысты адамдарға байланысты бұл маңызды."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> <xliff:g id="ACCOUNT">%2$s</xliff:g> есептік жазбасы бар жаңа пайдаланушы жасауға рұқсат ету керек пе?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> <xliff:g id="ACCOUNT">%2$s</xliff:g> есептік жазбасында жаңа пайдаланушы жасауға рұқсат ету керек пе (осы есептік жазбасы бар пайдаланушы әлдеқашан бар) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> қолданбасына <xliff:g id="ACCOUNT">%2$s</xliff:g> есептік жазбасы бар жаңа пайдаланушы (мұндай есептік жазбаға ие пайдаланушы бұрыннан бар) жасауға рұқсат етілсін бе?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> қолданбасына <xliff:g id="ACCOUNT">%2$s</xliff:g> есептік жазбасы бар жаңа пайдаланушы жасауға рұқсат етілсін бе?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Тілді қосу"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Аймақ параметрі"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Тіл атауын теріңіз"</string>
diff --git a/core/res/res/values-km/strings.xml b/core/res/res/values-km/strings.xml
index 00dc422..cf9b9d2 100644
--- a/core/res/res/values-km/strings.xml
+++ b/core/res/res/values-km/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"ឲ្យ​កម្មវិធី​ទទួល និង​ដំណើរការ​​សារ MMS ។ មាន​ន័យ​ថា កម្មវិធី​អាច​ត្រួតពិនិត្យ​ ឬ​លុប​សារ​ដែល​បាន​ផ្ញើ​ទៅ​ឧបករណ៍​របស់​អ្នក ដោយ​​មិន​បង្ហាញ​អ្នក។"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ទទួល​សារ​អត្ថបទ (MMS​)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"ឲ្យ​កម្មវិធី​ទទួល និង​ដំណើរការ​​សារ​ MMS ។ វា​មាន​ន័យ​ថា កម្មវិធី​អាច​តាមដាន​ ឬ​លុប​សារ​ដែល​បាន​ផ្ញើ​ទៅ​ឧបករណ៍​របស់​អ្នក​ដោយ​មិន​បង្ហាញ​ពួកវា។"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"អាន​សារ​ប្រកាស​ចល័ត"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ឲ្យ​កម្មវិធី​អាន​សារ​ប្រកាស​ការ​ហៅ​ដែល​ឧបករណ៍​របស់​​អ្នក​បាន​ទទួល។ ការ​ជូន​ដំណឹង​ប្រកាស​ចល័ត​ត្រូវ​បាន​បញ្ជូន​ទៅ​ទីតាំង​មួយ​ចំនួន ដើម្បី​ព្រមាន​អ្នក​អំពី​ស្ថានភាព​អាសន្ន។ កម្មវិធី​ព្យាបាទ​អាច​ជ្រៀតជ្រែក​ការ​អនុវត្ត ឬ​ប្រតិបត្តិការ​ឧបករណ៍​របស់​អ្នក​​ពេល​ទទួល​ការ​ប្រកាស​ចល័ត​ពេល​អាសន្ន។"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"អាន​អត្ថបទ​ព័ត៌មាន​បាន​ជាវ"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"អនុញ្ញាតឲ្យកម្មវិធីអាន និងសរសេរការកំណត់រចនាសម្ព័ន្ធមុខងារ កុំរំខាន។"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"ចាប់ផ្ដើម​មើល​ការប្រើប្រាស់​ការអនុញ្ញាត"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"អនុញ្ញាត​ឱ្យម្ចាស់​ចាប់ផ្ដើម​ការប្រើប្រាស់​ការអនុញ្ញាត​សម្រាប់កម្មវិធី។ មិនគួរ​ចាំបាច់​សម្រាប់​កម្មវិធី​ធម្មតា​ទេ។"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"គោលដៅផ្លូវកាត់ភាពងាយស្រួល"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"អនុញ្ញាតឱ្យ​កម្មវិធី​កំណត់​គោលដៅ​ផ្លូវកាត់​ភាពងាយស្រួល។"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"កំណត់​ក្បួន​ពាក្យ​សម្ងាត់"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"គ្រប់គ្រងប្រវែង និងតួអក្សរដែលអនុញ្ញាតឲ្យប្រើក្នុងពាក្យសម្ងាត់ និងលេខសម្ងាត់ចាក់សោអេក្រង់។"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"តាមដាន​ការ​ព្យាយាម​ដោះ​សោ​អេក្រង់"</string>
@@ -1363,6 +1369,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"ជ្រើស​រើស ដើម្បី​បិទ​ការ​កែ​កំហុសតាម USB ។"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"បាន​បើក​មុខងារប្រមូលធ្វើតេស្ត"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"ធ្វើការកំណត់ដូចដើមឡើងវិញ ដើម្បី​បិទ​មុខងារប្រមូលធ្វើតេស្ត។"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"កុងសូល​ស៊េរី​ត្រូវបានបើក"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"ប្រតិបត្តិការ​ទទួលរង​ការប៉ះពាល់។ សូម​ពិនិត្យមើល​កម្មវិធី​ដំណើរការ​ប្រព័ន្ធ ដើម្បី​បិទ។"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"មានទឹក ឬ​កម្ទេចផ្សេងៗ​នៅក្នុងរន្ធ USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"រន្ធ USB ត្រូវបាន​បិទ​ដោយ​ស្វ័យប្រវត្តិ។ សូមចុច​ដើម្បី​ស្វែងយល់​បន្ថែម។"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"អាច​ប្រើរន្ធ USB បាន"</string>
@@ -1581,8 +1589,8 @@
     <string name="expires_on" msgid="3676242949915959821">"ផុត​កំណត់​នៅ៖"</string>
     <string name="serial_number" msgid="758814067660862493">"លេខ​ស៊េរី៖"</string>
     <string name="fingerprints" msgid="4516019619850763049">"ស្នាម​ម្រាមដៃ​៖"</string>
-    <string name="sha256_fingerprint" msgid="4391271286477279263">"ស្នាម​ម្រាមដៃ SHA​-256 ​៖"</string>
-    <string name="sha1_fingerprint" msgid="7930330235269404581">"ស្នាម​ម្រាម​ដៃ SHA-1 ៖"</string>
+    <string name="sha256_fingerprint" msgid="4391271286477279263">"ស្នាម​ម្រាមដៃ SHA​-256៖"</string>
+    <string name="sha1_fingerprint" msgid="7930330235269404581">"ស្នាម​ម្រាម​ដៃ SHA-1៖"</string>
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"មើល​ទាំងអស់"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"ជ្រើស​សកម្មភាព"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"ចែករំលែក​ជា​មួយ"</string>
@@ -1892,8 +1900,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"មិន​​បែងចែក​ប្រភេទ"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"អ្នកបានកំណត់សារៈសំខាន់នៃការជូនដំណឹងទាំងនេះ"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"វាមានសារៈសំខាន់ដោយសារតែមនុស្សដែលពាក់ព័ន្ធ"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"អនុញ្ញាតឲ្យ <xliff:g id="APP">%1$s</xliff:g> បង្កើតអ្នកប្រើថ្មីដោយប្រើ <xliff:g id="ACCOUNT">%2$s</xliff:g> ឬទេ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"អនុញ្ញាតឲ្យ <xliff:g id="APP">%1$s</xliff:g> បង្កើតអ្នកប្រើថ្មីដោយប្រើ <xliff:g id="ACCOUNT">%2$s</xliff:g> (មានអ្នកប្រើសម្រាប់គណនីនេះរួចហើយ) ឬទេ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"អនុញ្ញាតឱ្យ <xliff:g id="APP">%1$s</xliff:g> បង្កើតអ្នកប្រើប្រាស់​ថ្មីដោយប្រើ <xliff:g id="ACCOUNT">%2$s</xliff:g> (អ្នកប្រើប្រាស់ដែលមានគណនីនេះមានរួចហើយ) ដែរឬទេ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"អនុញ្ញាតឱ្យ <xliff:g id="APP">%1$s</xliff:g> បង្កើតអ្នកប្រើប្រាស់​ថ្មីដោយប្រើ <xliff:g id="ACCOUNT">%2$s</xliff:g> ដែរឬទេ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"បន្ថែមភាសា"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ចំណូលចិត្តតំបន់"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"វាយបញ្ចូលឈ្មោះភាសា"</string>
diff --git a/core/res/res/values-kn/strings.xml b/core/res/res/values-kn/strings.xml
index 0902271..028d563 100644
--- a/core/res/res/values-kn/strings.xml
+++ b/core/res/res/values-kn/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS ಸಂದೇಶಗಳನ್ನು ಸ್ವೀಕರಿಸಲು ಮತ್ತು ಪ್ರಕ್ರಿಯೆಗೊಳಿಸಲು ಅಪ್ಲಿಕೇಶನ್‍‍ಗೆ ಅವಕಾಶ ಮಾಡಿಕೊಡುತ್ತದೆ. ಇದರರ್ಥ, ನಿಮ್ಮ ಸಾಧನಕ್ಕೆ ಕಳುಹಿಸಲಾಗಿರುವ ಸಂದೇಶಗಳನ್ನು ನಿಮಗೆ ತೋರಿಸದೆಯೇ, ಅಪ್ಲಿಕೇಶನ್ ಅವುಗಳನ್ನು ಮಾನಿಟರ್ ಮಾಡಬಹುದು ಅಥವಾ ಅಳಿಸಬಹುದು."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ಪಠ್ಯ ಸಂದೇಶಗಳನ್ನು ಸ್ವೀಕರಿಸಿ (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS ಸಂದೇಶಗಳನ್ನು ಸ್ವೀಕರಿಸಲು ಮತ್ತು ಪ್ರಕ್ರಿಯೆಗೊಳಿಸಲು ಅಪ್ಲಿಕೇಶನ್‍‍ಗೆ ಅವಕಾಶ ಮಾಡಿಕೊಡುತ್ತದೆ. ಇದರರ್ಥ, ನಿಮ್ಮ ಸಾಧನಕ್ಕೆ ಕಳುಹಿಸಲಾಗಿರುವ ಸಂದೇಶಗಳನ್ನು ನಿಮಗೆ ತೋರಿಸದೆಯೇ, ಅಪ್ಲಿಕೇಶನ್ ಅವುಗಳನ್ನು ಮಾನಿಟರ್ ಮಾಡಬಹುದು ಅಥವಾ ಅಳಿಸಬಹುದು."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ಸೆಲ್ ಪ್ರಸಾರದ ಸಂದೇಶಗಳನ್ನು ಓದಿರಿ"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ನಿಮ್ಮ ಸಾಧನದಿಂದ ಸ್ವೀಕರಿಸಿದ ಸೆಲ್ ಪ್ರಸಾರ ಸಂದೇಶಗಳನ್ನು ರೀಡ್ ಮಾಡಲು ಅಪ್ಲಿಕೇಶನ್‌‌ಗೆ ಅನುಮತಿಸುತ್ತದೆ. ಸೆಲ್ ಪ್ರಸಾರ ಎಚ್ಚರಿಕೆಗಳನ್ನು ತುರ್ತು ಸಂದರ್ಭಗಳಲ್ಲಿ ನಿಮಗೆ ಎಚ್ಚರಿಸುವ ಸಲುವಾಗಿ ಕೆಲವು ಸ್ಥಳಗಳಲ್ಲಿ ವಿತರಿಸಲಾಗುತ್ತದೆ. ದುರುದ್ದೇಶಪೂರಿತ ಅಪ್ಲಿಕೇಶನ್‌‌‌ಗಳು ತುರ್ತು ಸೆಲ್ ಪ್ರಸಾರವನ್ನು ಸ್ವೀಕರಿಸುವಾಗ, ನಿಮ್ಮ ಸಾಧನದ ಕಾರ್ಯಕ್ಷಮತೆ ಇಲ್ಲವೇ ಕಾರ್ಯಾಚರಣೆಯಲ್ಲಿ ಹಸ್ತಕ್ಷೇಪ ಮಾಡಬಹುದು."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ಚಂದಾದಾರ ಫೀಡ್‌ಗಳನ್ನು ಓದಿ"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"ಅಡಚಣೆ ಮಾಡಬೇಡಿ ಕಾನ್ಫಿಗರೇಶನ್ ಅನ್ನು ಓದಲು ಮತ್ತು ಬರೆಯಲು ಅಪ್ಲಿಕೇಶನ್‌ಗೆ ಅನುಮತಿಸುತ್ತದೆ."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"ವೀಕ್ಷಣಾ ಅನುಮತಿಯ ಬಳಕೆಯನ್ನು ಪ್ರಾರಂಭಿಸಿ"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ಆ್ಯಪ್‌ಗಾಗಿ ಅನುಮತಿ ಬಳಕೆಯನ್ನು ಪ್ರಾರಂಭಿಸಲು ಹೊಂದಿರುವವರಿಗೆ ಅನುಮತಿಸುತ್ತದೆ. ಸಾಮಾನ್ಯ ಆ್ಯಪ್‌ಗಳಿಗೆ ಎಂದಿಗೂ ಅಗತ್ಯವಿರುವುದಿಲ್ಲ."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ಪ್ರವೇಶಿಸುವಿಕೆ ಶಾರ್ಟ್‌ಕಟ್ ಟಾರ್ಗೆಟ್‌"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ಪ್ರವೇಶಿಸುವಿಕೆ ಶಾರ್ಟ್‌ಕಟ್ ಟಾರ್ಗೆಟ್‌ ಅನ್ನು ವಿವರಿಸಲು ಆ್ಯಪ್‌ಗೆ ಅನುಮತಿಸುತ್ತದೆ."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"ಪಾಸ್‌ವರ್ಡ್ ನಿಮಯಗಳನ್ನು ಹೊಂದಿಸಿ"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"ಪರದೆ ಲಾಕ್‌ನಲ್ಲಿನ ಪಾಸ್‌ವರ್ಡ್‌ಗಳು ಮತ್ತು ಪಿನ್‌ಗಳ ಅನುಮತಿಸಲಾದ ಅಕ್ಷರಗಳ ಪ್ರಮಾಣವನ್ನು ನಿಯಂತ್ರಿಸಿ."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"ಪರದೆಯ ಅನ್‌ಲಾಕ್ ಪ್ರಯತ್ನಗಳನ್ನು ಮೇಲ್ವಿಚಾರಣೆ ಮಾಡಿ"</string>
@@ -1155,7 +1161,7 @@
     <string name="whichImageCaptureApplicationNamed" msgid="8619384150737825003">"%1$s ಜೊತೆ ಚಿತ್ರ ಕ್ಯಾಪ್ಚರ್ ಮಾಡಿ"</string>
     <string name="whichImageCaptureApplicationLabel" msgid="6390303445371527066">"ಚಿತ್ರ ಕ್ಯಾಪ್ಚರ್ ಮಾಡಿ"</string>
     <string name="alwaysUse" msgid="4583018368000610438">"ಈ ಕ್ರಿಯೆಗೆ ಡಿಫಾಲ್ಟ್ ಆಗಿ ಬಳಸಿ."</string>
-    <string name="use_a_different_app" msgid="8134926230585710243">"ಬೇರೆಯ ಅಪ್ಲಿಕೇಶನ್ ಬಳಸಿ"</string>
+    <string name="use_a_different_app" msgid="8134926230585710243">"ಬೇರೊಂದು ಆ್ಯಪ್ ಬಳಸಿ"</string>
     <string name="clearDefaultHintMsg" msgid="3252584689512077257">"ಸಿಸ್ಟಂ ಸೆಟ್ಟಿಂಗ್‌ಗಳು &gt; ಅಪ್ಲಿಕೇಶನ್‌ಗಳು &gt; ಡೌನ್‌ಲೋಡ್ ಮಾಡಲಾದ ಡಿಫಾಲ್ಟ್‌‌ ಅನ್ನು ತೆರವುಗೊಳಿಸಿ."</string>
     <string name="chooseActivity" msgid="7486876147751803333">"ಕ್ರಿಯೆಯನ್ನು ಆಯ್ಕೆಮಾಡಿ"</string>
     <string name="chooseUsbActivity" msgid="6894748416073583509">"USB ಸಾಧನಕ್ಕೆ ಅಪ್ಲಿಕೇಶನ್‌‌ವೊಂದನ್ನು ಆಯ್ಕೆಮಾಡಿ"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ಡೀಬಗ್‌ ಮಾಡುವಿಕೆಯನ್ನು ನಿಷ್ಕ್ರಿಯಗೊಳಿಸಲು ಆಯ್ಕೆ ಮಾಡಿ."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"ಸ್ವಯಂ ಪರೀಕ್ಷೆಯಾಗುವಿಕೆ ಮೋಡ್ ಅನ್ನು ಸಕ್ರಿಯಗೊಳಿಸಲಾಗಿದೆ"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"ಸ್ವಯಂ ಪರೀಕ್ಷೆಯಾಗುವಿಕೆ ಮೋಡ್ ಅನ್ನು ನಿಷ್ಕ್ರಿಯಗೊಳಿಸಲು ಫ್ಯಾಕ್ಟರಿ ರಿಸೆಟ್ ಮಾಡಬೇಕು."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"ಸರಣಿ ಕನ್ಸೋಲ್ ಅನ್ನು ಸಕ್ರಿಯಗೊಳಿಸಲಾಗಿದೆ"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"ಕಾರ್ಯಕ್ಷಮತೆಯ ಮೇಲೆ ಪರಿಣಾಮ ಬೀರುತ್ತದೆ. ನಿಷ್ಕ್ರಿಯಗೊಳಿಸಲು, ಬೂಟ್‌ಲೋಡರ್ ಅನ್ನು ಪರಿಶೀಲಿಸಿ."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB ಪೋರ್ಟ್‌ನಲ್ಲಿ ದ್ರವ ಅಥವಾ ಧೂಳಿನ ಕಣಗಳಿವೆ"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB ಪೋರ್ಟ್ ಸ್ವಯಂಚಾಲಿತವಾಗಿ ನಿಷ್ಕ್ರಿಯಗೊಂಡಿದೆ. ಇನ್ನಷ್ಟು ತಿಳಿಯಲು ಟ್ಯಾಪ್ ಮಾಡಿ"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB ಪೋರ್ಟ್ ಬಳಸಲು ಸರಿ ಅನ್ನು ಆಯ್ಕೆ ಮಾಡಿ"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"ವರ್ಗೀಕರಿಸದಿರುವುದು"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ನೀವು ಈ ಅಧಿಸೂಚನೆಗಳ ಪ್ರಾಮುಖ್ಯತೆಯನ್ನು ಹೊಂದಿಸಿರುವಿರಿ."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ಜನರು ತೊಡಗಿಕೊಂಡಿರುವ ಕಾರಣ ಇದು ಅತ್ಯಂತ ಪ್ರಮುಖವಾಗಿದೆ."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ಮೂಲಕ ಹೊಸ ಬಳಕೆದಾರರನ್ನು ರಚಿಸಲು <xliff:g id="APP">%1$s</xliff:g> ಗೆ ಅನುಮತಿಸುವುದೇ ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g> (ಈ ಖಾತೆಯ ಬಳಕೆದಾರರು ಈಗಾಗಲೇ ಅಸ್ತಿತ್ವದಲ್ಲಿದ್ದಾರೆ) ಮೂಲಕ ಹೊಸ ಬಳಕೆದಾರರನ್ನು ರಚಿಸಲು <xliff:g id="APP">%1$s</xliff:g> ಗೆ ಅನುಮತಿಸುವುದೇ ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g> (ಈ ಖಾತೆಯ ಬಳಕೆದಾರರು ಈಗಾಗಲೇ ಅಸ್ತಿತ್ವದಲ್ಲಿದ್ದಾರೆ) ಮೂಲಕ ಹೊಸ ಬಳಕೆದಾರರನ್ನು ರಚಿಸಲು <xliff:g id="APP">%1$s</xliff:g> ಗೆ ಅನುಮತಿಸಬೇಕೆ ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ಮೂಲಕ ಹೊಸ ಬಳಕೆದಾರರನ್ನು ರಚಿಸಲು <xliff:g id="APP">%1$s</xliff:g> ಗೆ ಅನುಮತಿಸುವುದೇ ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ಭಾಷೆ ಸೇರಿಸಿ"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ಪ್ರದೇಶ ಪ್ರಾಶಸ್ತ್ಯ"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ಭಾಷೆ ಹೆಸರನ್ನು ಟೈಪ್ ಮಾಡಿ"</string>
diff --git a/core/res/res/values-ko/strings.xml b/core/res/res/values-ko/strings.xml
index 669bb96..f81cc00 100644
--- a/core/res/res/values-ko/strings.xml
+++ b/core/res/res/values-ko/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"앱이 SMS 메시지를 수신하고 처리할 수 있도록 허용합니다. 앱이 사용자에게 표시하지 않고 기기로 전송된 메시지를 확인 또는 삭제할 수도 있습니다."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"문자 메시지 받기(MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"앱이 MMS 메시지를 수신하고 처리할 수 있도록 허용합니다. 앱이 사용자에게 표시하지 않고 기기로 전송된 메시지를 확인 또는 삭제할 수도 있습니다."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"셀 브로드캐스트 메시지 읽기"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"앱이 기기가 수신한 셀 브로드캐스트 메시지를 읽을 수 있도록 합니다. 비상 상황임을 알리기 위해 일부 지역에서 셀 브로드캐스트 경고가 전달됩니다. 비상 셀 브로드캐스트를 수신할 때 악성 앱이 기기의 성능이나 작동을 방해할 수 있습니다."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"가입된 피드 읽기"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"앱에서 방해 금지 모드 설정을 읽고 작성하도록 허용합니다."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"권한 사용 보기 시작"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"앱의 권한 사용을 시작하려면 보유자를 허용하세요. 일반 앱에는 필요하지 않습니다."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"접근성 단축키 대상"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"앱이 접근성 단축키 대상을 정의할 수 있도록 허용합니다."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"비밀번호 규칙 설정"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"화면 잠금 비밀번호와 PIN에 허용되는 길이와 문자 수를 제어합니다."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"화면 잠금 해제 시도 모니터링"</string>
@@ -1345,7 +1351,7 @@
     <string name="no_permissions" msgid="7283357728219338112">"권한 필요 없음"</string>
     <string name="perm_costs_money" msgid="4902470324142151116">"비용이 부과될 수 있습니다."</string>
     <string name="dlg_ok" msgid="7376953167039865701">"확인"</string>
-    <string name="usb_charging_notification_title" msgid="1595122345358177163">"이 기기를 USB로 충전"</string>
+    <string name="usb_charging_notification_title" msgid="1595122345358177163">"이 기기를 USB로 충전 중"</string>
     <string name="usb_supplying_notification_title" msgid="4631045789893086181">"USB를 통해 연결된 기기 충전"</string>
     <string name="usb_mtp_notification_title" msgid="4238227258391151029">"USB 파일 전송 사용 설정됨"</string>
     <string name="usb_ptp_notification_title" msgid="5425857879922006878">"USB를 통해 PTP 사용 설정됨"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB 디버깅을 사용하지 않으려면 선택합니다."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"테스트 하네스 모드 사용 설정됨"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"테스트 하네스 모드를 사용 중지하려면 초기화하세요."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"시리얼 콘솔 사용 설정됨"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"성능에 영향을 미쳤습니다. 사용 중지하려면 부트로더를 확인하세요."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB 포트에서 액체 또는 이물질 감지됨"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB 포트가 자동으로 사용 중지되었습니다. 자세한 내용을 보려면 탭하세요."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB 포트를 사용해도 좋음"</string>
@@ -1857,8 +1865,8 @@
     <string name="zen_mode_downtime_feature_name" msgid="2626974636779860146">"다운타임"</string>
     <string name="zen_mode_default_weeknights_name" msgid="3081318299464998143">"평일 밤"</string>
     <string name="zen_mode_default_weekends_name" msgid="2786495801019345244">"주말"</string>
-    <string name="zen_mode_default_events_name" msgid="8158334939013085363">"캘린더 일정 중"</string>
-    <string name="zen_mode_default_every_night_name" msgid="3012363838882944175">"수면 중"</string>
+    <string name="zen_mode_default_events_name" msgid="8158334939013085363">"캘린더 일정"</string>
+    <string name="zen_mode_default_every_night_name" msgid="3012363838882944175">"수면 시간"</string>
     <string name="muted_by" msgid="5942954724562097128">"<xliff:g id="THIRD_PARTY">%1$s</xliff:g>(이)가 일부 소리를 음소거함"</string>
     <string name="system_error_wipe_data" msgid="6608165524785354962">"사용 중인 기기 내부에 문제가 발생했습니다. 초기화할 때까지 불안정할 수 있습니다."</string>
     <string name="system_error_manufacturer" msgid="8086872414744210668">"사용 중인 기기 내부에 문제가 발생했습니다. 자세한 내용은 제조업체에 문의하세요."</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"지정된 카테고리 없음"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"이러한 알림의 중요도를 설정했습니다."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"관련된 사용자가 있으므로 중요합니다."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g>이(가) <xliff:g id="ACCOUNT">%2$s</xliff:g>(으)로 신규 사용자를 만들도록 허용하시겠습니까?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g>이(가) <xliff:g id="ACCOUNT">%2$s</xliff:g>(이 계정의 사용자가 이미 있음)(으)로 신규 사용자를 만들도록 허용하시겠습니까?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g>에서 <xliff:g id="ACCOUNT">%2$s</xliff:g> 계정으로 신규 사용자를 만들도록 허용하시겠습니까? 이 계정으로 등록된 사용자가 이미 존재합니다."</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g>에서 <xliff:g id="ACCOUNT">%2$s</xliff:g> 계정으로 신규 사용자를 만들도록 허용하시겠습니까?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"언어 추가"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"지역 환경설정"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"언어 이름 입력"</string>
diff --git a/core/res/res/values-ky/strings.xml b/core/res/res/values-ky/strings.xml
index e448a30..c61992c 100644
--- a/core/res/res/values-ky/strings.xml
+++ b/core/res/res/values-ky/strings.xml
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; колдонмосуна байланыштарыңызды пайдаланууга уруксат берилсинби?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Жайгашкан жер"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"түзмөктүн жайгашкан жерин аныктоого"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; колдонмосу бул түзмөктүн кайда жүргөнүн көрүп турганга уруксат бересизби?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; колдонмосу бул түзмөктүн кайда жүргөнүн көрүп турсунбу?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"Колдонмону колдонуп жаткан маалда гана, ал сиздин кайда жүргөнүңүздү билип турат."</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; колдонмосу бул түзмөктүн жүргөн жерин &lt;b&gt;ар дайым&lt;/b&gt; билип турсунбу?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"Колдонмону пайдаланып жаткан учурда гана ал жайгашкан жерди көрө алат"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Колдонмого SMS билдирүүлөрүн кабыл алууга жана аларды иштетип чыгууга уруксат берет. Бул, колдонмо сизге билгизбестен түзмөгүңүзгө жөнөтүлгөн билдирүүлөрдү мониторлой же жок кыла алат дегенди билдирет."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"билдирүүлөрдү (MMS) кабыл алуу"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Колдонмого MMS билдирүүлөрүн кабыл алууга жана аларды иштетип чыгууга уруксат берет. Бул, колдонмо сизге билгизбестен түзмөгүңүзгө жөнөтүлгөн билдирүүлөрдү мониторлой же жок кыла алат дегенди билдирет."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"уюктук берүү билдирүүлөрүн окуу"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Колдонмого түзмөгүңүз кабыл алган уюк берүүнүн билдирүүлөрүн окууга жол берет. Шашылыш эскертүү билдирүүлөрү кээ бир жерлердеги өзгөчө кырдаалдар тууралу сизди эскертүү үчүн жөнөтүлөт. Зыяндуу колдономолор шашылыш эскертүүлөр берилип жатканда, сиздин түзмөктүн иштешине жолтоо болушу мүмкүн."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"жазылган түрмөктөрдү окуу"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Колдонмого \"Тынчымды алба\" режиминин конфигурациясын окуу жана жазуу мүмкүнчүлүгүн берет."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"уруксаттын колдонулушун көрүп баштоо"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Колдонмонун пайдаланылышына уруксат берүүгө мүмкүнчүлүк берет. Кадимки колдонмолорго эч качан талап кылынбашы керек."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"максаттуу атайын мүмкүнчүлүк аракетине кыска жол"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Колдонмого максаттуу атайын мүмкүнчүлүк аракетине кыска жолду аныктоого уруксат берет."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Сырсөз эрежелерин коюу"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Экран кулпусунун сырсөздөрү менен PIN\'дерине уруксат берилген узундук менен белгилерди көзөмөлдөө."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Экран кулпусун ачуу аракеттерин көзөмөлдөө"</string>
@@ -1075,7 +1081,7 @@
     <string name="Midnight" msgid="5630806906897892201">"Түн ортосу"</string>
     <string name="elapsed_time_short_format_mm_ss" msgid="4431555943828711473">"<xliff:g id="MINUTES">%1$02d</xliff:g>:<xliff:g id="SECONDS">%2$02d</xliff:g>"</string>
     <string name="elapsed_time_short_format_h_mm_ss" msgid="1846071997616654124">"<xliff:g id="HOURS">%1$d</xliff:g>:<xliff:g id="MINUTES">%2$02d</xliff:g>:<xliff:g id="SECONDS">%3$02d</xliff:g>"</string>
-    <string name="selectAll" msgid="6876518925844129331">"Бардыгын тандоо"</string>
+    <string name="selectAll" msgid="6876518925844129331">"Баарын тандоо"</string>
     <string name="cut" msgid="3092569408438626261">"Кесүү"</string>
     <string name="copy" msgid="2681946229533511987">"Көчүрүү"</string>
     <string name="failed_to_copy_to_clipboard" msgid="1833662432489814471">"Алмашуу буферине көчүрүлбөй калды"</string>
@@ -1257,7 +1263,7 @@
     <string name="wifi_available_content_failed_to_connect" msgid="3377406637062802645">"Бардык тармактарды көрүү үчүн басыңыз"</string>
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Туташуу"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Бардык тармактар"</string>
-    <string name="wifi_suggestion_title" msgid="6396033039578436801">"Сунушталган Wi‑Fi тармактарына туташтырылсынбы?"</string>
+    <string name="wifi_suggestion_title" msgid="6396033039578436801">"Сунушталган Wi‑Fi тармактарына туташасызбы?"</string>
     <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> сунуштаган тармактар. Түзмөк автоматтык түрдө туташышы мүмкүн."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Уруксат берүү"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Жок, рахмат"</string>
@@ -1315,7 +1321,7 @@
     <string name="sms_control_title" msgid="7296612781128917719">"SMS билдирүүлөр жөнөтүлүүдө"</string>
     <string name="sms_control_message" msgid="3867899169651496433">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; көп SMS билдирүүлөрдү жөнөтүп жатат. Бул колдонмо билдирүүлөрдү жөнөтө берсинби?"</string>
     <string name="sms_control_yes" msgid="3663725993855816807">"Ооба"</string>
-    <string name="sms_control_no" msgid="625438561395534982">"Жок"</string>
+    <string name="sms_control_no" msgid="625438561395534982">"Тыюу салынат"</string>
     <string name="sms_short_code_confirm_message" msgid="1645436466285310855">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; &lt;b&gt;<xliff:g id="DEST_ADDRESS">%2$s</xliff:g>&lt;/b&gt; номуруна билдирүү жөнөткөнү жатат."</string>
     <string name="sms_short_code_details" msgid="5873295990846059400">"Бул уюлдук эсебиңиздеги төлөмдөргө "<b>"алып келиши мүмкүн"</b>"."</string>
     <string name="sms_premium_short_code_details" msgid="7869234868023975"><b>"Бул уюлдук эсебиңиздеги төлөмдөргө алып келет."</b></string>
@@ -1346,7 +1352,7 @@
     <string name="no_permissions" msgid="7283357728219338112">"Эч уруксаттын кереги жок"</string>
     <string name="perm_costs_money" msgid="4902470324142151116">"бул үчүн акы алынышы мүмкүн"</string>
     <string name="dlg_ok" msgid="7376953167039865701">"Жарайт"</string>
-    <string name="usb_charging_notification_title" msgid="1595122345358177163">"Бул түзмөк USB аркылуу кубатталууда"</string>
+    <string name="usb_charging_notification_title" msgid="1595122345358177163">"USB аркылуу кубатталууда"</string>
     <string name="usb_supplying_notification_title" msgid="4631045789893086181">"USB аркылуу туташкан түзмөк кубатталууда"</string>
     <string name="usb_mtp_notification_title" msgid="4238227258391151029">"USB аркылуу файл өткөрүү режими күйгүзүлдү"</string>
     <string name="usb_ptp_notification_title" msgid="5425857879922006878">"USB аркылуу PTP режими күйгүзүлдү"</string>
@@ -1357,12 +1363,14 @@
     <string name="usb_power_notification_message" msgid="4647527153291917218">"Туташкан түзмөк кубатталууда. Дагы параметрлерди көрүү үчүн таптап коюңуз."</string>
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Аналогдук аудио жабдуу табылды"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"Тиркелген түзмөк бул телефонго шайкеш келбейт. Көбүрөөк маалымат алуу үчүн таптап коюңуз."</string>
-    <string name="adb_active_notification_title" msgid="6729044778949189918">"Мүчүлүштүктөрдү USB аркылуу оңдоо иштетилген"</string>
-    <string name="adb_active_notification_message" msgid="7463062450474107752">"USB аркылуу мүчүлүштүктөрдү оңдоону өчүрүү үчүн таптаңыз"</string>
+    <string name="adb_active_notification_title" msgid="6729044778949189918">"Мүчүлүштүктөрдү USB аркылуу оңдоо иштеп жатат"</string>
+    <string name="adb_active_notification_message" msgid="7463062450474107752">"Өчүрүү үчүн тийип коюңуз"</string>
     <!-- no translation found for adb_active_notification_message (8470296818270110396) -->
     <skip />
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Сыноо программасынын режими иштетилди"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Сыноо программасынын режимин өчүрүү үчүн, баштапкы жөндөөлөргө кайтарыңыз."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Сериялык консоль иштетилди"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Майнаптуулугуна таасири тиет. Аны өчүрүү үчүн операциялык тутумду жүктөгүчтү текшериңиз."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB портунда суюктук же урандылар бар"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB порт автоматтык түрдө өчүрүлдү. Кененирээк маалымат алуу үчүн таптап коюңуз."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB портун колдонууга болот"</string>
@@ -1451,7 +1459,7 @@
     <string name="grant_credentials_permission_message_footer" msgid="3125211343379376561">"Бул өтүнүчкө уруксат бересизби?"</string>
     <string name="grant_permissions_header_text" msgid="6874497408201826708">"Жетки талабы"</string>
     <string name="allow" msgid="7225948811296386551">"Уруксат берүү"</string>
-    <string name="deny" msgid="2081879885755434506">"Жок"</string>
+    <string name="deny" msgid="2081879885755434506">"Уруксат берилбейт"</string>
     <string name="permission_request_notification_title" msgid="6486759795926237907">"Уруксат талап кылуу"</string>
     <string name="permission_request_notification_with_subtitle" msgid="8530393139639560189">"Кийинки эсепке\nуруксат талап кылынууда: <xliff:g id="ACCOUNT">%s</xliff:g>."</string>
     <string name="forward_intent_to_owner" msgid="1207197447013960896">"Бул колдонмо жумуш профилиңиздин сыртында колдонулуп жатат"</string>
@@ -1892,8 +1900,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Категорияларга бөлүнгөн эмес"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Бул эскертмелердин маанилүүлүгүн белгиледиңиз."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Булар сиз үчүн маанилүү адамдар."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> колдонмосу <xliff:g id="ACCOUNT">%2$s</xliff:g> аккаунту менен жаңы колдонуучу түзө берсинби?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> колдонмосуна <xliff:g id="ACCOUNT">%2$s</xliff:g> аккаунту үчүн жаңы колдонуучу түзгөнгө уруксат бересизби (мындай аккаунту бар колдонуучу мурунтан эле бар)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> колдонмосуна <xliff:g id="ACCOUNT">%2$s</xliff:g> аккаунту менен жаңы колдонуучу түзүүгө уруксат бересизби (мындай аккаунту бар колдонуучу мурунтан эле бар)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> колдонмосуна <xliff:g id="ACCOUNT">%2$s</xliff:g> аккаунту менен жаңы колдонуучу түзүүгө уруксат бересизби?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Тил кошуу"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Чөлкөмдүк жөндөөлөр"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Тилди киргизиңиз"</string>
diff --git a/core/res/res/values-lo/strings.xml b/core/res/res/values-lo/strings.xml
index 56e0a70..fb3afb3 100644
--- a/core/res/res/values-lo/strings.xml
+++ b/core/res/res/values-lo/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"ອະນຸຍາດໃຫ້ແອັບຯຮັບ ແລະປະມວນຜົນຂໍ້ຄວາມ SMS. ນີ້ໝາຍຄວາມວ່າແອັບຯສາມາດຕິດຕາມ ຫຼືລຶບຂໍ້ຄວາມທີ່ສົ່ງເຂົ້າອຸປະກອນຂອງທ່ານ ໂດຍທີ່ບໍ່ສະແດງພວກມັນໃຫ້ທ່ານເຫັນ."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ຮັບຂໍ້ຄວາມ (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"ອະນຸຍາດໃຫ້ແອັບຯ ຮັບແລະປະມວນຜົນຂໍ້ຄວາມ MMS. ນີ້ໝາຍຄວາມວ່າແອັບຯສາມາດຕິດຕາມ ຫຼືລຶບຂໍ້ຄວາມທີ່ສົ່ງເຂົ້າອຸປະກອນຂອງທ່ານ ໂດຍທີ່ບໍ່ສະແດງພວກມັນໃຫ້ທ່ານເຫັນ."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ອ່ານຂໍ້ຄວາມກະຈາຍສັນຍານຂອງເສົາສັນຍານ"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ອະນຸຍາດໃຫ້ແອັບຯ ສາມາດອ່ານຂໍ້ຄວາມແຈ້ງເຕືອນເຫດສຸກເສີນ ທີ່ໄດ້ຮັບໂດຍອຸປະກອນຂອງທ່ານ. ການແຈ້ງເຕືອນສຸກເສີນທີ່ມີໃຫ້ບໍລິການໃນບາງພື້ນທີ່ ເພື່ອແຈ້ງເຕືອນໃຫ້ທ່ານຮູ້ເຖິງສະຖານະການສຸກເສີນ. ແອັບພລິເຄຊັນທີ່ເປັນອັນຕະລາຍອາດລົບກວນປະສິດທິພາບ ຫຼືການດຳເນີນງານຂອງອຸປະກອນຂອງທ່ານ ເມື່ອໄດ້ການຮັບແຈ້ງເຕືອນສຸກເສີນຈາກສະຖານີມືຖື."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ອ່ານຂໍ້ມູນຟີດທີ່ສະໝັກໄວ້"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"ອະນຸຍາດ​​ໃຫ້​ແອັບ​ອ່ານ​ ​ແລະ​ຂຽນການກນຳ​ດຄ່າ ບໍ່​ລົບ​ກວນ."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"ເລີ່ມການໃຊ້ສິດອະນຸຍາດການເບິ່ງ"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ອະນຸຍາດໃຫ້ຜູ້ຖືເລີ່ມການໃຊ້ສິດອະນຸຍາດສຳລັບແອັບໃດໜຶ່ງໄດ້. ແອັບປົກກະຕິບໍ່ຄວນຕ້ອງໃຊ້."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ເປົ້າໝາຍທາງລັດການຊ່ວຍເຂົ້າເຖິງ"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ອະນຸຍາດໃຫ້ແອັບລະບຸເປົ້າໝາຍທາງລັດການຊ່ວຍເຂົ້າເຖິງ."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"ຕັ້ງຄ່າກົດຂອງລະຫັດຜ່ານ"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"ຄວບຄຸມຄວາມຍາວ ແລະຕົວອັກສອນທີ່ອະ​ນຸ​ຍາດ​ໃຫ້​ຢູ່​ໃນລະ​ຫັດລັອກໜ້າຈໍ ແລະ PIN."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"ຕິດຕາມການພະຍາຍາມປົດລັອກໜ້າຈໍ"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"ເລືອກເພື່ອປິດການດີບັ໊ກຜ່ານ USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"ເປີດໃຊ້ໂໝດ Test Harness ແລ້ວ"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"ດຳເນີນການຣີເຊັດເປັນຄ່າຈາກໂຮງງານເພື່ອປິດການນຳໃຊ້ໂໝດ Test Harness."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"ເປີດນຳໃຊ້ຊີຣຽວຄອນໂຊແລ້ວ"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"ມີຜົນກະທົບກັບປະສິດທິພາບ. ເພື່ອປິດການນຳໃຊ້, ໃຫ້ກວດສອບ bootloader ເບິ່ງ."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"ມີຂອງແຫລວ ຫຼື ເສດດິນໃນຜອດ USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"ປິດຜອດ USB ໂດຍອັດຕະໂນມັດແລ້ວ. ແຕະເພື່ອສຶກສາເພີ່ມເຕີມ."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"ສາມາດໃຊ້ຜອດ USB ໄດ້"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"ບໍ່​ມີ​ໝວດ​ໝູ່"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ທ່ານຕັ້ງຄວາມສຳຄັນຂອງການແຈ້ງເຕືອນເຫຼົ່ານີ້."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ຂໍ້ຄວາມນີ້ສຳຄັນເນື່ອງຈາກບຸກຄົນທີ່ກ່ຽວຂ້ອງ."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"ອະນຸຍາດໃຫ້ <xliff:g id="APP">%1$s</xliff:g> ສ້າງຜູ້ໃຊ້ໃໝ່ສຳລັບ <xliff:g id="ACCOUNT">%2$s</xliff:g> ບໍ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"ອະນຸຍາດໃຫ້ <xliff:g id="APP">%1$s</xliff:g> ສ້າງຜູ້ໃຊ້ໃໝ່ສຳລັບ <xliff:g id="ACCOUNT">%2$s</xliff:g> (ຜູ້ໃຊ້ສຳລັບບັນຊີນີ້ມີຢູ່ແລ້ວ) ບໍ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"ອະນຸຍາດໃຫ້ <xliff:g id="APP">%1$s</xliff:g> ສ້າງຜູ້ໃຊ້ໃໝ່ກັບ <xliff:g id="ACCOUNT">%2$s</xliff:g> ໄດ້ບໍ່ (ມີຜູ້ໃຊ້ທີ່ໃຊ້ບັນຊີນີ້ຢູ່ກ່ອນແລ້ວ) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"ອະນຸຍາດໃຫ້ <xliff:g id="APP">%1$s</xliff:g> ສ້າງຜູ້ໃຊ້ໃໝ່ກັບ <xliff:g id="ACCOUNT">%2$s</xliff:g> ໄດ້ບໍ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ເພີ່ມພາສາ"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ການຕັ້ງຄ່າພາກພື້ນ"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ພິມຊື່ພາສາ"</string>
diff --git a/core/res/res/values-lt/strings.xml b/core/res/res/values-lt/strings.xml
index e674c2a..be9e32f 100644
--- a/core/res/res/values-lt/strings.xml
+++ b/core/res/res/values-lt/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Leidžiama programai gauti ir apdoroti SMS pranešimus. Tai reiškia, kad programa gali stebėti ir ištrinti į jūsų įrenginį siunčiamus pranešimus jums jų neparodžiusi."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"gauti teksto pranešimus (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Leidžiama programai gauti ir apdoroti MMS pranešimus. Tai reiškia, kad programa gali stebėti ir ištrinti į jūsų įrenginį siunčiamus pranešimus jums jų neparodžiusi."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"skaityti mobiliuoju transliuojamus pranešimus"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Programai leidžiama skaityti mobiliuoju transliuojamus pranešimus, gaunamus jūsų įrenginyje. Mobiliuoju transliuojami įspėjimai pristatomi kai kuriose vietose, kad įspėtų apie kritines situacijas. Kai gaunamas  mobiliuoju transliuojamas pranešimas apie kritinę situaciją, kenkėjiškos programos gali trukdyti įrenginiui veikti ar jį naudoti."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"skaityti prenumeruojamus tiekimus"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Leidžiama programai skaityti ir rašyti „Do Not Disturb“ konfigūraciją."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"pradėti peržiūrėti leidimo naudojimą"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Leidžia savininkui pradėti naudoti programos leidimą. Įprastoms programoms to neturėtų prireikti."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"pritaikomumo sparčiojo klavišo tikslas"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Programai leidžiama apibrėžti pritaikomumo sparčiojo klavišo tikslą."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Nustatyti slaptažodžio taisykles"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Valdykite, kokio ilgio ekrano užrakto slaptažodžius ir PIN kodus galima naudoti."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Stebėti bandymus atrakinti ekraną"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Pasirinkite, kas išjungtumėte USB derinimą."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Testavimo sistemos režimas įgalintas"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Atkurkite gamyklinius duomenis, kad išjungtumėte testavimo sistemos režimą."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serijos pultas įgalintas"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Našumas paveiktas. Norėdami išjungti, patikrinkite paleidyklę."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB prievade yra skysčių ar smulkių dalelių"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB prievadas automatiškai išjungtas. Palieskite, kad sužinotumėte daugiau."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Saugu naudoti USB prievadą"</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Be kategorijos"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Galite nustatyti šių pranešimų svarbą."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Tai svarbu dėl susijusių žmonių."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Leisti „<xliff:g id="APP">%1$s</xliff:g>“ kurti naują <xliff:g id="ACCOUNT">%2$s</xliff:g> naudotoją?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Leisti „<xliff:g id="APP">%1$s</xliff:g>“ kurti naują <xliff:g id="ACCOUNT">%2$s</xliff:g> naudotoją (šią paskyrą naudojantis naudotojas jau yra)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Leisti „<xliff:g id="APP">%1$s</xliff:g>“ kurti naują <xliff:g id="ACCOUNT">%2$s</xliff:g> naudotoją (šią paskyrą naudojantis naudotojas jau yra)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Leisti „<xliff:g id="APP">%1$s</xliff:g>“ kurti naują <xliff:g id="ACCOUNT">%2$s</xliff:g> naudotoją?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Pridėkite kalbą"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Regiono nuostata"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Įveskite kalbos pav."</string>
diff --git a/core/res/res/values-lv/strings.xml b/core/res/res/values-lv/strings.xml
index 96cb3cd..89575c6 100644
--- a/core/res/res/values-lv/strings.xml
+++ b/core/res/res/values-lv/strings.xml
@@ -347,6 +347,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Ļauj lietotnei saņemt un apstrādāt īsziņas. Tas nozīmē, ka lietotne var pārraudzīt vai dzēst uz jūsu ierīci nosūtītos ziņojumus, neparādot tos jums."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"saņemt ziņojumus (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Ļauj lietotnei saņemt un apstrādāt multiziņas. Tas nozīmē, ka lietotne var pārraudzīt vai dzēst uz jūsu ierīci nosūtītos ziņojumus, neparādot tos jums."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"šūnu apraides ziņojumu lasīšana"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Ļauj lietotnei lasīt ierīcē saņemtos šūnu apraides ziņojumus. Šūnu apraides brīdinājumi tiek piegādāti dažās atrašanās vietās, lai brīdinātu jūs par ārkārtas situācijām. Ļaunprātīgas lietotnes var traucēt ierīces veiktspēju vai darbības, kad ir saņemts ārkārtas šūnas apraides ziņojums."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lasīt abonētās plūsmas"</string>
@@ -658,6 +662,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Ļauj lietotnei lasīt un rakstīt režīma “Netraucēt” konfigurāciju."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"Datu skatīšana par izmantojamajām atļaujām"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Ļauj atļaujas īpašniekam sākt lietotnes atļauju izmantošanu. Parastām lietotnēm tas nekad nav nepieciešams."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"pieejamības īsinājumtaustiņa mērķis"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Ļauj lietotnei definēt pieejamības īsinājumtaustiņa mērķi."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Paroles kārtulu iestatīšana"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontrolēt ekrāna bloķēšanas paroļu un PIN garumu un tajos atļautās rakstzīmes."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Ekrāna atbloķēšanas mēģinājumu pārraudzīšana"</string>
@@ -1383,6 +1389,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Atlasiet, lai atspējotu USB atkļūdošanu."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Drošības pārbaudes režīms ir iespējots"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Lai atspējotu drošības pārbaudes režīmu, veiciet rūpnīcas datu atiestatīšanu."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Seriālā konsole ir iespējota"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Tiek ietekmēta veiktspēja. Lai atspējotu, pārbaudiet operētājsistēmu ielādes rīku."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB pieslēgvietā ir šķidrums vai daļiņas"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB pieslēgvieta ir automātiski atspējota. Pieskarieties, lai uzzinātu vairāk."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB pieslēgvietu drīkst izmantot"</string>
@@ -1924,8 +1932,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Nav kategorijas"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Jūs iestatījāt šo paziņojumu svarīguma līmeni."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Tas ir svarīgi iesaistīto personu dēļ."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Vai atļaut lietotnei <xliff:g id="APP">%1$s</xliff:g> izveidot jaunu lietotāju, izmantojot e-pasta adresi <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Vai atļaut lietotnei <xliff:g id="APP">%1$s</xliff:g> izveidot jaunu lietotāju, izmantojot e-pasta adresi <xliff:g id="ACCOUNT">%2$s</xliff:g> (lietotājs ar šādu kontu jau pastāv)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Vai atļaut lietotnei <xliff:g id="APP">%1$s</xliff:g> izveidot jaunu lietotāju, izmantojot e-pasta adresi <xliff:g id="ACCOUNT">%2$s</xliff:g> (lietotājs ar šādu kontu jau pastāv)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Vai atļaut lietotnei <xliff:g id="APP">%1$s</xliff:g> izveidot jaunu lietotāju, izmantojot e-pasta adresi <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Pievienot valodu"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Reģiona preference"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Ierakstiet valodas nosaukumu"</string>
diff --git a/core/res/res/values-mk/strings.xml b/core/res/res/values-mk/strings.xml
index 39ad811..7144e4d 100644
--- a/core/res/res/values-mk/strings.xml
+++ b/core/res/res/values-mk/strings.xml
@@ -243,7 +243,7 @@
     <string name="global_action_toggle_silent_mode" msgid="8219525344246810925">"Тивок режим"</string>
     <string name="global_action_silent_mode_on_status" msgid="3289841937003758806">"Звукот е исклучен"</string>
     <string name="global_action_silent_mode_off_status" msgid="1506046579177066419">"Звукот е вклучен"</string>
-    <string name="global_actions_toggle_airplane_mode" msgid="5884330306926307456">"Режим на работа во авион"</string>
+    <string name="global_actions_toggle_airplane_mode" msgid="5884330306926307456">"Авионски режим"</string>
     <string name="global_actions_airplane_mode_on_status" msgid="2719557982608919750">"Режимот на работа во авион е вклучен"</string>
     <string name="global_actions_airplane_mode_off_status" msgid="5075070442854490296">"Режимот на работа во авион е исклучен"</string>
     <string name="global_action_settings" msgid="1756531602592545966">"Поставки"</string>
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"Дали да се дозволи &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; да пристапува до контактите?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Локација"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"пристапува до локацијата на овој уред"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"Дали да се дозволи &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; да пристапува до локацијата на уредот?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"Дали да се дозволи &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; да пристапува до локацијата на уредов?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"Апликацијата ќе има пристап до локацијата само додека ја користите"</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"Да се дозволи &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; да пристапува до локацијата на уредов &lt;b&gt;во секое време&lt;/b&gt;?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"Апликацијата во моментов може да пристапува до локацијата само додека ја користите"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Овозможува апликацијата да прима и да обработува SMS пораки. Тоа значи дека апликацијата може да следи или да брише пораки испратени до вашиот уред без да ви ги прикаже вам."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"прими текстуални пораки (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Овозможува апликацијата да прима и да обработува MMS пораки. Тоа значи дека апликацијата може да следи или да брише пораки испратени до вашиот уред без да ви ги прикаже вам."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"прочитај пораки за мобилно емитување"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Овозможува апликациите да ги читаат пораките за мобилно емитување што ги прима вашиот уред. Предупредувањата за мобилно емитување се доставуваат на некои локации, за да ве предупредат на итни ситуации. Злонамерните апликации може да пречат во ефикасноста или работењето на вашиот уред кога се прима емитување за итен случај."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"читај претплатени навестувања на содржина"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Дозволува апликацијата да чита и пишува конфигурација Не вознемирувај."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"започнете со користење на дозволата за приказ"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Дозволува сопственикот да почне со користење на дозволата за апликација. Не треба да се користи за стандардни апликации."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"цел на кратенката за пристапност"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Дозволува апликација да одреди цел на кратенката за пристапност."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Постави правила за лозинката"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Контролирај ги должината и знаците што се дозволени за лозинки и PIN-броеви за отклучување екран."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Следи ги обидите за отклучување на екранот"</string>
@@ -1358,10 +1364,12 @@
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Откриен е аналоген аудиододаток"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"Приложениот уред не е компатибилен со телефонов. Допрете за да дознаете повеќе."</string>
     <string name="adb_active_notification_title" msgid="6729044778949189918">"Поврзано е отстранување грешки преку USB"</string>
-    <string name="adb_active_notification_message" msgid="7463062450474107752">"Допрете за да го исклучите отстранувањето грешки преку USB"</string>
+    <string name="adb_active_notification_message" msgid="7463062450474107752">"Допрете за да го исклучите"</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Изберете за да се оневозможи отстранување грешки на USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Овозможен е режимот на рамка за тестирање"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Извршете фабричко ресетирање за да го оневозможите режимот на рамка за тестирање."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Сериската конзола е овозможена"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Перформансите се засегнати. За да оневозможите, проверете го подигнувачот."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Течност или нечистотија во USB-портата"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-портата е автоматски оневозможена. Допрете за да дознаете повеќе."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Во ред е да се користи USB-порта"</string>
@@ -1893,8 +1901,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Некатегоризирано"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ја поставивте важноста на известувањава."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ова е важно заради луѓето кои се вклучени."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Дозволувате ли <xliff:g id="APP">%1$s</xliff:g> да создаде нов корисник со <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Дозволувате ли <xliff:g id="APP">%1$s</xliff:g> да создаде нов корисник со <xliff:g id="ACCOUNT">%2$s</xliff:g> (веќе постои корисник со оваа сметка)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Дозволувате <xliff:g id="APP">%1$s</xliff:g> да создаде нов корисник со <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Веќе постои корисник со оваа сметка.)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Дозволувате <xliff:g id="APP">%1$s</xliff:g> да создаде нов корисник со <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Додај јазик"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Претпочитувања за регион"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Внеси име на јазик"</string>
diff --git a/core/res/res/values-ml/strings.xml b/core/res/res/values-ml/strings.xml
index 8588031..479bb3a 100644
--- a/core/res/res/values-ml/strings.xml
+++ b/core/res/res/values-ml/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS സന്ദേശങ്ങൾ നേടാനും പ്രോസസ്സുചെയ്യാനും അപ്ലിക്കേഷനെ അനുവദിക്കുന്നു. നിങ്ങളുടെ ഉപകരണത്തിലേക്ക് അയയ്‌ക്കുന്ന സന്ദേശങ്ങൾ നിങ്ങൾക്ക് ദൃശ്യമാക്കാതെ തന്നെ അപ്ലിക്കേഷന് നിരീക്ഷിക്കാനോ ഇല്ലാതാക്കാനോ കഴിയുമെന്നാണ് ഇതിനർത്ഥം."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"വാചക സന്ദേശം നേടുക (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS സന്ദേശങ്ങൾ നേടാനും പ്രോസസ്സുചെയ്യാനും അപ്ലിക്കേഷനെ അനുവദിക്കുന്നു. നിങ്ങളുടെ ഉപകരണത്തിലേക്ക് അയയ്‌ക്കുന്ന സന്ദേശങ്ങൾ നിങ്ങൾക്ക് ദൃശ്യമാക്കാതെ തന്നെ അപ്ലിക്കേഷന് നിരീക്ഷിക്കാനോ ഇല്ലാതാക്കാനോ കഴിയുമെന്നാണ് ഇതിനർത്ഥം."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"സെൽ പ്രക്ഷേപണ സന്ദേശങ്ങൾ റീഡുചെയ്യുക"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"നിങ്ങളുടെ ഉപകരണത്തിൽ ലഭിച്ച സെൽ പ്രക്ഷേപണ സന്ദേശങ്ങൾ റീഡുചെയ്യാൻ അപ്ലിക്കേഷനെ അനുവദിക്കുന്നു. അടിയന്തര സാഹചര്യങ്ങളെക്കുറിച്ച് നിങ്ങൾക്ക് മുന്നറിയിപ്പ് നൽകാനായി ചില ലൊക്കേഷനുകളിൽ നൽകപ്പെടുന്നവയാണ് സെൽ പ്രക്ഷേപണ അലേർട്ടുകൾ. ഒരു അടിയന്തര സെൽ പ്രക്ഷേപണം ലഭിക്കുമ്പോൾ, ക്ഷുദ്രകരമായ അപ്ലിക്കേഷനുകൾ നിങ്ങളുടെ ഉപകരണത്തിന്റെ പ്രകടനമോ പ്രവർത്തനമോ തടസ്സപ്പെടുത്താനിടയുണ്ട്."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"സബ്‌സ്ക്രൈബ് ചെയ്‌ത ഫീഡുകൾ വായിക്കുക"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"\'ശല്യപ്പെടുത്തരുത്\' കോൺഫിഗറേഷൻ വായിക്കുന്നതിനും എഴുതുന്നതിനും ആപ്പിനെ അനുവദിക്കുന്നു."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"അനുമതി ഉപയോഗം കാണാൻ ആരംഭിക്കുക"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ഒരു ആപ്പിനുള്ള അനുമതി ഉപയോഗം ആരംഭിക്കാൻ ഹോൾഡറിനെ അനുവദിക്കുന്നു. സാധാരണ ആപ്പുകൾക്ക് ഒരിക്കലും ആവശ്യമില്ല."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ഉപയോഗസഹായി കുറുക്കുവഴിയുടെ ടാർഗറ്റ്"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ഉപയോഗസഹായി കുറുക്കുവഴിയുടെ ടാർഗറ്റ് നിർവ്വചിക്കാൻ ആപ്പിനെ അനുവദിക്കുക."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"പാസ്‌വേഡ് നിയമങ്ങൾ സജ്ജീകരിക്കുക"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"സ്‌ക്രീൻ ലോക്ക് പാസ്‌വേഡുകളിലും PIN-കളിലും അനുവദിച്ചിരിക്കുന്ന ദൈർഘ്യവും പ്രതീകങ്ങളും നിയന്ത്രിക്കുക."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"സ്‌ക്രീൻ അൺലോക്ക് ശ്രമങ്ങൾ നിരീക്ഷിക്കുക"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ഡീബഗ്ഗുചെയ്യൽ പ്രവർത്തനരഹിതമാക്കാൻ തിരഞ്ഞെടുക്കുക."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"പരിശോധനാ സംവിധാനങ്ങൾ മോഡ് പ്രവർത്തനക്ഷമമാക്കി"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"പരിശോധനാ സംവിധാന മോഡ് പ്രവർത്തനരഹിതമാക്കാൻ ഫാക്‌ടറി പുനഃക്രമീകരണം നിർവഹിക്കുക."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"സീരിയൽ കൺസോൾ പ്രവർത്തനക്ഷമമാക്കി"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"പ്രകടനത്തെ ബാധിച്ചു. പ്രവർത്തനരഹിതമാക്കാൻ, ബൂട്ട് ലോഡർ പരിശോധിക്കുക."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB പോർട്ടിൽ ദ്രാവകമോ പൊടിയോ കണ്ടെത്തി"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB പോർട്ടർ സ്വയമേവ പ്രവർത്തനരഹിതമായി. കൂടുതലറിയാൻ ടാപ്പ് ചെയ്യുക."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"ഇനി USB പോർട്ട് ഉപയോഗിക്കാം"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"വർഗ്ഗീകരിച്ചിട്ടില്ലാത്ത"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ഈ അറിയിപ്പുകളുടെ പ്രാധാന്യം നിങ്ങൾ സജ്ജീകരിച്ചു."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ഉൾപ്പെട്ടിട്ടുള്ള ആളുകളെ കണക്കിലെടുക്കുമ്പോള്‍ ഇത് പ്രധാനപ്പെട്ടതാണ്‌."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="ACCOUNT">%2$s</xliff:g> എന്ന അക്കൗണ്ട് ഉപയോഗിച്ച് പുതിയൊരു ഉപയോക്താവിനെ സൃഷ്ടിക്കാൻ <xliff:g id="APP">%1$s</xliff:g> എന്ന ആപ്പിനെ അനുവദിക്കണോ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g> എന്ന അക്കൗണ്ട് (ഈ അക്കൗണ്ട് ഉപയോഗിച്ചുള്ള ഒരു ഉപയോക്താവ് ഇതിനകം തന്നെ നിലവിലുണ്ട്) ഉപയോഗിച്ച് പുതിയൊരു ഉപയോക്താവിനെ സൃഷ്ടിക്കാൻ <xliff:g id="APP">%1$s</xliff:g> എന്ന ആപ്പിനെ അനുവദിക്കണോ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g> എന്ന അക്കൗണ്ട് (ഈ അക്കൗണ്ട് ഉപയോഗിക്കുന്ന ഒരു ഉപയോക്താവ് നിലവിലുണ്ട്) ഉപയോഗിച്ച് പുതിയ ഉപയോക്താവിനെ സൃഷ്‌ടിക്കാൻ <xliff:g id="APP">%1$s</xliff:g> എന്നതിനെ അനുവദിക്കണോ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> എന്ന അക്കൗണ്ട് ഉപയോഗിച്ച് പുതിയ ഉപയോക്താവിനെ സൃഷ്‌ടിക്കാൻ <xliff:g id="APP">%1$s</xliff:g> എന്നതിനെ അനുവദിക്കണോ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ഒരു ഭാഷ ചേർക്കുക"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"മേഖലാ മുൻഗണന"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ഭാഷയുടെ പേര് ടൈപ്പുചെയ്യുക"</string>
diff --git a/core/res/res/values-mn/strings.xml b/core/res/res/values-mn/strings.xml
index 3672802..1f29956 100644
--- a/core/res/res/values-mn/strings.xml
+++ b/core/res/res/values-mn/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Апп нь SMS мессежийг хүлээн авах болон гүйцэтгэх боломжтой. Ингэснээр апп нь таны төхөөрөмжрүү илгээсэн мессежийг танд үзүүлэхгүйгээр хянах болон устгаж чадна."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"текст мессеж(МMS) хүлээж авах"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Апп нь MMS мессежийг хүлээн авах болон гүйцэтгэх боломжтой. Ингэснээр апп нь таны төхөөрөмжрүү илгээсэн мессежийг танд үзүүлэхгүйгээр хянах болон устгаж чадна."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"үүрэн өргөн дамжууллын мессеж унших"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Апп нь таны төхөөрөмжийн хүлээн авсан үүрэн өргөн дамжуулах мессежийг унших боломжтой. Үүрэн өргөн дамжууллын мэдэгдэл нь яаралтай нөхцөл байдлыг анхааруулах зорилгоор зарим байршлуудад хүрдэг. Хортой апп нь яаралтай үүрэн өргөн дамжууллыг хүлээн авсан үед таны төхөөрөмжийн ажиллагаа болон чадамжид нөлөөлөх боломжтой."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"бүртгүүлсэн хангамжийг унших"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Апп-д Бүү саад бол тохируулгыг уншиж, бичихийг зөвшөөрөх"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"зөвшөөрлийн ашиглалтыг харж эхлэх"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Эзэмшигчид аппын зөвшөөрлөө ашиглаж эхлэхийг зөвшөөрдөг. Энгийн аппуудад шаардлагагүй."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"хандалтын товчлолын зорилт"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Аппад хандалтын товчлолын зорилтыг тодорхойлохыг зөвшөөрдөг."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Нууц үгний дүрмийг тохируулах"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Дэлгэц түгжих нууц үг болон ПИН кодны урт болон нийт тэмдэгтийн уртыг хянах."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Дэлгэцийн түгжээг тайлах оролдлогыг хянах"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB дебаг хийхийг идэвхгүй болгох бол сонгоно уу."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Туршилтын цогц горимыг идэвхжүүлсэн"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Туршилтын цогц горимыг идэвхгүй болгохын тулд үйлдвэрийн төлөвт шинэчилнэ үү."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Цуваа консолыг идэвхжүүлсэн"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Гүйцэтгэлд нөлөөлнө. Идэвхгүй болгохын тулд эхэлж ачаалагчийг шалгана уу."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB порт дээрх шингэн зүйл эсвэл бохирдол"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB портыг автоматаар идэвхгүй болгосон байна. Дэлгэрэнгүй мэдээлэл авахын тулд товшино уу."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB портыг ашиглахад зүгээр"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Ангилаагүй"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Та эдгээр мэдэгдлийн ач холбогдлыг тогтоосон."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Оролцсон хүмүүсээс шалтгаалан энэ нь өндөр ач холбогдолтой."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g>-г <xliff:g id="ACCOUNT">%2$s</xliff:g>-р шинэ Хэрэглэгч үүсгэхийг зөвшөөрөх үү?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g>-г <xliff:g id="ACCOUNT">%2$s</xliff:g>-р шинэ хэрэглэгч үүсгэхийг зөвшөөрөх үү (ийм бүртгэлтэй хэрэглэгч аль хэдийн байна) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g>-д <xliff:g id="ACCOUNT">%2$s</xliff:g>-тай (ийм бүртгэлтэй хэрэглэгч аль хэдийн байна) шинэ хэрэглэгч үүсгэхийг зөвшөөрөх үү ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g>-д <xliff:g id="ACCOUNT">%2$s</xliff:g>-тай шинэ хэрэглэгч үүсгэхийг зөвшөөрөх үү?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Хэл нэмэх"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Бүс нутгийн тохиргоо"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Улсын хэлийг бичнэ үү"</string>
diff --git a/core/res/res/values-mr/strings.xml b/core/res/res/values-mr/strings.xml
index c58ae61..5c6e358 100644
--- a/core/res/res/values-mr/strings.xml
+++ b/core/res/res/values-mr/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS मेसेज प्राप्त करण्याची आणि त्यावर प्रक्रिया करण्याची अ‍ॅप ला अनुमती देते. म्हणजेच अ‍ॅप आपल्या डीव्हाइसवर पाठविलेले मेसेज तुम्हाला न दर्शवता त्यांचे परीक्षण करू किंवा ते हटवू शकतो."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"मजकूर मेसेज मिळवा (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS मेसेज प्राप्त करण्यास आणि त्यावर प्रक्रिया करण्यास अ‍ॅप ला अनुमती देते. म्हणजेच अ‍ॅप आपल्या डिव्हाइसवर पाठविलेले मेसेज तुम्हाला न दर्शवता त्यांचे परीक्षण करू किंवा ते हटवू शकतो."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"सेल प्रसारण मेसेज वाचा"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"आपल्या डिव्हाइसद्वारे प्राप्त केलेले सेल प्रसारण मेसेज वाचण्यासाठी अ‍ॅप ला अनुमती देते. काही स्थानांमध्ये तुम्हाला आणीबाणीच्या परिस्थितीची चेतावणी देण्यासाठी सेल प्रसारण सूचना वितरीत केल्या जातात. आणीबाणी सेल प्रसारण प्राप्त होते तेव्हा आपल्या डिव्हाइसच्या कार्यप्रदर्शनात किंवा कार्यात दुर्भावनापूर्ण अ‍ॅप्स व्यत्यय आणू शकतात."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"सदस्यता घेतलेली फीड वाचा"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"व्यत्यय आणू नका कॉन्फिगरेशन वाचण्यासाठी आणि लिहिण्यासाठी अॅपला अनुमती देते."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"व्ह्यू परवानगी वापर सुरू करा"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"धारकास अ‍ॅपसाठी परवानगी वापरणे सुरू करण्याची अनुमती देते. सामान्य अ‍ॅप्ससाठी कधीही आवश्यकता नसते."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"अॅक्सेसिबिलिटी शॉर्टकट लक्ष्य"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"अ‍ॅपला अॅक्सेसिबिलिटी शॉर्टकट लक्ष्याबद्दल सांगण्यासाठी अनुमती द्या."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"पासवर्ड नियम सेट करा"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"स्क्रीन लॉक पासवर्ड आणि पिन मध्ये अनुमती दिलेले लांबी आणि वर्ण नियंत्रित करा."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"स्क्रीन अनलॉक प्रयत्नांचे परीक्षण करा"</string>
@@ -999,7 +1005,7 @@
     <string name="weeks" msgid="6509623834583944518">"आठवडे"</string>
     <string name="year" msgid="4001118221013892076">"वर्ष"</string>
     <string name="years" msgid="6881577717993213522">"वर्षे"</string>
-    <string name="now_string_shortest" msgid="8912796667087856402">"आत्ता"</string>
+    <string name="now_string_shortest" msgid="8912796667087856402">"आता"</string>
     <plurals name="duration_minutes_shortest" formatted="false" msgid="3957499975064245495">
       <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>मि</item>
       <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>मि</item>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB डीबगिंग बंद करण्यासाठी निवडा."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"टेस्ट हार्नेस मोड सुरू केला आहे"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"टेस्ट हार्नेस मोड बंद करण्यासाठी फॅक्टरी रीसेट करा."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"सिरीअल कन्सोल सुरू केला आहे"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"परफॉर्मन्सवर परिणाम होतो. बंद करण्यासाठी, बूटलोडर तपासा."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB पोर्ट मध्ये ओलावा किंवा धूळ आहे"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB पोर्ट आपोआप बंद होईल. अधिक जाणून घेण्यासाठी टॅप करा."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB पोर्ट वापरण्यासाठी ठीक आहे"</string>
@@ -1673,7 +1681,7 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"प्रवेशयोग्यता शॉर्टकटने <xliff:g id="SERVICE_NAME">%1$s</xliff:g> बंद केली"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"<xliff:g id="SERVICE_NAME">%1$s</xliff:g> वापरण्यासाठी दोन्ही व्हॉल्युम की तीन सेकंद दाबा आणि धरून ठेवा"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"तुम्ही अ‍ॅक्सेसिबिलिटी बटण दाबल्यावर वापरण्यासाठी वैशिष्ट्य निवडा:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"अ‍ॅक्सेसिबिलिटी जेश्चर ज्या सोबत वापराचे आहे अशी सेवा निवडा (स्क्रीनच्या खालच्या बाजूने दोन बोटांनी स्वाइप करा):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"अ‍ॅक्सेसिबिलिटी जेश्चर ज्यासोबत वापराचे आहे अशी सेवा निवडा (स्क्रीनच्या खालच्या बाजूने दोन बोटांनी स्वाइप करा):"</string>
     <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"अ‍ॅक्सेसिबिलिटी जेश्चर ज्या सोबत वापराचे आहे अशी सेवा निवडा (स्क्रीनच्या खालच्या बाजूने तीन बोटांनी स्वाइप करा):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"सेवांदरम्यान स्विच करण्यासाठी, अ‍ॅक्सेसिबिलिटी बटणाला स्पर्श करा आणि धरून ठेवा."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"सेवांदरम्यान स्विच करण्यासाठी, दोन बोटांनी वरच्या दिशेला स्वाइप करा आणि धरून ठेवा."</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"वर्गीकरण न केलेले"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"तुम्ही या सूचनांचे महत्त्व सेट केले."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"सामील असलेल्या लोकांमुळे हे महत्वाचे आहे."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="ACCOUNT">%2$s</xliff:g> सह नवीन वापरकर्ता तयार करण्याची <xliff:g id="APP">%1$s</xliff:g> ला अनुमती द्यायची?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g> सह नवीन वापरकर्ता तयार करण्याची (हे खाते असलेला वापरकर्ता आधीपासून विद्यमान आहे) <xliff:g id="APP">%1$s</xliff:g> ला अनुमती द्यायची?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g> सह नवीन वापरकर्ता तयार करण्याची (हे खाते असलेला वापरकर्ता आधीपासून अस्तित्वात आहे) <xliff:g id="APP">%1$s</xliff:g> ला अनुमती द्यायची आहे का?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> सह नवीन वापरकर्ता तयार करण्याची <xliff:g id="APP">%1$s</xliff:g> ला अनुमती द्यायची आहे का?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"एक भाषा जोडा"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"प्रदेश प्राधान्य"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"भाषा नाव टाइप करा"</string>
diff --git a/core/res/res/values-ms/strings.xml b/core/res/res/values-ms/strings.xml
index 1fd1d71..a7a4c99 100644
--- a/core/res/res/values-ms/strings.xml
+++ b/core/res/res/values-ms/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Membenarkan apl menerima dan memproses mesej SMS. Ini bermakna apl boleh memantau atau memadam mesej yang dihantar ke peranti anda tanpa menunjukkannya kepada anda."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"terima mesej teks (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Membenarkan apl menerima dan memproses mesej MMS. Ini bermakna apl boleh memantau atau memadam mesej yang dihantar ke peranti anda tanpa menunjukkannya kepada anda."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"baca mesej siaran sel"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Membolehkan apl membaca mesej siaran sel yang diterima oleh peranti anda. Isyarat siaran sel dihantar di beberapa lokasi untuk memberi amaran kepada anda tentang situasi kecemasan. Apl hasad boleh mengganggu prestasi atau operasi peranti anda apabila siaran sel kecemasan diterima."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"baca suapan langganan"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Membenarkan apl membaca dan menulis konfigurasi Jangan Ganggu."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"mulakan lihat penggunaan kebenaran"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Membenarkan pemegang memulakan penggunaan kebenaran untuk apl. Tidak sekali-kali diperlukan untuk apl biasa."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"sasaran pintasan kebolehaksesan"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Membenarkan apl mentakrifkan sasaran pintasan kebolehaksesan."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Tetapkan peraturan kata laluan"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Mengawal panjang dan aksara yang dibenarkan dalam kata laluan  dan PIN kunci skrin."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Pantau percubaan buka kunci skrin"</string>
@@ -1258,7 +1264,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Sambung"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Semua rangkaian"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Benarkan rangkaian Wi-Fi yang dicadangkan?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> rangkaian yang dicadangkan. Peranti mungkin disambungkan secara automatik."</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Rangkaian yang dicadangkan oleh <xliff:g id="NAME">%s</xliff:g>. Peranti mungkin disambungkan secara automatik."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Benarkan"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Tidak perlu"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi akan dihidupkan secara automatik"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Pilih untuk melumpuhkan penyahpepijatan USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Mod Abah-abah Ujian didayakan"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Laksanakan tetapan semula kilang untuk melumpuhkan Mod Abah-abah Ujian."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Konsol bersiri didayakan"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Prestasi terjejas. Untuk melumpuhkan, semak pemuat but."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Cecair atau serpihan dalam port USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Port USB dilumpuhkan secara automatik. Ketik untuk mengetahui lebih lanjut."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"OK untuk menggunakan port USB"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Tidak dikategorikan"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Anda menetapkan kepentingan pemberitahuan ini."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Mesej ini penting disebabkan orang yang terlibat."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Benarkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baharu dengan <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Benarkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baharu dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> (Pengguna dengan akaun ini sudah wujud)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Benarkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baharu dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> (Pengguna dengan akaun ini sudah wujud) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Benarkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baharu dengan <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Tambahkan bahasa"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Pilihan wilayah"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Taipkan nama bahasa"</string>
diff --git a/core/res/res/values-my/strings.xml b/core/res/res/values-my/strings.xml
index 4e91ca2..cbe8af4 100644
--- a/core/res/res/values-my/strings.xml
+++ b/core/res/res/values-my/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"အပလီကေးရှင်းအား စာတိုများ လက်ခံခြင်း၊ ဆောင်ရွက်ခြင်း ခွင့်ပြုပါ။ ဤခွင့်ပြုချက်တွင် အပလီကေးရှင်းအနေဖြင့် သင် လက်ခံရရှိသော စာများအား သင့်အား မပြပဲစောင့်ကြည့်ခွင့်နှင့် ဖျက်ပစ်ခွင့်များ ပါဝင်ပါသည်။"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"စာပို့ခြင်းအား လက်ခံရယူခြင်း (ရုပ်သံစာ)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"အပလီကေးရှင်းအား ရုပ်သံစာများ လက်ခံခြင်း၊ ဆောင်ရွက်ခြင်း ခွင့်ပြုပါ။ ဤခွင့်ပြုချက်တွင် အပလီကေးရှင်းအနေဖြင့် သင် လက်ခံရရှိသော စာများအား သင့်အား မပြပဲစောင့်ကြည့်ခွင့်နှင့် ဖျက်ပစ်ခွင့်များ ပါဝင်ပါသည်။"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"စာတိုများ ဖြန့်ဝေခြင်းစနစ်အား ဖတ်ခြင်း"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"အပလီကေးရှင်းကို သင်၏ စက်ပစ္စည်းမှ လက်ခံရရှိသော အများလွှင့်ထုတ်ချက်များကို ဖတ်ရန် ခွင့်ပြုသည်။  အများလွှင့်ထုတ်ချက်များသည် အရေးပေါ်အခြေအနေများကို သင့်အား သတိပေးရန် အချို့ နေရာများတွင် ပို့ပေးသည်။ အရေးပေါ်သတိပေးချက် ထုတ်လွှင့်ချက်ကို လက်ခံရရှိချိန်တွင်အန္တရာယ် ဖြစ်စေနိုင်သော အပလီကေးရှင်းများသည် သင့်စက်ပစ္စည်း၏ လုပ်ငန်းလည်ပတ်မှုနှင့် စွမ်းဆောင်မှုကို ဝင်စွက်ဖက်နိုင်သည်။"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"အမည်သွင်းထားသောဖိဖ့်များကို ဖတ်ခြင်း"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"မနှောင့်ယှက်ရန် ချိန်ညှိမှုကို အပ်ဖ်များ ဖတ်ခြင်း ပြင်ခြင်းပြုလုပ်နိုင်ရန် ခွင့်ပြုမည်။"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"အစမြင်ကွင်း ခွင့်ပြုချက် အသုံးပြုမှု"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"အက်ပ်တစ်ခုအတွက် ခွင့်ပြုချက်စတင်အသုံးပြုမှုကို ကိုင်ဆောင်သူအား ခွင့်ပြုသည်။ ပုံမှန်အက်ပ်များအတွက် ဘယ်သောအခါမျှ မလိုအပ်ပါ။"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"အများသုံးစွဲနိုင်မှု ဖြတ်လမ်းလင့်ခ် ပစ်မှတ်"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"အများသုံးစွဲနိုင်မှု ဖြတ်လမ်းလင့်ခ် ပစ်မှတ်ကို အက်ပ်အား သတ်မှတ်ခွင့်ပြုသည်။"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"စကားဝှက်စည်းမျဥ်းကိုသတ်မှတ်ရန်"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"မျက်နှာပြင်သော့ခတ်သည့် စကားဝှက်များနှင့် PINများရှိ ခွင့်ပြုထားသည့် စာလုံးအရေအတွက်နှင့် အက္ခရာများအား ထိန်းချုပ်ရန်။"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"မျက်နှာပြင်လော့ခ်ဖွင့်ရန် ကြိုးပမ်းမှုများကို စောင့်ကြည့်ပါ"</string>
@@ -1257,7 +1263,7 @@
     <string name="wifi_available_content_failed_to_connect" msgid="3377406637062802645">"ကွန်ရက်အားလုံးကို ကြည့်ရန် တို့ပါ"</string>
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"ချိတ်ဆက်ရန်"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"ကွန်ရက်အားလုံး"</string>
-    <string name="wifi_suggestion_title" msgid="6396033039578436801">"အကြံပြုထားသည့် Wi‑Fi ကွန်ရက်များကို ခွင့်ပြုလိုပါသလား။"</string>
+    <string name="wifi_suggestion_title" msgid="6396033039578436801">"အကြံပြုထားသည့် Wi‑Fi ကွန်ရက်များ ခွင့်ပြုမလား။"</string>
     <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> သည် ကွန်ရက်များကို အကြံပြုထားသည်။ စက်သည် အလိုအလျောက် ချိတ်ဆက်နိုင်သည်။"</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"ခွင့်ပြုရန်"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"မလိုပါ"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ဖြင့် အမှားရှာပြင်ခြင်းကို ပိတ်ရန် ရွေးပါ။"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"\'စမ်းသပ်ခြင်းစနစ်မုဒ်\' ဖွင့်ထားသည်"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"\'စမ်းသပ်ခြင်းစနစ် မုဒ်\' ကိုပိတ်ရန် စက်ရုံထုတ်အတိုင်း ပြင်ဆင်သတ်မှတ်ပါ။"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"အမှတ်စဉ် ကွန်ဆိုးလ်ကို ဖွင့်ထားသည်"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"စွမ်းဆောင်ရည်အပေါ် သက်ရောက်မှုရှိနိုင်ပါသည်။ ပိတ်ရန် bootloader ကို စစ်ဆေးပါ။"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB ပို့တ်တွင် အရည် သို့မဟုတ် အမှိုက်စ ရှိနေသည်"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB ပို့တ်ကို အလိုအလျောက် ပိတ်ထားသည်။ ပိုမိုလေ့လာရန် တို့ပါ။"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB ပို့တ်ကို အသုံးပြုနိုင်သည်"</string>
@@ -1449,8 +1457,8 @@
     <string name="grant_credentials_permission_message_header" msgid="2106103817937859662">"အောက်ပါထဲက အက်ပ်တစ်ခု သို့မဟုတ် ပိုလျက် သင်၏ အကောင့်ကို၊ ယခု နှင့် အနာဂတ်မှာ ရယူအသုံးချရန် ခွင့်ပြုချက်ကို တောင်းထားသည်။"</string>
     <string name="grant_credentials_permission_message_footer" msgid="3125211343379376561">"ဤတောင်းခံမှုအားခွင့်ပြုမည်လား"</string>
     <string name="grant_permissions_header_text" msgid="6874497408201826708">"သုံးစွဲခွင့် တောင်းဆိုရန်"</string>
-    <string name="allow" msgid="7225948811296386551">"ခွင့်ပြုသည်"</string>
-    <string name="deny" msgid="2081879885755434506">"ငြင်းပယ်သည်"</string>
+    <string name="allow" msgid="7225948811296386551">"ခွင့်ပြုရန်"</string>
+    <string name="deny" msgid="2081879885755434506">"ငြင်းပယ်ရန်"</string>
     <string name="permission_request_notification_title" msgid="6486759795926237907">"ခွင့်ပြုချက် တောင်းခံထားခြင်း"</string>
     <string name="permission_request_notification_with_subtitle" msgid="8530393139639560189">"အကောင့် <xliff:g id="ACCOUNT">%s</xliff:g> အတွက် \n ခွင့်ပြုချက် တောင်းခံထားပြီး"</string>
     <string name="forward_intent_to_owner" msgid="1207197447013960896">"သင်သည် ဒီအက်ပ်ကို သင့်အလုပ်ပရိုဖိုင် ပြင်ပတွင် အသုံးပြုနေ၏"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"အမျိုးအစားမခွဲရသေးပါ"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ဤသတိပေးချက်များ၏ အရေးပါမှုကိုသတ်မှတ်ပြီးပါပြီ။"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ပါဝင်သည့်လူများကြောင့် အရေးပါပါသည်။"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> ကို <xliff:g id="ACCOUNT">%2$s</xliff:g> ဖြင့်အသုံးပြုသူအသစ်ဖန်တီးခွင့်ပြုမလား။"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> ကို <xliff:g id="ACCOUNT">%2$s</xliff:g> ဖြင့်အသုံးပြုသူအသစ် ဖန်တီးခွင့်ပြုမလား (ဤအကောင့်ဖြင့် အသုံးပြုသူ ရှိနှင့်ပြီးဖြစ်သည်)။"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ဖြင့်အသုံးပြုသူအသစ်ကို <xliff:g id="APP">%1$s</xliff:g> အား ဖန်တီးခွင့်ပြုလိုပါသလား (ဤအကောင့်ဖြင့် အသုံးပြုသူ ရှိနှင့်ပြီးဖြစ်သည်) ။"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ဖြင့်အသုံးပြုသူအသစ်ကို <xliff:g id="APP">%1$s</xliff:g> အား ဖန်တီးခွင့်ပြုလိုပါသလား ။"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ဘာသာစကားတစ်ခု ထည့်ပါ"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ဒေသရွေးချယ်မှု"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ဘာသာစကားအမည် ထည့်ပါ"</string>
diff --git a/core/res/res/values-nb/strings.xml b/core/res/res/values-nb/strings.xml
index 6972a64..183e2e2 100644
--- a/core/res/res/values-nb/strings.xml
+++ b/core/res/res/values-nb/strings.xml
@@ -226,7 +226,7 @@
     <string name="global_actions" product="default" msgid="2406416831541615258">"Telefoninnstillinger"</string>
     <string name="global_action_lock" msgid="2844945191792119712">"Lås skjermen"</string>
     <string name="global_action_power_off" msgid="4471879440839879722">"Slå av"</string>
-    <string name="global_action_emergency" msgid="7112311161137421166">"Nødsituasjon"</string>
+    <string name="global_action_emergency" msgid="7112311161137421166">"Nødssituasjon"</string>
     <string name="global_action_bug_report" msgid="7934010578922304799">"Feilrapport"</string>
     <string name="global_action_logout" msgid="935179188218826050">"Avslutt økten"</string>
     <string name="global_action_screenshot" msgid="8329831278085426283">"Skjermdump"</string>
@@ -292,7 +292,7 @@
     <string name="permgrouprequest_calendar" msgid="289900767793189421">"Vil du gi &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; tilgang til kalenderen din?"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"sende og lese SMS-meldinger"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Vil du la &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; sende og se SMS-meldinger?"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"Vil du la &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; sende og se tekstmeldinger?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Lagring"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"åpne bilder, medieinnhold og filer på enheten din"</string>
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"Vil du gi &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; tilgang til bilder, medier og filer på enheten din?"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Lar appen motta og behandle tekstmeldinger. Dette betyr at appen kan overvåke eller slette meldinger som er sendt til enheten din uten at du har sett dem."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"motta tekstmeldinger (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Lar appen motta og behandle multimediemeldinger. Dette betyr at appen kan overvåke eller slette meldinger som er sendt til enheten din uten at du har sett dem."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lese kringkastede meldinger"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Tillater at appen kan lese kringkastede meldinger enheten din mottar. Kringkastede varsler leveres noen steder for å advare deg om nødssituasjoner. Skadelige apper kan forstyrre ytelsen eller funksjonen til enheten din når en kringkastet nødmelding mottas."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lese abonnement på nyhetskilder"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Lar appen lese og skrive konfigurasjon av Ikke forstyrr."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"start visning av bruk av tillatelser"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Lar innehaveren starte bruk av tillatelser for en app. Dette skal aldri være nødvendig for vanlige apper."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"mål for tilgjengelighetssnarvei"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Tillat at en app definerer målet for tilgjengelighetssnarveien."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Angi passordregler"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontrollerer tillatt lengde og tillatte tegn i passord og PIN-koder for opplåsing av skjermen."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Overvåk forsøk på å låse opp skjermen"</string>
@@ -815,7 +821,7 @@
     <string name="lockscreen_instructions_when_pattern_enabled" msgid="46154051614126049">"Trykk på menyknappen for å låse opp eller ringe et nødnummer."</string>
     <string name="lockscreen_instructions_when_pattern_disabled" msgid="686260028797158364">"Trykk på menyknappen for å låse opp."</string>
     <string name="lockscreen_pattern_instructions" msgid="7478703254964810302">"Tegn mønster for å låse opp"</string>
-    <string name="lockscreen_emergency_call" msgid="5298642613417801888">"Nødsituasjon"</string>
+    <string name="lockscreen_emergency_call" msgid="5298642613417801888">"Nødssituasjon"</string>
     <string name="lockscreen_return_to_call" msgid="5244259785500040021">"Tilbake til samtale"</string>
     <string name="lockscreen_pattern_correct" msgid="9039008650362261237">"Riktig!"</string>
     <string name="lockscreen_pattern_wrong" msgid="4317955014948108794">"Prøv på nytt"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Velg for å deaktivere USB-debugging."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Testrammeverk-modus er slått på"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Tilbakestill enheten til fabrikkstandard for å slå av Testrammeverk-modus."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Seriekonsollen er aktivert"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Ytelsen er påvirket. Sjekk oppstartsinnlasteren for å deaktivere."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Væske eller rusk i USB-porten"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-porten deaktiveres automatisk. Trykk for å finne ut mer."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Trygt å bruke USB-porten"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Uten kategori"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Du angir viktigheten for disse varslene."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Dette er viktig på grunn av folkene som er involvert."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Vil du la <xliff:g id="APP">%1$s</xliff:g> opprette en ny bruker med <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Vil du la <xliff:g id="APP">%1$s</xliff:g> opprette en ny bruker med <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Det finnes allerede en bruker med denne kontoen.)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Vil du la <xliff:g id="APP">%1$s</xliff:g> opprette en ny bruker med <xliff:g id="ACCOUNT">%2$s</xliff:g> (en bruker med denne kontoen eksisterer allerede)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Vil du la <xliff:g id="APP">%1$s</xliff:g> opprette en ny bruker med <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Legg til et språk"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Regionsinnstilling"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Skriv inn språknavn"</string>
diff --git a/core/res/res/values-ne/strings.xml b/core/res/res/values-ne/strings.xml
index ef312a9..4c4e1f0 100644
--- a/core/res/res/values-ne/strings.xml
+++ b/core/res/res/values-ne/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"अनुप्रयोगलाई SMS सन्देशहरू प्राप्त गर्न र प्रक्रिया गर्न अनुमति दिन्छ। यसको मतलब अनुप्रयोगले तपाईंको उपकरणमा पठाइएको सन्देशहरू तपाईंलाई नदेखाईनै मोनिटर गर्न वा मेटाउन सक्दछ।"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"पाठ सन्देश (MMS) प्राप्त गर्नुहोस्"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"अनुप्रयोगलाई MMS सन्देशहरू प्राप्त गर्न र प्रकृया गर्न अनुमति दिन्छ। यसको मतलब अनुप्रयोगले तपाईंको उपकरणमा पठाइएको सन्देशहरू तपाईंलाई नदेखाईनै मोनिटर गर्न वा मेटाउन सक्दछ।"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"सेल प्रसारित सन्देशहरू पढ्नुहोस्"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"तपाईंको उपकरणद्वारा प्राप्त सेल प्रसारण सन्देशहरू अनुप्रयोगलाई पढ्न अनुमति दिन्छ। सेल प्रसारण चेतावनीहरू केही स्थानहरूमा तपाईंलाई आपतकालीन गतिविधिहरूको बारेमा सचेत गराउन गरिएका छन्। खराब अनुप्रयोगहरूले एउटा आपतकालीन सेल प्रसारण प्राप्त गर्दछ जब तपाईंको उपकरणको प्रदर्शन वा अपरेशनको साथ हस्तक्षेप गर्न सक्दछन्।"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"सदस्य बनाइका फिडहरू पढ्नुहोस्"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"बाधा नपुर्याउँनुहोस् कन्फिगरेसन पढ्न र लेख्‍नको लागि अनुप्रयोगलाई अनुमति दिनुहोस्।"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"हेर्ने अनुमतिको प्रयोग सुरु गर्नुहोस्"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"वाहकलाई कुनै अनुप्रयोगसम्बन्धी अनुमतिको प्रयोग सुरु गर्न दिन्छ। साधारण अनुप्रयोगहरूलाई कहिल्यै आवश्यक नपर्नु पर्ने हो।"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"पहुँचसम्बन्धी सर्टकटको लक्ष्य"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"कुनै अनुप्रयोगलाई पहुँचसम्बन्धी सर्टकटको लक्ष्य परिभाषित गर्न दिन्छ।"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"पासवर्ड नियमहरू मिलाउनुहोस्"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"स्क्रिन लक पासवर्ड र PIN हरूमा अनुमति दिइएको लम्बाइ र वर्णहरूको नियन्त्रण गर्नुहोस्।"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"मनिटरको स्क्रिन अनलक गर्ने प्रयासहरू"</string>
@@ -1367,6 +1373,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB डिबगिङलाई असक्षम पार्न ट्याप गर्नुहोस्।"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"परीक्षण प्याकेज मोड सक्षम पारियो"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"परीक्षण प्याकेज मोड असक्षम पार्न फ्याक्ट्री रिसेट गर्नुहोस्।"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"क्रमसम्बन्धी कन्सोल सक्षम पारियो"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"कार्यसम्पादनमा प्रभाव परेको छ। यसलाई असक्षम पार्न बुटलोडरको जाँच गर्नुहोस्।"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB पोर्टमा तरल पदार्थ वा धुलो भएको कुरा पत्ता लाग्यो"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB पोर्ट स्वतः असक्षम पारियो। थप जान्न ट्याप गर्नुहोस्।"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB पोर्ट प्रयोग गर्दा हुन्छ"</string>
@@ -1896,8 +1904,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"वर्गीकरण नगरिएको"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"तपाईंले यी सूचनाहरूको महत्त्व सेट गर्नुहोस् ।"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"यसमा सङ्लग्न भएका मानिसहरूको कारणले गर्दा यो महत्वपूर्ण छ।"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="ACCOUNT">%2$s</xliff:g> सँगै नयाँ प्रयोगकर्ता सिर्जना गर्न <xliff:g id="APP">%1$s</xliff:g> लाई अनुमति दिने हो?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g> सँगै नयाँ प्रयोगकर्ता सिर्जना गर्न <xliff:g id="APP">%1$s</xliff:g> लाई अनुमति दिने (यस खाताको प्रयोगकर्ता पहिले नै अवस्थित छ) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g> (यस खाताको प्रयोगकर्ता पहिले नै अवस्थित छ) मा नयाँ प्रयोगकर्ता सिर्जना गर्न <xliff:g id="APP">%1$s</xliff:g> लाई अनुमति दिने हो?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> मा नयाँ प्रयोगकर्ता सिर्जना गर्न <xliff:g id="APP">%1$s</xliff:g> लाई अनुमति दिने हो?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"भाषा थप्नुहोस्"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"क्षेत्रको प्राथमिकता"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"भाषाको नाम टाइप गर्नुहोस्"</string>
diff --git a/core/res/res/values-nl/strings.xml b/core/res/res/values-nl/strings.xml
index 1a9797b..b3cc884 100644
--- a/core/res/res/values-nl/strings.xml
+++ b/core/res/res/values-nl/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Hiermee kan de app sms-berichten ontvangen en verwerken. Dit betekent dat de app berichten die naar je apparaat zijn verzonden, kan bijhouden of verwijderen zonder deze aan u weer te geven."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"tekstberichten (MMS) ontvangen"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Hiermee kan de app MMS-berichten ontvangen en verwerken. Dit betekent dat de app berichten die naar je apparaat zijn verzonden, kan bijhouden of verwijderen zonder deze aan u weer te geven."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"infodienstberichten lezen"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Toestaan dat de app infodienstberichten leest die worden ontvangen op je apparaat. Infodienstberichten worden verzonden naar bepaalde locaties om u te waarschjeen voor noodsituaties. Schadelijke apps kunnen de prestaties of verwerking van je apparaat verstoren wanneer een infodienstbericht wordt ontvangen."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"Geabonneerde feeds lezen"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Hiermee kan de app configuratie voor Niet storen lezen en schrijven."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"rechtengebruik starten"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Hiermee kan de houder het rechtengebruik voor een app starten. Nooit vereist voor normale apps."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"doel van snelkoppeling voor toegankelijkheid"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Hiermee kan een app het doel van de snelkoppeling voor toegankelijkheid definiëren."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Wachtwoordregels instellen"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"De lengte en het aantal tekens beheren die zijn toegestaan in wachtwoorden en pincodes voor schermvergrendeling."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Pogingen voor schermontgrendeling bijhouden"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Selecteer deze optie om USB-foutopsporing uit te schakelen."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test harness-modus is ingeschakeld"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Reset de fabrieksinstellingen om de test harness-modus uit te schakelen."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Seriële console ingeschakeld"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Dit is van invloed op de prestaties. Controleer de bootloader om dit uit te schakelen."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Vloeistof of vuil in USB-poort"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-poort is automatisch uitgeschakeld. Tik voor meer informatie."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB-poort kan worden gebruikt"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Geen categorie"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Je stelt het belang van deze meldingen in."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Dit is belangrijk vanwege de betrokken mensen."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Toestaan dat <xliff:g id="APP">%1$s</xliff:g> een nieuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> maakt?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Toestaan dat <xliff:g id="APP">%1$s</xliff:g> een nieuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> maakt (er is al een gebruiker met dit account)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Toestaan dat <xliff:g id="APP">%1$s</xliff:g> een nieuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> maakt (er is al een gebruiker met dit account)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Toestaan dat <xliff:g id="APP">%1$s</xliff:g> een nieuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> maakt?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Een taal toevoegen"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Regiovoorkeur"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Typ een taalnaam"</string>
diff --git a/core/res/res/values-or/strings.xml b/core/res/res/values-or/strings.xml
index 1da68a3..eb8f4c6 100644
--- a/core/res/res/values-or/strings.xml
+++ b/core/res/res/values-or/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS ମେସେଜ୍‌ ପ୍ରାପ୍ତ କରିବାକୁ ତଥା ପ୍ରକ୍ରିୟା କରାଇବାକୁ ଆପ୍‍ଟିକୁ ଅନୁମତି ଦିଏ। ଏହାର ଅର୍ଥ ହେଉଛି, ଆପଣଙ୍କ ଡିଭାଇସ୍‍କୁ ପଠାଯାଇଥିବା ମେସେଜ୍‍ ଆପଣଙ୍କୁ ନଦେଖାଇ ଆପ୍‍ଟି ମନିଟର୍‍ କିମ୍ବା ଡିଲିଟ୍‍ କରିପାରେ।"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ଟେକ୍ସଟ୍‍ ମେସେଜ୍‍ (MMS) ପ୍ରାପ୍ତ କରନ୍ତୁ"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS ମେସେଜ୍‌ ପ୍ରାପ୍ତ କରିବାକୁ ତଥା ପ୍ରକ୍ରିୟା କରାଇବାକୁ ଆପ୍‍ଟିକୁ ଅନୁମତି ଦିଏ। ଏହାର ଅର୍ଥ, ଆପଣଙ୍କ ଡିଭାଇସ୍‍କୁ ପଠାଯାଇଥିବା ମେସେଜ୍‍ ଆପଣଙ୍କୁ ନଦେଖାଇ ଆପ୍‍ଟି ମନିଟର୍‍ କିମ୍ବା ଡିଲିଟ୍‍ କରିପାରେ।"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ସେଲ୍‍ ବ୍ରଡ୍‍କାଷ୍ଟ ମେସେଜ୍‍ ପଢ଼ନ୍ତୁ"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ଆପଣଙ୍କ ଡିଭାଇସ୍‍ରେ ପ୍ରାପ୍ତ ହୋଇଥିବା ସେଲ୍‍ ବ୍ରଡ୍‍କାଷ୍ଟ ମେସେଜ୍‍ ପଢିବାକୁ ଆପ୍‍କୁ ଅନୁମତି ଦିଏ। ଜରୁରୀକାଳୀନ ଅବସ୍ଥା ବିଷୟରେ ଆପଣଙ୍କୁ ସତର୍କ କରାଇବାକୁ କିଛି ଲୋକେଶନ୍‍ରେ ସେଲ୍‍ ବ୍ରଡ୍‍କାଷ୍ଟ ସତର୍କ ଡେଲିଭର୍ କରାଯାଇଥାଏ। ଏକ ଜରୁରୀକାଳୀନ ସେଲ୍‍ ବ୍ରଡ୍‍କାଷ୍ଟ ପ୍ରାପ୍ତ ହେବାପରେ ହାନୀକାରକ ଆପ୍‍ ଆପଣଙ୍କ ଡିଭାଇସ୍‍ର କାର୍ଯ୍ୟକ୍ଷମତା କିମ୍ବା ସଞ୍ଚାଳନାରେ ବାଧା ପହଞ୍ଚାଇପାରନ୍ତି।"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ସବସ୍କ୍ରାଇବ୍ ହୋଇଥିବା ଫୀଡ୍‌କୁ ପଢ଼ନ୍ତୁ"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"\"ବିରକ୍ତ କରନ୍ତୁ ନାହିଁ\" କନଫିଗରେଶନ୍‍ ପଢ଼ିବା ତଥା ଲେଖିବା ପାଇଁ ଆପକୁ ଅନୁମତି ଦେଇଥାଏ।"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"ଅନୁମତି ବ୍ୟବହାର ଦେଖିବା ଆରମ୍ଭ କରନ୍ତୁ"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ଏକ ଆପ୍ ପାଇଁ ଅନୁମତିର ବ୍ୟବହାର ଆରମ୍ଭ କରିବାକୁ ଧାରକକୁ ଅନୁମତି ଦେଇଥାଏ। ସାଧାରଣ ଆପ୍‌ଗୁଡ଼ିକ ପାଇଁ ଏହା ଆବଶ୍ୟକ ନୁହେଁ।"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ଆକ୍ସେସିବିଲିଟୀ ସର୍ଟକଟ୍ ଟାର୍ଗେଟ୍"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ଆକ୍ସେସିବିଲିଟୀ ସର୍ଟକଟ୍ ଟାର୍ଗେଟ୍ ବ୍ୟାଖ୍ୟା କରିବା ପାଇଁ ଯେ କୌଣସି ଆପ୍‍କୁ ଅନୁମତି ଦିଏ।"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"ପାସ୍‌ୱର୍ଡ ନିୟମାବଳୀ ସେଟ୍ କରନ୍ତୁ"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"ଲକ୍‍ ସ୍କ୍ରୀନ୍‍ ପାସ୍‌ୱର୍ଡ ଓ PINରେ ଅନୁମୋଦିତ ଦୀର୍ଘତା ଓ ବର୍ଣ୍ଣ ନିୟନ୍ତ୍ରଣ କରନ୍ତୁ।"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"ସ୍କ୍ରୀନ୍-ଅନଲକ୍ କରିବା ଉଦ୍ୟମ ନୀରିକ୍ଷଣ କରନ୍ତୁ"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ଡିବଗିଙ୍ଗକୁ ଅକ୍ଷମ କରିବା ପାଇଁ ଚୟନ କରନ୍ତୁ।"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"ଟେଷ୍ଟ ହାର୍ନେସ୍ ମୋଡ୍ ସକ୍ଷମ ଅଛି"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"ଟେଷ୍ଟ ହାର୍‌ନେସ୍ ମୋଡ୍ ଅକ୍ଷମ କରିବାକୁ ଏକ ଫ୍ୟାକ୍ଟରୀ ରିସେଟ୍ କରନ୍ତୁ।"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"କ୍ରମିକ କନ୍‍‍ସୋଲ୍‍କୁ ସକ୍ଷମ କରାଯାଇଛି"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"କାର୍ଯ୍ୟଦକ୍ଷତା ପ୍ରଭାବିତ ହୋଇଛି। ଅକ୍ଷମ କରିବା ପାଇଁ, ବୁଟ୍‌ଲୋଡର୍‍ର ଯାଞ୍ଚ କରନ୍ତୁ।"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB ପୋର୍ଟରେ ତରଳ ପଦାର୍ଥ ବା ଧୂଳି"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB ପୋର୍ଟ ସ୍ୱଚାଳିତ ଭାବେ ଅକ୍ଷମ ହୋଇଛି। ଅଧିକ ଜାଣିବା ପାଇଁ ଟାପ୍ କରନ୍ତୁ।"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB ପୋର୍ଟ ବ୍ୟବହାର କରିବା ପାଇଁ ଠିକ୍ ଅଟେ"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"ଅବର୍ଗୀକୃତ"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ଏହି ବିଜ୍ଞପ୍ତିଗୁଡ଼ିକର ପ୍ରମୁଖତା ଆପଣ ସେଟ୍‍ କରନ୍ତି।"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ସମ୍ପୃକ୍ତ ଲୋକଙ୍କ କାରଣରୁ ଏହା ଗୁରୁତ୍ୱପୂର୍ଣ୍ଣ ଅଟେ।"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ସହ ଏକ ନୂଆ ୟୁଜର୍‌ ତିଆରି କରିବା ପାଇଁ <xliff:g id="APP">%1$s</xliff:g>କୁ ଅନୁମତି ଦେବେ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ସହ ଏକ ନୂଆ ୟୁଜର୍‌ ତିଆରି କରିବାକୁ <xliff:g id="APP">%1$s</xliff:g>କୁ ଅନୁମତି ଦେବେ (ଏହି ଆକାଉଣ୍ଟରେ ଜଣେ ୟୁଜର୍‌ ପୂର୍ବରୁ ରହିଛନ୍ତି)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g>ରେ ଏକ ନୂଆ ଉପଯୋଗକର୍ତ୍ତା ତିଆରି କରିବା ପାଇଁ <xliff:g id="ACCOUNT">%2$s</xliff:g>କୁ (ପୂର୍ବରୁ ଏହି ଆକାଉଣ୍ଟ ଉପଯୋଗକର୍ତ୍ତାଙ୍କ ନାମରେ ଅଛି) ଅନୁମତି ଦେବେ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g>ରେ ଏକ ନୂଆ ଉପଯୋଗକର୍ତ୍ତା ତିଆରି କରିବା ପାଇଁ <xliff:g id="ACCOUNT">%2$s</xliff:g>କୁ ଅନୁମତି ଦେବେ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ଏକ ଭାଷା ଯୋଡ଼ନ୍ତୁ"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ପସନ୍ଦର ଅଞ୍ଚଳ"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ଭାଷାର ନାମ ଟାଇପ୍‍ କରନ୍ତୁ"</string>
diff --git a/core/res/res/values-pa/strings.xml b/core/res/res/values-pa/strings.xml
index d39ea13..bc68885 100644
--- a/core/res/res/values-pa/strings.xml
+++ b/core/res/res/values-pa/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"ਐਪ ਨੂੰ SMS ਸੁਨੇਹੇ ਪ੍ਰਾਪਤ ਕਰਨ ਅਤੇ ਉਹਨਾਂ ਦੀ ਪ੍ਰਕਿਰਿਆ ਕਰਨ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ। ਇਸਦਾ ਮਤਲਬ ਹੈ ਕਿ ਐਪ ਤੁਹਾਡੇ ਡੀਵਾਈਸ ਤੇ ਭੇਜੇ ਗਏ ਸੁਨੇਹਿਆਂ ਨੂੰ ਤੁਹਾਨੂੰ ਦਿਖਾਏ ਬਿਨਾਂ ਨਿਰੀਖਣ ਕਰ ਸਕਦੀ ਹੈ ਜਾਂ ਮਿਟਾ ਸਕਦੀ ਹੈ।"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ਟੈਕਸਟ ਸੁਨੇਹੇ (MMS) ਪੜ੍ਹੋ"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"ਐਪ ਨੂੰ MMS ਸੁਨੇਹੇ ਪ੍ਰਾਪਤ ਕਰਨ ਅਤੇ ਉਹਨਾਂ ਦੀ ਪ੍ਰਕਿਰਿਆ ਕਰਨ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ। ਇਸਦਾ ਮਤਲਬ ਹੈ ਕਿ ਐਪ ਤੁਹਾਡੇ ਡੀਵਾਈਸ ਤੇ ਭੇਜੇ ਗਏ ਸੁਨੇਹਿਆਂ ਨੂੰ ਤੁਹਾਨੂੰ ਦਿਖਾਏ ਬਿਨਾਂ ਨਿਰੀਖਣ ਕਰ ਸਕਦੀ ਹੈ ਜਾਂ ਮਿਟਾ ਸਕਦੀ ਹੈ।"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ਸੈਲ ਪ੍ਰਸਾਰਨ ਸੁਨੇਹੇ ਪੜ੍ਹੋ"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ਐਪ ਨੂੰ ਤੁਹਾਡੀ ਡੀਵਾਈਸ ਵੱਲੋਂ ਪ੍ਰਾਪਤ ਕੀਤੇ ਸੈੱਲ ਪ੍ਰਸਾਰਣ ਸੁਨੇਹੇ ਪੜ੍ਹਨ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ। ਸੈੱਲ ਪ੍ਰਸਾਰਣ ਚਿਤਾਵਨੀਆਂ ਤੁਹਾਨੂੰ ਸੰਕਟਕਾਲੀਨ ਸਥਿਤੀਆਂ ਦੀ ਚਿਤਾਵਨੀ ਦੇਣ ਲਈ ਕੁਝ ਨਿਰਧਾਰਤ ਟਿਕਾਣਿਆਂ ਤੇ ਪ੍ਰਦਾਨ ਕੀਤੀਆਂ ਜਾਂਦੀਆਂ ਹਨ। ਖਰਾਬ ਐਪਾਂ ਤੁਹਾਡੇ ਡੀਵਾਈਸ ਦੇ ਪ੍ਰਦਰਸ਼ਨ ਜਾਂ ਓਪਰੇਸ਼ਨ ਵਿੱਚ ਵਿਘਨ ਪਾ ਸਕਦੀਆਂ ਹਨ ਜਦੋਂ ਇੱਕ ਸੰਕਟਕਾਲੀਨ ਸੈੱਲ ਪ੍ਰਸਾਰਣ ਪ੍ਰਾਪਤ ਕੀਤਾ ਜਾਂਦਾ ਹੈ।"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ਸਬਸਕ੍ਰਾਈਬ ਕੀਤੇ ਫੀਡਸ ਪੜ੍ਹੋ"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"ਐਪ ਨੂੰ ਪਰੇਸ਼ਾਨ ਨਾ ਕਰੋ ਕੌਂਫਿਗਰੇਸ਼ਨ ਨੂੰ ਪੜ੍ਹਨ ਅਤੇ ਲਿਖਣ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ।"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"ਇਜਾਜ਼ਤ ਵਰਤੋਂ ਦੇਖਣਾ ਸ਼ੁਰੂ ਕਰੋ"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ਧਾਰਕ ਨੂੰ ਕਿਸੇ ਹੋਰ ਐਪ ਲਈ ਇਜਾਜ਼ਤ ਵਰਤੋਂ ਨੂੰ ਸ਼ੁਰੂ ਕਰਨ ਦਿੰਦਾ ਹੈ। ਸਧਾਰਨ ਐਪਾਂ ਲਈ ਕਦੇ ਵੀ ਲੋੜੀਂਦਾ ਨਹੀਂ ਹੋਵੇਗਾ।"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ਪਹੁੰਚਯੋਗਤਾ ਸ਼ਾਰਟਕੱਟ ਟੀਚਾ"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ਕਿਸੇ ਐਪ ਨੂੰ ਪਹੁੰਚਯੋਗਤਾ ਸ਼ਾਰਟਕੱਟ ਟੀਚੇ ਨੂੰ ਪਰਿਭਾਸ਼ਿਤ ਕਰਨ ਦਿਓ।"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"ਪਾਸਵਰਡ ਨਿਯਮ ਸੈੱਟ ਕਰੋ"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"ਸਕ੍ਰੀਨ ਲਾਕ ਪਾਸਵਰਡਾਂ ਅਤੇ ਪਿੰਨ ਵਿੱਚ ਆਗਿਆ ਦਿੱਤੀ ਲੰਮਾਈ ਅਤੇ ਅੱਖਰਾਂ ਤੇ ਨਿਯੰਤਰਣ ਪਾਓ।"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"ਸਕ੍ਰੀਨ ਅਣਲਾਕ ਕਰਨ ਦੀਆਂ ਕੋਸ਼ਿਸ਼ਾਂ \'ਤੇ ਨਿਗਰਾਨੀ ਰੱਖੋ"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB ਡੀਬੱਗਿੰਗ ਅਯੋਗ ਬਣਾਉਣ ਲਈ ਚੁਣੋ।"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"ਟੈਸਟ ਹਾਰਨੈੱਸ ਮੋਡ ਚਾਲੂ ਹੈ"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"ਟੈਸਟ ਹਾਰਨੈੱਸ ਮੋਡ ਬੰਦ ਕਰਨ ਲਈ ਫੈਕਟਰੀ ਰੀਸੈੱਟ ਕਰੋ।"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"ਸੀਰੀਅਲ ਕੰਸੋਲ ਚਾਲੂ ਕੀਤਾ ਗਿਆ"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"ਕਾਰਗੁਜ਼ਾਰੀ ਪ੍ਰਭਾਵਿਤ ਹੋਈ ਹੈ। ਬੰਦ ਕਰਨ ਲਈ, ਬੂਟਲੋਡਰ ਦੇਖੋ।"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB ਪੋਰਟ ਵਿੱਚ ਪਾਣੀ ਜਾਂ ਧੂੜ-ਮਿੱਟੀ"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB ਪੋਰਟ ਸਵੈਚਲਿਤ ਤੌਰ \'ਤੇ ਬੰਦ ਕੀਤਾ ਗਿਆ। ਹੋਰ ਜਾਣਨ ਲਈ ਟੈਪ ਕਰੋ।"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB ਪੋਰਟ ਵਰਤਣ ਲਈ ਠੀਕ ਹੈ"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"ਗੈਰ-ਸ਼੍ਰੇਣੀਕਿਰਤ"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ਤੁਸੀਂ ਇਹਨਾਂ ਸੂਚਨਾਵਾਂ ਦੀ ਮਹੱਤਤਾ ਸੈੱਟ ਕੀਤੀ।"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ਇਹ ਸ਼ਾਮਲ ਲੋਕਾਂ ਦੇ ਕਾਰਨ ਮਹੱਤਵਪੂਰਨ ਹੈ।"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"ਕੀ <xliff:g id="APP">%1$s</xliff:g> ਨੂੰ <xliff:g id="ACCOUNT">%2$s</xliff:g> ਨਾਲ ਇੱਕ ਨਵਾਂ ਵਰਤੋਂਕਾਰ ਬਣਾਉਣ ਦੀ ਮਨਜ਼ੂਰੀ ਦੇਣੀ ਹੈ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"ਕੀ <xliff:g id="APP">%1$s</xliff:g> ਨੂੰ <xliff:g id="ACCOUNT">%2$s</xliff:g> ਨਾਲ ਇੱਕ ਨਵਾਂ ਵਰਤੋਂਕਾਰ ਬਣਾਉਣ ਦੀ ਆਗਿਆ ਦੇਣੀ ਹੈ (ਇਸ ਖਾਤੇ ਨਾਲ ਇੱਕ ਵਰਤੋਂਕਾਰ ਪਹਿਲਾਂ ਤੋਂ ਹੀ ਮੌਜੂਦ ਹੈ) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"ਕੀ <xliff:g id="APP">%1$s</xliff:g> ਨੂੰ <xliff:g id="ACCOUNT">%2$s</xliff:g> ਨਾਲ ਨਵਾਂ ਵਰਤੋਂਕਾਰ ਬਣਾਉਣ ਦੀ ਇਜਾਜ਼ਤ ਦੇਣੀ ਹੈ (ਇਸ ਖਾਤੇ ਨਾਲ ਇੱਕ ਵਰਤੋਂਕਾਰ ਪਹਿਲਾਂ ਤੋਂ ਹੀ ਮੌਜੂਦ ਹੈ)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"ਕੀ <xliff:g id="APP">%1$s</xliff:g> ਨੂੰ <xliff:g id="ACCOUNT">%2$s</xliff:g> ਨਾਲ ਨਵਾਂ ਵਰਤੋਂਕਾਰ ਬਣਾਉਣ ਦੀ ਇਜਾਜ਼ਤ ਦੇਣੀ ਹੈ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ਇੱਕ ਭਾਸ਼ਾ ਸ਼ਾਮਲ ਕਰੋ"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ਖੇਤਰ ਤਰਜੀਹ"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"ਭਾਸ਼ਾ ਨਾਮ ਟਾਈਪ ਕਰੋ"</string>
diff --git a/core/res/res/values-pl/strings.xml b/core/res/res/values-pl/strings.xml
index a53608a..1dbe1c1 100644
--- a/core/res/res/values-pl/strings.xml
+++ b/core/res/res/values-pl/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Pozwala aplikacji na odbieranie i przetwarzanie SMS-ów. To oznacza, że aplikacja będzie mogła bez Twojej wiedzy monitorować i usuwać wiadomości wysyłane do Twojego urządzenia."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"odbieranie wiadomości tekstowych (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Pozwala aplikacji na odbieranie i przetwarzanie MMS-ów. To oznacza, że aplikacja będzie mogła bez Twojej wiedzy monitorować i usuwać wiadomości wysyłane do Twojego urządzenia."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"odczyt komunikatów z sieci komórkowej"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Zezwala aplikacji na odczyt komunikatów z sieci komórkowej odebranych na urządzeniu. Komunikaty alarmowe z sieci komórkowej są dostarczane w niektórych lokalizacjach w celu ostrzeżenia Cię o sytuacjach zagrożenia. Złośliwe aplikacje mogą wpływać na wydajność lub zakłócać działanie urządzenia po odebraniu komunikatu alarmowego z sieci komórkowej."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"czytanie subskrybowanych źródeł"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Pozwala aplikacji na odczyt i zmianę konfiguracji trybu Nie przeszkadzać."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"rozpocząć wyświetlanie użycia uprawnień"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Umożliwia rozpoczęcie korzystania z uprawnienia dotyczącego danej aplikacji jego posiadaczowi. Zwykłe aplikacje nie powinny potrzebować tego uprawnienia."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cel skrótu do ułatwień dostępu"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Pozwala aplikacji definiować cel skrótu do ułatwień dostępu."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Określ reguły hasła"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontrolowanie długości haseł blokady ekranu i kodów PIN oraz dozwolonych w nich znaków."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitorowanie prób odblokowania ekranu"</string>
@@ -1302,7 +1308,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Połącz"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Wszystkie sieci"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Zezwalać na sugerowane sieci Wi‑Fi?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Sugerowane sieci: <xliff:g id="NAME">%s</xliff:g>. Urządzenie może połączyć się automatycznie."</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Sugerowane sieci: <xliff:g id="NAME">%s</xliff:g>. Urządzenie może łączyć się automatycznie."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Zezwól"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Nie, dziękuję"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi włączy się automatycznie"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Wybierz, aby wyłączyć debugowanie USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Tryb jarzma testowego został włączony"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Przywróć ustawienia fabryczne, by wyłączyć tryb jarzma testowego."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Konsola szeregowa włączona"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Wpływa na wydajność. Aby wyłączyć, sprawdź program rozruchowy."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Wilgoć lub brud w porcie USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Port USB został automatycznie wyłączony. Kliknij, by dowiedzieć się więcej."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Możesz używać portu USB"</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Bez kategorii"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ustawiłeś ważność tych powiadomień."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ta wiadomość jest ważna ze względu na osoby uczestniczące w wątku."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Zezwalasz aplikacji <xliff:g id="APP">%1$s</xliff:g> na utworzenie nowego użytkownika dla konta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Zezwalasz aplikacji <xliff:g id="APP">%1$s</xliff:g> na utworzenie nowego użytkownika dla konta <xliff:g id="ACCOUNT">%2$s</xliff:g>)? Użytkownik z tym kontem już istnieje."</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Zezwolić aplikacji <xliff:g id="APP">%1$s</xliff:g> na utworzenie nowego użytkownika dla konta <xliff:g id="ACCOUNT">%2$s</xliff:g> (użytkownik dla tego konta już istnieje)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Zezwolić aplikacji <xliff:g id="APP">%1$s</xliff:g> na utworzenie nowego użytkownika dla konta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Dodaj język"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Ustawienie regionu"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Wpisz nazwę języka"</string>
diff --git a/core/res/res/values-pt-rBR/strings.xml b/core/res/res/values-pt-rBR/strings.xml
index f0d8d05..c5bcb1d 100644
--- a/core/res/res/values-pt-rBR/strings.xml
+++ b/core/res/res/values-pt-rBR/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite que o app receba e processe mensagens SMS. Isso significa que o app pode monitorar ou excluir mensagens enviadas para o dispositivo sem mostrá-las para você."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"receber mensagens de texto (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite que o app receba e processe mensagens MMS. Isso significa que o app pode monitorar ou excluir as mensagens enviadas para o dispositivo sem mostrá-las para você."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ler mensagens de difusão celular"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite que o app leia mensagens de difusão celular recebidas por seu dispositivo. Alertas de difusão celular são recebidos em alguns locais para avisar você de situações de emergência. Apps maliciosos podem interferir no desempenho ou funcionamento de seu dispositivo quando uma difusão celular de emergência é recebida."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ler feeds inscritos"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permitir que o app leia e grave a configuração \"Não perturbe\"."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"iniciar uso da permissão para visualização"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permite que o sistema inicie o uso de permissão para um app. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"objetivo do atalho de acessibilidade"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permite que um app defina o objetivo do atalho de acessibilidade."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Definir regras para senha"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controla o tamanho e os caracteres permitidos nos PINs e nas senhas do bloqueio de tela."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitorar tentativas de desbloqueio de tela"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Selecione para desativar a depuração USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Modo Arcabouço de testes ativado"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Realize uma redefinição para configuração original para desativar o modo Arcabouço de testes."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Console serial ativado"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"O desempenho foi impactado. Para desativar, verifique o carregador de inicialização."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Líquido ou detrito na porta USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"A porta USB é desativada automaticamente. Toque para saber mais."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"É seguro usar a porta USB"</string>
@@ -1478,7 +1486,7 @@
     <string name="submit" msgid="1602335572089911941">"Enviar"</string>
     <string name="car_mode_disable_notification_title" msgid="5704265646471239078">"O app para carro está sendo usado"</string>
     <string name="car_mode_disable_notification_message" msgid="7647248420931129377">"Toque para sair do app para carro."</string>
-    <string name="tethered_notification_title" msgid="3146694234398202601">"Vínculo ou ponto de acesso ativo"</string>
+    <string name="tethered_notification_title" msgid="3146694234398202601">"Ponto de acesso ou tethering ativo"</string>
     <string name="tethered_notification_message" msgid="2113628520792055377">"Toque para configurar."</string>
     <string name="disable_tether_notification_title" msgid="7526977944111313195">"Tethering desativado"</string>
     <string name="disable_tether_notification_message" msgid="2913366428516852495">"Fale com seu administrador para saber detalhes"</string>
@@ -1672,8 +1680,8 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"O atalho de acessibilidade desativou o <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Toque nos dois botões de volume e os mantenha pressionados por três segundo para usar o <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Escolha um serviço a ser usado quando você toca no botão Acessibilidade:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Escolha um serviço a ser usado com o gesto de acessibilidade (deslizar de baixo para cima na tela com dois dedos):"</string>
-    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Escolha um serviço a ser usado com o gesto de acessibilidade (deslizar de baixo para cima na tela com três dedos):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Escolha um serviço para usar com o gesto de acessibilidade (deslizar de baixo para cima na tela com dois dedos):"</string>
+    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Escolha um serviço para usar com o gesto de acessibilidade (deslizar de baixo para cima na tela com três dedos):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Para alternar entre serviços, toque no botão de acessibilidade e mantenha-o pressionado."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Para alternar entre serviços, deslize de baixo para cima na tela com dois dedos sem soltar."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Para alternar entre serviços, deslize de baixo para cima na tela com três dedos sem soltar."</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sem classificação"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Você definiu a importância dessas notificações."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Isso é importante por causa das pessoas envolvidas."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Permitir que <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Permitir que <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um usuário com essa conta)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um usuário com essa conta)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Adicionar um idioma"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferência de região"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Digitar nome do idioma"</string>
diff --git a/core/res/res/values-pt-rPT/strings.xml b/core/res/res/values-pt-rPT/strings.xml
index 5d5618f..29ef549 100644
--- a/core/res/res/values-pt-rPT/strings.xml
+++ b/core/res/res/values-pt-rPT/strings.xml
@@ -229,7 +229,7 @@
     <string name="global_action_emergency" msgid="7112311161137421166">"Emergência"</string>
     <string name="global_action_bug_report" msgid="7934010578922304799">"Relatório de erros"</string>
     <string name="global_action_logout" msgid="935179188218826050">"Terminar sessão"</string>
-    <string name="global_action_screenshot" msgid="8329831278085426283">"Captura de ecrã"</string>
+    <string name="global_action_screenshot" msgid="8329831278085426283">"Capt. ecrã"</string>
     <string name="bugreport_title" msgid="5981047024855257269">"Relatório de erro"</string>
     <string name="bugreport_message" msgid="398447048750350456">"Será recolhida informação sobre o estado atual do seu dispositivo a enviar através de uma mensagem de email. Demorará algum tempo até que o relatório de erro esteja pronto para ser enviado. Aguarde um pouco."</string>
     <string name="bugreport_option_interactive_title" msgid="8635056131768862479">"Relatório interativo"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite que a aplicação receba e processe mensagens SMS. Isto significa que a aplicação poderá monitorizar ou eliminar mensagens enviadas para o seu dispositivo sem as apresentar."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"receber mensagens de texto (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite que a aplicação receba e processe mensagens MMS. Isto significa que a aplicação poderá monitorizar ou eliminar mensagens enviadas para o seu dispositivo sem as apresentar."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ler mensagens de transmissão celular"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite que a aplicação leia mensagens de transmissão celular recebidas pelo seu dispositivo. Os alertas de transmissão celular são fornecidos em algumas localizações para avisá-lo sobre situações de emergência. As aplicações maliciosas podem interferir com o desempenho ou funcionamento do seu dispositivo quando for recebida uma transmissão celular de emergência."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ler feeds subscritos"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permite à aplicação ler e alterar a configuração de Não incomodar"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"iniciar utilização da autorização de visualização"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permite que o titular inicie a utilização de autorizações para uma aplicação. Nunca deverá ser necessário para aplicações normais."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"alvo do atalho de acessibilidade"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permite a uma aplicação definir o alvo do atalho de acessibilidade."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Definir regras de palavra-passe"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controlar o comprimento e os carateres permitidos nos PINs e nas palavras-passe do bloqueio de ecrã."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitorizar tentativas de desbloqueio do ecrã"</string>
@@ -1357,10 +1363,12 @@
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"Acessório de áudio analógico detetado"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"O dispositivo ligado não é compatível com este telemóvel. Toque para saber mais."</string>
     <string name="adb_active_notification_title" msgid="6729044778949189918">"Depuração USB ligada"</string>
-    <string name="adb_active_notification_message" msgid="7463062450474107752">"Toque para desativar a depuração USB."</string>
+    <string name="adb_active_notification_message" msgid="7463062450474107752">"Toque para desativar a depuração USB"</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Selecione para desativar a depuração por USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Modo de estrutura de teste ativado"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Efetue uma reposição de dados de fábrica para desativar o Modo de estrutura de teste."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Consola de série ativada"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"O desempenho é afetado. Para desativar, selecione o carregador de arranque."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Líquido ou resíduos na porta USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"A porta USB é automaticamente desativada. Toque para saber mais."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"É seguro utilizar a porta USB"</string>
@@ -1508,7 +1516,7 @@
     <string name="sync_really_delete" msgid="2572600103122596243">"Eliminar os itens"</string>
     <string name="sync_undo_deletes" msgid="2941317360600338602">"Anular as eliminações"</string>
     <string name="sync_do_nothing" msgid="3743764740430821845">"Não fazer nada por agora"</string>
-    <string name="choose_account_label" msgid="5655203089746423927">"Selecionar uma conta"</string>
+    <string name="choose_account_label" msgid="5655203089746423927">"Selecione uma conta"</string>
     <string name="add_account_label" msgid="2935267344849993553">"Adicionar uma conta"</string>
     <string name="add_account_button_label" msgid="3611982894853435874">"Adicionar conta"</string>
     <string name="number_picker_increment_button" msgid="2412072272832284313">"Aumentar"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sem categoria"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Definiu a importância destas notificações."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"É importante devido às pessoas envolvidas."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Pretende permitir que o <xliff:g id="APP">%1$s</xliff:g> crie um novo utilizador com <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Pretende permitir que o <xliff:g id="APP">%1$s</xliff:g> crie um novo utilizador com <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um utilizador com esta conta)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Pretende permitir que a aplicação <xliff:g id="APP">%1$s</xliff:g> crie um novo utilizador com a conta <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um utilizador com esta conta)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Pretende permitir que a aplicação <xliff:g id="APP">%1$s</xliff:g> crie um novo utilizador com a conta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Adicionar um idioma"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferência de região"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Intr. nome do idioma"</string>
diff --git a/core/res/res/values-pt/strings.xml b/core/res/res/values-pt/strings.xml
index f0d8d05..c5bcb1d 100644
--- a/core/res/res/values-pt/strings.xml
+++ b/core/res/res/values-pt/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite que o app receba e processe mensagens SMS. Isso significa que o app pode monitorar ou excluir mensagens enviadas para o dispositivo sem mostrá-las para você."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"receber mensagens de texto (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite que o app receba e processe mensagens MMS. Isso significa que o app pode monitorar ou excluir as mensagens enviadas para o dispositivo sem mostrá-las para você."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ler mensagens de difusão celular"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite que o app leia mensagens de difusão celular recebidas por seu dispositivo. Alertas de difusão celular são recebidos em alguns locais para avisar você de situações de emergência. Apps maliciosos podem interferir no desempenho ou funcionamento de seu dispositivo quando uma difusão celular de emergência é recebida."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ler feeds inscritos"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permitir que o app leia e grave a configuração \"Não perturbe\"."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"iniciar uso da permissão para visualização"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permite que o sistema inicie o uso de permissão para um app. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"objetivo do atalho de acessibilidade"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permite que um app defina o objetivo do atalho de acessibilidade."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Definir regras para senha"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controla o tamanho e os caracteres permitidos nos PINs e nas senhas do bloqueio de tela."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitorar tentativas de desbloqueio de tela"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Selecione para desativar a depuração USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Modo Arcabouço de testes ativado"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Realize uma redefinição para configuração original para desativar o modo Arcabouço de testes."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Console serial ativado"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"O desempenho foi impactado. Para desativar, verifique o carregador de inicialização."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Líquido ou detrito na porta USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"A porta USB é desativada automaticamente. Toque para saber mais."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"É seguro usar a porta USB"</string>
@@ -1478,7 +1486,7 @@
     <string name="submit" msgid="1602335572089911941">"Enviar"</string>
     <string name="car_mode_disable_notification_title" msgid="5704265646471239078">"O app para carro está sendo usado"</string>
     <string name="car_mode_disable_notification_message" msgid="7647248420931129377">"Toque para sair do app para carro."</string>
-    <string name="tethered_notification_title" msgid="3146694234398202601">"Vínculo ou ponto de acesso ativo"</string>
+    <string name="tethered_notification_title" msgid="3146694234398202601">"Ponto de acesso ou tethering ativo"</string>
     <string name="tethered_notification_message" msgid="2113628520792055377">"Toque para configurar."</string>
     <string name="disable_tether_notification_title" msgid="7526977944111313195">"Tethering desativado"</string>
     <string name="disable_tether_notification_message" msgid="2913366428516852495">"Fale com seu administrador para saber detalhes"</string>
@@ -1672,8 +1680,8 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"O atalho de acessibilidade desativou o <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Toque nos dois botões de volume e os mantenha pressionados por três segundo para usar o <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Escolha um serviço a ser usado quando você toca no botão Acessibilidade:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Escolha um serviço a ser usado com o gesto de acessibilidade (deslizar de baixo para cima na tela com dois dedos):"</string>
-    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Escolha um serviço a ser usado com o gesto de acessibilidade (deslizar de baixo para cima na tela com três dedos):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Escolha um serviço para usar com o gesto de acessibilidade (deslizar de baixo para cima na tela com dois dedos):"</string>
+    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Escolha um serviço para usar com o gesto de acessibilidade (deslizar de baixo para cima na tela com três dedos):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Para alternar entre serviços, toque no botão de acessibilidade e mantenha-o pressionado."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Para alternar entre serviços, deslize de baixo para cima na tela com dois dedos sem soltar."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Para alternar entre serviços, deslize de baixo para cima na tela com três dedos sem soltar."</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Sem classificação"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Você definiu a importância dessas notificações."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Isso é importante por causa das pessoas envolvidas."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Permitir que <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Permitir que <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um usuário com essa conta)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um usuário com essa conta)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Adicionar um idioma"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferência de região"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Digitar nome do idioma"</string>
diff --git a/core/res/res/values-ro/strings.xml b/core/res/res/values-ro/strings.xml
index d790efc..8ee45f9 100644
--- a/core/res/res/values-ro/strings.xml
+++ b/core/res/res/values-ro/strings.xml
@@ -347,6 +347,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite aplicației să primească și să proceseze mesaje SMS. Acest lucru înseamnă că aplicația ar putea monitoriza sau șterge mesajele trimise pe dispozitivul dvs. fără a vi le arăta."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"primește mesaje text (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite aplicației să primească și să proceseze mesaje MMS. Acest lucru înseamnă că aplicația ar putea monitoriza sau șterge mesajele trimise pe dispozitivul dvs. fără a vi le arăta."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"citește mesajele cu transmisie celulară"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite aplicației să citească mesajele primite prin transmisie celulară de dispozitivul dvs. Alertele cu transmisie celulară sunt difuzate în unele locații pentru a vă avertiza cu privire la situațiile de urgență. Aplicațiile rău intenționate pot afecta performanța sau funcționarea dispozitivului dvs. când este primită o transmisie celulară de urgență."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"citire feeduri abonat"</string>
@@ -658,6 +662,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permite aplicației să citească și să scrie configurația Nu deranja."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"porniți folosirea permisiunii de vizualizare"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Permite proprietarului să pornească folosirea permisiunii pentru o aplicație. Nu ar trebui să fie necesară pentru aplicațiile obișnuite."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ținta comenzii rapide de accesibilitate"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Permite unei aplicații să definească ținta comenzii rapide de accesibilitate."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Să seteze reguli pentru parolă"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Stabiliți lungimea și tipul de caractere permise pentru parolele și codurile PIN de blocare a ecranului."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Să monitorizeze încercările de deblocare a ecranului"</string>
@@ -1383,6 +1389,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Selectați pentru a dezactiva remedierea erorilor prin USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Modul Set de testare este activat"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Reveniți la setările din fabrică pentru a dezactiva modul Set de testare."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Consola din serie este activată"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performanța este afectată. Pentru a dezactiva, verificați programul bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Lichide sau reziduuri în portul USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Portul USB este dezactivat automat. Atingeți ca să aflați mai multe."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Portul USB poate fi folosit"</string>
@@ -1924,8 +1932,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Neclasificate"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Dvs. setați importanța acestor notificări."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Notificarea este importantă având în vedere persoanele implicate."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Permiteți ca <xliff:g id="APP">%1$s</xliff:g> să creeze un nou utilizator folosind <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Permiteți ca <xliff:g id="APP">%1$s</xliff:g> să creeze un nou utilizator folosind <xliff:g id="ACCOUNT">%2$s</xliff:g>? (există deja un utilizator cu acest cont)"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Permiteți ca <xliff:g id="APP">%1$s</xliff:g> să creeze un nou utilizator folosind <xliff:g id="ACCOUNT">%2$s</xliff:g>? (există deja un utilizator cu acest cont)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Permiteți ca <xliff:g id="APP">%1$s</xliff:g> să creeze un nou utilizator folosind <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Adăugați o limbă"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Regiunea preferată"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Numele limbii"</string>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index 0becae0..655cf1b 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Приложение сможет получать и обрабатывать SMS. Это значит, что оно сможет отслеживать и удалять отправленные на ваше устройство сообщения, не показывая их."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"Прием MMS-сообщений"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Приложение сможет получать и обрабатывать MMS. Это значит, что оно сможет отслеживать и удалять отправленные на ваше устройство сообщения, не показывая их."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"Читать сообщения массовой рассылки"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Приложение получит доступ к сообщениям широковещательных SMS-служб, которые в некоторых странах используются для информирования населения об экстренных ситуациях. Вредоносные программы могут помешать работе устройства, на которое поступают такие сообщения."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"Просмотр фидов пользователя"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Открывает приложению доступ к настройкам режима \"Не беспокоить\" и позволяет изменять их."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"Просмотр данных об используемых разрешениях"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Приложение получит доступ к данным об используемых разрешениях. Это разрешение не требуется обычным приложениям."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"Цель быстрого включения"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Приложение сможет определять цель быстрого включения."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Настройка правил для паролей"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Контролировать длину и символы при вводе пароля и PIN-кода."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Отслеживание попыток разблокировать экран"</string>
@@ -1301,7 +1307,7 @@
     <string name="wifi_available_content_failed_to_connect" msgid="3377406637062802645">"Нажмите, чтобы увидеть список сетей"</string>
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Подключиться"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Все сети"</string>
-    <string name="wifi_suggestion_title" msgid="6396033039578436801">"Разрешить подключение к предложенным сетям Wi‑Fi?"</string>
+    <string name="wifi_suggestion_title" msgid="6396033039578436801">"Подключаться к предложенным сетям Wi‑Fi?"</string>
     <string name="wifi_suggestion_content" msgid="5603992011371520746">"Приложение \"<xliff:g id="NAME">%s</xliff:g>\" рекомендует сети, к которым устройство может подключаться автоматически."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Разрешить"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Нет, спасибо"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Нажмите, чтобы отключить отладку по USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Тестовый режим включен"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Чтобы отключить тестовый режим, сбросьте настройки до заводских."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Консоль последовательного порта включена"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Производительность устройства снижена. Чтобы отключить консоль, перейдите в загрузчик операционной системы."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"В USB-порт попала вода или грязь"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-порт был автоматически отключен. Нажмите, чтобы узнать подробности."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB-порт можно использовать"</string>
@@ -1720,8 +1728,8 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"Сервис <xliff:g id="SERVICE_NAME">%1$s</xliff:g> отключен"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Чтобы использовать сервис \"<xliff:g id="SERVICE_NAME">%1$s</xliff:g>\", нажмите и удерживайте обе клавиши громкости в течение трех секунд."</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Выберите сервис, который будет запускаться при нажатии кнопки специальных возможностей:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Выберите сервис, который будет запускаться жестом для доступа к специальным возможностям (провести по экрану снизу вверх двумя пальцами):"</string>
-    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Выберите сервис, который будет запускаться жестом для доступа к специальным возможностям (провести по экрану снизу вверх тремя пальцами):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Выберите сервис, который будет запускаться жестом (провести по экрану снизу вверх двумя пальцами):"</string>
+    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Выберите сервис, который будет запускаться жестом (провести по экрану снизу вверх тремя пальцами):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Для переключения между сервисами нажмите и удерживайте кнопку специальных возможностей."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Для переключения между сервисами проведите по экрану снизу вверх двумя пальцами и задержите их."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Для переключения между сервисами проведите по экрану снизу вверх тремя пальцами и задержите их."</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Без категории"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Вы определяете важность этих уведомлений."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Важное (люди)"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Разрешить приложению \"<xliff:g id="APP">%1$s</xliff:g>\" создать пользователя для аккаунта <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Разрешить приложению \"<xliff:g id="APP">%1$s</xliff:g>\" создать нового пользователя для аккаунта <xliff:g id="ACCOUNT">%2$s</xliff:g> (пользователь c таким аккаунтом уже есть)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Разрешить приложению \"<xliff:g id="APP">%1$s</xliff:g>\" создать нового пользователя с аккаунтом <xliff:g id="ACCOUNT">%2$s</xliff:g> (пользователь с этим аккаунтом уже существует)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Разрешить приложению \"<xliff:g id="APP">%1$s</xliff:g>\" создать нового пользователя с аккаунтом <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Добавьте язык"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Региональные настройки"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Введите язык"</string>
diff --git a/core/res/res/values-si/strings.xml b/core/res/res/values-si/strings.xml
index a46da16..5fc6b53 100644
--- a/core/res/res/values-si/strings.xml
+++ b/core/res/res/values-si/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS පණිවිඩ ලැබීමට සහ ක්‍රියාත්මක කිරීමට යෙදුමට අවසර දෙන්න. මෙහි තේරුම යෙදුමට ඔබගේ උපාංගයට ලැබෙන පණිවිඩ අධීක්ෂණය කිරීමට හැකිවීම වන අතර, ඒවා ඔබට නොපෙන්වා මකා දැමීමටද හැකි වීමයි."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"පෙළ පණිවුඩ ලබාගන්න (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS පණිවිඩ සොයා ලබාගැනීමට සහ ක්‍රියාත්මක කිරීමට යෙදුමට අවසර දෙන්න. යෙදුම නිරීක්ෂණය කරනු ලබන අතර ඔබට ලැබුන පණිවිඩ පෙන්වීමෙන් තොරවම මකා දැමිය හැකි බව මෙමඟින් අදහස් කරයි."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"සෙල් ප්‍රචාරණ පණිවිඩ කියවීම"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ඔබගේ උපාංගයට ලැබුණු සෙල් විකාශන පණිවිඩ කියවීමට යෙදුමට අවසර දෙන්න. ඔබට හදිසි අවස්ථාවන් පිළිබඳ අනතුරු ඇඟවීමට සෙල් විකාශන පණිවිඩ ඇතැම් ස්ථානවල සිට යවනු ලබයි. හදිසි සෙල් විකාශන ලැබෙන අවස්ථාවකදී, අනිෂ්ට යෙදුම් මඟින් ඔබගේ උපාංගයට කාර්ය සාධනයට හෝ ක්‍රියකරණයට බාධා සිදුවිය හැක."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"දායක වූ සංග්‍රහ කියවීම"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"බාධා නොකරන්න වින්‍යාස කිරීම කියවීමට සහ ලිවීමට යෙදුමට ඉඩ දෙයි."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"අවසර භාවිතය බැලීමට ආරම්භ කරන්න"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"තබා සිටින්නාට යෙදුමක් සඳහා අවසර භාවිතය ආරම්භ කිරීමට ඉඩ දෙයි. සාමාන්‍ය යෙදුම් සඳහා කිසි විටෙක අවශ්‍ය නොවිය යුතු ය."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ප්‍රවේශ්‍යතා කෙටිමං ඉලක්කය"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ප්‍රවේශ්‍යතා කෙටිමං ඉලක්කය නිර්වචනය කිරීමට යෙදුමකට ඉඩ දෙන්න."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"මුරපද නීති සකස් කිරීම"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"තිර අගුලු මුරපද සහ PIN තුළ ඉඩ දෙන දිග සහ අනුලකුණු පාලනය කිරීම."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"තිරය අගුළු ඇරීමේ උත්සාහයන් නිරීක්ෂණය කරන්න"</string>
@@ -1363,6 +1369,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB නිදොස්කරණය අබල කිරීමට තෝරන්න."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"පුරක පරීක්‍ෂා ප්‍රකාරය සබලයි"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"පුරක පරීක්‍ෂා ප්‍රකාරය අබල කිරීමට කර්මාන්තශාලා යළි සැකසීමක් ඉටු කරන්න."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"අනුක්‍රමික කොන්සෝලය සබලයි"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"කාර්ය සාධනය බලපෑමට ලක් වී ඇත. අබල කිරීමට, ආරම්භකය පරීක්ෂා කරන්න."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB තොට තුළ ද්‍රව හෝ කුණු"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB තොට ස්වයංක්‍රීයව අබල කෙරේ. තවත් දැන ගැනීමට තට්ටු කරන්න."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB තොට භාවිත කළාට කමක් නැත"</string>
@@ -1892,8 +1900,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"වර්ගීකරණය නොකළ"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ඔබ මෙම දැනුම්දීම්වල වැදගත්කම සකසා ඇත."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"සම්බන්ධ වූ පුද්ගලයන් නිසා මෙය වැදගත් වේ."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> හට <xliff:g id="ACCOUNT">%2$s</xliff:g> සමගින් නව පරිශීලකයෙකු සෑදීමට ඉඩ දෙන්නද?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> හට <xliff:g id="ACCOUNT">%2$s</xliff:g> සමගින් නව පරිශීලකයෙකු සෑදීමට ඉඩ දෙන්නද (මෙම ගිණුම සහිත පරිශීලකයෙකු දැනටමත් සිටී) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> හට <xliff:g id="ACCOUNT">%2$s</xliff:g> සමගින් නව පරිශීලකයෙකු සෑදීමට ඉඩ දෙන්නද (මෙම ගිණුම සහිත පරිශීලකයෙකු දැනටමත් සිටී) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> හට <xliff:g id="ACCOUNT">%2$s</xliff:g> සමගින් නව පරිශීලකයෙකු සෑදීමට ඉඩ දෙන්නද ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"භාෂාවක් එක් කරන්න"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ප්‍රදේශ මනාපය"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"භාෂා නම ටයිප් කරන්න"</string>
diff --git a/core/res/res/values-sk/strings.xml b/core/res/res/values-sk/strings.xml
index f996537..ce17331 100644
--- a/core/res/res/values-sk/strings.xml
+++ b/core/res/res/values-sk/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Umožňuje aplikácii prijímať a spracovávať správy SMS. Znamená to, že aplikácia môže sledovať správy odoslané na vaše zariadenie alebo ich odstrániť bez toho, aby sa vám zobrazili."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"prijímať textové správy (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Umožňuje aplikácii prijímať a spracovávať správy MMS. Znamená to, že aplikácia môže sledovať správy odoslané na vaše zariadenie alebo ich odstrániť bez toho, aby sa vám zobrazili."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"čítať správy informačných služieb"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Umožňuje aplikácii čítať správy informačných služieb prijaté vaším zariadením. Správy informačných služieb sa doručujú na určitých miestach a upozorňujú na tiesňové situácie. Škodlivé aplikácie môžu pri prijatí správy informačnej služby narušiť výkonnosť alebo prevádzku vášho zariadenia."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"čítať odoberané informačné kanály"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Umožňuje aplikácii čítať a zapisovať konfiguráciu režimu bez vyrušení."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"spustenie používania povolenia na zobrazenie"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Umožňuje držiteľovi spustiť používanie povolenia aplikáciou. Bežné aplikácie by toto povolenie nemali nikdy potrebovať."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cieľ skratky dostupnosti"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Umožňuje aplikácii definovať cieľ skratky dostupnosti."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Nastaviť pravidlá pre heslo"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Nastavte dĺžku hesiel na odomknutie obrazovky aj kódov PIN a v nich používané znaky."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Sledovanie pokusov o odomknutie obrazovky"</string>
@@ -1302,7 +1308,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Pripojiť"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Všetky siete"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Chcete povoliť navrhované siete Wi‑Fi?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Siete navrhnuté aplikáciou <xliff:g id="NAME">%s</xliff:g>. Zariadenie sa môže pripojiť automaticky."</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"Siete navrhuje aplikácia <xliff:g id="NAME">%s</xliff:g>. Zariadenie sa môže pripájať automaticky."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Povoliť"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Nie, ďakujem"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi sa zapne automaticky"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Vyberte, ak chcete zakázať ladenie cez USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Režim správcu testov je aktivovaný"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Ak chcete zakázať režim správcu testov, obnovte výrobné nastavenia."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Sériová konzola je povolená"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Ovplyvňuje výkon. Ak ju chcete zakázať, skontrolujte zavádzací program systému."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Tekutina alebo nečistoty v porte USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Port USB je automaticky deaktivovaný. Ďalšie informácie zobrazíte klepnutím."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Port USB môžete použiť"</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Nekategorizované"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Nastavili ste dôležitosť týchto upozornení."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Táto správa je dôležitá vzhľadom na osoby, ktorých sa to týka."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Povoliť aplikácii <xliff:g id="APP">%1$s</xliff:g> vytvoriť nového používateľa pomocou účtu <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Povoliť aplikácii <xliff:g id="APP">%1$s</xliff:g> vytvoriť nového používateľa pomocou účtu <xliff:g id="ACCOUNT">%2$s</xliff:g> (používateľ s týmto účtom už existuje)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Chcete povoliť aplikácii <xliff:g id="APP">%1$s</xliff:g> vytvoriť nového používateľa pomocou účtu <xliff:g id="ACCOUNT">%2$s</xliff:g> (používateľ s týmto účtom už existuje)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Chcete povoliť aplikácii <xliff:g id="APP">%1$s</xliff:g> vytvoriť nového používateľa pomocou účtu <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Pridať jazyk"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferovaný región"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Zadajte názov jazyka"</string>
diff --git a/core/res/res/values-sl/strings.xml b/core/res/res/values-sl/strings.xml
index b75644b..ec0863f 100644
--- a/core/res/res/values-sl/strings.xml
+++ b/core/res/res/values-sl/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Aplikaciji omogoča prejemanje in obdelavo SMS-ov. S tem lahko aplikacija nadzoruje ali izbriše sporočila, poslana v napravo, ne da bi vam jih pokazala."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"prejemanje sporočil (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Aplikaciji omogoča prejemanje in obdelavo MMS-ov. S tem lahko aplikacija nadzoruje ali izbriše sporočila, poslana v napravo, ne da bi vam jih pokazala."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"branje sporočil oddaje v celici"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Omogoča aplikaciji branje sporočil oddaje v celici, ki jih prejme naprava. Opozorila oddaje v celici so dostavljena na nekaterih lokacijah, da vas opozorijo na izredne razmere. Zlonamerne aplikacije lahko vplivajo na delovanje naprave, ko dobi sporočilo oddaje v celici."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"branje naročenih virov"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Aplikaciji omogoča branje in pisanje konfiguracije načina »ne moti«."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"začetek uporabe dovoljenja za ogledovanje"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Imetniku omogoča začetek uporabe dovoljenj za aplikacijo. Nikoli ni potrebno za navadne aplikacije."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"cilj bližnjice funkcije za ljudi s posebnimi potrebami"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Aplikaciji dovoljuje, da določi cilj bližnjice funkcije za ljudi s posebnimi potrebami."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Nastavitev pravil za geslo"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Nadzor nad dolžino in znaki, ki so dovoljeni v geslih in kodah PIN za odklepanje zaslona."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Nadzor nad poskusi odklepanja zaslona"</string>
@@ -1063,10 +1069,10 @@
       <item quantity="other">pred <xliff:g id="COUNT_1">%d</xliff:g> minutami</item>
     </plurals>
     <plurals name="duration_hours_relative" formatted="false" msgid="676894109982008411">
-      <item quantity="one">pred <xliff:g id="COUNT_1">%d</xliff:g> uro</item>
-      <item quantity="two">pred <xliff:g id="COUNT_1">%d</xliff:g> urama</item>
-      <item quantity="few">pred <xliff:g id="COUNT_1">%d</xliff:g> urami</item>
-      <item quantity="other">pred <xliff:g id="COUNT_1">%d</xliff:g> urami</item>
+      <item quantity="one">pred <xliff:g id="COUNT_1">%d</xliff:g> h</item>
+      <item quantity="two">pred <xliff:g id="COUNT_1">%d</xliff:g> h</item>
+      <item quantity="few">pred <xliff:g id="COUNT_1">%d</xliff:g> h</item>
+      <item quantity="other">pred <xliff:g id="COUNT_1">%d</xliff:g> h</item>
     </plurals>
     <plurals name="duration_days_relative" formatted="false" msgid="2203515825765397130">
       <item quantity="one">pred <xliff:g id="COUNT_1">%d</xliff:g> dnevom</item>
@@ -1302,7 +1308,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"Vzpostavi povezavo"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"Vsa omrežja"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"Želite dovoliti predlagana omrežja Wi-Fi?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> – predlagana omrežja Naprava se lahko poveže samodejno."</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> – predlagana omrežja. Naprava se lahko poveže samodejno."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"Dovoli"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"Ne, hvala"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Povezava Wi‑Fi se bo samodejno vklopila"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Izberite, če želite onemogočiti iskanje in odpravljanje napak prek vrat USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Način preizkusnega ogrodja je omogočen"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Če želite onemogočiti način preizkusnega ogrodja, ponastavite napravo na tovarniške nastavitve."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Serijska konzola je omogočena"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Učinkovitost delovanja je slabša. Uporabo konzole lahko onemogočite v zagonskem nalagalniku."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"V vratih USB je tekočina ali umazanija"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Vrata USB so samodejno onemogočena. Dotaknite se, če želite izvedeti več."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Vrata USB so varna za uporabo"</string>
@@ -1539,7 +1547,7 @@
     </plurals>
     <string name="action_mode_done" msgid="7217581640461922289">"Končano"</string>
     <string name="progress_erasing" msgid="2569962663843586562">"Brisanje skupne shrambe …"</string>
-    <string name="share" msgid="1778686618230011964">"Deli z dr."</string>
+    <string name="share" msgid="1778686618230011964">"Deli"</string>
     <string name="find" msgid="4808270900322985960">"Najdi"</string>
     <string name="websearch" msgid="4337157977400211589">"Spletno iskanje"</string>
     <string name="find_next" msgid="5742124618942193978">"Najdi naslednje"</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Nekategorizirano"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Vi določite raven pomembnosti teh obvestil."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Pomembno zaradi udeleženih ljudi."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Dovolite, da aplikacija <xliff:g id="APP">%1$s</xliff:g> ustvari novega uporabnika za račun <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Dovolite aplikaciji <xliff:g id="APP">%1$s</xliff:g>, da ustvari novega uporabnika za račun <xliff:g id="ACCOUNT">%2$s</xliff:g> (uporabnik s tem računom že obstaja)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Ali aplikaciji <xliff:g id="APP">%1$s</xliff:g> dovolite, da ustvari novega uporabnika za račun <xliff:g id="ACCOUNT">%2$s</xliff:g> (uporabnik s tem računom že obstaja)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Ali aplikaciji <xliff:g id="APP">%1$s</xliff:g> dovolite, da ustvari novega uporabnika za račun <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Dodajanje jezika"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Nastavitev območja"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Vnesite ime jezika"</string>
diff --git a/core/res/res/values-sq/strings.xml b/core/res/res/values-sq/strings.xml
index 2b1dd68..95359cc 100644
--- a/core/res/res/values-sq/strings.xml
+++ b/core/res/res/values-sq/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Lejon aplikacionin të marrë dhe përpunojë mesazhe SMS. Kjo do të thotë se aplikacioni mund të monitorojë ose fshijë mesazhe të dërguara në pajisjen tënde, pa t\'i treguar ato."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"prano mesazhe në tekst (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Lejon aplikacionin të marrë dhe përpunojë mesazhe MMS. Kjo do të thotë se aplikacioni mund të monitorojë ose fshijë mesazhe të dërguara në pajisjen tënde, pa t\'i treguar ato."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"lexo mesazhet e transmetimit të qelizës"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Lejon aplikacionin të lexojë mesazhet e transmetimit të qelizës, të marra nga pajisja jote. Alarmet e transmetimit të qelizës dërgohen në disa vendndodhje për të të paralajmëruar në situata urgjente. Aplikacionet keqdashëse mund të ndërhyjnë në veprimtarinë ose operacionin e pajisjes tënde kur merret një transmetim urgjent i qelizës."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"lexo informacione të abonuara"</string>
@@ -549,7 +553,7 @@
     <string name="fingerprint_error_lockout_permanent" msgid="5033251797919508137">"Shumë përpjekje. Sensori i gjurmës së gishtit u çaktivizua."</string>
     <string name="fingerprint_error_unable_to_process" msgid="6107816084103552441">"Provo përsëri."</string>
     <string name="fingerprint_error_no_fingerprints" msgid="7654382120628334248">"Nuk ka asnjë gjurmë gishti të regjistruar."</string>
-    <string name="fingerprint_error_hw_not_present" msgid="409523969613176352">"Kjo pajisje nuk ka një sensor të gjurmës së gishtit."</string>
+    <string name="fingerprint_error_hw_not_present" msgid="409523969613176352">"Kjo pajisje nuk ka sensor të gjurmës së gishtit."</string>
     <string name="fingerprint_name_template" msgid="5870957565512716938">"Gishti <xliff:g id="FINGERID">%d</xliff:g>"</string>
   <string-array name="fingerprint_error_vendor">
   </string-array>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Lejon aplikacionin të lexojë dhe shkruajë konfigurimin e \"Mos shqetëso\"."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"nis përdorimin e lejes për shikimin"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Lejon që mbajtësi të nisë përdorimin e lejeve për një aplikacion. Nuk duhet të nevojitet asnjëherë për aplikacionet normale."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"objektivi i shkurtores së qasshmërisë"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Lejon që një aplikacion të përcaktojë objektivin e shkurtores së qasshmërisë."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Cakto rregullat e fjalëkalimit"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontrollo gjatësinë dhe karakteret e lejuara në fjalëkalimet dhe kodet PIN të kyçjes së ekranit."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Monitoro tentativat e shkyçjes së ekranit"</string>
@@ -1357,11 +1363,13 @@
     <string name="usb_power_notification_message" msgid="4647527153291917218">"Pajisja e lidhur po karikohet. Trokit për opsione të tjera."</string>
     <string name="usb_unsupported_audio_accessory_title" msgid="3529881374464628084">"U zbulua aksesor i audios analoge"</string>
     <string name="usb_unsupported_audio_accessory_message" msgid="6309553946441565215">"Pajisja e bashkuar nuk është e pajtueshme me këtë telefon. Trokit për të mësuar më shumë."</string>
-    <string name="adb_active_notification_title" msgid="6729044778949189918">"Korrigjuesi i USB-së i lidhur"</string>
+    <string name="adb_active_notification_title" msgid="6729044778949189918">"Korrigjuesi i USB-së është i lidhur"</string>
     <string name="adb_active_notification_message" msgid="7463062450474107752">"Trokit për të çaktivizuar korrigjimin e USB-së"</string>
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Përzgjidhe për të çaktivizuar korrigjimin e gabimeve të USB-së"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Modaliteti i lidhjes së testimit është aktivizuar"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Kryej një rivendosje në cilësimet e fabrikës për të çaktivizuar \"Modalitetin e lidhjes së testimit\"."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Paneli komandues i serisë është aktivizuar"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Ndikohet cilësia e funksionimit. Për ta çaktivizuar, kontrollo ngarkuesin e sistemit."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Lëngje ose papastërti në portën e USB-së"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Porta e USB-së është çaktivizuar automatikisht. Trokit për të mësuar më shumë."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Në rregulloj për përdorimin e portës USB"</string>
@@ -1580,8 +1588,8 @@
     <string name="expires_on" msgid="3676242949915959821">"Skadon më:"</string>
     <string name="serial_number" msgid="758814067660862493">"Numri serik:"</string>
     <string name="fingerprints" msgid="4516019619850763049">"Shenjat e gishtave:"</string>
-    <string name="sha256_fingerprint" msgid="4391271286477279263">"Shenja e gishtit SHA-256:"</string>
-    <string name="sha1_fingerprint" msgid="7930330235269404581">"Shenja e gishtit SHA-1:"</string>
+    <string name="sha256_fingerprint" msgid="4391271286477279263">"Gjurma e gishtit SHA-256:"</string>
+    <string name="sha1_fingerprint" msgid="7930330235269404581">"Gjurma e gishtit SHA-1:"</string>
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Shikoji të gjitha"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Zgjidh aktivitetin"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Shpërnda publikisht me"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"E pakategorizuara"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ke caktuar rëndësinë e këtyre njoftimeve."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Është i rëndësishëm për shkak të personave të përfshirë."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Të lejohet <xliff:g id="APP">%1$s</xliff:g> që të krijojë një përdorues të ri me <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Të lejohet <xliff:g id="APP">%1$s</xliff:g> që të krijojë një përdorues të ri me <xliff:g id="ACCOUNT">%2$s</xliff:g> (një përdorues me këtë llogari ekziston tashmë) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Të lejohet <xliff:g id="APP">%1$s</xliff:g> që të krijojë një përdorues të ri me <xliff:g id="ACCOUNT">%2$s</xliff:g> (një përdorues me këtë llogari ekziston tashmë) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Të lejohet <xliff:g id="APP">%1$s</xliff:g> që të krijojë një përdorues të ri me <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Shto një gjuhë"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Preferenca e rajonit"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Shkruaj emrin e gjuhës"</string>
diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml
index 6404abc..39ad5f4 100644
--- a/core/res/res/values-sr/strings.xml
+++ b/core/res/res/values-sr/strings.xml
@@ -27,7 +27,7 @@
     <string name="terabyteShort" msgid="231613018159186962">"TB"</string>
     <string name="petabyteShort" msgid="5637816680144990219">"PB"</string>
     <string name="fileSizeSuffix" msgid="8897567456150907538">"<xliff:g id="NUMBER">%1$s</xliff:g> <xliff:g id="UNIT">%2$s</xliff:g>"</string>
-    <string name="untitled" msgid="4638956954852782576">"&lt;Без наслова&gt;"</string>
+    <string name="untitled" msgid="4638956954852782576">"&lt;Без имена&gt;"</string>
     <string name="emptyPhoneNumber" msgid="7694063042079676517">"(Нема броја телефона)"</string>
     <string name="unknownName" msgid="6867811765370350269">"Непознато"</string>
     <string name="defaultVoiceMailAlphaTag" msgid="2660020990097733077">"Гласовна пошта"</string>
@@ -347,6 +347,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Дозвољава апликацији да прима и обрађује SMS поруке. То значи да апликација може да надгледа или брише поруке које се шаљу уређају, а да вам их не прикаже."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"пријем текстуалних порука (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Дозвољава апликацији да прима и обрађује MMS поруке. То значи да апликација може да надгледа или брише поруке које се шаљу уређају, а да вам их не прикаже."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"читање порука инфо сервиса"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Омогућава апликацији да чита поруке инфо сервиса које уређај прима. Упозорења инфо сервиса се на неким локацијама примају као упозорења на хитне случајеве. Злонамерне апликације могу да утичу на учинак или ометају функционисање уређаја када се прими порука инфо сервиса о хитном случају."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"читање пријављених фидова"</string>
@@ -658,6 +662,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Дозвољава апликацији да чита и уписује конфигурацију подешавања Не узнемиравај."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"почетак коришћења дозволе за преглед"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Дозвољава власнику да започне коришћење дозволе за апликацију. Никада не би требало да буде потребна за уобичајене апликације."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"циљ пречице за приступачност"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Дозвољава апликацији да дефинише циљ пречице за приступачност."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Подешавање правила за лозинку"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Контролише дужину и знакове дозвољене у лозинкама и PIN-овима за закључавање екрана."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Надгледајте покушаје откључавања екрана"</string>
@@ -1383,6 +1389,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Изаберите да бисте онемогућили отклањања грешака са USB-а."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Омогућен је режим пробног коришћења"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Обавите ресетовање на фабричка подешавања да бисте онемогућили режим пробног коришћења."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Серијска конзола је омогућена"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Учинак је смањен. Да бисте онемогући конзолу, проверите покретачки програм."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Течност или нечистоћа у USB порту"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB порт је аутоматски искључен. Додирните да бисте сазнали више."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Коришћење USB порта је дозвољено"</string>
@@ -1924,8 +1932,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Некатегоризовано"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ви подешавате важност ових обавештења."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Ово је важно због људи који учествују."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Желите ли да дозволите апликацији <xliff:g id="APP">%1$s</xliff:g> да направи новог корисника за <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Желите ли да дозволите апликацији <xliff:g id="APP">%1$s</xliff:g> да направи новог корисника за <xliff:g id="ACCOUNT">%2$s</xliff:g> (корисник са овим налогом већ постоји)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Желите ли да дозволите да <xliff:g id="APP">%1$s</xliff:g> направи новог корисника са налогом <xliff:g id="ACCOUNT">%2$s</xliff:g> (корисник са тим налогом већ постоји)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Желите ли да дозволите да <xliff:g id="APP">%1$s</xliff:g> направи новог корисника са налогом <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Додајте језик"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Подешавање региона"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Унесите назив језика"</string>
diff --git a/core/res/res/values-sv/strings.xml b/core/res/res/values-sv/strings.xml
index cf4f786..061d7b7 100644
--- a/core/res/res/values-sv/strings.xml
+++ b/core/res/res/values-sv/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Tillåter att appen tar emot och hanterar SMS. Detta innebär att appen kan övervaka eller ta bort meddelanden som skickats till enheten utan att visa dem för dig."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"ta emot textmeddelanden (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Tillåter att appen tar emot och hanterar MMS-meddelanden. Detta innebär att appen kan övervaka eller ta bort meddelanden som skickats till enheten utan att visa dem för dig."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"läsa SMS-meddelanden"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Appen tillåts läsa SMS som skickas till din enhet. På vissa platser skickas SMS för att varna för nödsituationer. Skadliga appar kan påverka enhetens prestanda eller funktionalitet när du får ett meddelande om en nödsituation via SMS."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"läsa flöden som du prenumererar på"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Ger appen läs- och skrivbehörighet till konfigurationen för Stör ej."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"börja visa behörighetsanvändningen"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Gör att innehavaren kan öppna behörighetsanvändning för en app. Ska inte behövas för vanliga appar."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"mål för Aktivera tillgänglighet snabbt"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Tillåter att en app kan definiera målet för Aktivera tillgänglighet snabbt."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Ange lösenordsregler"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Styr tillåten längd och tillåtna tecken i lösenord och pinkoder för skärmlåset."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Övervaka försök att låsa upp skärmen"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Välj för att inaktivera USB-felsökning."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Läget för testverktyg har aktiverats"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Inaktivera testverktygsläget genom att göra en återställning till standardinställningarna."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Seriekonsolen är aktiverad"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Prestandan påverkas. Inaktivera via starthanteraren."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Vätska eller smuts i USB-porten"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-porten har inaktiverats automatiskt. Tryck för att läsa mer."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Nu kan du använda USB-porten"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Okategoriserad"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Du anger hur viktiga aviseringarna är."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Detta är viktigt på grund av personerna som deltar."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Tillåter du att <xliff:g id="APP">%1$s</xliff:g> skapar en ny användare för <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Tillåter du att <xliff:g id="APP">%1$s</xliff:g> skapar en ny användare för <xliff:g id="ACCOUNT">%2$s</xliff:g> (det finns redan en användare med det här kontot)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Tillåter du att <xliff:g id="APP">%1$s</xliff:g> skapar en ny användare för <xliff:g id="ACCOUNT">%2$s</xliff:g> (det finns redan en användare med det här kontot)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Tillåter du att <xliff:g id="APP">%1$s</xliff:g> skapar en ny användare för <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Lägg till ett språk"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Regionsinställningar"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Ange språket"</string>
diff --git a/core/res/res/values-sw/strings.xml b/core/res/res/values-sw/strings.xml
index 80fc4f8..16df4e3 100644
--- a/core/res/res/values-sw/strings.xml
+++ b/core/res/res/values-sw/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Inaruhusu programu kupokea na kuchakata ujumbe wa SMS. Hii inamaanisha programu hii inaweza kuchunguza na kufuta ujumbe uliotumwa katika kifaa chako bila ya kukuonyesha."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"pokea ujumbe wa maandishi wa MMS"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Inaruhusu programu kupokea na kuchakata ujumbe medianwai (MMS). Hii inamaanisha uwezo wa kuchunguza na kufuta ujumbe uliotumwa kwa kifaa chako bila ya kukuonyesha."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"soma mawasiliano ya matangazo ya simu"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Huruhusu programu kusoma mawasiliano ya matangazo ya simu yaliyoingia kwenye kifaa chako. Arifa za matangazo ya simu huwasilishwa katika maeneo mengine ili kukuonya juu ya hali za dharura. Huenda programu hasidi zikatatiza utendajikazi au shughuli ya kifaa chako wakati matangazo ya simu ya dharura yameingia."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"kusoma mipasho kutoka vyanzo unavyofuatilia"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Inaruhusu programu kusoma na kuandika usanidi wa kipengee cha Usinisumbue."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"anzisha kipengele cha kuona matumizi ya ruhusa"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Huruhusu kishikiliaji kuanzisha matumizi ya ruhusa ya programu. Haipaswi kuhitajika kwa ajili ya programu za kawaida."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"kulenga njia ya mkato ya ufikivu"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Huruhusu programu kubainisha ulengaji wa njia ya mkato ya ufikivu."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Kuweka kanuni za nenosiri"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Dhibiti urefu na maandishi yanayokubalika katika nenosiri la kufunga skrini na PIN."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Kuhesabu mara ambazo skrini inajaribu kufunguliwa"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Chagua ili kulemaza utatuaji USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Hali ya Muunganisho wa Majaribio imewashwa"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Rejesha mipangilio iliyotoka nayo kiwandani ili uzime hali ya Muunganisho wa Majaribio."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Muunganisho kupitia mlango umewashwa"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Utendaji unaathirika. lli uzime, teua programu ya kuwasha mfumo wa uendeshaji."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Unyevu au uchafu katika mlango wa USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Mlango wa USB umezimwa kiotomatiki. Gusa ili upate maelezo zaidi."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Ni sawa kutumia mlango wa USB"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Ambazo aina haijabainishwa"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Uliweka mipangilio ya umuhimu wa arifa hizi."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Hii ni muhimu kwa sababu ya watu waliohusika."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Ungependa kuruhusu <xliff:g id="APP">%1$s</xliff:g> iunde Mtumiaji mpya ikitumia <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Ungependa kuruhusu <xliff:g id="APP">%1$s</xliff:g> iunde Mtumiaji mpya ikitumia <xliff:g id="ACCOUNT">%2$s</xliff:g> (Je, akaunti hii tayari ina Mtumiaji)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Ruhusu <xliff:g id="APP">%1$s</xliff:g> iweke Mtumiaji mpya ikitumia <xliff:g id="ACCOUNT">%2$s</xliff:g> (Je, tayari kuna mtumiaji anayetumia akaunti hii)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Ungependa kuruhusu <xliff:g id="APP">%1$s</xliff:g> iweke Mtumiaji mpya ikitumia <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Ongeza lugha"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Mapendeleo ya eneo"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Weka jina la lugha"</string>
diff --git a/core/res/res/values-ta/strings.xml b/core/res/res/values-ta/strings.xml
index 7028672..3b80a43 100644
--- a/core/res/res/values-ta/strings.xml
+++ b/core/res/res/values-ta/strings.xml
@@ -220,7 +220,7 @@
     <string name="reboot_safemode_title" msgid="7054509914500140361">"பாதுகாப்பான பயன்முறைக்கு மீண்டும் தொடங்கவும்"</string>
     <string name="reboot_safemode_confirm" msgid="55293944502784668">"பாதுகாப்பான பயன்முறைக்குச் செல்ல மீண்டும் துவக்க விரும்புகிறீர்களா? நீங்கள் நிறுவிய எல்லா மூன்றாம் தரப்பு பயன்பாடுகளையும் இது முடக்கும். நீங்கள் மீண்டும் மறுதொடக்கம் செய்யும்போது அவை மீட்டமைக்கப்படும்."</string>
     <string name="recent_tasks_title" msgid="3691764623638127888">"சமீபத்தியவை"</string>
-    <string name="no_recent_tasks" msgid="8794906658732193473">"சமீபத்திய பயன்பாடுகள் எதுவுமில்லை."</string>
+    <string name="no_recent_tasks" msgid="8794906658732193473">"சமீபத்திய ஆப்ஸ் எதுவுமில்லை."</string>
     <string name="global_actions" product="tablet" msgid="408477140088053665">"டேப்லெட் விருப்பங்கள்"</string>
     <string name="global_actions" product="tv" msgid="9091480417912345975">"Android TV விருப்பத்தேர்வுகள்"</string>
     <string name="global_actions" product="default" msgid="2406416831541615258">"தொலைபேசி விருப்பங்கள்"</string>
@@ -271,7 +271,7 @@
     <string name="notification_channel_heavy_weight_app" msgid="6218742927792852607">"ஆப்ஸ் இயங்குகிறது"</string>
     <string name="notification_channel_foreground_service" msgid="3931987440602669158">"பேட்டரியைப் பயன்படுத்தும் ஆப்ஸ்"</string>
     <string name="foreground_service_app_in_background" msgid="1060198778219731292">"<xliff:g id="APP_NAME">%1$s</xliff:g> ஆப்ஸ் பேட்டரியைப் பயன்படுத்துகிறது"</string>
-    <string name="foreground_service_apps_in_background" msgid="7175032677643332242">"<xliff:g id="NUMBER">%1$d</xliff:g> பயன்பாடுகள் பேட்டரியைப் பயன்படுத்துகின்றன"</string>
+    <string name="foreground_service_apps_in_background" msgid="7175032677643332242">"<xliff:g id="NUMBER">%1$d</xliff:g> ஆப்ஸ் பேட்டரியைப் பயன்படுத்துகின்றன"</string>
     <string name="foreground_service_tap_for_details" msgid="372046743534354644">"பேட்டரி மற்றும் டேட்டா உபயோக விவரங்களைக் காண, தட்டவும்"</string>
     <string name="foreground_service_multiple_separator" msgid="4021901567939866542">"<xliff:g id="LEFT_SIDE">%1$s</xliff:g>, <xliff:g id="RIGHT_SIDE">%2$s</xliff:g>"</string>
     <string name="safeMode" msgid="2788228061547930246">"பாதுகாப்பு பயன்முறை"</string>
@@ -341,33 +341,37 @@
     <string name="permlab_answerPhoneCalls" msgid="4077162841226223337">"ஃபோன் அழைப்புகளுக்குப் பதிலளி"</string>
     <string name="permdesc_answerPhoneCalls" msgid="2901889867993572266">"உள்வரும் ஃபோன் அழைப்பிற்குப் பதிலளிக்க, ஆப்ஸை அனுமதிக்கும்."</string>
     <string name="permlab_receiveSms" msgid="8673471768947895082">"உரைச் செய்திகளை (SMS) பெறுதல்"</string>
-    <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS செய்திகளைப் பெற, செயற்படுத்தப் ஆப்ஸை அனுமதிக்கிறது. இதற்கு அர்த்தம் உங்கள் சாதனத்திற்கு அனுப்பப்படும் செய்திகளை உங்களுக்குக் காட்டாமல் கண்காணிப்பதற்கு அல்லது நீக்குவதற்குப் பயன்பாட்டால் முடியும் என்பதாகும்."</string>
+    <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS செய்திகளைப் பெற, செயற்படுத்தப் ஆப்ஸை அனுமதிக்கிறது. இதற்கு அர்த்தம் உங்கள் சாதனத்திற்கு அனுப்பப்படும் செய்திகளை உங்களுக்குக் காட்டாமல் கண்காணிப்பதற்கு அல்லது நீக்குவதற்கு ஆப்ஸால் முடியும் என்பதாகும்."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"உரைச் செய்திகளை (MMS) பெறுதல்"</string>
-    <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS செய்திகளைப் பெற, செயற்படுத்தப் ஆப்ஸை அனுமதிக்கிறது. இதற்கு அர்த்தம் உங்கள் சாதனத்திற்கு அனுப்பப்படும் செய்திகளை உங்களுக்குக் காட்டாமல் கண்காணிக்கவோ, நீக்கவோ பயன்பாட்டால் முடியும் என்பதாகும்."</string>
+    <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS செய்திகளைப் பெற, செயற்படுத்தப் ஆப்ஸை அனுமதிக்கிறது. இதற்கு அர்த்தம் உங்கள் சாதனத்திற்கு அனுப்பப்படும் செய்திகளை உங்களுக்குக் காட்டாமல் கண்காணிக்கவோ, நீக்கவோ ஆப்ஸால் முடியும் என்பதாகும்."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"செல் அலைபரப்புச் செய்திகளைப் படித்தல்"</string>
-    <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"உங்கள் சாதனத்தில் பெறப்படும் செல் அலைபரப்புச் செய்திகளைப் படிப்பதற்குப் ஆப்ஸை அனுமதிக்கிறது. அவசரநிலை சூழ்நிலைகளை உங்களுக்கு எச்சரிக்கைச் செய்வதற்கு சில இடங்களில் செல் அலைபரப்பு விழிப்பூட்டல்கள் வழங்கப்படும். அவசரநிலை மொபைல் அலைபரப்புப் பெறப்படும்போது உங்கள் சாதனத்தின் செயல்திறன் அல்லது செயல்பாட்டுடன் தீங்கிழைக்கும் பயன்பாடுகள் அதைத் தடுக்கலாம்."</string>
+    <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"உங்கள் சாதனத்தில் பெறப்படும் செல் அலைபரப்புச் செய்திகளைப் படிப்பதற்குப் ஆப்ஸை அனுமதிக்கிறது. அவசரநிலை சூழ்நிலைகளை உங்களுக்கு எச்சரிக்கைச் செய்வதற்கு சில இடங்களில் செல் அலைபரப்பு விழிப்பூட்டல்கள் வழங்கப்படும். அவசரநிலை மொபைல் அலைபரப்புப் பெறப்படும்போது உங்கள் சாதனத்தின் செயல்திறன் அல்லது செயல்பாட்டுடன் தீங்கிழைக்கும் ஆப்ஸ் அதைத் தடுக்கலாம்."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"குழுசேர்ந்த ஊட்டங்களைப் படித்தல்"</string>
     <string name="permdesc_subscribedFeedsRead" msgid="5557058907906144505">"தற்போது ஒத்திசைந்த ஊட்டங்களைப் பற்றிய விவரங்களைப் பெற ஆப்ஸை அனுமதிக்கிறது."</string>
     <string name="permlab_sendSms" msgid="7544599214260982981">"SMS செய்திகளை அனுப்புதல் மற்றும் பார்த்தல்"</string>
-    <string name="permdesc_sendSms" msgid="7094729298204937667">"SMS செய்திகளை அனுப்ப ஆப்ஸை அனுமதிக்கிறது. இதற்கு எதிர்பாராத பேமெண்ட்கள் விதிக்கப்படலாம். தீங்கு விளைவிக்கும் பயன்பாடுகள் உங்களின் உறுதிப்படுத்தல் எதுவுமின்றி செய்திகளை அனுப்பி உங்களுக்குக் கட்டணம் விதிக்கலாம்."</string>
+    <string name="permdesc_sendSms" msgid="7094729298204937667">"SMS செய்திகளை அனுப்ப ஆப்ஸை அனுமதிக்கிறது. இதற்கு எதிர்பாராத பேமெண்ட்கள் விதிக்கப்படலாம். தீங்கு விளைவிக்கும் ஆப்ஸ் உங்களின் உறுதிப்படுத்தல் எதுவுமின்றி செய்திகளை அனுப்பி உங்களுக்குக் கட்டணம் விதிக்கலாம்."</string>
     <string name="permlab_readSms" msgid="8745086572213270480">"உங்கள் உரைச் செய்திகளை (SMS அல்லது MMS) படித்தல்"</string>
     <string name="permdesc_readSms" product="tablet" msgid="4741697454888074891">"இந்த ஆப்ஸ் உங்கள் டேப்லெட்டில் சேமிக்கப்பட்டுள்ள எல்லா SMS (உரை) செய்திகளையும் படிக்கலாம்."</string>
     <string name="permdesc_readSms" product="tv" msgid="9106832390302749856">"உங்கள் Android TVயில் சேமித்துள்ள அனைத்து மெசேஜ்களையும் இந்த ஆப்ஸால் தெரிந்துகொள்ள முடியும்."</string>
     <string name="permdesc_readSms" product="default" msgid="6826832415656437652">"இந்த ஆப்ஸ் உங்கள் மொபைலில் சேமிக்கப்பட்டுள்ள எல்லா SMS (உரை) செய்திகளையும் படிக்கலாம்."</string>
     <string name="permlab_receiveWapPush" msgid="5991398711936590410">"உரைச் செய்திகளைப் (WAP) பெறுதல்"</string>
     <string name="permdesc_receiveWapPush" msgid="748232190220583385">"WAP செய்திகளைப் பெற, செயற்படுத்தப் ஆப்ஸை அனுமதிக்கிறது. உங்களுக்கு அனுப்பப்படும் செய்திகளை உங்களுக்குக் காட்டாமல் கண்காணிக்க அல்லது நீக்குவதற்கான திறன் இந்த அனுமதியில் உள்ளடங்கும்."</string>
-    <string name="permlab_getTasks" msgid="6466095396623933906">"இயங்கும் பயன்பாடுகளை மீட்டெடுத்தல்"</string>
-    <string name="permdesc_getTasks" msgid="7454215995847658102">"நடப்பில் மற்றும் சமீபத்தில் இயங்கும் காரியங்களின் தகவலைப் பெற ஆப்ஸை அனுமதிக்கிறது. சாதனத்தில் எந்தப் பயன்பாடுகள் பயன்படுத்தப்படுகின்றன என்பது குறித்த தகவலைக் கண்டறிய ஆப்ஸை இது அனுமதிக்கலாம்."</string>
+    <string name="permlab_getTasks" msgid="6466095396623933906">"இயங்கும் ஆப்ஸை மீட்டெடுத்தல்"</string>
+    <string name="permdesc_getTasks" msgid="7454215995847658102">"நடப்பில் மற்றும் சமீபத்தில் இயங்கும் காரியங்களின் தகவலைப் பெற ஆப்ஸை அனுமதிக்கிறது. சாதனத்தில் எந்த ஆப்ஸ் பயன்படுத்தப்படுகின்றன என்பது குறித்த தகவலைக் கண்டறிய ஆப்ஸை இது அனுமதிக்கலாம்."</string>
     <string name="permlab_manageProfileAndDeviceOwners" msgid="7918181259098220004">"சுயவிவரத்தையும் சாதன உரிமையாளர்களையும் நிர்வகித்தல்"</string>
-    <string name="permdesc_manageProfileAndDeviceOwners" msgid="106894851498657169">"சுயவிவர உரிமையாளர்களையும் சாதன உரிமையாளரையும் அமைக்க, பயன்பாடுகளை அனுமதிக்கிறது."</string>
-    <string name="permlab_reorderTasks" msgid="2018575526934422779">"இயங்கும் பயன்பாடுகளை மறுவரிசைப்படுத்தல்"</string>
+    <string name="permdesc_manageProfileAndDeviceOwners" msgid="106894851498657169">"சுயவிவர உரிமையாளர்களையும் சாதன உரிமையாளரையும் அமைக்க, ஆப்ஸை அனுமதிக்கிறது."</string>
+    <string name="permlab_reorderTasks" msgid="2018575526934422779">"இயங்கும் ஆப்ஸை மறுவரிசைப்படுத்தல்"</string>
     <string name="permdesc_reorderTasks" msgid="7734217754877439351">"பின்புலத்திலும், முன்புலத்திலும் காரியங்களை நகர்த்த ஆப்ஸை அனுமதிக்கிறது. உங்கள் உள்ளீடு இல்லாமலே ஆப்ஸ் இதைச் செய்யலாம்."</string>
     <string name="permlab_enableCarMode" msgid="5684504058192921098">"கார் பயன்முறையை இயக்குதல்"</string>
     <string name="permdesc_enableCarMode" msgid="4853187425751419467">"கார் முறையை இயக்க, ஆப்ஸை அனுமதிக்கிறது."</string>
-    <string name="permlab_killBackgroundProcesses" msgid="3914026687420177202">"பிற பயன்பாடுகளை மூடுதல்"</string>
-    <string name="permdesc_killBackgroundProcesses" msgid="4593353235959733119">"பிற ஆப்ஸின் பின்புலச் செயல்முறைகளை நிறுத்த ஆப்ஸை அனுமதிக்கிறது. இதனால் பிற பயன்பாடுகள் இயங்குவதை நிறுத்தலாம்."</string>
+    <string name="permlab_killBackgroundProcesses" msgid="3914026687420177202">"பிற ஆப்ஸை மூடுதல்"</string>
+    <string name="permdesc_killBackgroundProcesses" msgid="4593353235959733119">"பிற ஆப்ஸின் பின்புலச் செயல்முறைகளை நிறுத்த ஆப்ஸை அனுமதிக்கிறது. இதனால் பிற ஆப்ஸ் இயங்குவதை நிறுத்தலாம்."</string>
     <string name="permlab_systemAlertWindow" msgid="7238805243128138690">"இந்த ஆப்ஸ் பிற ஆப்ஸின் மேலே தோன்றலாம்"</string>
-    <string name="permdesc_systemAlertWindow" msgid="2393776099672266188">"இந்த ஆப்ஸ் பிற ஆப்ஸின் மேலே அல்லது திரையின் பிற பகுதிகளில் தோன்றலாம். இது வழக்கமான ஆப்ஸ் உபயோகத்தில் குறுக்கிட்டு, பிற பயன்பாடுகள் தோன்றும் விதத்தை மாற்றக்கூடும்."</string>
+    <string name="permdesc_systemAlertWindow" msgid="2393776099672266188">"இந்த ஆப்ஸ் பிற ஆப்ஸின் மேலே அல்லது திரையின் பிற பகுதிகளில் தோன்றலாம். இது வழக்கமான ஆப்ஸ் உபயோகத்தில் குறுக்கிட்டு, பிற ஆப்ஸ் தோன்றும் விதத்தை மாற்றக்கூடும்."</string>
     <string name="permlab_runInBackground" msgid="7365290743781858803">"பின்னணியில் இயக்கு"</string>
     <string name="permdesc_runInBackground" msgid="7370142232209999824">"இந்த ஆப்ஸ், பின்னணியில் இயங்கலாம். இதனால் பேட்டரி விரைவாகத் தீர்ந்துவிடக்கூடும்."</string>
     <string name="permlab_useDataInBackground" msgid="8694951340794341809">"பின்னணியில் தரவைப் பயன்படுத்து"</string>
@@ -381,7 +385,7 @@
     <string name="permlab_getPackageSize" msgid="7472921768357981986">"பயன்பாட்டுச் சேமிப்பு இடத்தை அளவிடல்"</string>
     <string name="permdesc_getPackageSize" msgid="3921068154420738296">"ஆப்ஸ், அதன் குறியீடு, தரவு, மற்றும் தற்காலிகச் சேமிப்பு அளவுகளை மீட்டெடுக்க அனுமதிக்கிறது"</string>
     <string name="permlab_writeSettings" msgid="2226195290955224730">"சாதன அமைப்புகளை மாற்றுதல்"</string>
-    <string name="permdesc_writeSettings" msgid="7775723441558907181">"முறைமையின் அமைப்பு தரவைத் திருத்த, ஆப்ஸை அனுமதிக்கிறது. தீங்குவிளைவிக்கும் பயன்பாடுகள், முறைமையின் உள்ளமைவைச் சிதைக்கலாம்."</string>
+    <string name="permdesc_writeSettings" msgid="7775723441558907181">"முறைமையின் அமைப்பு தரவைத் திருத்த, ஆப்ஸை அனுமதிக்கிறது. தீங்குவிளைவிக்கும் ஆப்ஸ், முறைமையின் உள்ளமைவைச் சிதைக்கலாம்."</string>
     <string name="permlab_receiveBootCompleted" msgid="5312965565987800025">"தொடக்கத்தில் இயக்குதல்"</string>
     <string name="permdesc_receiveBootCompleted" product="tablet" msgid="7390304664116880704">"மறுஇயக்கம் முடிந்தது, விரைவில் தானாகவே தொடங்க, ஆப்ஸை அனுமதிக்கிறது. இதனால் டேப்லெட் நீண்ட நேரம் கழித்து தொடங்கும் மற்றும் எப்போதும் இயங்குகின்ற டேப்லெட்டின் ஒட்டுமொத்தச் செயல்பாட்டையும் தாமதமாகும்."</string>
     <string name="permdesc_receiveBootCompleted" product="tv" msgid="6725487837446317527">"சாதனம் தொடங்கியவுடன் ஆப்ஸைத் தானாகவே தொடங்க அனுமதிக்கும். இது Android TV தொடங்குவதற்கான நேரத்தைத் தாமதமாக்குவதோடு எப்போதும் இயங்கிக்கொண்டிருப்பதன் மூலம் ஒட்டுமொத்த சாதனத்தின் வேகத்தைக் குறைக்கும்."</string>
@@ -391,21 +395,21 @@
     <string name="permdesc_broadcastSticky" product="tv" msgid="5029460344724532288">"வலைபரப்பு முடிந்த பின்னரும் தங்கிவிடும் ஸ்டிக்கி வலைபரப்புகளை அனுப்ப ஆப்ஸை அனுமதிக்கும். அளவுக்கதிகமான உபயோகம் Android TVயின் வேகத்தைக் குறைக்கவோ நிலையற்றதாகவோ ஆக்கக்கூடும். இதனால் அதிகமான நினைவகம் பயன்படுத்தப்படும்."</string>
     <string name="permdesc_broadcastSticky" product="default" msgid="2825803764232445091">"அலைபரப்பு முடிந்த பின்னும் இருக்கும், தொடர்ந்து அணுகத்தக்க அலைபரப்பை அனுப்பப் ஆப்ஸை அனுமதிக்கிறது. அதிகமாகப் பயன்படுத்தினால், மொபைலானது நினைவகத்தை மிக அதிகமாகப் பயன்படுத்துவதால் வேகம் குறைந்ததாகவும், நிலையற்றதாகவும் ஆகலாம்."</string>
     <string name="permlab_readContacts" msgid="8348481131899886131">"உங்கள் தொடர்புகளைப் படித்தல்"</string>
-    <string name="permdesc_readContacts" product="tablet" msgid="5294866856941149639">"குறிப்பிட்டவர்களுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்டதின் எண்ணிக்கை உட்பட, உங்கள் டேப்லெட்டில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைப் படிக்க ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதி, உங்கள் தொடர்பு தரவைச் சேமிக்க பயன்பாடுகளை அனுமதிக்கிறது, மேலும் தீங்கிழைக்கும் பயன்பாடுகள் உங்களுக்குத் தெரியாமல் தொடர்பு தரவைப் பகிரலாம்."</string>
+    <string name="permdesc_readContacts" product="tablet" msgid="5294866856941149639">"குறிப்பிட்டவர்களுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்டதின் எண்ணிக்கை உட்பட, உங்கள் டேப்லெட்டில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைப் படிக்க ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதி, உங்கள் தொடர்பு தரவைச் சேமிக்க ஆப்ஸை அனுமதிக்கிறது, மேலும் தீங்கிழைக்கும் ஆப்ஸ் உங்களுக்குத் தெரியாமல் தொடர்பு தரவைப் பகிரலாம்."</string>
     <string name="permdesc_readContacts" product="tv" msgid="3890061004911027912">"உங்கள் Android TVயில் சேமித்துள்ள தொடர்புகள் பற்றிய தரவைத் தெரிந்துகொள்ள ஆப்ஸை அனுமதிக்கும். குறிப்பிட்ட தனிநபரை எத்தனை முறை அழைத்தீர்கள், பிறவழிகளில் தொடர்புகொண்டீர்கள் அல்லது அவருக்கு எத்தனை முறை மின்னஞ்சல் அனுப்பினீர்கள் என்பதும் இதில் அடங்கும். இது உங்கள் தொடர்புத் தரவைச் சேமிக்க ஆப்ஸை அனுமதிக்கும், அத்துடன் தீங்குவிளைவிக்கும் ஆப்ஸ் உங்களுக்குத் தெரியாமல் தொடர்புத் தரவைப் பகிரக்கூடும்."</string>
-    <string name="permdesc_readContacts" product="default" msgid="8440654152457300662">"குறிப்பிட்டவர்களுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்ட எண்ணிக்கை உட்பட, உங்கள் மொபைலில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைப் படிக்க ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதி, உங்கள் தொடர்பு தரவைச் சேமிக்க பயன்பாடுகளை அனுமதிக்கிறது, மேலும் தீங்கிழைக்கும் பயன்பாடுகள் உங்களுக்குத் தெரியாமல் தொடர்பு தரவைப் பகிரலாம்."</string>
+    <string name="permdesc_readContacts" product="default" msgid="8440654152457300662">"குறிப்பிட்டவர்களுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்ட எண்ணிக்கை உட்பட, உங்கள் மொபைலில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைப் படிக்க ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதி, உங்கள் தொடர்பு தரவைச் சேமிக்க ஆப்ஸை அனுமதிக்கிறது, மேலும் தீங்கிழைக்கும் ஆப்ஸ் உங்களுக்குத் தெரியாமல் தொடர்பு தரவைப் பகிரலாம்."</string>
     <string name="permlab_writeContacts" msgid="5107492086416793544">"உங்கள் தொடர்புகளை மாற்றுதல்"</string>
-    <string name="permdesc_writeContacts" product="tablet" msgid="897243932521953602">"குறிப்பிட்ட தொடர்புகளுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்டதின் எண்ணிக்கை உள்பட, உங்கள் டேப்லெட்டில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதியானது தொடர்புத் தரவை நீக்கப் பயன்பாடுகளை அனுமதிக்கிறது."</string>
+    <string name="permdesc_writeContacts" product="tablet" msgid="897243932521953602">"குறிப்பிட்ட தொடர்புகளுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்டதின் எண்ணிக்கை உள்பட, உங்கள் டேப்லெட்டில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதியானது தொடர்புத் தரவை நீக்க ஆப்ஸை அனுமதிக்கிறது."</string>
     <string name="permdesc_writeContacts" product="tv" msgid="307929337692573341">"உங்கள் Android TVயில் சேமித்துள்ள தொடர்புகள் பற்றிய தரவை மாற்ற ஆப்ஸை அனுமதிக்கும். குறிப்பிட்ட தொடர்பை எத்தனை முறை அழைத்தீர்கள், பிறவழிகளில் தொடர்புகொண்டீர்கள் அல்லது அவருக்கு எத்தனை முறை மின்னஞ்சல் அனுப்பினீர்கள் என்பதும் இதில் அடங்கும். தொடர்புத் தரவை நீக்க ஆப்ஸை இது அனுமதிக்கும்."</string>
-    <string name="permdesc_writeContacts" product="default" msgid="589869224625163558">"குறிப்பிட்ட தொடர்புகளுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்டதின் எண்ணிக்கை உள்பட, உங்கள் மொபைலில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதியானது தொடர்புத் தரவை நீக்கப் பயன்பாடுகளை அனுமதிக்கிறது."</string>
+    <string name="permdesc_writeContacts" product="default" msgid="589869224625163558">"குறிப்பிட்ட தொடர்புகளுடன் நீங்கள் அழைத்த, மின்னஞ்சல் அனுப்பிய அல்லது வேறு வழியில் தொடர்புகொண்டதின் எண்ணிக்கை உள்பட, உங்கள் மொபைலில் சேமிக்கப்பட்ட உங்கள் தொடர்புகள் குறித்த தரவைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இந்த அனுமதியானது தொடர்புத் தரவை நீக்க ஆப்ஸை அனுமதிக்கிறது."</string>
     <string name="permlab_readCallLog" msgid="3478133184624102739">"அழைப்புப் பதிவைப் படித்தல்"</string>
     <string name="permdesc_readCallLog" msgid="3204122446463552146">"இந்த ஆப்ஸ் உங்கள் அழைப்பு வரலாற்றைப் படிக்கலாம்."</string>
     <string name="permlab_writeCallLog" msgid="8552045664743499354">"அழைப்புப் பதிவை எழுதுதல்"</string>
-    <string name="permdesc_writeCallLog" product="tablet" msgid="6661806062274119245">"உள்வரும் மற்றும் வெளிச்செல்லும் அழைப்புகள் குறித்த தகவல் உள்பட உங்கள் டேப்லெட்டின் அழைப்புப் பதிவைத் திருத்துவதற்குப் ஆப்ஸை அனுமதிக்கிறது. உங்கள் அழைப்பின் பதிவை அழிக்க அல்லது திருத்த தீங்கு விளைவிக்கும் பயன்பாடுகள் இதைப் பயன்படுத்தலாம்."</string>
+    <string name="permdesc_writeCallLog" product="tablet" msgid="6661806062274119245">"உள்வரும் மற்றும் வெளிச்செல்லும் அழைப்புகள் குறித்த தகவல் உள்பட உங்கள் டேப்லெட்டின் அழைப்புப் பதிவைத் திருத்துவதற்குப் ஆப்ஸை அனுமதிக்கிறது. உங்கள் அழைப்பின் பதிவை அழிக்க அல்லது திருத்த தீங்கு விளைவிக்கும் ஆப்ஸ் இதைப் பயன்படுத்தலாம்."</string>
     <string name="permdesc_writeCallLog" product="tv" msgid="7939219462637746280">"உள்வரும், வெளிச்செல்லும் அழைப்புகள் குறித்த தகவல் உட்பட உங்கள் Android TVயின் அழைப்புப் பதிவைத் திருத்த ஆப்ஸை அனுமதிக்கும். உங்கள் அழைப்புப் பதிவை அழிக்கவோ திருத்தவோ தீங்கு விளைவிக்கும் ஆப்ஸ் இதைப் பயன்படுத்தக்கூடும்."</string>
-    <string name="permdesc_writeCallLog" product="default" msgid="683941736352787842">"உள்வரும் மற்றும் வெளிச்செல்லும் அழைப்புகள் குறித்த தகவல் உள்பட உங்கள் மொபைல் அழைப்புப் பதிவைத் திருத்துவதற்குப் ஆப்ஸை அனுமதிக்கிறது. உங்கள் அழைப்பின் பதிவை அழிக்க அல்லது திருத்த தீங்கு விளைவிக்கும் பயன்பாடுகள் இதைப் பயன்படுத்தலாம்."</string>
+    <string name="permdesc_writeCallLog" product="default" msgid="683941736352787842">"உள்வரும் மற்றும் வெளிச்செல்லும் அழைப்புகள் குறித்த தகவல் உள்பட உங்கள் மொபைல் அழைப்புப் பதிவைத் திருத்துவதற்குப் ஆப்ஸை அனுமதிக்கிறது. உங்கள் அழைப்பின் பதிவை அழிக்க அல்லது திருத்த தீங்கு விளைவிக்கும் ஆப்ஸ் இதைப் பயன்படுத்தலாம்."</string>
     <string name="permlab_bodySensors" msgid="4683341291818520277">"உடல் உணர்விகளை (இதயத் துடிப்பு மானிட்டர்கள் போன்றவை) அணுகுதல்"</string>
-    <string name="permdesc_bodySensors" product="default" msgid="4380015021754180431">"உங்கள் இதயத்துடிப்பு விகிதம் போன்ற உங்கள் உடல்நிலையைக் கண்காணிக்கும் உணர்விகளில் இருந்து தரவை அணுக பயன்பாடுகளை அனுமதிக்கும்."</string>
+    <string name="permdesc_bodySensors" product="default" msgid="4380015021754180431">"உங்கள் இதயத்துடிப்பு விகிதம் போன்ற உங்கள் உடல்நிலையைக் கண்காணிக்கும் உணர்விகளில் இருந்து தரவை அணுக ஆப்ஸை அனுமதிக்கும்."</string>
     <string name="permlab_readCalendar" msgid="6716116972752441641">"கேலெண்டர் நிகழ்வுகளையும் விவரங்களையும் படிக்கலாம்"</string>
     <string name="permdesc_readCalendar" product="tablet" msgid="4993979255403945892">"இந்த ஆப்ஸ் உங்கள் டேப்லெட்டில் சேமிக்கப்பட்டுள்ள கேலெண்டர் நிகழ்வுகள் அனைத்தையும் படிக்கலாம், உங்கள் கேலெண்டர் தரவைப் பகிரலாம் அல்லது சேமிக்கலாம்."</string>
     <string name="permdesc_readCalendar" product="tv" msgid="1066881547471014386">"உங்கள் Android TVயில் சேமித்துள்ள அனைத்துக் கேலெண்டர் நிகழ்வுகளையும் இந்த ஆப்ஸால் தெரிந்துகொள்ள முடியும். அத்துடன் உங்களின் கேலெண்டர் தரவைப் பகிரவும் சேமிக்கவும் முடியும்."</string>
@@ -439,7 +443,7 @@
     <string name="permlab_vibrate" msgid="7696427026057705834">"அதிர்வைக் கட்டுப்படுத்துதல்"</string>
     <string name="permdesc_vibrate" msgid="6284989245902300945">"அதிர்வைக் கட்டுப்படுத்தப் ஆப்ஸை அனுமதிக்கிறது."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"தொலைபேசி எண்களை நேரடியாக அழைத்தல்"</string>
-    <string name="permdesc_callPhone" msgid="3740797576113760827">"உங்கள் தலையீட்டின்றி மொபைல் எண்களை அழைக்கப் ஆப்ஸை அனுமதிக்கிறது. இதன் விளைவாக எதிர்பாராத கட்டணங்களோ அழைப்புகளோ ஏற்படலாம். அவசரகால எண்களை அழைக்க இது ஆப்ஸை அனுமதிக்காது என்பதை நினைவில்கொள்ளவும். தீங்கிழைக்கும் பயன்பாடுகள், உங்கள் உறுதிப்படுத்தல் இன்றி அழைப்புகளைச் செய்வதால் உங்களுக்குச் செலவு ஏற்படக்கூடும்."</string>
+    <string name="permdesc_callPhone" msgid="3740797576113760827">"உங்கள் தலையீட்டின்றி மொபைல் எண்களை அழைக்கப் ஆப்ஸை அனுமதிக்கிறது. இதன் விளைவாக எதிர்பாராத கட்டணங்களோ அழைப்புகளோ ஏற்படலாம். அவசரகால எண்களை அழைக்க இது ஆப்ஸை அனுமதிக்காது என்பதை நினைவில்கொள்ளவும். தீங்கிழைக்கும் ஆப்ஸ், உங்கள் உறுதிப்படுத்தல் இன்றி அழைப்புகளைச் செய்வதால் உங்களுக்குச் செலவு ஏற்படக்கூடும்."</string>
     <string name="permlab_accessImsCallService" msgid="3574943847181793918">"IMS அழைப்புச் சேவையை அணுகுதல்"</string>
     <string name="permdesc_accessImsCallService" msgid="8992884015198298775">"உங்கள் குறுக்கீடின்றி IMS சேவையைப் பயன்படுத்தி அழைப்பதற்கு, ஆப்ஸை அனுமதிக்கும்."</string>
     <string name="permlab_readPhoneState" msgid="9178228524507610486">"மொபைல் நிலை மற்றும் அடையாளத்தைப் படித்தல்"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"தொந்தரவு செய்ய வேண்டாம் உள்ளமைவைப் படிக்கவும் எழுதவும், ஆப்ஸை அனுமதிக்கிறது."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"அனுமதி உபயோகத்தை அணுகுதல்"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"ஆப்ஸிற்கான அனுமதி உபயோகத்தை ஹோல்டருக்கு வழங்கும். இயல்பான ஆப்ஸிற்கு இது எப்போதுமே தேவைப்படாது."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"அணுகலம்ச ஷார்ட்கட் இலக்கு"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"அணுகலம்ச ஷார்ட்கட் இலக்கை விளக்க ஆப்ஸை அனுமதிக்கும்."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"கடவுச்சொல் விதிகளை அமைக்கவும்"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"திரைப் பூட்டின் கடவுச்சொற்கள் மற்றும் பின்களில் அனுமதிக்கப்படும் நீளத்தையும் எழுத்துக்குறிகளையும் கட்டுப்படுத்தும்."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"திரையைத் திறப்பதற்கான முயற்சிகளைக் கண்காணி"</string>
@@ -939,15 +945,15 @@
     <string name="permlab_readHistoryBookmarks" msgid="3775265775405106983">"உங்கள் இணையப் புத்தக்கக்குறிகள் மற்றும் வரலாற்றைப் படித்தல்"</string>
     <string name="permdesc_readHistoryBookmarks" msgid="8462378226600439658">"உலாவி மூலம் பார்வையிட்ட எல்லா URLகளின் வரலாற்றையும், உலாவியில் குறிக்கப்பட்ட எல்லா புத்தகக்குறிகளையும் படிக்கப் ஆப்ஸை அனுமதிக்கிறது. குறிப்பு: மூன்றாம் தரப்பு உலாவிகள் அல்லது இணைய உலாவல் திறன்களுடன் கூடிய பிற பயன்பாடுகளால் இந்த அனுமதி செயற்படுத்தப்படாமல் போகலாம்."</string>
     <string name="permlab_writeHistoryBookmarks" msgid="3714785165273314490">"இணையப் புத்தகக்குறிகளையும், வரலாற்றையும் எழுதுதல்"</string>
-    <string name="permdesc_writeHistoryBookmarks" product="tablet" msgid="6825527469145760922">"உங்கள் டேப்லெட்டில் சேமிக்கப்பட்ட உலாவியின் வரலாறு அல்லது புத்தகக்குறிகளைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இது உலாவியின் தரவை அழிக்கவோ, திருத்தவோ ஆப்ஸை அனுமதிக்கலாம். குறிப்பு: இணைய உலாவல் செயல்திறன்கள் மூலம் மூன்றாம் தரப்பு உலாவிகள் அல்லது பிற பயன்பாடுகள் இந்த அனுமதியைச் செயற்படுத்த முடியாது."</string>
+    <string name="permdesc_writeHistoryBookmarks" product="tablet" msgid="6825527469145760922">"உங்கள் டேப்லெட்டில் சேமிக்கப்பட்ட உலாவியின் வரலாறு அல்லது புத்தகக்குறிகளைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இது உலாவியின் தரவை அழிக்கவோ, திருத்தவோ ஆப்ஸை அனுமதிக்கலாம். குறிப்பு: இணைய உலாவல் செயல்திறன்கள் மூலம் மூன்றாம் தரப்பு உலாவிகள் அல்லது பிற ஆப்ஸ் இந்த அனுமதியைச் செயற்படுத்த முடியாது."</string>
     <string name="permdesc_writeHistoryBookmarks" product="tv" msgid="6340829212433680418">"Android TVயில் சேமித்துள்ள உலாவியின் மூலம் பார்க்கப்பட்ட தளங்களையோ புக்மார்க்குகளையோ திருத்த ஆப்ஸை அனுமதிக்கும். இது உலாவியின் தரவை அழிக்கவோ திருத்தவோ ஆப்ஸை அனுமதிக்கக்கூடும். கவனத்திற்கு: மூன்றாம் தரப்பு உலாவிகளோ இணைய உலாவல் திறன்களுடன் கூடிய பிற ஆப்ஸோ இந்த அனுமதியைச் செயல்படுத்த முடியாது."</string>
-    <string name="permdesc_writeHistoryBookmarks" product="default" msgid="8497389531014185509">"உங்கள் மொபைலில் சேமிக்கப்பட்ட உலாவியின் வரலாறு அல்லது புத்தகக்குறிகளைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இது உலாவியின் தரவை அழிக்கவோ, திருத்தவோ ஆப்ஸை அனுமதிக்கலாம். குறிப்பு: இணைய உலாவல் செயல்திறன்கள் மூலம் மூன்றாம் தரப்பு உலாவிகள் அல்லது பிற பயன்பாடுகள் இந்த அனுமதியைச் செயற்படுத்த முடியாது."</string>
+    <string name="permdesc_writeHistoryBookmarks" product="default" msgid="8497389531014185509">"உங்கள் மொபைலில் சேமிக்கப்பட்ட உலாவியின் வரலாறு அல்லது புத்தகக்குறிகளைத் திருத்த ஆப்ஸை அனுமதிக்கிறது. இது உலாவியின் தரவை அழிக்கவோ, திருத்தவோ ஆப்ஸை அனுமதிக்கலாம். குறிப்பு: இணைய உலாவல் செயல்திறன்கள் மூலம் மூன்றாம் தரப்பு உலாவிகள் அல்லது பிற ஆப்ஸ் இந்த அனுமதியைச் செயற்படுத்த முடியாது."</string>
     <string name="permlab_setAlarm" msgid="1379294556362091814">"அலாரத்தை அமைத்தல்"</string>
     <string name="permdesc_setAlarm" msgid="316392039157473848">"நிறுவிய அலார கடிகாரப் பயன்பாட்டில் அலாரத்தை அமைக்க, ஆப்ஸை அனுமதிக்கிறது. சில அலார கடிகார பயன்பாடுகளில் இந்த அம்சம் இல்லாமல் இருக்கலாம்."</string>
     <string name="permlab_addVoicemail" msgid="5525660026090959044">"குரலஞ்சலைச் சேர்த்தல்"</string>
     <string name="permdesc_addVoicemail" msgid="6604508651428252437">"குரலஞ்சல் இன்பாக்ஸில் செய்திகளைச் சேர்க்க, ஆப்ஸை அனுமதிக்கிறது."</string>
     <string name="permlab_writeGeolocationPermissions" msgid="5962224158955273932">"உலாவியின் புவியியல் இருப்பிடம் சார்ந்த அனுமதிகளைத் திருத்துதல்"</string>
-    <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"உலாவியின் புவியியல் இருப்பிடம் சார்ந்த அனுமதிகளைத் திருத்த, ஆப்ஸை அனுமதிக்கிறது. இடத் தகவலை தன்னிச்சையான இணையதளங்களுக்கு அனுப்புவதை அனுமதிக்க, தீங்குவிளைவிக்கும் பயன்பாடுகள் இதைப் பயன்படுத்தலாம்."</string>
+    <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"உலாவியின் புவியியல் இருப்பிடம் சார்ந்த அனுமதிகளைத் திருத்த, ஆப்ஸை அனுமதிக்கிறது. இடத் தகவலை தன்னிச்சையான இணையதளங்களுக்கு அனுப்புவதை அனுமதிக்க, தீங்குவிளைவிக்கும் ஆப்ஸ் இதைப் பயன்படுத்தலாம்."</string>
     <string name="save_password_message" msgid="767344687139195790">"இந்தக் கடவுச்சொல்லை உலாவி நினைவில்கொள்ள விரும்புகிறீர்களா?"</string>
     <string name="save_password_notnow" msgid="6389675316706699758">"இப்போது இல்லை"</string>
     <string name="save_password_remember" msgid="6491879678996749466">"நினைவில்கொள்"</string>
@@ -1156,10 +1162,10 @@
     <string name="whichImageCaptureApplicationLabel" msgid="6390303445371527066">"படமெடு"</string>
     <string name="alwaysUse" msgid="4583018368000610438">"இந்தச் செயலுக்கு இயல்பாகப் பயன்படுத்து."</string>
     <string name="use_a_different_app" msgid="8134926230585710243">"வேறு ஆப்ஸைப் பயன்படுத்தவும்"</string>
-    <string name="clearDefaultHintMsg" msgid="3252584689512077257">"முறைமை அமைப்பு &gt; பயன்பாடுகள் &gt; பதிவிறக்கியவை என்பதில் உள்ள இயல்பை அழிக்கவும்."</string>
+    <string name="clearDefaultHintMsg" msgid="3252584689512077257">"முறைமை அமைப்பு &gt; ஆப்ஸ் &gt; பதிவிறக்கியவை என்பதில் உள்ள இயல்பை அழிக்கவும்."</string>
     <string name="chooseActivity" msgid="7486876147751803333">"செயலைத் தேர்ந்தெடுக்கவும்"</string>
     <string name="chooseUsbActivity" msgid="6894748416073583509">"USB சாதனத்திற்கான பயன்பாட்டைத் தேர்வுசெய்க"</string>
-    <string name="noApplications" msgid="2991814273936504689">"இந்தச் செயலைச் செய்ய பயன்பாடுகள் எதுவுமில்லை."</string>
+    <string name="noApplications" msgid="2991814273936504689">"இந்தச் செயலைச் செய்ய ஆப்ஸ் எதுவுமில்லை."</string>
     <string name="aerr_application" msgid="250320989337856518">"<xliff:g id="APPLICATION">%1$s</xliff:g> செயலிழந்தது"</string>
     <string name="aerr_process" msgid="6201597323218674729">"<xliff:g id="PROCESS">%1$s</xliff:g> செயலிழந்தது"</string>
     <string name="aerr_application_repeated" msgid="3146328699537439573">"<xliff:g id="APPLICATION">%1$s</xliff:g> தொடர்ந்து செயலிழக்கிறது"</string>
@@ -1184,7 +1190,7 @@
     <string name="launch_warning_original" msgid="188102023021668683">"<xliff:g id="APP_NAME">%1$s</xliff:g> உண்மையாக வெளியிடப்பட்டது."</string>
     <string name="screen_compat_mode_scale" msgid="3202955667675944499">"அளவு"</string>
     <string name="screen_compat_mode_show" msgid="4013878876486655892">"எப்போதும் காட்டு"</string>
-    <string name="screen_compat_mode_hint" msgid="1064524084543304459">"சிஸ்டம் அமைப்பு &gt; பயன்பாடுகள் &gt; பதிவிறக்கம் என்பதில் இதை மீண்டும் இயக்கவும்."</string>
+    <string name="screen_compat_mode_hint" msgid="1064524084543304459">"சிஸ்டம் அமைப்பு &gt; ஆப்ஸ் &gt; பதிவிறக்கம் என்பதில் இதை மீண்டும் இயக்கவும்."</string>
     <string name="unsupported_display_size_message" msgid="6545327290756295232">"தற்போதைய திரை அளவு அமைப்பை <xliff:g id="APP_NAME">%1$s</xliff:g> ஆதரிக்காததால், அது வழக்கத்திற்கு மாறாகச் செயல்படக்கூடும்."</string>
     <string name="unsupported_display_size_show" msgid="7969129195360353041">"எப்போதும் காட்டு"</string>
     <string name="unsupported_compile_sdk_message" msgid="4253168368781441759">"<xliff:g id="APP_NAME">%1$s</xliff:g> பயன்பாடானது, இந்தச் சாதனத்தின் Android OSக்கு இணக்கமற்ற பதிப்பிற்காக உருவாக்கப்பட்டதால், இதில் சரியாகச் செயல்படாது. இந்த ஆப்ஸின் புதுப்பிக்கப்பட்ட பதிப்பானது தற்போது கிடைக்கக்கூடும்."</string>
@@ -1204,7 +1210,7 @@
     <string name="app_upgrading_toast" msgid="3008139776215597053">"<xliff:g id="APPLICATION">%1$s</xliff:g>ஐ மேம்படுத்துகிறது…"</string>
     <string name="android_upgrading_apk" msgid="7904042682111526169">"<xliff:g id="NUMBER_0">%1$d</xliff:g> / <xliff:g id="NUMBER_1">%2$d</xliff:g> ஆப்ஸை ஒருங்கிணைக்கிறது."</string>
     <string name="android_preparing_apk" msgid="8162599310274079154">"<xliff:g id="APPNAME">%1$s</xliff:g>ஐத் தயார்செய்கிறது."</string>
-    <string name="android_upgrading_starting_apps" msgid="451464516346926713">"பயன்பாடுகள் தொடங்கப்படுகின்றன."</string>
+    <string name="android_upgrading_starting_apps" msgid="451464516346926713">"ஆப்ஸ் தொடங்கப்படுகின்றன."</string>
     <string name="android_upgrading_complete" msgid="1405954754112999229">"துவக்குதலை முடிக்கிறது."</string>
     <string name="heavy_weight_notification" msgid="9087063985776626166">"<xliff:g id="APP">%1$s</xliff:g> இயங்குகிறது"</string>
     <string name="heavy_weight_notification_detail" msgid="2304833848484424985">"கேமிற்குச் செல்ல, தட்டவும்"</string>
@@ -1322,7 +1328,7 @@
     <string name="sms_short_code_confirm_allow" msgid="4458878637111023413">"அனுப்பு"</string>
     <string name="sms_short_code_confirm_deny" msgid="2927389840209170706">"ரத்துசெய்"</string>
     <string name="sms_short_code_remember_choice" msgid="5289538592272218136">"எனது விருப்பத்தேர்வை நினைவில்கொள்"</string>
-    <string name="sms_short_code_remember_undo_instruction" msgid="4960944133052287484">"அமைப்பு &gt; பயன்பாடுகள் என்பதில் பிறகு நீங்கள் மாற்றலாம்"</string>
+    <string name="sms_short_code_remember_undo_instruction" msgid="4960944133052287484">"அமைப்பு &gt; ஆப்ஸ் என்பதில் பிறகு நீங்கள் மாற்றலாம்"</string>
     <string name="sms_short_code_confirm_always_allow" msgid="3241181154869493368">"எப்போதும் அனுமதி"</string>
     <string name="sms_short_code_confirm_never_allow" msgid="446992765774269673">"ஒருபோதும் அனுமதிக்காதே"</string>
     <string name="sim_removed_title" msgid="6227712319223226185">"சிம் கார்டு அகற்றப்பட்டது"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB பிழைதிருத்தத்தை முடக்க, தேர்ந்தெடுக்கவும்."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"\'தன்னியக்க சோதனைப்\' பயன்முறை இயக்கப்பட்டது"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"’தன்னியக்க சோதனைப்\' பயன்முறையை முடக்க ஆரம்பநிலைக்கு மீட்டமைக்கவும்."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"சீரியல் கன்சோல் இயக்கப்பட்டது"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"செயல்திறன் பாதிக்கப்பட்டுள்ளது. முடக்குவதற்கு பூட்லோடரைத் தேர்வுசெய்யவும்."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB போர்ட்டில் சேதம் உள்ளது"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB போர்ட் தானாகவே முடக்கப்பட்டது மேலும் அறிய, தட்டவும்."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB போர்ட்டைப் பயன்படுத்தலாம்"</string>
@@ -1446,7 +1454,7 @@
     <string name="ime_action_default" msgid="2840921885558045721">"செயலாக்கு"</string>
     <string name="dial_number_using" msgid="5789176425167573586">"<xliff:g id="NUMBER">%s</xliff:g> ஐப் பயன்படுத்தி\nஅழை"</string>
     <string name="create_contact_using" msgid="4947405226788104538">"<xliff:g id="NUMBER">%s</xliff:g> ஐப்\nபயன்படுத்தி தொடர்பை உருவாக்கு"</string>
-    <string name="grant_credentials_permission_message_header" msgid="2106103817937859662">"பின்வரும் ஒன்று அல்லது அதற்கு மேற்பட்ட பயன்பாடுகள், இப்போதும் எதிர்காலத்திலும் உங்கள் கணக்கை அணுகுவதற்கான அனுமதியைக் கோருகின்றன."</string>
+    <string name="grant_credentials_permission_message_header" msgid="2106103817937859662">"பின்வரும் ஒன்று அல்லது அதற்கு மேற்பட்ட ஆப்ஸ், இப்போதும் எதிர்காலத்திலும் உங்கள் கணக்கை அணுகுவதற்கான அனுமதியைக் கோருகின்றன."</string>
     <string name="grant_credentials_permission_message_footer" msgid="3125211343379376561">"இந்தக் கோரிக்கையை அனுமதிக்க விரும்புகிறீர்களா?"</string>
     <string name="grant_permissions_header_text" msgid="6874497408201826708">"‍அணுகல் கோரிக்கை"</string>
     <string name="allow" msgid="7225948811296386551">"அனுமதி"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"வகைப்படுத்தப்படாதவை"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"இந்த அறிவிப்புகளின் முக்கியத்துவத்தை அமைத்துள்ளீர்கள்."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ஈடுபட்டுள்ளவர்களின் காரணமாக, இது முக்கியமானது."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="ACCOUNT">%2$s</xliff:g> மூலம் புதிய பயனரை உருவாக்க <xliff:g id="APP">%1$s</xliff:g>ஐ அனுமதிக்கவா?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g> (இந்தக் கணக்கில் ஏற்கனவே ஒரு பயனர் உள்ளார்) மூலம் புதிய பயனரை உருவாக்க <xliff:g id="APP">%1$s</xliff:g>ஐ அனுமதிக்கவா?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g> மூலம் புதிய பயனரை உருவாக்க <xliff:g id="APP">%1$s</xliff:g> ஆப்ஸை அனுமதிக்கவா (இந்தக் கணக்கில் ஏற்கெனவே ஒரு பயனர் உள்ளார்) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> மூலம் புதிய பயனரை உருவாக்க <xliff:g id="APP">%1$s</xliff:g> ஆப்ஸை அனுமதிக்கவா?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"மொழியைச் சேர்"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"மண்டல விருப்பம்"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"மொழி பெயரை உள்ளிடுக"</string>
diff --git a/core/res/res/values-te/strings.xml b/core/res/res/values-te/strings.xml
index aa5c271..37e0590 100644
--- a/core/res/res/values-te/strings.xml
+++ b/core/res/res/values-te/strings.xml
@@ -292,7 +292,7 @@
     <string name="permgrouprequest_calendar" msgid="289900767793189421">"మీ క్యాలెండర్‌ని యాక్సెస్ చేయడానికి &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ని అనుమతించాలా?"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"SMS సందేశాలను పంపడం మరియు వీక్షించడం"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"SMS సందేశాలు పంపడానికి మరియు వీక్షించడానికి &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ని అనుమతించాలా?"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"SMS సందేశాలు పంపడం, చూడటం చేయగలిగేలా &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ను అనుమతించాలా?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"నిల్వ"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"మీ పరికరంలోని ఫోటోలు, మీడియా మరియు ఫైల్‌లను యాక్సెస్ చేయడానికి"</string>
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"మీ పరికరంలోని ఫోటోలు, మీడియా మరియు ఫైల్‌లను యాక్సెస్ చేయడానికి &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;ను అనుమతించాలా?"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"SMS సందేశాలను స్వీకరించడానికి మరియు ప్రాసెస్ చేయడానికి యాప్‌ను అనుమతిస్తుంది. యాప్ మీ డివైజ్‌కు పంపబడిన సందేశాలను మీకు చూపకుండానే పర్యవేక్షించగలదని లేదా తొలగించగలదని దీని అర్థం."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"వచన సందేశాలను (MMS) స్వీకరించడం"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"MMS సందేశాలను స్వీకరించడానికి మరియు ప్రాసెస్ చేయడానికి యాప్‌ను అనుమతిస్తుంది. యాప్ మీ డివైజ్‌కు పంపబడిన సందేశాలను మీకు చూపకుండానే పర్యవేక్షించగలదని లేదా తొలగించగలదని దీని అర్థం."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"సెల్ ప్రసార సందేశాలను చదవడం"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"మీ పరికరం స్వీకరించిన సెల్ ప్రసార సందేశాలను చదవడానికి యాప్‌ను అనుమతిస్తుంది. సెల్ ప్రసార హెచ్చరికలు అత్యవసర పరిస్థితుల గురించి మిమ్మల్ని హెచ్చరించడానికి కొన్ని స్థానాల్లో అందించబడతాయి. అత్యవసర సెల్ ప్రసారం స్వీకరించినప్పుడు హానికరమైన యాప్‌లు మీ పరికరం యొక్క పనితీరు లేదా నిర్వహణకు అంతరాయం కలిగించవచ్చు."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"చందా చేయబడిన ఫీడ్‌లను చదవడం"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"అంతరాయం కలిగించవద్దు ఎంపిక కాన్ఫిగరేషన్ చదవడానికి మరియు వ్రాయడానికి అనువర్తనాన్ని అనుమతిస్తుంది."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"వీక్షణ అనుమతి వినియోగాన్ని ప్రారంభించండి"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"యాప్‌నకు అనుమతి వినియోగాన్ని ప్రారంభించడానికి హోల్డర్‌‌ను అనుమతిస్తుంది. సాధారణ యాప్‌లకు ఎప్పటికీ ఇటువంటి అనుమతి అవసరం ఉండదు."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"యాక్సెసిబిలిటీ షార్ట్‌కట్ లక్ష్యం"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"యాక్సెసిబిలిటీ షార్ట్‌కట్ లక్ష్యాన్ని నిర్వచించడానికి యాప్‌ను అనుమతించండి."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"పాస్‌వర్డ్ నియమాలను సెట్ చేయండి"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"స్క్రీన్ లాక్ పాస్‌వర్డ్‌లు మరియు PINల్లో అనుమతించబడిన పొడవు మరియు అక్షరాలను నియంత్రిస్తుంది."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"స్క్రీన్ అన్‌లాక్ ప్రయత్నాలను పర్యవేక్షించండి"</string>
@@ -1257,8 +1263,8 @@
     <string name="wifi_available_content_failed_to_connect" msgid="3377406637062802645">"అన్ని నెట్‌వర్క్‌లు చూడటానికి నొక్కండి"</string>
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"కనెక్ట్ చేయి"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"అన్ని నెట్‌వర్క్‌లు"</string>
-    <string name="wifi_suggestion_title" msgid="6396033039578436801">"సూచించిన Wi‑Fi నెట్‌వర్క్‍లను అనుమతించాలా?"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> సూచించిన నెట్ వర్క్ లు పరికరం ఆటోమేటిక్ గా కనెక్ట్ కాకపోవచ్చు."</string>
+    <string name="wifi_suggestion_title" msgid="6396033039578436801">"సూచించిన Wi‑Fi నెట్‌వర్క్‌లను అనుమతించాలా?"</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"<xliff:g id="NAME">%s</xliff:g> సూచించిన నెట్‌వర్క్‌లు. పరికరం ఆటోమేటిక్‌గా కనెక్ట్ అవచ్చు."</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"అనుమతించు"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"వద్దు"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi స్వయంచాలకంగా ఆన్ అవుతుంది"</string>
@@ -1330,7 +1336,7 @@
     <string name="sim_done_button" msgid="827949989369963775">"పూర్తయింది"</string>
     <string name="sim_added_title" msgid="3719670512889674693">"సిమ్ కార్డు జోడించబడింది"</string>
     <string name="sim_added_message" msgid="6599945301141050216">"మొబైల్ నెట్‌వర్క్‌ను యాక్సెస్ చేయడానికి మీ పరికరాన్ని పునఃప్రారంభించండి."</string>
-    <string name="sim_restart_button" msgid="4722407842815232347">"పునఃప్రారంభించు"</string>
+    <string name="sim_restart_button" msgid="4722407842815232347">"రీస్టార్ట్ చేయి"</string>
     <string name="install_carrier_app_notification_title" msgid="9056007111024059888">"మొబైల్ సేవను సక్రియం చేయండి"</string>
     <string name="install_carrier_app_notification_text" msgid="3346681446158696001">"మీ కొత్త SIMని సక్రియం చేయడానికి క్యారియర్ యాప్‌ను డౌన్‌లోడ్ చేయండి"</string>
     <string name="install_carrier_app_notification_text_app_name" msgid="1196505084835248137">"మీ కొత్త SIMని సక్రియం చేయడం కోసం <xliff:g id="APP_NAME">%1$s</xliff:g> యాప్‌ని డౌన్‌లోడ్ చేయండి"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"డీబగ్గింగ్‌ని నిలిపివేయడానికి ఎంచుకోండి."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"పరీక్ష నియంత్రణ మోడ్ ప్రారంభించబడింది"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"పరీక్ష నియంత్రణ మోడ్‌ను నిలిపివేయడానికి ఫ్యాక్టరీ రీసెట్‍‌ను అమలు చేయండి."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"సీరియల్ కన్సోల్ ప్రారంభించబడింది"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"పని తీరు ప్రభావితమైంది. నిలిపివేయడానికి, బూట్‌లోడర్‌ను తనిఖీ చేయండి."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB పోర్ట్‌లో ద్రవ లేదా వ్యర్థ పదార్థాలు ఉన్నాయి"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB పోర్ట్ ఆటోమేటిక్‌గా నిలిపివేయబడింది. మరింత తెలుసుకోవడానికి నొక్కండి."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB పోర్ట్‌ను ఉపయోగించడం సురక్షితం"</string>
@@ -1673,7 +1681,7 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"యాక్సెస్ సామర్థ్య షార్ట్‌కట్ ద్వారా <xliff:g id="SERVICE_NAME">%1$s</xliff:g> ఆఫ్ చేయబడింది"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"<xliff:g id="SERVICE_NAME">%1$s</xliff:g>ని ఉపయోగించడానికి వాల్యూమ్ కీలు రెండింటినీ 3 సెకన్లు నొక్కి ఉంచండి"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"యాక్సెసిబిలిటీ బటన్‌ను మీరు నొక్కినప్పుడు ఉపయోగించాల్సిన ఒక ఫీచర్‌ను ఎంచుకోండి:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"యాక్సెసిబిలిటీ సంజ్ఞతో ఉపయోగించడానికి ఒక సేవను ఎంచుకోండి (రెండు చేతి వేళ్లతో స్క్రీన్‌ను కింద నుండి పైకి స్వైప్ చేయండి):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"యాక్సెసిబిలిటీ సంజ్ఞతో ఉపయోగించడానికి ఒక సేవను ఎంచుకోండి (రెండు వేళ్లతో స్క్రీన్‌ను కింద నుండి పైకి స్వైప్ చేయండి):"</string>
     <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"యాక్సెసిబిలిటీ సంజ్ఞతో ఉపయోగించడానికి ఒక సేవను ఎంచుకోండి (మూడు చేతి వేళ్లతో స్క్రీన్‌ను కింద నుండి పైకి స్వైప్ చేయండి):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"సేవల మధ్య మారడానికి, యాక్సెసిబిలిటీ బటన్‌ను నొక్కి &amp; పట్టుకోండి."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"సేవల మధ్య మారడానికి, రెండు చేతి వేళ్ళతో పైకి స్వైప్ చేసి పట్టుకోండి."</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"వర్గీకరించబడలేదు"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"మీరు ఈ నోటిఫికేషన్‌ల ప్రాముఖ్యతను సెట్ చేసారు."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ఇందులో పేర్కొనబడిన వ్యక్తులను బట్టి ఇది చాలా ముఖ్యమైనది."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="ACCOUNT">%2$s</xliff:g>తో కొత్త వినియోగదారుని సృష్టించడానికి <xliff:g id="APP">%1$s</xliff:g>ని అనుమతించాలా ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="ACCOUNT">%2$s</xliff:g>తో (ఈ ఖాతాతో ఇప్పటికే ఒక వినియోగదారు ఉన్నారు) కొత్త వినియోగదారుని సృష్టించడానికి <xliff:g id="APP">%1$s</xliff:g>ని అనుమతించాలా?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="ACCOUNT">%2$s</xliff:g>తో కొత్త వినియోగదారుని సృష్టించడానికి <xliff:g id="APP">%1$s</xliff:g>ను అనుమతించాలా (ఈ ఖాతాతో ఇప్పటికే ఒక వినియోగదారు ఉన్నారు) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g>తో కొత్త వినియోగదారుని సృష్టించడానికి <xliff:g id="APP">%1$s</xliff:g>ను అనుమతించాలా?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"భాషను జోడించండి"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ప్రాంతం ప్రాధాన్యత"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"భాష పేరును టైప్ చేయండి"</string>
diff --git a/core/res/res/values-th/strings.xml b/core/res/res/values-th/strings.xml
index 3472cb2..482288e 100644
--- a/core/res/res/values-th/strings.xml
+++ b/core/res/res/values-th/strings.xml
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"อนุญาตให้ &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; เข้าถึงรายชื่อติดต่อไหม"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"ตำแหน่ง"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"เข้าถึงตำแหน่งของอุปกรณ์นี้"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"อนุญาตให้ &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; เข้าถึงตำแหน่งของอุปกรณ์นี้ไหม"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"อนุญาตให้&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;เข้าถึงตำแหน่งของอุปกรณ์นี้ไหม"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"แอปจะมีสิทธิ์เข้าถึงตำแหน่งในขณะที่คุณใช้แอปเท่านั้น"</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"อนุญาตให้ &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; เข้าถึงตำแหน่งของอุปกรณ์นี้&lt;b&gt;ตลอดเวลา&lt;/b&gt;ไหม"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"ปัจจุบันแอปมีสิทธิ์เข้าถึงตำแหน่งในขณะที่คุณใช้แอปเท่านั้น"</string>
@@ -298,7 +298,7 @@
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"อนุญาตให้ &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; เข้าถึงรูปภาพ สื่อ และไฟล์ในอุปกรณ์ไหม"</string>
     <string name="permgrouplab_microphone" msgid="171539900250043464">"ไมโครโฟน"</string>
     <string name="permgroupdesc_microphone" msgid="4988812113943554584">"บันทึกเสียง"</string>
-    <string name="permgrouprequest_microphone" msgid="9167492350681916038">"อนุญาตให้ &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; บันทึกเสียงไหม"</string>
+    <string name="permgrouprequest_microphone" msgid="9167492350681916038">"อนุญาตให้&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;บันทึกเสียงไหม"</string>
     <string name="permgrouplab_activityRecognition" msgid="1565108047054378642">"การเคลื่อนไหวร่างกาย"</string>
     <string name="permgroupdesc_activityRecognition" msgid="6949472038320473478">"เข้าถึงกิจกรรมการเคลื่อนไหวร่างกายของคุณ"</string>
     <string name="permgrouprequest_activityRecognition" msgid="7626438016904799383">"อนุญาตให้ &lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; เข้าถึงกิจกรรมการเคลื่อนไหวร่างกายของคุณไหม"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"อนุญาตให้แอปพลิเคชันรับและประมวลผลข้อความ SMS ซึ่งหมายความว่าแอปพลิเคชันจะสามารถตรวจสอบหรือลบข้อความที่ส่งมายังอุปกรณ์ของคุณได้โดยไม่ต้องแสดงให้คุณเห็น"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"รับข้อความ (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"อนุญาตให้แอปพลิเคชันรับและประมวลผลข้อความ MMS ซึ่งหมายความว่าแอปพลิเคชันจะสามารถตรวจสอบหรือลบข้อความที่ส่งมายังอุปกรณ์ของคุณได้โดยไม่ต้องแสดงให้คุณเห็น"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"อ่านข้อความที่ได้รับจากสถานีมือถือ"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"อนุญาตให้แอปอ่านข้อความจากสถานีมือถือที่อุปกรณ์ได้รับ การแจ้งเตือนทางมือถือมีให้บริการในบางพื้นที่ โดยจะแจ้งเตือนคุณเกี่ยวกับสถานการณ์ฉุกเฉิน แอปที่เป็นอันตรายอาจเข้าแทรกแซงการทำงานของอุปกรณ์เมื่อได้รับข้อความแจ้งเตือนฉุกเฉิน"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"อ่านฟีดข้อมูลที่สมัครไว้"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"อนุญาตให้แอปอ่านและเขียนการกำหนดค่าโหมดห้ามรบกวน"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"เริ่มการใช้สิทธิ์การดู"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"อนุญาตให้เจ้าของเริ่มการใช้สิทธิ์ของแอป ไม่จำเป็นสำหรับแอปทั่วไป"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"เป้าหมายทางลัดการช่วยเหลือพิเศษ"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"อนุญาตให้แอปกำหนดเป้าหมายทางลัดการช่วยเหลือพิเศษ"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"ตั้งค่ากฎรหัสผ่าน"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"ควบคุมความยาวและอักขระที่สามารถใช้ในรหัสผ่านของการล็อกหน้าจอและ PIN"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"ตรวจสอบความพยายามในการปลดล็อกหน้าจอ"</string>
@@ -1258,7 +1264,7 @@
     <string name="wifi_available_action_connect" msgid="2635699628459488788">"เชื่อมต่อ"</string>
     <string name="wifi_available_action_all_networks" msgid="4368435796357931006">"เครือข่ายทั้งหมด"</string>
     <string name="wifi_suggestion_title" msgid="6396033039578436801">"อนุญาตให้เชื่อมต่อเครือข่าย Wi-Fi ที่แนะนำไหม"</string>
-    <string name="wifi_suggestion_content" msgid="5603992011371520746">"เครือข่ายที่แนะนำ <xliff:g id="NAME">%s</xliff:g> อุปกรณ์อาจเชื่อมต่อโดยอัตโนมัติ"</string>
+    <string name="wifi_suggestion_content" msgid="5603992011371520746">"เครือข่ายที่แนะนำโดย <xliff:g id="NAME">%s</xliff:g> และอุปกรณ์อาจเชื่อมต่อโดยอัตโนมัติ"</string>
     <string name="wifi_suggestion_action_allow_app" msgid="7978995387498669901">"อนุญาต"</string>
     <string name="wifi_suggestion_action_disallow_app" msgid="6434097275967940372">"ไม่เป็นไร"</string>
     <string name="wifi_wakeup_onboarding_title" msgid="228772560195634292">"Wi‑Fi จะเปิดโดยอัตโนมัติ"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"เลือกเพื่อปิดใช้งานการแก้ไขข้อบกพร่อง USB"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"โหมดโปรแกรมทดสอบอัตโนมัติเปิดใช้อยู่"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"รีเซ็ตเป็นค่าเริ่มต้นเพื่อปิดใช้โหมดโปรแกรมทดสอบอัตโนมัติ"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"เปิดใช้คอนโซลการเรียงอันดับแล้ว"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"ประสิทธิภาพได้รับผลกระทบ ตรวจสอบ Bootloader เพื่อปิดใช้งาน"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"มีของเหลวหรือฝุ่นละอองในพอร์ต USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"พอร์ต USB ปิดใช้โดยอัตโนมัติ แตะเพื่อดูข้อมูลเพิ่มเติม"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"ใช้พอร์ต USB ได้แล้ว"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"ไม่จัดอยู่ในหมวดหมู่ใดๆ"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"คุณตั้งค่าความสำคัญของการแจ้งเตือนเหล่านี้"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"ข้อความนี้สำคัญเนื่องจากบุคคลที่เกี่ยวข้อง"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"อนุญาตให้ <xliff:g id="APP">%1$s</xliff:g> สร้างผู้ใช้ใหม่ด้วย <xliff:g id="ACCOUNT">%2$s</xliff:g> ไหม"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"อนุญาตให้ <xliff:g id="APP">%1$s</xliff:g> สร้างผู้ใช้ใหม่ด้วย <xliff:g id="ACCOUNT">%2$s</xliff:g> (มีผู้ใช้ที่มีบัญชีนี้อยู่แล้ว) ไหม"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"อนุญาตให้ <xliff:g id="APP">%1$s</xliff:g> สร้างผู้ใช้ใหม่ด้วย <xliff:g id="ACCOUNT">%2$s</xliff:g> ไหม (มีผู้ใช้ที่มีบัญชีนี้อยู่แล้ว)"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"อนุญาตให้ <xliff:g id="APP">%1$s</xliff:g> สร้างผู้ใช้ใหม่ด้วย <xliff:g id="ACCOUNT">%2$s</xliff:g> ไหม"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"เพิ่มภาษา"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"ค่ากำหนดภูมิภาค"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"พิมพ์ชื่อภาษา"</string>
diff --git a/core/res/res/values-tl/strings.xml b/core/res/res/values-tl/strings.xml
index 49a13c9..f2db658 100644
--- a/core/res/res/values-tl/strings.xml
+++ b/core/res/res/values-tl/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Pinapayagan ang app na tumanggap at magproseso ng mga mensaheng SMS. Nangangahulugan ito na maaaring sumubaybay o magtanggal ang app ng mga mensaheng ipinapadala sa iyong device nang hindi ipinapakita ang mga ito sa iyo."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"tumanggap ng mga text message (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Pinapayagan ang app na tumanggap at magproseso ng mga mensaheng MMS. Nangangahulugan ito na maaaring sumubaybay o magtanggal ang app ng mga mensaheng ipinapadala sa iyong device nang hindi ipinapakita ang mga ito sa iyo."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"basahin ang mga mensahe ng cell broadcast"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Binibigyang-daan ang app na magbasa ng mga mensahe ng cell broadcast na natanggap ng iyong device. Inihahatid ang mga alerto ng cell broadcast sa ilang lokasyon upang balaan ka tungkol sa mga emergency na sitwasyon. Maaaring makaabala ang nakakahamak na apps sa performance o pagpapatakbo ng iyong device kapag nakatanggap ng emergency na cell broadcast."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"magbasa ng mga na-subscribe na feed"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Nagbibigay-daan sa app na basahin at isulat ang configuration ng Huwag Istorbohin."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"simulan ang paggamit sa pahintulot sa pagtingin"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Binibigyang-daan ang may hawak na simulan ang paggamit ng pahintulot para sa isang app. Hindi dapat kailanganin kailanman para sa mga normal na app."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"Target ng shortcut sa pagiging accessible"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Nagbibigay-daan sa isang app na tukuyin ang target ng shortcut sa pagiging accessible."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Magtakda ng mga panuntunan sa password"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kontrolin ang haba at ang mga character na pinapayagan sa mga password at PIN sa screen lock."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Subaybayan ang mga pagsubok sa pag-unlock ng screen"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Piliin upang i-disable ang debugging ng USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Naka-enable ang Test Harness Mode"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Mag-factory reset para i-disable ang Test Harness Mode."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Naka-enable ang serial console"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Naaapektuhan ang performance. Para i-disable, lagyan ng check ang bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Liquid o debris sa USB port"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Awtomatikong na-disable ang USB port. Mag-tap para matuto pa."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Ayos na gamitin ang USB port"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Di-nakategorya"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ikaw ang magtatakda sa kahalagahan ng mga notification na ito."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Mahalaga ito dahil sa mga taong kasangkot."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Payagan ang <xliff:g id="APP">%1$s</xliff:g> na gumawa ng bagong User sa <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Payagan ang <xliff:g id="APP">%1$s</xliff:g> na gumawa ng bagong User sa <xliff:g id="ACCOUNT">%2$s</xliff:g> (mayroon nang User sa account na ito) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Payagan ang <xliff:g id="APP">%1$s</xliff:g> na gumawa ng bagong User sa <xliff:g id="ACCOUNT">%2$s</xliff:g> (mayroon nang User sa account na ito) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Payagan ang <xliff:g id="APP">%1$s</xliff:g> na gumawa ng bagong User sa <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Magdagdag ng wika"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Kagustuhan sa rehiyon"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"I-type ang wika"</string>
diff --git a/core/res/res/values-tr/strings.xml b/core/res/res/values-tr/strings.xml
index dd75d23..cf3fbfc 100644
--- a/core/res/res/values-tr/strings.xml
+++ b/core/res/res/values-tr/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Uygulamaya SMS iletilerini alma ve işleme izni verir. Bu izin, uygulamanın cihazınıza gönderilen iletileri takip edip size göstermeden silebileceği anlamına gelir."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"kısa mesajları (MMS) al"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Uygulamaya MMS iletilerini alma ve işleme izni verir. Bu izin, uygulamanın cihazınıza gönderilen iletileri takip edip size göstermeden silebileceği anlamına gelir."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"hücre yayını mesajlarını oku"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Uygulamaya, cihazınız tarafından alınan hücre yayını mesajlarını okuma izni verir. Hücre yayını uyarıları bazı yerlerde acil durumlar konusunda sizi uyarmak için gönderilir. Kötü amaçlı uygulamalar acil hücre yayını alındığında cihazınızın performansına ya da çalışmasına engel olabilir."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"abone olunan yayınları okuma"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Uygulamaya, Rahatsız Etmeyin yapılandırmasını okuma ve yazma izni verir."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"izin kullanımı görüntülemeye başlama"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"İzin sahibinin bir uygulama için izin kullanımı başlatmasına olanak tanır. Normal uygulamalar için hiçbir zaman kullanılmamalıdır."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"erişilebilirlik kısayolu hedefi"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Uygulamaların erişilebilirlik kısayolu hedefi tanımlamasına izin verir."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Şifre kuralları ayarla"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Ekran kilidini açma şifrelerinde ve PIN\'lerde izin verilen uzunluğu ve karakterleri denetleyin."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Ekran kilidini açma denemelerini izle"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB hata ayıklamasını devre dışı bırakmak için seçin."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Test Bandı Modu etkin"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Test Bandı Modu\'nu devre dışı bırakmak için cihazı fabrika ayarlarına sıfırlayın."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Seri konsol etkinleştirildi"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Performans etkilendi. Devre dışı bırakmak için bootloader\'ı kontrol edin."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB bağlantı noktasında sıvı veya toz var"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB bağlantı noktası otomatik olarak devre dışı bırakıldı. Daha fazla bilgi için dokunun."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB bağlantı noktasını kullanabilirsiniz"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Kategorize edilmemiş"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Bu bildirimlerin önem derecesini ayarladınız."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Bu, dahil olan kişiler nedeniyle önemlidir."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> uygulamasının <xliff:g id="ACCOUNT">%2$s</xliff:g> hesabına sahip yeni bir Kullanıcı eklemesine izin verilsin mi?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> uygulamasının <xliff:g id="ACCOUNT">%2$s</xliff:g> hesabına sahip yeni bir Kullanıcı eklemesine izin verilsin mi (bu hesaba sahip bir kullanıcı zaten var)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> uygulamasının <xliff:g id="ACCOUNT">%2$s</xliff:g> hesabına sahip yeni bir Kullanıcı eklemesine izin verilsin mi (bu hesaba sahip bir kullanıcı zaten var)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> uygulamasının <xliff:g id="ACCOUNT">%2$s</xliff:g> hesabına sahip yeni bir Kullanıcı eklemesine izin verilsin mi?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Dil ekleyin"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Bölge tercihi"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Dil adını yazın"</string>
diff --git a/core/res/res/values-uk/strings.xml b/core/res/res/values-uk/strings.xml
index 02c7957..0ac716d 100644
--- a/core/res/res/values-uk/strings.xml
+++ b/core/res/res/values-uk/strings.xml
@@ -350,6 +350,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Дозволяє програмі отримувати й обробляти SMS-повідомлення. Це означає, що програма може відстежувати чи видаляти повідомлення, надіслані на ваш пристрій, навіть не показуючи їх вам."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"отримувати текстові повідомлення (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Дозволяє програмі отримувати й обробляти MMS-повідомлення. Це означає, що програма може відстежувати чи видаляти повідомлення, надіслані на ваш пристрій, навіть не показуючи їх вам."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"читати широкомовні повідомлення мережі"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Дозволяє програмі читати широкомовні повідомлення мережі, отримані пристроєм. Широкомовні сповіщення мережі надсилаються в деяких країнах для попередження про надзвичайні ситуації. Шкідливі програми можуть втручатися у швидкодію чи роботу пристрою під час отримання широкомовного повідомлення мережі про надзвичайну ситуацію."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"читати підписані канали"</string>
@@ -661,6 +665,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Додаток зможе переглядати та змінювати конфігурацію режиму \"Не турбувати\"."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"перегляньте дані про використання дозволів"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Власник зможе використовувати дозволи для цього додатка. Цей дозвіл не потрібен для звичайних додатків."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"потрібні засоби спеціальних можливостей"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Дає додатку змогу визначати потрібні засоби спеціальних можливостей."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Устан. правила пароля"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Укажіть максимальну довжину та кількість символів для паролів розблокування екрана та PIN-кодів."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Відстежувати спроби розблокування екрана"</string>
@@ -1405,6 +1411,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Виберіть, щоб вимкнути налагодження за USB"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Увімкнено режим автоматизованого тестування"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Щоб вимкнути режим автоматизованого тестування, відновіть заводські налаштування."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Послідовну консоль увімкнено"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Продуктивність зазнала впливу. Щоб вимкнути, перевірте завантажувач операційної системи."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Рідина або сміття в USB-порту"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB-порт автоматично вимкнено. Торкніться, щоб дізнатися більше."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Можна використовувати USB-порт"</string>
@@ -1958,8 +1966,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Без категорії"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Ви вказуєте пріоритет цих сповіщень."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Важливе з огляду на учасників."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Дозволити додатку <xliff:g id="APP">%1$s</xliff:g> створити нового користувача з обліковим записом <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Дозволити додатку <xliff:g id="APP">%1$s</xliff:g> створити нового користувача з обліковим записом <xliff:g id="ACCOUNT">%2$s</xliff:g> (користувач із таким обліковим записом уже існує)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Дозволити додатку <xliff:g id="APP">%1$s</xliff:g> створити нового користувача з обліковим записом <xliff:g id="ACCOUNT">%2$s</xliff:g> (користувач із таким обліковим записом уже існує)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Дозволити додатку <xliff:g id="APP">%1$s</xliff:g> створити нового користувача з обліковим записом <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Додати мову"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Вибір регіону"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Введіть назву мови"</string>
diff --git a/core/res/res/values-ur/strings.xml b/core/res/res/values-ur/strings.xml
index f7d03c5..43ecaf6 100644
--- a/core/res/res/values-ur/strings.xml
+++ b/core/res/res/values-ur/strings.xml
@@ -324,7 +324,7 @@
     <string name="capability_desc_canControlMagnification" msgid="4791858203568383773">"ڈسپلے کے زوم کی سطح اور پوزیشن کو کنٹرول کریں۔"</string>
     <string name="capability_title_canPerformGestures" msgid="7418984730362576862">"اشارے انجام دینے کی"</string>
     <string name="capability_desc_canPerformGestures" msgid="8296373021636981249">"تھپتھپانا، سوائپ کرنا، چٹکی بھرنا اور دیگر اشارے انجام دے سکتی ہے"</string>
-    <string name="capability_title_canCaptureFingerprintGestures" msgid="6309568287512278670">"فنگرپرنٹ کے اشارے"</string>
+    <string name="capability_title_canCaptureFingerprintGestures" msgid="6309568287512278670">"فنگر پرنٹ کے اشارے"</string>
     <string name="capability_desc_canCaptureFingerprintGestures" msgid="4386487962402228670">"آلہ کے فنگر پرنٹ سینسر پر کیے گئے اشاروں کو کیپچر کر سکتا ہے۔"</string>
     <string name="permlab_statusBar" msgid="7417192629601890791">"اسٹیٹس بار کو غیر فعال یا اس میں ترمیم کریں"</string>
     <string name="permdesc_statusBar" msgid="8434669549504290975">"ایپ کو اسٹیٹس بار غیر فعال کرنے یا سسٹم آئیکنز شامل کرنے اور ہٹانے کی اجازت دیتا ہے۔"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"‏ایپ کو SMS پیغامات حاصل اور ان پر کارروائی کرنے کی اجازت دیتا ہے۔ اس کا مطلب ہے کہ ایپ آپ کے آلے پر مرسلہ پیغامات آپ کو دکھائے بغیر ان پر نگاہ رکھ یا انہیں حذف کرسکتی ہے۔"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"‏متنی پیغامات (MMS) حاصل کریں"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"‏ایپ کو MMS پیغامات حاصل اور ان پر کارروائی کرنے کی اجازت دیتا ہے۔ اس کا مطلب ہے کہ ایپ آپ کے آلے پر مرسلہ پیغامات آپ کو دکھائے بغیر ان پر نگاہ رکھ یا انہیں حذف کرسکتی ہے۔"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"سیل کے نشریاتی پیغامات پڑھیں"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ایپ کو آپ کے آلے کو موصولہ سیل کے نشریاتی پیغامات پڑھنے کی اجازت دیتا ہے۔ سیل کی نشریاتی الرٹس آپ کو ہنگامی حالات سے مطلع کرنے کیلئے کچھ مقامات میں مہیا کی جاتی ہیں۔ نقصان دہ ایپس کوئی ہنگامی سیل کا نشریہ موصول ہونے پر آپ کے آلے کی کارکردگی یا عمل میں خلل ڈال سکتی ہیں۔"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"سبسکرائب کردہ فیڈز پڑھیں"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"ایپ کو ڈسٹرب نہ کریں کنفیگریشن لکھنے اور پڑھنے کے قابل کرتا ہے۔"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"اجازت کی استعمال کا ملاحظہ شروع کریں"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"حامل کو ایپ کی اجازت کے استعمال کو شروع کرنے کی اجازت دیتا ہے۔ عام ایپس کے لیے کبھی بھی درکار نہیں ہونا چاہیے۔"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"ایکسیسبیلٹی شارٹ کٹ ہدف"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"ایپ کو ایکسیسبیلٹی شارٹ کٹ ہدف کی وضاحت کرنے کے ليے اجازتیں۔"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"پاس ورڈ کے اصول سیٹ کریں"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"‏اسکرین لاک پاس ورڈز اور PINs میں اجازت یافتہ لمبائی اور حروف کو کنٹرول کریں۔"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"اسکرین غیر مقفل کرنے کی کوششیں مانیٹر کریں"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"‏USB ڈیبگ کرنے کو غیر فعال کرنے کیلئے منتخب کریں۔"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"ٹیسٹ ہارنیس موڈ فعال ہے"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"ٹیسٹ ہارنیس موڈ غیر فعال کرنے کے لیے فیکٹری ری سیٹ کریں۔"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"شمار کونسول فعال ہے"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"کارکردگی پر اثر پڑا ہے۔ غیر فعال کرنے کے ليے، بوٹ لوڈر چیک کریں۔"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"‏USB پورٹ میں سیال یا دھول ہے"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"‏USB پورٹ خودکار طور پر غیر فعال کر دیا گیا۔ مزید جاننے کیلئے تھپتھپائیں۔"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"‏USB پورٹ کا استعمال ٹھیک ہے"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"غیر زمرہ بند"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"ان اطلاعات کی اہمیت آپ مقرر کرتے ہیں۔"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"اس میں موجود لوگوں کی وجہ سے یہ اہم ہے۔"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> کو <xliff:g id="ACCOUNT">%2$s</xliff:g> کے ساتھ ایک نیا صارف بنانے کی اجازت دیں؟"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> کو <xliff:g id="ACCOUNT">%2$s</xliff:g> کے ساتھ ایک نیا صارف بنانے کی اجازت دیں (اس اکاؤنٹ کے ساتھ ایک صارف پہلے سے موجود ہے) ؟"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> کو <xliff:g id="ACCOUNT">%2$s</xliff:g> کے ساتھ ایک نیا صارف بنانے کی اجازت دیں (اس اکاؤنٹ کے ساتھ ایک صارف پہلے سے موجود ہے) ؟"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="ACCOUNT">%2$s</xliff:g> کے ساتھ نئے صارف کو تخلیق کرنے کے لیے <xliff:g id="APP">%1$s</xliff:g> کو اجازت دیں ؟"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"ایک زبان شامل کریں"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"علاقہ کی ترجیح"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"زبان کا نام ٹائپ کریں"</string>
diff --git a/core/res/res/values-uz/strings.xml b/core/res/res/values-uz/strings.xml
index a6c1d3a..5ebda207 100644
--- a/core/res/res/values-uz/strings.xml
+++ b/core/res/res/values-uz/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Ilovaga SMS xabarlarini qabul qilish va va ularni qayta ishlash uchun ruxsat beradi. Bu sizga yuborilgan xabarlarni ilova sizga ko‘rsatmasdan kuzatishi va o‘chirishi mumkinligini bildiradi."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"MMS xabarlarni olish"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Ilovaga MMS xabarlarini qabul qilish va ularni qayta ishlash uchun ruxsat beradi. Bu sizga yuborilgan xabarlarni ilova sizga ko‘rsatmasdan kuzatishi va o‘chirishi mumkinligini bildiradi."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"uyali tarmoq operatori xabarlarini o‘qish"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Ilovaga qurilmangiz tomonidan qabul qilingan uyali tarmoq operatori xabarlarini o‘qish uchun ruxsat beradi. Uyali tarmoq operatorining ogohlantiruvchi xabarlari ba’zi manzillarga favqulodda holatlar haqida ogohlantirish uchun jo‘natiladi. Zararli ilovalar uyali tarmoq orqali favqulodda xabar qabul qilinganda qurilmangizning ish faoliyati yoki amallariga xalaqit qilishi mumkin"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"obunalarni o‘qish"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"“Bezovta qilinmasin” rejimi sozlamalarini ko‘rish va o‘zgartirish."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"foydalaniladigan ruxsatlar axborotini ochish"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Ilova foydalanadigan ruxsatlar axborotini ishga tushirishga ruxsat beradi. Oddiy ilovalar uchun talab qilinmaydi."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"tezkor yoqish maqsadi"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Ilova tezkor yoqish maqsadini aniqlay oladi."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Parol qoidalarini o‘rnatish"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Ekran qulfi paroli va PIN kodlari uchun qo‘yiladigan talablarni (belgilar soni va uzunligi) nazorat qiladi."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Ekranni qulfdan chiqarishga urinishlarni nazorat qilish"</string>
@@ -1227,12 +1233,12 @@
     <string name="volume_music_hint_silent_ringtone_selected" msgid="8310739960973156272">"Ovozsiz rejim tanlandi"</string>
     <string name="volume_call" msgid="3941680041282788711">"Suhbat vaqtidagi tovush balandligi"</string>
     <string name="volume_bluetooth_call" msgid="2002891926351151534">"Kiruvchi bluetooth tovushi"</string>
-    <string name="volume_alarm" msgid="1985191616042689100">"Signal tovushi balandligi"</string>
+    <string name="volume_alarm" msgid="1985191616042689100">"Signal tovushi"</string>
     <string name="volume_notification" msgid="2422265656744276715">"Eslatma tovushi"</string>
     <string name="volume_unknown" msgid="1400219669770445902">"Tovush balandligi"</string>
     <string name="volume_icon_description_bluetooth" msgid="6538894177255964340">"Bluetooth tovushi"</string>
     <string name="volume_icon_description_ringer" msgid="3326003847006162496">"Rington balandligi"</string>
-    <string name="volume_icon_description_incall" msgid="8890073218154543397">"Qo‘ng‘iroq tovushi balandligi"</string>
+    <string name="volume_icon_description_incall" msgid="8890073218154543397">"Suhbat tovushi"</string>
     <string name="volume_icon_description_media" msgid="4217311719665194215">"Multimedia tovushi"</string>
     <string name="volume_icon_description_notification" msgid="7044986546477282274">"Eslatma tovushi"</string>
     <string name="ringtone_default" msgid="3789758980357696936">"Standart rington"</string>
@@ -1362,6 +1368,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"USB orqali nosozliklarni tuzatishni o‘chirib qo‘yish uchun bosing."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Xavfsizlik sinovi rejimi yoqildi"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Xavfsizlik sinovi rejimini faolsizlantirish uchun zavod sozlamalariga qaytaring."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Davomiy port terminali yoqildi"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Samaradorlik pasaydi. Terminalni faolsizlantirish uchun operatsion tizim yuklagichini oching."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB portda suyuqlik yoki parcha bor"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB port avtomatik tarzda faolsizlashtirildi. Batafsil axborot olish uchun bosing."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB portdan foydalanish mumkin"</string>
@@ -1891,8 +1899,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Turkumlanmagan"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Siz ushbu bildirishnomalarning muhimligini belgilagansiz."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Bu odamlar siz uchun muhim."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"<xliff:g id="APP">%1$s</xliff:g> ilovasiga <xliff:g id="ACCOUNT">%2$s</xliff:g> hisobi bilan yangi foydalanuvchi yaratishiga ruxsat berilsinmi ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"<xliff:g id="APP">%1$s</xliff:g> ilovasiga <xliff:g id="ACCOUNT">%2$s</xliff:g> hisobi bilan yangi foydalanuvchi yaratishiga ruxsat berilsinmi (bunday hisobdagi foydalanuvchi allaqachon mavjud) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"<xliff:g id="APP">%1$s</xliff:g> ilovasiga <xliff:g id="ACCOUNT">%2$s</xliff:g> hisobi bilan yangi foydalanuvchi yaratishiga ruxsat berilsinmi (bunday hisobdagi foydalanuvchi allaqachon mavjud) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"<xliff:g id="APP">%1$s</xliff:g> ilovasiga <xliff:g id="ACCOUNT">%2$s</xliff:g> hisobi bilan yangi foydalanuvchi yaratishiga ruxsat berilsinmi ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Til qoʻshish"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Hudud sozlamalari"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Til nomini kiriting"</string>
diff --git a/core/res/res/values-vi/strings.xml b/core/res/res/values-vi/strings.xml
index 59b55d0..a34585b 100644
--- a/core/res/res/values-vi/strings.xml
+++ b/core/res/res/values-vi/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Cho phép ứng dụng nhận và xử lý tin nhắn SMS. Điều này có nghĩa là ứng dụng có thể theo dõi hoặc xóa tin nhắn được gửi đến thiết bị của bạn mà không hiển thị chúng cho bạn."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"nhận tin nhắn văn bản (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Cho phép ứng dụng nhận và xử lý tin nhắn MMS. Điều này có nghĩa là ứng dụng có thể theo dõi hoặc xóa tin nhắn được gửi đến thiết bị của bạn mà không hiển thị chúng cho bạn."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"đọc tin nhắn quảng bá"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Cho phép ứng dụng đọc tin nhắn quảng bá mà thiết bị của bạn nhận được. Tin nhắn quảng bá cảnh báo được gửi ở một số địa điểm nhằm cảnh báo cho bạn về các tình huống khẩn cấp. Các ứng dụng độc hại có thể gây ảnh hưởng đến hiệu suất hoặc hoạt động của thiết bị của bạn khi nhận được tin nhắn quảng bá khẩn cấp."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"đọc nguồn cấp dữ liệu đã đăng ký"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Cho phép ứng dụng đọc và ghi cấu hình Không làm phiền."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"cấp quyền xem"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Cho phép chủ sở hữu cấp quyền cho một ứng dụng. Các ứng dụng thông thường sẽ không bao giờ cần quyền này."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"đích đến của phím tắt hỗ trợ tiếp cận"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Cho phép ứng dụng xác định đích đến của phím tắt hỗ trợ tiếp cận."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Đặt quy tắc mật khẩu"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Kiểm soát độ dài và ký tự được phép trong mật khẩu khóa màn hình và mã PIN."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Giám sát những lần thử mở khóa màn hình"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Chọn để tắt chế độ gỡ lỗi qua USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Đã bật Chế độ khai thác kiểm thử"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Khôi phục cài đặt gốc để tắt Chế độ khai thác kiểm thử."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"Đã bật bảng điều khiển cổng nối tiếp"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Hiệu suất sẽ bị ảnh hưởng. Để tắt, hãy chọn trình tải khởi động."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Có chất lỏng hoặc mảnh vỡ trong cổng USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Cổng USB đã tự động tắt. Nhấn để tìm hiểu thêm."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"Có thể sử dụng cổng USB"</string>
@@ -1579,8 +1587,8 @@
     <string name="expires_on" msgid="3676242949915959821">"Hết hạn vào:"</string>
     <string name="serial_number" msgid="758814067660862493">"Số sê-ri:"</string>
     <string name="fingerprints" msgid="4516019619850763049">"Tệp tham chiếu:"</string>
-    <string name="sha256_fingerprint" msgid="4391271286477279263">"Tệp tham chiếu SHA-256:"</string>
-    <string name="sha1_fingerprint" msgid="7930330235269404581">"Tệp tham chiếu SHA-1:"</string>
+    <string name="sha256_fingerprint" msgid="4391271286477279263">"Vân tay SHA-256:"</string>
+    <string name="sha1_fingerprint" msgid="7930330235269404581">"Vân tay SHA-1:"</string>
     <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Xem tất cả"</string>
     <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Chọn hoạt động"</string>
     <string name="share_action_provider_share_with" msgid="5247684435979149216">"Chia sẻ với"</string>
@@ -1672,8 +1680,8 @@
     <string name="accessibility_shortcut_disabling_service" msgid="2747243438223109821">"Đã tắt phím tắt trợ năng <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_shortcut_spoken_feedback" msgid="8376923232350078434">"Nhấn và giữ đồng thời cả hai phím âm lượng trong 3 giây để sử dụng <xliff:g id="SERVICE_NAME">%1$s</xliff:g>"</string>
     <string name="accessibility_button_prompt_text" msgid="1176658502969738564">"Chọn dịch vụ sẽ sử dụng khi bạn nhấn vào nút hỗ trợ tiếp cận:"</string>
-    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Chọn dịch vụ sẽ sử dụng với cử chỉ hỗ trợ tiếp cận (vuốt lên từ cuối màn hình bằng 2 ngón tay):"</string>
-    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Chọn dịch vụ sẽ sử dụng với cử chỉ hỗ trợ tiếp cận (vuốt lên từ cuối màn hình bằng 3 ngón tay):"</string>
+    <string name="accessibility_gesture_prompt_text" msgid="8259145549733019401">"Chọn dịch vụ sẽ sử dụng với cử chỉ hỗ trợ tiếp cận này (vuốt lên từ cuối màn hình bằng 2 ngón tay):"</string>
+    <string name="accessibility_gesture_3finger_prompt_text" msgid="1041435574275047665">"Chọn dịch vụ sẽ sử dụng với cử chỉ hỗ trợ tiếp cận này (vuốt lên từ cuối màn hình bằng 3 ngón tay):"</string>
     <string name="accessibility_button_instructional_text" msgid="7003212763213614833">"Để chuyển đổi giữa các dịch vụ, hãy chạm và giữ nút hỗ trợ tiếp cận."</string>
     <string name="accessibility_gesture_instructional_text" msgid="5261788874937410950">"Để chuyển đổi giữa các dịch vụ, hãy vuốt lên và giữ bằng 2 ngón tay."</string>
     <string name="accessibility_gesture_3finger_instructional_text" msgid="4969448938984394550">"Để chuyển đổi giữa các dịch vụ, hãy vuốt lên và giữ bằng 3 ngón tay."</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Chưa được phân loại"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Bạn đặt tầm quan trọng của các thông báo này."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Thông báo này quan trọng vì những người có liên quan."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Cho phép <xliff:g id="APP">%1$s</xliff:g> tạo người dùng mới bằng <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Cho phép <xliff:g id="APP">%1$s</xliff:g> tạo người dùng mới bằng <xliff:g id="ACCOUNT">%2$s</xliff:g> (người dùng có tài khoản này đã tồn tại)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Cho phép <xliff:g id="APP">%1$s</xliff:g> tạo người dùng mới bằng <xliff:g id="ACCOUNT">%2$s</xliff:g> (đã tồn tại người dùng có tài khoản này)?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Cho phép <xliff:g id="APP">%1$s</xliff:g> tạo người dùng mới bằng <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Thêm ngôn ngữ"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Tùy chọn khu vực"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Nhập tên ngôn ngữ"</string>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index d8b18d3..64e0a1b 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -283,7 +283,7 @@
     <string name="permgrouprequest_contacts" msgid="6032805601881764300">"允许&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;访问您的通讯录吗?"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"位置信息"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"获取此设备的位置信息"</string>
-    <string name="permgrouprequest_location" msgid="3788275734953323491">"允许“<xliff:g id="APP_NAME">%1$s</xliff:g>”获取此设备的位置信息吗?"</string>
+    <string name="permgrouprequest_location" msgid="3788275734953323491">"要允许“<xliff:g id="APP_NAME">%1$s</xliff:g>”获取此设备的位置信息吗?"</string>
     <string name="permgrouprequestdetail_location" msgid="1347189607421252902">"只有当您使用该应用时,该应用才有权访问位置信息"</string>
     <string name="permgroupbackgroundrequest_location" msgid="5039063878675613235">"要&lt;b&gt;一律允许&lt;/b&gt;允许&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;访问此设备的位置信息吗?"</string>
     <string name="permgroupbackgroundrequestdetail_location" msgid="4597006851453417387">"目前只有当您使用该应用时,该应用才能访问位置信息"</string>
@@ -292,7 +292,7 @@
     <string name="permgrouprequest_calendar" msgid="289900767793189421">"允许&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;访问您的日历吗?"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"短信"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"发送和查看短信"</string>
-    <string name="permgrouprequest_sms" msgid="7168124215838204719">"允许&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;发送和查看短信吗?"</string>
+    <string name="permgrouprequest_sms" msgid="7168124215838204719">"要允许&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt;发送和查看短信吗?"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"存储空间"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"访问您设备上的照片、媒体内容和文件"</string>
     <string name="permgrouprequest_storage" msgid="7885942926944299560">"允许“<xliff:g id="APP_NAME">%1$s</xliff:g>”&lt;b&gt;&lt;/b&gt;访问您设备上的照片、媒体内容和文件吗?"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"允许该应用接收和处理短信。这就意味着,该应用可能会监视发送到您设备的短信,或删除发送到您设备的短信而不向您显示。"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"接收讯息(彩信)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"允许该应用接收和处理彩信。这就意味着,该应用可能会监视发送到您设备的彩信,或删除发送到您设备的彩信而不向您显示。"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"读取小区广播消息"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"允许应用读取您的设备收到的小区广播消息。小区广播消息是在某些地区发送的、用于发布紧急情况警告的提醒信息。恶意应用可能会在您收到小区紧急广播时干扰您设备的性能或操作。"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"读取订阅的供稿"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"允许此应用读取和写入“勿扰”模式配置。"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"授权使用“查看权限”"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"允许该应用开始查看应用的权限使用情况(普通应用绝不需要此权限)。"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"无障碍功能快捷方式目标"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"允许应用定义无障碍功能快捷方式目标。"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"设置密码规则"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"控制锁屏密码和 PIN 码所允许的长度和字符。"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"监控屏幕解锁尝试次数"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"选择即可停用 USB 调试功能。"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"自动化测试框架模式已启用"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"恢复出厂设置以停用自动化测试框架模式。"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"已启用序列控制台"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"性能受到影响。要停用,请查看引导加载程序。"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB 端口中有液体或碎屑"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB 端口已自动停用。点按即可了解详情。"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"允许使用 USB 端口"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"未分类"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"这些通知的重要程度由您来设置。"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"这条通知涉及特定的人,因此被归为重要通知。"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 创建新用户吗?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g>(目前已有用户使用此帐号)创建新用户吗?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g>(目前已有用户使用此帐号)创建新用户吗?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 创建新用户吗?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"添加语言"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"区域偏好设置"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"输入语言名称"</string>
diff --git a/core/res/res/values-zh-rHK/strings.xml b/core/res/res/values-zh-rHK/strings.xml
index 1a73904..67a7dbb 100644
--- a/core/res/res/values-zh-rHK/strings.xml
+++ b/core/res/res/values-zh-rHK/strings.xml
@@ -201,7 +201,7 @@
     <string name="turn_on_radio" msgid="3912793092339962371">"開啟無線網絡"</string>
     <string name="turn_off_radio" msgid="8198784949987062346">"關閉無線網絡"</string>
     <string name="screen_lock" msgid="799094655496098153">"螢幕鎖定"</string>
-    <string name="power_off" msgid="4266614107412865048">"關閉"</string>
+    <string name="power_off" msgid="4266614107412865048">"關機"</string>
     <string name="silent_mode_silent" msgid="319298163018473078">"鈴聲關閉"</string>
     <string name="silent_mode_vibrate" msgid="7072043388581551395">"鈴聲震動"</string>
     <string name="silent_mode_ring" msgid="8592241816194074353">"鈴聲開啟"</string>
@@ -225,7 +225,7 @@
     <string name="global_actions" product="tv" msgid="9091480417912345975">"Android TV 選項"</string>
     <string name="global_actions" product="default" msgid="2406416831541615258">"手機選項"</string>
     <string name="global_action_lock" msgid="2844945191792119712">"螢幕鎖定"</string>
-    <string name="global_action_power_off" msgid="4471879440839879722">"關閉"</string>
+    <string name="global_action_power_off" msgid="4471879440839879722">"關機"</string>
     <string name="global_action_emergency" msgid="7112311161137421166">"緊急"</string>
     <string name="global_action_bug_report" msgid="7934010578922304799">"錯誤報告"</string>
     <string name="global_action_logout" msgid="935179188218826050">"結束工作階段"</string>
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"允許應用程式接收和處理短訊。這表示應用程式可監控傳送至您裝置的訊息,或在您閱讀訊息前擅自刪除訊息。"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"接收短訊 (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"允許應用程式接收和處理 MMS 訊息。這表示應用程式可監控傳送至您裝置的訊息,或在您閱讀訊息前擅自刪除訊息。"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"讀取區域廣播訊息"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"允許應用程式讀取您裝置接收的區域廣播訊息。某些地點會發出區域廣播警報,警告您發生緊急狀況。惡意應用程式可能會在裝置收到緊急區域廣播時,干擾裝置的性能或運作。"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"讀取訂閱的資訊提供"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"允許應用程式讀取和寫入「請勿騷擾」設定。"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"開始查看權限使用情況"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"允許應用程式開始查看應用程式的權限使用情況 (一般應用程式並不需要)。"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"無障礙功能捷徑目標位置"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"允許應用程式定義無障礙功能捷徑目標位置。"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"設定密碼規則"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"控制螢幕鎖定密碼和 PIN 所允許的長度和字元。"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"監控螢幕解鎖嘗試次數"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"選取即可停用 USB 偵錯。"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"已啟用測試工具模式"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"請將裝置回復原廠設定,以停用測試工具模式。"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"已啟用序列控制器"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"效能受到影響,勾選啟動程式即可停用。"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB 連接埠中有液體或碎片"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"USB 連接埠已自動停用。輕按即可瞭解詳情。"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"USB 連接埠可安全使用"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"未分類"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"您可以設定這些通知的重要性。"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"列為重要的原因:涉及的人。"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"要允許 <xliff:g id="APP">%1$s</xliff:g> 使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者嗎?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"要允許 <xliff:g id="APP">%1$s</xliff:g> 使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者 (此帳戶目前已有此使用者) 嗎?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"要允許 <xliff:g id="APP">%1$s</xliff:g> 使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者 (此帳戶目前已有此使用者) 嗎?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"要允許 <xliff:g id="APP">%1$s</xliff:g> 使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者嗎?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"新增語言"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"地區偏好設定"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"輸入語言名稱"</string>
diff --git a/core/res/res/values-zh-rTW/strings.xml b/core/res/res/values-zh-rTW/strings.xml
index 8f8b758..923a23f 100644
--- a/core/res/res/values-zh-rTW/strings.xml
+++ b/core/res/res/values-zh-rTW/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"允許應用程式接收和處理簡訊。這項設定可讓應用程式監控傳送至你裝置的訊息,或在你閱讀訊息前擅自刪除訊息。"</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"接收簡訊 (MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"允許應用程式接收和處理多媒體訊息。這項設定可讓應用程式監控傳送至你裝置的訊息,或在你閱讀訊息前擅自刪除訊息。"</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"讀取區域廣播訊息"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"允許應用程式讀取你裝置收到的區域廣播訊息。某些地點會發出區域廣播警示,警告你有緊急狀況發生。請注意,惡意應用程式可能會在裝置收到緊急區域廣播時,干擾裝置的效能或運作。"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"讀取訂閱資訊提供"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"允許應用程式讀取及寫入「零打擾」設定。"</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"啟動檢視權限用途"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"允許應用程式開始使用其他應用程式 (一般應用程式並不需要)。"</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"指定無障礙捷徑目標"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"允許應用程式定義指定的無障礙捷徑目標。"</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"設定密碼規則"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"管理螢幕鎖定密碼和 PIN 碼支援的字元和長度上限。"</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"監控螢幕解鎖嘗試次數"</string>
@@ -1361,10 +1367,12 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"選取這個選項以停用 USB 偵錯功能。"</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"測試控管工具模式已啟用"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"恢復原廠設定以停用測試控管工具模式。"</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"已啟用序列主控台"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"效能已受到影響。如要停用,請檢查系統啟動載入程式。"</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"USB 連接埠中有液體或灰塵"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"系統已自動停用 USB 連接埠。輕觸即可瞭解詳情。"</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"現在可以使用 USB 連接埠"</string>
-    <string name="usb_contaminant_not_detected_message" msgid="2415791798244545292">"手機目前無法偵測液體或灰塵。"</string>
+    <string name="usb_contaminant_not_detected_message" msgid="2415791798244545292">"手機目前沒有偵測到液體或灰塵。"</string>
     <string name="taking_remote_bugreport_notification_title" msgid="6742483073875060934">"正在接收錯誤報告…"</string>
     <string name="share_remote_bugreport_notification_title" msgid="4987095013583691873">"要分享錯誤報告嗎?"</string>
     <string name="sharing_remote_bugreport_notification_title" msgid="7572089031496651372">"正在分享錯誤報告…"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"未分類"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"這些通知的重要性由你決定。"</string>
     <string name="importance_from_person" msgid="9160133597262938296">"這則通知涉及特定人士,因此被歸為重要通知。"</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"要允許 <xliff:g id="APP">%1$s</xliff:g> 為 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者嗎?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"要允許 <xliff:g id="APP">%1$s</xliff:g> 為 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者嗎 (這個帳戶目前已有使用者)?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"要允許「<xliff:g id="APP">%1$s</xliff:g>」替 <xliff:g id="ACCOUNT">%2$s</xliff:g> (這個帳戶目前已有使用者) 建立新使用者嗎?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"要允許「<xliff:g id="APP">%1$s</xliff:g>」替 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者嗎?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"新增語言"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"地區偏好設定"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"請輸入語言名稱"</string>
diff --git a/core/res/res/values-zu/strings.xml b/core/res/res/values-zu/strings.xml
index 4c37933..04091ff 100644
--- a/core/res/res/values-zu/strings.xml
+++ b/core/res/res/values-zu/strings.xml
@@ -344,6 +344,10 @@
     <string name="permdesc_receiveSms" msgid="6424387754228766939">"Ivumela uhlelo lokusebenza ukuthola nokucubungula imilayezo ye-SMS. Loku kuchaza ukuthi uhlelo lokusebenza lungangamela noma lesuse imilayezo ethunyelwe kudivayisi yakho ngaphandle kokukubonisa yona."</string>
     <string name="permlab_receiveMms" msgid="1821317344668257098">"thola imiyalezo ebhaliwe (i-MMS)"</string>
     <string name="permdesc_receiveMms" msgid="533019437263212260">"Ivumela uhlelo lokusebenza ukuthola nokucubungula imilayezo ye-MMS. Loku kuchaza ukuthi uhlelo lokusebenza lungangamela noma lesuse imilayezo ethunyelwe kudivayisi yakho ngaphandle kokukubonisa yona."</string>
+    <!-- no translation found for permlab_bindCellBroadcastService (4468585041824555604) -->
+    <skip />
+    <!-- no translation found for permdesc_bindCellBroadcastService (9073440260695196089) -->
+    <skip />
     <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"funda imilayezo yokusakaza yeselula"</string>
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Ivumela uhlelo lokusebenza ukufunda imilayezo yokusakaza yeselula etholwe idivayisi yakho. Izaziso zokusakaza zeselula zilethwa kwezinye izindawo ukukuxwayisa ngezimo ezisheshayo. Izinhlelo zokusebenza ezingalungile zingaphazamisana nokusebenza noma umsebenzi wedivayisi yakho uma ukusakaza kweselula kwesimo esisheshayo kutholwa."</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"funda izifunzo ezikhokhelwayo"</string>
@@ -655,6 +659,8 @@
     <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Ivumela izinhlelo zokusebenza ukufunda nokubhala ukulungiswa kokuthi Ungaphazamisi."</string>
     <string name="permlab_startViewPermissionUsage" msgid="5484728591597709944">"qala ukusetshenziswa kokubuka imvume"</string>
     <string name="permdesc_startViewPermissionUsage" msgid="4808345878203594428">"Ivumela umphathi ukuthi aqale ukusetshenziswa kwemvume kohlelo lokusebenza. Akumele idingelwe izinhlelo zokusebenza ezijwayelekile."</string>
+    <string name="permlab_accessibilityShortcutTarget" msgid="1385930065395622809">"impokophelo yesinqamuleli sokufinyeleleka"</string>
+    <string name="permdesc_accessibilityShortcutTarget" msgid="562750894417800432">"Ivumela uhlelo lokusebenza ukuthi luchaze impokophelo yesinqamuleli sokufinyeleleka."</string>
     <string name="policylab_limitPassword" msgid="4497420728857585791">"Misa imithetho yephasiwedi"</string>
     <string name="policydesc_limitPassword" msgid="2502021457917874968">"Lawula ubude nezinhlamvu ezivunyelwe kumaphasiwedi wokukhiya isikrini nama-PIN."</string>
     <string name="policylab_watchLogin" msgid="5091404125971980158">"Qapha imizamo yokuvula isikrini sakho"</string>
@@ -1361,6 +1367,8 @@
     <string name="adb_active_notification_message" product="tv" msgid="8470296818270110396">"Khetha ukuvimbela ukulungisa iphutha le-USB."</string>
     <string name="test_harness_mode_notification_title" msgid="2216359742631914387">"Imodi yokuhlola i-harness inikwe amandla"</string>
     <string name="test_harness_mode_notification_message" msgid="1343197173054407119">"Yenza ukusetha kabusha kwasekuqaleni ukuze ukhubaze imodi yokuqina yokuhlola."</string>
+    <string name="console_running_notification_title" msgid="4955436518220103382">"I-serial console inikwe amandla"</string>
+    <string name="console_running_notification_message" msgid="1331995933976263865">"Ukusebenza kuyathinteka. Ukuze ukhubaze, hlola i-bootloader."</string>
     <string name="usb_contaminant_detected_title" msgid="7136400633704058349">"Uketshezi noma ama-debris kumbobo ye-USB"</string>
     <string name="usb_contaminant_detected_message" msgid="832337061059487250">"Imbobo ye-USB inqanyulwa ngokuzenzakalela. Thepha ukuze ufunde kabanzi."</string>
     <string name="usb_contaminant_not_detected_title" msgid="7708281124088684821">"KULUNGILE ukusebenzisa imbobo ye-USB"</string>
@@ -1890,8 +1898,8 @@
     <string name="default_notification_channel_label" msgid="5929663562028088222">"Akufakwanga esigabeni"</string>
     <string name="importance_from_user" msgid="7318955817386549931">"Usethe ukubaluleka kwalezi zaziso."</string>
     <string name="importance_from_person" msgid="9160133597262938296">"Lokhu kubalulekile ngenxa yabantu ababandakanyekayo."</string>
-    <string name="user_creation_account_exists" msgid="1942606193570143289">"Vumela i-<xliff:g id="APP">%1$s</xliff:g> ukudala umsebenzisi omusha nge-<xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
-    <string name="user_creation_adding" msgid="4482658054622099197">"Vumela i-<xliff:g id="APP">%1$s</xliff:g> ukudala umsebenzisi omusha nge-<xliff:g id="ACCOUNT">%2$s</xliff:g> (umsebenzisi onale akhawunti usuvel ukhona) ?"</string>
+    <string name="user_creation_account_exists" msgid="6559477114648176531">"Vumela i-<xliff:g id="APP">%1$s</xliff:g> ukuthi idale umsebenzisi omusha nge-<xliff:g id="ACCOUNT">%2$s</xliff:g> (Umsebenzisi onale akhawunti usevele ukhona) ?"</string>
+    <string name="user_creation_adding" msgid="9089159170398841763">"Vumela i-<xliff:g id="APP">%1$s</xliff:g> ukuthi idale umsebenzisi omusha nge-<xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
     <string name="language_selection_title" msgid="2680677278159281088">"Engeza ulwimi"</string>
     <string name="country_selection_title" msgid="2954859441620215513">"Okuncamelayo kwesifunda"</string>
     <string name="search_language_hint" msgid="7042102592055108574">"Thayipha igama lolimi"</string>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 0c9ae85..14f5d97 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -3755,6 +3755,16 @@
         <attr name="summary" />
     </declare-styleable>
 
+    <!-- Use <code>accessibility-shortcut-target</code> as the root tag of the XML resource that
+         describes an activity, which is referenced from the
+         <code>android.accessibilityshortcut.target</code> meta-data entry. -->
+    <declare-styleable name="AccessibilityShortcutTarget">
+        <!-- Short description of the target of accessibility shortcut purpose or behavior.-->
+        <attr name="description" />
+        <!-- Brief summary of the target of accessibility shortcut purpose or behavior. -->
+        <attr name="summary" />
+    </declare-styleable>
+
     <!-- Use <code>print-service</code> as the root tag of the XML resource that
          describes an {@link android.printservice.PrintService} service, which is
          referenced from its {@link android.printservice.PrintService#SERVICE_META_DATA}
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 3ea8a77..381ed7f 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -349,10 +349,10 @@
          will be given a single shared user ID, so they can for example run
          in the same process.  Note that for them to actually get the same
          user ID, they must also be signed with the same signature.
-         @deprecated Shared user id's cause non-deterministic behaviour within the
-         package manager. As such, it's use is discouraged, deprecated, and will
-         be removed altogether in a future version of Android. Instead, proper
-         communication mechanisms such as services and providers should be used
+         @deprecated Shared user IDs cause non-deterministic behavior within the
+         package manager. As such, its use is strongly discouraged and may be
+         removed in a future version of Android. Instead, apps should use proper
+         communication mechanisms, such as services and content providers,
          to facilitate interoperability between shared components. -->
     <attr name="sharedUserId" format="string" />
 
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 5fd53de..3fef7a2d 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -433,6 +433,18 @@
         -->
     </string-array>
 
+    <!-- Configuration of network interfaces that support WakeOnLAN -->
+    <string-array translatable="false" name="config_wakeonlan_supported_interfaces">
+        <!--
+        <item>wlan0</item>
+        <item>eth0</item>
+        -->
+    </string-array>
+
+    <!-- Package name for the default CellBroadcastService module [DO NOT TRANSLATE] -->
+    <string name="cellbroadcast_default_package" translatable="false">com.android.cellbroadcastreceiver
+    </string>
+
     <!-- If the mobile hotspot feature requires provisioning, a package name and class name
         can be provided to launch a supported application that provisions the devices.
 
@@ -2527,6 +2539,16 @@
          will be locked. -->
     <bool name="config_multiuserDelayUserDataLocking">false</bool>
 
+    <!-- Whether to only install system packages on a user if they're whitelisted for that user
+         type. These are flags and can be freely combined.
+         0 (0b000) - disable whitelist (install all system packages; no logging)
+         1 (0b001) - enforce (only install system packages if they are whitelisted)
+         2 (0b010) - log (log when a non-whitelisted package is run)
+         4 (0b100) - treat any package not mentioned in the whitelist file as implicitly whitelisted
+        Note: This list must be kept current with PACKAGE_WHITELIST_MODE_PROP in
+        frameworks/base/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java -->
+    <integer name="config_userTypePackageWhitelistMode">5</integer> <!-- 0b101 -->
+
     <!-- Whether UI for multi user should be shown -->
     <bool name="config_enableMultiUserUI">false</bool>
 
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index d2989d9..bf5f706 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -890,6 +890,16 @@
       messages. This means the app could monitor or delete messages sent to your
       device without showing them to you.</string>
 
+    <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this.[CHAR LIMIT=NONE] -->
+    <string name="permlab_bindCellBroadcastService">Forward cell broadcast messages</string>
+    <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR LIMIT=NONE] -->
+    <string name="permdesc_bindCellBroadcastService">Allows the app to bind to the
+        cell broadcast module in order to forward cell broadcast messages
+        as they are received. Cell broadcast alerts are delivered in some
+        locations to warn you of emergency situations. Malicious apps may
+        interfere with the performance or operation of your device when an
+        emergency cell broadcast is received.</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_readCellBroadcasts">read cell broadcast messages</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
@@ -3629,6 +3639,11 @@
     <!-- Message of notification shown when Test Harness Mode is enabled. [CHAR LIMIT=NONE] -->
     <string name="test_harness_mode_notification_message">Perform a factory reset to disable Test Harness Mode.</string>
 
+    <!-- Title of notification shown when serial console is enabled. [CHAR LIMIT=NONE] -->
+    <string name="console_running_notification_title">Serial console enabled</string>
+    <!-- Message of notification shown when serial console is enabled. [CHAR LIMIT=NONE] -->
+    <string name="console_running_notification_message">Performance is impacted. To disable, check bootloader.</string>
+
     <!-- Title of notification shown when contaminant is detected on the USB port. [CHAR LIMIT=NONE] -->
     <string name="usb_contaminant_detected_title">Liquid or debris in USB port</string>
     <!-- Message of notification shown when contaminant is detected on the USB port. [CHAR LIMIT=NONE] -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 761e02f..363bc9d 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -511,6 +511,7 @@
   <java-symbol type="integer" name="config_multiuserMaximumUsers" />
   <java-symbol type="integer" name="config_multiuserMaxRunningUsers" />
   <java-symbol type="bool" name="config_multiuserDelayUserDataLocking" />
+  <java-symbol type="integer" name="config_userTypePackageWhitelistMode"/>
   <java-symbol type="integer" name="config_safe_media_volume_index" />
   <java-symbol type="integer" name="config_safe_media_volume_usb_mB" />
   <java-symbol type="integer" name="config_mobile_mtu" />
@@ -746,6 +747,8 @@
   <java-symbol type="string" name="config_default_dns_server" />
   <java-symbol type="string" name="config_ethernet_iface_regex" />
   <java-symbol type="array" name="config_ethernet_interfaces" />
+  <java-symbol type="array" name="config_wakeonlan_supported_interfaces" />
+  <java-symbol type="string" name="cellbroadcast_default_package" />
   <java-symbol type="string" name="config_forceVoiceInteractionServicePackage" />
   <java-symbol type="string" name="config_mms_user_agent" />
   <java-symbol type="string" name="config_mms_user_agent_profile_url" />
@@ -1880,15 +1883,14 @@
   <java-symbol type="anim" name="screen_rotate_180_enter" />
   <java-symbol type="anim" name="screen_rotate_180_exit" />
   <java-symbol type="anim" name="screen_rotate_180_frame" />
+  <java-symbol type="anim" name="screen_rotate_alpha"/>
   <java-symbol type="anim" name="screen_rotate_finish_enter" />
   <java-symbol type="anim" name="screen_rotate_finish_exit" />
   <java-symbol type="anim" name="screen_rotate_finish_frame" />
   <java-symbol type="anim" name="screen_rotate_minus_90_enter" />
   <java-symbol type="anim" name="screen_rotate_minus_90_exit" />
-  <java-symbol type="anim" name="screen_rotate_minus_90_frame" />
   <java-symbol type="anim" name="screen_rotate_plus_90_enter" />
   <java-symbol type="anim" name="screen_rotate_plus_90_exit" />
-  <java-symbol type="anim" name="screen_rotate_plus_90_frame" />
   <java-symbol type="anim" name="screen_rotate_start_enter" />
   <java-symbol type="anim" name="screen_rotate_start_exit" />
   <java-symbol type="anim" name="screen_rotate_start_frame" />
@@ -2093,6 +2095,8 @@
   <java-symbol type="string" name="adb_active_notification_title" />
   <java-symbol type="string" name="test_harness_mode_notification_title" />
   <java-symbol type="string" name="test_harness_mode_notification_message" />
+  <java-symbol type="string" name="console_running_notification_title" />
+  <java-symbol type="string" name="console_running_notification_message" />
   <java-symbol type="string" name="taking_remote_bugreport_notification_title" />
   <java-symbol type="string" name="share_remote_bugreport_notification_title" />
   <java-symbol type="string" name="sharing_remote_bugreport_notification_title" />
diff --git a/core/tests/bugreports/Android.bp b/core/tests/bugreports/Android.bp
index d3bf0dd..e9d5bb1 100644
--- a/core/tests/bugreports/Android.bp
+++ b/core/tests/bugreports/Android.bp
@@ -20,7 +20,6 @@
         "android.test.base",
     ],
     static_libs: ["androidx.test.rules", "truth-prebuilt"],
-    test_suites: ["general-tests"],
     sdk_version: "test_current",
     platform_apis: true,
 }
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 2417209..c7e54f3 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -1155,7 +1155,10 @@
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+                <category android:name="android.intent.category.ACCESSIBILITY_SHORTCUT_TARGET" />
             </intent-filter>
+            <meta-data android:name="android.accessibilityshortcut.target"
+                       android:resource="@xml/accessibility_shortcut_test_activity"/>
         </activity>
 
         <!-- Activity-level metadata -->
diff --git a/core/tests/coretests/res/values/strings.xml b/core/tests/coretests/res/values/strings.xml
index ef915bb..f630188 100644
--- a/core/tests/coretests/res/values/strings.xml
+++ b/core/tests/coretests/res/values/strings.xml
@@ -142,4 +142,10 @@
 
     <!-- ResourcesLocaleResolutionTest -->
     <string name="dummy_string">dummy string</string>
+
+    <!-- Description of the accessibility shortcut [CHAR LIMIT=NONE] -->
+    <string name="accessibility_shortcut_description">Accessibility shortcut description</string>
+
+    <!-- Summary of the accessibility shortcut [CHAR LIMIT=NONE] -->
+    <string name="accessibility_shortcut_summary">Accessibility shortcut summary</string>
 </resources>
diff --git a/core/tests/coretests/res/xml/accessibility_shortcut_test_activity.xml b/core/tests/coretests/res/xml/accessibility_shortcut_test_activity.xml
new file mode 100644
index 0000000..60e2998
--- /dev/null
+++ b/core/tests/coretests/res/xml/accessibility_shortcut_test_activity.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<accessibility-shortcut-target xmlns:android="http://schemas.android.com/apk/res/android"
+                        android:description="@string/accessibility_shortcut_description"
+                        android:summary="@string/accessibility_shortcut_summary"
+/>
\ No newline at end of file
diff --git a/core/tests/coretests/src/android/accessibilityservice/AccessibilityShortcutInfoTest.java b/core/tests/coretests/src/android/accessibilityservice/AccessibilityShortcutInfoTest.java
new file mode 100644
index 0000000..abaeb0a
--- /dev/null
+++ b/core/tests/coretests/src/android/accessibilityservice/AccessibilityShortcutInfoTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2019 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.accessibilityservice;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.view.accessibility.AccessibilityManager;
+import android.view.accessibility.AccessibilityTestActivity;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.frameworks.coretests.R;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+
+/**
+ * AccessibilityShortcutInfo can only be created by system. Verify the instance creation and
+ * basic function here.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class AccessibilityShortcutInfoTest {
+    private Context mTargetContext;
+    private PackageManager mPackageManager;
+    private AccessibilityShortcutInfo mShortcutInfo;
+
+    @Before
+    public void setUp() {
+        mTargetContext = InstrumentationRegistry.getInstrumentation()
+                .getTargetContext();
+        mPackageManager = mTargetContext.getPackageManager();
+
+        final ComponentName testShortcutName = new ComponentName(mTargetContext,
+                AccessibilityTestActivity.class);
+        final AccessibilityManager accessibilityManager = (AccessibilityManager) mTargetContext
+                .getSystemService(Context.ACCESSIBILITY_SERVICE);
+        final List<AccessibilityShortcutInfo> infoList = accessibilityManager
+                .getInstalledAccessibilityShortcutListAsUser(
+                        mTargetContext, mTargetContext.getUserId());
+        for (AccessibilityShortcutInfo info : infoList) {
+            final ActivityInfo activityInfo = info.getActivityInfo();
+            final ComponentName name = new ComponentName(
+                    activityInfo.packageName, activityInfo.name);
+            if (name.equals(testShortcutName)) {
+                mShortcutInfo = info;
+                break;
+            }
+        }
+
+        assertNotNull("Can't find " + testShortcutName, mShortcutInfo);
+    }
+
+    @Test
+    public void testDescription() {
+        final String description = mTargetContext.getResources()
+                .getString(R.string.accessibility_shortcut_description);
+
+        assertNotNull("Can't find description string", description);
+        assertThat("Description is not correct",
+                mShortcutInfo.loadDescription(mPackageManager), is(description));
+    }
+
+    @Test
+    public void testSummary() {
+        final String summary = mTargetContext.getResources()
+                .getString(R.string.accessibility_shortcut_summary);
+
+        assertNotNull("Can't find summary string", summary);
+        assertThat("Summary is not correct",
+                mShortcutInfo.loadSummary(mPackageManager), is(summary));
+    }
+}
diff --git a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
index 51da0c8..39bf742 100644
--- a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
+++ b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
@@ -611,6 +611,10 @@
         }
 
         @Override
+        public void attachStartupAgents(String s) throws RemoteException {
+        }
+
+        @Override
         public void scheduleApplicationInfoChanged(ApplicationInfo applicationInfo)
                 throws RemoteException {
         }
diff --git a/core/tests/coretests/src/android/app/usage/UsageStatsTest.java b/core/tests/coretests/src/android/app/usage/UsageStatsTest.java
index 6ec3dc9..0ac00b8 100644
--- a/core/tests/coretests/src/android/app/usage/UsageStatsTest.java
+++ b/core/tests/coretests/src/android/app/usage/UsageStatsTest.java
@@ -173,7 +173,7 @@
         left.update("com.test.activity1", 400000, ACTIVITY_STOPPED, 1);
         assertEquals(left.mLastTimeUsed, 350000);
         assertEquals(left.mLastTimeVisible, 400000);
-        assertEquals(left.mActivities.get(1), ACTIVITY_STOPPED);
+        assertTrue(left.mActivities.indexOfKey(1) < 0);
         assertEquals(left.mTotalTimeInForeground, 350000 - 200000);
         assertEquals(left.mTotalTimeVisible, 400000 - 200000);
 
@@ -231,7 +231,7 @@
         left.update("com.test.activity1", 400000, ACTIVITY_STOPPED, 1);
         assertEquals(left.mLastTimeUsed, 300000);
         assertEquals(left.mLastTimeVisible, 400000);
-        assertEquals(left.mActivities.get(1), ACTIVITY_STOPPED);
+        assertTrue(left.mActivities.indexOfKey(1) < 0);
         assertEquals(left.mTotalTimeInForeground, 300000 - 200000);
         assertEquals(left.mTotalTimeVisible, 400000 - 100000);
     }
@@ -249,7 +249,7 @@
         left.update("com.test.activity1", 200000, ACTIVITY_STOPPED, 1);
         assertEquals(left.mLastTimeUsed, 200000);
         assertEquals(left.mLastTimeVisible, 200000);
-        assertEquals(left.mActivities.get(1), ACTIVITY_STOPPED);
+        assertTrue(left.mActivities.indexOfKey(1) < 0);
         assertEquals(left.mTotalTimeInForeground, 200000 - 100000);
         assertEquals(left.mTotalTimeVisible, 200000 - 100000);
 
@@ -359,14 +359,14 @@
         left.update("com.test.activity1", 550000, ACTIVITY_STOPPED, 1);
         assertEquals(left.mLastTimeUsed, 450000);
         assertEquals(left.mLastTimeVisible, 550000);
-        assertEquals(left.mActivities.get(1), ACTIVITY_STOPPED);
+        assertTrue(left.mActivities.indexOfKey(1) < 0);
         assertEquals(left.mTotalTimeInForeground, 350000);
         assertEquals(left.mTotalTimeVisible, 350000 + 100000 /*550000 - 450000*/);
 
         left.update("com.test.activity2", 650000, ACTIVITY_STOPPED, 2);
         assertEquals(left.mLastTimeUsed, 450000);
         assertEquals(left.mLastTimeVisible, 650000);
-        assertEquals(left.mActivities.get(2), ACTIVITY_STOPPED);
+        assertTrue(left.mActivities.indexOfKey(2) < 0);
         assertEquals(left.mTotalTimeInForeground, 350000);
         assertEquals(left.mTotalTimeVisible, 450000 + 100000 /*650000 - 550000*/);
     }
diff --git a/core/tests/coretests/src/android/content/pm/AndroidTelephonyCommonUpdaterTest.java b/core/tests/coretests/src/android/content/pm/AndroidTelephonyCommonUpdaterTest.java
deleted file mode 100644
index 8ab9ddb..0000000
--- a/core/tests/coretests/src/android/content/pm/AndroidTelephonyCommonUpdaterTest.java
+++ /dev/null
@@ -1,140 +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 android.content.pm;
-
-import static android.content.pm.PackageBuilder.builder;
-import static android.content.pm.SharedLibraryNames.ANDROID_HIDL_BASE;
-import static android.content.pm.SharedLibraryNames.ANDROID_HIDL_MANAGER;
-import static android.content.pm.SharedLibraryNames.ANDROID_TELEPHONY_COMMON;
-
-import android.os.Build;
-import androidx.test.filters.SmallTest;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-/**
- * Test for {@link AndroidHidlUpdater}
- */
-@SmallTest
-@RunWith(JUnit4.class)
-public class AndroidTelephonyCommonUpdaterTest extends PackageSharedLibraryUpdaterTest {
-
-    private static final String OTHER_LIBRARY = "other.library";
-    private static final String PHONE_UID = "android.uid.phone";
-
-    @Test
-    public void targeted_at_Q() {
-        PackageBuilder before = builder()
-                .targetSdkVersion(Build.VERSION_CODES.Q);
-
-        PackageBuilder after = builder().targetSdkVersion(Build.VERSION_CODES.Q)
-            .requiredLibraries(ANDROID_TELEPHONY_COMMON);
-
-        // Should add telephony-common libraries
-        checkBackwardsCompatibility(before, after);
-    }
-
-    @Test
-    public void targeted_at_Q_phoneUID() {
-        PackageBuilder before = builder().setSharedUid(PHONE_UID)
-                .targetSdkVersion(Build.VERSION_CODES.Q);
-
-        // Should add telephony-common libraries
-        PackageBuilder after = builder().setSharedUid(PHONE_UID)
-                .targetSdkVersion(Build.VERSION_CODES.Q)
-                .requiredLibraries(ANDROID_TELEPHONY_COMMON);
-
-        checkBackwardsCompatibility(before, after);
-    }
-
-    @Test
-    public void targeted_at_Q_not_empty_usesLibraries() {
-        PackageBuilder before = builder()
-                .targetSdkVersion(Build.VERSION_CODES.Q)
-                .requiredLibraries(OTHER_LIBRARY);
-
-        // no change
-        checkBackwardsCompatibility(before, before);
-    }
-
-    @Test
-    public void targeted_at_Q_not_empty_usesLibraries_phoneUID() {
-        PackageBuilder before = builder().setSharedUid(PHONE_UID)
-                .targetSdkVersion(Build.VERSION_CODES.Q)
-                .requiredLibraries(OTHER_LIBRARY);
-
-        // The telephony-common jars should be added at the start of the list because it
-        // is not on the bootclasspath and the package targets pre-R.
-        PackageBuilder after = builder().setSharedUid(PHONE_UID)
-                .targetSdkVersion(Build.VERSION_CODES.Q)
-                .requiredLibraries(ANDROID_TELEPHONY_COMMON, OTHER_LIBRARY);
-
-        checkBackwardsCompatibility(before, after);
-    }
-
-    @Test
-    public void targeted_at_R_in_usesLibraries() {
-        PackageBuilder before = builder()
-                .targetSdkVersion(Build.VERSION_CODES.Q + 1)
-                .requiredLibraries(ANDROID_TELEPHONY_COMMON);
-
-        PackageBuilder after = builder()
-                .targetSdkVersion(Build.VERSION_CODES.Q + 1);
-
-        // Libraries are removed because they are not available for apps target >= R and not run
-        // on phone-uid
-        checkBackwardsCompatibility(before, after);
-    }
-
-    @Test
-    public void targeted_at_Q_in_usesLibraries() {
-        PackageBuilder before = builder().asSystemApp()
-                .targetSdkVersion(Build.VERSION_CODES.Q)
-                .requiredLibraries(ANDROID_TELEPHONY_COMMON);
-
-        // No change is required because the package explicitly requests the telephony libraries
-        // and is targeted at the current version so does not need backwards compatibility.
-        checkBackwardsCompatibility(before, before);
-    }
-
-
-    @Test
-    public void targeted_at_R_in_usesOptionalLibraries() {
-        PackageBuilder before = builder().targetSdkVersion(Build.VERSION_CODES.Q + 1)
-            .optionalLibraries(ANDROID_TELEPHONY_COMMON);
-
-        // Dependency is removed, it is not available.
-        PackageBuilder after = builder().targetSdkVersion(Build.VERSION_CODES.Q + 1);
-
-        // Libraries are removed because they are not available for apps targeting Q+
-        checkBackwardsCompatibility(before, after);
-    }
-
-    @Test
-    public void targeted_at_R() {
-        PackageBuilder before = builder()
-            .targetSdkVersion(Build.VERSION_CODES.Q + 1);
-
-        // no change
-        checkBackwardsCompatibility(before, before);
-    }
-
-    private void checkBackwardsCompatibility(PackageBuilder before, PackageBuilder after) {
-        checkBackwardsCompatibility(before, after, AndroidTelephonyCommonUpdater::new);
-    }
-}
diff --git a/core/tests/coretests/src/android/content/pm/PackageBuilder.java b/core/tests/coretests/src/android/content/pm/PackageBuilder.java
index f3a56e2..f7544af 100644
--- a/core/tests/coretests/src/android/content/pm/PackageBuilder.java
+++ b/core/tests/coretests/src/android/content/pm/PackageBuilder.java
@@ -37,8 +37,6 @@
 
     private ArrayList<String> mOptionalLibraries;
 
-    private String mSharedUid;
-
     public static PackageBuilder builder() {
         return new PackageBuilder();
     }
@@ -49,7 +47,6 @@
         pkg.applicationInfo.flags = mFlags;
         pkg.usesLibraries = mRequiredLibraries;
         pkg.usesOptionalLibraries = mOptionalLibraries;
-        pkg.mSharedUserId = mSharedUid;
         return pkg;
     }
 
@@ -58,11 +55,6 @@
         return this;
     }
 
-    PackageBuilder setSharedUid(String uid) {
-        this.mSharedUid = uid;
-        return this;
-    }
-
     PackageBuilder asSystemApp() {
         this.mFlags |= ApplicationInfo.FLAG_SYSTEM;
         return this;
diff --git a/core/tests/coretests/src/android/view/ViewGroupTest.java b/core/tests/coretests/src/android/view/ViewGroupTest.java
index 979a839..506cc2d 100644
--- a/core/tests/coretests/src/android/view/ViewGroupTest.java
+++ b/core/tests/coretests/src/android/view/ViewGroupTest.java
@@ -16,9 +16,14 @@
 
 package android.view;
 
-import static androidx.test.InstrumentationRegistry.getContext;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
 import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
 
 import android.content.Context;
 import android.graphics.Region;
@@ -39,6 +44,60 @@
 @SmallTest
 public class ViewGroupTest {
 
+    @Test
+    public void testDispatchMouseEventsUnderCursor() {
+        final Context context = getInstrumentation().getContext();
+        final TestView viewGroup = new TestView(context, 0 /* left */, 0 /* top */,
+                200 /* right */, 200 /* bottom */);
+        final TestView viewA = spy(new TestView(context, 0 /* left */, 0 /* top */,
+                100 /* right */, 200 /* bottom */));
+        final TestView viewB = spy(new TestView(context, 100 /* left */, 0 /* top */,
+                200 /* right */, 200 /* bottom */));
+
+        viewGroup.addView(viewA);
+        viewGroup.addView(viewB);
+
+        // Make sure all of them handle touch events dispatched to them.
+        doReturn(true).when(viewA).dispatchTouchEvent(any());
+        doReturn(true).when(viewB).dispatchTouchEvent(any());
+
+        MotionEvent.PointerProperties[] properties = new MotionEvent.PointerProperties[2];
+        properties[0] = new MotionEvent.PointerProperties();
+        properties[0].id = 0;
+        properties[0].toolType = MotionEvent.TOOL_TYPE_FINGER;
+        properties[1] = new MotionEvent.PointerProperties();
+        properties[1].id = 1;
+        properties[1].toolType = MotionEvent.TOOL_TYPE_FINGER;
+
+        MotionEvent.PointerCoords[] coords = new MotionEvent.PointerCoords[2];
+        coords[0] = new MotionEvent.PointerCoords();
+        coords[0].x = 80;
+        coords[0].y = 100;
+        coords[1] = new MotionEvent.PointerCoords();
+        coords[1].x = 240;
+        coords[1].y = 100;
+
+        MotionEvent event;
+        // Make sure the down event is active with a pointer which coordinate is different from the
+        // cursor position, which is the midpoint of all 2 pointers above.
+        event = MotionEvent.obtain(0 /* downTime */, 0 /* eventTime */, MotionEvent.ACTION_DOWN,
+                2 /* pointerCount */, properties, coords, 0 /* metaState */, 0 /* buttonState */,
+                0 /* xPrecision */, 0 /* yPrecision */, 0 /* deviceId */, 0 /* edgeFlags */,
+                InputDevice.SOURCE_MOUSE, 0 /* flags */);
+        viewGroup.dispatchTouchEvent(event);
+        verify(viewB).dispatchTouchEvent(event);
+
+        event = MotionEvent.obtain(0 /* downTime */, 0 /* eventTime */,
+                MotionEvent.ACTION_POINTER_DOWN | (1 << MotionEvent.ACTION_POINTER_INDEX_SHIFT),
+                2 /* pointerCount */, properties, coords, 0 /* metaState */, 0 /* buttonState */,
+                0 /* xPrecision */, 0 /* yPrecision */, 0 /* deviceId */, 0 /* edgeFlags */,
+                InputDevice.SOURCE_MOUSE, 0 /* flags */);
+        viewGroup.dispatchTouchEvent(event);
+        verify(viewB).dispatchTouchEvent(event);
+
+        verify(viewA, never()).dispatchTouchEvent(any());
+    }
+
     /**
      * Test if {@link ViewGroup#subtractObscuredTouchableRegion} works as expected.
      *
@@ -59,7 +118,7 @@
      */
     @Test
     public void testSubtractObscuredTouchableRegion() {
-        final Context context = getContext();
+        final Context context = getInstrumentation().getContext();
         final TestView viewA = new TestView(context, 8 /* right */);
         final TestView viewB = new TestView(context, 6 /* right */);
         final TestView viewC = new TestView(context, 10 /* right */);
@@ -119,10 +178,14 @@
                 (contain ? "" : " not"), x), contain, region.contains(x, 0 /* y */));
     }
 
-    private static class TestView extends ViewGroup {
+    public static class TestView extends ViewGroup {
         TestView(Context context, int right) {
+            this(context, 0 /* left */, 0 /* top */, right, 1 /* bottom */);
+        }
+
+        TestView(Context context, int left, int top, int right, int bottom) {
             super(context);
-            setFrame(0 /* left */, 0 /* top */, right, 1 /* bottom */);
+            setFrame(left, top, right, bottom);
         }
 
         @Override
diff --git a/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java b/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java
index 682416c..3586216a 100644
--- a/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java
+++ b/core/tests/coretests/src/android/view/accessibility/AccessibilityServiceConnectionImpl.java
@@ -23,8 +23,6 @@
 import android.os.Bundle;
 import android.os.IBinder;
 
-import java.util.List;
-
 /**
  * Stub implementation of IAccessibilityServiceConnection so each test doesn't need to implement
  * all of the methods
@@ -73,7 +71,7 @@
         return null;
     }
 
-    public List<AccessibilityWindowInfo> getWindows() {
+    public AccessibilityWindowInfo.WindowListSparseArray getWindows() {
         return null;
     }
 
diff --git a/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java b/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
index c5da549..02a88fc 100644
--- a/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
+++ b/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
@@ -162,8 +162,13 @@
         }
 
         @Override
-        public void internalNotifySessionLifecycle(boolean started) {
-            throw new UnsupportedOperationException("Should not have been called");
+        void internalNotifySessionResumed() {
+            throw new UnsupportedOperationException("should not have been called");
+        }
+
+        @Override
+        void internalNotifySessionPaused() {
+            throw new UnsupportedOperationException("should not have been called");
         }
 
         @Override
diff --git a/core/tests/featureflagtests/OWNERS b/core/tests/featureflagtests/OWNERS
index 1a8fd2b..2ff4f5a 100644
--- a/core/tests/featureflagtests/OWNERS
+++ b/core/tests/featureflagtests/OWNERS
@@ -1,2 +1,2 @@
 sbasi@google.com
-zhfan@google.com
\ No newline at end of file
+tmfang@google.com
\ No newline at end of file
diff --git a/data/etc/Android.bp b/data/etc/Android.bp
index 4493f3a..befa637 100644
--- a/data/etc/Android.bp
+++ b/data/etc/Android.bp
@@ -22,6 +22,12 @@
 }
 
 prebuilt_etc {
+    name: "preinstalled-packages-platform.xml",
+    sub_dir: "sysconfig",
+    src: "preinstalled-packages-platform.xml",
+}
+
+prebuilt_etc {
     name: "hiddenapi-package-whitelist.xml",
     sub_dir: "sysconfig",
     src: "hiddenapi-package-whitelist.xml",
@@ -133,3 +139,8 @@
     sub_dir: "permissions",
     src: "com.android.timezone.updater.xml",
 }
+
+filegroup {
+    name: "services.core.protolog.json",
+    srcs: ["services.core.protolog.json"],
+}
diff --git a/data/etc/TEST_MAPPING b/data/etc/TEST_MAPPING
new file mode 100644
index 0000000..1a5db2f
--- /dev/null
+++ b/data/etc/TEST_MAPPING
@@ -0,0 +1,13 @@
+{
+    "presubmit": [
+        {
+            "file_patterns": ["(/|^)platform.xml"],
+            "name": "CtsPermission2TestCases",
+            "options": [
+                {
+                    "include-filter": "android.permission2.cts.RuntimePermissionProperties"
+                }
+            ]
+        }
+    ]
+}
diff --git a/data/etc/hiddenapi-package-whitelist.xml b/data/etc/hiddenapi-package-whitelist.xml
index 054f68b..f1ba3f6 100644
--- a/data/etc/hiddenapi-package-whitelist.xml
+++ b/data/etc/hiddenapi-package-whitelist.xml
@@ -53,6 +53,10 @@
   <hidden-api-whitelisted-app package="com.android.providers.media" />
   <hidden-api-whitelisted-app package="com.android.providers.tv" />
   <hidden-api-whitelisted-app package="com.android.providers.userdictionary" />
+  <!-- TODO (b/141954427): Remove networkstack -->
+  <hidden-api-whitelisted-app package="com.android.networkstack" />
+  <!-- TODO (b/141954427): Remove wifistack -->
+  <hidden-api-whitelisted-app package="com.android.server.wifistack" />
   <hidden-api-whitelisted-app package="com.android.smspush" />
   <hidden-api-whitelisted-app package="com.android.spare_parts" />
   <hidden-api-whitelisted-app package="com.android.statementservice" />
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index d66930a..dceb243 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -206,6 +206,10 @@
                       targetSdk="29">
         <new-permission name="android.permission.ACCESS_BACKGROUND_LOCATION" />
     </split-permission>
+    <split-permission name="android.permission.READ_EXTERNAL_STORAGE"
+                      targetSdk="29">
+        <new-permission name="android.permission.ACCESS_MEDIA_LOCATION" />
+    </split-permission>
 
     <!-- This is a list of all the libraries available for application
          code to link against. -->
@@ -225,8 +229,6 @@
     <library name="android.hidl.manager-V1.0-java"
             file="/system/framework/android.hidl.manager-V1.0-java.jar"
             dependency="android.hidl.base-V1.0-java" />
-    <library name="telephony-common"
-        file="/system/framework/telephony-common.jar" />
 
     <!-- These are the standard packages that are white-listed to always have internet
          access while in power save mode, even if they aren't in the foreground. -->
diff --git a/data/etc/preinstalled-packages-platform.xml b/data/etc/preinstalled-packages-platform.xml
new file mode 100644
index 0000000..ccd8b5b
--- /dev/null
+++ b/data/etc/preinstalled-packages-platform.xml
@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<!--
+This XML file declares which system packages should be initially installed for new users based on
+the type of user. All system packages on the device should ideally have an entry in an xml file
+(keys by its manifest name).
+
+Main user-types (every user will be at least one of these types) are:
+  SYSTEM    (user 0)
+  FULL      (any non-profile human user)
+  PROFILE   (profile human user)
+
+Additional optional types are:   GUEST,    RESTRICTED,    MANAGED_PROFILE,    EPHEMERAL,    DEMO
+
+The meaning of each of these user types is delineated by flags in
+frameworks/base/core/java/android/content/pm/UserInfo.java.
+See frameworks/base/services/core/java/com/android/server/pm/UserSystemPackageInstaller#getFlagsFromUserTypes
+
+The following three examples should cover most normal cases:
+
+1. For a system package to be pre-installed only in user 0:
+
+   <install-in-user-type package="com.android.example">
+       <install-in user-type="SYSTEM">
+   </install-in-user-type>
+
+
+2. For a system package to be pre-installed on all human users (e.g. a web browser), i.e. to be
+installed on any user of type type FULL or PROFILE (since this covers all human users):
+
+   <install-in-user-type package="com.android.example">
+       <install-in user-type="FULL">
+       <install-in user-type="PROFILE">
+   </install-in-user-type>
+
+
+3. For a system package to be pre-installed on all human users except for profile users (e.g. a
+wallpaper app, since profiles cannot display wallpaper):
+
+   <install-in-user-type package="com.android.example">
+       <install-in user-type="FULL">
+   </install-in-user-type>
+
+
+Some system packages truly are required to be on all users, regardless of type, in which case use:
+   <install-in-user-type package="com.android.example">
+       <install-in user-type="SYSTEM">
+       <install-in user-type="FULL">
+       <install-in user-type="PROFILE">
+   </install-in-user-type>
+
+More fine-grained options are also available (see below). Additionally, packages can blacklist
+user types. Blacklists override any whitelisting (in any file).
+E.g.
+     <install-in-user-type package="com.android.example">
+        <install-in user-type="FULL" />
+        <do-not-install-in user-type="GUEST" />
+    </install-in-user-type>
+
+If a user is of type FULL and GUEST, this package will NOT be installed, because the
+'do-not-install-in' takes precedence over 'install-in'.
+
+The way that a device treats system packages that do not have any entry (for any user type) at all
+is determined by the config resource value config_userTypePackageWhitelistMode.
+See frameworks/base/core/res/res/values/config.xml#config_userTypePackageWhitelistMode.
+
+Changes to the whitelist during system updates can result in installing new system packages
+to pre-existing users, but cannot uninstall system packages from pre-existing users.
+-->
+<config>
+    <install-in-user-type package="com.android.providers.settings">
+        <install-in user-type="SYSTEM" />
+        <install-in user-type="FULL" />
+        <install-in user-type="PROFILE" />
+    </install-in-user-type>
+</config>
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 89523d6..51136b9 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -127,6 +127,7 @@
         <permission name="android.permission.ACCESS_IMS_CALL_SERVICE"/>
         <permission name="android.permission.BIND_CARRIER_MESSAGING_SERVICE"/>
         <permission name="android.permission.BIND_CARRIER_SERVICES"/>
+        <permission name="android.permission.BIND_CELL_BROADCAST_SERVICE"/>
         <permission name="android.permission.BIND_IMS_SERVICE"/>
         <permission name="android.permission.BIND_TELEPHONY_DATA_SERVICE"/>
         <permission name="android.permission.BIND_VISUAL_VOICEMAIL_SERVICE"/>
diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json
new file mode 100644
index 0000000..34b3951
--- /dev/null
+++ b/data/etc/services.core.protolog.json
@@ -0,0 +1,2170 @@
+{
+  "version": "1.0.0",
+  "messages": {
+    "-2146181682": {
+      "message": "Releasing screen wakelock, obscured by %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_KEEP_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-2138637148": {
+      "message": "Clearing focused app, displayId=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/ActivityDisplay.java"
+    },
+    "-2109864870": {
+      "message": "app-release(): mOuter=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-2086729999": {
+      "message": "Removing app token: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-2072089308": {
+      "message": "Attempted to add window with token that is a sub-window: %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-2039580386": {
+      "message": "Attempted to add input method window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-2024464438": {
+      "message": "app-onAnimationFinished(): mOuter=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-2012562539": {
+      "message": "startAnimation(): Notify animation start:",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-2002500255": {
+      "message": "Defer removing snapshot surface in %dms",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/TaskSnapshotSurface.java"
+    },
+    "-1991255017": {
+      "message": "Drawing snapshot surface sizeMismatch=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/TaskSnapshotSurface.java"
+    },
+    "-1976930686": {
+      "message": "Attempted to add Accessibility overlay window with bad token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1963461591": {
+      "message": "Removing %s from %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1958209312": {
+      "message": "Clear freezing of %s: hidden=%b freezing=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/ActivityRecord.java"
+    },
+    "-1953668890": {
+      "message": "Can't start recents animation, nextAppTransition=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "-1949279037": {
+      "message": "Attempted to add input method window with bad token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1939358269": {
+      "message": "mRecentScreenshotAnimator finish",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "-1938839202": {
+      "message": "SURFACE LEAK DESTROY: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-1915280162": {
+      "message": "Attempted to add wallpaper window with bad token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1886298021": {
+      "message": "setAppStartingWindow: token=%s pkg=%s transferFrom=%s newTask=%b taskSwitch=%b processRunning=%b allowTaskSnapshot=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/ActivityRecord.java"
+    },
+    "-1884933373": {
+      "message": "enableScreenAfterBoot: mDisplayEnabled=%b mForceDisplayEnabled=%b mShowingBootMessages=%b mSystemBooted=%b. %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1872288685": {
+      "message": "applyAnimation: anim=%s nextAppTransition=%s transit=%s isEntrance=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "-1868124841": {
+      "message": "screenOnEarly=%b, awake=%b, currentAppOrientation=%d, orientationSensorEnabled=%b, keyguardDrawComplete=%b, windowManagerDrawComplete=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "-1862269827": {
+      "message": "applyAnimation: anim=%s transit=%s isEntrance=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "-1838803135": {
+      "message": "Attempted to set windowing mode to a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1836092044": {
+      "message": "Creating SnapshotStartingData",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1824578273": {
+      "message": "Reporting new frame to %s: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_RESIZE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-1822611824": {
+      "message": "\tRemove token=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-1797409732": {
+      "message": "Skipping %s because %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-1770075711": {
+      "message": "Adding window client %s that is dead, aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1768557332": {
+      "message": "removeWallpaperAnimation()",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "-1750206390": {
+      "message": "Exception thrown when creating surface for client %s (%s). %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1747461042": {
+      "message": "set mOrientationChanging of %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-1741065110": {
+      "message": "No app is requesting an orientation, return %d for display id=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-1736245181": {
+      "message": "Tried to remove starting window but startingWindow was null: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1730156332": {
+      "message": "Display id=%d rotation changed to %d from %d, lastOrientation=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "-1710206702": {
+      "message": "Display id=%d is frozen while keyguard locked, return %d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-1661704580": {
+      "message": "Attempted to set replacing window on non-existing app token %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1661404819": {
+      "message": "applyAnimation: atoken=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1632122349": {
+      "message": "Changing surface while display frozen: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1597650595": {
+      "message": "removeAppToken: %s delayed=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1596995693": {
+      "message": "startAnimation",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-1587841219": {
+      "message": "Focus moving from %s to %s displayId=%d",
+      "level": "INFO",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1568331821": {
+      "message": "Enabling listeners",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "-1561845439": {
+      "message": "reParentWindowToken: removing window token=%s from task=%s",
+      "level": "INFO",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1545962566": {
+      "message": "View server did not start",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1526645239": {
+      "message": "Timeout waiting for drawn: undrawn=%s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1524305318": {
+      "message": "Nulling last startingData",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1519226370": {
+      "message": "startingData was nulled out before handling mAddStartingWindow: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1515151503": {
+      "message": ">>> OPEN TRANSACTION removeReplacedWindows",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "-1497837552": {
+      "message": "onAnimationFinished(): mPendingAnimations=%d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-1483752006": {
+      "message": "  THUMBNAIL %s: CREATE",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/AppWindowThumbnail.java"
+    },
+    "-1470632028": {
+      "message": "Marking app token %s with replacing windows.",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1455600136": {
+      "message": "Attempted to add Dream window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1448427933": {
+      "message": "startingWindow was set but startingSurface==null, couldn't remove",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1443029505": {
+      "message": "SAFE MODE ENABLED (menu=%d s=%d dpad=%d trackball=%d)",
+      "level": "INFO",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1434147454": {
+      "message": "cleanupAnimation(): Notify animation finished mPendingAnimations=%d reorderMode=%d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "-1427184084": {
+      "message": "addWindow: New client %s: window=%s Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1413901262": {
+      "message": "startRecentsActivity(): intent=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "-1391944764": {
+      "message": "SURFACE DESTROY: %s. %s",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "-1389772804": {
+      "message": "Attempted to add voice interaction window with bad token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1350198040": {
+      "message": "hideBootMessagesLocked: mDisplayEnabled=%b mForceDisplayEnabled=%b mShowingBootMessages=%b mSystemBooted=%b. %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1318134223": {
+      "message": "No longer Stopped: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1270731689": {
+      "message": "Attempted to set replacing window on app token with no content %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1270148832": {
+      "message": "Resize start waiting for draw, mDrawState=DRAW_PENDING in %s, surfaceController %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_RESIZE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-1263554915": {
+      "message": "Attempted to add Dream window with bad token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1259022216": {
+      "message": "SURFACE HIDE ( %s ): %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "-1257821162": {
+      "message": "OUT SURFACE %s: copied",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1219773477": {
+      "message": "setInputConsumerEnabled(%s): mCanceled=%b",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "-1207757583": {
+      "message": "startAnimation(): Notify animation start: %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "-1176488860": {
+      "message": "SURFACE isSecure=%b: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "-1156118957": {
+      "message": "Updated config=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "-1144293044": {
+      "message": "SURFACE SET FREEZE LAYER: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "-1130891072": {
+      "message": "Orientation continue waiting for draw in %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "-1130868271": {
+      "message": "Resizing %s WITH DRAW PENDING",
+      "level": "INFO",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-1117599386": {
+      "message": "Deferring rotation, display is not enabled.",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "-1113134997": {
+      "message": "Attempted to add application window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1103716954": {
+      "message": "Not removing %s due to exit animation",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-1103115659": {
+      "message": "Performing post-rotate rotation",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "-1099052739": {
+      "message": "\tAdd token=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-1097148233": {
+      "message": "commitVisibility: %s: hidden=%b hiddenRequested=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1089874824": {
+      "message": "SURFACE SHOW (performLayout): %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "-1077196445": {
+      "message": "Add starting %s: startingData=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-1076978367": {
+      "message": "thawRotation: mRotation=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1060365734": {
+      "message": "Attempted to add QS dialog window with bad token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1047945589": {
+      "message": "Remove client=%x, surfaceController=%s Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-1044506655": {
+      "message": "New transit away from wallpaper: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "-1042574499": {
+      "message": "Attempted to add Accessibility overlay window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-1009117329": {
+      "message": "isFetchingAppTransitionSpecs=true",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "-1001633850": {
+      "message": "Removing focused app token:%s displayId=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-993378225": {
+      "message": "finishDrawingLocked: mDrawState=COMMIT_DRAW_PENDING %s in %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_DRAW",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "-986746907": {
+      "message": "Starting window removed %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-979259577": {
+      "message": "setAppVisibility(%s, visible=%b): %s hidden=%b hiddenRequested=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-955458843": {
+      "message": "Set freezing of %s: hidden=%b freezing=%b hiddenRequested=%b. %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-953872371": {
+      "message": "setClientHidden: %s clientHidden=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-928291778": {
+      "message": "applyAnimation: anim=%s nextAppTransition=%d transit=%s Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "-916108501": {
+      "message": "Adding %s to %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-914253865": {
+      "message": "Attempted to add voice interaction window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-883738232": {
+      "message": "Adding more than one toast window for UID at a time.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-874446906": {
+      "message": "showBootMessage: msg=%s always=%b mAllowBootMessages=%b mShowingBootMessages=%b mSystemBooted=%b. %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-861859917": {
+      "message": "Attempted to add window to a display that does not exist: %d. Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-861707633": {
+      "message": "Destroying surface %s called by %s",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "-856025122": {
+      "message": "SURFACE transparentRegionHint=%s: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-853404763": {
+      "message": "\twallpaper=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-853226675": {
+      "message": "Attempted to add window with exiting application token .%s Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-809771899": {
+      "message": "findFocusedWindow: Reached focused app=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-807062773": {
+      "message": "Aborted starting %s: removed=%b startingData=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-793346159": {
+      "message": "New transit into wallpaper: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "-784959154": {
+      "message": "Attempted to add private presentation window to a non-private display.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-783405930": {
+      "message": "Performing post-rotate rotation",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-771282525": {
+      "message": "Losing focus: %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-760801764": {
+      "message": "onAnimationCancelled",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/WallpaperAnimationAdapter.java"
+    },
+    "-754503024": {
+      "message": "Relayout %s: oldVis=%d newVis=%d. %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-747671114": {
+      "message": "Failed looking up window callers=%s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-714291355": {
+      "message": "Losing delayed focus: %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-694710814": {
+      "message": "Pausing rotation during drag",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DragState.java"
+    },
+    "-687185281": {
+      "message": "New topFocusedDisplayId=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "-666510420": {
+      "message": "With display frozen, orientationChangeComplete=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "-666419717": {
+      "message": "Creating animation bounds layer",
+      "level": "INFO",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-653156702": {
+      "message": "createAppAnimations()",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "-650040763": {
+      "message": "rotationForOrientation(orient=%d, last=%d); user=%d %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "-635082269": {
+      "message": "******** booted=%b msg=%b haveBoot=%b haveApp=%b haveWall=%b wallEnabled=%b haveKeyguard=%b",
+      "level": "INFO",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-622997754": {
+      "message": "postWindowRemoveCleanupLocked: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-618015844": {
+      "message": "performEnableScreen: mDisplayEnabled=%b mForceDisplayEnabled=%b mShowingBootMessages=%b mSystemBooted=%b mOnlyCore=%b. %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-583031528": {
+      "message": "%s",
+      "level": "INFO",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-576070986": {
+      "message": "Performing post-rotate rotation after seamless rotation",
+      "level": "INFO",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "-573268667": {
+      "message": "applyAnimation: transition animation is disabled or skipped. atoken=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-554834595": {
+      "message": "Display id=%d is frozen, return %d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-549028919": {
+      "message": "enableScreenIfNeededLocked: mDisplayEnabled=%b mForceDisplayEnabled=%b mShowingBootMessages=%b mSystemBooted=%b. %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-545190927": {
+      "message": "<<< CLOSE TRANSACTION animate",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowAnimator.java"
+    },
+    "-519504830": {
+      "message": "applyAnimation: anim=%s nextAppTransition=ANIM_CUSTOM transit=%s isEntrance=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "-507657818": {
+      "message": "Window %s is already added",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-496681057": {
+      "message": "Attempted to get remove mode of a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-481924678": {
+      "message": "handleNotObscuredLocked w: %s, w.mHasSurface: %b, w.isOnScreen(): %b, w.isDisplayedLw(): %b, w.mAttrs.userActivityTimeout: %d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_KEEP_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "-477481651": {
+      "message": "SURFACE DESTROY PENDING: %s. %s",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "-445944810": {
+      "message": "finish(%b): mCanceled=%b",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "-444624452": {
+      "message": "REPARENT from: %s to: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "-439951996": {
+      "message": "Disabling listeners",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "-415912575": {
+      "message": "setTask: %s at top.",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/ActivityRecord.java"
+    },
+    "-415865166": {
+      "message": "findFocusedWindow: Found new focus @ %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-405536909": {
+      "message": "Removing snapshot surface",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/TaskSnapshotSurface.java"
+    },
+    "-393505149": {
+      "message": "unable to update pointer icon",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-386552155": {
+      "message": "Attempted to set system decors flag to a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-379068494": {
+      "message": "unknownApps is not empty: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "-371630969": {
+      "message": "New wallpaper target=%s, oldWallpaper=%s, openingApps=%s, closingApps=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "-367797467": {
+      "message": "Creating SplashScreenStartingData",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-344488673": {
+      "message": "Finishing drawing window %s: mDrawState=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "-336658140": {
+      "message": "Checking theme of starting window: 0x%x",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-324085783": {
+      "message": "SURFACE CROP %s: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "-322035974": {
+      "message": "App freeze timeout expired.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-320419645": {
+      "message": "Removing replaced window: %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-198463978": {
+      "message": "updateRotationUnchecked: alwaysSendConfiguration=%b forceRelayout=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-193782861": {
+      "message": "Final remove of window: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_WINDOW_MOVEMENT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-167822951": {
+      "message": "Attempted to add starting window to token with already existing starting window",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-129722369": {
+      "message": "New transit: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "-121104356": {
+      "message": "Remove %s: mSurfaceController=%s mAnimatingExit=%b mRemoveOnExit=%b mHasSurface=%b surfaceShowing=%b animating=%b app-animation=%b mWillReplaceWindow=%b inPendingTransaction=%b mDisplayFrozen=%b callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "-116086365": {
+      "message": "******************** ENABLING SCREEN!",
+      "level": "INFO",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-106400104": {
+      "message": "Preload recents with %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "-104758113": {
+      "message": "Removing app %s delayed=%b animation=%s animating=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-96848838": {
+      "message": "Gaining focus: %s",
+      "level": "INFO",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-87705714": {
+      "message": "findFocusedWindow: focusedApp=null using new focus @ %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "-87703044": {
+      "message": "Boot completed: SurfaceFlinger is dead!",
+      "level": "ERROR",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "-86763148": {
+      "message": "  KILL SURFACE SESSION %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/Session.java"
+    },
+    "-34965929": {
+      "message": "Moving pending starting from %s to %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "-29233992": {
+      "message": "SURFACE CLEAR CROP: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "-7343917": {
+      "message": "onAnimationFinished(): targetStack=%s targetActivity=%s mRestoreTargetBehindStack=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "9803449": {
+      "message": "startFreezingDisplayLocked: exitAnim=%d enterAnim=%d called by %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "10608884": {
+      "message": "  FREEZE %s: CREATE",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/ScreenRotationAnimation.java"
+    },
+    "11060725": {
+      "message": "Attempted to get system decors flag of a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "17696244": {
+      "message": "startAnimation(): mPendingStart=%b mCanceled=%b",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "38267433": {
+      "message": "Attempted to reset replacing window on non-existing app token %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "44171776": {
+      "message": "Resetting app token %s of replacing window marks.",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "51200510": {
+      "message": "  BLACK %s: DESTROY",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/BlackFrame.java"
+    },
+    "51628177": {
+      "message": "Attempted to get windowing mode of a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "83950285": {
+      "message": "removeAnimation(%d)",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "91350919": {
+      "message": "Attempted to set IME flag to a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "95281111": {
+      "message": "Attempted to get IME flag of a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "95902367": {
+      "message": "Relayout of %s: focusMayChange=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "100936473": {
+      "message": "Wallpaper animation!",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "115108840": {
+      "message": "Removing startingView=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "118187173": {
+      "message": "Enqueueing ADD_STARTING",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "123161180": {
+      "message": "SEVER CHILDREN",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "150351993": {
+      "message": "addWindow: %s startingWindow=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "152914409": {
+      "message": "  BLACK %s: CREATE layer=%d",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/BlackFrame.java"
+    },
+    "154699456": {
+      "message": "Last window, removing starting window %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "173419252": {
+      "message": "No thumbnail header bitmap for: %d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "184362060": {
+      "message": "screenshotTask(%d): mCanceled=%b",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "186668272": {
+      "message": "Now changing app %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "194124419": {
+      "message": "goodToGo(): Animation finished already, canceled=%s mPendingAnimations=%d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "196230599": {
+      "message": "Moving existing starting %s from %s to %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "221540118": {
+      "message": "mUserActivityTimeout set to %d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_KEEP_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "241961619": {
+      "message": "Adding %s to %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowToken.java"
+    },
+    "246676969": {
+      "message": "Attempted to add window with non-application token .%s Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "248210157": {
+      "message": "Finishing remote animation",
+      "level": "INFO",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "254883724": {
+      "message": "addWindowToken: Attempted to add binder token: %s for already created window token: %s displayId=%d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "255692476": {
+      "message": "**** GOOD TO GO",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "269576220": {
+      "message": "Resuming rotation after drag",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DragState.java"
+    },
+    "274773837": {
+      "message": "applyAnimation: anim=%s nextAppTransition=ANIM_CLIP_REVEAL transit=%s Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "285317231": {
+      "message": "Input focus has changed to %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/InputMonitor.java"
+    },
+    "288485303": {
+      "message": "Attempted to set remove mode to a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "289967521": {
+      "message": "Check opening app=%s: allDrawn=%b startingDisplayed=%b startingMoved=%b isRelaunching()=%b startingWindow=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "292904800": {
+      "message": "Deferring rotation, animation in progress.",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "302992539": {
+      "message": "addAnimation(%s)",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "309039362": {
+      "message": "SURFACE MATRIX [%f,%f,%f,%f]: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "342460966": {
+      "message": "DRAG %s: pos=(%d,%d)",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/DragState.java"
+    },
+    "344795667": {
+      "message": "*** APP TRANSITION TIMEOUT. displayId=%d isTransitionSet()=%b mOpeningApps.size()=%d mClosingApps.size()=%d mChangingApps.size()=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "355720268": {
+      "message": "stopFreezingDisplayLocked: Unfreezing now",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "371641947": {
+      "message": "Window Manager Crash %s",
+      "level": "WTF",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "374972436": {
+      "message": "performEnableScreen: Waiting for anim complete",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "385096046": {
+      "message": "Delaying loss of focus...",
+      "level": "INFO",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "399841913": {
+      "message": "SURFACE RECOVER DESTROY: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "416664944": {
+      "message": "No longer freezing: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "417311568": {
+      "message": "onResize: Resizing %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RESIZE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "424524729": {
+      "message": "Attempted to add wallpaper window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "435494046": {
+      "message": "Attempted to add window to a display for which the application does not have access: %d.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "457951957": {
+      "message": "\tNot visible=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/WallpaperAnimationAdapter.java"
+    },
+    "463993897": {
+      "message": "Aborted waiting for drawn: %s",
+      "level": "WARN",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "474000473": {
+      "message": "No stack above target stack=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "481370485": {
+      "message": "Computed rotation=%d for display id=%d based on lastOrientation=%d and oldRotation=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "490877640": {
+      "message": "onStackOrderChanged(): stack=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "492980365": {
+      "message": "TRANSIT_TASK_OPEN_BEHIND,  adding %s to mOpeningApps",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "495032901": {
+      "message": "Expected target stack=%s to restored behind stack=%s but it is behind stack=%s",
+      "level": "WARN",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "508887531": {
+      "message": "applyAnimation voice: anim=%s transit=%s isEntrance=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "557227556": {
+      "message": "onAnimationFinished(): Notify animation finished:",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "558823034": {
+      "message": "SURFACE isOpaque=%b: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "585096182": {
+      "message": "SURFACE isColorSpaceAgnostic=%b: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "594260577": {
+      "message": "createWallpaperAnimations()",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "600140673": {
+      "message": "checkBootAnimationComplete: Waiting for anim complete",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "608694300": {
+      "message": "  NEW SURFACE SESSION %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/Session.java"
+    },
+    "620368427": {
+      "message": "******* TELLING SURFACE FLINGER WE ARE BOOTED!",
+      "level": "INFO",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "628276090": {
+      "message": "Delaying app transition for screen rotation animation to finish",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "631792420": {
+      "message": "Attempted to add window with token that is not a window: %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "633654009": {
+      "message": "SURFACE POS (setPositionInTransaction) @ (%f,%f): %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "644675193": {
+      "message": "Real start recents",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "646155519": {
+      "message": "Started intent=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "662572728": {
+      "message": "Attempted to add a toast window with bad token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "665256544": {
+      "message": "All windows drawn!",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "668425960": {
+      "message": "Notify removed startingWindow %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "676824470": {
+      "message": "Test completed successfully: %b %d %o %x %e %g %f %% %s.",
+      "level": "ERROR",
+      "group": "TEST_GROUP",
+      "at": "com\/android\/server\/wm\/ProtoLogGroup.java"
+    },
+    "685047360": {
+      "message": "Resizing window %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_RESIZE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "690411811": {
+      "message": "goodToGo(): No apps to animate",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "693423992": {
+      "message": "setAnimationLocked: setting mFocusMayChange true",
+      "level": "INFO",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "704998117": {
+      "message": "Failed to create surface control for %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "745391677": {
+      "message": "  CREATE SURFACE %s IN SESSION %s: pid=%d format=%d flags=0x%x \/ %s",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "758852025": {
+      "message": "Surface returned was null: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "765395228": {
+      "message": "onAnimationFinished(): controller=%s reorderMode=%d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "791468751": {
+      "message": "Pausing rotation during re-position",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/TaskPositioner.java"
+    },
+    "794570322": {
+      "message": "Now closing app %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "811802785": {
+      "message": "Changing app %s hidden=%b performLayout=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "829434921": {
+      "message": "Draw state now committed in %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "835814848": {
+      "message": "%s",
+      "level": "INFO",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "845234215": {
+      "message": "App is requesting an orientation, return %d for display id=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "847534382": {
+      "message": "Non-null appWindowToken for system window of rootType=%d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "853091290": {
+      "message": "Moved stack=%s behind stack=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "868946719": {
+      "message": "notifyAppResumed: wasStopped=%b %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "873914452": {
+      "message": "goodToGo()",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "884043983": {
+      "message": "removeDeadWindows: %s",
+      "level": "WARN",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "892244061": {
+      "message": "Waiting for drawn %s: removed=%b visible=%b mHasSurface=%b drawState=%d",
+      "level": "INFO",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "898863925": {
+      "message": "Attempted to add QS dialog window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "913494177": {
+      "message": "removeAllWindowsIfPossible: removing win=%s",
+      "level": "WARN",
+      "group": "WM_DEBUG_WINDOW_MOVEMENT",
+      "at": "com\/android\/server\/wm\/WindowToken.java"
+    },
+    "916191774": {
+      "message": "Orientation change complete in %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "917739349": {
+      "message": "Set focused app to: %s moveFocusNow=%b displayId=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/ActivityDisplay.java"
+    },
+    "954470154": {
+      "message": "FORCED DISPLAY SCALING DISABLED",
+      "level": "INFO",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "990058731": {
+      "message": "notifyAppStopped: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1001904964": {
+      "message": "***** BOOT TIMEOUT: forcing display enabled",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1004585481": {
+      "message": "%s forcing orientation to %d for display id=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "1021057640": {
+      "message": "Marking app token %s with replacing child windows.",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1051545910": {
+      "message": "Exit animation finished in %s: remove=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1073230342": {
+      "message": "startAnimation",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/WallpaperAnimationAdapter.java"
+    },
+    "1089714158": {
+      "message": "  FREEZE %s: DESTROY",
+      "level": "INFO",
+      "group": "WM_SHOW_SURFACE_ALLOC",
+      "at": "com\/android\/server\/wm\/ScreenRotationAnimation.java"
+    },
+    "1108406230": {
+      "message": "stopFreezingDisplayLocked: Returning mWaitingForConfig=%b, mAppsFreezingScreen=%d, mWindowsFreezingScreen=%d, mClientFreezingScreen=%b, mOpeningApps.size()=%d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1112047265": {
+      "message": "finishDrawingWindow: %s mDrawState=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1115417974": {
+      "message": "FORCED DISPLAY SIZE: %dx%d",
+      "level": "INFO",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1140424002": {
+      "message": "Finished screen turning on...",
+      "level": "INFO",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/DisplayPolicy.java"
+    },
+    "1160771501": {
+      "message": "Resize reasons for w=%s:  %s surfaceResized=%b configChanged=%b dragResizingChanged=%b reportOrientationChanged=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_RESIZE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1166381079": {
+      "message": "Execute app transition: %s, displayId: %d Callers=%s",
+      "level": "WARN",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "1195433019": {
+      "message": "Clearing startingData for token=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1208313423": {
+      "message": "addWindowToken: Attempted to add token: %s for non-exiting displayId=%d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1219600119": {
+      "message": "addWindow: win=%s Callers=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_FOCUS",
+      "at": "com\/android\/server\/wm\/WindowToken.java"
+    },
+    "1220075598": {
+      "message": "SURFACE SIZE %dx%d: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowSurfaceController.java"
+    },
+    "1224307091": {
+      "message": "checkBootAnimationComplete: Animation complete!",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1244668962": {
+      "message": "Added starting %s: startingWindow=%s startingView=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1288731814": {
+      "message": "WindowState.hideLw: setting mFocusMayChange true",
+      "level": "INFO",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1325649102": {
+      "message": "Bad requesting window %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1329340614": {
+      "message": "Orientation not waiting for draw in %s, surfaceController %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1331177619": {
+      "message": "Attempted to add a toast window with unknown token %s.  Aborting.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1358462645": {
+      "message": "Looking for focus: %s, flags=%d, canReceive=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "1401700824": {
+      "message": "Window drawn win=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1404220922": {
+      "message": "Translucent=%s Floating=%s ShowWallpaper=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1422781269": {
+      "message": "Resuming rotation after re-position",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/TaskPositioner.java"
+    },
+    "1423418408": {
+      "message": "unable to restore pointer icon",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1423592961": {
+      "message": "<<< CLOSE TRANSACTION removeReplacedWindows",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "1430336882": {
+      "message": "findFocusedWindow: focusedApp windows not focusable using new focus @ %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "1434383382": {
+      "message": "Attempted to get flag of a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1448683958": {
+      "message": "Override pending remote transitionSet=%b adapter=%s",
+      "level": "INFO",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "1457990604": {
+      "message": "applyAnimation: anim=%s nextAppTransition=ANIM_CUSTOM_IN_PLACE transit=%s Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "1469292670": {
+      "message": "Changing focus from %s to %s displayId=%d Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "1495525537": {
+      "message": "createWallpaperAnimations()",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "1496418389": {
+      "message": "Removing starting %s from %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1497304204": {
+      "message": "Deferring rotation, rotation is paused.",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "1504168072": {
+      "message": "removeIfPossible: %s callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1518495446": {
+      "message": "removeWindowToken: Attempted to remove non-existing token: %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1519757176": {
+      "message": "setHomeApp(%s)",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "1521476038": {
+      "message": "Attempted to set flag to a display that does not exist: %d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1525976603": {
+      "message": "cancelAnimation(): reason=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimationController.java"
+    },
+    "1531527061": {
+      "message": "createAnimationAdapter(): token=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "1563755163": {
+      "message": "Permission Denial: %s from pid=%d, uid=%d requires %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1573332272": {
+      "message": "Display id=%d selected orientation %d, got rotation %d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "1577579529": {
+      "message": "win=%s destroySurfaces: appStopped=%b win.mWindowRemovalAllowed=%b win.mRemoveOnExit=%b",
+      "level": "ERROR",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1589610525": {
+      "message": "applyAnimation NEXT_TRANSIT_TYPE_OPEN_CROSS_PROFILE_APPS: anim=%s transit=%s isEntrance=true Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "1628345525": {
+      "message": "Now opening app %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "1634557978": {
+      "message": "**** Dismissing screen rotation animation",
+      "level": "INFO",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1635462459": {
+      "message": "onMovedByResize: Moving %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RESIZE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1637745145": {
+      "message": "Clear freezing of %s force=%b",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1720696061": {
+      "message": "Adding window to Display that has been removed.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1739298851": {
+      "message": "removeWindowToken: Attempted to remove token: %s for non-exiting displayId=%d",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1747941491": {
+      "message": "SURFACE controller=%s alpha=%f matrix=[%f*%f,%f*%f][%f*%f,%f*%f]: %s",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "1756082882": {
+      "message": "Orientation change skips hidden %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/WindowStateAnimator.java"
+    },
+    "1762317752": {
+      "message": "Expected target stack=%s to be top most but found stack=%s",
+      "level": "WARN",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RecentsAnimation.java"
+    },
+    "1764592478": {
+      "message": "reparent: moving app token=%s to task=%d at %d",
+      "level": "INFO",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1774661765": {
+      "message": "Devices still not ready after waiting %d milliseconds before attempting to detect safe mode.",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1814552834": {
+      "message": "performLayout: App token exiting now removed %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "1836306327": {
+      "message": "Skipping set freeze of %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/ActivityRecord.java"
+    },
+    "1865125884": {
+      "message": "finishScreenTurningOn: mAwake=%b, mScreenOnEarly=%b, mScreenOnFully=%b, mKeyguardDrawComplete=%b, mWindowManagerDrawComplete=%b",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/DisplayPolicy.java"
+    },
+    "1865246212": {
+      "message": "\tapp=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "1866772666": {
+      "message": "SAFE MODE not enabled",
+      "level": "INFO",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "1878395049": {
+      "message": "Loading animation for app transition. transit=%s enter=%b frame=%s insets=%s surfaceInsets=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1883987026": {
+      "message": "removeAppToken make exiting: %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "1891501279": {
+      "message": "cancelAnimation(): reason=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "1921821199": {
+      "message": "Preserving %s until the new one is added",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "1947239194": {
+      "message": "Deferring rotation, still finishing previous rotation",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "1964565370": {
+      "message": "Starting remote animation",
+      "level": "INFO",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/RemoteAnimationController.java"
+    },
+    "1984470582": {
+      "message": "Creating TaskScreenshotAnimatable: task: %s width: %d height: %d",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_RECENTS_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/TaskScreenshotAnimatable.java"
+    },
+    "1984738415": {
+      "message": "Now animating app in place %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "1984782949": {
+      "message": ">>> OPEN TRANSACTION animate",
+      "level": "INFO",
+      "group": "WM_SHOW_TRANSACTIONS",
+      "at": "com\/android\/server\/wm\/WindowAnimator.java"
+    },
+    "1993685727": {
+      "message": "Setting mOrientationChangeComplete=true because wtoken %s numInteresting=%d numDrawn=%d",
+      "level": "INFO",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "2016061474": {
+      "message": "Prepare app transition: transit=%s %s alwaysKeepCurrent=%b displayId=%d Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "2018454757": {
+      "message": "WS.removeImmediately: %s Already removed...",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "2028163120": {
+      "message": "applyAnimation: anim=%s nextAppTransition=ANIM_SCALE_UP transit=%s isEntrance=%s Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    },
+    "2034780299": {
+      "message": "CHECK_IF_BOOT_ANIMATION_FINISHED:",
+      "level": "INFO",
+      "group": "WM_DEBUG_BOOT",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "2045641491": {
+      "message": "Checking %d opening apps (frozen=%b timeout=%b)...",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS",
+      "at": "com\/android\/server\/wm\/AppTransitionController.java"
+    },
+    "2054958632": {
+      "message": "Schedule remove starting %s startingWindow=%s startingView=%s Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "2057434754": {
+      "message": "\tvisible=%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_REMOTE_ANIMATIONS",
+      "at": "com\/android\/server\/wm\/WallpaperAnimationAdapter.java"
+    },
+    "2076259606": {
+      "message": "Finish starting %s: first real window is shown, no animation",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_STARTING_WINDOW",
+      "at": "com\/android\/server\/wm\/AppWindowToken.java"
+    },
+    "2083556954": {
+      "message": "Set mOrientationChanging of %s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "2086878461": {
+      "message": "Could not send command %s with parameters %s. %s",
+      "level": "WARN",
+      "group": "WM_ERROR",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "2088592090": {
+      "message": "handleNotObscuredLocked: %s was holding screen wakelock but no longer has FLAG_KEEP_SCREEN_ON!!! called by%s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_KEEP_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/RootWindowContainer.java"
+    },
+    "2096635066": {
+      "message": "Acquiring screen wakelock due to %s",
+      "level": "DEBUG",
+      "group": "WM_DEBUG_KEEP_SCREEN_ON",
+      "at": "com\/android\/server\/wm\/WindowManagerService.java"
+    },
+    "2114149926": {
+      "message": "Not removing %s because app died while it's visible",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ADD_REMOVE",
+      "at": "com\/android\/server\/wm\/WindowState.java"
+    },
+    "2128604122": {
+      "message": "findFocusedWindow: No focusable windows.",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_FOCUS_LIGHT",
+      "at": "com\/android\/server\/wm\/DisplayContent.java"
+    },
+    "2128917433": {
+      "message": "onProposedRotationChanged, rotation=%d",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_ORIENTATION",
+      "at": "com\/android\/server\/wm\/DisplayRotation.java"
+    },
+    "2137411379": {
+      "message": "applyAnimation: anim=%s animAttr=0x%x transit=%s isEntrance=%b Callers=%s",
+      "level": "VERBOSE",
+      "group": "WM_DEBUG_APP_TRANSITIONS_ANIM",
+      "at": "com\/android\/server\/wm\/AppTransition.java"
+    }
+  },
+  "groups": {
+    "TEST_GROUP": {
+      "tag": "WindowManagetProtoLogTest"
+    },
+    "WM_DEBUG_ADD_REMOVE": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_APP_TRANSITIONS": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_APP_TRANSITIONS_ANIM": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_BOOT": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_DRAW": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_FOCUS": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_FOCUS_LIGHT": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_KEEP_SCREEN_ON": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_ORIENTATION": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_RECENTS_ANIMATIONS": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_REMOTE_ANIMATIONS": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_RESIZE": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_SCREEN_ON": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_STARTING_WINDOW": {
+      "tag": "WindowManager"
+    },
+    "WM_DEBUG_WINDOW_MOVEMENT": {
+      "tag": "WindowManager"
+    },
+    "WM_ERROR": {
+      "tag": "WindowManager"
+    },
+    "WM_SHOW_SURFACE_ALLOC": {
+      "tag": "WindowManager"
+    },
+    "WM_SHOW_TRANSACTIONS": {
+      "tag": "WindowManager"
+    }
+  }
+}
diff --git a/data/fonts/fonts.xml b/data/fonts/fonts.xml
index 072beae..c692097 100644
--- a/data/fonts/fonts.xml
+++ b/data/fonts/fonts.xml
@@ -323,14 +323,16 @@
         <font weight="700" style="normal">NotoSansLaoUI-Bold.ttf</font>
     </family>
     <family lang="und-Mymr" variant="elegant">
-        <font weight="400" style="normal">NotoSansMyanmar-Regular-ZawDecode.ttf</font>
-        <font weight="700" style="normal">NotoSansMyanmar-Bold-ZawDecode.ttf</font>
+        <font weight="400" style="normal">NotoSansMyanmar-Regular.otf</font>
+        <font weight="500" style="normal">NotoSansMyanmar-Medium.otf</font>
+        <font weight="700" style="normal">NotoSansMyanmar-Bold.otf</font>
         <font weight="400" style="normal" fallbackFor="serif">NotoSerifMyanmar-Regular.otf</font>
         <font weight="700" style="normal" fallbackFor="serif">NotoSerifMyanmar-Bold.otf</font>
     </family>
     <family lang="und-Mymr" variant="compact">
-        <font weight="400" style="normal">NotoSansMyanmarUI-Regular-ZawDecode.ttf</font>
-        <font weight="700" style="normal">NotoSansMyanmarUI-Bold-ZawDecode.ttf</font>
+        <font weight="400" style="normal">NotoSansMyanmarUI-Regular.otf</font>
+        <font weight="500" style="normal">NotoSansMyanmarUI-Medium.otf</font>
+        <font weight="700" style="normal">NotoSansMyanmarUI-Bold.otf</font>
     </family>
     <family lang="und-Thaa">
         <font weight="400" style="normal">NotoSansThaana-Regular.ttf</font>
diff --git a/graphics/java/android/graphics/drawable/GradientDrawable.java b/graphics/java/android/graphics/drawable/GradientDrawable.java
index b9945cc..96ac0f9 100644
--- a/graphics/java/android/graphics/drawable/GradientDrawable.java
+++ b/graphics/java/android/graphics/drawable/GradientDrawable.java
@@ -637,7 +637,7 @@
      * @see #setOrientation(Orientation)
      */
     public Orientation getOrientation() {
-        return mGradientState.getOrientation();
+        return mGradientState.mOrientation;
     }
 
     /**
@@ -653,7 +653,7 @@
      * @see #getOrientation()
      */
     public void setOrientation(Orientation orientation) {
-        mGradientState.setOrientation(orientation);
+        mGradientState.mOrientation = orientation;
         mGradientIsDirty = true;
         invalidateSelf();
     }
@@ -1270,7 +1270,7 @@
 
                 if (st.mGradient == LINEAR_GRADIENT) {
                     final float level = st.mUseLevel ? getLevel() / 10000.0f : 1.0f;
-                    switch (st.getOrientation()) {
+                    switch (st.mOrientation) {
                     case TOP_BOTTOM:
                         x0 = r.left;            y0 = r.top;
                         x1 = x0;                y1 = level * r.bottom;
@@ -1759,6 +1759,33 @@
         int angle = (int) a.getFloat(R.styleable.GradientDrawableGradient_angle, st.mAngle);
         st.mAngle = ((angle % 360) + 360) % 360; // offset negative angle measures
 
+        switch (st.mAngle) {
+            case 0:
+                st.mOrientation = Orientation.LEFT_RIGHT;
+                break;
+            case 45:
+                st.mOrientation = Orientation.BL_TR;
+                break;
+            case 90:
+                st.mOrientation = Orientation.BOTTOM_TOP;
+                break;
+            case 135:
+                st.mOrientation = Orientation.BR_TL;
+                break;
+            case 180:
+                st.mOrientation = Orientation.RIGHT_LEFT;
+                break;
+            case 225:
+                st.mOrientation = Orientation.TR_BL;
+                break;
+            case 270:
+                st.mOrientation = Orientation.TOP_BOTTOM;
+                break;
+            case 315:
+                st.mOrientation = Orientation.TL_BR;
+                break;
+        }
+
         final TypedValue tv = a.peekValue(R.styleable.GradientDrawableGradient_gradientRadius);
         if (tv != null) {
             final float radius;
@@ -1981,7 +2008,7 @@
         int[] mAttrPadding;
 
         public GradientState(Orientation orientation, int[] gradientColors) {
-            setOrientation(orientation);
+            mOrientation = orientation;
             setGradientColors(gradientColors);
         }
 
@@ -2184,93 +2211,11 @@
             mCenterY = y;
         }
 
-        public void setOrientation(Orientation orientation) {
-            // Update the angle here so that subsequent attempts to obtain the orientation
-            // from the angle overwrite previously configured values during inflation
-            mAngle = getAngleFromOrientation(orientation);
-            mOrientation = orientation;
-        }
-
         @NonNull
         public Orientation getOrientation() {
-            updateGradientStateOrientation();
             return mOrientation;
         }
 
-        /**
-         * Update the orientation of the gradient based on the given angle only if the type is
-         * {@link #LINEAR_GRADIENT}
-         */
-        private void updateGradientStateOrientation() {
-            if (mGradient == LINEAR_GRADIENT) {
-                int angle = mAngle;
-                if (angle % 45 != 0) {
-                    throw new IllegalArgumentException("Linear gradient requires 'angle' attribute "
-                            + "to be a multiple of 45");
-                }
-
-                Orientation orientation;
-                switch (angle) {
-                    case 0:
-                        orientation = Orientation.LEFT_RIGHT;
-                        break;
-                    case 45:
-                        orientation = Orientation.BL_TR;
-                        break;
-                    case 90:
-                        orientation = Orientation.BOTTOM_TOP;
-                        break;
-                    case 135:
-                        orientation = Orientation.BR_TL;
-                        break;
-                    case 180:
-                        orientation = Orientation.RIGHT_LEFT;
-                        break;
-                    case 225:
-                        orientation = Orientation.TR_BL;
-                        break;
-                    case 270:
-                        orientation = Orientation.TOP_BOTTOM;
-                        break;
-                    case 315:
-                        orientation = Orientation.TL_BR;
-                        break;
-                    default:
-                        // Should not get here as exception is thrown above if angle is not multiple
-                        // of 45 degrees
-                        orientation = Orientation.LEFT_RIGHT;
-                        break;
-                }
-                mOrientation = orientation;
-            }
-        }
-
-        private int getAngleFromOrientation(@Nullable Orientation orientation) {
-            if (orientation != null) {
-                switch (orientation) {
-                    default:
-                    case LEFT_RIGHT:
-                        return 0;
-                    case BL_TR:
-                        return 45;
-                    case BOTTOM_TOP:
-                        return 90;
-                    case BR_TL:
-                        return 135;
-                    case RIGHT_LEFT:
-                        return 180;
-                    case TR_BL:
-                        return 225;
-                    case TOP_BOTTOM:
-                        return 270;
-                    case TL_BR:
-                        return 315;
-                }
-            } else {
-                return 0;
-            }
-        }
-
         public void setGradientColors(@Nullable int[] colors) {
             mGradientColors = colors;
             mSolidColors = null;
diff --git a/keystore/java/android/security/KeyChain.java b/keystore/java/android/security/KeyChain.java
index 1829d2f..bf23634 100644
--- a/keystore/java/android/security/KeyChain.java
+++ b/keystore/java/android/security/KeyChain.java
@@ -343,6 +343,16 @@
     public static final int KEY_ATTESTATION_FAILURE = 4;
 
     /**
+     * Used by DPC or delegated app in
+     * {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias} or
+     * {@link android.app.admin.DelegatedAdminReceiver#onChoosePrivateKeyAlias} to identify that
+     * the requesting app is not granted access to any key, and nor will the user be able to grant
+     * access manually.
+     */
+    public static final String KEY_ALIAS_SELECTION_DENIED =
+            "alias-selection-denied-ef829e15-210a-409d-96c9-ee684fc41972";
+
+    /**
      * Returns an {@code Intent} that can be used for credential
      * installation. The intent may be used without any extras, in
      * which case the user will be able to install credentials from
diff --git a/keystore/java/android/security/keystore/AttestationUtils.java b/keystore/java/android/security/keystore/AttestationUtils.java
index bd497c1..94499ce 100644
--- a/keystore/java/android/security/keystore/AttestationUtils.java
+++ b/keystore/java/android/security/keystore/AttestationUtils.java
@@ -74,6 +74,13 @@
     public static final int ID_TYPE_MEID = 3;
 
     /**
+     * Specifies that the device should attest its MEIDs. For use with {@link #attestDeviceIds}.
+     *
+     * @see #attestDeviceIds
+     */
+    public static final int USE_INDIVIDUAL_ATTESTATION = 4;
+
+    /**
      * Creates an array of X509Certificates from the provided KeymasterCertificateChain.
      *
      * @hide Only called by the DevicePolicyManager.
@@ -196,6 +203,13 @@
                             meid.getBytes(StandardCharsets.UTF_8));
                     break;
                 }
+                case USE_INDIVIDUAL_ATTESTATION: {
+                    //TODO: Add the Keymaster tag for requesting the use of individual
+                    //attestation certificate, which should be
+                    //KeymasterDefs.KM_TAG_DEVICE_UNIQUE_ATTESTATION
+                    attestArgs.addBoolean(720);
+                    break;
+                }
                 default:
                     throw new IllegalArgumentException("Unknown device ID type " + idType);
             }
diff --git a/libs/androidfw/AssetManager2.cpp b/libs/androidfw/AssetManager2.cpp
index 01caf01..eec49df 100644
--- a/libs/androidfw/AssetManager2.cpp
+++ b/libs/androidfw/AssetManager2.cpp
@@ -224,6 +224,62 @@
   return &loaded_package->GetOverlayableMap();
 }
 
+bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name,
+                                            std::string* out) const {
+  uint8_t package_id = 0U;
+  for (const auto& apk_assets : apk_assets_) {
+    const LoadedArsc* loaded_arsc = apk_assets->GetLoadedArsc();
+    if (loaded_arsc == nullptr) {
+      continue;
+    }
+
+    const auto& loaded_packages = loaded_arsc->GetPackages();
+    if (loaded_packages.empty()) {
+      continue;
+    }
+
+    const auto& loaded_package = loaded_packages[0];
+    if (loaded_package->GetPackageName() == package_name) {
+      package_id = GetAssignedPackageId(loaded_package.get());
+      break;
+    }
+  }
+
+  if (package_id == 0U) {
+    ANDROID_LOG(ERROR) << base::StringPrintf("No package with name '%s", package_name.data());
+    return false;
+  }
+
+  const size_t idx = package_ids_[package_id];
+  if (idx == 0xff) {
+    return false;
+  }
+
+  std::string output;
+  for (const ConfiguredPackage& package : package_groups_[idx].packages_) {
+    const LoadedPackage* loaded_package = package.loaded_package_;
+    for (auto it = loaded_package->begin(); it != loaded_package->end(); it++) {
+      const OverlayableInfo* info = loaded_package->GetOverlayableInfo(*it);
+      if (info != nullptr) {
+        ResourceName res_name;
+        if (!GetResourceName(*it, &res_name)) {
+          ANDROID_LOG(ERROR) << base::StringPrintf(
+              "Unable to retrieve name of overlayable resource 0x%08x", *it);
+          return false;
+        }
+
+        const std::string name = ToFormattedResourceString(&res_name);
+        output.append(base::StringPrintf(
+            "resource='%s' overlayable='%s' actor='%s' policy='0x%08x'\n",
+            name.c_str(), info->name.c_str(), info->actor.c_str(), info->policy_flags));
+      }
+    }
+  }
+
+  *out = std::move(output);
+  return true;
+}
+
 void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
   const int diff = configuration_.diff(configuration);
   configuration_ = configuration;
@@ -1073,7 +1129,7 @@
   }
 }
 
-uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
+uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) const {
   for (auto& package_group : package_groups_) {
     for (auto& package2 : package_group.packages_) {
       if (package2.loaded_package_ == package) {
diff --git a/libs/androidfw/include/androidfw/AssetManager2.h b/libs/androidfw/include/androidfw/AssetManager2.h
index 1e2b36c..de46081 100644
--- a/libs/androidfw/include/androidfw/AssetManager2.h
+++ b/libs/androidfw/include/androidfw/AssetManager2.h
@@ -124,6 +124,10 @@
   // This may be nullptr if the APK represented by `cookie` has no resource table.
   const DynamicRefTable* GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const;
 
+  // Returns a string representation of the overlayable API of a package.
+  bool GetOverlayablesToString(const android::StringPiece& package_name,
+                               std::string* out) const;
+
   const std::unordered_map<std::string, std::string>*
     GetOverlayableMapForPackage(uint32_t package_id) const;
 
@@ -308,7 +312,7 @@
   const ResolvedBag* GetBag(uint32_t resid, std::vector<uint32_t>& child_resids);
 
   // Retrieve the assigned package id of the package if loaded into this AssetManager
-  uint8_t GetAssignedPackageId(const LoadedPackage* package);
+  uint8_t GetAssignedPackageId(const LoadedPackage* package) const;
 
   // The ordered list of ApkAssets to search. These are not owned by the AssetManager, and must
   // have a longer lifetime.
diff --git a/libs/androidfw/tests/AssetManager2_test.cpp b/libs/androidfw/tests/AssetManager2_test.cpp
index 40c8e46..1591024 100644
--- a/libs/androidfw/tests/AssetManager2_test.cpp
+++ b/libs/androidfw/tests/AssetManager2_test.cpp
@@ -707,7 +707,7 @@
   EXPECT_EQ("", resultDisabled);
 }
 
-TEST_F(AssetManager2Test, GetOverlayableMap) {
+TEST_F(AssetManager2Test, GetOverlayablesToString) {
   ResTable_config desired_config;
   memset(&desired_config, 0, sizeof(desired_config));
 
@@ -721,6 +721,12 @@
   ASSERT_EQ(2, map->size());
   ASSERT_EQ(map->at("OverlayableResources1"), "overlay://theme");
   ASSERT_EQ(map->at("OverlayableResources2"), "overlay://com.android.overlayable");
+
+  std::string api;
+  ASSERT_TRUE(assetmanager.GetOverlayablesToString("com.android.overlayable", &api));
+  ASSERT_EQ(api.find("not_overlayable"), std::string::npos);
+  ASSERT_NE(api.find("resource='com.android.overlayable:string/overlayable2' overlayable='OverlayableResources1' actor='overlay://theme' policy='0x0000000a'\n"),
+            std::string::npos);
 }
 
 }  // namespace android
diff --git a/libs/hwui/pipeline/skia/LayerDrawable.cpp b/libs/hwui/pipeline/skia/LayerDrawable.cpp
index b017384..f839213e 100644
--- a/libs/hwui/pipeline/skia/LayerDrawable.cpp
+++ b/libs/hwui/pipeline/skia/LayerDrawable.cpp
@@ -43,41 +43,28 @@
     if (!matrix.rectStaysRect()) return true;
     SkRect dstDevRect = matrix.mapRect(dstRect);
     float dstW, dstH;
-    bool requiresIntegerTranslate = false;
     if (MathUtils::isZero(matrix.getScaleX()) && MathUtils::isZero(matrix.getScaleY())) {
         // Has a 90 or 270 degree rotation, although total matrix may also have scale factors
         // in m10 and m01. Those scalings are automatically handled by mapRect so comparing
         // dimensions is sufficient, but swap width and height comparison.
         dstW = dstDevRect.height();
         dstH = dstDevRect.width();
-        requiresIntegerTranslate = true;
     } else {
         // Handle H/V flips or 180 rotation matrices. Axes may have been mirrored, but
         // dimensions are still safe to compare directly.
         dstW = dstDevRect.width();
         dstH = dstDevRect.height();
-        requiresIntegerTranslate =
-                matrix.getScaleX() < -NON_ZERO_EPSILON || matrix.getScaleY() < -NON_ZERO_EPSILON;
     }
     if (!(MathUtils::areEqual(dstW, srcRect.width()) &&
           MathUtils::areEqual(dstH, srcRect.height()))) {
         return true;
     }
-    if (requiresIntegerTranslate) {
-        // Device rect and source rect should be integer aligned to ensure there's no difference
-        // in how nearest-neighbor sampling is resolved.
-        return !(isIntegerAligned(srcRect.x()) &&
-                 isIntegerAligned(srcRect.y()) &&
-                 isIntegerAligned(dstDevRect.x()) &&
-                 isIntegerAligned(dstDevRect.y()));
-    } else {
-        // As long as src and device rects are translated by the same fractional amount,
-        // filtering won't be needed
-        return !(MathUtils::areEqual(SkScalarFraction(srcRect.x()),
-                                     SkScalarFraction(dstDevRect.x())) &&
-                 MathUtils::areEqual(SkScalarFraction(srcRect.y()),
-                                     SkScalarFraction(dstDevRect.y())));
-    }
+    // Device rect and source rect should be integer aligned to ensure there's no difference
+    // in how nearest-neighbor sampling is resolved.
+    return !(isIntegerAligned(srcRect.x()) &&
+             isIntegerAligned(srcRect.y()) &&
+             isIntegerAligned(dstDevRect.x()) &&
+             isIntegerAligned(dstDevRect.y()));
 }
 
 bool LayerDrawable::DrawLayer(GrContext* context, SkCanvas* canvas, Layer* layer,
diff --git a/libs/hwui/pipeline/skia/SkiaPipeline.cpp b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
index 67c181b..3010206 100644
--- a/libs/hwui/pipeline/skia/SkiaPipeline.cpp
+++ b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
@@ -569,6 +569,7 @@
     // Set up the overdraw canvas.
     SkImageInfo offscreenInfo = SkImageInfo::MakeA8(surface->width(), surface->height());
     sk_sp<SkSurface> offscreen = surface->makeSurface(offscreenInfo);
+    LOG_ALWAYS_FATAL_IF(!offscreen, "Failed to create offscreen SkSurface for overdraw viz.");
     SkOverdrawCanvas overdrawCanvas(offscreen->getCanvas());
 
     // Fake a redraw to replay the draw commands.  This will increment the alpha channel
diff --git a/libs/hwui/renderthread/CacheManager.cpp b/libs/hwui/renderthread/CacheManager.cpp
index fc26813..8eb8153 100644
--- a/libs/hwui/renderthread/CacheManager.cpp
+++ b/libs/hwui/renderthread/CacheManager.cpp
@@ -39,7 +39,7 @@
 // to the screen resolution. This is meant to be a conservative default based on
 // that analysis. The 4.0f is used because the default pixel format is assumed to
 // be ARGB_8888.
-#define SURFACE_SIZE_MULTIPLIER (12.0f * 4.0f)
+#define SURFACE_SIZE_MULTIPLIER (5.0f * 4.0f)
 #define BACKGROUND_RETENTION_PERCENTAGE (0.5f)
 
 CacheManager::CacheManager(const DisplayInfo& display)
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index 684dc22..30cc007 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -491,9 +491,9 @@
                 swap.dequeueDuration = 0;
             } else {
                 swap.dequeueDuration =
-                        us2ns(ANativeWindow_getLastDequeueDuration(mNativeSurface.get()));
+                        ANativeWindow_getLastDequeueDuration(mNativeSurface.get());
             }
-            swap.queueDuration = us2ns(ANativeWindow_getLastQueueDuration(mNativeSurface.get()));
+            swap.queueDuration = ANativeWindow_getLastQueueDuration(mNativeSurface.get());
         } else {
             swap.dequeueDuration = 0;
             swap.queueDuration = 0;
diff --git a/libs/input/Android.bp b/libs/input/Android.bp
index 16f2917..6bb896fd 100644
--- a/libs/input/Android.bp
+++ b/libs/input/Android.bp
@@ -20,11 +20,11 @@
     ],
 
     shared_libs: [
+        "libandroid_runtime",
         "libbinder",
         "libcutils",
         "liblog",
         "libutils",
-        "libhwui",
         "libgui",
         "libui",
         "libinput",
diff --git a/libs/input/PointerController.cpp b/libs/input/PointerController.cpp
index abf0837..e4348f2 100644
--- a/libs/input/PointerController.cpp
+++ b/libs/input/PointerController.cpp
@@ -24,12 +24,6 @@
 
 #include <log/log.h>
 
-#include <SkBitmap.h>
-#include <SkCanvas.h>
-#include <SkColor.h>
-#include <SkPaint.h>
-#include <SkBlendMode.h>
-
 namespace android {
 
 // --- WeakLooperCallback ---
diff --git a/libs/input/SpriteController.cpp b/libs/input/SpriteController.cpp
index fd386e9..804644c 100644
--- a/libs/input/SpriteController.cpp
+++ b/libs/input/SpriteController.cpp
@@ -23,11 +23,9 @@
 #include <utils/String8.h>
 #include <gui/Surface.h>
 
-#include <SkBitmap.h>
-#include <SkCanvas.h>
-#include <SkColor.h>
-#include <SkPaint.h>
-
+#include <android/graphics/bitmap.h>
+#include <android/graphics/canvas.h>
+#include <android/graphics/paint.h>
 #include <android/native_window.h>
 
 namespace android {
@@ -132,8 +130,8 @@
         SpriteUpdate& update = updates.editItemAt(i);
 
         if (update.state.surfaceControl == NULL && update.state.wantSurfaceVisible()) {
-            update.state.surfaceWidth = update.state.icon.bitmap.width();
-            update.state.surfaceHeight = update.state.icon.bitmap.height();
+            update.state.surfaceWidth = update.state.icon.bitmap.getInfo().width;
+            update.state.surfaceHeight = update.state.icon.bitmap.getInfo().height;
             update.state.surfaceDrawn = false;
             update.state.surfaceVisible = false;
             update.state.surfaceControl = obtainSurface(
@@ -154,8 +152,8 @@
         }
 
         if (update.state.wantSurfaceVisible()) {
-            int32_t desiredWidth = update.state.icon.bitmap.width();
-            int32_t desiredHeight = update.state.icon.bitmap.height();
+            int32_t desiredWidth = update.state.icon.bitmap.getInfo().width;
+            int32_t desiredHeight = update.state.icon.bitmap.getInfo().height;
             if (update.state.surfaceWidth < desiredWidth
                     || update.state.surfaceHeight < desiredHeight) {
                 needApplyTransaction = true;
@@ -201,26 +199,22 @@
             if (status) {
                 ALOGE("Error %d locking sprite surface before drawing.", status);
             } else {
-                SkBitmap surfaceBitmap;
-                ssize_t bpr = outBuffer.stride * bytesPerPixel(outBuffer.format);
-                surfaceBitmap.installPixels(SkImageInfo::MakeN32Premul(outBuffer.width, outBuffer.height),
-                                            outBuffer.bits, bpr);
+                graphics::Paint paint;
+                paint.setBlendMode(ABLEND_MODE_SRC);
 
-                SkCanvas surfaceCanvas(surfaceBitmap);
+                graphics::Canvas canvas(outBuffer, (int32_t) surface->getBuffersDataSpace());
+                canvas.drawBitmap(update.state.icon.bitmap, 0, 0, &paint);
 
-                SkPaint paint;
-                paint.setBlendMode(SkBlendMode::kSrc);
-                surfaceCanvas.drawBitmap(update.state.icon.bitmap, 0, 0, &paint);
+                const int iconWidth = update.state.icon.bitmap.getInfo().width;
+                const int iconHeight = update.state.icon.bitmap.getInfo().height;
 
-                if (outBuffer.width > update.state.icon.bitmap.width()) {
-                    paint.setColor(0); // transparent fill color
-                    surfaceCanvas.drawRect(SkRect::MakeLTRB(update.state.icon.bitmap.width(), 0,
-                            outBuffer.width, update.state.icon.bitmap.height()), paint);
+                if (outBuffer.width > iconWidth) {
+                    paint.setBlendMode(ABLEND_MODE_CLEAR); // clear to transparent
+                    canvas.drawRect({iconWidth, 0, outBuffer.width, iconHeight}, paint);
                 }
-                if (outBuffer.height > update.state.icon.bitmap.height()) {
-                    paint.setColor(0); // transparent fill color
-                    surfaceCanvas.drawRect(SkRect::MakeLTRB(0, update.state.icon.bitmap.height(),
-                            outBuffer.width, outBuffer.height), paint);
+                if (outBuffer.height > iconHeight) {
+                    paint.setBlendMode(ABLEND_MODE_CLEAR); // clear to transparent
+                    canvas.drawRect({0, iconHeight, outBuffer.width, outBuffer.height}, paint);
                 }
 
                 status = surface->unlockAndPost();
@@ -398,12 +392,7 @@
 
     uint32_t dirty;
     if (icon.isValid()) {
-        SkBitmap* bitmapCopy = &mLocked.state.icon.bitmap;
-        if (bitmapCopy->tryAllocPixels(icon.bitmap.info().makeColorType(kN32_SkColorType))) {
-            icon.bitmap.readPixels(bitmapCopy->info(), bitmapCopy->getPixels(),
-                    bitmapCopy->rowBytes(), 0, 0);
-        }
-
+        mLocked.state.icon.bitmap = icon.bitmap.copy(ANDROID_BITMAP_FORMAT_RGBA_8888);
         if (!mLocked.state.icon.isValid()
                 || mLocked.state.icon.hotSpotX != icon.hotSpotX
                 || mLocked.state.icon.hotSpotY != icon.hotSpotY) {
diff --git a/libs/input/SpriteController.h b/libs/input/SpriteController.h
index 79a904f..2513544 100644
--- a/libs/input/SpriteController.h
+++ b/libs/input/SpriteController.h
@@ -20,10 +20,9 @@
 #include <utils/RefBase.h>
 #include <utils/Looper.h>
 
+#include <android/graphics/bitmap.h>
 #include <gui/SurfaceComposerClient.h>
 
-#include <SkBitmap.h>
-
 namespace android {
 
 /*
@@ -56,21 +55,16 @@
  */
 struct SpriteIcon {
     inline SpriteIcon() : style(0), hotSpotX(0), hotSpotY(0) { }
-    inline SpriteIcon(const SkBitmap& bitmap, int32_t style, float hotSpotX, float hotSpotY) :
+    inline SpriteIcon(const graphics::Bitmap& bitmap, int32_t style, float hotSpotX, float hotSpotY) :
             bitmap(bitmap), style(style), hotSpotX(hotSpotX), hotSpotY(hotSpotY) { }
 
-    SkBitmap bitmap;
+    graphics::Bitmap bitmap;
     int32_t style;
     float hotSpotX;
     float hotSpotY;
 
     inline SpriteIcon copy() const {
-        SkBitmap bitmapCopy;
-        if (bitmapCopy.tryAllocPixels(bitmap.info().makeColorType(kN32_SkColorType))) {
-            bitmap.readPixels(bitmapCopy.info(), bitmapCopy.getPixels(), bitmapCopy.rowBytes(),
-                    0, 0);
-        }
-        return SpriteIcon(bitmapCopy, style, hotSpotX, hotSpotY);
+        return SpriteIcon(bitmap.copy(ANDROID_BITMAP_FORMAT_RGBA_8888), style, hotSpotX, hotSpotY);
     }
 
     inline void reset() {
@@ -81,7 +75,7 @@
     }
 
     inline bool isValid() const {
-        return !bitmap.isNull() && !bitmap.empty();
+        return bitmap.isValid() && !bitmap.isEmpty();
     }
 };
 
@@ -183,7 +177,7 @@
      * This structure is designed so that it can be copied during updates so that
      * surfaces can be resized and redrawn without blocking the client by holding a lock
      * on the sprites for a long time.
-     * Note that the SkBitmap holds a reference to a shared (and immutable) pixel ref. */
+     * Note that the SpriteIcon holds a reference to a shared (and immutable) bitmap. */
     struct SpriteState {
         inline SpriteState() :
                 dirty(0), visible(false),
diff --git a/libs/input/tests/Android.bp b/libs/input/tests/Android.bp
index e83b2a7..b1e3d6f 100644
--- a/libs/input/tests/Android.bp
+++ b/libs/input/tests/Android.bp
@@ -18,9 +18,9 @@
         "PointerController_test.cpp",
     ],
     shared_libs: [
+        "libandroid_runtime",
         "libinputservice",
         "libgui",
-        "libhwui",
         "libutils",
     ],
     static_libs: [
diff --git a/location/java/android/location/AbstractListenerManager.java b/location/java/android/location/AbstractListenerManager.java
new file mode 100644
index 0000000..c41023e
--- /dev/null
+++ b/location/java/android/location/AbstractListenerManager.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2014 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.location;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.HandlerExecutor;
+import android.os.RemoteException;
+import android.util.ArrayMap;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.util.Preconditions;
+
+import java.util.concurrent.Executor;
+import java.util.function.Consumer;
+
+/**
+ * A base class to manage listeners that have a 1:N -> source:listener relationship.
+ *
+ * @hide
+ */
+abstract class AbstractListenerManager<T> {
+
+    private static class Registration<T> {
+        private final Executor mExecutor;
+        @Nullable private volatile T mListener;
+
+        private Registration(Executor executor, T listener) {
+            Preconditions.checkArgument(listener != null);
+            Preconditions.checkArgument(executor != null);
+            mExecutor = executor;
+            mListener = listener;
+        }
+
+        private void unregister() {
+            mListener = null;
+        }
+
+        private void execute(Consumer<T> operation) {
+            mExecutor.execute(() -> {
+                T listener = mListener;
+                if (listener == null) {
+                    return;
+                }
+
+                // we may be under the binder identity if a direct executor is used
+                long identity = Binder.clearCallingIdentity();
+                try {
+                    operation.accept(listener);
+                } finally {
+                    Binder.restoreCallingIdentity(identity);
+                }
+            });
+        }
+    }
+
+    @GuardedBy("mListeners")
+    private final ArrayMap<Object, Registration<T>> mListeners = new ArrayMap<>();
+
+    public boolean addListener(@NonNull T listener, @NonNull Handler handler)
+            throws RemoteException {
+        return addInternal(listener, handler);
+    }
+
+    public boolean addListener(@NonNull T listener, @NonNull Executor executor)
+            throws RemoteException {
+        return addInternal(listener, executor);
+    }
+
+    protected final boolean addInternal(Object listener, Handler handler) throws RemoteException {
+        return addInternal(listener, new HandlerExecutor(handler));
+    }
+
+    protected final boolean addInternal(Object listener, Executor executor) throws RemoteException {
+        return addInternal(listener, new Registration<>(executor, convertKey(listener)));
+    }
+
+    private boolean addInternal(Object key, Registration<T> registration) throws RemoteException {
+        Preconditions.checkNotNull(key);
+        Preconditions.checkNotNull(registration);
+
+        synchronized (mListeners) {
+            if (mListeners.isEmpty() && !registerService()) {
+                return false;
+            }
+            Registration<T> oldRegistration = mListeners.put(key, registration);
+            if (oldRegistration != null) {
+                oldRegistration.unregister();
+            }
+            return true;
+        }
+    }
+
+    public void removeListener(Object listener) throws RemoteException {
+        synchronized (mListeners) {
+            Registration<T> oldRegistration = mListeners.remove(listener);
+            if (oldRegistration == null) {
+                return;
+            }
+            oldRegistration.unregister();
+
+            if (mListeners.isEmpty()) {
+                unregisterService();
+            }
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    protected T convertKey(@NonNull Object listener) {
+        return (T) listener;
+    }
+
+    protected abstract boolean registerService() throws RemoteException;
+    protected abstract void unregisterService() throws RemoteException;
+
+    protected void execute(Consumer<T> operation) {
+        synchronized (mListeners) {
+            for (Registration<T> registration : mListeners.values()) {
+                registration.execute(operation);
+            }
+        }
+    }
+}
diff --git a/location/java/android/location/BatchedLocationCallbackTransport.java b/location/java/android/location/BatchedLocationCallbackTransport.java
deleted file mode 100644
index e00f855..0000000
--- a/location/java/android/location/BatchedLocationCallbackTransport.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 android.location;
-
-import android.content.Context;
-import android.os.RemoteException;
-
-import java.util.List;
-
-/**
- * A handler class to manage transport callbacks for {@link BatchedLocationCallback}.
- *
- * @hide
- */
-class BatchedLocationCallbackTransport
-        extends LocalListenerHelper<BatchedLocationCallback> {
-    private final ILocationManager mLocationManager;
-
-    private final IBatchedLocationCallback mCallbackTransport = new CallbackTransport();
-
-    public BatchedLocationCallbackTransport(Context context, ILocationManager locationManager) {
-        super(context, "BatchedLocationCallbackTransport");
-        mLocationManager = locationManager;
-    }
-
-    @Override
-    protected boolean registerWithServer() throws RemoteException {
-        return mLocationManager.addGnssBatchingCallback(
-                mCallbackTransport,
-                getContext().getPackageName());
-    }
-
-    @Override
-    protected void unregisterFromServer() throws RemoteException {
-        mLocationManager.removeGnssBatchingCallback();
-    }
-
-    private class CallbackTransport extends IBatchedLocationCallback.Stub {
-        @Override
-        public void onLocationBatch(final List<Location> locations) {
-            ListenerOperation<BatchedLocationCallback> operation =
-                    new ListenerOperation<BatchedLocationCallback>() {
-                @Override
-                public void execute(BatchedLocationCallback callback)
-                        throws RemoteException {
-                    callback.onLocationBatch(locations);
-                }
-            };
-            foreach(operation);
-        }
-    }
-}
diff --git a/location/java/android/location/GnssMeasurementCallbackTransport.java b/location/java/android/location/GnssMeasurementCallbackTransport.java
deleted file mode 100644
index 8cb8c0b..0000000
--- a/location/java/android/location/GnssMeasurementCallbackTransport.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2014 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.location;
-
-import android.content.Context;
-import android.os.RemoteException;
-
-import com.android.internal.util.Preconditions;
-
-/**
- * A handler class to manage transport callbacks for {@link GnssMeasurementsEvent.Callback}.
- *
- * @hide
- */
-class GnssMeasurementCallbackTransport
-        extends LocalListenerHelper<GnssMeasurementsEvent.Callback> {
-    private static final String TAG = "GnssMeasCbTransport";
-    private final ILocationManager mLocationManager;
-
-    private final IGnssMeasurementsListener mListenerTransport = new ListenerTransport();
-
-    public GnssMeasurementCallbackTransport(Context context, ILocationManager locationManager) {
-        super(context, TAG);
-        mLocationManager = locationManager;
-    }
-
-    @Override
-    protected boolean registerWithServer() throws RemoteException {
-        return mLocationManager.addGnssMeasurementsListener(
-                mListenerTransport,
-                getContext().getPackageName());
-    }
-
-    @Override
-    protected void unregisterFromServer() throws RemoteException {
-        mLocationManager.removeGnssMeasurementsListener(mListenerTransport);
-    }
-
-    /**
-     * Injects GNSS measurement corrections into the GNSS chipset.
-     *
-     * @param measurementCorrections a {@link GnssMeasurementCorrections} object with the GNSS
-     *     measurement corrections to be injected into the GNSS chipset.
-     */
-    protected void injectGnssMeasurementCorrections(
-            GnssMeasurementCorrections measurementCorrections) throws RemoteException {
-        Preconditions.checkNotNull(measurementCorrections);
-        mLocationManager.injectGnssMeasurementCorrections(
-                measurementCorrections, getContext().getPackageName());
-    }
-
-    protected long getGnssCapabilities() throws RemoteException {
-        return mLocationManager.getGnssCapabilities(getContext().getPackageName());
-    }
-
-    private class ListenerTransport extends IGnssMeasurementsListener.Stub {
-        @Override
-        public void onGnssMeasurementsReceived(final GnssMeasurementsEvent event) {
-            ListenerOperation<GnssMeasurementsEvent.Callback> operation =
-                    new ListenerOperation<GnssMeasurementsEvent.Callback>() {
-                        @Override
-                        public void execute(GnssMeasurementsEvent.Callback callback)
-                                throws RemoteException {
-                            callback.onGnssMeasurementsReceived(event);
-                        }
-                    };
-            foreach(operation);
-        }
-
-        @Override
-        public void onStatusChanged(final int status) {
-            ListenerOperation<GnssMeasurementsEvent.Callback> operation =
-                    new ListenerOperation<GnssMeasurementsEvent.Callback>() {
-                @Override
-                public void execute(GnssMeasurementsEvent.Callback callback)
-                        throws RemoteException {
-                    callback.onStatusChanged(status);
-                }
-            };
-            foreach(operation);
-        }
-    }
-}
diff --git a/location/java/android/location/GnssNavigationMessageCallbackTransport.java b/location/java/android/location/GnssNavigationMessageCallbackTransport.java
deleted file mode 100644
index 1eafd02..0000000
--- a/location/java/android/location/GnssNavigationMessageCallbackTransport.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2014 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.location;
-
-import android.content.Context;
-import android.os.RemoteException;
-
-/**
- * A handler class to manage transport callback for {@link GnssNavigationMessage.Callback}.
- *
- * @hide
- */
-class GnssNavigationMessageCallbackTransport
-        extends LocalListenerHelper<GnssNavigationMessage.Callback> {
-    private final ILocationManager mLocationManager;
-
-    private final IGnssNavigationMessageListener mListenerTransport = new ListenerTransport();
-
-    public GnssNavigationMessageCallbackTransport(
-            Context context,
-            ILocationManager locationManager) {
-        super(context, "GnssNavigationMessageCallbackTransport");
-        mLocationManager = locationManager;
-    }
-
-    @Override
-    protected boolean registerWithServer() throws RemoteException {
-        return mLocationManager.addGnssNavigationMessageListener(
-                mListenerTransport,
-                getContext().getPackageName());
-    }
-
-    @Override
-    protected void unregisterFromServer() throws RemoteException {
-        mLocationManager.removeGnssNavigationMessageListener(mListenerTransport);
-    }
-
-    private class ListenerTransport extends IGnssNavigationMessageListener.Stub {
-        @Override
-        public void onGnssNavigationMessageReceived(final GnssNavigationMessage event) {
-            ListenerOperation<GnssNavigationMessage.Callback> operation =
-                    new ListenerOperation<GnssNavigationMessage.Callback>() {
-                @Override
-                public void execute(GnssNavigationMessage.Callback callback)
-                        throws RemoteException {
-                    callback.onGnssNavigationMessageReceived(event);
-                }
-            };
-            foreach(operation);
-        }
-
-        @Override
-        public void onStatusChanged(final int status) {
-            ListenerOperation<GnssNavigationMessage.Callback> operation =
-                    new ListenerOperation<GnssNavigationMessage.Callback>() {
-                @Override
-                public void execute(GnssNavigationMessage.Callback callback)
-                        throws RemoteException {
-                    callback.onStatusChanged(status);
-                }
-            };
-            foreach(operation);
-        }
-    }
-}
diff --git a/location/java/android/location/LocalListenerHelper.java b/location/java/android/location/LocalListenerHelper.java
deleted file mode 100644
index 592d01d..0000000
--- a/location/java/android/location/LocalListenerHelper.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2014 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.location;
-
-import android.annotation.NonNull;
-import android.content.Context;
-import android.os.Handler;
-import android.os.RemoteException;
-import android.util.Log;
-
-import com.android.internal.util.Preconditions;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A base handler class to manage transport and local listeners.
- *
- * @hide
- */
-abstract class LocalListenerHelper<TListener> {
-    private final HashMap<TListener, Handler> mListeners = new HashMap<>();
-
-    private final String mTag;
-    private final Context mContext;
-
-    protected LocalListenerHelper(Context context, String name) {
-        Preconditions.checkNotNull(name);
-        mContext = context;
-        mTag = name;
-    }
-
-    /**
-     * Adds a {@param listener} to the list of listeners on which callbacks will be executed. The
-     * execution will happen on the {@param handler} thread or alternatively in the callback thread
-     * if a  {@code null} handler value is passed.
-     */
-    public boolean add(@NonNull TListener listener, Handler handler) {
-        Preconditions.checkNotNull(listener);
-        synchronized (mListeners) {
-            // we need to register with the service first, because we need to find out if the
-            // service will actually support the request before we attempt anything
-            if (mListeners.isEmpty()) {
-                boolean registeredWithService;
-                try {
-                    registeredWithService = registerWithServer();
-                } catch (RemoteException e) {
-                    Log.e(mTag, "Error handling first listener.", e);
-                    return false;
-                }
-                if (!registeredWithService) {
-                    Log.e(mTag, "Unable to register listener transport.");
-                    return false;
-                }
-            }
-            if (mListeners.containsKey(listener)) {
-                return true;
-            }
-            mListeners.put(listener, handler);
-            return true;
-        }
-    }
-
-    public void remove(@NonNull TListener listener) {
-        Preconditions.checkNotNull(listener);
-        synchronized (mListeners) {
-            boolean removed = mListeners.containsKey(listener);
-            mListeners.remove(listener);
-            boolean isLastRemoved = removed && mListeners.isEmpty();
-            if (isLastRemoved) {
-                try {
-                    unregisterFromServer();
-                } catch (RemoteException e) {
-                    Log.v(mTag, "Error handling last listener removal", e);
-                }
-            }
-        }
-    }
-
-    protected abstract boolean registerWithServer() throws RemoteException;
-    protected abstract void unregisterFromServer() throws RemoteException;
-
-    protected interface ListenerOperation<TListener> {
-        void execute(TListener listener) throws RemoteException;
-    }
-
-    protected Context getContext() {
-        return mContext;
-    }
-
-    private void executeOperation(ListenerOperation<TListener> operation, TListener listener) {
-        try {
-            operation.execute(listener);
-        } catch (RemoteException e) {
-            Log.e(mTag, "Error in monitored listener.", e);
-            // don't return, give a fair chance to all listeners to receive the event
-        }
-    }
-
-    protected void foreach(final ListenerOperation<TListener> operation) {
-        Collection<Map.Entry<TListener, Handler>> listeners;
-        synchronized (mListeners) {
-            listeners = new ArrayList<>(mListeners.entrySet());
-        }
-        for (final Map.Entry<TListener, Handler> listener : listeners) {
-            if (listener.getValue() == null) {
-                executeOperation(operation, listener.getKey());
-            } else {
-                listener.getValue().post(new Runnable() {
-                    @Override
-                    public void run() {
-                        executeOperation(operation, listener.getKey());
-                    }
-                });
-            }
-        }
-    }
-}
diff --git a/location/java/android/location/LocationManager.java b/location/java/android/location/LocationManager.java
index 5be4770..90e29df 100644
--- a/location/java/android/location/LocationManager.java
+++ b/location/java/android/location/LocationManager.java
@@ -22,24 +22,24 @@
 import static android.Manifest.permission.WRITE_SECURE_SETTINGS;
 
 import android.Manifest;
+import android.annotation.CallbackExecutor;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.RequiresFeature;
 import android.annotation.RequiresPermission;
-import android.annotation.SuppressLint;
 import android.annotation.SystemApi;
 import android.annotation.SystemService;
 import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.app.PendingIntent;
 import android.content.Context;
-import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.os.Binder;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.HandlerExecutor;
 import android.os.Looper;
-import android.os.Message;
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.UserHandle;
@@ -47,47 +47,32 @@
 import android.util.ArrayMap;
 import android.util.Log;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.location.ProviderProperties;
 import com.android.internal.util.Preconditions;
 
-import java.util.ArrayList;
 import java.util.List;
+import java.util.concurrent.Executor;
+import java.util.concurrent.RejectedExecutionException;
 
 /**
- * This class provides access to the system location services.  These
- * services allow applications to obtain periodic updates of the
- * device's geographical location, or to fire an application-specified
- * {@link Intent} when the device enters the proximity of a given
- * geographical location.
+ * This class provides access to the system location services. These services allow applications to
+ * obtain periodic updates of the device's geographical location, or to be notified when the device
+ * enters the proximity of a given geographical location.
  *
- * <p class="note">Unless noted, all Location API methods require
- * the {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} or
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permissions.
- * If your application only has the coarse permission then it will not have
- * access to the GPS or passive location providers. Other providers will still
- * return location results, but the update rate will be throttled and the exact
- * location will be obfuscated to a coarse level of accuracy.
+ * <p class="note">Unless noted, all Location API methods require the {@link
+ * android.Manifest.permission#ACCESS_COARSE_LOCATION} or {@link
+ * android.Manifest.permission#ACCESS_FINE_LOCATION} permissions. If your application only has the
+ * coarse permission then it will not have access to fine location providers. Other providers will
+ * still return location results, but the exact location will be obfuscated to a coarse level of
+ * accuracy.
  */
+@SuppressWarnings({"deprecation", "DeprecatedIsStillUsed"})
 @SystemService(Context.LOCATION_SERVICE)
 @RequiresFeature(PackageManager.FEATURE_LOCATION)
 public class LocationManager {
-    private static final String TAG = "LocationManager";
 
-    private final Context mContext;
-    @UnsupportedAppUsage
-    private final ILocationManager mService;
-    private final GnssMeasurementCallbackTransport mGnssMeasurementCallbackTransport;
-    private final GnssNavigationMessageCallbackTransport mGnssNavigationMessageCallbackTransport;
-    private final BatchedLocationCallbackTransport mBatchedLocationCallbackTransport;
-    private final ArrayMap<GnssStatus.Callback, GnssStatusListenerTransport> mGnssStatusListeners =
-            new ArrayMap<>();
-    private final ArrayMap<OnNmeaMessageListener, GnssStatusListenerTransport> mGnssNmeaListeners =
-            new ArrayMap<>();
-    private final ArrayMap<GpsStatus.Listener, GnssStatusListenerTransport> mGpsStatusListeners =
-            new ArrayMap<>();
-    // volatile + GnssStatus final-fields pattern to avoid a partially published object
-    private volatile GnssStatus mGnssStatus;
-    private int mTimeToFirstFix;
+    private static final String TAG = "LocationManager";
 
     /**
      * Name of the network location provider.
@@ -148,23 +133,27 @@
     /**
      * This key is no longer in use.
      *
-     * Key used for a Bundle extra holding an Integer status value
-     * when a status change is broadcast using a PendingIntent.
+     * <p>Key used for a Bundle extra holding an Integer status value when a status change is
+     * broadcast using a PendingIntent.
      *
-     * @deprecated Status changes are deprecated and no longer broadcast.
+     * @deprecated Status changes are deprecated and no longer broadcast from Android Q onwards.
      */
     @Deprecated
     public static final String KEY_STATUS_CHANGED = "status";
 
     /**
-     * Key used for a Bundle extra holding an Boolean status value
-     * when a provider enabled/disabled event is broadcast using a PendingIntent.
+     * Key used for an extra holding a boolean enabled/disabled status value when a provider
+     * enabled/disabled event is broadcast using a PendingIntent.
+     *
+     * @see #requestLocationUpdates(String, long, float, PendingIntent)
      */
     public static final String KEY_PROVIDER_ENABLED = "providerEnabled";
 
     /**
-     * Key used for a Bundle extra holding a Location value
-     * when a location change is broadcast using a PendingIntent.
+     * Key used for an extra holding a {@link Location} value when a location change is broadcast
+     * using a PendingIntent.
+     *
+     * @see #requestLocationUpdates(String, long, float, PendingIntent)
      */
     public static final String KEY_LOCATION_CHANGED = "location";
 
@@ -238,112 +227,31 @@
     public static final String METADATA_SETTINGS_FOOTER_STRING =
             "com.android.settings.location.FOOTER_STRING";
 
-    // Map from LocationListeners to their associated ListenerTransport objects
-    private final ArrayMap<LocationListener, ListenerTransport> mListeners = new ArrayMap<>();
+    private final Context mContext;
 
-    private class ListenerTransport extends ILocationListener.Stub {
-        private static final int TYPE_LOCATION_CHANGED = 1;
-        private static final int TYPE_STATUS_CHANGED = 2;
-        private static final int TYPE_PROVIDER_ENABLED = 3;
-        private static final int TYPE_PROVIDER_DISABLED = 4;
+    @UnsupportedAppUsage
+    private final ILocationManager mService;
 
-        private LocationListener mListener;
-        private final Handler mListenerHandler;
+    @GuardedBy("mListeners")
+    private final ArrayMap<LocationListener, LocationListenerTransport> mListeners =
+            new ArrayMap<>();
 
-        ListenerTransport(LocationListener listener, Looper looper) {
-            mListener = listener;
+    @GuardedBy("mBatchedLocationCallbackManager")
+    private final BatchedLocationCallbackManager mBatchedLocationCallbackManager =
+            new BatchedLocationCallbackManager();
+    private final GnssStatusListenerManager
+            mGnssStatusListenerManager = new GnssStatusListenerManager();
+    private final GnssMeasurementsListenerManager mGnssMeasurementsListenerManager =
+            new GnssMeasurementsListenerManager();
+    private final GnssNavigationMessageListenerManager mGnssNavigationMessageListenerTransport =
+            new GnssNavigationMessageListenerManager();
 
-            if (looper == null) {
-                mListenerHandler = new Handler() {
-                    @Override
-                    public void handleMessage(Message msg) {
-                        _handleMessage(msg);
-                    }
-                };
-            } else {
-                mListenerHandler = new Handler(looper) {
-                    @Override
-                    public void handleMessage(Message msg) {
-                        _handleMessage(msg);
-                    }
-                };
-            }
-        }
-
-        @Override
-        public void onLocationChanged(Location location) {
-            Message msg = Message.obtain();
-            msg.what = TYPE_LOCATION_CHANGED;
-            msg.obj = location;
-            sendCallbackMessage(msg);
-        }
-
-        @Override
-        public void onStatusChanged(String provider, int status, Bundle extras) {
-            Message msg = Message.obtain();
-            msg.what = TYPE_STATUS_CHANGED;
-            Bundle b = new Bundle();
-            b.putString("provider", provider);
-            b.putInt("status", status);
-            if (extras != null) {
-                b.putBundle("extras", extras);
-            }
-            msg.obj = b;
-            sendCallbackMessage(msg);
-        }
-
-        @Override
-        public void onProviderEnabled(String provider) {
-            Message msg = Message.obtain();
-            msg.what = TYPE_PROVIDER_ENABLED;
-            msg.obj = provider;
-            sendCallbackMessage(msg);
-        }
-
-        @Override
-        public void onProviderDisabled(String provider) {
-            Message msg = Message.obtain();
-            msg.what = TYPE_PROVIDER_DISABLED;
-            msg.obj = provider;
-            sendCallbackMessage(msg);
-        }
-
-        private void sendCallbackMessage(Message msg) {
-            if (!mListenerHandler.sendMessage(msg)) {
-                locationCallbackFinished();
-            }
-        }
-
-        private void _handleMessage(Message msg) {
-            switch (msg.what) {
-                case TYPE_LOCATION_CHANGED:
-                    Location location = new Location((Location) msg.obj);
-                    mListener.onLocationChanged(location);
-                    break;
-                case TYPE_STATUS_CHANGED:
-                    Bundle b = (Bundle) msg.obj;
-                    String provider = b.getString("provider");
-                    int status = b.getInt("status");
-                    Bundle extras = b.getBundle("extras");
-                    mListener.onStatusChanged(provider, status, extras);
-                    break;
-                case TYPE_PROVIDER_ENABLED:
-                    mListener.onProviderEnabled((String) msg.obj);
-                    break;
-                case TYPE_PROVIDER_DISABLED:
-                    mListener.onProviderDisabled((String) msg.obj);
-                    break;
-            }
-            locationCallbackFinished();
-        }
-
-        private void locationCallbackFinished() {
-            try {
-                mService.locationCallbackFinished(this);
-            } catch (RemoteException e) {
-                throw e.rethrowFromSystemServer();
-            }
-        }
+    /**
+     * @hide
+     */
+    public LocationManager(@NonNull Context context, @NonNull ILocationManager service) {
+        mService = service;
+        mContext = context;
     }
 
     /**
@@ -371,367 +279,273 @@
     }
 
     /**
-     * @hide - hide this constructor because it has a parameter
-     * of type ILocationManager, which is a system private class. The
-     * right way to create an instance of this class is using the
-     * factory Context.getSystemService.
+     * Returns the extra location controller package on the device.
+     *
+     * @hide
      */
-    public LocationManager(@NonNull Context context, @NonNull ILocationManager service) {
-        mService = service;
-        mContext = context;
-        mGnssMeasurementCallbackTransport =
-                new GnssMeasurementCallbackTransport(mContext, mService);
-        mGnssNavigationMessageCallbackTransport =
-                new GnssNavigationMessageCallbackTransport(mContext, mService);
-        mBatchedLocationCallbackTransport =
-                new BatchedLocationCallbackTransport(mContext, mService);
-
-    }
-
-    private LocationProvider createProvider(String name, ProviderProperties properties) {
-        return new LocationProvider(name, properties);
+    @SystemApi
+    public @Nullable String getExtraLocationControllerPackage() {
+        try {
+            return mService.getExtraLocationControllerPackage();
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+            return null;
+        }
     }
 
     /**
-     * Returns a list of the names of all known location providers.
-     * <p>All providers are returned, including ones that are not permitted to
-     * be accessed by the calling activity or are currently disabled.
+     * Set the extra location controller package for location services on the device.
      *
-     * @return list of Strings containing names of the provider
+     * @hide
      */
-    public @NonNull List<String> getAllProviders() {
+    @SystemApi
+    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
+    public void setExtraLocationControllerPackage(@Nullable String packageName) {
         try {
-            return mService.getAllProviders();
+            mService.setExtraLocationControllerPackage(packageName);
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Set whether the extra location controller package is currently enabled on the device.
+     *
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
+    public void setExtraLocationControllerPackageEnabled(boolean enabled) {
+        try {
+            mService.setExtraLocationControllerPackageEnabled(enabled);
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns whether extra location controller package is currently enabled on the device.
+     *
+     * @hide
+     */
+    @SystemApi
+    public boolean isExtraLocationControllerPackageEnabled() {
+        try {
+            return mService.isExtraLocationControllerPackageEnabled();
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+            return false;
+        }
+    }
+
+    /**
+     * Set the extra location controller package for location services on the device.
+     *
+     * @removed
+     * @deprecated Use {@link #setExtraLocationControllerPackage} instead.
+     * @hide
+     */
+    @Deprecated
+    @SystemApi
+    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
+    public void setLocationControllerExtraPackage(String packageName) {
+        try {
+            mService.setExtraLocationControllerPackage(packageName);
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Set whether the extra location controller package is currently enabled on the device.
+     *
+     * @removed
+     * @deprecated Use {@link #setExtraLocationControllerPackageEnabled} instead.
+     * @hide
+     */
+    @SystemApi
+    @Deprecated
+    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
+    public void setLocationControllerExtraPackageEnabled(boolean enabled) {
+        try {
+            mService.setExtraLocationControllerPackageEnabled(enabled);
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns the current enabled/disabled state of location. To listen for changes, see
+     * {@link #MODE_CHANGED_ACTION}.
+     *
+     * @return true if location is enabled and false if location is disabled.
+     */
+    public boolean isLocationEnabled() {
+        return isLocationEnabledForUser(Process.myUserHandle());
+    }
+
+    /**
+     * Returns the current enabled/disabled state of location for the given user.
+     *
+     * @param userHandle the user to query
+     * @return true if location is enabled and false if location is disabled.
+     *
+     * @hide
+     */
+    @SystemApi
+    public boolean isLocationEnabledForUser(@NonNull UserHandle userHandle) {
+        try {
+            return mService.isLocationEnabledForUser(userHandle.getIdentifier());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
     }
 
     /**
-     * Returns a list of the names of location providers.
+     * Enables or disables location for the given user.
      *
-     * @param enabledOnly if true then only the providers which are currently
-     * enabled are returned.
-     * @return list of Strings containing names of the providers
+     * @param enabled true to enable location and false to disable location.
+     * @param userHandle the user to set
+     *
+     * @hide
      */
-    public @NonNull List<String> getProviders(boolean enabledOnly) {
+    @SystemApi
+    @TestApi
+    @RequiresPermission(WRITE_SECURE_SETTINGS)
+    public void setLocationEnabledForUser(boolean enabled, @NonNull UserHandle userHandle) {
+        Settings.Secure.putIntForUser(
+                mContext.getContentResolver(),
+                Settings.Secure.LOCATION_MODE,
+                enabled
+                        ? Settings.Secure.LOCATION_MODE_ON
+                        : Settings.Secure.LOCATION_MODE_OFF,
+                userHandle.getIdentifier());
+    }
+
+    /**
+     * Returns the current enabled/disabled status of the given provider. To listen for changes, see
+     * {@link #PROVIDERS_CHANGED_ACTION}.
+     *
+     * Before API version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method would throw
+     * {@link SecurityException} if the location permissions were not sufficient to use the
+     * specified provider.
+     *
+     * @param provider the name of the provider
+     * @return true if the provider exists and is enabled
+     *
+     * @throws IllegalArgumentException if provider is null
+     */
+    public boolean isProviderEnabled(@NonNull String provider) {
+        return isProviderEnabledForUser(provider, Process.myUserHandle());
+    }
+
+    /**
+     * Returns the current enabled/disabled status of the given provider and user. Callers should
+     * prefer {@link #isLocationEnabledForUser(UserHandle)} unless they depend on provider-specific
+     * APIs.
+     *
+     * Before API version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method would throw
+     * {@link SecurityException} if the location permissions were not sufficient to use the
+     * specified provider.
+     *
+     * @param provider the name of the provider
+     * @param userHandle the user to query
+     * @return true if the provider exists and is enabled
+     *
+     * @throws IllegalArgumentException if provider is null
+     * @hide
+     */
+    @SystemApi
+    public boolean isProviderEnabledForUser(
+            @NonNull String provider, @NonNull UserHandle userHandle) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+
         try {
-            return mService.getProviders(null, enabledOnly);
+            return mService.isProviderEnabledForUser(provider, userHandle.getIdentifier());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
     }
 
     /**
-     * Returns the information associated with the location provider of the
-     * given name, or null if no provider exists by that name.
+     * Method for enabling or disabling a single location provider. This method is deprecated and
+     * functions as a best effort. It should not be relied on in any meaningful sense as providers
+     * may no longer be enabled or disabled by clients.
      *
-     * @param name the provider name
-     * @return a LocationProvider, or null
+     * @param provider the name of the provider
+     * @param enabled true to enable the provider. false to disable the provider
+     * @param userHandle the user to set
+     * @return true if the value was set, false otherwise
      *
-     * @throws IllegalArgumentException if name is null or does not exist
-     * @throws SecurityException if the caller is not permitted to access the
-     * given provider.
+     * @throws IllegalArgumentException if provider is null
+     * @deprecated Do not manipulate providers individually, use
+     * {@link #setLocationEnabledForUser(boolean, UserHandle)} instead.
+     * @hide
      */
-    public @Nullable LocationProvider getProvider(@NonNull String name) {
-        checkProvider(name);
+    @Deprecated
+    @SystemApi
+    @RequiresPermission(WRITE_SECURE_SETTINGS)
+    public boolean setProviderEnabledForUser(
+            @NonNull String provider, boolean enabled, @NonNull UserHandle userHandle) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+
+        return Settings.Secure.putStringForUser(
+                mContext.getContentResolver(),
+                Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
+                (enabled ? "+" : "-") + provider,
+                userHandle.getIdentifier());
+    }
+
+    /**
+     * Gets the last known location from the fused provider, or null if there is no last known
+     * location. The returned location may be quite old in some circumstances, so the age of the
+     * location should always be checked.
+     *
+     * @return the last known location, or null if not available
+     * @throws SecurityException if no suitable location permission is present
+     *
+     * @hide
+     */
+    @Nullable
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public Location getLastLocation() {
         try {
-            ProviderProperties properties = mService.getProviderProperties(name);
-            if (properties == null) {
-                return null;
-            }
-            return createProvider(name, properties);
+            return mService.getLastLocation(null, mContext.getPackageName());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
     }
 
     /**
-     * Returns a list of the names of LocationProviders that satisfy the given
-     * criteria, or null if none do.  Only providers that are permitted to be
-     * accessed by the calling activity will be returned.
+     * Gets the last known location from the given provider, or null if there is no last known
+     * location. The returned location may be quite old in some circumstances, so the age of the
+     * location should always be checked.
      *
-     * @param criteria the criteria that the returned providers must match
-     * @param enabledOnly if true then only the providers which are currently
-     * enabled are returned.
-     * @return list of Strings containing names of the providers
-     */
-    public @NonNull List<String> getProviders(@NonNull Criteria criteria, boolean enabledOnly) {
-        checkCriteria(criteria);
-        try {
-            return mService.getProviders(criteria, enabledOnly);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Returns the name of the provider that best meets the given criteria. Only providers
-     * that are permitted to be accessed by the calling activity will be
-     * returned.  If several providers meet the criteria, the one with the best
-     * accuracy is returned.  If no provider meets the criteria,
-     * the criteria are loosened in the following sequence:
-     *
-     * <ul>
-     * <li> power requirement
-     * <li> accuracy
-     * <li> bearing
-     * <li> speed
-     * <li> altitude
-     * </ul>
-     *
-     * <p> Note that the requirement on monetary cost is not removed
-     * in this process.
-     *
-     * @param criteria the criteria that need to be matched
-     * @param enabledOnly if true then only a provider that is currently enabled is returned
-     * @return name of the provider that best matches the requirements
-     */
-    public @Nullable String getBestProvider(@NonNull Criteria criteria, boolean enabledOnly) {
-        checkCriteria(criteria);
-        try {
-            return mService.getBestProvider(criteria, enabledOnly);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Register for location updates using the named provider, and a
-     * pending intent.
-     *
-     * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)}
-     * for more detail on how to use this method.
-     *
-     * @param provider the name of the provider with which to register
-     * @param minTime minimum time interval between location updates, in milliseconds
-     * @param minDistance minimum distance between location updates, in meters
-     * @param listener a {@link LocationListener} whose
-     * {@link LocationListener#onLocationChanged} method will be called for
-     * each location update
-     *
-     * @throws IllegalArgumentException if provider is null or doesn't exist
-     * on this device
-     * @throws IllegalArgumentException if listener is null
-     * @throws RuntimeException if the calling thread has no Looper
+     * @param provider the name of the provider
+     * @return the last known location for the given provider, or null if not available
      * @throws SecurityException if no suitable permission is present
+     * @throws IllegalArgumentException if provider is null or doesn't exist
      */
     @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
-    public void requestLocationUpdates(@NonNull String provider, long minTime, float minDistance,
-            @NonNull LocationListener listener) {
-        checkProvider(provider);
-        checkListener(listener);
+    @Nullable
+    public Location getLastKnownLocation(@NonNull String provider) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
 
         LocationRequest request = LocationRequest.createFromDeprecatedProvider(
-                provider, minTime, minDistance, false);
-        requestLocationUpdates(request, listener, null, null);
-    }
+                provider, 0, 0, true);
 
-    /**
-     * Register for location updates using the named provider, and a callback on
-     * the specified looper thread.
-     *
-     * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)}
-     * for more detail on how to use this method.
-     *
-     * @param provider the name of the provider with which to register
-     * @param minTime minimum time interval between location updates, in milliseconds
-     * @param minDistance minimum distance between location updates, in meters
-     * @param listener a {@link LocationListener} whose
-     * {@link LocationListener#onLocationChanged} method will be called for
-     * each location update
-     * @param looper a Looper object whose message queue will be used to
-     * implement the callback mechanism, or null to make callbacks on the calling
-     * thread
-     *
-     * @throws IllegalArgumentException if provider is null or doesn't exist
-     * @throws IllegalArgumentException if listener is null
-     * @throws SecurityException if no suitable permission is present
-     */
-    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
-    public void requestLocationUpdates(@NonNull String provider, long minTime, float minDistance,
-            @NonNull LocationListener listener, @Nullable Looper looper) {
-        checkProvider(provider);
-        checkListener(listener);
-
-        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
-                provider, minTime, minDistance, false);
-        requestLocationUpdates(request, listener, looper, null);
-    }
-
-    /**
-     * Register for location updates using a Criteria, and a callback
-     * on the specified looper thread.
-     *
-     * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)}
-     * for more detail on how to use this method.
-     *
-     * @param minTime minimum time interval between location updates, in milliseconds
-     * @param minDistance minimum distance between location updates, in meters
-     * @param criteria contains parameters for the location manager to choose the
-     * appropriate provider and parameters to compute the location
-     * @param listener a {@link LocationListener} whose
-     * {@link LocationListener#onLocationChanged} method will be called for
-     * each location update
-     * @param looper a Looper object whose message queue will be used to
-     * implement the callback mechanism, or null to make callbacks on the calling
-     * thread
-     *
-     * @throws IllegalArgumentException if criteria is null
-     * @throws IllegalArgumentException if listener is null
-     * @throws SecurityException if no suitable permission is present
-     */
-    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
-    public void requestLocationUpdates(long minTime, float minDistance, @NonNull Criteria criteria,
-            @NonNull LocationListener listener, @Nullable Looper looper) {
-        checkCriteria(criteria);
-        checkListener(listener);
-
-        LocationRequest request = LocationRequest.createFromDeprecatedCriteria(
-                criteria, minTime, minDistance, false);
-        requestLocationUpdates(request, listener, looper, null);
-    }
-
-    /**
-     * Register for location updates using the named provider, and a
-     * pending intent.
-     *
-     * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)}
-     * for more detail on how to use this method.
-     *
-     * @param provider the name of the provider with which to register
-     * @param minTime minimum time interval between location updates, in milliseconds
-     * @param minDistance minimum distance between location updates, in meters
-     * @param intent a {@link PendingIntent} to be sent for each location update
-     *
-     * @throws IllegalArgumentException if provider is null or doesn't exist
-     * on this device
-     * @throws IllegalArgumentException if intent is null
-     * @throws SecurityException if no suitable permission is present
-     */
-    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
-    public void requestLocationUpdates(@NonNull String provider, long minTime, float minDistance,
-            @NonNull PendingIntent intent) {
-        checkProvider(provider);
-        checkPendingIntent(intent);
-
-        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
-                provider, minTime, minDistance, false);
-        requestLocationUpdates(request, null, null, intent);
-    }
-
-    /**
-     * Register for location updates using a Criteria and pending intent.
-     *
-     * <p>The <code>requestLocationUpdates()</code> and
-     * <code>requestSingleUpdate()</code> register the current activity to be
-     * updated periodically by the named provider, or by the provider matching
-     * the specified {@link Criteria}, with location and status updates.
-     *
-     * <p> It may take a while to receive the first location update. If
-     * an immediate location is required, applications may use the
-     * {@link #getLastKnownLocation(String)} method.
-     *
-     * <p> Location updates are received either by {@link LocationListener}
-     * callbacks, or by broadcast intents to a supplied {@link PendingIntent}.
-     *
-     * <p> If the caller supplied a pending intent, then location updates
-     * are sent with a key of {@link #KEY_LOCATION_CHANGED} and a
-     * {@link android.location.Location} value.
-     *
-     * <p> The location update interval can be controlled using the minTime parameter.
-     * The elapsed time between location updates will never be less than
-     * minTime, although it can be more depending on the Location Provider
-     * implementation and the update interval requested by other applications.
-     *
-     * <p> Choosing a sensible value for minTime is important to conserve
-     * battery life. Each location update requires power from
-     * GPS, WIFI, Cell and other radios. Select a minTime value as high as
-     * possible while still providing a reasonable user experience.
-     * If your application is not in the foreground and showing
-     * location to the user then your application should avoid using an active
-     * provider (such as {@link #NETWORK_PROVIDER} or {@link #GPS_PROVIDER}),
-     * but if you insist then select a minTime of 5 * 60 * 1000 (5 minutes)
-     * or greater. If your application is in the foreground and showing
-     * location to the user then it is appropriate to select a faster
-     * update interval.
-     *
-     * <p> The minDistance parameter can also be used to control the
-     * frequency of location updates. If it is greater than 0 then the
-     * location provider will only send your application an update when
-     * the location has changed by at least minDistance meters, AND
-     * at least minTime milliseconds have passed. However it is more
-     * difficult for location providers to save power using the minDistance
-     * parameter, so minTime should be the primary tool to conserving battery
-     * life.
-     *
-     * <p> If your application wants to passively observe location
-     * updates triggered by other applications, but not consume
-     * any additional power otherwise, then use the {@link #PASSIVE_PROVIDER}
-     * This provider does not actively turn on or modify active location
-     * providers, so you do not need to be as careful about minTime and
-     * minDistance. However if your application performs heavy work
-     * on a location update (such as network activity) then you should
-     * select non-zero values for minTime and/or minDistance to rate-limit
-     * your update frequency in the case another application enables a
-     * location provider with extremely fast updates.
-     *
-     * <p>In case the provider is disabled by the user, updates will stop,
-     * and a provider availability update will be sent.
-     * As soon as the provider is enabled again,
-     * location updates will immediately resume and a provider availability
-     * update sent. Providers can also send status updates, at any time,
-     * with extra's specific to the provider. If a callback was supplied
-     * then status and availability updates are via
-     * {@link LocationListener#onProviderDisabled},
-     * {@link LocationListener#onProviderEnabled} or
-     * {@link LocationListener#onStatusChanged}. Alternately, if a
-     * pending intent was supplied then status and availability updates
-     * are broadcast intents with extra keys of
-     * {@link #KEY_PROVIDER_ENABLED} or {@link #KEY_STATUS_CHANGED}.
-     *
-     * <p> If a {@link LocationListener} is used but with no Looper specified
-     * then the calling thread must already
-     * be a {@link android.os.Looper} thread such as the main thread of the
-     * calling Activity. If a Looper is specified with a {@link LocationListener}
-     * then callbacks are made on the supplied Looper thread.
-     *
-     * <p> When location callbacks are invoked, the system will hold a wakelock
-     * on your application's behalf for some period of time, but not
-     * indefinitely. If your application requires a long running wakelock
-     * within the location callback, you should acquire it yourself.
-     *
-     * <p class="note"> Prior to Jellybean, the minTime parameter was
-     * only a hint, and some location provider implementations ignored it.
-     * From Jellybean and onwards it is mandatory for Android compatible
-     * devices to observe both the minTime and minDistance parameters.
-     *
-     * @param minTime minimum time interval between location updates, in milliseconds
-     * @param minDistance minimum distance between location updates, in meters
-     * @param criteria contains parameters for the location manager to choose the
-     * appropriate provider and parameters to compute the location
-     * @param intent a {@link PendingIntent} to be sent for each location update
-     *
-     * @throws IllegalArgumentException if criteria is null
-     * @throws IllegalArgumentException if intent is null
-     * @throws SecurityException if no suitable permission is present
-     */
-    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
-    public void requestLocationUpdates(long minTime, float minDistance, @NonNull Criteria criteria,
-            @NonNull PendingIntent intent) {
-        checkCriteria(criteria);
-        checkPendingIntent(intent);
-
-        LocationRequest request = LocationRequest.createFromDeprecatedCriteria(
-                criteria, minTime, minDistance, false);
-        requestLocationUpdates(request, null, null, intent);
+        try {
+            return mService.getLastLocation(request, mContext.getPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
     }
 
     /**
      * Register for a single location update using the named provider and
      * a callback.
      *
-     * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)}
+     * <p>See {@link #requestLocationUpdates(String, long, float, LocationListener, Looper)}
      * for more detail on how to use this method.
      *
      * @param provider the name of the provider with which to register
@@ -745,16 +559,20 @@
      * @throws IllegalArgumentException if provider is null or doesn't exist
      * @throws IllegalArgumentException if listener is null
      * @throws SecurityException if no suitable permission is present
+     * @deprecated This method can drain much more battery than expected if it is not possible to
+     * calculate location. Prefer any of the requestLocationUpdates() methods which require explicit
+     * removal.
      */
+    @Deprecated
     @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
     public void requestSingleUpdate(
             @NonNull String provider, @NonNull LocationListener listener, @Nullable Looper looper) {
-        checkProvider(provider);
-        checkListener(listener);
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+        Preconditions.checkArgument(listener != null, "invalid null listener");
 
         LocationRequest request = LocationRequest.createFromDeprecatedProvider(
                 provider, 0, 0, true);
-        requestLocationUpdates(request, listener, looper, null);
+        requestLocationUpdates(request, listener, looper);
     }
 
     /**
@@ -776,18 +594,21 @@
      * @throws IllegalArgumentException if criteria is null
      * @throws IllegalArgumentException if listener is null
      * @throws SecurityException if no suitable permission is present
+     * @deprecated This method can drain much more battery than expected if it is not possible to
+     * calculate location. Prefer any of the requestLocationUpdates() methods which require explicit
+     * removal.
      */
     @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
     public void requestSingleUpdate(
             @NonNull Criteria criteria,
             @NonNull LocationListener listener,
             @Nullable Looper looper) {
-        checkCriteria(criteria);
-        checkListener(listener);
+        Preconditions.checkArgument(criteria != null, "invalid null criteria");
+        Preconditions.checkArgument(listener != null, "invalid null listener");
 
         LocationRequest request = LocationRequest.createFromDeprecatedCriteria(
                 criteria, 0, 0, true);
-        requestLocationUpdates(request, listener, looper, null);
+        requestLocationUpdates(request, listener, looper);
     }
 
     /**
@@ -802,15 +623,18 @@
      * @throws IllegalArgumentException if provider is null or doesn't exist
      * @throws IllegalArgumentException if intent is null
      * @throws SecurityException if no suitable permission is present
+     * @deprecated This method can drain much more battery than expected if it is not possible to
+     * calculate location. Prefer any of the requestLocationUpdates() methods which require explicit
+     * removal.
      */
     @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
     public void requestSingleUpdate(@NonNull String provider, @NonNull PendingIntent intent) {
-        checkProvider(provider);
+        Preconditions.checkArgument(provider != null, "invalid null provider");
         checkPendingIntent(intent);
 
         LocationRequest request = LocationRequest.createFromDeprecatedProvider(
                 provider, 0, 0, true);
-        requestLocationUpdates(request, null, null, intent);
+        requestLocationUpdates(request, intent);
     }
 
     /**
@@ -826,68 +650,283 @@
      * @throws IllegalArgumentException if provider is null or doesn't exist
      * @throws IllegalArgumentException if intent is null
      * @throws SecurityException if no suitable permission is present
+     * @deprecated This method can drain much more battery than expected if it is not possible to
+     * calculate location. Prefer any of the requestLocationUpdates() methods which require explicit
+     * removal.
      */
     @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
     public void requestSingleUpdate(@NonNull Criteria criteria, @NonNull PendingIntent intent) {
-        checkCriteria(criteria);
+        Preconditions.checkArgument(criteria != null, "invalid null criteria");
         checkPendingIntent(intent);
 
         LocationRequest request = LocationRequest.createFromDeprecatedCriteria(
                 criteria, 0, 0, true);
-        requestLocationUpdates(request, null, null, intent);
+        requestLocationUpdates(request, intent);
     }
 
     /**
-     * Register for fused location updates using a LocationRequest and callback.
+     * Register for location updates from the given provider with the given arguments. {@link
+     * LocationListener} callbacks will take place on the given {@link Looper} or {@link Executor}.
+     * If a null {@link Looper} is supplied, the Looper of the calling thread will be used instead.
+     * Only one request can be registered for each unique listener, so any subsequent requests with
+     * the same listener will overwrite all associated arguments.
      *
-     * <p>Upon a location update, the system delivers the new {@link Location} to the
-     * provided {@link LocationListener}, by calling its {@link
-     * LocationListener#onLocationChanged} method.</p>
+     * <p> It may take a while to receive the first location update. If an immediate location is
+     * required, applications may use the {@link #getLastKnownLocation(String)} method.
      *
-     * <p>The system will automatically select and enable the best providers
-     * to compute a location for your application. It may use only passive
-     * locations, or just a single location source, or it may fuse together
-     * multiple location sources in order to produce the best possible
-     * result, depending on the quality of service requested in the
-     * {@link LocationRequest}.
+     * <p> The location update interval can be controlled using the minimum time parameter. The
+     * elapsed time between location updates will never be less than this parameter, although it may
+     * be more depending on location availability and other factors. Choosing a sensible value for
+     * the minimum time parameter is important to conserve battery life. Every location update
+     * requires power from a variety of sensors. Select a minimum time parameter as high as possible
+     * while still providing a reasonable user experience. If your application is not in the
+     * foreground and showing location to the user then your application should consider switching
+     * to the {@link #PASSIVE_PROVIDER} instead.
      *
-     * <p>LocationRequest can be null, in which case the system will choose
-     * default, low power parameters for location updates. You will occasionally
-     * receive location updates as available, without a major power impact on the
-     * system. If your application just needs an occasional location update
-     * without any strict demands, then pass a null LocationRequest.
+     * <p> The minimum distance parameter can also be used to control the frequency of location
+     * updates. If it is greater than 0 then the location provider will only send your application
+     * an update when the location has changed by at least minDistance meters, AND when the minimum
+     * time has elapsed. However it is more difficult for location providers to save power using the
+     * minimum distance parameter, so the minimum time parameter should be the primary tool for
+     * conserving battery life.
      *
-     * <p>Only one LocationRequest can be registered for each unique callback
-     * or pending intent. So a subsequent request with the same callback or
-     * pending intent will over-write the previous LocationRequest.
+     * <p> If your application wants to passively observe location updates triggered by other
+     * applications, but not consume any additional power otherwise, then use the {@link
+     * #PASSIVE_PROVIDER}. This provider does not turn on or modify active location providers, so
+     * you do not need to be as careful about minimum time and minimum distance parameters. However,
+     * if your application performs heavy work on a location update (such as network activity) then
+     * you should select non-zero values for the parameters to rate-limit your update frequency in
+     * the case another application enables a location provider with extremely fast updates.
      *
-     * <p> If a pending intent is supplied then location updates
-     * are sent with a key of {@link #KEY_LOCATION_CHANGED} and a
-     * {@link android.location.Location} value. If a callback is supplied
-     * then location updates are made using the
-     * {@link LocationListener#onLocationChanged} callback, on the specified
-     * Looper thread. If a {@link LocationListener} is used
-     * but with a null Looper then the calling thread must already
-     * be a {@link android.os.Looper} thread (such as the main thread) and
-     * callbacks will occur on this thread.
+     * <p>In case the provider you have selected is disabled, location updates will cease, and a
+     * provider availability update will be sent. As soon as the provider is enabled again, another
+     * provider availability update will be sent and location updates will immediately resume.
      *
-     * <p> Provider status updates and availability updates are deprecated
-     * because the system is performing provider fusion on the applications
-     * behalf. So {@link LocationListener#onProviderDisabled},
-     * {@link LocationListener#onProviderEnabled}, {@link LocationListener#onStatusChanged}
-     * will not be called, and intents with extra keys of
-     * {@link #KEY_PROVIDER_ENABLED} or {@link #KEY_STATUS_CHANGED} will not
-     * be received.
+     * <p> When location callbacks are invoked, the system will hold a wakelock on your
+     * application's behalf for some period of time, but not indefinitely. If your application
+     * requires a long running wakelock within the location callback, you should acquire it
+     * yourself.
      *
-     * <p> To unregister for Location updates, use: {@link #removeUpdates(LocationListener)}.
+     * <p class="note"> Prior to Jellybean, the minTime parameter was only a hint, and some location
+     * provider implementations ignored it. For Jellybean and onwards however, it is mandatory for
+     * Android compatible devices to observe both the minTime and minDistance parameters.
      *
-     * @param request quality of service required, null for default low power
-     * @param listener a {@link LocationListener} whose
-     * {@link LocationListener#onLocationChanged} method will be called when
-     * the location update is available
-     * @param looper a Looper object whose message queue will be used to
-     * implement the callback mechanism, or null to make callbacks on the calling
-     * thread
+     * <p>To unregister for location updates, use {@link #removeUpdates(LocationListener)}.
+     *
+     * @param provider the name of the provider with which to register
+     * @param minTimeMs minimum time interval between location updates in milliseconds
+     * @param minDistanceM minimum distance between location updates in meters
+     * @param listener the listener to receive location updates
+     *
+     * @throws IllegalArgumentException if provider is null or doesn't exist
+     * @throws IllegalArgumentException if listener is null
+     * @throws RuntimeException if the calling thread has no Looper
+     * @throws SecurityException if no suitable permission is present
+     */
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(@NonNull String provider, long minTimeMs, float minDistanceM,
+            @NonNull LocationListener listener) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+        Preconditions.checkArgument(listener != null, "invalid null listener");
+
+        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
+                provider, minTimeMs, minDistanceM, false);
+        requestLocationUpdates(request, listener, null);
+    }
+
+    /**
+     * Register for location updates using the named provider, and a callback on
+     * the specified {@link Looper}.
+     *
+     * <p>See {@link #requestLocationUpdates(String, long, float, LocationListener)}
+     * for more detail on how this method works.
+     *
+     * @param provider the name of the provider with which to register
+     * @param minTimeMs minimum time interval between location updates in milliseconds
+     * @param minDistanceM minimum distance between location updates in meters
+     * @param listener the listener to receive location updates
+     * @param looper the looper handling listener callbacks, or null to use the looper of the
+     *               calling thread
+     *
+     * @throws IllegalArgumentException if provider is null or doesn't exist
+     * @throws IllegalArgumentException if listener is null
+     * @throws SecurityException if no suitable permission is present
+     */
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(@NonNull String provider, long minTimeMs, float minDistanceM,
+            @NonNull LocationListener listener, @Nullable Looper looper) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+        Preconditions.checkArgument(listener != null, "invalid null listener");
+
+        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
+                provider, minTimeMs, minDistanceM, false);
+        requestLocationUpdates(request, listener, looper);
+    }
+
+    /**
+     * Register for location updates using the named provider, and a callback on
+     * the specified {@link Executor}.
+     *
+     * <p>See {@link #requestLocationUpdates(String, long, float, LocationListener)}
+     * for more detail on how this method works.
+     *
+     * @param provider the name of the provider with which to register
+     * @param minTimeMs minimum time interval between location updates in milliseconds
+     * @param minDistanceM minimum distance between location updates in meters
+     * @param executor the executor handling listener callbacks
+     * @param listener the listener to receive location updates
+     *
+     * @throws IllegalArgumentException if provider is null or doesn't exist
+     * @throws IllegalArgumentException if executor is null
+     * @throws IllegalArgumentException if listener is null
+     * @throws SecurityException if no suitable permission is present
+     */
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(
+            @NonNull String provider,
+            long minTimeMs,
+            float minDistanceM,
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull LocationListener listener) {
+        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
+                provider, minTimeMs, minDistanceM, false);
+        requestLocationUpdates(request, executor, listener);
+    }
+
+    /**
+     * Register for location updates using a provider selected through the given Criteria, and a
+     * callback on the specified {@link Looper}.
+     *
+     * <p>See {@link #requestLocationUpdates(String, long, float, LocationListener)}
+     * for more detail on how this method works.
+     *
+     * @param minTimeMs minimum time interval between location updates in milliseconds
+     * @param minDistanceM minimum distance between location updates in meters
+     * @param criteria contains parameters to choose the appropriate provider for location updates
+     * @param listener the listener to receive location updates
+     *
+     * @throws IllegalArgumentException if criteria is null
+     * @throws IllegalArgumentException if listener is null
+     * @throws SecurityException if no suitable permission is present
+     */
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(long minTimeMs, float minDistanceM,
+            @NonNull Criteria criteria, @NonNull LocationListener listener,
+            @Nullable Looper looper) {
+        Preconditions.checkArgument(criteria != null, "invalid null criteria");
+        Preconditions.checkArgument(listener != null, "invalid null listener");
+
+        LocationRequest request = LocationRequest.createFromDeprecatedCriteria(
+                criteria, minTimeMs, minDistanceM, false);
+        requestLocationUpdates(request, listener, looper);
+    }
+
+    /**
+     * Register for location updates using a provider selected through the given Criteria, and a
+     * callback on the specified {@link Executor}.
+     *
+     * <p>See {@link #requestLocationUpdates(String, long, float, LocationListener)}
+     * for more detail on how this method works.
+     *
+     * @param minTimeMs minimum time interval between location updates in milliseconds
+     * @param minDistanceM minimum distance between location updates in meters
+     * @param criteria contains parameters to choose the appropriate provider for location updates
+     * @param executor the executor handling listener callbacks
+     * @param listener the listener to receive location updates
+     *
+     * @throws IllegalArgumentException if criteria is null
+     * @throws IllegalArgumentException if executor is null
+     * @throws IllegalArgumentException if listener is null
+     * @throws SecurityException        if no suitable permission is present
+     */
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(
+            long minTimeMs,
+            float minDistanceM,
+            @NonNull Criteria criteria,
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull LocationListener listener) {
+        LocationRequest request = LocationRequest.createFromDeprecatedCriteria(
+                criteria, minTimeMs, minDistanceM, false);
+        requestLocationUpdates(request, executor, listener);
+    }
+
+    /**
+     * Register for location updates using the named provider, and callbacks delivered via the
+     * provided {@link PendingIntent}.
+     *
+     * <p>The delivered pending intents will contain extras with the callback information. The keys
+     * used for the extras are {@link #KEY_LOCATION_CHANGED} and {@link #KEY_PROVIDER_ENABLED}. See
+     * the documentation for each respective extra key for information on the values.
+     *
+     * <p>To unregister for location updates, use {@link #removeUpdates(PendingIntent)}.
+     *
+     * <p>See {@link #requestLocationUpdates(String, long, float, LocationListener)}
+     * for more detail on how this method works.
+     *
+     * @param provider the name of the provider with which to register
+     * @param minTimeMs minimum time interval between location updates in milliseconds
+     * @param minDistanceM minimum distance between location updates in meters
+     * @param pendingIntent the pending intent to send location updates
+     *
+     * @throws IllegalArgumentException if provider is null or doesn't exist
+     * @throws IllegalArgumentException if pendingIntent is null
+     * @throws SecurityException if no suitable permission is present
+     */
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(@NonNull String provider, long minTimeMs, float minDistanceM,
+            @NonNull PendingIntent pendingIntent) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+        checkPendingIntent(pendingIntent);
+
+        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
+                provider, minTimeMs, minDistanceM, false);
+        requestLocationUpdates(request, pendingIntent);
+    }
+
+    /**
+     * Register for location updates using a provider selected through the given Criteria, and
+     * callbacks delivered via the provided {@link PendingIntent}.
+     *
+     * <p>See {@link #requestLocationUpdates(String, long, float, PendingIntent)} for more detail on
+     * how this method works.
+     *
+     * @param minTimeMs minimum time interval between location updates in milliseconds
+     * @param minDistanceM minimum distance between location updates in meters
+     * @param criteria contains parameters to choose the appropriate provider for location updates
+     * @param pendingIntent the pending intent to send location updates
+     *
+     * @throws IllegalArgumentException if provider is null or doesn't exist
+     * @throws IllegalArgumentException if pendingIntent is null
+     * @throws SecurityException if no suitable permission is present
+     */
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(long minTimeMs, float minDistanceM,
+            @NonNull Criteria criteria, @NonNull PendingIntent pendingIntent) {
+        Preconditions.checkArgument(criteria != null, "invalid null criteria");
+        checkPendingIntent(pendingIntent);
+
+        LocationRequest request = LocationRequest.createFromDeprecatedCriteria(
+                criteria, minTimeMs, minDistanceM, false);
+        requestLocationUpdates(request, pendingIntent);
+    }
+
+    /**
+     * Register for location updates using a {@link LocationRequest}, and a callback on the
+     * specified {@link Looper}.
+     *
+     * <p>The system will automatically select and enable the best provider based on the given
+     * {@link LocationRequest}. The LocationRequest can be null, in which case the system will
+     * choose default low power parameters for location updates, but this is heavily discouraged,
+     * and an explicit LocationRequest should always be provided.
+     *
+     * <p>See {@link #requestLocationUpdates(String, long, float, LocationListener)}
+     * for more detail on how this method works.
+     *
+     * @param locationRequest the location request containing location parameters
+     * @param listener the listener to receive location updates
+     * @param looper the looper handling listener callbacks, or null to use the looper of the
+     *               calling thread
      *
      * @throws IllegalArgumentException if listener is null
      * @throws SecurityException if no suitable permission is present
@@ -898,30 +937,26 @@
     @TestApi
     @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
     public void requestLocationUpdates(
-            @NonNull LocationRequest request,
+            @Nullable LocationRequest locationRequest,
             @NonNull LocationListener listener,
             @Nullable Looper looper) {
-        checkListener(listener);
-        requestLocationUpdates(request, listener, looper, null);
+        Handler handler = looper == null ? new Handler() : new Handler(looper);
+        requestLocationUpdates(locationRequest, new HandlerExecutor(handler), listener);
     }
 
-
     /**
-     * Register for fused location updates using a LocationRequest and a pending intent.
+     * Register for location updates using a {@link LocationRequest}, and a callback on the
+     * specified {@link Executor}.
      *
-     * <p>Upon a location update, the system delivers the new {@link Location} with your provided
-     * {@link PendingIntent}, as the value for {@link LocationManager#KEY_LOCATION_CHANGED}
-     * in the intent's extras.</p>
+     * <p>See {@link #requestLocationUpdates(LocationRequest, LocationListener, Looper)} for more
+     * detail on how this method works.
      *
-     * <p> To unregister for Location updates, use: {@link #removeUpdates(PendingIntent)}.
+     * @param locationRequest the location request containing location parameters
+     * @param executor the executor handling listener callbacks
+     * @param listener the listener to receive location updates
      *
-     * <p> See {@link #requestLocationUpdates(LocationRequest, LocationListener, Looper)}
-     * for more detail.
-     *
-     * @param request quality of service required, null for default low power
-     * @param intent a {@link PendingIntent} to be sent for the location update
-     *
-     * @throws IllegalArgumentException if intent is null
+     * @throws IllegalArgumentException if executor is null
+     * @throws IllegalArgumentException if listener is null
      * @throws SecurityException if no suitable permission is present
      *
      * @hide
@@ -930,9 +965,71 @@
     @TestApi
     @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
     public void requestLocationUpdates(
-            @NonNull LocationRequest request, @NonNull PendingIntent intent) {
-        checkPendingIntent(intent);
-        requestLocationUpdates(request, null, null, intent);
+            @Nullable LocationRequest locationRequest,
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull LocationListener listener) {
+        synchronized (mListeners) {
+            LocationListenerTransport transport = mListeners.get(listener);
+            if (transport != null) {
+                transport.unregister();
+            } else {
+                transport = new LocationListenerTransport(listener);
+                mListeners.put(listener, transport);
+            }
+            transport.register(executor);
+
+            boolean registered = false;
+            try {
+                mService.requestLocationUpdates(locationRequest, transport, null,
+                        mContext.getPackageName());
+                registered = true;
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            } finally {
+                if (!registered) {
+                    // allow gc after exception
+                    transport.unregister();
+                    mListeners.remove(listener);
+                }
+            }
+        }
+    }
+
+    /**
+     * Register for location updates using a {@link LocationRequest}, and callbacks delivered via
+     * the provided {@link PendingIntent}.
+     *
+     * <p>See {@link #requestLocationUpdates(LocationRequest, LocationListener, Looper)} and
+     * {@link #requestLocationUpdates(String, long, float, PendingIntent)} for more detail on how
+     * this method works.
+     *
+     * @param locationRequest the location request containing location parameters
+     * @param pendingIntent the pending intent to send location updates
+     *
+     * @throws IllegalArgumentException if pendingIntent is null
+     * @throws SecurityException if no suitable permission is present
+     *
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
+    public void requestLocationUpdates(
+            @Nullable LocationRequest locationRequest,
+            @NonNull PendingIntent pendingIntent) {
+        Preconditions.checkArgument(locationRequest != null, "invalid null location request");
+        Preconditions.checkArgument(pendingIntent != null, "invalid null pending intent");
+        if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.JELLY_BEAN) {
+            Preconditions.checkArgument(pendingIntent.isTargetedToPackage(),
+                    "pending intent must be targeted to package");
+        }
+
+        try {
+            mService.requestLocationUpdates(locationRequest, null, pendingIntent,
+                    mContext.getPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
     }
 
     /**
@@ -943,94 +1040,376 @@
      * chipset is in the process of getting the first fix.  If the client has cached the location,
      * it can inject the {@link Location}, so if an app requests for a {@link Location} from {@link
      * #getLastKnownLocation(String)}, the location information is still useful before getting
-     * the first fix.</p>
+     * the first fix.
      *
-     * <p> Useful in products like Auto.
+     * @param location newly available {@link Location} object
+     * @return true if the location was successfully injected, false otherwise
      *
-     * @param newLocation newly available {@link Location} object
-     * @return true if update was successful, false if not
-     *
-     * @throws SecurityException if no suitable permission is present
+     * @throws IllegalArgumentException if location is null
+     * @throws SecurityException if permissions are not present
      *
      * @hide
      */
     @RequiresPermission(allOf = {LOCATION_HARDWARE, ACCESS_FINE_LOCATION})
-    public boolean injectLocation(@NonNull Location newLocation) {
+    public boolean injectLocation(@NonNull Location location) {
+        if (location == null) {
+            IllegalArgumentException e = new IllegalArgumentException("invalid null location");
+            if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
+                throw e;
+            } else {
+                Log.w(TAG, e);
+                return false;
+            }
+        }
+
         try {
-            return mService.injectLocation(newLocation);
+            return mService.injectLocation(location);
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
     }
 
-    private ListenerTransport wrapListener(LocationListener listener, Looper looper) {
-        if (listener == null) return null;
-        synchronized (mListeners) {
-            ListenerTransport transport = mListeners.get(listener);
-            if (transport == null) {
-                transport = new ListenerTransport(listener, looper);
-            }
-            mListeners.put(listener, transport);
-            return transport;
-        }
-    }
-
-    @UnsupportedAppUsage
-    private void requestLocationUpdates(LocationRequest request, LocationListener listener,
-            Looper looper, PendingIntent intent) {
-
-        String packageName = mContext.getPackageName();
-
-        // wrap the listener class
-        ListenerTransport transport = wrapListener(listener, looper);
-
-        try {
-            mService.requestLocationUpdates(request, transport, intent, packageName);
-       } catch (RemoteException e) {
-           throw e.rethrowFromSystemServer();
-       }
-    }
-
     /**
-     * Removes all location updates for the specified LocationListener.
+     * Removes location updates for the specified {@link LocationListener}. Following this call,
+     * the listener will no longer receive location updates.
      *
-     * <p>Following this call, updates will no longer
-     * occur for this listener.
+     * @param listener listener that no longer needs location updates
      *
-     * @param listener listener object that no longer needs location updates
      * @throws IllegalArgumentException if listener is null
      */
     public void removeUpdates(@NonNull LocationListener listener) {
-        checkListener(listener);
-        String packageName = mContext.getPackageName();
+        Preconditions.checkArgument(listener != null, "invalid null listener");
 
-        ListenerTransport transport;
         synchronized (mListeners) {
-            transport = mListeners.remove(listener);
+            LocationListenerTransport transport = mListeners.remove(listener);
+            if (transport == null) {
+                return;
+            }
+            transport.unregister();
+
+            try {
+                mService.removeUpdates(transport, null, mContext.getPackageName());
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
         }
-        if (transport == null) return;
+    }
+
+    /**
+     * Removes location updates for the specified {@link PendingIntent}. Following this call, the
+     * PendingIntent will no longer receive location updates.
+     *
+     * @param pendingIntent pending intent that no longer needs location updates
+     *
+     * @throws IllegalArgumentException if pendingIntent is null
+     */
+    public void removeUpdates(@NonNull PendingIntent pendingIntent) {
+        Preconditions.checkArgument(pendingIntent != null, "invalid null pending intent");
 
         try {
-            mService.removeUpdates(transport, null, packageName);
+            mService.removeUpdates(null, pendingIntent, mContext.getPackageName());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
     }
 
     /**
-     * Removes all location updates for the specified pending intent.
+     * Returns a list of the names of all known location providers. All providers are returned,
+     * including ones that are not permitted to be accessed by the calling activity or are currently
+     * disabled.
      *
-     * <p>Following this call, updates will no longer for this pending intent.
-     *
-     * @param intent pending intent object that no longer needs location updates
-     * @throws IllegalArgumentException if intent is null
+     * @return list of provider names
      */
-    public void removeUpdates(@NonNull PendingIntent intent) {
-        checkPendingIntent(intent);
-        String packageName = mContext.getPackageName();
+    public @NonNull List<String> getAllProviders() {
+        try {
+            return mService.getAllProviders();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns a list of the names of location providers. Only providers that the caller has
+     * permission to access will be returned.
+     *
+     * @param enabledOnly if true then only enabled providers are included
+     * @return list of provider names
+     */
+    public @NonNull List<String> getProviders(boolean enabledOnly) {
+        try {
+            return mService.getProviders(null, enabledOnly);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns a list of the names of providers that satisfy the given criteria. Only providers that
+     * the caller has permission to access will be returned.
+     *
+     * @param criteria the criteria that providers must match
+     * @param enabledOnly if true then only enabled providers are included
+     * @return list of provider names
+     *
+     * @throws IllegalArgumentException if criteria is null
+     */
+    public @NonNull List<String> getProviders(@NonNull Criteria criteria, boolean enabledOnly) {
+        Preconditions.checkArgument(criteria != null, "invalid null criteria");
 
         try {
-            mService.removeUpdates(null, intent, packageName);
+            return mService.getProviders(criteria, enabledOnly);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns the name of the provider that best meets the given criteria. Only providers that are
+     * permitted to be accessed by the caller will be returned. If several providers meet the
+     * criteria, the one with the best accuracy is returned. If no provider meets the criteria, the
+     * criteria are loosened in the following order:
+     *
+     * <ul>
+     * <li> power requirement
+     * <li> accuracy
+     * <li> bearing
+     * <li> speed
+     * <li> altitude
+     * </ul>
+     *
+     * <p> Note that the requirement on monetary cost is not removed in this process.
+     *
+     * @param criteria the criteria that need to be matched
+     * @param enabledOnly if true then only enabled providers are included
+     * @return name of the provider that best matches the criteria, or null if none match
+     *
+     * @throws IllegalArgumentException if criteria is null
+     */
+    public @Nullable String getBestProvider(@NonNull Criteria criteria, boolean enabledOnly) {
+        Preconditions.checkArgument(criteria != null, "invalid null criteria");
+
+        try {
+            return mService.getBestProvider(criteria, enabledOnly);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns the information about the location provider with the given name, or null if no
+     * provider exists by that name.
+     *
+     * @param provider the provider name
+     * @return location provider information, or null if provider does not exist
+     *
+     * @throws IllegalArgumentException if provider is null
+     */
+    public @Nullable LocationProvider getProvider(@NonNull String provider) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+        try {
+            ProviderProperties properties = mService.getProviderProperties(provider);
+            if (properties == null) {
+                return null;
+            }
+            return new LocationProvider(provider, properties);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Returns true if the given package name matches a location provider package, and false
+     * otherwise.
+     *
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(Manifest.permission.READ_DEVICE_CONFIG)
+    public boolean isProviderPackage(@NonNull String packageName) {
+        try {
+            return mService.isProviderPackage(packageName);
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+            return false;
+        }
+    }
+
+    /**
+     * Sends additional commands to a location provider. Can be used to support provider specific
+     * extensions to the Location Manager API.
+     *
+     * @param provider name of the location provider
+     * @param command  name of the command to send to the provider
+     * @param extras   optional arguments for the command, or null
+     * @return true always, the return value may be ignored
+     */
+    public boolean sendExtraCommand(
+            @NonNull String provider, @NonNull String command, @Nullable Bundle extras) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+        Preconditions.checkArgument(command != null, "invalid null command");
+
+        try {
+            return mService.sendExtraCommand(provider, command, extras);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Creates a test location provider and adds it to the set of active providers. This provider
+     * will replace any provider with the same name that exists prior to this call.
+     *
+     * @param provider the provider name
+     *
+     * @throws IllegalArgumentException if provider is null
+     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
+     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
+     * allowed} for your app.
+     */
+    public void addTestProvider(
+            @NonNull String provider, boolean requiresNetwork, boolean requiresSatellite,
+            boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude,
+            boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+
+        ProviderProperties properties = new ProviderProperties(requiresNetwork,
+                requiresSatellite, requiresCell, hasMonetaryCost, supportsAltitude, supportsSpeed,
+                supportsBearing, powerRequirement, accuracy);
+        try {
+            mService.addTestProvider(provider, properties, mContext.getOpPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Removes the test location provider with the given name or does nothing if no such test
+     * location provider exists.
+     *
+     * @param provider the provider name
+     *
+     * @throws IllegalArgumentException if provider is null
+     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
+     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
+     * allowed} for your app.
+     */
+    public void removeTestProvider(@NonNull String provider) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+
+        try {
+            mService.removeTestProvider(provider, mContext.getOpPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Sets a new location for the given test provider. This location will be identiable as a mock
+     * location to all clients via {@link Location#isFromMockProvider()}.
+     *
+     * <p>The location object must have a minimum number of fields set to be considered valid, as
+     * per documentation on {@link Location} class.
+     *
+     * @param provider the provider name
+     * @param location the mock location
+     *
+     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
+     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
+     * allowed} for your app.
+     * @throws IllegalArgumentException if the provider is null or not a test provider
+     * @throws IllegalArgumentException if the location is null or incomplete
+     */
+    public void setTestProviderLocation(@NonNull String provider, @NonNull Location location) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+        Preconditions.checkArgument(location != null, "invalid null location");
+
+        if (!location.isComplete()) {
+            IllegalArgumentException e = new IllegalArgumentException(
+                    "Incomplete location object, missing timestamp or accuracy? " + location);
+            if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN) {
+                Log.w(TAG, e);
+                location.makeComplete();
+            } else {
+                throw e;
+            }
+        }
+
+        try {
+            mService.setTestProviderLocation(provider, location, mContext.getOpPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Does nothing.
+     *
+     * @deprecated This method has always been a no-op, and may be removed in the future.
+     */
+    @Deprecated
+    public void clearTestProviderLocation(@NonNull String provider) {}
+
+    /**
+     * Sets the given test provider to be enabled or disabled.
+     *
+     * @param provider the provider name
+     * @param enabled the mock enabled value
+     *
+     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
+     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
+     * allowed} for your app.
+     * @throws IllegalArgumentException if provider is null or not a test provider
+     */
+    public void setTestProviderEnabled(@NonNull String provider, boolean enabled) {
+        Preconditions.checkArgument(provider != null, "invalid null provider");
+
+        try {
+            mService.setTestProviderEnabled(provider, enabled, mContext.getOpPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Equivalent to calling {@link #setTestProviderEnabled(String, boolean)} to disable a test
+     * provider.
+     *
+     * @deprecated Use {@link #setTestProviderEnabled(String, boolean)} instead.
+     */
+    @Deprecated
+    public void clearTestProviderEnabled(@NonNull String provider) {
+        setTestProviderEnabled(provider, false);
+    }
+
+    /**
+     * This method has no effect as provider status has been deprecated and is no longer supported.
+     *
+     * @deprecated This method has no effect.
+     */
+    @Deprecated
+    public void setTestProviderStatus(
+            @NonNull String provider, int status, @Nullable Bundle extras, long updateTime) {}
+
+    /**
+     * This method has no effect as provider status has been deprecated and is no longer supported.
+     *
+     * @deprecated This method has no effect.
+     */
+    @Deprecated
+    public void clearTestProviderStatus(@NonNull String provider) {}
+
+    /**
+     * Get the last list of {@link LocationRequest}s sent to the provider.
+     *
+     * @hide
+     */
+    @TestApi
+    @NonNull
+    public List<LocationRequest> getTestProviderCurrentRequests(String providerName) {
+        Preconditions.checkArgument(providerName != null, "invalid null provider");
+        try {
+            return mService.getTestProviderCurrentRequests(providerName,
+                    mContext.getOpPackageName());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -1099,6 +1478,32 @@
     }
 
     /**
+     * Removes the proximity alert with the given PendingIntent.
+     *
+     * <p>Before API version 17, this method could be used with
+     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} or
+     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
+     * From API version 17 and onwards, this method requires
+     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission.
+     *
+     * @param intent the PendingIntent that no longer needs to be notified of
+     * proximity alerts
+     *
+     * @throws IllegalArgumentException if intent is null
+     * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
+     * permission is not present
+     */
+    public void removeProximityAlert(@NonNull PendingIntent intent) {
+        checkPendingIntent(intent);
+
+        try {
+            mService.removeGeofence(null, intent, mContext.getPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Add a geofence with the specified LocationRequest quality of service.
      *
      * <p> When the device
@@ -1140,7 +1545,7 @@
             @NonNull Geofence fence,
             @NonNull PendingIntent intent) {
         checkPendingIntent(intent);
-        checkGeofence(fence);
+        Preconditions.checkArgument(fence != null, "invalid null geofence");
 
         try {
             mService.requestGeofence(request, fence, intent, mContext.getPackageName());
@@ -1150,33 +1555,6 @@
     }
 
     /**
-     * Removes the proximity alert with the given PendingIntent.
-     *
-     * <p>Before API version 17, this method could be used with
-     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} or
-     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
-     * From API version 17 and onwards, this method requires
-     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission.
-     *
-     * @param intent the PendingIntent that no longer needs to be notified of
-     * proximity alerts
-     *
-     * @throws IllegalArgumentException if intent is null
-     * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
-     * permission is not present
-     */
-    public void removeProximityAlert(@NonNull PendingIntent intent) {
-        checkPendingIntent(intent);
-        String packageName = mContext.getPackageName();
-
-        try {
-            mService.removeGeofence(null, intent, packageName);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
      * Remove a single geofence.
      *
      * <p>This removes only the specified geofence associated with the
@@ -1194,11 +1572,10 @@
      */
     public void removeGeofence(@NonNull Geofence fence, @NonNull PendingIntent intent) {
         checkPendingIntent(intent);
-        checkGeofence(fence);
-        String packageName = mContext.getPackageName();
+        Preconditions.checkArgument(fence != null, "invalid null geofence");
 
         try {
-            mService.removeGeofence(fence, intent, packageName);
+            mService.removeGeofence(fence, intent, mContext.getPackageName());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -1217,773 +1594,15 @@
      */
     public void removeAllGeofences(@NonNull PendingIntent intent) {
         checkPendingIntent(intent);
-        String packageName = mContext.getPackageName();
 
         try {
-            mService.removeGeofence(null, intent, packageName);
+            mService.removeGeofence(null, intent, mContext.getPackageName());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
     }
 
-    /**
-     * Returns the current enabled/disabled state of location. To listen for changes, see
-     * {@link #MODE_CHANGED_ACTION}.
-     *
-     * @return true if location is enabled and false if location is disabled.
-     */
-    public boolean isLocationEnabled() {
-        return isLocationEnabledForUser(Process.myUserHandle());
-    }
-
-    /**
-     * Returns the current enabled/disabled state of location.
-     *
-     * @param userHandle the user to query
-     * @return true if location is enabled and false if location is disabled.
-     *
-     * @hide
-     */
-    @SystemApi
-    public boolean isLocationEnabledForUser(@NonNull UserHandle userHandle) {
-        try {
-            return mService.isLocationEnabledForUser(userHandle.getIdentifier());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Enables or disables the location setting.
-     *
-     * @param enabled true to enable location and false to disable location.
-     * @param userHandle the user to set
-     *
-     * @hide
-     */
-    @SystemApi
-    @TestApi
-    @RequiresPermission(WRITE_SECURE_SETTINGS)
-    public void setLocationEnabledForUser(boolean enabled, @NonNull UserHandle userHandle) {
-        Settings.Secure.putIntForUser(
-                mContext.getContentResolver(),
-                Settings.Secure.LOCATION_MODE,
-                enabled
-                        ? Settings.Secure.LOCATION_MODE_ON
-                        : Settings.Secure.LOCATION_MODE_OFF,
-                userHandle.getIdentifier());
-    }
-
-    /**
-     * Returns the current enabled/disabled status of the given provider. To listen for changes, see
-     * {@link #PROVIDERS_CHANGED_ACTION}.
-     *
-     * Before API version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method would throw
-     * {@link SecurityException} if the location permissions were not sufficient to use the
-     * specified provider.
-     *
-     * @param provider the name of the provider
-     * @return true if the provider exists and is enabled
-     *
-     * @throws IllegalArgumentException if provider is null
-     */
-    public boolean isProviderEnabled(@NonNull String provider) {
-        return isProviderEnabledForUser(provider, Process.myUserHandle());
-    }
-
-    /**
-     * Returns the current enabled/disabled status of the given provider and user. Callers should
-     * prefer {@link #isLocationEnabledForUser(UserHandle)} unless they depend on provider-specific
-     * APIs.
-     *
-     * Before API version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method would throw
-     * {@link SecurityException} if the location permissions were not sufficient to use the
-     * specified provider.
-     *
-     * @param provider the name of the provider
-     * @param userHandle the user to query
-     * @return true if the provider exists and is enabled
-     *
-     * @throws IllegalArgumentException if provider is null
-     * @hide
-     */
-    @SystemApi
-    public boolean isProviderEnabledForUser(
-            @NonNull String provider, @NonNull UserHandle userHandle) {
-        checkProvider(provider);
-
-        try {
-            return mService.isProviderEnabledForUser(provider, userHandle.getIdentifier());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Method for enabling or disabling a single location provider. This method is deprecated and
-     * functions as a best effort. It should not be relied on in any meaningful sense as providers
-     * may no longer be enabled or disabled by clients.
-     *
-     * @param provider the name of the provider
-     * @param enabled true to enable the provider. false to disable the provider
-     * @param userHandle the user to set
-     * @return true if the value was set, false otherwise
-     *
-     * @throws IllegalArgumentException if provider is null
-     * @deprecated Do not manipulate providers individually, use
-     * {@link #setLocationEnabledForUser(boolean, UserHandle)} instead.
-     * @hide
-     */
-    @Deprecated
-    @SystemApi
-    @RequiresPermission(WRITE_SECURE_SETTINGS)
-    public boolean setProviderEnabledForUser(
-            @NonNull String provider, boolean enabled, @NonNull UserHandle userHandle) {
-        checkProvider(provider);
-
-        return Settings.Secure.putStringForUser(
-                mContext.getContentResolver(),
-                Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
-                (enabled ? "+" : "-") + provider,
-                userHandle.getIdentifier());
-    }
-
-    /**
-     * Get the last known location.
-     *
-     * <p>This location could be very old so use
-     * {@link Location#getElapsedRealtimeNanos} to calculate its age. It can
-     * also return null if no previous location is available.
-     *
-     * <p>Always returns immediately.
-     *
-     * @return The last known location, or null if not available
-     * @throws SecurityException if no suitable permission is present
-     *
-     * @hide
-     */
-    @Nullable
-    public Location getLastLocation() {
-        String packageName = mContext.getPackageName();
-
-        try {
-            return mService.getLastLocation(null, packageName);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Returns a Location indicating the data from the last known
-     * location fix obtained from the given provider.
-     *
-     * <p> This can be done
-     * without starting the provider.  Note that this location could
-     * be out-of-date, for example if the device was turned off and
-     * moved to another location.
-     *
-     * <p> If the provider is currently disabled, null is returned.
-     *
-     * @param provider the name of the provider
-     * @return the last known location for the provider, or null
-     *
-     * @throws SecurityException if no suitable permission is present
-     * @throws IllegalArgumentException if provider is null or doesn't exist
-     */
-    @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
-    @Nullable
-    public Location getLastKnownLocation(@NonNull String provider) {
-        checkProvider(provider);
-        String packageName = mContext.getPackageName();
-        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
-                provider, 0, 0, true);
-
-        try {
-            return mService.getLastLocation(request, packageName);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Creates a mock location provider and adds it to the set of active providers.
-     *
-     * @param name the provider name
-     *
-     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
-     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
-     * allowed} for your app.
-     * @throws IllegalArgumentException if a provider with the given name already exists
-     */
-    public void addTestProvider(
-            @NonNull String name, boolean requiresNetwork, boolean requiresSatellite,
-            boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude,
-            boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) {
-        ProviderProperties properties = new ProviderProperties(requiresNetwork,
-                requiresSatellite, requiresCell, hasMonetaryCost, supportsAltitude, supportsSpeed,
-                supportsBearing, powerRequirement, accuracy);
-        if (name.matches(LocationProvider.BAD_CHARS_REGEX)) {
-            throw new IllegalArgumentException("provider name contains illegal character: " + name);
-        }
-
-        try {
-            mService.addTestProvider(name, properties, mContext.getOpPackageName());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Removes the mock location provider with the given name.
-     *
-     * @param provider the provider name
-     *
-     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
-     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
-     * allowed} for your app.
-     * @throws IllegalArgumentException if no provider with the given name exists
-     */
-    public void removeTestProvider(@NonNull String provider) {
-        try {
-            mService.removeTestProvider(provider, mContext.getOpPackageName());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Sets a mock location for the given provider.
-     * <p>This location will be used in place of any actual location from the provider.
-     * The location object must have a minimum number of fields set to be
-     * considered a valid LocationProvider Location, as per documentation
-     * on {@link Location} class.
-     *
-     * @param provider the provider name
-     * @param loc the mock location
-     *
-     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
-     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
-     * allowed} for your app.
-     * @throws IllegalArgumentException if no provider with the given name exists
-     * @throws IllegalArgumentException if the location is incomplete
-     */
-    public void setTestProviderLocation(@NonNull String provider, @NonNull Location loc) {
-        if (!loc.isComplete()) {
-            IllegalArgumentException e = new IllegalArgumentException(
-                    "Incomplete location object, missing timestamp or accuracy? " + loc);
-            if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN) {
-                // just log on old platform (for backwards compatibility)
-                Log.w(TAG, e);
-                loc.makeComplete();
-            } else {
-                // really throw it!
-                throw e;
-            }
-        }
-
-        try {
-            mService.setTestProviderLocation(provider, loc, mContext.getOpPackageName());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Removes any mock location associated with the given provider.
-     *
-     * @param provider the provider name
-     *
-     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
-     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
-     * allowed} for your app.
-     * @throws IllegalArgumentException if no provider with the given name exists
-     *
-     * @deprecated This function has always been a no-op, and may be removed in the future.
-     */
-    @Deprecated
-    public void clearTestProviderLocation(@NonNull String provider) {}
-
-    /**
-     * Sets a mock enabled value for the given provider.  This value will be used in place
-     * of any actual value from the provider.
-     *
-     * @param provider the provider name
-     * @param enabled the mock enabled value
-     *
-     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
-     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
-     * allowed} for your app.
-     * @throws IllegalArgumentException if no provider with the given name exists
-     */
-    public void setTestProviderEnabled(@NonNull String provider, boolean enabled) {
-        try {
-            mService.setTestProviderEnabled(provider, enabled, mContext.getOpPackageName());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Removes any mock enabled value associated with the given provider.
-     *
-     * @param provider the provider name
-     *
-     * @throws SecurityException if {@link android.app.AppOpsManager#OPSTR_MOCK_LOCATION
-     * mock location app op} is not set to {@link android.app.AppOpsManager#MODE_ALLOWED
-     * allowed} for your app.
-     * @throws IllegalArgumentException if no provider with the given name exists
-     *
-     * @deprecated Use {@link #setTestProviderEnabled(String, boolean)} instead.
-     */
-    @Deprecated
-    public void clearTestProviderEnabled(@NonNull String provider) {
-        setTestProviderEnabled(provider, false);
-    }
-
-    /**
-     * This method has no effect as provider status has been deprecated and is no longer supported.
-     *
-     * @deprecated This method has no effect.
-     */
-    @Deprecated
-    public void setTestProviderStatus(
-            @NonNull String provider, int status, @Nullable Bundle extras, long updateTime) {}
-
-    /**
-     * This method has no effect as provider status has been deprecated and is no longer supported.
-     *
-     * @deprecated This method has no effect.
-     */
-    @Deprecated
-    public void clearTestProviderStatus(@NonNull String provider) {}
-
-    /**
-     * Get the last list of {@link LocationRequest}s sent to the provider.
-     *
-     * @hide
-     */
-    @TestApi
-    @NonNull
-    public List<LocationRequest> getTestProviderCurrentRequests(String providerName) {
-        checkProvider(providerName);
-        try {
-            return mService.getTestProviderCurrentRequests(providerName,
-                    mContext.getOpPackageName());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    // --- GPS-specific support ---
-
-    // This class is used to send Gnss status events to the client's specific thread.
-    private class GnssStatusListenerTransport extends IGnssStatusListener.Stub {
-
-        private final GnssStatus.Callback mGnssCallback;
-        private final OnNmeaMessageListener mGnssNmeaListener;
-
-        private class GnssHandler extends Handler {
-            GnssHandler(Handler handler) {
-                super(handler != null ? handler.getLooper() : Looper.myLooper());
-            }
-
-            @Override
-            public void handleMessage(Message msg) {
-                switch (msg.what) {
-                    case NMEA_RECEIVED:
-                        synchronized (mNmeaBuffer) {
-                            for (Nmea nmea : mNmeaBuffer) {
-                                mGnssNmeaListener.onNmeaMessage(nmea.mNmea, nmea.mTimestamp);
-                            }
-                            mNmeaBuffer.clear();
-                        }
-                        break;
-                    case GNSS_EVENT_STARTED:
-                        mGnssCallback.onStarted();
-                        break;
-                    case GNSS_EVENT_STOPPED:
-                        mGnssCallback.onStopped();
-                        break;
-                    case GNSS_EVENT_FIRST_FIX:
-                        mGnssCallback.onFirstFix(mTimeToFirstFix);
-                        break;
-                    case GNSS_EVENT_SATELLITE_STATUS:
-                        mGnssCallback.onSatelliteStatusChanged(mGnssStatus);
-                        break;
-                    default:
-                        break;
-                }
-            }
-        }
-
-        private final Handler mGnssHandler;
-
-        private static final int NMEA_RECEIVED = 1;
-        private static final int GNSS_EVENT_STARTED = 2;
-        private static final int GNSS_EVENT_STOPPED = 3;
-        private static final int GNSS_EVENT_FIRST_FIX = 4;
-        private static final int GNSS_EVENT_SATELLITE_STATUS = 5;
-
-        private class Nmea {
-            long mTimestamp;
-            String mNmea;
-
-            Nmea(long timestamp, String nmea) {
-                mTimestamp = timestamp;
-                mNmea = nmea;
-            }
-        }
-        private final ArrayList<Nmea> mNmeaBuffer;
-
-        GnssStatusListenerTransport(GnssStatus.Callback callback, Handler handler) {
-            mGnssCallback = callback;
-            mGnssHandler = new GnssHandler(handler);
-            mGnssNmeaListener = null;
-            mNmeaBuffer = null;
-        }
-
-        GnssStatusListenerTransport(OnNmeaMessageListener listener, Handler handler) {
-            mGnssCallback = null;
-            mGnssHandler = new GnssHandler(handler);
-            mGnssNmeaListener = listener;
-            mNmeaBuffer = new ArrayList<>();
-        }
-
-        GnssStatusListenerTransport(GpsStatus.Listener listener, Handler handler) {
-            mGnssHandler = new GnssHandler(handler);
-            mNmeaBuffer = null;
-            mGnssCallback = listener != null ? new GnssStatus.Callback() {
-                @Override
-                public void onStarted() {
-                    listener.onGpsStatusChanged(GpsStatus.GPS_EVENT_STARTED);
-                }
-
-                @Override
-                public void onStopped() {
-                    listener.onGpsStatusChanged(GpsStatus.GPS_EVENT_STOPPED);
-                }
-
-                @Override
-                public void onFirstFix(int ttff) {
-                    listener.onGpsStatusChanged(GpsStatus.GPS_EVENT_FIRST_FIX);
-                }
-
-                @Override
-                public void onSatelliteStatusChanged(GnssStatus status) {
-                    listener.onGpsStatusChanged(GpsStatus.GPS_EVENT_SATELLITE_STATUS);
-                }
-            } : null;
-            mGnssNmeaListener = null;
-        }
-
-        @Override
-        public void onGnssStarted() {
-            if (mGnssCallback != null) {
-                mGnssHandler.obtainMessage(GNSS_EVENT_STARTED).sendToTarget();
-            }
-        }
-
-        @Override
-        public void onGnssStopped() {
-            if (mGnssCallback != null) {
-                mGnssHandler.obtainMessage(GNSS_EVENT_STOPPED).sendToTarget();
-            }
-        }
-
-        @Override
-        public void onFirstFix(int ttff) {
-            if (mGnssCallback != null) {
-                mTimeToFirstFix = ttff;
-                mGnssHandler.obtainMessage(GNSS_EVENT_FIRST_FIX).sendToTarget();
-            }
-        }
-
-        @Override
-        public void onSvStatusChanged(int svCount, int[] prnWithFlags,
-                float[] cn0s, float[] elevations, float[] azimuths, float[] carrierFreqs) {
-            if (mGnssCallback != null) {
-                mGnssStatus = new GnssStatus(svCount, prnWithFlags, cn0s, elevations, azimuths,
-                        carrierFreqs);
-
-                mGnssHandler.removeMessages(GNSS_EVENT_SATELLITE_STATUS);
-                mGnssHandler.obtainMessage(GNSS_EVENT_SATELLITE_STATUS).sendToTarget();
-            }
-        }
-
-        @Override
-        public void onNmeaReceived(long timestamp, String nmea) {
-            if (mGnssNmeaListener != null) {
-                synchronized (mNmeaBuffer) {
-                    mNmeaBuffer.add(new Nmea(timestamp, nmea));
-                }
-
-                mGnssHandler.removeMessages(NMEA_RECEIVED);
-                mGnssHandler.obtainMessage(NMEA_RECEIVED).sendToTarget();
-            }
-        }
-    }
-
-    /**
-     * Adds a GPS status listener.
-     *
-     * @param listener GPS status listener object to register
-     *
-     * @return true if the listener was successfully added
-     *
-     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
-     * @deprecated use {@link #registerGnssStatusCallback(GnssStatus.Callback)} instead.
-     */
-    @Deprecated
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean addGpsStatusListener(GpsStatus.Listener listener) {
-        boolean result;
-
-        if (mGpsStatusListeners.get(listener) != null) {
-            return true;
-        }
-        try {
-            GnssStatusListenerTransport transport = new GnssStatusListenerTransport(listener, null);
-            result = mService.registerGnssStatusCallback(transport, mContext.getPackageName());
-            if (result) {
-                mGpsStatusListeners.put(listener, transport);
-            }
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-
-        return result;
-    }
-
-    /**
-     * Removes a GPS status listener.
-     *
-     * @param listener GPS status listener object to remove
-     * @deprecated use {@link #unregisterGnssStatusCallback(GnssStatus.Callback)} instead.
-     */
-    @Deprecated
-    public void removeGpsStatusListener(GpsStatus.Listener listener) {
-        try {
-            GnssStatusListenerTransport transport = mGpsStatusListeners.remove(listener);
-            if (transport != null) {
-                mService.unregisterGnssStatusCallback(transport);
-            }
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Registers a GNSS status callback.
-     *
-     * @param callback GNSS status callback object to register
-     *
-     * @return true if the listener was successfully added
-     *
-     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
-     */
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean registerGnssStatusCallback(@NonNull GnssStatus.Callback callback) {
-        return registerGnssStatusCallback(callback, null);
-    }
-
-    /**
-     * Registers a GNSS status callback.
-     *
-     * @param callback GNSS status callback object to register
-     * @param handler the handler that the callback runs on.
-     *
-     * @return true if the listener was successfully added
-     *
-     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
-     */
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean registerGnssStatusCallback(
-            @NonNull GnssStatus.Callback callback, @Nullable Handler handler) {
-        boolean result;
-        synchronized (mGnssStatusListeners) {
-            if (mGnssStatusListeners.get(callback) != null) {
-                return true;
-            }
-            try {
-                GnssStatusListenerTransport transport =
-                        new GnssStatusListenerTransport(callback, handler);
-                result = mService.registerGnssStatusCallback(transport, mContext.getPackageName());
-                if (result) {
-                    mGnssStatusListeners.put(callback, transport);
-                }
-            } catch (RemoteException e) {
-                throw e.rethrowFromSystemServer();
-            }
-        }
-
-        return result;
-    }
-
-    /**
-     * Removes a GNSS status callback.
-     *
-     * @param callback GNSS status callback object to remove
-     */
-    public void unregisterGnssStatusCallback(@NonNull GnssStatus.Callback callback) {
-        synchronized (mGnssStatusListeners) {
-            try {
-                GnssStatusListenerTransport transport = mGnssStatusListeners.remove(callback);
-                if (transport != null) {
-                    mService.unregisterGnssStatusCallback(transport);
-                }
-            } catch (RemoteException e) {
-                throw e.rethrowFromSystemServer();
-            }
-        }
-    }
-
-    /**
-     * Adds an NMEA listener.
-     *
-     * @param listener a {@link GpsStatus.NmeaListener} object to register
-     *
-     * @return true if the listener was successfully added
-     *
-     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
-     * @deprecated use {@link #addNmeaListener(OnNmeaMessageListener)} instead.
-     * @removed
-     */
-    @Deprecated
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean addNmeaListener(GpsStatus.NmeaListener listener) {
-        return false;
-    }
-
-    /**
-     * Removes an NMEA listener.
-     *
-     * @param listener a {@link GpsStatus.NmeaListener} object to remove
-     * @deprecated use {@link #removeNmeaListener(OnNmeaMessageListener)} instead.
-     * @removed
-     */
-    @Deprecated
-    public void removeNmeaListener(GpsStatus.NmeaListener listener) {}
-
-    /**
-     * Adds an NMEA listener.
-     *
-     * @param listener a {@link OnNmeaMessageListener} object to register
-     *
-     * @return true if the listener was successfully added
-     *
-     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
-     */
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean addNmeaListener(@NonNull OnNmeaMessageListener listener) {
-        return addNmeaListener(listener, null);
-    }
-
-    /**
-     * Adds an NMEA listener.
-     *
-     * @param listener a {@link OnNmeaMessageListener} object to register
-     * @param handler the handler that the listener runs on.
-     *
-     * @return true if the listener was successfully added
-     *
-     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
-     */
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean addNmeaListener(
-            @NonNull OnNmeaMessageListener listener, @Nullable Handler handler) {
-        boolean result;
-
-        if (mGnssNmeaListeners.get(listener) != null) {
-            // listener is already registered
-            return true;
-        }
-        try {
-            GnssStatusListenerTransport transport =
-                    new GnssStatusListenerTransport(listener, handler);
-            result = mService.registerGnssStatusCallback(transport, mContext.getPackageName());
-            if (result) {
-                mGnssNmeaListeners.put(listener, transport);
-            }
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-
-        return result;
-    }
-
-    /**
-     * Removes an NMEA listener.
-     *
-     * @param listener a {@link OnNmeaMessageListener} object to remove
-     */
-    public void removeNmeaListener(@NonNull OnNmeaMessageListener listener) {
-        try {
-            GnssStatusListenerTransport transport = mGnssNmeaListeners.remove(listener);
-            if (transport != null) {
-                mService.unregisterGnssStatusCallback(transport);
-            }
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * No-op method to keep backward-compatibility.
-     * Don't use it. Use {@link #registerGnssMeasurementsCallback} instead.
-     * @hide
-     * @deprecated Not supported anymore.
-     * @removed
-     */
-    @Deprecated
-    @SystemApi
-    @SuppressLint("Doclava125")
-    public boolean addGpsMeasurementListener(GpsMeasurementsEvent.Listener listener) {
-        return false;
-    }
-
-    /**
-     * Registers a GPS Measurement callback.
-     *
-     * @param callback a {@link GnssMeasurementsEvent.Callback} object to register.
-     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
-     */
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean registerGnssMeasurementsCallback(
-            @NonNull GnssMeasurementsEvent.Callback callback) {
-        return registerGnssMeasurementsCallback(callback, null);
-    }
-
-    /**
-     * Registers a GPS Measurement callback.
-     *
-     * @param callback a {@link GnssMeasurementsEvent.Callback} object to register.
-     * @param handler the handler that the callback runs on.
-     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
-     */
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean registerGnssMeasurementsCallback(
-            @NonNull GnssMeasurementsEvent.Callback callback, @Nullable Handler handler) {
-        return mGnssMeasurementCallbackTransport.add(callback, handler);
-    }
-
-    /**
-     * Injects GNSS measurement corrections into the GNSS chipset.
-     *
-     * @param measurementCorrections a {@link GnssMeasurementCorrections} object with the GNSS
-     *     measurement corrections to be injected into the GNSS chipset.
-     * @hide
-     */
-    @SystemApi
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public void injectGnssMeasurementCorrections(
-            @NonNull GnssMeasurementCorrections measurementCorrections) {
-        try {
-            mGnssMeasurementCallbackTransport.injectGnssMeasurementCorrections(
-                    measurementCorrections);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
+    // ================= GNSS APIs =================
 
     /**
      * Returns the supported capabilities of the GNSS chipset.
@@ -1996,7 +1615,7 @@
     @RequiresPermission(ACCESS_FINE_LOCATION)
     public @NonNull GnssCapabilities getGnssCapabilities() {
         try {
-            long gnssCapabilities = mGnssMeasurementCallbackTransport.getGnssCapabilities();
+            long gnssCapabilities = mService.getGnssCapabilities(mContext.getPackageName());
             if (gnssCapabilities == GnssCapabilities.INVALID_CAPABILITIES) {
                 gnssCapabilities = 0L;
             }
@@ -2007,122 +1626,9 @@
     }
 
     /**
-     * No-op method to keep backward-compatibility. Don't use it. Use {@link
-     * #unregisterGnssMeasurementsCallback} instead.
-     *
-     * @hide
-     * @deprecated use {@link #unregisterGnssMeasurementsCallback(GnssMeasurementsEvent.Callback)}
-     *     instead.
-     * @removed
-     */
-    @Deprecated
-    @SystemApi
-    @SuppressLint("Doclava125")
-    public void removeGpsMeasurementListener(GpsMeasurementsEvent.Listener listener) {}
-
-    /**
-     * Unregisters a GPS Measurement callback.
-     *
-     * @param callback a {@link GnssMeasurementsEvent.Callback} object to remove.
-     */
-    public void unregisterGnssMeasurementsCallback(
-            @NonNull GnssMeasurementsEvent.Callback callback) {
-        mGnssMeasurementCallbackTransport.remove(callback);
-    }
-
-    /**
-     * No-op method to keep backward-compatibility.
-     * Don't use it. Use {@link #registerGnssNavigationMessageCallback} instead.
-     * @hide
-     * @deprecated Not supported anymore.
-     * @removed
-     */
-    @Deprecated
-    @SystemApi
-    @SuppressLint("Doclava125")
-    public boolean addGpsNavigationMessageListener(GpsNavigationMessageEvent.Listener listener) {
-        return false;
-    }
-
-    /**
-     * No-op method to keep backward-compatibility.
-     * Don't use it. Use {@link #unregisterGnssNavigationMessageCallback} instead.
-     * @hide
-     * @deprecated use
-     * {@link #unregisterGnssNavigationMessageCallback(GnssNavigationMessage.Callback)}
-     * instead
-     * @removed
-     */
-    @Deprecated
-    @SystemApi
-    @SuppressLint("Doclava125")
-    public void removeGpsNavigationMessageListener(GpsNavigationMessageEvent.Listener listener) {}
-
-    /**
-     * Registers a GNSS Navigation Message callback.
-     *
-     * @param callback a {@link GnssNavigationMessage.Callback} object to register.
-     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
-     */
-    public boolean registerGnssNavigationMessageCallback(
-            @NonNull GnssNavigationMessage.Callback callback) {
-        return registerGnssNavigationMessageCallback(callback, null);
-    }
-
-    /**
-     * Registers a GNSS Navigation Message callback.
-     *
-     * @param callback a {@link GnssNavigationMessage.Callback} object to register.
-     * @param handler the handler that the callback runs on.
-     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
-     */
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public boolean registerGnssNavigationMessageCallback(
-            @NonNull GnssNavigationMessage.Callback callback, @Nullable Handler handler) {
-        return mGnssNavigationMessageCallbackTransport.add(callback, handler);
-    }
-
-    /**
-     * Unregisters a GNSS Navigation Message callback.
-     *
-     * @param callback a {@link GnssNavigationMessage.Callback} object to remove.
-     */
-    public void unregisterGnssNavigationMessageCallback(
-            @NonNull GnssNavigationMessage.Callback callback) {
-        mGnssNavigationMessageCallbackTransport.remove(callback);
-    }
-
-    /**
-     * Retrieves information about the current status of the GPS engine.
-     * This should only be called from the {@link GpsStatus.Listener#onGpsStatusChanged}
-     * callback to ensure that the data is copied atomically.
-     *
-     * The caller may either pass in a {@link GpsStatus} object to set with the latest
-     * status information, or pass null to create a new {@link GpsStatus} object.
-     *
-     * @param status object containing GPS status details, or null.
-     * @return status object containing updated GPS status.
-     */
-    @Deprecated
-    @RequiresPermission(ACCESS_FINE_LOCATION)
-    public @Nullable GpsStatus getGpsStatus(@Nullable GpsStatus status) {
-        if (status == null) {
-            status = new GpsStatus();
-        }
-        // When mGnssStatus is null, that means that this method is called outside
-        // onGpsStatusChanged().  Return an empty status to maintain backwards compatibility.
-        if (mGnssStatus != null) {
-            status.setStatus(mGnssStatus, mTimeToFirstFix);
-        }
-        return status;
-    }
-
-    /**
-     * Returns the model year of the GNSS hardware and software build.
-     *
-     * <p> More details, such as build date, may be available in {@link #getGnssHardwareModelName()}.
-     *
-     * <p> May return 0 if the model year is less than 2016.
+     * Returns the model year of the GNSS hardware and software build. More details, such as build
+     * date, may be available in {@link #getGnssHardwareModelName()}. May return 0 if the model year
+     * is less than 2016.
      */
     public int getGnssYearOfHardware() {
         try {
@@ -2151,6 +1657,454 @@
     }
 
     /**
+     * Retrieves information about the current status of the GPS engine. This should only be called
+     * from within the {@link GpsStatus.Listener#onGpsStatusChanged} callback to ensure that the
+     * data is copied atomically.
+     *
+     * The caller may either pass in an existing {@link GpsStatus} object to be overwritten, or pass
+     * null to create a new {@link GpsStatus} object.
+     *
+     * @param status object containing GPS status details, or null.
+     * @return status object containing updated GPS status.
+     *
+     * @deprecated GpsStatus APIs are deprecated, use {@link GnssStatus} APIs instead.
+     */
+    @Deprecated
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public @Nullable GpsStatus getGpsStatus(@Nullable GpsStatus status) {
+        if (status == null) {
+            status = new GpsStatus();
+        }
+        // When mGnssStatus is null, that means that this method is called outside
+        // onGpsStatusChanged().  Return an empty status to maintain backwards compatibility.
+        GnssStatus gnssStatus = mGnssStatusListenerManager.getGnssStatus();
+        int ttff = mGnssStatusListenerManager.getTtff();
+        if (gnssStatus != null) {
+            status.setStatus(gnssStatus, ttff);
+        }
+        return status;
+    }
+
+    /**
+     * Adds a GPS status listener.
+     *
+     * @param listener GPS status listener object to register
+     * @return true if the listener was successfully added
+     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
+     *
+     * @deprecated use {@link #registerGnssStatusCallback(GnssStatus.Callback)} instead. No longer
+     * supported in apps targeting R and above.
+     */
+    @Deprecated
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean addGpsStatusListener(GpsStatus.Listener listener) {
+        UnsupportedOperationException ex = new UnsupportedOperationException(
+                "GpsStatus APIs not supported in R and above, use GnssStatus APIs instead");
+        if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
+            throw ex;
+        } else {
+            Log.w(TAG, ex);
+        }
+
+        try {
+            return mGnssStatusListenerManager.addListener(listener, new Handler());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Removes a GPS status listener.
+     *
+     * @param listener GPS status listener object to remove
+     *
+     * @deprecated use {@link #unregisterGnssStatusCallback(GnssStatus.Callback)} instead. No longer
+     * supported in apps targeting R and above.
+     */
+    @Deprecated
+    public void removeGpsStatusListener(GpsStatus.Listener listener) {
+        UnsupportedOperationException ex = new UnsupportedOperationException(
+                "GpsStatus APIs not supported in R and above, use GnssStatus APIs instead");
+        if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
+            throw ex;
+        } else {
+            Log.w(TAG, ex);
+        }
+
+        try {
+            mGnssStatusListenerManager.removeListener(listener);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Registers a GNSS status callback.
+     *
+     * @param callback GNSS status callback object to register
+     * @return true if the listener was successfully added
+     *
+     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
+     *
+     * @deprecated Use {@link #registerGnssStatusCallback(GnssStatus.Callback, Handler)} or {@link
+     * #registerGnssStatusCallback(Executor, GnssStatus.Callback)} instead.
+     */
+    @Deprecated
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssStatusCallback(@NonNull GnssStatus.Callback callback) {
+        return registerGnssStatusCallback(callback, null);
+    }
+
+    /**
+     * Registers a GNSS status callback.
+     *
+     * @param callback GNSS status callback object to register
+     * @param handler  a handler with a looper that the callback runs on
+     * @return true if the listener was successfully added
+     *
+     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssStatusCallback(
+            @NonNull GnssStatus.Callback callback, @Nullable Handler handler) {
+        if (handler == null) {
+            handler = new Handler();
+        }
+
+        try {
+            return mGnssStatusListenerManager.addListener(callback, handler);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Registers a GNSS status callback.
+     *
+     * @param callback GNSS status callback object to register
+     * @param executor the executor that the callback runs on
+     * @return true if the listener was successfully added
+     *
+     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssStatusCallback(
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull GnssStatus.Callback callback) {
+        try {
+            return mGnssStatusListenerManager.addListener(callback, executor);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Removes a GNSS status callback.
+     *
+     * @param callback GNSS status callback object to remove
+     */
+    public void unregisterGnssStatusCallback(@NonNull GnssStatus.Callback callback) {
+        try {
+            mGnssStatusListenerManager.removeListener(callback);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * No-op method to keep backward-compatibility.
+     *
+     * @deprecated use {@link #addNmeaListener(OnNmeaMessageListener)} instead.
+     * @removed
+     */
+    @Deprecated
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean addNmeaListener(GpsStatus.NmeaListener listener) {
+        return false;
+    }
+
+    /**
+     * No-op method to keep backward-compatibility.
+     *
+     * @deprecated use {@link #removeNmeaListener(OnNmeaMessageListener)} instead.
+     * @removed
+     */
+    @Deprecated
+    public void removeNmeaListener(GpsStatus.NmeaListener listener) {}
+
+    /**
+     * Adds an NMEA listener.
+     *
+     * @param listener a {@link OnNmeaMessageListener} object to register
+     * @return true if the listener was successfully added
+     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
+     * @deprecated Use {@link #addNmeaListener(OnNmeaMessageListener, Handler)} or {@link
+     * #addNmeaListener(Executor, OnNmeaMessageListener)} instead.
+     */
+    @Deprecated
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean addNmeaListener(@NonNull OnNmeaMessageListener listener) {
+        return addNmeaListener(listener, null);
+    }
+
+    /**
+     * Adds an NMEA listener.
+     *
+     * @param listener a {@link OnNmeaMessageListener} object to register
+     * @param handler  a handler with the looper that the listener runs on.
+     * @return true if the listener was successfully added
+     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean addNmeaListener(
+            @NonNull OnNmeaMessageListener listener, @Nullable Handler handler) {
+        if (handler == null) {
+            handler = new Handler();
+        }
+        try {
+            return mGnssStatusListenerManager.addListener(listener, handler);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Adds an NMEA listener.
+     *
+     * @param listener a {@link OnNmeaMessageListener} object to register
+     * @param executor the {@link Executor} that the listener runs on.
+     * @return true if the listener was successfully added
+     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean addNmeaListener(
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull OnNmeaMessageListener listener) {
+        try {
+            return mGnssStatusListenerManager.addListener(listener, executor);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Removes an NMEA listener.
+     *
+     * @param listener a {@link OnNmeaMessageListener} object to remove
+     */
+    public void removeNmeaListener(@NonNull OnNmeaMessageListener listener) {
+        try {
+            mGnssStatusListenerManager.removeListener(listener);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * No-op method to keep backward-compatibility.
+     *
+     * @hide
+     * @deprecated Use {@link #registerGnssMeasurementsCallback} instead.
+     * @removed
+     */
+    @Deprecated
+    @SystemApi
+    public boolean addGpsMeasurementListener(GpsMeasurementsEvent.Listener listener) {
+        return false;
+    }
+
+    /**
+     * No-op method to keep backward-compatibility.
+     *
+     * @hide
+     * @deprecated Use {@link #unregisterGnssMeasurementsCallback} instead.
+     * @removed
+     */
+    @Deprecated
+    @SystemApi
+    public void removeGpsMeasurementListener(GpsMeasurementsEvent.Listener listener) {}
+
+    /**
+     * Registers a GPS Measurement callback.
+     *
+     * @param callback a {@link GnssMeasurementsEvent.Callback} object to register.
+     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
+     * @deprecated Use {@link
+     * #registerGnssMeasurementsCallback(GnssMeasurementsEvent.Callback, Handler)} or {@link
+     * #registerGnssMeasurementsCallback(Executor, GnssMeasurementsEvent.Callback)} instead.
+     */
+    @Deprecated
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssMeasurementsCallback(
+            @NonNull GnssMeasurementsEvent.Callback callback) {
+        return registerGnssMeasurementsCallback(callback, null);
+    }
+
+    /**
+     * Registers a GPS Measurement callback.
+     *
+     * @param callback a {@link GnssMeasurementsEvent.Callback} object to register.
+     * @param handler  the handler that the callback runs on.
+     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssMeasurementsCallback(
+            @NonNull GnssMeasurementsEvent.Callback callback, @Nullable Handler handler) {
+        if (handler == null) {
+            handler = new Handler();
+        }
+        try {
+            return mGnssMeasurementsListenerManager.addListener(callback, handler);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Registers a GPS Measurement callback.
+     *
+     * @param callback a {@link GnssMeasurementsEvent.Callback} object to register.
+     * @param executor the executor that the callback runs on.
+     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssMeasurementsCallback(
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull GnssMeasurementsEvent.Callback callback) {
+        try {
+            return mGnssMeasurementsListenerManager.addListener(callback, executor);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Injects GNSS measurement corrections into the GNSS chipset.
+     *
+     * @param measurementCorrections a {@link GnssMeasurementCorrections} object with the GNSS
+     *     measurement corrections to be injected into the GNSS chipset.
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public void injectGnssMeasurementCorrections(
+            @NonNull GnssMeasurementCorrections measurementCorrections) {
+        Preconditions.checkArgument(measurementCorrections != null);
+        try {
+            mService.injectGnssMeasurementCorrections(
+                    measurementCorrections, mContext.getPackageName());
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Unregisters a GPS Measurement callback.
+     *
+     * @param callback a {@link GnssMeasurementsEvent.Callback} object to remove.
+     */
+    public void unregisterGnssMeasurementsCallback(
+            @NonNull GnssMeasurementsEvent.Callback callback) {
+        try {
+            mGnssMeasurementsListenerManager.removeListener(callback);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * No-op method to keep backward-compatibility.
+     *
+     * @hide
+     * @deprecated Use {@link #registerGnssNavigationMessageCallback} instead.
+     * @removed
+     */
+    @Deprecated
+    @SystemApi
+    public boolean addGpsNavigationMessageListener(GpsNavigationMessageEvent.Listener listener) {
+        return false;
+    }
+
+    /**
+     * No-op method to keep backward-compatibility.
+     *
+     * @hide
+     * @deprecated Use {@link #unregisterGnssNavigationMessageCallback} instead.
+     * @removed
+     */
+    @Deprecated
+    @SystemApi
+    public void removeGpsNavigationMessageListener(GpsNavigationMessageEvent.Listener listener) {}
+
+    /**
+     * Registers a GNSS Navigation Message callback.
+     *
+     * @param callback a {@link GnssNavigationMessage.Callback} object to register.
+     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
+     * @deprecated Use {@link
+     * #registerGnssNavigationMessageCallback(GnssNavigationMessage.Callback, Handler)} or {@link
+     * #registerGnssNavigationMessageCallback(Executor, GnssNavigationMessage.Callback)} instead.
+     */
+    @Deprecated
+    public boolean registerGnssNavigationMessageCallback(
+            @NonNull GnssNavigationMessage.Callback callback) {
+        return registerGnssNavigationMessageCallback(callback, null);
+    }
+
+    /**
+     * Registers a GNSS Navigation Message callback.
+     *
+     * @param callback a {@link GnssNavigationMessage.Callback} object to register.
+     * @param handler  the handler that the callback runs on.
+     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssNavigationMessageCallback(
+            @NonNull GnssNavigationMessage.Callback callback, @Nullable Handler handler) {
+        if (handler == null) {
+            handler = new Handler();
+        }
+
+        try {
+            return mGnssNavigationMessageListenerTransport.addListener(callback, handler);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Registers a GNSS Navigation Message callback.
+     *
+     * @param callback a {@link GnssNavigationMessage.Callback} object to register.
+     * @param executor the looper that the callback runs on.
+     * @return {@code true} if the callback was added successfully, {@code false} otherwise.
+     */
+    @RequiresPermission(ACCESS_FINE_LOCATION)
+    public boolean registerGnssNavigationMessageCallback(
+            @NonNull @CallbackExecutor Executor executor,
+            @NonNull GnssNavigationMessage.Callback callback) {
+        try {
+            return mGnssNavigationMessageListenerTransport.addListener(callback, executor);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Unregisters a GNSS Navigation Message callback.
+     *
+     * @param callback a {@link GnssNavigationMessage.Callback} object to remove.
+     */
+    public void unregisterGnssNavigationMessageCallback(
+            @NonNull GnssNavigationMessage.Callback callback) {
+        try {
+            mGnssNavigationMessageListenerTransport.removeListener(callback);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Returns the batch size (in number of Location objects) that are supported by the batching
      * interface.
      *
@@ -2192,12 +2146,20 @@
     @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
     public boolean registerGnssBatchedLocationCallback(long periodNanos, boolean wakeOnFifoFull,
             @NonNull BatchedLocationCallback callback, @Nullable Handler handler) {
-        mBatchedLocationCallbackTransport.add(callback, handler);
+        if (handler == null) {
+            handler = new Handler();
+        }
 
-        try {
-            return mService.startGnssBatch(periodNanos, wakeOnFifoFull, mContext.getPackageName());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
+        synchronized (mBatchedLocationCallbackManager) {
+            try {
+                if (mBatchedLocationCallbackManager.addListener(callback, handler)) {
+                    return mService.startGnssBatch(periodNanos, wakeOnFifoFull,
+                            mContext.getPackageName());
+                }
+                return false;
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
         }
     }
 
@@ -2231,34 +2193,14 @@
     @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
     public boolean unregisterGnssBatchedLocationCallback(
             @NonNull BatchedLocationCallback callback) {
-
-        mBatchedLocationCallbackTransport.remove(callback);
-
-        try {
-            return mService.stopGnssBatch();
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Sends additional commands to a location provider. Can be used to support provider specific
-     * extensions to the Location Manager API.
-     *
-     * @param provider name of the location provider.
-     * @param command  name of the command to send to the provider.
-     * @param extras   optional arguments for the command (or null).
-     * @return true always
-     */
-    public boolean sendExtraCommand(
-            @NonNull String provider, @NonNull String command, @Nullable Bundle extras) {
-        Preconditions.checkArgument(provider != null, "invalid null provider");
-        Preconditions.checkArgument(command != null, "invalid null command");
-
-        try {
-            return mService.sendExtraCommand(provider, command, extras);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
+        synchronized (mBatchedLocationCallbackManager) {
+            try {
+                mBatchedLocationCallbackManager.removeListener(callback);
+                mService.stopGnssBatch();
+                return true;
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
         }
     }
 
@@ -2277,31 +2219,11 @@
         }
     }
 
-    private static void checkProvider(String provider) {
-        if (provider == null) {
-            throw new IllegalArgumentException("invalid provider: " + provider);
-        }
-    }
-
-    private static void checkCriteria(Criteria criteria) {
-        if (criteria == null) {
-            throw new IllegalArgumentException("invalid criteria: " + criteria);
-        }
-    }
-
-    private static void checkListener(LocationListener listener) {
-        if (listener == null) {
-            throw new IllegalArgumentException("invalid listener: " + listener);
-        }
-    }
-
-    private void checkPendingIntent(PendingIntent intent) {
-        if (intent == null) {
-            throw new IllegalArgumentException("invalid pending intent: " + intent);
-        }
-        if (!intent.isTargetedToPackage()) {
+    private void checkPendingIntent(PendingIntent pendingIntent) {
+        Preconditions.checkArgument(pendingIntent != null, "invalid null pending intent");
+        if (!pendingIntent.isTargetedToPackage()) {
             IllegalArgumentException e = new IllegalArgumentException(
-                    "pending intent must be targeted to package");
+                    "invalid pending intent - must be targeted to package");
             if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.JELLY_BEAN) {
                 throw e;
             } else {
@@ -2310,123 +2232,399 @@
         }
     }
 
-    private static void checkGeofence(Geofence fence) {
-        if (fence == null) {
-            throw new IllegalArgumentException("invalid geofence: " + fence);
+    private class LocationListenerTransport extends ILocationListener.Stub {
+
+        private final LocationListener mListener;
+        @Nullable private volatile Executor mExecutor = null;
+
+        private LocationListenerTransport(@NonNull LocationListener listener) {
+            Preconditions.checkArgument(listener != null, "invalid null listener");
+            mListener = listener;
+        }
+
+        public LocationListener getKey() {
+            return mListener;
+        }
+
+        public void register(@NonNull Executor executor) {
+            Preconditions.checkArgument(executor != null, "invalid null executor");
+            mExecutor = executor;
+        }
+
+        public void unregister() {
+            mExecutor = null;
+        }
+
+        @Override
+        public void onLocationChanged(Location location) {
+            Executor currentExecutor = mExecutor;
+            if (currentExecutor == null) {
+                return;
+            }
+
+            try {
+                currentExecutor.execute(() -> {
+                    try {
+                        if (currentExecutor != mExecutor) {
+                            return;
+                        }
+
+                        // we may be under the binder identity if a direct executor is used
+                        long identity = Binder.clearCallingIdentity();
+                        try {
+                            mListener.onLocationChanged(location);
+                        } finally {
+                            Binder.restoreCallingIdentity(identity);
+                        }
+                    } finally {
+                        locationCallbackFinished();
+                    }
+                });
+            } catch (RejectedExecutionException e) {
+                locationCallbackFinished();
+                throw e;
+            }
+        }
+
+        @Override
+        public void onStatusChanged(String provider, int status, Bundle extras) {
+            Executor currentExecutor = mExecutor;
+            if (currentExecutor == null) {
+                return;
+            }
+
+            try {
+                currentExecutor.execute(() -> {
+                    try {
+                        if (currentExecutor != mExecutor) {
+                            return;
+                        }
+
+                        // we may be under the binder identity if a direct executor is used
+                        long identity = Binder.clearCallingIdentity();
+                        try {
+                            mListener.onStatusChanged(provider, status, extras);
+                        } finally {
+                            Binder.restoreCallingIdentity(identity);
+                        }
+                    } finally {
+                        locationCallbackFinished();
+                    }
+                });
+            } catch (RejectedExecutionException e) {
+                locationCallbackFinished();
+                throw e;
+            }
+        }
+
+        @Override
+        public void onProviderEnabled(String provider) {
+            Executor currentExecutor = mExecutor;
+            if (currentExecutor == null) {
+                return;
+            }
+
+            try {
+                currentExecutor.execute(() -> {
+                    try {
+                        if (currentExecutor != mExecutor) {
+                            return;
+                        }
+
+                        // we may be under the binder identity if a direct executor is used
+                        long identity = Binder.clearCallingIdentity();
+                        try {
+                            mListener.onProviderEnabled(provider);
+                        } finally {
+                            Binder.restoreCallingIdentity(identity);
+                        }
+                    } finally {
+                        locationCallbackFinished();
+                    }
+                });
+            } catch (RejectedExecutionException e) {
+                locationCallbackFinished();
+                throw e;
+            }
+        }
+
+        @Override
+        public void onProviderDisabled(String provider) {
+            Executor currentExecutor = mExecutor;
+            if (currentExecutor == null) {
+                return;
+            }
+
+            try {
+                currentExecutor.execute(() -> {
+                    try {
+                        if (currentExecutor != mExecutor) {
+                            return;
+                        }
+
+                        // we may be under the binder identity if a direct executor is used
+                        long identity = Binder.clearCallingIdentity();
+                        try {
+                            mListener.onProviderDisabled(provider);
+                        } finally {
+                            Binder.restoreCallingIdentity(identity);
+                        }
+                    } finally {
+                        locationCallbackFinished();
+                    }
+                });
+            } catch (RejectedExecutionException e) {
+                locationCallbackFinished();
+                throw e;
+            }
+        }
+
+        private void locationCallbackFinished() {
+            try {
+                mService.locationCallbackFinished(this);
+            } catch (RemoteException e) {
+                throw e.rethrowFromSystemServer();
+            }
         }
     }
 
-    /**
-     * Returns true if the given package name matches a location provider package, and false
-     * otherwise.
-     *
-     * @hide
-     */
-    @SystemApi
-    @RequiresPermission(Manifest.permission.READ_DEVICE_CONFIG)
-    public boolean isProviderPackage(@NonNull String packageName) {
-        try {
-            return mService.isProviderPackage(packageName);
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
-            return false;
+    private static class NmeaAdapter extends GnssStatus.Callback implements OnNmeaMessageListener {
+
+        private final OnNmeaMessageListener mListener;
+
+        private NmeaAdapter(OnNmeaMessageListener listener) {
+            mListener = listener;
+        }
+
+        @Override
+        public void onNmeaMessage(String message, long timestamp) {
+            mListener.onNmeaMessage(message, timestamp);
         }
     }
 
-    /**
-     * Set the extra location controller package for location services on the device.
-     *
-     * @hide
-     */
-    @SystemApi
-    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
-    public void setExtraLocationControllerPackage(@Nullable String packageName) {
-        try {
-            mService.setExtraLocationControllerPackage(packageName);
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
+    private class GnssStatusListenerManager extends
+            AbstractListenerManager<GnssStatus.Callback> {
+
+        @Nullable
+        private IGnssStatusListener mListenerTransport;
+
+        @Nullable
+        private volatile GnssStatus mGnssStatus;
+        private volatile int mTtff;
+
+        public GnssStatus getGnssStatus() {
+            return mGnssStatus;
+        }
+
+        public int getTtff() {
+            return mTtff;
+        }
+
+        public boolean addListener(@NonNull GpsStatus.Listener listener, @NonNull Handler handler)
+                throws RemoteException {
+            return addInternal(listener, handler);
+        }
+
+        public boolean addListener(@NonNull OnNmeaMessageListener listener,
+                @NonNull Handler handler)
+                throws RemoteException {
+            return addInternal(listener, handler);
+        }
+
+        public boolean addListener(@NonNull OnNmeaMessageListener listener,
+                @NonNull Executor executor)
+                throws RemoteException {
+            return addInternal(listener, executor);
+        }
+
+        @Override
+        protected GnssStatus.Callback convertKey(Object listener) {
+            if (listener instanceof GnssStatus.Callback) {
+                return (GnssStatus.Callback) listener;
+            } else if (listener instanceof GpsStatus.Listener) {
+                return new GnssStatus.Callback() {
+                    private final GpsStatus.Listener mGpsListener = (GpsStatus.Listener) listener;
+
+                    @Override
+                    public void onStarted() {
+                        mGpsListener.onGpsStatusChanged(GpsStatus.GPS_EVENT_STARTED);
+                    }
+
+                    @Override
+                    public void onStopped() {
+                        mGpsListener.onGpsStatusChanged(GpsStatus.GPS_EVENT_STOPPED);
+                    }
+
+                    @Override
+                    public void onFirstFix(int ttffMillis) {
+                        mGpsListener.onGpsStatusChanged(GpsStatus.GPS_EVENT_FIRST_FIX);
+                    }
+
+                    @Override
+                    public void onSatelliteStatusChanged(GnssStatus status) {
+                        mGpsListener.onGpsStatusChanged(GpsStatus.GPS_EVENT_SATELLITE_STATUS);
+                    }
+                };
+            } else if (listener instanceof OnNmeaMessageListener) {
+                return new NmeaAdapter((OnNmeaMessageListener) listener);
+            } else {
+                throw new IllegalStateException();
+            }
+        }
+
+        @Override
+        protected boolean registerService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport == null);
+
+            mListenerTransport = new GnssStatusListener();
+            return mService.registerGnssStatusCallback(mListenerTransport,
+                    mContext.getPackageName());
+        }
+
+        @Override
+        protected void unregisterService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport != null);
+
+            mService.unregisterGnssStatusCallback(mListenerTransport);
+            mListenerTransport = null;
+        }
+
+        private class GnssStatusListener extends IGnssStatusListener.Stub {
+            @Override
+            public void onGnssStarted() {
+                execute(GnssStatus.Callback::onStarted);
+            }
+
+            @Override
+            public void onGnssStopped() {
+                execute(GnssStatus.Callback::onStopped);
+            }
+
+            @Override
+            public void onFirstFix(int ttff) {
+                mTtff = ttff;
+                execute((callback) -> callback.onFirstFix(ttff));
+            }
+
+            @Override
+            public void onSvStatusChanged(int svCount, int[] svidWithFlags, float[] cn0s,
+                    float[] elevations, float[] azimuths, float[] carrierFreqs) {
+                GnssStatus localStatus = new GnssStatus(svCount, svidWithFlags, cn0s, elevations,
+                        azimuths, carrierFreqs);
+                mGnssStatus = localStatus;
+                execute((callback) -> callback.onSatelliteStatusChanged(localStatus));
+            }
+
+            @Override
+            public void onNmeaReceived(long timestamp, String nmea) {
+                execute((callback) -> {
+                    if (callback instanceof NmeaAdapter) {
+                        ((NmeaAdapter) callback).onNmeaMessage(nmea, timestamp);
+                    }
+                });
+            }
         }
     }
 
-    /**
-     * Set the extra location controller package for location services on the device.
-     *
-     * @removed
-     * @deprecated Use {@link #setExtraLocationControllerPackage} instead.
-     * @hide
-     */
-    @Deprecated
-    @SystemApi
-    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
-    public void setLocationControllerExtraPackage(String packageName) {
-        try {
-            mService.setExtraLocationControllerPackage(packageName);
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
+    private class GnssMeasurementsListenerManager extends
+            AbstractListenerManager<GnssMeasurementsEvent.Callback> {
+
+        @Nullable
+        private IGnssMeasurementsListener mListenerTransport;
+
+        @Override
+        protected boolean registerService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport == null);
+
+            mListenerTransport = new GnssMeasurementsListener();
+            return mService.addGnssMeasurementsListener(mListenerTransport,
+                    mContext.getPackageName());
+        }
+
+        @Override
+        protected void unregisterService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport != null);
+
+            mService.removeGnssMeasurementsListener(mListenerTransport);
+            mListenerTransport = null;
+        }
+
+        private class GnssMeasurementsListener extends IGnssMeasurementsListener.Stub {
+            @Override
+            public void onGnssMeasurementsReceived(final GnssMeasurementsEvent event) {
+                execute((callback) -> callback.onGnssMeasurementsReceived(event));
+            }
+
+            @Override
+            public void onStatusChanged(int status) {
+                execute((callback) -> callback.onStatusChanged(status));
+            }
         }
     }
 
-    /**
-     * Returns the extra location controller package on the device.
-     *
-     * @hide
-     */
-    @SystemApi
-    public @Nullable String getExtraLocationControllerPackage() {
-        try {
-            return mService.getExtraLocationControllerPackage();
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
-            return null;
+    private class GnssNavigationMessageListenerManager extends
+            AbstractListenerManager<GnssNavigationMessage.Callback> {
+
+        @Nullable
+        private IGnssNavigationMessageListener mListenerTransport;
+
+        @Override
+        protected boolean registerService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport == null);
+
+            mListenerTransport = new GnssNavigationMessageListener();
+            return mService.addGnssNavigationMessageListener(mListenerTransport,
+                    mContext.getPackageName());
+        }
+
+        @Override
+        protected void unregisterService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport != null);
+
+            mService.removeGnssNavigationMessageListener(mListenerTransport);
+            mListenerTransport = null;
+        }
+
+        private class GnssNavigationMessageListener extends IGnssNavigationMessageListener.Stub {
+            @Override
+            public void onGnssNavigationMessageReceived(GnssNavigationMessage event) {
+                execute((listener) -> listener.onGnssNavigationMessageReceived(event));
+            }
+
+            @Override
+            public void onStatusChanged(int status) {
+                execute((listener) -> listener.onStatusChanged(status));
+            }
         }
     }
 
-    /**
-     * Set whether the extra location controller package is currently enabled on the device.
-     *
-     * @removed
-     * @deprecated Use {@link #setExtraLocationControllerPackageEnabled} instead.
-     * @hide
-     */
-    @SystemApi
-    @Deprecated
-    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
-    public void setLocationControllerExtraPackageEnabled(boolean enabled) {
-        try {
-            mService.setExtraLocationControllerPackageEnabled(enabled);
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
+    private class BatchedLocationCallbackManager extends
+            AbstractListenerManager<BatchedLocationCallback> {
+
+        @Nullable
+        private IBatchedLocationCallback mListenerTransport;
+
+        @Override
+        protected boolean registerService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport == null);
+
+            mListenerTransport = new BatchedLocationCallback();
+            return mService.addGnssBatchingCallback(mListenerTransport, mContext.getPackageName());
+        }
+
+        @Override
+        protected void unregisterService() throws RemoteException {
+            Preconditions.checkState(mListenerTransport != null);
+
+            mService.removeGnssBatchingCallback();
+            mListenerTransport = null;
+        }
+
+        private class BatchedLocationCallback extends IBatchedLocationCallback.Stub {
+            @Override
+            public void onLocationBatch(List<Location> locations) {
+                execute((listener) -> listener.onLocationBatch(locations));
+            }
         }
     }
-
-    /**
-     * Set whether the extra location controller package is currently enabled on the device.
-     *
-     * @hide
-     */
-    @SystemApi
-    @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
-    public void setExtraLocationControllerPackageEnabled(boolean enabled) {
-        try {
-            mService.setExtraLocationControllerPackageEnabled(enabled);
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
-     * Returns whether extra location controller package is currently enabled on the device.
-     *
-     * @hide
-     */
-    @SystemApi
-    public boolean isExtraLocationControllerPackageEnabled() {
-        try {
-            return mService.isExtraLocationControllerPackageEnabled();
-        } catch (RemoteException e) {
-            e.rethrowFromSystemServer();
-            return false;
-        }
-    }
-
 }
diff --git a/location/java/android/location/LocationProvider.java b/location/java/android/location/LocationProvider.java
index b69a9d7..52a03b6 100644
--- a/location/java/android/location/LocationProvider.java
+++ b/location/java/android/location/LocationProvider.java
@@ -53,28 +53,10 @@
     @Deprecated
     public static final int AVAILABLE = 2;
 
-    /**
-     * A regular expression matching characters that may not appear
-     * in the name of a LocationProvider
-     * @hide
-     */
-    public static final String BAD_CHARS_REGEX = "[^a-zA-Z0-9]";
-
     private final String mName;
     private final ProviderProperties mProperties;
 
-    /**
-     * Constructs a LocationProvider with the given name.   Provider names must
-     * consist only of the characters [a-zA-Z0-9].
-     *
-     * @throws IllegalArgumentException if name contains an illegal character
-     *
-     * @hide
-     */
-    public LocationProvider(String name, ProviderProperties properties) {
-        if (name.matches(BAD_CHARS_REGEX)) {
-            throw new IllegalArgumentException("provider name contains illegal character: " + name);
-        }
+    LocationProvider(String name, ProviderProperties properties) {
         mName = name;
         mProperties = properties;
     }
diff --git a/location/lib/Android.bp b/location/lib/Android.bp
index b36aa03..fe0f669 100644
--- a/location/lib/Android.bp
+++ b/location/lib/Android.bp
@@ -16,12 +16,11 @@
 
 java_sdk_library {
     name: "com.android.location.provider",
-    srcs: [
-        "java/**/*.java",
-        ":framework-all-sources",
-    ],
+    srcs: ["java/**/*.java"],
+    api_srcs: [":framework-all-sources"],
     libs: [
         "androidx.annotation_annotation",
+        "framework-all",
     ],
     api_packages: ["com.android.location.provider"],
 }
diff --git a/media/Android.bp b/media/Android.bp
index a59b3e7..2f75e44 100644
--- a/media/Android.bp
+++ b/media/Android.bp
@@ -63,26 +63,6 @@
     path: "apex/java",
 }
 
-filegroup {
-    name: "mediaplayer2-srcs",
-    srcs: [
-        "apex/java/android/media/CloseGuard.java",
-        "apex/java/android/media/DataSourceCallback.java",
-        "apex/java/android/media/DataSourceDesc.java",
-        "apex/java/android/media/UriDataSourceDesc.java",
-        "apex/java/android/media/FileDataSourceDesc.java",
-        "apex/java/android/media/Media2Utils.java",
-        "apex/java/android/media/MediaPlayer2Utils.java",
-        "apex/java/android/media/MediaPlayer2.java",
-        "apex/java/android/media/Media2HTTPService.java",
-        "apex/java/android/media/Media2HTTPConnection.java",
-        "apex/java/android/media/RoutingDelegate.java",
-        "apex/java/android/media/BufferingParams.java",
-        "apex/java/android/media/ProxyDataSourceCallback.java",
-    ],
-    path: "apex/java",
-}
-
 metalava_updatable_media_args = " --error UnhiddenSystemApi " +
     "--hide RequiresPermission " +
     "--hide MissingPermission --hide BroadcastBehavior " +
diff --git a/media/apex/java/android/media/DataSourceDesc.java b/media/apex/java/android/media/DataSourceDesc.java
deleted file mode 100644
index 9a9c74a..0000000
--- a/media/apex/java/android/media/DataSourceDesc.java
+++ /dev/null
@@ -1,384 +0,0 @@
-/*
- * Copyright 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.media;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.Uri;
-import android.os.ParcelFileDescriptor;
-
-import java.net.CookieHandler;
-import java.net.CookieManager;
-import java.net.HttpCookie;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Data source descriptor.
- *
- * Used by {@link MediaPlayer2#setDataSource}, {@link MediaPlayer2#setNextDataSource} and
- * {@link MediaPlayer2#setNextDataSources} to set data source for playback.
- *
- * @hide
- */
-public class DataSourceDesc {
-    // intentionally less than long.MAX_VALUE
-    static final long LONG_MAX = 0x7ffffffffffffffL;
-
-    // keep consistent with native code
-    public static final long LONG_MAX_TIME_MS = LONG_MAX / 1000;
-    /**
-     * @hide
-     */
-    public static final long LONG_MAX_TIME_US = LONG_MAX_TIME_MS * 1000;
-
-    public static final long POSITION_UNKNOWN = LONG_MAX_TIME_MS;
-
-    private String mMediaId;
-    private long mStartPositionMs = 0;
-    private long mEndPositionMs = POSITION_UNKNOWN;
-
-    DataSourceDesc(String mediaId, long startPositionMs, long endPositionMs) {
-        mMediaId = mediaId;
-        mStartPositionMs = startPositionMs;
-        mEndPositionMs = endPositionMs;
-    }
-
-    /**
-     * Releases the resources held by this {@code DataSourceDesc} object.
-     */
-    void close() {
-    }
-
-    // Have to declare protected for finalize() since it is protected
-    // in the base class Object.
-    @Override
-    protected void finalize() throws Throwable {
-        close();
-    }
-
-    /**
-     * Return the media Id of data source.
-     * @return the media Id of data source
-     */
-    public @Nullable String getMediaId() {
-        return mMediaId;
-    }
-
-    /**
-     * Return the position in milliseconds at which the playback will start.
-     * @return the position in milliseconds at which the playback will start
-     */
-    public long getStartPosition() {
-        return mStartPositionMs;
-    }
-
-    /**
-     * Return the position in milliseconds at which the playback will end.
-     * {@link #POSITION_UNKNOWN} means ending at the end of source content.
-     * @return the position in milliseconds at which the playback will end
-     */
-    public long getEndPosition() {
-        return mEndPositionMs;
-    }
-
-    @Override
-    public String toString() {
-        final StringBuilder sb = new StringBuilder("DataSourceDesc{");
-        sb.append("mMediaId=").append(mMediaId);
-        sb.append(", mStartPositionMs=").append(mStartPositionMs);
-        sb.append(", mEndPositionMs=").append(mEndPositionMs);
-        sb.append('}');
-        return sb.toString();
-    }
-
-    /**
-     * Builder for {@link DataSourceDesc}.
-     * <p>
-     * Here is an example where <code>Builder</code> is used to define the
-     * {@link DataSourceDesc} to be used by a {@link MediaPlayer2} instance:
-     *
-     * <pre class="prettyprint">
-     * DataSourceDesc newDSD = new DataSourceDesc.Builder()
-     *         .setDataSource(context, uri, headers, cookies)
-     *         .setStartPosition(1000)
-     *         .setEndPosition(15000)
-     *         .build();
-     * mediaplayer2.setDataSourceDesc(newDSD);
-     * </pre>
-     */
-    public static final class Builder {
-        private static final int SOURCE_TYPE_UNKNOWN = 0;
-        private static final int SOURCE_TYPE_URI = 1;
-        private static final int SOURCE_TYPE_FILE = 2;
-
-        private int mSourceType = SOURCE_TYPE_UNKNOWN;
-        private String mMediaId;
-        private long mStartPositionMs = 0;
-        private long mEndPositionMs = POSITION_UNKNOWN;
-
-        // For UriDataSourceDesc
-        private Uri mUri;
-        private Map<String, String> mHeader;
-        private List<HttpCookie> mCookies;
-
-        // For FileDataSourceDesc
-        private ParcelFileDescriptor mPFD;
-        private long mOffset = 0;
-        private long mLength = FileDataSourceDesc.FD_LENGTH_UNKNOWN;
-
-        /**
-         * Constructs a new BuilderBase with the defaults.
-         */
-        public Builder() {
-        }
-
-        /**
-         * Constructs a new BuilderBase from a given {@link DataSourceDesc} instance
-         * @param dsd the {@link DataSourceDesc} object whose data will be reused
-         * in the new BuilderBase.
-         */
-        public Builder(@Nullable DataSourceDesc dsd) {
-            if (dsd == null) {
-                return;
-            }
-            mMediaId = dsd.mMediaId;
-            mStartPositionMs = dsd.mStartPositionMs;
-            mEndPositionMs = dsd.mEndPositionMs;
-            if (dsd instanceof FileDataSourceDesc) {
-                mSourceType = SOURCE_TYPE_FILE;
-                mPFD = ((FileDataSourceDesc) dsd).getParcelFileDescriptor();
-                mOffset = ((FileDataSourceDesc) dsd).getOffset();
-                mLength = ((FileDataSourceDesc) dsd).getLength();
-            } else if (dsd instanceof UriDataSourceDesc) {
-                mSourceType = SOURCE_TYPE_URI;
-                mUri = ((UriDataSourceDesc) dsd).getUri();
-                mHeader = ((UriDataSourceDesc) dsd).getHeaders();
-                mCookies = ((UriDataSourceDesc) dsd).getCookies();
-            } else {
-                throw new IllegalStateException("Unknown source type:" + mSourceType);
-            }
-        }
-
-        /**
-         * Sets all fields that have been set in the {@link DataSourceDesc} object.
-         * <code>IllegalStateException</code> will be thrown if there is conflict between fields.
-         *
-         * @return {@link DataSourceDesc}
-         */
-        @NonNull
-        public DataSourceDesc build() {
-            if (mSourceType == SOURCE_TYPE_UNKNOWN) {
-                throw new IllegalStateException("Source is not set.");
-            }
-            if (mStartPositionMs > mEndPositionMs) {
-                throw new IllegalStateException("Illegal start/end position: "
-                    + mStartPositionMs + " : " + mEndPositionMs);
-            }
-
-            DataSourceDesc desc;
-            if (mSourceType == SOURCE_TYPE_FILE) {
-                desc = new FileDataSourceDesc(
-                        mMediaId, mStartPositionMs, mEndPositionMs, mPFD, mOffset, mLength);
-            } else if (mSourceType == SOURCE_TYPE_URI) {
-                desc = new UriDataSourceDesc(
-                        mMediaId, mStartPositionMs, mEndPositionMs, mUri, mHeader, mCookies);
-            } else {
-                throw new IllegalStateException("Unknown source type:" + mSourceType);
-            }
-            return desc;
-        }
-
-        /**
-         * Sets the media Id of this data source.
-         *
-         * @param mediaId the media Id of this data source
-         * @return the same Builder instance.
-         */
-        @NonNull
-        public Builder setMediaId(@Nullable String mediaId) {
-            mMediaId = mediaId;
-            return this;
-        }
-
-        /**
-         * Sets the start position in milliseconds at which the playback will start.
-         * Any negative number is treated as 0.
-         *
-         * @param position the start position in milliseconds at which the playback will start
-         * @return the same Builder instance.
-         *
-         */
-        @NonNull
-        public Builder setStartPosition(long position) {
-            if (position < 0) {
-                position = 0;
-            }
-            mStartPositionMs = position;
-            return this;
-        }
-
-        /**
-         * Sets the end position in milliseconds at which the playback will end.
-         * Any negative number is treated as maximum duration {@link #LONG_MAX_TIME_MS}
-         * of the data source
-         *
-         * @param position the end position in milliseconds at which the playback will end
-         * @return the same Builder instance.
-         */
-        @NonNull
-        public Builder setEndPosition(long position) {
-            if (position < 0) {
-                position = LONG_MAX_TIME_MS;
-            }
-            mEndPositionMs = position;
-            return this;
-        }
-
-        /**
-         * Sets the data source as a content Uri.
-         *
-         * @param uri the Content URI of the data you want to play
-         * @return the same Builder instance.
-         * @throws NullPointerException if context or uri is null.
-         */
-        @NonNull
-        public Builder setDataSource(@NonNull Uri uri) {
-            setSourceType(SOURCE_TYPE_URI);
-            Media2Utils.checkArgument(uri != null, "uri cannot be null");
-            mUri = uri;
-            return this;
-        }
-
-        /**
-         * Sets the data source as a content Uri.
-         *
-         * To provide cookies for the subsequent HTTP requests, you can install your own default
-         * cookie handler and use other variants of setDataSource APIs instead. Alternatively, you
-         * can use this API to pass the cookies as a list of HttpCookie. If the app has not
-         * installed a CookieHandler already, {@link MediaPlayer2} will create a CookieManager
-         * and populates its CookieStore with the provided cookies when this data source is passed
-         * to {@link MediaPlayer2}. If the app has installed its own handler already, the handler
-         * is required to be of CookieManager type such that {@link MediaPlayer2} can update the
-         * manager’s CookieStore.
-         *
-         *  <p><strong>Note</strong> that the cross domain redirection is allowed by default,
-         * but that can be changed with key/value pairs through the headers parameter with
-         * "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value to
-         * disallow or allow cross domain redirection.
-         *
-         * @param uri the Content URI of the data you want to play
-         * @param headers the headers to be sent together with the request for the data
-         *                The headers must not include cookies. Instead, use the cookies param.
-         * @param cookies the cookies to be sent together with the request
-         * @return the same Builder instance.
-         * @throws NullPointerException if context or uri is null.
-         * @throws IllegalArgumentException if the cookie handler is not of CookieManager type
-         *                                  when cookies are provided.
-         */
-        @NonNull
-        public Builder setDataSource(@NonNull Uri uri, @Nullable Map<String, String> headers,
-                @Nullable List<HttpCookie> cookies) {
-            setSourceType(SOURCE_TYPE_URI);
-            Media2Utils.checkArgument(uri != null, "uri cannot be null");
-            if (cookies != null) {
-                CookieHandler cookieHandler = CookieHandler.getDefault();
-                if (cookieHandler != null && !(cookieHandler instanceof CookieManager)) {
-                    throw new IllegalArgumentException(
-                            "The cookie handler has to be of CookieManager type "
-                                    + "when cookies are provided.");
-                }
-            }
-
-            mUri = uri;
-            if (headers != null) {
-                mHeader = new HashMap<String, String>(headers);
-            }
-            if (cookies != null) {
-                mCookies = new ArrayList<HttpCookie>(cookies);
-            }
-            return this;
-        }
-
-        /**
-         * Sets the data source (ParcelFileDescriptor) to use. The ParcelFileDescriptor must be
-         * seekable (N.B. a LocalSocket is not seekable). When the {@link DataSourceDesc}
-         * created by this builder is passed to {@link MediaPlayer2} via
-         * {@link MediaPlayer2#setDataSource},
-         * {@link MediaPlayer2#setNextDataSource} or
-         * {@link MediaPlayer2#setNextDataSources}, MediaPlayer2 will
-         * close the ParcelFileDescriptor.
-         *
-         * @param pfd the ParcelFileDescriptor for the file to play
-         * @return the same Builder instance.
-         * @throws NullPointerException if pfd is null.
-         */
-        @NonNull
-        public Builder setDataSource(@NonNull ParcelFileDescriptor pfd) {
-            setSourceType(SOURCE_TYPE_FILE);
-            Media2Utils.checkArgument(pfd != null, "pfd cannot be null.");
-            mPFD = pfd;
-            return this;
-        }
-
-        /**
-         * Sets the data source (ParcelFileDescriptor) to use. The ParcelFileDescriptor must be
-         * seekable (N.B. a LocalSocket is not seekable). When the {@link DataSourceDesc}
-         * created by this builder is passed to {@link MediaPlayer2} via
-         * {@link MediaPlayer2#setDataSource},
-         * {@link MediaPlayer2#setNextDataSource} or
-         * {@link MediaPlayer2#setNextDataSources}, MediaPlayer2 will
-         * close the ParcelFileDescriptor.
-         *
-         * Any negative number for offset is treated as 0.
-         * Any negative number for length is treated as maximum length of the data source.
-         *
-         * @param pfd the ParcelFileDescriptor for the file to play
-         * @param offset the offset into the file where the data to be played starts, in bytes
-         * @param length the length in bytes of the data to be played
-         * @return the same Builder instance.
-         * @throws NullPointerException if pfd is null.
-         */
-        @NonNull
-        public Builder setDataSource(
-                @NonNull ParcelFileDescriptor pfd, long offset, long length) {
-            setSourceType(SOURCE_TYPE_FILE);
-            if (pfd == null) {
-                throw new NullPointerException("pfd cannot be null.");
-            }
-            if (offset < 0) {
-                offset = 0;
-            }
-            if (length < 0) {
-                length = FileDataSourceDesc.FD_LENGTH_UNKNOWN;
-            }
-            mPFD = pfd;
-            mOffset = offset;
-            mLength = length;
-            return this;
-        }
-
-        private void setSourceType(int type) {
-            if (mSourceType != SOURCE_TYPE_UNKNOWN) {
-                throw new IllegalStateException("Source is already set. type=" + mSourceType);
-            }
-            mSourceType = type;
-        }
-    }
-}
diff --git a/media/apex/java/android/media/FileDataSourceDesc.java b/media/apex/java/android/media/FileDataSourceDesc.java
deleted file mode 100644
index 2aa2cb7..0000000
--- a/media/apex/java/android/media/FileDataSourceDesc.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright 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.media;
-
-import android.annotation.NonNull;
-import android.os.ParcelFileDescriptor;
-import android.util.Log;
-
-import java.io.IOException;
-
-/**
- * Structure of data source descriptor for sources using file descriptor.
- *
- * Used by {@link MediaPlayer2#setDataSource}, {@link MediaPlayer2#setNextDataSource} and
- * {@link MediaPlayer2#setNextDataSources} to set data source for playback.
- *
- * <p>Users should use {@link Builder} to create {@link FileDataSourceDesc}.
- * @hide
- */
-public class FileDataSourceDesc extends DataSourceDesc {
-    private static final String TAG = "FileDataSourceDesc";
-
-    /**
-     * Used when the length of file descriptor is unknown.
-     *
-     * @see #getLength()
-     */
-    public static final long FD_LENGTH_UNKNOWN = LONG_MAX;
-
-    private ParcelFileDescriptor mPFD;
-    private long mOffset = 0;
-    private long mLength = FD_LENGTH_UNKNOWN;
-    private int mCount = 0;
-    private boolean mClosed = false;
-
-    FileDataSourceDesc(String mediaId, long startPositionMs, long endPositionMs,
-            ParcelFileDescriptor pfd, long offset, long length) {
-        super(mediaId, startPositionMs, endPositionMs);
-        mPFD = pfd;
-        mOffset = offset;
-        mLength = length;
-    }
-
-    /**
-     * Releases the resources held by this {@code FileDataSourceDesc} object.
-     */
-    @Override
-    void close() {
-        super.close();
-        decCount();
-    }
-
-    /**
-     * Decrements usage count by {@link MediaPlayer2}.
-     * If this is the last usage, also releases the file descriptor held by this
-     * {@code FileDataSourceDesc} object.
-     */
-    void decCount() {
-        synchronized (this) {
-            --mCount;
-            if (mCount > 0) {
-                return;
-            }
-
-            try {
-                mPFD.close();
-                mClosed = true;
-            } catch (IOException e) {
-                Log.e(TAG, "failed to close pfd: " + e);
-            }
-        }
-    }
-
-    /**
-     * Increments usage count by {@link MediaPlayer2} if PFD has not been closed.
-     */
-    void incCount() {
-        synchronized (this) {
-            if (!mClosed) {
-                ++mCount;
-            }
-        }
-    }
-
-    /**
-     * Return the status of underline ParcelFileDescriptor
-     * @return true if underline ParcelFileDescriptor is closed, false otherwise.
-     */
-    boolean isPFDClosed() {
-        synchronized (this) {
-            return mClosed;
-        }
-    }
-
-    /**
-     * Return the ParcelFileDescriptor of this data source.
-     * @return the ParcelFileDescriptor of this data source
-     */
-    public @NonNull ParcelFileDescriptor getParcelFileDescriptor() {
-        return mPFD;
-    }
-
-    /**
-     * Return the offset associated with the ParcelFileDescriptor of this data source.
-     * It's meaningful only when it has been set by the {@link Builder}.
-     * @return the offset associated with the ParcelFileDescriptor of this data source
-     */
-    public long getOffset() {
-        return mOffset;
-    }
-
-    /**
-     * Return the content length associated with the ParcelFileDescriptor of this data source.
-     * {@link #FD_LENGTH_UNKNOWN} means same as the length of source content.
-     * @return the content length associated with the ParcelFileDescriptor of this data source
-     */
-    public long getLength() {
-        return mLength;
-    }
-}
diff --git a/media/apex/java/android/media/Media2HTTPConnection.java b/media/apex/java/android/media/Media2HTTPConnection.java
deleted file mode 100644
index a369a62..0000000
--- a/media/apex/java/android/media/Media2HTTPConnection.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * Copyright 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 android.media;
-
-import static android.media.MediaPlayer2.MEDIA_ERROR_UNSUPPORTED;
-
-import android.os.StrictMode;
-import android.util.Log;
-
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.CookieHandler;
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.NoRouteToHostException;
-import java.net.ProtocolException;
-import java.net.Proxy;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.net.UnknownServiceException;
-import java.util.HashMap;
-import java.util.Map;
-
-/** @hide */
-public class Media2HTTPConnection {
-    private static final String TAG = "Media2HTTPConnection";
-    private static final boolean VERBOSE = false;
-
-    // connection timeout - 30 sec
-    private static final int CONNECT_TIMEOUT_MS = 30 * 1000;
-
-    private long mCurrentOffset = -1;
-    private URL mURL = null;
-    private Map<String, String> mHeaders = null;
-    private HttpURLConnection mConnection = null;
-    private long mTotalSize = -1;
-    private InputStream mInputStream = null;
-
-    private boolean mAllowCrossDomainRedirect = true;
-    private boolean mAllowCrossProtocolRedirect = true;
-
-    // from com.squareup.okhttp.internal.http
-    private final static int HTTP_TEMP_REDIRECT = 307;
-    private final static int MAX_REDIRECTS = 20;
-
-    public Media2HTTPConnection() {
-        CookieHandler cookieHandler = CookieHandler.getDefault();
-        if (cookieHandler == null) {
-            Log.w(TAG, "Media2HTTPConnection: Unexpected. No CookieHandler found.");
-        }
-    }
-
-    public boolean connect(String uri, String headers) {
-        if (VERBOSE) {
-            Log.d(TAG, "connect: uri=" + uri + ", headers=" + headers);
-        }
-
-        try {
-            disconnect();
-            mAllowCrossDomainRedirect = true;
-            mURL = new URL(uri);
-            mHeaders = convertHeaderStringToMap(headers);
-        } catch (MalformedURLException e) {
-            return false;
-        }
-
-        return true;
-    }
-
-    private boolean parseBoolean(String val) {
-        try {
-            return Long.parseLong(val) != 0;
-        } catch (NumberFormatException e) {
-            return "true".equalsIgnoreCase(val) ||
-                "yes".equalsIgnoreCase(val);
-        }
-    }
-
-    /* returns true iff header is internal */
-    private boolean filterOutInternalHeaders(String key, String val) {
-        if ("android-allow-cross-domain-redirect".equalsIgnoreCase(key)) {
-            mAllowCrossDomainRedirect = parseBoolean(val);
-            // cross-protocol redirects are also controlled by this flag
-            mAllowCrossProtocolRedirect = mAllowCrossDomainRedirect;
-        } else {
-            return false;
-        }
-        return true;
-    }
-
-    private Map<String, String> convertHeaderStringToMap(String headers) {
-        HashMap<String, String> map = new HashMap<String, String>();
-
-        String[] pairs = headers.split("\r\n");
-        for (String pair : pairs) {
-            int colonPos = pair.indexOf(":");
-            if (colonPos >= 0) {
-                String key = pair.substring(0, colonPos);
-                String val = pair.substring(colonPos + 1);
-
-                if (!filterOutInternalHeaders(key, val)) {
-                    map.put(key, val);
-                }
-            }
-        }
-
-        return map;
-    }
-
-    public void disconnect() {
-        teardownConnection();
-        mHeaders = null;
-        mURL = null;
-    }
-
-    private void teardownConnection() {
-        if (mConnection != null) {
-            if (mInputStream != null) {
-                try {
-                    mInputStream.close();
-                } catch (IOException e) {
-                }
-                mInputStream = null;
-            }
-
-            mConnection.disconnect();
-            mConnection = null;
-
-            mCurrentOffset = -1;
-        }
-    }
-
-    private static final boolean isLocalHost(URL url) {
-        if (url == null) {
-            return false;
-        }
-
-        String host = url.getHost();
-
-        if (host == null) {
-            return false;
-        }
-
-        try {
-            if (host.equalsIgnoreCase("localhost")) {
-                return true;
-            }
-            if (InetAddress.getByName(host).isLoopbackAddress()) {
-                return true;
-            }
-        } catch (IllegalArgumentException | UnknownHostException e) {
-        }
-        return false;
-    }
-
-    private void seekTo(long offset) throws IOException {
-        teardownConnection();
-
-        try {
-            int response;
-            int redirectCount = 0;
-
-            URL url = mURL;
-
-            // do not use any proxy for localhost (127.0.0.1)
-            boolean noProxy = isLocalHost(url);
-
-            while (true) {
-                if (noProxy) {
-                    mConnection = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
-                } else {
-                    mConnection = (HttpURLConnection)url.openConnection();
-                }
-                mConnection.setConnectTimeout(CONNECT_TIMEOUT_MS);
-
-                // handle redirects ourselves if we do not allow cross-domain redirect
-                mConnection.setInstanceFollowRedirects(mAllowCrossDomainRedirect);
-
-                if (mHeaders != null) {
-                    for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
-                        mConnection.setRequestProperty(
-                                entry.getKey(), entry.getValue());
-                    }
-                }
-
-                if (offset > 0) {
-                    mConnection.setRequestProperty(
-                            "Range", "bytes=" + offset + "-");
-                }
-
-                response = mConnection.getResponseCode();
-                if (response != HttpURLConnection.HTTP_MULT_CHOICE &&
-                        response != HttpURLConnection.HTTP_MOVED_PERM &&
-                        response != HttpURLConnection.HTTP_MOVED_TEMP &&
-                        response != HttpURLConnection.HTTP_SEE_OTHER &&
-                        response != HTTP_TEMP_REDIRECT) {
-                    // not a redirect, or redirect handled by HttpURLConnection
-                    break;
-                }
-
-                if (++redirectCount > MAX_REDIRECTS) {
-                    throw new NoRouteToHostException("Too many redirects: " + redirectCount);
-                }
-
-                String method = mConnection.getRequestMethod();
-                if (response == HTTP_TEMP_REDIRECT &&
-                        !method.equals("GET") && !method.equals("HEAD")) {
-                    // "If the 307 status code is received in response to a
-                    // request other than GET or HEAD, the user agent MUST NOT
-                    // automatically redirect the request"
-                    throw new NoRouteToHostException("Invalid redirect");
-                }
-                String location = mConnection.getHeaderField("Location");
-                if (location == null) {
-                    throw new NoRouteToHostException("Invalid redirect");
-                }
-                url = new URL(mURL /* TRICKY: don't use url! */, location);
-                if (!url.getProtocol().equals("https") &&
-                        !url.getProtocol().equals("http")) {
-                    throw new NoRouteToHostException("Unsupported protocol redirect");
-                }
-                boolean sameProtocol = mURL.getProtocol().equals(url.getProtocol());
-                if (!mAllowCrossProtocolRedirect && !sameProtocol) {
-                    throw new NoRouteToHostException("Cross-protocol redirects are disallowed");
-                }
-                boolean sameHost = mURL.getHost().equals(url.getHost());
-                if (!mAllowCrossDomainRedirect && !sameHost) {
-                    throw new NoRouteToHostException("Cross-domain redirects are disallowed");
-                }
-
-                if (response != HTTP_TEMP_REDIRECT) {
-                    // update effective URL, unless it is a Temporary Redirect
-                    mURL = url;
-                }
-            }
-
-            if (mAllowCrossDomainRedirect) {
-                // remember the current, potentially redirected URL if redirects
-                // were handled by HttpURLConnection
-                mURL = mConnection.getURL();
-            }
-
-            if (response == HttpURLConnection.HTTP_PARTIAL) {
-                // Partial content, we cannot just use getContentLength
-                // because what we want is not just the length of the range
-                // returned but the size of the full content if available.
-
-                String contentRange =
-                    mConnection.getHeaderField("Content-Range");
-
-                mTotalSize = -1;
-                if (contentRange != null) {
-                    // format is "bytes xxx-yyy/zzz
-                    // where "zzz" is the total number of bytes of the
-                    // content or '*' if unknown.
-
-                    int lastSlashPos = contentRange.lastIndexOf('/');
-                    if (lastSlashPos >= 0) {
-                        String total =
-                            contentRange.substring(lastSlashPos + 1);
-
-                        try {
-                            mTotalSize = Long.parseLong(total);
-                        } catch (NumberFormatException e) {
-                        }
-                    }
-                }
-            } else if (response != HttpURLConnection.HTTP_OK) {
-                throw new IOException();
-            } else {
-                mTotalSize = mConnection.getContentLength();
-            }
-
-            if (offset > 0 && response != HttpURLConnection.HTTP_PARTIAL) {
-                // Some servers simply ignore "Range" requests and serve
-                // data from the start of the content.
-                throw new ProtocolException();
-            }
-
-            mInputStream =
-                new BufferedInputStream(mConnection.getInputStream());
-
-            mCurrentOffset = offset;
-        } catch (IOException e) {
-            mTotalSize = -1;
-            teardownConnection();
-            mCurrentOffset = -1;
-
-            throw e;
-        }
-    }
-
-    public int readAt(long offset, byte[] data, int size) {
-        StrictMode.ThreadPolicy policy =
-            new StrictMode.ThreadPolicy.Builder().permitAll().build();
-
-        StrictMode.setThreadPolicy(policy);
-
-        try {
-            if (offset != mCurrentOffset) {
-                seekTo(offset);
-            }
-
-            int n = mInputStream.read(data, 0, size);
-
-            if (n == -1) {
-                // InputStream signals EOS using a -1 result, our semantics
-                // are to return a 0-length read.
-                n = 0;
-            }
-
-            mCurrentOffset += n;
-
-            if (VERBOSE) {
-                Log.d(TAG, "readAt " + offset + " / " + size + " => " + n);
-            }
-
-            return n;
-        } catch (ProtocolException e) {
-            Log.w(TAG, "readAt " + offset + " / " + size + " => " + e);
-            return MEDIA_ERROR_UNSUPPORTED;
-        } catch (NoRouteToHostException e) {
-            Log.w(TAG, "readAt " + offset + " / " + size + " => " + e);
-            return MEDIA_ERROR_UNSUPPORTED;
-        } catch (UnknownServiceException e) {
-            Log.w(TAG, "readAt " + offset + " / " + size + " => " + e);
-            return MEDIA_ERROR_UNSUPPORTED;
-        } catch (IOException e) {
-            if (VERBOSE) {
-                Log.d(TAG, "readAt " + offset + " / " + size + " => -1");
-            }
-            return -1;
-        } catch (Exception e) {
-            if (VERBOSE) {
-                Log.d(TAG, "unknown exception " + e);
-                Log.d(TAG, "readAt " + offset + " / " + size + " => -1");
-            }
-            return -1;
-        }
-    }
-
-    public long getSize() {
-        if (mConnection == null) {
-            try {
-                seekTo(0);
-            } catch (IOException e) {
-                return -1;
-            }
-        }
-
-        return mTotalSize;
-    }
-
-    public String getMIMEType() {
-        if (mConnection == null) {
-            try {
-                seekTo(0);
-            } catch (IOException e) {
-                return "application/octet-stream";
-            }
-        }
-
-        return mConnection.getContentType();
-    }
-
-    public String getUri() {
-        return mURL.toString();
-    }
-}
diff --git a/media/apex/java/android/media/Media2HTTPService.java b/media/apex/java/android/media/Media2HTTPService.java
deleted file mode 100644
index 0d46ce4..0000000
--- a/media/apex/java/android/media/Media2HTTPService.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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 android.media;
-
-import android.util.Log;
-
-import java.net.HttpCookie;
-import java.util.List;
-
-/** @hide */
-public class Media2HTTPService {
-    private static final String TAG = "Media2HTTPService";
-    private List<HttpCookie> mCookies;
-    private Boolean mCookieStoreInitialized = new Boolean(false);
-
-    public Media2HTTPService(List<HttpCookie> cookies) {
-        mCookies = cookies;
-        Log.v(TAG, "Media2HTTPService(" + this + "): Cookies: " + cookies);
-    }
-
-    public Media2HTTPConnection makeHTTPConnection() {
-
-        synchronized (mCookieStoreInitialized) {
-            Media2Utils.storeCookies(mCookies);
-        }
-
-        return new Media2HTTPConnection();
-    }
-
-    /* package private */ static Media2HTTPService createHTTPService(String path) {
-        return createHTTPService(path, null);
-    }
-
-    // when cookies are provided
-    static Media2HTTPService createHTTPService(String path, List<HttpCookie> cookies) {
-        if (path.startsWith("http://") || path.startsWith("https://")) {
-            return (new Media2HTTPService(cookies));
-        } else if (path.startsWith("widevine://")) {
-            Log.d(TAG, "Widevine classic is no longer supported");
-        }
-
-        return null;
-    }
-}
diff --git a/media/apex/java/android/media/Media2Utils.java b/media/apex/java/android/media/Media2Utils.java
deleted file mode 100644
index a87e967..0000000
--- a/media/apex/java/android/media/Media2Utils.java
+++ /dev/null
@@ -1,78 +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 android.media;
-
-import android.util.Log;
-
-import java.net.CookieHandler;
-import java.net.CookieManager;
-import java.net.CookieStore;
-import java.net.HttpCookie;
-import java.util.List;
-
-/** @hide */
-public class Media2Utils {
-    private static final String TAG = "Media2Utils";
-
-    private Media2Utils() {
-    }
-
-    /**
-     * Ensures that an expression checking an argument is true.
-     *
-     * @param expression the expression to check
-     * @param errorMessage the exception message to use if the check fails; will
-     *     be converted to a string using {@link String#valueOf(Object)}
-     * @throws IllegalArgumentException if {@code expression} is false
-     */
-    public static void checkArgument(boolean expression, String errorMessage) {
-        if (!expression) {
-            throw new IllegalArgumentException(errorMessage);
-        }
-    }
-
-    public static synchronized void storeCookies(List<HttpCookie> cookies) {
-        CookieHandler cookieHandler = CookieHandler.getDefault();
-        if (cookieHandler == null) {
-            cookieHandler = new CookieManager();
-            CookieHandler.setDefault(cookieHandler);
-            Log.v(TAG, "storeCookies: CookieManager created: " + cookieHandler);
-        } else {
-            Log.v(TAG, "storeCookies: CookieHandler (" + cookieHandler + ") exists.");
-        }
-
-        if (cookies != null) {
-            if (cookieHandler instanceof CookieManager) {
-                CookieManager cookieManager = (CookieManager)cookieHandler;
-                CookieStore store = cookieManager.getCookieStore();
-                for (HttpCookie cookie : cookies) {
-                    try {
-                        store.add(null, cookie);
-                    } catch (Exception e) {
-                        Log.v(TAG, "storeCookies: CookieStore.add" + cookie, e);
-                    }
-                }
-            } else {
-                Log.w(TAG, "storeCookies: The installed CookieHandler is not a CookieManager."
-                        + " Can’t add the provided cookies to the cookie store.");
-            }
-        }   // cookies
-
-        Log.v(TAG, "storeCookies: cookieHandler: " + cookieHandler + " Cookies: " + cookies);
-
-    }
-}
diff --git a/media/apex/java/android/media/MediaPlayer2.java b/media/apex/java/android/media/MediaPlayer2.java
deleted file mode 100644
index 614d737..0000000
--- a/media/apex/java/android/media/MediaPlayer2.java
+++ /dev/null
@@ -1,5507 +0,0 @@
-/*
- * Copyright 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 android.media;
-
-import android.annotation.CallbackExecutor;
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.StringDef;
-import android.annotation.TestApi;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.res.AssetFileDescriptor;
-import android.graphics.Rect;
-import android.graphics.SurfaceTexture;
-import android.media.MediaDrm.KeyRequest;
-import android.media.MediaPlayer2.DrmInfo;
-import android.media.MediaPlayer2Proto.PlayerMessage;
-import android.media.MediaPlayer2Proto.Value;
-import android.media.protobuf.InvalidProtocolBufferException;
-import android.net.Uri;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.Looper;
-import android.os.Message;
-import android.os.ParcelFileDescriptor;
-import android.os.PersistableBundle;
-import android.os.PowerManager;
-import android.util.Log;
-import android.util.Pair;
-import android.util.Size;
-import android.view.Surface;
-import android.view.SurfaceHolder;
-
-import com.android.internal.annotations.GuardedBy;
-
-import java.io.ByteArrayOutputStream;
-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.lang.ref.WeakReference;
-import java.net.HttpCookie;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.UUID;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * MediaPlayer2 class can be used to control playback of audio/video files and streams.
- *
- * <p>
- * This API is not generally intended for third party application developers.
- * Use the <a href="{@docRoot}jetpack/androidx.html">AndroidX</a>
- * <a href="{@docRoot}reference/androidx/media2/package-summary.html">Media2 Library</a>
- * for consistent behavior across all devices.
- *
- * <p>Topics covered here are:
- * <ol>
- * <li><a href="#PlayerStates">Player states</a>
- * <li><a href="#InvalidStates">Invalid method calls</a>
- * <li><a href="#Permissions">Permissions</a>
- * <li><a href="#Callbacks">Callbacks</a>
- * </ol>
- *
- *
- * <h3 id="PlayerStates">Player states</h3>
- *
- * <p>The playback control of audio/video files is managed as a state machine.</p>
- * <p><div style="text-align:center;"><img src="../../../images/mediaplayer2_state_diagram.png"
- *         alt="MediaPlayer2 State diagram"
- *         border="0" /></div></p>
- * <p>The MediaPlayer2 object has five states:</p>
- * <ol>
- *     <li><p>{@link #PLAYER_STATE_IDLE}: MediaPlayer2 is in the <strong>Idle</strong>
- *         state after it's created, or after calling {@link #reset()}.</p>
- *
- *         <p>While in this state, you should call
- *         {@link #setDataSource setDataSource}. It is a good
- *         programming practice to register an {@link EventCallback#onCallCompleted onCallCompleted}
- *         <a href="#Callbacks">callback</a> and watch for {@link #CALL_STATUS_BAD_VALUE} and
- *         {@link #CALL_STATUS_ERROR_IO}, which might be caused by <code>setDataSource</code>.
- *         </p>
- *
- *         <p>Calling {@link #prepare()} transfers a MediaPlayer2 object to
- *         the <strong>Prepared</strong> state. Note
- *         that {@link #prepare()} is asynchronous. When the preparation completes,
- *         if you register an {@link EventCallback#onInfo onInfo} <a href="#Callbacks">callback</a>,
- *         the player executes the callback
- *         with {@link #MEDIA_INFO_PREPARED} and transitions to the
- *         <strong>Prepared</strong> state.</p>
- *         </li>
- *
- *     <li>{@link #PLAYER_STATE_PREPARED}: A MediaPlayer object must be in the
- *         <strong>Prepared</strong> state before playback can be started for the first time.
- *         While in this state, you can set player properties
- *         such as audio/sound volume and looping by invoking the corresponding set methods.
- *         Calling {@link #play()} transfers a MediaPlayer2 object to
- *         the <strong>Playing</strong> state.
- *      </li>
- *
- *     <li>{@link #PLAYER_STATE_PLAYING}:
- *         <p>The player plays the data source while in this state.
- *         If you register an {@link EventCallback#onInfo onInfo} <a href="#Callbacks">callback</a>,
- *         the player regularly executes the callback with
- *         {@link #MEDIA_INFO_BUFFERING_UPDATE}.
- *         This allows applications to keep track of the buffering status
- *         while streaming audio/video.</p>
- *
- *         <p> When the playback reaches the end of stream, the behavior depends on whether or
- *         not you've enabled looping by calling {@link #loopCurrent}:</p>
- *         <ul>
- *         <li>If the looping mode was set to <code>false</code>, the player will transfer
- *         to the <strong>Paused</strong> state. If you registered an {@link EventCallback#onInfo
- *         onInfo} <a href="#Callbacks">callback</a>
- *         the player calls the callback with {@link #MEDIA_INFO_DATA_SOURCE_END} and enters
- *         the <strong>Paused</strong> state.
- *         </li>
- *         <li>If the looping mode was set to <code>true</code>,
- *         the MediaPlayer2 object remains in the <strong>Playing</strong> state and replays its
- *         data source from the beginning.</li>
- *         </ul>
- *         </li>
- *
- *     <li>{@link #PLAYER_STATE_PAUSED}: Audio/video playback pauses while in this state.
- *         Call {@link #play()} to resume playback from the position where it paused.</li>
- *
- *     <li>{@link #PLAYER_STATE_ERROR}: <p>In general, playback might fail due to various
- *          reasons such as unsupported audio/video format, poorly interleaved
- *          audio/video, resolution too high, streaming timeout, and others.
- *          In addition, due to programming errors, a playback
- *          control operation might be performed from an <a href="#InvalidStates">invalid state</a>.
- *          In these cases the player transitions to the <strong>Error</strong> state.</p>
- *
- *          <p>If you register an {@link EventCallback#onError onError}}
- *          <a href="#Callbacks">callback</a>,
- *          the callback will be performed when entering the state. When programming errors happen,
- *          such as calling {@link #prepare()} and
- *          {@link #setDataSource} methods
- *          from an <a href="#InvalidStates">invalid state</a>, the callback is called with
- *          {@link #CALL_STATUS_INVALID_OPERATION}. The MediaPlayer2 object enters the
- *          <strong>Error</strong> state whether or not a callback exists. </p>
- *
- *          <p>To recover from an error and reuse a MediaPlayer2 object that is in the <strong>
- *          Error</strong> state,
- *          call {@link #reset()}. The object will return to the <strong>Idle</strong>
- *          state and all state information will be lost.</p>
- *          </li>
- * </ol>
- *
- * <p>You should follow these best practices when coding an app that uses MediaPlayer2:</p>
- *
- * <ul>
- *
- * <li>Use <a href="#Callbacks">callbacks</a> to respond to state changes and errors.</li>
- *
- * <li>When  a MediaPlayer2 object is no longer being used, call {@link #close()} as soon as
- * possible to release the resources used by the internal player engine associated with the
- * MediaPlayer2. Failure to call {@link #close()} may cause subsequent instances of
- * MediaPlayer2 objects to fallback to software implementations or fail altogether.
- * You cannot use MediaPlayer2
- * after you call {@link #close()}. There is no way to bring it back to any other state.</li>
- *
- * <li>The current playback position can be retrieved with a call to
- * {@link #getCurrentPosition()},
- * which is helpful for applications such as a Music player that need to keep track of the playback
- * progress.</li>
- *
- * <li>The playback position can be adjusted with a call to {@link #seekTo}. Although the
- * asynchronous {@link #seekTo} call returns right away, the actual seek operation may take a
- * while to finish, especially for audio/video being streamed. If you register an
- * {@link EventCallback#onCallCompleted onCallCompleted} <a href="#Callbacks">callback</a>,
- * the callback is
- * called When the seek operation completes with {@link #CALL_COMPLETED_SEEK_TO}.</li>
- *
- * <li>You can call {@link #seekTo} from the <strong>Paused</strong> state.
- * In this case, if you are playing a video stream and
- * the requested position is valid  one video frame is displayed.</li>
- *
- * </ul>
- *
- * <h3 id="InvalidStates">Invalid method calls</h3>
- *
- * <p>The only methods you safely call from the <strong>Error</strong> state are
- * {@link #close},
- * {@link #reset},
- * {@link #notifyWhenCommandLabelReached},
- * {@link #clearPendingCommands},
- * {@link #registerEventCallback},
- * {@link #unregisterEventCallback}
- * and {@link #getState}.
- * Any other methods might throw an exception, return meaningless data, or invoke a
- * {@link EventCallback#onCallCompleted onCallCompleted} with an error code.</p>
- *
- * <p>Most methods can be called from any non-Error state. They will either perform their work or
- * silently have no effect. The following table lists the methods that will invoke a
- * {@link EventCallback#onCallCompleted onCallCompleted} with an error code
- * or throw an exception when they are called from the associated invalid states.</p>
- *
- * <table border="0" cellspacing="0" cellpadding="0">
- * <tr><th>Method Name</th>
- * <th>Invalid States</th></tr>
- *
- * <tr><td>setDataSource</td> <td>{Prepared, Paused, Playing}</td></tr>
- * <tr><td>prepare</td> <td>{Prepared, Paused, Playing}</td></tr>
- * <tr><td>play</td> <td>{Idle}</td></tr>
- * <tr><td>pause</td> <td>{Idle}</td></tr>
- * <tr><td>seekTo</td> <td>{Idle}</td></tr>
- * <tr><td>getCurrentPosition</td> <td>{Idle}</td></tr>
- * <tr><td>getDuration</td> <td>{Idle}</td></tr>
- * <tr><td>getBufferedPosition</td> <td>{Idle}</td></tr>
- * <tr><td>getTrackInfo</td> <td>{Idle}</td></tr>
- * <tr><td>getSelectedTrack</td> <td>{Idle}</td></tr>
- * <tr><td>selectTrack</td> <td>{Idle}</td></tr>
- * <tr><td>deselectTrack</td> <td>{Idle}</td></tr>
- * </table>
- *
- * <h3 id="Permissions">Permissions</h3>
- * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
- * when used with network-based content.
- *
- * <h3 id="Callbacks">Callbacks</h3>
- * <p>Many errors do not result in a transition to the  <strong>Error</strong> state.
- * It is good programming practice to register callback listeners using
- * {@link #registerEventCallback}.
- * You can receive a callback at any time and from any state.</p>
- *
- * <p>If it's important for your app to respond to state changes (for instance, to update the
- * controls on a transport UI), you should register an
- * {@link EventCallback#onCallCompleted onCallCompleted} and
- * detect state change commands by testing the <code>what</code> parameter for a callback from one
- * of the state transition methods: {@link #CALL_COMPLETED_PREPARE}, {@link #CALL_COMPLETED_PLAY},
- * and {@link #CALL_COMPLETED_PAUSE}.
- * Then check the <code>status</code> parameter. The value {@link #CALL_STATUS_NO_ERROR} indicates a
- * successful transition. Any other value will be an error. Call {@link #getState()} to
- * determine the current state. </p>
- *
- * @hide
- */
-public class MediaPlayer2 implements AutoCloseable, AudioRouting {
-    static {
-        System.loadLibrary("media2_jni");
-        native_init();
-    }
-
-    private static native void native_init();
-
-    private static final int NEXT_SOURCE_STATE_ERROR = -1;
-    private static final int NEXT_SOURCE_STATE_INIT = 0;
-    private static final int NEXT_SOURCE_STATE_PREPARING = 1;
-    private static final int NEXT_SOURCE_STATE_PREPARED = 2;
-
-    private static final String TAG = "MediaPlayer2";
-
-    private Context mContext;
-
-    private long mNativeContext;  // accessed by native methods
-    private long mNativeSurfaceTexture;  // accessed by native methods
-    private int mListenerContext;  // accessed by native methods
-    private SurfaceHolder mSurfaceHolder;
-    private PowerManager.WakeLock mWakeLock = null;
-    private boolean mScreenOnWhilePlaying;
-    private boolean mStayAwake;
-
-    private final Object mSrcLock = new Object();
-    //--- guarded by |mSrcLock| start
-    private SourceInfo mCurrentSourceInfo;
-    private final Queue<SourceInfo> mNextSourceInfos = new ConcurrentLinkedQueue<>();
-    //--- guarded by |mSrcLock| end
-    private final AtomicLong mSrcIdGenerator = new AtomicLong(0);
-
-    private volatile float mVolume = 1.0f;
-    private Size mVideoSize = new Size(0, 0);
-
-    private static ExecutorService sDrmThreadPool = Executors.newCachedThreadPool();
-
-    // Creating a dummy audio track, used for keeping session id alive
-    private final Object mSessionIdLock = new Object();
-    @GuardedBy("mSessionIdLock")
-    private AudioTrack mDummyAudioTrack;
-
-    private HandlerThread mHandlerThread;
-    private final TaskHandler mTaskHandler;
-    private final Object mTaskLock = new Object();
-    @GuardedBy("mTaskLock")
-    private final List<Task> mPendingTasks = new LinkedList<>();
-    @GuardedBy("mTaskLock")
-    private Task mCurrentTask;
-    private final AtomicLong mTaskIdGenerator = new AtomicLong(0);
-
-    @GuardedBy("mTaskLock")
-    boolean mIsPreviousCommandSeekTo = false;
-    // |mPreviousSeekPos| and |mPreviousSeekMode| are valid only when |mIsPreviousCommandSeekTo|
-    // is true, and they are accessed on |mHandlerThread| only.
-    long mPreviousSeekPos = -1;
-    int mPreviousSeekMode = SEEK_PREVIOUS_SYNC;
-
-    @GuardedBy("this")
-    private boolean mReleased;
-
-    private final CloseGuard mGuard = CloseGuard.get();
-
-    /**
-     * Default constructor.
-     * <p>When done with the MediaPlayer2, you should call {@link #close()},
-     * to free the resources. If not released, too many MediaPlayer2 instances may
-     * result in an exception.</p>
-     */
-    public MediaPlayer2(@NonNull Context context) {
-        mGuard.open("close");
-
-        mContext = context;
-        mHandlerThread = new HandlerThread("MediaPlayer2TaskThread");
-        mHandlerThread.start();
-        Looper looper = mHandlerThread.getLooper();
-        mTaskHandler = new TaskHandler(this, looper);
-        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
-        int sessionId = am.generateAudioSessionId();
-        keepAudioSessionIdAlive(sessionId);
-
-        /* Native setup requires a weak reference to our object.
-         * It's easier to create it here than in C++.
-         */
-        native_setup(sessionId, new WeakReference<MediaPlayer2>(this));
-    }
-
-    private native void native_setup(int sessionId, Object mediaplayer2This);
-
-    /**
-     * Releases the resources held by this {@code MediaPlayer2} object.
-     *
-     * It is considered good practice to call this method when you're
-     * done using the MediaPlayer2. In particular, whenever an Activity
-     * of an application is paused (its onPause() method is called),
-     * or stopped (its onStop() method is called), this method should be
-     * invoked to release the MediaPlayer2 object, unless the application
-     * has a special need to keep the object around. In addition to
-     * unnecessary resources (such as memory and instances of codecs)
-     * being held, failure to call this method immediately if a
-     * MediaPlayer2 object is no longer needed may also lead to
-     * continuous battery consumption for mobile devices, and playback
-     * failure for other applications if no multiple instances of the
-     * same codec are supported on a device. Even if multiple instances
-     * of the same codec are supported, some performance degradation
-     * may be expected when unnecessary multiple instances are used
-     * at the same time.
-     *
-     * {@code close()} may be safely called after a prior {@code close()}.
-     * This class implements the Java {@code AutoCloseable} interface and
-     * may be used with try-with-resources.
-     */
-    // This is a synchronous call.
-    @Override
-    public void close() {
-        synchronized (mGuard) {
-            mGuard.close();
-        }
-        release();
-    }
-
-    private synchronized void release() {
-        if (mReleased) {
-            return;
-        }
-        stayAwake(false);
-        updateSurfaceScreenOn();
-        synchronized (mEventCbLock) {
-            mEventCallbackRecords.clear();
-        }
-        if (mHandlerThread != null) {
-            mHandlerThread.quitSafely();
-            mHandlerThread = null;
-        }
-
-        clearSourceInfos();
-
-        // Modular DRM clean up
-        synchronized (mDrmEventCallbackLock) {
-            mDrmEventCallback = null;
-        }
-        clearMediaDrmObjects();
-
-        native_release();
-
-        synchronized (mSessionIdLock) {
-            mDummyAudioTrack.release();
-        }
-
-        mReleased = true;
-    }
-
-    void clearMediaDrmObjects() {
-        Collection<MediaDrm> drmObjs = mDrmObjs.values();
-        synchronized (mDrmObjs) {
-            for (MediaDrm drmObj : drmObjs) {
-                drmObj.close();
-            }
-            mDrmObjs.clear();
-        }
-    }
-
-    private native void native_release();
-
-    // Have to declare protected for finalize() since it is protected
-    // in the base class Object.
-    @Override
-    protected void finalize() throws Throwable {
-        if (mGuard != null) {
-            mGuard.warnIfOpen();
-        }
-
-        close();
-        native_finalize();
-    }
-
-    private native void native_finalize();
-
-    /**
-     * Resets the MediaPlayer2 to its uninitialized state. After calling
-     * this method, you will have to initialize it again by setting the
-     * data source and calling prepare().
-     */
-    // This is a synchronous call.
-    public void reset() {
-        clearSourceInfos();
-        clearMediaDrmObjects();
-
-        stayAwake(false);
-        native_reset();
-
-        AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
-        int sessionId = am.generateAudioSessionId();
-        keepAudioSessionIdAlive(sessionId);
-
-        // make sure none of the listeners get called anymore
-        if (mTaskHandler != null) {
-            mTaskHandler.removeCallbacksAndMessages(null);
-        }
-
-    }
-
-    private native void native_reset();
-
-    /**
-     * Starts or resumes playback. If playback had previously been paused,
-     * playback will continue from where it was paused. If playback had
-     * reached end of stream and been paused, or never started before,
-     * playback will start at the beginning.
-     *
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object play() {
-        return addTask(new Task(CALL_COMPLETED_PLAY, false) {
-            @Override
-            void process() {
-                stayAwake(true);
-                native_start();
-            }
-        });
-    }
-
-    private native void native_start() throws IllegalStateException;
-
-    /**
-     * Prepares the player for playback, asynchronously.
-     *
-     * After setting the datasource and the display surface, you need to call prepare().
-     *
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object prepare() {
-        return addTask(new Task(CALL_COMPLETED_PREPARE, true) {
-            @Override
-            void process() {
-                native_prepare();
-            }
-        });
-    }
-
-    private native void native_prepare();
-
-    /**
-     * Pauses playback. Call play() to resume.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object pause() {
-        return addTask(new Task(CALL_COMPLETED_PAUSE, false) {
-            @Override
-            void process() {
-                stayAwake(false);
-
-                native_pause();
-            }
-        });
-    }
-
-    private native void native_pause() throws IllegalStateException;
-
-    /**
-     * Tries to play next data source if applicable.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object skipToNext() {
-        return addTask(new Task(CALL_COMPLETED_SKIP_TO_NEXT, false) {
-            @Override
-            void process() {
-                if (getState() == PLAYER_STATE_PLAYING) {
-                    native_pause();
-                }
-                playNextDataSource();
-            }
-        });
-    }
-
-    /**
-     * Gets the current playback position.
-     *
-     * @return the current position in milliseconds
-     */
-    public native long getCurrentPosition();
-
-    /**
-     * Gets the duration of the current data source.
-     * Same as {@link #getDuration(DataSourceDesc)} with
-     * {@code dsd = getCurrentDataSource()}.
-     *
-     * @return the duration in milliseconds, if no duration is available
-     *         (for example, if streaming live content), -1 is returned.
-     * @throws NullPointerException if current data source is null
-     */
-    public long getDuration() {
-        return getDuration(getCurrentDataSource());
-    }
-
-    /**
-     * Gets the duration of the dsd.
-     *
-     * @param dsd the descriptor of data source of which you want to get duration
-     * @return the duration in milliseconds, if no duration is available
-     *         (for example, if streaming live content), -1 is returned.
-     * @throws NullPointerException if dsd is null
-     */
-    public long getDuration(@NonNull DataSourceDesc dsd) {
-        if (dsd == null) {
-            throw new NullPointerException("non-null dsd is expected");
-        }
-        SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo == null) {
-            return -1;
-        }
-
-        return native_getDuration(sourceInfo.mId);
-    }
-
-    private native long native_getDuration(long srcId);
-
-    /**
-     * Gets the buffered media source position of current data source.
-     * Same as {@link #getBufferedPosition(DataSourceDesc)} with
-     * {@code dsd = getCurrentDataSource()}.
-     *
-     * @return the current buffered media source position in milliseconds
-     * @throws NullPointerException if current data source is null
-     */
-    public long getBufferedPosition() {
-        return getBufferedPosition(getCurrentDataSource());
-    }
-
-    /**
-     * Gets the buffered media source position of given dsd.
-     * For example a buffering update of 8000 milliseconds when 5000 milliseconds of the content
-     * has already been played indicates that the next 3000 milliseconds of the
-     * content to play has been buffered.
-     *
-     * @param dsd the descriptor of data source of which you want to get buffered position
-     * @return the current buffered media source position in milliseconds
-     * @throws NullPointerException if dsd is null
-     */
-    public long getBufferedPosition(@NonNull DataSourceDesc dsd) {
-        if (dsd == null) {
-            throw new NullPointerException("non-null dsd is expected");
-        }
-        SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo == null) {
-            return 0;
-        }
-
-        // Use cached buffered percent for now.
-        int bufferedPercentage = sourceInfo.mBufferedPercentage.get();
-
-        long duration = getDuration(dsd);
-        if (duration < 0) {
-            duration = 0;
-        }
-
-        return duration * bufferedPercentage / 100;
-    }
-
-    /**
-     * MediaPlayer2 has not been prepared or just has been reset.
-     * In this state, MediaPlayer2 doesn't fetch data.
-     */
-    public static final int PLAYER_STATE_IDLE = 1001;
-
-    /**
-     * MediaPlayer2 has been just prepared.
-     * In this state, MediaPlayer2 just fetches data from media source,
-     * but doesn't actively render data.
-     */
-    public static final int PLAYER_STATE_PREPARED = 1002;
-
-    /**
-     * MediaPlayer2 is paused.
-     * In this state, MediaPlayer2 has allocated resources to construct playback
-     * pipeline, but it doesn't actively render data.
-     */
-    public static final int PLAYER_STATE_PAUSED = 1003;
-
-    /**
-     * MediaPlayer2 is actively playing back data.
-     */
-    public static final int PLAYER_STATE_PLAYING = 1004;
-
-    /**
-     * MediaPlayer2 has hit some fatal error and cannot continue playback.
-     */
-    public static final int PLAYER_STATE_ERROR = 1005;
-
-    /**
-     * @hide
-     */
-    @IntDef(flag = false, prefix = "MEDIAPLAYER2_STATE", value = {
-        PLAYER_STATE_IDLE,
-        PLAYER_STATE_PREPARED,
-        PLAYER_STATE_PAUSED,
-        PLAYER_STATE_PLAYING,
-        PLAYER_STATE_ERROR })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface MediaPlayer2State {}
-
-    /**
-     * Gets the current player state.
-     *
-     * @return the current player state.
-     */
-    public @MediaPlayer2State int getState() {
-        return native_getState();
-    }
-
-    private native int native_getState();
-
-    /**
-     * Sets the audio attributes for this MediaPlayer2.
-     * See {@link AudioAttributes} for how to build and configure an instance of this class.
-     * You must call this method before {@link #play()} and {@link #pause()} in order
-     * for the audio attributes to become effective thereafter.
-     * @param attributes a non-null set of audio attributes
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setAudioAttributes(@NonNull AudioAttributes attributes) {
-        return addTask(new Task(CALL_COMPLETED_SET_AUDIO_ATTRIBUTES, false) {
-            @Override
-            void process() {
-                if (attributes == null) {
-                    final String msg = "Cannot set AudioAttributes to null";
-                    throw new IllegalArgumentException(msg);
-                }
-                native_setAudioAttributes(attributes);
-            }
-        });
-    }
-
-    // return true if the parameter is set successfully, false otherwise
-    private native boolean native_setAudioAttributes(AudioAttributes audioAttributes);
-
-    /**
-     * Gets the audio attributes for this MediaPlayer2.
-     * @return attributes a set of audio attributes
-     */
-    public @NonNull AudioAttributes getAudioAttributes() {
-        return native_getAudioAttributes();
-    }
-
-    private native AudioAttributes native_getAudioAttributes();
-
-    /**
-     * Sets the data source as described by a DataSourceDesc.
-     * When the data source is of {@link FileDataSourceDesc} type, the {@link ParcelFileDescriptor}
-     * in the {@link FileDataSourceDesc} will be closed by the player.
-     *
-     * @param dsd the descriptor of data source you want to play
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setDataSource(@NonNull DataSourceDesc dsd) {
-        return addTask(new Task(CALL_COMPLETED_SET_DATA_SOURCE, false) {
-            @Override
-            void process() throws IOException {
-                checkDataSourceDesc(dsd);
-                int state = getState();
-                try {
-                    if (state != PLAYER_STATE_ERROR && state != PLAYER_STATE_IDLE) {
-                        throw new IllegalStateException("called in wrong state " + state);
-                    }
-
-                    synchronized (mSrcLock) {
-                        setCurrentSourceInfo_l(new SourceInfo(dsd));
-                        handleDataSource(true /* isCurrent */, dsd, mCurrentSourceInfo.mId);
-                    }
-                } finally {
-                    dsd.close();
-                }
-            }
-
-        });
-    }
-
-    /**
-     * Sets a single data source as described by a DataSourceDesc which will be played
-     * after current data source is finished.
-     * When the data source is of {@link FileDataSourceDesc} type, the {@link ParcelFileDescriptor}
-     * in the {@link FileDataSourceDesc} will be closed by the player.
-     *
-     * @param dsd the descriptor of data source you want to play after current one
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setNextDataSource(@NonNull DataSourceDesc dsd) {
-        return addTask(new Task(CALL_COMPLETED_SET_NEXT_DATA_SOURCE, false) {
-            @Override
-            void process() {
-                checkDataSourceDesc(dsd);
-                synchronized (mSrcLock) {
-                    clearNextSourceInfos_l();
-                    mNextSourceInfos.add(new SourceInfo(dsd));
-                }
-                prepareNextDataSource();
-            }
-        });
-    }
-
-    /**
-     * Sets a list of data sources to be played sequentially after current data source is done.
-     * When the data source is of {@link FileDataSourceDesc} type, the {@link ParcelFileDescriptor}
-     * in the {@link FileDataSourceDesc} will be closed by the player.
-     *
-     * @param dsds the list of data sources you want to play after current one
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setNextDataSources(@NonNull List<DataSourceDesc> dsds) {
-        return addTask(new Task(CALL_COMPLETED_SET_NEXT_DATA_SOURCES, false) {
-            @Override
-            void process() {
-                if (dsds == null || dsds.size() == 0) {
-                    throw new IllegalArgumentException("data source list cannot be null or empty.");
-                }
-                boolean hasError = false;
-                for (DataSourceDesc dsd : dsds) {
-                    if (dsd == null) {
-                        hasError = true;
-                        continue;
-                    }
-                    if (dsd instanceof FileDataSourceDesc) {
-                        FileDataSourceDesc fdsd = (FileDataSourceDesc) dsd;
-                        if (fdsd.isPFDClosed()) {
-                            hasError = true;
-                            continue;
-                        }
-
-                        fdsd.incCount();
-                    }
-                }
-                if (hasError) {
-                    for (DataSourceDesc dsd : dsds) {
-                        if (dsd != null) {
-                            dsd.close();
-                        }
-                    }
-                    throw new IllegalArgumentException("invalid data source list");
-                }
-
-                synchronized (mSrcLock) {
-                    clearNextSourceInfos_l();
-                    for (DataSourceDesc dsd : dsds) {
-                        mNextSourceInfos.add(new SourceInfo(dsd));
-                    }
-                }
-                prepareNextDataSource();
-            }
-        });
-    }
-
-    // throws IllegalArgumentException if dsd is null or underline PFD of dsd has been closed.
-    private void checkDataSourceDesc(DataSourceDesc dsd) {
-        if (dsd == null) {
-            throw new IllegalArgumentException("dsd is expected to be non null");
-        }
-        if (dsd instanceof FileDataSourceDesc) {
-            FileDataSourceDesc fdsd = (FileDataSourceDesc) dsd;
-            if (fdsd.isPFDClosed()) {
-                throw new IllegalArgumentException("the underline FileDescriptor has been closed");
-            }
-            fdsd.incCount();
-        }
-    }
-
-    /**
-     * Removes all data sources pending to be played.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object clearNextDataSources() {
-        return addTask(new Task(CALL_COMPLETED_CLEAR_NEXT_DATA_SOURCES, false) {
-            @Override
-            void process() {
-                synchronized (mSrcLock) {
-                    clearNextSourceInfos_l();
-                }
-            }
-        });
-    }
-
-    /**
-     * Gets the current data source as described by a DataSourceDesc.
-     *
-     * @return the current DataSourceDesc
-     */
-    public @Nullable DataSourceDesc getCurrentDataSource() {
-        synchronized (mSrcLock) {
-            return mCurrentSourceInfo == null ? null : mCurrentSourceInfo.mDSD;
-        }
-    }
-
-    private void handleDataSource(boolean isCurrent, @NonNull DataSourceDesc dsd, long srcId)
-            throws IOException {
-        Media2Utils.checkArgument(dsd != null, "the DataSourceDesc cannot be null");
-
-        if (dsd instanceof FileDataSourceDesc) {
-            FileDataSourceDesc fileDSD = (FileDataSourceDesc) dsd;
-            ParcelFileDescriptor pfd = fileDSD.getParcelFileDescriptor();
-            if (pfd.getStatSize() == -1) {
-                // Underlying pipeline doesn't understand '-1' size. Create a wrapper for
-                // translation.
-                // TODO: Make native code handle '-1' size.
-                handleDataSource(isCurrent,
-                        srcId,
-                        new ProxyDataSourceCallback(pfd),
-                        fileDSD.getStartPosition(),
-                        fileDSD.getEndPosition());
-            } else {
-                handleDataSource(isCurrent,
-                        srcId,
-                        pfd,
-                        fileDSD.getOffset(),
-                        fileDSD.getLength(),
-                        fileDSD.getStartPosition(),
-                        fileDSD.getEndPosition());
-            }
-        } else if (dsd instanceof UriDataSourceDesc) {
-            UriDataSourceDesc uriDSD = (UriDataSourceDesc) dsd;
-            handleDataSource(isCurrent,
-                             srcId,
-                             mContext,
-                             uriDSD.getUri(),
-                             uriDSD.getHeaders(),
-                             uriDSD.getCookies(),
-                             uriDSD.getStartPosition(),
-                             uriDSD.getEndPosition());
-        } else {
-            throw new IllegalArgumentException("Unsupported DataSourceDesc. " + dsd.toString());
-        }
-    }
-
-    /**
-     * To provide cookies for the subsequent HTTP requests, you can install your own default cookie
-     * handler and use other variants of setDataSource APIs instead. Alternatively, you can use
-     * this API to pass the cookies as a list of HttpCookie. If the app has not installed
-     * a CookieHandler already, this API creates a CookieManager and populates its CookieStore with
-     * the provided cookies. If the app has installed its own handler already, this API requires the
-     * handler to be of CookieManager type such that the API can update the manager’s CookieStore.
-     *
-     * <p><strong>Note</strong> that the cross domain redirection is allowed by default,
-     * but that can be changed with key/value pairs through the headers parameter with
-     * "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value to
-     * disallow or allow cross domain redirection.
-     *
-     * @throws IllegalArgumentException if cookies are provided and the installed handler is not
-     *                                  a CookieManager
-     * @throws IllegalStateException    if it is called in an invalid state
-     * @throws NullPointerException     if context or uri is null
-     * @throws IOException              if uri has a file scheme and an I/O error occurs
-     */
-    private void handleDataSource(
-            boolean isCurrent, long srcId,
-            @NonNull Context context, @NonNull Uri uri,
-            @Nullable Map<String, String> headers, @Nullable List<HttpCookie> cookies,
-            long startPos, long endPos)
-            throws IOException {
-        // The context and URI usually belong to the calling user. Get a resolver for that user.
-        final ContentResolver resolver = context.getContentResolver();
-        final String scheme = uri.getScheme();
-        if (ContentResolver.SCHEME_FILE.equals(scheme)) {
-            handleDataSource(isCurrent, srcId, uri.getPath(), null, null, startPos, endPos);
-            return;
-        }
-
-        final int ringToneType = RingtoneManager.getDefaultType(uri);
-        try {
-            AssetFileDescriptor afd;
-            // Try requested Uri locally first
-            if (ContentResolver.SCHEME_CONTENT.equals(scheme) && ringToneType != -1) {
-                afd = RingtoneManager.openDefaultRingtoneUri(context, uri);
-                if (attemptDataSource(isCurrent, srcId, afd, startPos, endPos)) {
-                    return;
-                }
-                final Uri actualUri = RingtoneManager.getActualDefaultRingtoneUri(
-                        context, ringToneType);
-                afd = resolver.openAssetFileDescriptor(actualUri, "r");
-            } else {
-                afd = resolver.openAssetFileDescriptor(uri, "r");
-            }
-            if (attemptDataSource(isCurrent, srcId, afd, startPos, endPos)) {
-                return;
-            }
-        } catch (NullPointerException | SecurityException | IOException ex) {
-            Log.w(TAG, "Couldn't open " + uri == null ? "null uri" : uri.toSafeString(), ex);
-            // Fallback to media server
-        }
-        handleDataSource(isCurrent, srcId, uri.toString(), headers, cookies, startPos, endPos);
-    }
-
-    private boolean attemptDataSource(boolean isCurrent, long srcId, AssetFileDescriptor afd,
-            long startPos, long endPos) throws IOException {
-        try {
-            if (afd.getDeclaredLength() < 0) {
-                handleDataSource(isCurrent,
-                        srcId,
-                        ParcelFileDescriptor.dup(afd.getFileDescriptor()),
-                        0,
-                        DataSourceDesc.LONG_MAX,
-                        startPos,
-                        endPos);
-            } else {
-                handleDataSource(isCurrent,
-                        srcId,
-                        ParcelFileDescriptor.dup(afd.getFileDescriptor()),
-                        afd.getStartOffset(),
-                        afd.getDeclaredLength(),
-                        startPos,
-                        endPos);
-            }
-            return true;
-        } catch (NullPointerException | SecurityException | IOException ex) {
-            Log.w(TAG, "Couldn't open srcId:" + srcId + ": " + ex);
-            return false;
-        } finally {
-            if (afd != null) {
-                afd.close();
-            }
-        }
-    }
-
-    private void handleDataSource(
-            boolean isCurrent, long srcId,
-            String path, Map<String, String> headers, List<HttpCookie> cookies,
-            long startPos, long endPos)
-            throws IOException {
-        String[] keys = null;
-        String[] values = null;
-
-        if (headers != null) {
-            keys = new String[headers.size()];
-            values = new String[headers.size()];
-
-            int i = 0;
-            for (Map.Entry<String, String> entry: headers.entrySet()) {
-                keys[i] = entry.getKey();
-                values[i] = entry.getValue();
-                ++i;
-            }
-        }
-        handleDataSource(isCurrent, srcId, path, keys, values, cookies, startPos, endPos);
-    }
-
-    private void handleDataSource(boolean isCurrent, long srcId,
-            String path, String[] keys, String[] values, List<HttpCookie> cookies,
-            long startPos, long endPos)
-            throws IOException {
-        final Uri uri = Uri.parse(path);
-        final String scheme = uri.getScheme();
-        if ("file".equals(scheme)) {
-            path = uri.getPath();
-        } else if (scheme != null) {
-            // handle non-file sources
-            Media2Utils.storeCookies(cookies);
-            nativeHandleDataSourceUrl(
-                    isCurrent,
-                    srcId,
-                    Media2HTTPService.createHTTPService(path),
-                    path,
-                    keys,
-                    values,
-                    startPos,
-                    endPos);
-            return;
-        }
-
-        final File file = new File(path);
-        if (file.exists()) {
-            FileInputStream is = new FileInputStream(file);
-            FileDescriptor fd = is.getFD();
-            handleDataSource(isCurrent, srcId, ParcelFileDescriptor.dup(fd),
-                    0, DataSourceDesc.LONG_MAX, startPos, endPos);
-            is.close();
-        } else {
-            throw new IOException("handleDataSource failed.");
-        }
-    }
-
-    private native void nativeHandleDataSourceUrl(
-            boolean isCurrent, long srcId,
-            Media2HTTPService httpService, String path, String[] keys, String[] values,
-            long startPos, long endPos)
-            throws IOException;
-
-    /**
-     * Sets the data source (FileDescriptor) to use. The FileDescriptor must be
-     * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
-     * to close the file descriptor. It is safe to do so as soon as this call returns.
-     *
-     * @throws IllegalStateException if it is called in an invalid state
-     * @throws IllegalArgumentException if fd is not a valid FileDescriptor
-     * @throws IOException if fd can not be read
-     */
-    private void handleDataSource(
-            boolean isCurrent, long srcId,
-            ParcelFileDescriptor pfd, long offset, long length,
-            long startPos, long endPos) throws IOException {
-        nativeHandleDataSourceFD(isCurrent, srcId, pfd.getFileDescriptor(), offset, length,
-                startPos, endPos);
-    }
-
-    private native void nativeHandleDataSourceFD(boolean isCurrent, long srcId,
-            FileDescriptor fd, long offset, long length,
-            long startPos, long endPos) throws IOException;
-
-    /**
-     * @throws IllegalStateException if it is called in an invalid state
-     * @throws IllegalArgumentException if dataSource is not a valid DataSourceCallback
-     */
-    private void handleDataSource(boolean isCurrent, long srcId, DataSourceCallback dataSource,
-            long startPos, long endPos) {
-        nativeHandleDataSourceCallback(isCurrent, srcId, dataSource, startPos, endPos);
-    }
-
-    private native void nativeHandleDataSourceCallback(
-            boolean isCurrent, long srcId, DataSourceCallback dataSource,
-            long startPos, long endPos);
-
-    // return true if there is a next data source, false otherwise.
-    // This function should be always called on |mHandlerThread|.
-    private boolean prepareNextDataSource() {
-        HandlerThread handlerThread = mHandlerThread;
-        if (handlerThread != null && Looper.myLooper() != handlerThread.getLooper()) {
-            Log.e(TAG, "prepareNextDataSource: called on wrong looper");
-        }
-
-        boolean hasNextDSD;
-        int state = getState();
-        synchronized (mSrcLock) {
-            hasNextDSD = !mNextSourceInfos.isEmpty();
-            if (state == PLAYER_STATE_ERROR || state == PLAYER_STATE_IDLE) {
-                // Current source has not been prepared yet.
-                return hasNextDSD;
-            }
-
-            SourceInfo nextSource = mNextSourceInfos.peek();
-            if (!hasNextDSD || nextSource.mStateAsNextSource != NEXT_SOURCE_STATE_INIT) {
-                // There is no next source or it's in preparing or prepared state.
-                return hasNextDSD;
-            }
-
-            try {
-                nextSource.mStateAsNextSource = NEXT_SOURCE_STATE_PREPARING;
-                handleDataSource(false /* isCurrent */, nextSource.mDSD, nextSource.mId);
-            } catch (Exception e) {
-                Message msg = mTaskHandler.obtainMessage(
-                        MEDIA_ERROR, MEDIA_ERROR_IO, MEDIA_ERROR_UNKNOWN, null);
-                mTaskHandler.handleMessage(msg, nextSource.mId);
-
-                SourceInfo nextSourceInfo = mNextSourceInfos.poll();
-                if (nextSource != null) {
-                    nextSourceInfo.close();
-                }
-                return prepareNextDataSource();
-            }
-        }
-        return hasNextDSD;
-    }
-
-    // This function should be always called on |mHandlerThread|.
-    private void playNextDataSource() {
-        HandlerThread handlerThread = mHandlerThread;
-        if (handlerThread != null && Looper.myLooper() != handlerThread.getLooper()) {
-            Log.e(TAG, "playNextDataSource: called on wrong looper");
-        }
-
-        boolean hasNextDSD = false;
-        synchronized (mSrcLock) {
-            if (!mNextSourceInfos.isEmpty()) {
-                hasNextDSD = true;
-                SourceInfo nextSourceInfo = mNextSourceInfos.peek();
-                if (nextSourceInfo.mStateAsNextSource == NEXT_SOURCE_STATE_PREPARED) {
-                    // Switch to next source only when it has been prepared.
-                    setCurrentSourceInfo_l(mNextSourceInfos.poll());
-
-                    long srcId = mCurrentSourceInfo.mId;
-                    try {
-                        nativePlayNextDataSource(srcId);
-                    } catch (Exception e) {
-                        Message msg2 = mTaskHandler.obtainMessage(
-                                MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
-                        mTaskHandler.handleMessage(msg2, srcId);
-                        // Keep |mNextSourcePlayPending|
-                        hasNextDSD = prepareNextDataSource();
-                    }
-                    if (hasNextDSD) {
-                        stayAwake(true);
-
-                        // Now a new current src is playing.
-                        // Wait for MEDIA_INFO_DATA_SOURCE_START to prepare next source.
-                    }
-                } else if (nextSourceInfo.mStateAsNextSource == NEXT_SOURCE_STATE_INIT) {
-                    hasNextDSD = prepareNextDataSource();
-                }
-            }
-        }
-
-        if (!hasNextDSD) {
-            sendEvent(new EventNotifier() {
-                @Override
-                public void notify(EventCallback callback) {
-                    callback.onInfo(
-                            MediaPlayer2.this, null, MEDIA_INFO_DATA_SOURCE_LIST_END, 0);
-                }
-            });
-        }
-    }
-
-    private native void nativePlayNextDataSource(long srcId);
-
-    /**
-     * Configures the player to loop on the current data source.
-     * @param loop true if the current data source is meant to loop.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object loopCurrent(boolean loop) {
-        return addTask(new Task(CALL_COMPLETED_LOOP_CURRENT, false) {
-            @Override
-            void process() {
-                setLooping(loop);
-            }
-        });
-    }
-
-    private native void setLooping(boolean looping);
-
-    /**
-     * Sets the volume of the audio of the media to play, expressed as a linear multiplier
-     * on the audio samples.
-     * Note that this volume is specific to the player, and is separate from stream volume
-     * used across the platform.<br>
-     * A value of 0.0f indicates muting, a value of 1.0f is the nominal unattenuated and unamplified
-     * gain. See {@link #getMaxPlayerVolume()} for the volume range supported by this player.
-     * @param volume a value between 0.0f and {@link #getMaxPlayerVolume()}.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setPlayerVolume(float volume) {
-        return addTask(new Task(CALL_COMPLETED_SET_PLAYER_VOLUME, false) {
-            @Override
-            void process() {
-                mVolume = volume;
-                native_setVolume(volume);
-            }
-        });
-    }
-
-    private native void native_setVolume(float volume);
-
-    /**
-     * Returns the current volume of this player.
-     * Note that it does not take into account the associated stream volume.
-     * @return the player volume.
-     */
-    public float getPlayerVolume() {
-        return mVolume;
-    }
-
-    /**
-     * @return the maximum volume that can be used in {@link #setPlayerVolume(float)}.
-     */
-    public float getMaxPlayerVolume() {
-        return 1.0f;
-    }
-
-    /**
-     * Insert a task in the command queue to help the client to identify whether a batch
-     * of commands has been finished. When this command is processed, a notification
-     * {@link EventCallback#onCommandLabelReached onCommandLabelReached} will be fired with the
-     * given {@code label}.
-     *
-     * @see EventCallback#onCommandLabelReached
-     *
-     * @param label An application specific Object used to help to identify the completeness
-     * of a batch of commands.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object notifyWhenCommandLabelReached(@NonNull Object label) {
-        return addTask(new Task(CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED, false) {
-            @Override
-            void process() {
-                sendEvent(new EventNotifier() {
-                    @Override
-                    public void notify(EventCallback callback) {
-                        callback.onCommandLabelReached(
-                                MediaPlayer2.this, label);
-                    }
-                });
-            }
-        });
-    }
-
-    /**
-     * Sets the {@link SurfaceHolder} to use for displaying the video
-     * portion of the media.
-     *
-     * Either a surface holder or surface must be set if a display or video sink
-     * is needed. Not calling this method or {@link #setSurface(Surface)}
-     * when playing back a video will result in only the audio track being played.
-     * A null surface holder or surface will result in only the audio track being
-     * played.
-     *
-     * @param sh the SurfaceHolder to use for video display
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    public @NonNull Object setDisplay(@Nullable SurfaceHolder sh) {
-        return addTask(new Task(CALL_COMPLETED_SET_DISPLAY, false) {
-            @Override
-            void process() {
-                mSurfaceHolder = sh;
-                Surface surface;
-                if (sh != null) {
-                    surface = sh.getSurface();
-                } else {
-                    surface = null;
-                }
-                native_setVideoSurface(surface);
-                updateSurfaceScreenOn();
-            }
-        });
-    }
-
-    /**
-     * Sets the {@link Surface} to be used as the sink for the video portion of
-     * the media.  Setting a
-     * Surface will un-set any Surface or SurfaceHolder that was previously set.
-     * A null surface will result in only the audio track being played.
-     *
-     * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
-     * returned from {@link SurfaceTexture#getTimestamp()} will have an
-     * unspecified zero point.  These timestamps cannot be directly compared
-     * between different media sources, different instances of the same media
-     * source, or multiple runs of the same program.  The timestamp is normally
-     * monotonically increasing and is unaffected by time-of-day adjustments,
-     * but it is reset when the position is set.
-     *
-     * @param surface The {@link Surface} to be used for the video portion of
-     * the media.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setSurface(@Nullable Surface surface) {
-        return addTask(new Task(CALL_COMPLETED_SET_SURFACE, false) {
-            @Override
-            void process() {
-                if (mScreenOnWhilePlaying && surface != null) {
-                    Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
-                }
-                mSurfaceHolder = null;
-                native_setVideoSurface(surface);
-                updateSurfaceScreenOn();
-            }
-        });
-    }
-
-    private native void native_setVideoSurface(Surface surface);
-
-    /**
-     * Set the low-level power management behavior for this MediaPlayer2. This
-     * can be used when the MediaPlayer2 is not playing through a SurfaceHolder
-     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
-     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
-     *
-     * <p>This function has the MediaPlayer2 access the low-level power manager
-     * service to control the device's power usage while playing is occurring.
-     * The parameter is a {@link android.os.PowerManager.WakeLock}.
-     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
-     * permission.
-     * By default, no attempt is made to keep the device awake during playback.
-     *
-     * @param wakeLock the power wake lock used during playback.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     * @see android.os.PowerManager
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setWakeLock(@NonNull PowerManager.WakeLock wakeLock) {
-        return addTask(new Task(CALL_COMPLETED_SET_WAKE_LOCK, false) {
-            @Override
-            void process() {
-                boolean wasHeld = false;
-
-                if (mWakeLock != null) {
-                    if (mWakeLock.isHeld()) {
-                        wasHeld = true;
-                        mWakeLock.release();
-                    }
-                }
-
-                mWakeLock = wakeLock;
-                if (mWakeLock != null) {
-                    mWakeLock.setReferenceCounted(false);
-                    if (wasHeld) {
-                        mWakeLock.acquire();
-                    }
-                }
-            }
-        });
-    }
-
-    /**
-     * Control whether we should use the attached SurfaceHolder to keep the
-     * screen on while video playback is occurring.  This is the preferred
-     * method over {@link #setWakeLock} where possible, since it doesn't
-     * require that the application have permission for low-level wake lock
-     * access.
-     *
-     * @param screenOn Supply true to keep the screen on, false to allow it to turn off.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setScreenOnWhilePlaying(boolean screenOn) {
-        return addTask(new Task(CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING, false) {
-            @Override
-            void process() {
-                if (mScreenOnWhilePlaying != screenOn) {
-                    if (screenOn && mSurfaceHolder == null) {
-                        Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective"
-                                + " without a SurfaceHolder");
-                    }
-                    mScreenOnWhilePlaying = screenOn;
-                    updateSurfaceScreenOn();
-                }
-            }
-        });
-    }
-
-    private void stayAwake(boolean awake) {
-        if (mWakeLock != null) {
-            if (awake && !mWakeLock.isHeld()) {
-                mWakeLock.acquire();
-            } else if (!awake && mWakeLock.isHeld()) {
-                mWakeLock.release();
-            }
-        }
-        mStayAwake = awake;
-        updateSurfaceScreenOn();
-    }
-
-    private void updateSurfaceScreenOn() {
-        if (mSurfaceHolder != null) {
-            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
-        }
-    }
-
-    /**
-     * Cancels a pending command.
-     *
-     * @param token the command to be canceled. This is the returned Object when command is issued.
-     * @return {@code false} if the task could not be cancelled; {@code true} otherwise.
-     * @throws IllegalArgumentException if argument token is null.
-     */
-    // This is a synchronous call.
-    public boolean cancelCommand(@NonNull Object token) {
-        if (token == null) {
-            throw new IllegalArgumentException("command token should not be null");
-        }
-        synchronized (mTaskLock) {
-            return mPendingTasks.remove(token);
-        }
-    }
-
-    /**
-     * Discards all pending commands.
-     */
-    // This is a synchronous call.
-    public void clearPendingCommands() {
-        synchronized (mTaskLock) {
-            mPendingTasks.clear();
-        }
-    }
-
-    //--------------------------------------------------------------------------
-    // Explicit Routing
-    //--------------------
-    private AudioDeviceInfo mPreferredDevice = null;
-
-    /**
-     * Specifies an audio device (via an {@link AudioDeviceInfo} object) to route
-     * the output from this MediaPlayer2.
-     * @param deviceInfo The {@link AudioDeviceInfo} specifying the audio sink or source.
-     *  If deviceInfo is null, default routing is restored.
-     * @return true if succesful, false if the specified {@link AudioDeviceInfo} is non-null and
-     * does not correspond to a valid audio device.
-     */
-    // This is a synchronous call.
-    @Override
-    public boolean setPreferredDevice(@Nullable AudioDeviceInfo deviceInfo) {
-        boolean status = native_setPreferredDevice(deviceInfo);
-        if (status) {
-            synchronized (this) {
-                mPreferredDevice = deviceInfo;
-            }
-        }
-        return status;
-    }
-
-    private native boolean native_setPreferredDevice(AudioDeviceInfo device);
-
-    /**
-     * Returns the selected output specified by {@link #setPreferredDevice}. Note that this
-     * is not guaranteed to correspond to the actual device being used for playback.
-     */
-    @Override
-    public @Nullable AudioDeviceInfo getPreferredDevice() {
-        synchronized (this) {
-            return mPreferredDevice;
-        }
-    }
-
-    /**
-     * Returns an {@link AudioDeviceInfo} identifying the current routing of this MediaPlayer2
-     * Note: The query is only valid if the MediaPlayer2 is currently playing.
-     * If the player is not playing, the returned device can be null or correspond to previously
-     * selected device when the player was last active.
-     */
-    @Override
-    public @Nullable native AudioDeviceInfo getRoutedDevice();
-
-    /**
-     * Adds an {@link AudioRouting.OnRoutingChangedListener} to receive notifications of routing
-     * changes on this MediaPlayer2.
-     * @param listener The {@link AudioRouting.OnRoutingChangedListener} interface to receive
-     * notifications of rerouting events.
-     * @param handler  Specifies the {@link Handler} object for the thread on which to execute
-     * the callback. If <code>null</code>, the handler on the main looper will be used.
-     */
-    // This is a synchronous call.
-    @Override
-    public void addOnRoutingChangedListener(@NonNull AudioRouting.OnRoutingChangedListener listener,
-            @Nullable Handler handler) {
-        if (listener == null) {
-            throw new IllegalArgumentException("addOnRoutingChangedListener: listener is NULL");
-        }
-        RoutingDelegate routingDelegate = new RoutingDelegate(this, listener, handler);
-        native_addDeviceCallback(routingDelegate);
-    }
-
-    private native void native_addDeviceCallback(RoutingDelegate rd);
-
-    /**
-     * Removes an {@link AudioRouting.OnRoutingChangedListener} which has been previously added
-     * to receive rerouting notifications.
-     * @param listener The previously added {@link AudioRouting.OnRoutingChangedListener} interface
-     * to remove.
-     */
-    // This is a synchronous call.
-    @Override
-    public void removeOnRoutingChangedListener(
-            @NonNull AudioRouting.OnRoutingChangedListener listener) {
-        if (listener == null) {
-            throw new IllegalArgumentException("removeOnRoutingChangedListener: listener is NULL");
-        }
-        native_removeDeviceCallback(listener);
-    }
-
-    private native void native_removeDeviceCallback(
-            AudioRouting.OnRoutingChangedListener listener);
-
-    /**
-     * Returns the size of the video.
-     *
-     * @return the size of the video. The width and height of size could be 0 if there is no video,
-     * or the size has not been determined yet.
-     * The {@code EventCallback} can be registered via
-     * {@link #registerEventCallback(Executor, EventCallback)} to provide a
-     * notification {@code EventCallback.onVideoSizeChanged} when the size
-     * is available.
-     */
-    public @NonNull Size getVideoSize() {
-        return mVideoSize;
-    }
-
-    /**
-     * Return Metrics data about the current player.
-     *
-     * @return a {@link PersistableBundle} containing the set of attributes and values
-     * available for the media being handled by this instance of MediaPlayer2
-     * The attributes are descibed in {@link MetricsConstants}.
-     *
-     * Additional vendor-specific fields may also be present in the return value.
-     */
-    public @Nullable PersistableBundle getMetrics() {
-        PersistableBundle bundle = native_getMetrics();
-        return bundle;
-    }
-
-    private native PersistableBundle native_getMetrics();
-
-    /**
-     * Gets the current buffering management params used by the source component.
-     * Calling it only after {@code setDataSource} has been called.
-     * Each type of data source might have different set of default params.
-     *
-     * @return the current buffering management params used by the source component.
-     * @throws IllegalStateException if the internal player engine has not been
-     * initialized, or {@code setDataSource} has not been called.
-     */
-    // TODO: make it public when ready
-    @NonNull
-    native BufferingParams getBufferingParams();
-
-    /**
-     * Sets buffering management params.
-     * The object sets its internal BufferingParams to the input, except that the input is
-     * invalid or not supported.
-     * Call it only after {@code setDataSource} has been called.
-     * The input is a hint to MediaPlayer2.
-     *
-     * @param params the buffering management params.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // TODO: make it public when ready
-    // This is an asynchronous call.
-    @NonNull Object setBufferingParams(@NonNull BufferingParams params) {
-        return addTask(new Task(CALL_COMPLETED_SET_BUFFERING_PARAMS, false) {
-            @Override
-            void process() {
-                Media2Utils.checkArgument(params != null, "the BufferingParams cannot be null");
-                native_setBufferingParams(params);
-            }
-        });
-    }
-
-    private native void native_setBufferingParams(@NonNull BufferingParams params);
-
-    /**
-     * Sets playback rate using {@link PlaybackParams}. The object sets its internal
-     * PlaybackParams to the input. This allows the object to resume at previous speed
-     * when play() is called. Speed of zero is not allowed. Calling it does not change
-     * the object state.
-     *
-     * @param params the playback params.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setPlaybackParams(@NonNull PlaybackParams params) {
-        return addTask(new Task(CALL_COMPLETED_SET_PLAYBACK_PARAMS, false) {
-            @Override
-            void process() {
-                Media2Utils.checkArgument(params != null, "the PlaybackParams cannot be null");
-                native_setPlaybackParams(params);
-            }
-        });
-    }
-
-    private native void native_setPlaybackParams(@NonNull PlaybackParams params);
-
-    /**
-     * Gets the playback params, containing the current playback rate.
-     *
-     * @return the playback params.
-     * @throws IllegalStateException if the internal player engine has not been initialized.
-     */
-    @NonNull
-    public native PlaybackParams getPlaybackParams();
-
-    /**
-     * Sets A/V sync mode.
-     *
-     * @param params the A/V sync params to apply
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setSyncParams(@NonNull SyncParams params) {
-        return addTask(new Task(CALL_COMPLETED_SET_SYNC_PARAMS, false) {
-            @Override
-            void process() {
-                Media2Utils.checkArgument(params != null, "the SyncParams cannot be null");
-                native_setSyncParams(params);
-            }
-        });
-    }
-
-    private native void native_setSyncParams(@NonNull SyncParams params);
-
-    /**
-     * Gets the A/V sync mode.
-     *
-     * @return the A/V sync params
-     * @throws IllegalStateException if the internal player engine has not been initialized.
-     */
-    @NonNull
-    public native SyncParams getSyncParams();
-
-    /**
-     * Moves the media to specified time position.
-     * Same as {@link #seekTo(long, int)} with {@code mode = SEEK_PREVIOUS_SYNC}.
-     *
-     * @param msec the offset in milliseconds from the start to seek to
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object seekTo(long msec) {
-        return seekTo(msec, SEEK_PREVIOUS_SYNC /* mode */);
-    }
-
-    /**
-     * Seek modes used in method seekTo(long, int) to move media position
-     * to a specified location.
-     *
-     * Do not change these mode values without updating their counterparts
-     * in include/media/IMediaSource.h!
-     */
-    /**
-     * This mode is used with {@link #seekTo(long, int)} to move media position to
-     * a sync (or key) frame associated with a data source that is located
-     * right before or at the given time.
-     *
-     * @see #seekTo(long, int)
-     */
-    public static final int SEEK_PREVIOUS_SYNC    = 0x00;
-    /**
-     * This mode is used with {@link #seekTo(long, int)} to move media position to
-     * a sync (or key) frame associated with a data source that is located
-     * right after or at the given time.
-     *
-     * @see #seekTo(long, int)
-     */
-    public static final int SEEK_NEXT_SYNC        = 0x01;
-    /**
-     * This mode is used with {@link #seekTo(long, int)} to move media position to
-     * a sync (or key) frame associated with a data source that is located
-     * closest to (in time) or at the given time.
-     *
-     * @see #seekTo(long, int)
-     */
-    public static final int SEEK_CLOSEST_SYNC     = 0x02;
-    /**
-     * This mode is used with {@link #seekTo(long, int)} to move media position to
-     * a frame (not necessarily a key frame) associated with a data source that
-     * is located closest to or at the given time.
-     *
-     * @see #seekTo(long, int)
-     */
-    public static final int SEEK_CLOSEST          = 0x03;
-
-    /** @hide */
-    @IntDef(flag = false, prefix = "SEEK", value = {
-            SEEK_PREVIOUS_SYNC,
-            SEEK_NEXT_SYNC,
-            SEEK_CLOSEST_SYNC,
-            SEEK_CLOSEST,
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface SeekMode {}
-
-    /**
-     * Moves the media to specified time position by considering the given mode.
-     * <p>
-     * When seekTo is finished, the user will be notified via
-     * {@link EventCallback#onCallCompleted} with {@link #CALL_COMPLETED_SEEK_TO}.
-     * There is at most one active seekTo processed at any time. If there is a to-be-completed
-     * seekTo, new seekTo requests will be queued in such a way that only the last request
-     * is kept. When current seekTo is completed, the queued request will be processed if
-     * that request is different from just-finished seekTo operation, i.e., the requested
-     * position or mode is different.
-     *
-     * @param msec the offset in milliseconds from the start to seek to.
-     * When seeking to the given time position, there is no guarantee that the data source
-     * has a frame located at the position. When this happens, a frame nearby will be rendered.
-     * If msec is negative, time position zero will be used.
-     * If msec is larger than duration, duration will be used.
-     * @param mode the mode indicating where exactly to seek to.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object seekTo(long msec, @SeekMode int mode) {
-        return addTask(new Task(CALL_COMPLETED_SEEK_TO, true) {
-            @Override
-            void process() {
-                if (mode < SEEK_PREVIOUS_SYNC || mode > SEEK_CLOSEST) {
-                    final String msg = "Illegal seek mode: " + mode;
-                    throw new IllegalArgumentException(msg);
-                }
-                // TODO: pass long to native, instead of truncating here.
-                long posMs = msec;
-                if (posMs > Integer.MAX_VALUE) {
-                    Log.w(TAG, "seekTo offset " + posMs + " is too large, cap to "
-                            + Integer.MAX_VALUE);
-                    posMs = Integer.MAX_VALUE;
-                } else if (posMs < Integer.MIN_VALUE) {
-                    Log.w(TAG, "seekTo offset " + posMs + " is too small, cap to "
-                            + Integer.MIN_VALUE);
-                    posMs = Integer.MIN_VALUE;
-                }
-
-                synchronized (mTaskLock) {
-                    if (mIsPreviousCommandSeekTo
-                            && mPreviousSeekPos == posMs
-                            && mPreviousSeekMode == mode) {
-                        throw new CommandSkippedException(
-                                "same as previous seekTo");
-                    }
-                }
-
-                native_seekTo(posMs, mode);
-
-                synchronized (mTaskLock) {
-                    mIsPreviousCommandSeekTo = true;
-                    mPreviousSeekPos = posMs;
-                    mPreviousSeekMode = mode;
-                }
-            }
-        });
-    }
-
-    private native void native_seekTo(long msec, int mode);
-
-    /**
-     * Get current playback position as a {@link MediaTimestamp}.
-     * <p>
-     * The MediaTimestamp represents how the media time correlates to the system time in
-     * a linear fashion using an anchor and a clock rate. During regular playback, the media
-     * time moves fairly constantly (though the anchor frame may be rebased to a current
-     * system time, the linear correlation stays steady). Therefore, this method does not
-     * need to be called often.
-     * <p>
-     * To help users get current playback position, this method always anchors the timestamp
-     * to the current {@link System#nanoTime system time}, so
-     * {@link MediaTimestamp#getAnchorMediaTimeUs} can be used as current playback position.
-     *
-     * @return a MediaTimestamp object if a timestamp is available, or {@code null} if no timestamp
-     *         is available, e.g. because the media player has not been initialized.
-     *
-     * @see MediaTimestamp
-     */
-    @Nullable
-    public MediaTimestamp getTimestamp() {
-        try {
-            // TODO: get the timestamp from native side
-            return new MediaTimestamp(
-                    getCurrentPosition() * 1000L,
-                    System.nanoTime(),
-                    getState() == PLAYER_STATE_PLAYING ? getPlaybackParams().getSpeed() : 0.f);
-        } catch (IllegalStateException e) {
-            return null;
-        }
-    }
-
-    /**
-     * Checks whether the MediaPlayer2 is looping or non-looping.
-     *
-     * @return true if the MediaPlayer2 is currently looping, false otherwise
-     */
-    // This is a synchronous call.
-    public native boolean isLooping();
-
-    /**
-     * Sets the audio session ID.
-     *
-     * @param sessionId the audio session ID.
-     * The audio session ID is a system wide unique identifier for the audio stream played by
-     * this MediaPlayer2 instance.
-     * The primary use of the audio session ID  is to associate audio effects to a particular
-     * instance of MediaPlayer2: if an audio session ID is provided when creating an audio effect,
-     * this effect will be applied only to the audio content of media players within the same
-     * audio session and not to the output mix.
-     * When created, a MediaPlayer2 instance automatically generates its own audio session ID.
-     * However, it is possible to force this player to be part of an already existing audio session
-     * by calling this method.
-     * This method must be called when player is in {@link #PLAYER_STATE_IDLE} or
-     * {@link #PLAYER_STATE_PREPARED} state in order to have sessionId take effect.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setAudioSessionId(int sessionId) {
-        final AudioTrack dummyAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
-                    AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, 2,
-                    AudioTrack.MODE_STATIC, sessionId);
-        return addTask(new Task(CALL_COMPLETED_SET_AUDIO_SESSION_ID, false) {
-            @Override
-            void process() {
-                keepAudioSessionIdAlive(dummyAudioTrack);
-                native_setAudioSessionId(sessionId);
-            }
-        });
-    }
-
-    private native void native_setAudioSessionId(int sessionId);
-
-    /**
-     * Returns the audio session ID.
-     *
-     * @return the audio session ID. {@see #setAudioSessionId(int)}
-     * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer2 was
-     * contructed.
-     */
-    // This is a synchronous call.
-    public native int getAudioSessionId();
-
-    /**
-     * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
-     * effect which can be applied on any sound source that directs a certain amount of its
-     * energy to this effect. This amount is defined by setAuxEffectSendLevel().
-     * See {@link #setAuxEffectSendLevel(float)}.
-     * <p>After creating an auxiliary effect (e.g.
-     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
-     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
-     * to attach the player to the effect.
-     * <p>To detach the effect from the player, call this method with a null effect id.
-     * <p>This method must be called after one of the overloaded <code> setDataSource </code>
-     * methods.
-     * @param effectId system wide unique id of the effect to attach
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object attachAuxEffect(int effectId) {
-        return addTask(new Task(CALL_COMPLETED_ATTACH_AUX_EFFECT, false) {
-            @Override
-            void process() {
-                native_attachAuxEffect(effectId);
-            }
-        });
-    }
-
-    private native void native_attachAuxEffect(int effectId);
-
-    /**
-     * Sets the send level of the player to the attached auxiliary effect.
-     * See {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
-     * <p>By default the send level is 0, so even if an effect is attached to the player
-     * this method must be called for the effect to be applied.
-     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
-     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
-     * so an appropriate conversion from linear UI input x to level is:
-     * x == 0 -> level = 0
-     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
-     * @param level send level scalar
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     */
-    // This is an asynchronous call.
-    public @NonNull Object setAuxEffectSendLevel(float level) {
-        return addTask(new Task(CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL, false) {
-            @Override
-            void process() {
-                native_setAuxEffectSendLevel(level);
-            }
-        });
-    }
-
-    private native void native_setAuxEffectSendLevel(float level);
-
-    private static native void native_stream_event_onTearDown(
-            long nativeCallbackPtr, long userDataPtr);
-    private static native void native_stream_event_onStreamPresentationEnd(
-            long nativeCallbackPtr, long userDataPtr);
-    private static native void native_stream_event_onStreamDataRequest(
-            long jAudioTrackPtr, long nativeCallbackPtr, long userDataPtr);
-
-    /* Do not change these values (starting with INVOKE_ID) without updating
-     * their counterparts in include/media/mediaplayer2.h!
-     */
-    private static final int INVOKE_ID_GET_TRACK_INFO = 1;
-    private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
-    private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
-    private static final int INVOKE_ID_SELECT_TRACK = 4;
-    private static final int INVOKE_ID_DESELECT_TRACK = 5;
-    private static final int INVOKE_ID_GET_SELECTED_TRACK = 7;
-
-    /**
-     * Invoke a generic method on the native player using opaque protocol
-     * buffer message for the request and reply. Both payloads' format is a
-     * convention between the java caller and the native player.
-     *
-     * @param msg PlayerMessage for the extension.
-     *
-     * @return PlayerMessage with the data returned by the
-     * native player.
-     */
-    private PlayerMessage invoke(PlayerMessage msg) {
-        byte[] ret = native_invoke(msg.toByteArray());
-        if (ret == null) {
-            return null;
-        }
-        try {
-            return PlayerMessage.parseFrom(ret);
-        } catch (InvalidProtocolBufferException e) {
-            return null;
-        }
-    }
-
-    private native byte[] native_invoke(byte[] request);
-
-    /**
-     * @hide
-     */
-    @IntDef(flag = false, prefix = "MEDIA_TRACK_TYPE", value = {
-            TrackInfo.MEDIA_TRACK_TYPE_VIDEO,
-            TrackInfo.MEDIA_TRACK_TYPE_AUDIO,
-            TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface TrackType {}
-
-    /**
-     * Class for MediaPlayer2 to return each audio/video/subtitle track's metadata.
-     *
-     * @see MediaPlayer2#getTrackInfo
-     */
-    public static class TrackInfo {
-        /**
-         * Gets the track type.
-         * @return TrackType which indicates if the track is video, audio, timed text.
-         */
-        public int getTrackType() {
-            return mTrackType;
-        }
-
-        /**
-         * Gets the language code of the track.
-         * @return a language code in either way of ISO-639-1 or ISO-639-2.
-         * When the language is unknown or could not be determined,
-         * ISO-639-2 language code, "und", is returned.
-         */
-        public @NonNull String getLanguage() {
-            String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
-            return language == null ? "und" : language;
-        }
-
-        /**
-         * Gets the {@link MediaFormat} of the track.  If the format is
-         * unknown or could not be determined, null is returned.
-         */
-        public @Nullable MediaFormat getFormat() {
-            if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
-                    || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
-                return mFormat;
-            }
-            return null;
-        }
-
-        public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
-        public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
-        public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
-
-        /** @hide */
-        public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
-
-        public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
-        public static final int MEDIA_TRACK_TYPE_METADATA = 5;
-
-        final int mId;
-        final int mTrackType;
-        final MediaFormat mFormat;
-
-        static TrackInfo create(int idx, Iterator<Value> in) {
-            int trackType = in.next().getInt32Value();
-            // TODO: build the full MediaFormat; currently we are using createSubtitleFormat
-            // even for audio/video tracks, meaning we only set the mime and language.
-            String mime = in.next().getStringValue();
-            String language = in.next().getStringValue();
-            MediaFormat format = MediaFormat.createSubtitleFormat(mime, language);
-
-            if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
-                format.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.next().getInt32Value());
-                format.setInteger(MediaFormat.KEY_IS_DEFAULT, in.next().getInt32Value());
-                format.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.next().getInt32Value());
-            }
-            return new TrackInfo(idx, trackType, format);
-        }
-
-        /** @hide */
-        TrackInfo(int id, int type, MediaFormat format) {
-            mId = id;
-            mTrackType = type;
-            mFormat = format;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder out = new StringBuilder(128);
-            out.append(getClass().getName());
-            out.append('{');
-            switch (mTrackType) {
-                case MEDIA_TRACK_TYPE_VIDEO:
-                    out.append("VIDEO");
-                    break;
-                case MEDIA_TRACK_TYPE_AUDIO:
-                    out.append("AUDIO");
-                    break;
-                case MEDIA_TRACK_TYPE_TIMEDTEXT:
-                    out.append("TIMEDTEXT");
-                    break;
-                case MEDIA_TRACK_TYPE_SUBTITLE:
-                    out.append("SUBTITLE");
-                    break;
-                default:
-                    out.append("UNKNOWN");
-                    break;
-            }
-            out.append(", " + mFormat.toString());
-            out.append("}");
-            return out.toString();
-        }
-    };
-
-    /**
-     * Returns a List of track information of current data source.
-     * Same as {@link #getTrackInfo(DataSourceDesc)} with
-     * {@code dsd = getCurrentDataSource()}.
-     *
-     * @return List of track info. The total number of tracks is the array length.
-     * Must be called again if an external timed text source has been added after
-     * addTimedTextSource method is called.
-     * @throws IllegalStateException if it is called in an invalid state.
-     * @throws NullPointerException if current data source is null
-     */
-    public @NonNull List<TrackInfo> getTrackInfo() {
-        return getTrackInfo(getCurrentDataSource());
-    }
-
-    /**
-     * Returns a List of track information.
-     *
-     * @param dsd the descriptor of data source of which you want to get track info
-     * @return List of track info. The total number of tracks is the array length.
-     * Must be called again if an external timed text source has been added after
-     * addTimedTextSource method is called.
-     * @throws IllegalStateException if it is called in an invalid state.
-     * @throws NullPointerException if dsd is null
-     */
-    public @NonNull List<TrackInfo> getTrackInfo(@NonNull DataSourceDesc dsd) {
-        if (dsd == null) {
-            throw new NullPointerException("non-null dsd is expected");
-        }
-        SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo == null) {
-            return new ArrayList<TrackInfo>(0);
-        }
-
-        TrackInfo[] trackInfo = getInbandTrackInfo(sourceInfo);
-        return (trackInfo != null ? Arrays.asList(trackInfo) : new ArrayList<TrackInfo>(0));
-    }
-
-    private TrackInfo[] getInbandTrackInfo(SourceInfo sourceInfo) throws IllegalStateException {
-        PlayerMessage request = PlayerMessage.newBuilder()
-                .addValues(Value.newBuilder().setInt32Value(INVOKE_ID_GET_TRACK_INFO))
-                .addValues(Value.newBuilder().setInt64Value(sourceInfo.mId))
-                .build();
-        PlayerMessage response = invoke(request);
-        if (response == null) {
-            return null;
-        }
-        Iterator<Value> in = response.getValuesList().iterator();
-        int size = in.next().getInt32Value();
-        if (size == 0) {
-            return null;
-        }
-        TrackInfo[] trackInfo = new TrackInfo[size];
-        for (int i = 0; i < size; ++i) {
-            trackInfo[i] = TrackInfo.create(i, in);
-        }
-        return trackInfo;
-    }
-
-    /**
-     * Returns the index of the audio, video, or subtitle track currently selected for playback.
-     * The return value is an index into the array returned by {@link #getTrackInfo}, and can
-     * be used in calls to {@link #selectTrack(TrackInfo)} or {@link #deselectTrack(TrackInfo)}.
-     * Same as {@link #getSelectedTrack(DataSourceDesc, int)} with
-     * {@code dsd = getCurrentDataSource()}.
-     *
-     * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
-     * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
-     * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
-     * @return metadata corresponding to the audio, video, or subtitle track currently selected for
-     * playback; {@code null} is returned when there is no selected track for {@code trackType} or
-     * when {@code trackType} is not one of audio, video, or subtitle.
-     * @throws IllegalStateException if called after {@link #close()}
-     * @throws NullPointerException if current data source is null
-     *
-     * @see #getTrackInfo()
-     * @see #selectTrack(TrackInfo)
-     * @see #deselectTrack(TrackInfo)
-     */
-    @Nullable
-    public TrackInfo getSelectedTrack(@TrackType int trackType) {
-        return getSelectedTrack(getCurrentDataSource(), trackType);
-    }
-
-    /**
-     * Returns the index of the audio, video, or subtitle track currently selected for playback.
-     * The return value is an index into the array returned by {@link #getTrackInfo}, and can
-     * be used in calls to {@link #selectTrack(DataSourceDesc, TrackInfo)} or
-     * {@link #deselectTrack(DataSourceDesc, TrackInfo)}.
-     *
-     * @param dsd the descriptor of data source of which you want to get selected track
-     * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
-     * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
-     * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
-     * @return metadata corresponding to the audio, video, or subtitle track currently selected for
-     * playback; {@code null} is returned when there is no selected track for {@code trackType} or
-     * when {@code trackType} is not one of audio, video, or subtitle.
-     * @throws IllegalStateException if called after {@link #close()}
-     * @throws NullPointerException if dsd is null
-     *
-     * @see #getTrackInfo(DataSourceDesc)
-     * @see #selectTrack(DataSourceDesc, TrackInfo)
-     * @see #deselectTrack(DataSourceDesc, TrackInfo)
-     */
-    @Nullable
-    public TrackInfo getSelectedTrack(@NonNull DataSourceDesc dsd, @TrackType int trackType) {
-        if (dsd == null) {
-            throw new NullPointerException("non-null dsd is expected");
-        }
-        SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo == null) {
-            return null;
-        }
-
-        PlayerMessage request = PlayerMessage.newBuilder()
-                .addValues(Value.newBuilder().setInt32Value(INVOKE_ID_GET_SELECTED_TRACK))
-                .addValues(Value.newBuilder().setInt64Value(sourceInfo.mId))
-                .addValues(Value.newBuilder().setInt32Value(trackType))
-                .build();
-        PlayerMessage response = invoke(request);
-        if (response == null) {
-            return null;
-        }
-        // TODO: return full TrackInfo data from native player instead of index
-        final int idx = response.getValues(0).getInt32Value();
-        final List<TrackInfo> trackInfos = getTrackInfo(dsd);
-        return trackInfos.isEmpty() ? null : trackInfos.get(idx);
-    }
-
-    /**
-     * Selects a track of current data source.
-     * Same as {@link #selectTrack(DataSourceDesc, TrackInfo)} with
-     * {@code dsd = getCurrentDataSource()}.
-     *
-     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
-     * object can be obtained from {@link #getTrackInfo()}.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     *
-     * This is an asynchronous call.
-     *
-     * @see MediaPlayer2#getTrackInfo()
-     */
-    @NonNull
-    public Object selectTrack(@NonNull TrackInfo trackInfo) {
-        return selectTrack(getCurrentDataSource(), trackInfo);
-    }
-
-    /**
-     * Selects a track.
-     * <p>
-     * If a MediaPlayer2 is in invalid state, it throws an IllegalStateException exception.
-     * If a MediaPlayer2 is in <em>Started</em> state, the selected track is presented immediately.
-     * If a MediaPlayer2 is not in Started state, it just marks the track to be played.
-     * </p>
-     * <p>
-     * In any valid state, if it is called multiple times on the same type of track (ie. Video,
-     * Audio, Timed Text), the most recent one will be chosen.
-     * </p>
-     * <p>
-     * The first audio and video tracks are selected by default if available, even though
-     * this method is not called. However, no timed text track will be selected until
-     * this function is called.
-     * </p>
-     * <p>
-     * Currently, only timed text tracks or audio tracks can be selected via this method.
-     * In addition, the support for selecting an audio track at runtime is pretty limited
-     * in that an audio track can only be selected in the <em>Prepared</em> state.
-     * </p>
-     * @param dsd the descriptor of data source of which you want to select track
-     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
-     * object can be obtained from {@link #getTrackInfo()}.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     *
-     * This is an asynchronous call.
-     *
-     * @see MediaPlayer2#getTrackInfo(DataSourceDesc)
-     */
-    @NonNull
-    public Object selectTrack(@NonNull DataSourceDesc dsd, @NonNull TrackInfo trackInfo) {
-        return addTask(new Task(CALL_COMPLETED_SELECT_TRACK, false) {
-            @Override
-            void process() {
-                selectOrDeselectTrack(dsd, trackInfo.mId, true /* select */);
-            }
-        });
-    }
-
-    /**
-     * Deselect a track of current data source.
-     * Same as {@link #deselectTrack(DataSourceDesc, TrackInfo)} with
-     * {@code dsd = getCurrentDataSource()}.
-     *
-     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
-     * object can be obtained from {@link #getTrackInfo()}.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     *
-     * This is an asynchronous call.
-     *
-     * @see MediaPlayer2#getTrackInfo()
-     */
-    @NonNull
-    public Object deselectTrack(@NonNull TrackInfo trackInfo) {
-        return deselectTrack(getCurrentDataSource(), trackInfo);
-    }
-
-    /**
-     * Deselect a track.
-     * <p>
-     * Currently, the track must be a timed text track and no audio or video tracks can be
-     * deselected. If the timed text track identified by index has not been
-     * selected before, it throws an exception.
-     * </p>
-     * @param dsd the descriptor of data source of which you want to deselect track
-     * @param trackInfo metadata corresponding to the track to be selected. A {@code trackInfo}
-     * object can be obtained from {@link #getTrackInfo()}.
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     *
-     * This is an asynchronous call.
-     *
-     * @see MediaPlayer2#getTrackInfo(DataSourceDesc)
-     */
-    @NonNull
-    public Object deselectTrack(@NonNull DataSourceDesc dsd, @NonNull TrackInfo trackInfo) {
-        return addTask(new Task(CALL_COMPLETED_DESELECT_TRACK, false) {
-            @Override
-            void process() {
-                selectOrDeselectTrack(dsd, trackInfo.mId, false /* select */);
-            }
-        });
-    }
-
-    private void selectOrDeselectTrack(@NonNull DataSourceDesc dsd, int index, boolean select) {
-        if (dsd == null) {
-            throw new IllegalArgumentException("non-null dsd is expected");
-        }
-        SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo == null) {
-            return;
-        }
-
-        PlayerMessage request = PlayerMessage.newBuilder()
-                .addValues(Value.newBuilder().setInt32Value(
-                            select ? INVOKE_ID_SELECT_TRACK : INVOKE_ID_DESELECT_TRACK))
-                .addValues(Value.newBuilder().setInt64Value(sourceInfo.mId))
-                .addValues(Value.newBuilder().setInt32Value(index))
-                .build();
-        invoke(request);
-    }
-
-    /* Do not change these values without updating their counterparts
-     * in include/media/mediaplayer2.h!
-     */
-    private static final int MEDIA_NOP = 0; // interface test message
-    private static final int MEDIA_PREPARED = 1;
-    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
-    private static final int MEDIA_BUFFERING_UPDATE = 3;
-    private static final int MEDIA_SEEK_COMPLETE = 4;
-    private static final int MEDIA_SET_VIDEO_SIZE = 5;
-    private static final int MEDIA_STARTED = 6;
-    private static final int MEDIA_PAUSED = 7;
-    private static final int MEDIA_STOPPED = 8;
-    private static final int MEDIA_SKIPPED = 9;
-    private static final int MEDIA_DRM_PREPARED = 10;
-    private static final int MEDIA_NOTIFY_TIME = 98;
-    private static final int MEDIA_TIMED_TEXT = 99;
-    private static final int MEDIA_ERROR = 100;
-    private static final int MEDIA_INFO = 200;
-    private static final int MEDIA_SUBTITLE_DATA = 201;
-    private static final int MEDIA_META_DATA = 202;
-    private static final int MEDIA_DRM_INFO = 210;
-
-    private class TaskHandler extends Handler {
-        private MediaPlayer2 mMediaPlayer;
-
-        TaskHandler(MediaPlayer2 mp, Looper looper) {
-            super(looper);
-            mMediaPlayer = mp;
-        }
-
-        @Override
-        public void handleMessage(Message msg) {
-            handleMessage(msg, 0);
-        }
-
-        public void handleMessage(Message msg, long srcId) {
-            if (mMediaPlayer.mNativeContext == 0) {
-                Log.w(TAG, "mediaplayer2 went away with unhandled events");
-                return;
-            }
-            final int what = msg.arg1;
-            final int extra = msg.arg2;
-
-            final SourceInfo sourceInfo = getSourceInfo(srcId);
-            if (sourceInfo == null) {
-                return;
-            }
-            final DataSourceDesc dsd = sourceInfo.mDSD;
-
-            switch(msg.what) {
-                case MEDIA_PREPARED:
-                case MEDIA_DRM_PREPARED:
-                {
-                    sourceInfo.mPrepareBarrier--;
-                    if (sourceInfo.mPrepareBarrier > 0) {
-                        break;
-                    } else if (sourceInfo.mPrepareBarrier < 0) {
-                        Log.w(TAG, "duplicated (drm) prepared events");
-                        break;
-                    }
-
-                    if (dsd != null) {
-                        sendEvent(new EventNotifier() {
-                            @Override
-                            public void notify(EventCallback callback) {
-                                callback.onInfo(
-                                        mMediaPlayer, dsd, MEDIA_INFO_PREPARED, 0);
-                            }
-                        });
-                    }
-
-                    synchronized (mSrcLock) {
-                        SourceInfo nextSourceInfo = mNextSourceInfos.peek();
-                        Log.i(TAG, "MEDIA_PREPARED: srcId=" + srcId
-                                + ", curSrc=" + mCurrentSourceInfo
-                                + ", nextSrc=" + nextSourceInfo);
-
-                        if (isCurrentSource(srcId)) {
-                            prepareNextDataSource();
-                        } else if (isNextSource(srcId)) {
-                            nextSourceInfo.mStateAsNextSource = NEXT_SOURCE_STATE_PREPARED;
-                            if (nextSourceInfo.mPlayPendingAsNextSource) {
-                                playNextDataSource();
-                            }
-                        }
-                    }
-
-                    synchronized (mTaskLock) {
-                        if (mCurrentTask != null
-                                && mCurrentTask.mMediaCallType == CALL_COMPLETED_PREPARE
-                                && mCurrentTask.mDSD == dsd
-                                && mCurrentTask.mNeedToWaitForEventToComplete) {
-                            mCurrentTask.sendCompleteNotification(CALL_STATUS_NO_ERROR);
-                            mCurrentTask = null;
-                            processPendingTask_l();
-                        }
-                    }
-                    return;
-                }
-
-                case MEDIA_DRM_INFO:
-                {
-                    if (msg.obj == null) {
-                        Log.w(TAG, "MEDIA_DRM_INFO msg.obj=NULL");
-                    } else if (msg.obj instanceof byte[]) {
-                        // The PlayerMessage was parsed already in postEventFromNative
-
-                        final DrmInfo drmInfo;
-                        synchronized (sourceInfo) {
-                            if (sourceInfo.mDrmInfo != null) {
-                                drmInfo = sourceInfo.mDrmInfo.makeCopy();
-                            } else {
-                                drmInfo = null;
-                            }
-                        }
-
-                        // notifying the client outside the lock
-                        DrmPreparationInfo drmPrepareInfo = null;
-                        if (drmInfo != null) {
-                            try {
-                                drmPrepareInfo = sendDrmEventWait(
-                                        new DrmEventNotifier<DrmPreparationInfo>() {
-                                            @Override
-                                            public DrmPreparationInfo notifyWait(
-                                                    DrmEventCallback callback) {
-                                                return callback.onDrmInfo(mMediaPlayer, dsd,
-                                                        drmInfo);
-                                            }
-                                        });
-                            } catch (InterruptedException | ExecutionException
-                                    | TimeoutException e) {
-                                Log.w(TAG, "Exception while waiting for DrmPreparationInfo", e);
-                            }
-                        }
-                        if (sourceInfo.mDrmHandle.setPreparationInfo(drmPrepareInfo)) {
-                            sourceInfo.mPrepareBarrier++;
-                            final Task prepareDrmTask;
-                            prepareDrmTask = newPrepareDrmTask(dsd, drmPrepareInfo.mUUID);
-                            mTaskHandler.post(new Runnable() {
-                                @Override
-                                public void run() {
-                                    // Run as simple Runnable, not Task
-                                    try {
-                                        prepareDrmTask.process();
-                                    } catch (NoDrmSchemeException | IOException e) {
-                                        final String errMsg;
-                                        errMsg = "Unexpected Exception during prepareDrm";
-                                        throw new RuntimeException(errMsg, e);
-                                    }
-                                }
-                            });
-                        } else {
-                            Log.w(TAG, "No valid DrmPreparationInfo set");
-                        }
-                    } else {
-                        Log.w(TAG, "MEDIA_DRM_INFO msg.obj of unexpected type " + msg.obj);
-                    }
-                    return;
-                }
-
-                case MEDIA_PLAYBACK_COMPLETE:
-                {
-                    if (isCurrentSource(srcId)) {
-                        sendEvent(new EventNotifier() {
-                            @Override
-                            public void notify(EventCallback callback) {
-                                callback.onInfo(
-                                        mMediaPlayer, dsd, MEDIA_INFO_DATA_SOURCE_END, 0);
-                            }
-                        });
-                        stayAwake(false);
-
-                        synchronized (mSrcLock) {
-                            SourceInfo nextSourceInfo = mNextSourceInfos.peek();
-                            if (nextSourceInfo != null) {
-                                nextSourceInfo.mPlayPendingAsNextSource = true;
-                            }
-                            Log.i(TAG, "MEDIA_PLAYBACK_COMPLETE: srcId=" + srcId
-                                    + ", curSrc=" + mCurrentSourceInfo
-                                    + ", nextSrc=" + nextSourceInfo);
-                        }
-
-                        playNextDataSource();
-                    }
-
-                    return;
-                }
-
-                case MEDIA_STOPPED:
-                case MEDIA_STARTED:
-                case MEDIA_PAUSED:
-                case MEDIA_SKIPPED:
-                case MEDIA_NOTIFY_TIME:
-                {
-                    // Do nothing. The client should have enough information with
-                    // {@link EventCallback#onMediaTimeDiscontinuity}.
-                    break;
-                }
-
-                case MEDIA_BUFFERING_UPDATE:
-                {
-                    final int percent = msg.arg1;
-                    sendEvent(new EventNotifier() {
-                        @Override
-                        public void notify(EventCallback callback) {
-                            callback.onInfo(
-                                    mMediaPlayer, dsd, MEDIA_INFO_BUFFERING_UPDATE, percent);
-                        }
-                    });
-
-                    SourceInfo src = getSourceInfo(srcId);
-                    if (src != null) {
-                        src.mBufferedPercentage.set(percent);
-                    }
-
-                    return;
-                }
-
-                case MEDIA_SEEK_COMPLETE:
-                {
-                    synchronized (mTaskLock) {
-                        if (!mPendingTasks.isEmpty()
-                                && mPendingTasks.get(0).mMediaCallType != CALL_COMPLETED_SEEK_TO
-                                && getState() == PLAYER_STATE_PLAYING) {
-                            mIsPreviousCommandSeekTo = false;
-                        }
-
-                        if (mCurrentTask != null
-                                && mCurrentTask.mMediaCallType == CALL_COMPLETED_SEEK_TO
-                                && mCurrentTask.mNeedToWaitForEventToComplete) {
-                            mCurrentTask.sendCompleteNotification(CALL_STATUS_NO_ERROR);
-                            mCurrentTask = null;
-                            processPendingTask_l();
-                        }
-                    }
-                    return;
-                }
-
-                case MEDIA_SET_VIDEO_SIZE:
-                {
-                    final int width = msg.arg1;
-                    final int height = msg.arg2;
-
-                    mVideoSize = new Size(width, height);
-                    sendEvent(new EventNotifier() {
-                        @Override
-                        public void notify(EventCallback callback) {
-                            callback.onVideoSizeChanged(
-                                    mMediaPlayer, dsd, mVideoSize);
-                        }
-                    });
-                    return;
-                }
-
-                case MEDIA_ERROR:
-                {
-                    Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
-                    sendEvent(new EventNotifier() {
-                        @Override
-                        public void notify(EventCallback callback) {
-                            callback.onError(
-                                    mMediaPlayer, dsd, what, extra);
-                        }
-                    });
-                    sendEvent(new EventNotifier() {
-                        @Override
-                        public void notify(EventCallback callback) {
-                            callback.onInfo(
-                                    mMediaPlayer, dsd, MEDIA_INFO_DATA_SOURCE_END, 0);
-                        }
-                    });
-                    stayAwake(false);
-                    return;
-                }
-
-                case MEDIA_INFO:
-                {
-                    switch (msg.arg1) {
-                        case MEDIA_INFO_VIDEO_TRACK_LAGGING:
-                            Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
-                            break;
-                    }
-
-                    sendEvent(new EventNotifier() {
-                        @Override
-                        public void notify(EventCallback callback) {
-                            callback.onInfo(
-                                    mMediaPlayer, dsd, what, extra);
-                        }
-                    });
-
-                    if (msg.arg1 == MEDIA_INFO_DATA_SOURCE_START) {
-                        if (isCurrentSource(srcId)) {
-                            prepareNextDataSource();
-                        }
-                    }
-
-                    // No real default action so far.
-                    return;
-                }
-
-                case MEDIA_TIMED_TEXT:
-                {
-                    final TimedText text;
-                    if (msg.obj instanceof byte[]) {
-                        PlayerMessage playerMsg;
-                        try {
-                            playerMsg = PlayerMessage.parseFrom((byte[]) msg.obj);
-                        } catch (InvalidProtocolBufferException e) {
-                            Log.w(TAG, "Failed to parse timed text.", e);
-                            return;
-                        }
-                        text = TimedTextUtil.parsePlayerMessage(playerMsg);
-                    } else {
-                        text = null;
-                    }
-
-                    sendEvent(new EventNotifier() {
-                        @Override
-                        public void notify(EventCallback callback) {
-                            callback.onTimedText(
-                                    mMediaPlayer, dsd, text);
-                        }
-                    });
-                    return;
-                }
-
-                case MEDIA_SUBTITLE_DATA:
-                {
-                    if (msg.obj instanceof byte[]) {
-                        PlayerMessage playerMsg;
-                        try {
-                            playerMsg = PlayerMessage.parseFrom((byte[]) msg.obj);
-                        } catch (InvalidProtocolBufferException e) {
-                            Log.w(TAG, "Failed to parse subtitle data.", e);
-                            return;
-                        }
-                        Iterator<Value> in = playerMsg.getValuesList().iterator();
-                        final int trackIndex = in.next().getInt32Value();
-                        TrackInfo trackInfo = getTrackInfo(dsd).get(trackIndex);
-                        final long startTimeUs = in.next().getInt64Value();
-                        final long durationTimeUs = in.next().getInt64Value();
-                        final byte[] subData = in.next().getBytesValue().toByteArray();
-                        SubtitleData data = new SubtitleData(trackInfo,
-                                startTimeUs, durationTimeUs, subData);
-                        sendEvent(new EventNotifier() {
-                            @Override
-                            public void notify(EventCallback callback) {
-                                callback.onSubtitleData(
-                                        mMediaPlayer, dsd, data);
-                            }
-                        });
-                    }
-                    return;
-                }
-
-                case MEDIA_META_DATA:
-                {
-                    final TimedMetaData data;
-                    if (msg.obj instanceof byte[]) {
-                        PlayerMessage playerMsg;
-                        try {
-                            playerMsg = PlayerMessage.parseFrom((byte[]) msg.obj);
-                        } catch (InvalidProtocolBufferException e) {
-                            Log.w(TAG, "Failed to parse timed meta data.", e);
-                            return;
-                        }
-                        Iterator<Value> in = playerMsg.getValuesList().iterator();
-                        data = new TimedMetaData(
-                                in.next().getInt64Value(),  // timestampUs
-                                in.next().getBytesValue().toByteArray());  // metaData
-                    } else {
-                        data = null;
-                    }
-
-                    sendEvent(new EventNotifier() {
-                        @Override
-                        public void notify(EventCallback callback) {
-                            callback.onTimedMetaDataAvailable(
-                                    mMediaPlayer, dsd, data);
-                        }
-                    });
-                    return;
-                }
-
-                case MEDIA_NOP: // interface test message - ignore
-                {
-                    break;
-                }
-
-                default:
-                {
-                    Log.e(TAG, "Unknown message type " + msg.what);
-                    return;
-                }
-            }
-        }
-    }
-
-    /*
-     * Called from native code when an interesting event happens.  This method
-     * just uses the TaskHandler system to post the event back to the main app thread.
-     * We use a weak reference to the original MediaPlayer2 object so that the native
-     * code is safe from the object disappearing from underneath it.  (This is
-     * the cookie passed to native_setup().)
-     */
-    private static void postEventFromNative(Object mediaplayer2Ref, long srcId,
-                                            int what, int arg1, int arg2, byte[] obj) {
-        final MediaPlayer2 mp = (MediaPlayer2) ((WeakReference) mediaplayer2Ref).get();
-        if (mp == null) {
-            return;
-        }
-
-        final SourceInfo sourceInfo = mp.getSourceInfo(srcId);
-        switch (what) {
-            case MEDIA_DRM_INFO:
-                // We need to derive mDrmInfo before prepare() returns so processing it here
-                // before the notification is sent to TaskHandler below. TaskHandler runs in the
-                // notification looper so its handleMessage might process the event after prepare()
-                // has returned.
-                Log.v(TAG, "postEventFromNative MEDIA_DRM_INFO");
-                if (obj != null && sourceInfo != null) {
-                    PlayerMessage playerMsg;
-                    try {
-                        playerMsg = PlayerMessage.parseFrom(obj);
-                    } catch (InvalidProtocolBufferException e) {
-                        Log.w(TAG, "MEDIA_DRM_INFO failed to parse msg.obj " + obj);
-                        break;
-                    }
-                    DrmInfo drmInfo = DrmInfo.create(playerMsg);
-                    synchronized (sourceInfo) {
-                        sourceInfo.mDrmInfo = drmInfo;
-                    }
-                } else {
-                    Log.w(TAG, "MEDIA_DRM_INFO sourceInfo " + sourceInfo
-                            + " msg.obj of unexpected type " + obj);
-                }
-                break;
-
-            case MEDIA_PREPARED:
-                // By this time, we've learned about DrmInfo's presence or absence. This is meant
-                // mainly for prepare() use case. For prepare(), this still can run to a race
-                // condition b/c MediaPlayerNative releases the prepare() lock before calling notify
-                // so we also set mDrmInfoResolved in prepare().
-                if (sourceInfo != null) {
-                    synchronized (sourceInfo) {
-                        sourceInfo.mDrmInfoResolved = true;
-                    }
-                }
-                break;
-        }
-
-        if (mp.mTaskHandler != null) {
-            Message m = mp.mTaskHandler.obtainMessage(what, arg1, arg2, obj);
-
-            mp.mTaskHandler.post(new Runnable() {
-                @Override
-                public void run() {
-                    mp.mTaskHandler.handleMessage(m, srcId);
-                }
-            });
-        }
-    }
-
-    /**
-     * Class encapsulating subtitle data, as received through the
-     * {@link EventCallback#onSubtitleData} interface.
-     * <p>
-     * A {@link SubtitleData} object includes:
-     * <ul>
-     * <li> track metadadta in a {@link TrackInfo} object</li>
-     * <li> the start time (in microseconds) of the data</li>
-     * <li> the duration (in microseconds) of the data</li>
-     * <li> the actual data.</li>
-     * </ul>
-     * The data is stored in a byte-array, and is encoded in one of the supported in-band
-     * subtitle formats. The subtitle encoding is determined by the MIME type of the
-     * {@link TrackInfo} of the subtitle track, one of
-     * {@link MediaFormat#MIMETYPE_TEXT_CEA_608}, {@link MediaFormat#MIMETYPE_TEXT_CEA_708},
-     * {@link MediaFormat#MIMETYPE_TEXT_VTT}.
-     */
-    public static final class SubtitleData {
-
-        private TrackInfo mTrackInfo;
-        private long mStartTimeUs;
-        private long mDurationUs;
-        private byte[] mData;
-
-        private SubtitleData(TrackInfo trackInfo, long startTimeUs, long durationUs, byte[] data) {
-            mTrackInfo = trackInfo;
-            mStartTimeUs = startTimeUs;
-            mDurationUs = durationUs;
-            mData = (data != null ? data : new byte[0]);
-        }
-
-        /**
-         * @return metadata of track which contains this subtitle data
-         */
-        @NonNull
-        public TrackInfo getTrackInfo() {
-            return mTrackInfo;
-        }
-
-        /**
-         * @return media time at which the subtitle should start to be displayed in microseconds
-         */
-        public long getStartTimeUs() {
-            return mStartTimeUs;
-        }
-
-        /**
-         * @return the duration in microsecond during which the subtitle should be displayed
-         */
-        public long getDurationUs() {
-            return mDurationUs;
-        }
-
-        /**
-         * Returns the encoded data for the subtitle content.
-         * Encoding format depends on the subtitle type, refer to
-         * <a href="https://en.wikipedia.org/wiki/CEA-708">CEA 708</a>,
-         * <a href="https://en.wikipedia.org/wiki/EIA-608">CEA/EIA 608</a> and
-         * <a href="https://www.w3.org/TR/webvtt1/">WebVTT</a>, defined by the MIME type
-         * of the subtitle track.
-         * @return the encoded subtitle data
-         */
-        @NonNull
-        public byte[] getData() {
-            return mData;
-        }
-    }
-
-    /**
-     * Interface definition for callbacks to be invoked when the player has the corresponding
-     * events.
-     */
-    public static class EventCallback {
-        /**
-         * Called to indicate the video size
-         *
-         * The video size (width and height) could be 0 if there was no video,
-         * or the value was not determined yet.
-         *
-         * @param mp the MediaPlayer2 associated with this callback
-         * @param dsd the DataSourceDesc of this data source
-         * @param size the size of the video
-         */
-        public void onVideoSizeChanged(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @NonNull Size size) { }
-
-        /**
-         * Called to indicate an avaliable timed text
-         *
-         * @param mp the MediaPlayer2 associated with this callback
-         * @param dsd the DataSourceDesc of this data source
-         * @param text the timed text sample which contains the text
-         *             needed to be displayed and the display format.
-         * @hide
-         */
-        public void onTimedText(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @NonNull TimedText text) { }
-
-        /**
-         * Called to indicate avaliable timed metadata
-         * <p>
-         * This method will be called as timed metadata is extracted from the media,
-         * in the same order as it occurs in the media. The timing of this event is
-         * not controlled by the associated timestamp.
-         * <p>
-         * Currently only HTTP live streaming data URI's embedded with timed ID3 tags generates
-         * {@link TimedMetaData}.
-         *
-         * @see MediaPlayer2#selectTrack
-         * @see MediaPlayer2.OnTimedMetaDataAvailableListener
-         * @see TimedMetaData
-         *
-         * @param mp the MediaPlayer2 associated with this callback
-         * @param dsd the DataSourceDesc of this data source
-         * @param data the timed metadata sample associated with this event
-         */
-        public void onTimedMetaDataAvailable(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
-                @NonNull TimedMetaData data) { }
-
-        /**
-         * Called to indicate an error.
-         *
-         * @param mp the MediaPlayer2 the error pertains to
-         * @param dsd the DataSourceDesc of this data source
-         * @param what the type of error that has occurred.
-         * @param extra an extra code, specific to the error. Typically
-         * implementation dependent.
-         */
-        public void onError(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
-                @MediaError int what, int extra) { }
-
-        /**
-         * Called to indicate an info or a warning.
-         *
-         * @param mp the MediaPlayer2 the info pertains to.
-         * @param dsd the DataSourceDesc of this data source
-         * @param what the type of info or warning.
-         * @param extra an extra code, specific to the info. Typically
-         * implementation dependent.
-         */
-        public void onInfo(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
-                @MediaInfo int what, int extra) { }
-
-        /**
-         * Called to acknowledge an API call.
-         *
-         * @param mp the MediaPlayer2 the call was made on.
-         * @param dsd the DataSourceDesc of this data source
-         * @param what the enum for the API call.
-         * @param status the returned status code for the call.
-         */
-        public void onCallCompleted(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd, @CallCompleted int what,
-                @CallStatus int status) { }
-
-        /**
-         * Called to indicate media clock has changed.
-         *
-         * @param mp the MediaPlayer2 the media time pertains to.
-         * @param dsd the DataSourceDesc of this data source
-         * @param timestamp the new media clock.
-         */
-        public void onMediaTimeDiscontinuity(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
-                @NonNull MediaTimestamp timestamp) { }
-
-        /**
-         * Called to indicate {@link #notifyWhenCommandLabelReached(Object)} has been processed.
-         *
-         * @param mp the MediaPlayer2 {@link #notifyWhenCommandLabelReached(Object)} was called on.
-         * @param label the application specific Object given by
-         *        {@link #notifyWhenCommandLabelReached(Object)}.
-         */
-        public void onCommandLabelReached(@NonNull MediaPlayer2 mp, @NonNull Object label) { }
-
-        /**
-         * Called when when a player subtitle track has new subtitle data available.
-         * @param mp the player that reports the new subtitle data
-         * @param dsd the DataSourceDesc of this data source
-         * @param data the subtitle data
-         */
-        public void onSubtitleData(
-                @NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
-                @NonNull SubtitleData data) { }
-    }
-
-    private final Object mEventCbLock = new Object();
-    private ArrayList<Pair<Executor, EventCallback>> mEventCallbackRecords =
-            new ArrayList<Pair<Executor, EventCallback>>();
-
-    /**
-     * Registers the callback to be invoked for various events covered by {@link EventCallback}.
-     *
-     * @param executor the executor through which the callback should be invoked
-     * @param eventCallback the callback that will be run
-     */
-    // This is a synchronous call.
-    public void registerEventCallback(@NonNull @CallbackExecutor Executor executor,
-            @NonNull EventCallback eventCallback) {
-        if (eventCallback == null) {
-            throw new IllegalArgumentException("Illegal null EventCallback");
-        }
-        if (executor == null) {
-            throw new IllegalArgumentException(
-                    "Illegal null Executor for the EventCallback");
-        }
-        synchronized (mEventCbLock) {
-            for (Pair<Executor, EventCallback> cb : mEventCallbackRecords) {
-                if (cb.first == executor && cb.second == eventCallback) {
-                    Log.w(TAG, "The callback has been registered before.");
-                    return;
-                }
-            }
-            mEventCallbackRecords.add(new Pair(executor, eventCallback));
-        }
-    }
-
-    /**
-     * Unregisters the {@link EventCallback}.
-     *
-     * @param eventCallback the callback to be unregistered
-     */
-    // This is a synchronous call.
-    public void unregisterEventCallback(@NonNull EventCallback eventCallback) {
-        synchronized (mEventCbLock) {
-            for (Pair<Executor, EventCallback> cb : mEventCallbackRecords) {
-                if (cb.second == eventCallback) {
-                    mEventCallbackRecords.remove(cb);
-                }
-            }
-        }
-    }
-
-    private void sendEvent(final EventNotifier notifier) {
-        synchronized (mEventCbLock) {
-            try {
-                for (Pair<Executor, EventCallback> cb : mEventCallbackRecords) {
-                    cb.first.execute(() -> notifier.notify(cb.second));
-                }
-            } catch (RejectedExecutionException e) {
-                // The executor has been shut down.
-                Log.w(TAG, "The executor has been shut down. Ignoring event.");
-            }
-        }
-    }
-
-    private void sendDrmEvent(final DrmEventNotifier notifier) {
-        synchronized (mDrmEventCallbackLock) {
-            try {
-                Pair<Executor, DrmEventCallback> cb = mDrmEventCallback;
-                if (cb != null) {
-                    cb.first.execute(() -> notifier.notify(cb.second));
-                }
-            } catch (RejectedExecutionException e) {
-                // The executor has been shut down.
-                Log.w(TAG, "The executor has been shut down. Ignoring drm event.");
-            }
-        }
-    }
-
-    private <T> T sendDrmEventWait(final DrmEventNotifier<T> notifier)
-            throws InterruptedException, ExecutionException, TimeoutException {
-        return sendDrmEventWait(notifier, 0);
-    }
-
-    private <T> T sendDrmEventWait(final DrmEventNotifier<T> notifier, final long timeoutMs)
-            throws InterruptedException, ExecutionException, TimeoutException {
-        synchronized (mDrmEventCallbackLock) {
-            Pair<Executor, DrmEventCallback> cb = mDrmEventCallback;
-            if (cb != null) {
-                CompletableFuture<T> ret = new CompletableFuture<>();
-                cb.first.execute(() -> ret.complete(notifier.notifyWait(cb.second)));
-                return timeoutMs <= 0 ? ret.get() : ret.get(timeoutMs, TimeUnit.MILLISECONDS);
-            }
-        }
-        return null;
-    }
-
-    private interface EventNotifier {
-        void notify(EventCallback callback);
-    }
-
-    private interface DrmEventNotifier<T> {
-        default void notify(DrmEventCallback callback) { }
-        default T notifyWait(DrmEventCallback callback) {
-            return null;
-        }
-    }
-
-    /* Do not change these values without updating their counterparts
-     * in include/media/MediaPlayer2Types.h!
-     */
-    /** Unspecified media player error.
-     * @see EventCallback#onError
-     */
-    public static final int MEDIA_ERROR_UNKNOWN = 1;
-
-    /**
-     * The video is streamed and its container is not valid for progressive
-     * playback i.e the video's index (e.g moov atom) is not at the start of the
-     * file.
-     * @see EventCallback#onError
-     */
-    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
-
-    /** File or network related operation errors. */
-    public static final int MEDIA_ERROR_IO = -1004;
-    /** Bitstream is not conforming to the related coding standard or file spec. */
-    public static final int MEDIA_ERROR_MALFORMED = -1007;
-    /** Bitstream is conforming to the related coding standard or file spec, but
-     * the media framework does not support the feature. */
-    public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
-    /** Some operation takes too long to complete, usually more than 3-5 seconds. */
-    public static final int MEDIA_ERROR_TIMED_OUT = -110;
-
-    /** Unspecified low-level system error. This value originated from UNKNOWN_ERROR in
-     * system/core/include/utils/Errors.h
-     * @see EventCallback#onError
-     * @hide
-     */
-    public static final int MEDIA_ERROR_SYSTEM = -2147483648;
-
-    /**
-     * @hide
-     */
-    @IntDef(flag = false, prefix = "MEDIA_ERROR", value = {
-            MEDIA_ERROR_UNKNOWN,
-            MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK,
-            MEDIA_ERROR_IO,
-            MEDIA_ERROR_MALFORMED,
-            MEDIA_ERROR_UNSUPPORTED,
-            MEDIA_ERROR_TIMED_OUT,
-            MEDIA_ERROR_SYSTEM
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface MediaError {}
-
-    /* Do not change these values without updating their counterparts
-     * in include/media/MediaPlayer2Types.h!
-     */
-    /** Unspecified media player info.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_UNKNOWN = 1;
-
-    /** The player just started the playback of this datas source.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_DATA_SOURCE_START = 2;
-
-    /** The player just pushed the very first video frame for rendering.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
-
-    /** The player just rendered the very first audio sample.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_AUDIO_RENDERING_START = 4;
-
-    /** The player just completed the playback of this data source.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_DATA_SOURCE_END = 5;
-
-    /** The player just completed the playback of all data sources set by {@link #setDataSource},
-     * {@link #setNextDataSource} and {@link #setNextDataSources}.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_DATA_SOURCE_LIST_END = 6;
-
-    /** The player just completed an iteration of playback loop. This event is sent only when
-     *  looping is enabled by {@link #loopCurrent}.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_DATA_SOURCE_REPEAT = 7;
-
-    /** The player just prepared a data source.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_PREPARED = 100;
-
-    /** The video is too complex for the decoder: it can't decode frames fast
-     *  enough. Possibly only the audio plays fine at this stage.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
-
-    /** MediaPlayer2 is temporarily pausing playback internally in order to
-     * buffer more data.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_BUFFERING_START = 701;
-
-    /** MediaPlayer2 is resuming playback after filling buffers.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_BUFFERING_END = 702;
-
-    /** Estimated network bandwidth information (kbps) is available; currently this event fires
-     * simultaneously as {@link #MEDIA_INFO_BUFFERING_START} and {@link #MEDIA_INFO_BUFFERING_END}
-     * when playing network files.
-     * @see EventCallback#onInfo
-     * @hide
-     */
-    public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
-
-    /**
-     * Update status in buffering a media source received through progressive downloading.
-     * The received buffering percentage indicates how much of the content has been buffered
-     * or played. For example a buffering update of 80 percent when half the content
-     * has already been played indicates that the next 30 percent of the
-     * content to play has been buffered.
-     *
-     * The {@code extra} parameter in {@code EventCallback.onInfo} is the
-     * percentage (0-100) of the content that has been buffered or played thus far.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_BUFFERING_UPDATE = 704;
-
-    /** Bad interleaving means that a media has been improperly interleaved or
-     * not interleaved at all, e.g has all the video samples first then all the
-     * audio ones. Video is playing but a lot of disk seeks may be happening.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
-
-    /** The media cannot be seeked (e.g live stream)
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
-
-    /** A new set of metadata is available.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
-
-    /** Informs that audio is not playing. Note that playback of the video
-     * is not interrupted.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_AUDIO_NOT_PLAYING = 804;
-
-    /** Informs that video is not playing. Note that playback of the audio
-     * is not interrupted.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_VIDEO_NOT_PLAYING = 805;
-
-    /** Failed to handle timed text track properly.
-     * @see EventCallback#onInfo
-     *
-     * {@hide}
-     */
-    public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
-
-    /** Subtitle track was not supported by the media framework.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
-
-    /** Reading the subtitle track takes too long.
-     * @see EventCallback#onInfo
-     */
-    public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
-
-    /**
-     * @hide
-     */
-    @IntDef(flag = false, prefix = "MEDIA_INFO", value = {
-            MEDIA_INFO_UNKNOWN,
-            MEDIA_INFO_DATA_SOURCE_START,
-            MEDIA_INFO_VIDEO_RENDERING_START,
-            MEDIA_INFO_AUDIO_RENDERING_START,
-            MEDIA_INFO_DATA_SOURCE_END,
-            MEDIA_INFO_DATA_SOURCE_LIST_END,
-            MEDIA_INFO_PREPARED,
-            MEDIA_INFO_VIDEO_TRACK_LAGGING,
-            MEDIA_INFO_BUFFERING_START,
-            MEDIA_INFO_BUFFERING_END,
-            MEDIA_INFO_NETWORK_BANDWIDTH,
-            MEDIA_INFO_BUFFERING_UPDATE,
-            MEDIA_INFO_BAD_INTERLEAVING,
-            MEDIA_INFO_NOT_SEEKABLE,
-            MEDIA_INFO_METADATA_UPDATE,
-            MEDIA_INFO_AUDIO_NOT_PLAYING,
-            MEDIA_INFO_VIDEO_NOT_PLAYING,
-            MEDIA_INFO_TIMED_TEXT_ERROR,
-            MEDIA_INFO_UNSUPPORTED_SUBTITLE,
-            MEDIA_INFO_SUBTITLE_TIMED_OUT
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface MediaInfo {}
-
-    //--------------------------------------------------------------------------
-    /** The player just completed a call {@link #attachAuxEffect}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_ATTACH_AUX_EFFECT = 1;
-
-    /** The player just completed a call {@link #deselectTrack}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_DESELECT_TRACK = 2;
-
-    /** The player just completed a call {@link #loopCurrent}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_LOOP_CURRENT = 3;
-
-    /** The player just completed a call {@link #pause}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_PAUSE = 4;
-
-    /** The player just completed a call {@link #play}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_PLAY = 5;
-
-    /** The player just completed a call {@link #prepare}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_PREPARE = 6;
-
-    /** The player just completed a call {@link #seekTo}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SEEK_TO = 14;
-
-    /** The player just completed a call {@link #selectTrack}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SELECT_TRACK = 15;
-
-    /** The player just completed a call {@link #setAudioAttributes}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_AUDIO_ATTRIBUTES = 16;
-
-    /** The player just completed a call {@link #setAudioSessionId}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_AUDIO_SESSION_ID = 17;
-
-    /** The player just completed a call {@link #setAuxEffectSendLevel}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL = 18;
-
-    /** The player just completed a call {@link #setDataSource}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_DATA_SOURCE = 19;
-
-    /** The player just completed a call {@link #setNextDataSource}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCE = 22;
-
-    /** The player just completed a call {@link #setNextDataSources}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCES = 23;
-
-    /** The player just completed a call {@link #setPlaybackParams}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_PLAYBACK_PARAMS = 24;
-
-    /** The player just completed a call {@link #setPlayerVolume}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_PLAYER_VOLUME = 26;
-
-    /** The player just completed a call {@link #setSurface}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_SURFACE = 27;
-
-    /** The player just completed a call {@link #setSyncParams}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_SYNC_PARAMS = 28;
-
-    /** The player just completed a call {@link #skipToNext}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SKIP_TO_NEXT = 29;
-
-    /** The player just completed a call {@link #clearNextDataSources}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_CLEAR_NEXT_DATA_SOURCES = 30;
-
-    /** The player just completed a call {@link #setBufferingParams}.
-     * @see EventCallback#onCallCompleted
-     * @hide
-     */
-    public static final int CALL_COMPLETED_SET_BUFFERING_PARAMS = 31;
-
-    /** The player just completed a call {@link #setDisplay}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_DISPLAY = 33;
-
-    /** The player just completed a call {@link #setWakeLock}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_WAKE_LOCK = 34;
-
-    /** The player just completed a call {@link #setScreenOnWhilePlaying}.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING = 35;
-
-    /**
-     * The start of the methods which have separate call complete callback.
-     * @hide
-     */
-    public static final int SEPARATE_CALL_COMPLETED_CALLBACK_START = 1000;
-
-    /** The player just completed a call {@link #notifyWhenCommandLabelReached}.
-     * @see EventCallback#onCommandLabelReached
-     * @hide
-     */
-    public static final int CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED =
-            SEPARATE_CALL_COMPLETED_CALLBACK_START;
-
-    /** The player just completed a call {@link #prepareDrm}.
-     * @see DrmEventCallback#onDrmPrepared
-     * @hide
-     */
-    public static final int CALL_COMPLETED_PREPARE_DRM =
-            SEPARATE_CALL_COMPLETED_CALLBACK_START + 1;
-
-    /**
-     * @hide
-     */
-    @IntDef(flag = false, prefix = "CALL_COMPLETED", value = {
-            CALL_COMPLETED_ATTACH_AUX_EFFECT,
-            CALL_COMPLETED_DESELECT_TRACK,
-            CALL_COMPLETED_LOOP_CURRENT,
-            CALL_COMPLETED_PAUSE,
-            CALL_COMPLETED_PLAY,
-            CALL_COMPLETED_PREPARE,
-            CALL_COMPLETED_SEEK_TO,
-            CALL_COMPLETED_SELECT_TRACK,
-            CALL_COMPLETED_SET_AUDIO_ATTRIBUTES,
-            CALL_COMPLETED_SET_AUDIO_SESSION_ID,
-            CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL,
-            CALL_COMPLETED_SET_DATA_SOURCE,
-            CALL_COMPLETED_SET_NEXT_DATA_SOURCE,
-            CALL_COMPLETED_SET_NEXT_DATA_SOURCES,
-            CALL_COMPLETED_SET_PLAYBACK_PARAMS,
-            CALL_COMPLETED_SET_PLAYER_VOLUME,
-            CALL_COMPLETED_SET_SURFACE,
-            CALL_COMPLETED_SET_SYNC_PARAMS,
-            CALL_COMPLETED_SKIP_TO_NEXT,
-            CALL_COMPLETED_CLEAR_NEXT_DATA_SOURCES,
-            CALL_COMPLETED_SET_BUFFERING_PARAMS,
-            CALL_COMPLETED_SET_DISPLAY,
-            CALL_COMPLETED_SET_WAKE_LOCK,
-            CALL_COMPLETED_SET_SCREEN_ON_WHILE_PLAYING,
-            CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED,
-            CALL_COMPLETED_PREPARE_DRM,
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface CallCompleted {}
-
-    /** Status code represents that call is completed without an error.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_STATUS_NO_ERROR = 0;
-
-    /** Status code represents that call is ended with an unknown error.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_STATUS_ERROR_UNKNOWN = Integer.MIN_VALUE;
-
-    /** Status code represents that the player is not in valid state for the operation.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_STATUS_INVALID_OPERATION = 1;
-
-    /** Status code represents that the argument is illegal.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_STATUS_BAD_VALUE = 2;
-
-    /** Status code represents that the operation is not allowed.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_STATUS_PERMISSION_DENIED = 3;
-
-    /** Status code represents a file or network related operation error.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_STATUS_ERROR_IO = 4;
-
-    /** Status code represents that the call has been skipped. For example, a {@link #seekTo}
-     * request may be skipped if it is followed by another {@link #seekTo} request.
-     * @see EventCallback#onCallCompleted
-     */
-    public static final int CALL_STATUS_SKIPPED = 5;
-
-    /** Status code represents that DRM operation is called before preparing a DRM scheme through
-     *  {@code prepareDrm}.
-     * @see EventCallback#onCallCompleted
-     */
-    // TODO: change @code to @link when DRM is unhidden
-    public static final int CALL_STATUS_NO_DRM_SCHEME = 6;
-
-    /**
-     * @hide
-     */
-    @IntDef(flag = false, prefix = "CALL_STATUS", value = {
-            CALL_STATUS_NO_ERROR,
-            CALL_STATUS_ERROR_UNKNOWN,
-            CALL_STATUS_INVALID_OPERATION,
-            CALL_STATUS_BAD_VALUE,
-            CALL_STATUS_PERMISSION_DENIED,
-            CALL_STATUS_ERROR_IO,
-            CALL_STATUS_SKIPPED,
-            CALL_STATUS_NO_DRM_SCHEME})
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface CallStatus {}
-
-    // Modular DRM begin
-
-    /**
-     * An immutable structure per {@link DataSourceDesc} with settings required to initiate a DRM
-     * protected playback session.
-     *
-     * @see DrmPreparationInfo.Builder
-     */
-    public static final class DrmPreparationInfo {
-
-        /**
-         * Mutable builder to create a {@link MediaPlayer2.DrmPreparationInfo} object.
-         *
-         * {@link Builder#Builder(UUID) UUID} must not be null; {@link #setKeyType keyType}
-         * must be one of {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}.
-         * <p>
-         * When {@link #setKeyType keyType} is {@link MediaDrm#KEY_TYPE_STREAMING},
-         * {@link #setInitData(byte[]) initData} and {@link #setMimeType(String) mimeType}
-         * must not be null; When {@link #setKeyType keyType} is {@link MediaDrm#KEY_TYPE_OFFLINE},
-         * {@link #setKeySetId(byte[]) keySetId} must not be null.
-         */
-        public static final class Builder {
-
-            private final UUID mUUID;
-            private byte[] mKeySetId;
-            private byte[] mInitData;
-            private String mMimeType;
-            private int mKeyType;
-            private Map<String, String> mOptionalParameters;
-
-            /**
-             * @param uuid UUID of the crypto scheme selected to decrypt content. An UUID can be
-             * retrieved from the source listening to {@link DrmEventCallback#onDrmInfo}.
-             */
-            public Builder(@NonNull UUID uuid) {
-                this.mUUID = uuid;
-            }
-
-            /**
-             * Set identifier of a persisted offline key obtained from
-             * {@link MediaPlayer2.DrmEventCallback#onDrmPrepared}.
-             *
-             * A {@code keySetId} can be used to restore persisted offline keys into a new playback
-             * session of a DRM protected data source. When {@code keySetId} is set,
-             * {@code initData}, {@code mimeType}, {@code keyType}, {@code optionalParameters} are
-             * ignored.
-             *
-             * @param keySetId identifier of a persisted offline key
-             * @return this
-             */
-            public @NonNull Builder setKeySetId(@Nullable byte[] keySetId) {
-                this.mKeySetId = keySetId;
-                return this;
-            }
-
-            /**
-             * Set container-specific DRM initialization data. Its meaning is interpreted based on
-             * {@code mimeType}. For example, it could contain the content ID, key ID or other data
-             * obtained from the content metadata that is required to generate a
-             * {@link MediaDrm.KeyRequest}.
-             *
-             * @param initData container-specific DRM initialization data
-             * @return this
-             */
-            public @NonNull Builder setInitData(@Nullable byte[] initData) {
-                this.mInitData = initData;
-                return this;
-            }
-
-            /**
-             * Set mime type of the content
-             *
-             * @param mimeType mime type to the content
-             * @return this
-             */
-            public @NonNull Builder setMimeType(@Nullable String mimeType) {
-                this.mMimeType = mimeType;
-                return this;
-            }
-
-            /**
-             * Set type of the key request. The request may be to acquire keys
-             * for streaming, {@link MediaDrm#KEY_TYPE_STREAMING}, or for offline content,
-             * {@link MediaDrm#KEY_TYPE_OFFLINE}. Releasing previously acquired keys
-             * ({@link MediaDrm#KEY_TYPE_RELEASE}) is not allowed.
-             *
-             * @param keyType type of the key request
-             * @return this
-             */
-            public @NonNull Builder setKeyType(@MediaPlayer2.MediaDrmKeyType int keyType) {
-                this.mKeyType = keyType;
-                return this;
-            }
-
-            /**
-             * Set optional parameters to be included in a {@link MediaDrm.KeyRequest} message sent
-             * to the license server.
-             *
-             * @param optionalParameters optional parameters to be included in a key request
-             * @return this
-             */
-            public @NonNull Builder setOptionalParameters(
-                    @Nullable Map<String, String> optionalParameters) {
-                this.mOptionalParameters = optionalParameters;
-                return this;
-            }
-
-            /**
-             * @return an immutable {@link DrmPreparationInfo} based on settings of this builder
-             */
-            @NonNull
-            public DrmPreparationInfo build() {
-                final DrmPreparationInfo info = new DrmPreparationInfo(mUUID, mKeySetId, mInitData,
-                        mMimeType, mKeyType, mOptionalParameters);
-                if (!info.isValid()) {
-                    throw new IllegalArgumentException("invalid DrmPreparationInfo");
-                }
-                return info;
-            }
-
-        }
-
-        private final UUID mUUID;
-        private final byte[] mKeySetId;
-        private final byte[] mInitData;
-        private final String mMimeType;
-        private final int mKeyType;
-        private final Map<String, String> mOptionalParameters;
-
-        private DrmPreparationInfo(UUID mUUID, byte[] mKeySetId, byte[] mInitData, String mMimeType,
-                int mKeyType, Map<String, String> optionalParameters) {
-            this.mUUID = mUUID;
-            this.mKeySetId = mKeySetId;
-            this.mInitData = mInitData;
-            this.mMimeType = mMimeType;
-            this.mKeyType = mKeyType;
-            this.mOptionalParameters = optionalParameters;
-        }
-
-        boolean isValid() {
-            if (mUUID == null) {
-                return false;
-            }
-            if (mKeySetId != null) {
-                // offline restore case
-                return true;
-            }
-            if (mInitData != null && mMimeType != null) {
-                // new streaming license case
-                return true;
-            }
-            return false;
-        }
-
-        /**
-         * @return UUID of the crypto scheme selected to decrypt content.
-         */
-        @NonNull
-        public UUID getUuid() {
-            return mUUID;
-        }
-
-        /**
-         * @return identifier of the persisted offline key.
-         */
-        @Nullable
-        public byte[] getKeySetId() {
-            return mKeySetId;
-        }
-
-        /**
-         * @return container-specific DRM initialization data.
-         */
-        @Nullable
-        public byte[] getInitData() {
-            return mInitData;
-        }
-
-        /**
-         * @return mime type of the content
-         */
-        @Nullable
-        public String getMimeType() {
-            return mMimeType;
-        }
-
-        /**
-         * @return type of the key request.
-         */
-        @MediaPlayer2.MediaDrmKeyType
-        public int getKeyType() {
-            return mKeyType;
-        }
-
-        /**
-         * @return optional parameters to be included in the {@link MediaDrm.KeyRequest}.
-         */
-        @Nullable
-        public Map<String, String> getOptionalParameters() {
-            return mOptionalParameters;
-        }
-    }
-
-    /**
-     * Interface definition for callbacks to be invoked when the player has the corresponding
-     * DRM events.
-     */
-    public static abstract class DrmEventCallback {
-
-        /**
-         * Called to indicate DRM info is available. Return a {@link DrmPreparationInfo} object that
-         * bundles DRM initialization parameters.
-         *
-         * @param mp the {@code MediaPlayer2} associated with this callback
-         * @param dsd the {@link DataSourceDesc} of this data source
-         * @param drmInfo DRM info of the source including PSSH, and subset of crypto schemes
-         *        supported by this device
-         * @return a {@link DrmPreparationInfo} object to initialize DRM playback, or null to skip
-         *         DRM initialization
-         */
-        @Nullable
-        public abstract DrmPreparationInfo onDrmInfo(@NonNull MediaPlayer2 mp,
-                @NonNull DataSourceDesc dsd, @NonNull DrmInfo drmInfo);
-
-        /**
-         * Called to give the app the opportunity to configure DRM before the session is created.
-         *
-         * This facilitates configuration of the properties, like 'securityLevel', which
-         * has to be set after DRM scheme creation but before the DRM session is opened.
-         *
-         * The only allowed DRM calls in this listener are
-         * {@link MediaDrm#getPropertyString(String)},
-         * {@link MediaDrm#getPropertyByteArray(String)},
-         * {@link MediaDrm#setPropertyString(String, String)},
-         * {@link MediaDrm#setPropertyByteArray(String, byte[])},
-         * {@link MediaDrm#setOnExpirationUpdateListener},
-         * and {@link MediaDrm#setOnKeyStatusChangeListener}.
-         *
-         * @param mp the {@code MediaPlayer2} associated with this callback
-         * @param dsd the {@link DataSourceDesc} of this data source
-         * @param drm handle to get/set DRM properties and listeners for this data source
-         */
-        public void onDrmConfig(@NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
-                @NonNull MediaDrm drm) { }
-
-        /**
-         * Called to indicate the DRM session for {@code dsd} is ready for key request/response
-         *
-         * @param mp the {@code MediaPlayer2} associated with this callback
-         * @param dsd the {@link DataSourceDesc} of this data source
-         * @param request a {@link MediaDrm.KeyRequest} prepared using the
-         *        {@link DrmPreparationInfo} returned from
-         *        {@link #onDrmInfo(MediaPlayer2, DataSourceDesc, DrmInfo)}
-         * @return the response to {@code request} (from license server); returning {@code null} or
-         *         throwing an {@link RuntimeException} from this callback would trigger an
-         *         {@link EventCallback#onError}.
-         */
-        @NonNull
-        public abstract byte[] onDrmKeyRequest(@NonNull MediaPlayer2 mp,
-                @NonNull DataSourceDesc dsd, @NonNull MediaDrm.KeyRequest request);
-
-        /**
-         * Called to notify the client that {@code mp} is ready to decrypt DRM protected data source
-         * {@code dsd} or if there is an error during DRM preparation
-         *
-         * @param mp the {@code MediaPlayer2} associated with this callback
-         * @param dsd the {@link DataSourceDesc} of this data source
-         * @param status the result of DRM preparation.
-         * @param keySetId optional identifier that can be used to restore DRM playback initiated
-         *        with a {@link MediaDrm#KEY_TYPE_OFFLINE} key request.
-         *
-         * @see DrmPreparationInfo.Builder#setKeySetId(byte[])
-         */
-        public void onDrmPrepared(@NonNull MediaPlayer2 mp, @NonNull DataSourceDesc dsd,
-                @PrepareDrmStatusCode int status, @Nullable byte[] keySetId) { }
-
-    }
-
-    private final Object mDrmEventCallbackLock = new Object();
-    private Pair<Executor, DrmEventCallback> mDrmEventCallback;
-
-    /**
-     * Registers the callback to be invoked for various DRM events.
-     *
-     * This is a synchronous call.
-     *
-     * @param eventCallback the callback that will be run
-     * @param executor the executor through which the callback should be invoked
-     */
-    public void setDrmEventCallback(@NonNull @CallbackExecutor Executor executor,
-            @NonNull DrmEventCallback eventCallback) {
-        if (eventCallback == null) {
-            throw new IllegalArgumentException("Illegal null EventCallback");
-        }
-        if (executor == null) {
-            throw new IllegalArgumentException(
-                    "Illegal null Executor for the EventCallback");
-        }
-        synchronized (mDrmEventCallbackLock) {
-            mDrmEventCallback = new Pair<Executor, DrmEventCallback>(executor, eventCallback);
-        }
-    }
-
-    /**
-     * Clear the {@link DrmEventCallback}.
-     *
-     * This is a synchronous call.
-     */
-    public void clearDrmEventCallback() {
-        synchronized (mDrmEventCallbackLock) {
-            mDrmEventCallback = null;
-        }
-    }
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * DRM preparation has succeeded.
-     */
-    public static final int PREPARE_DRM_STATUS_SUCCESS = 0;
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * The device required DRM provisioning but couldn't reach the provisioning server.
-     */
-    public static final int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR = 1;
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * The device required DRM provisioning but the provisioning server denied the request.
-     */
-    public static final int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR = 2;
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * The DRM preparation has failed .
-     */
-    public static final int PREPARE_DRM_STATUS_PREPARATION_ERROR = 3;
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * The crypto scheme UUID is not supported by the device.
-     */
-    public static final int PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME = 4;
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * The hardware resources are not available, due to being in use.
-     */
-    public static final int PREPARE_DRM_STATUS_RESOURCE_BUSY = 5;
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * Restoring persisted offline keys failed.
-     */
-    public static final int PREPARE_DRM_STATUS_RESTORE_ERROR = 6;
-
-    /**
-     * A status code for {@link DrmEventCallback#onDrmPrepared} listener.
-     * <p>
-     *
-     * Error during key request/response exchange with license server.
-     */
-    public static final int PREPARE_DRM_STATUS_KEY_EXCHANGE_ERROR = 7;
-
-    /** @hide */
-    @IntDef(flag = false, prefix = "PREPARE_DRM_STATUS", value = {
-        PREPARE_DRM_STATUS_SUCCESS,
-        PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR,
-        PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR,
-        PREPARE_DRM_STATUS_PREPARATION_ERROR,
-        PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME,
-        PREPARE_DRM_STATUS_RESOURCE_BUSY,
-        PREPARE_DRM_STATUS_RESTORE_ERROR,
-        PREPARE_DRM_STATUS_KEY_EXCHANGE_ERROR,
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface PrepareDrmStatusCode {}
-
-    /** @hide */
-    @IntDef({
-        MediaDrm.KEY_TYPE_STREAMING,
-        MediaDrm.KEY_TYPE_OFFLINE,
-        MediaDrm.KEY_TYPE_RELEASE,
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface MediaDrmKeyType {}
-
-    /** @hide */
-    @StringDef({
-        MediaDrm.PROPERTY_VENDOR,
-        MediaDrm.PROPERTY_VERSION,
-        MediaDrm.PROPERTY_DESCRIPTION,
-        MediaDrm.PROPERTY_ALGORITHMS,
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface MediaDrmStringProperty {}
-
-    /**
-     * Retrieves the DRM Info associated with the given source
-     *
-     * @param dsd The DRM protected data source
-     *
-     * @throws IllegalStateException if called before being prepared
-     * @hide
-     */
-    @TestApi
-    public DrmInfo getDrmInfo(@NonNull DataSourceDesc dsd) {
-        final SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo != null) {
-            DrmInfo drmInfo = null;
-
-            // there is not much point if the app calls getDrmInfo within an OnDrmInfoListener;
-            // regardless below returns drmInfo anyway instead of raising an exception
-            synchronized (sourceInfo) {
-                if (!sourceInfo.mDrmInfoResolved && sourceInfo.mDrmInfo == null) {
-                    final String msg = "The Player has not been prepared yet";
-                    Log.v(TAG, msg);
-                    throw new IllegalStateException(msg);
-                }
-
-                if (sourceInfo.mDrmInfo != null) {
-                    drmInfo  = sourceInfo.mDrmInfo.makeCopy();
-                }
-            }   // synchronized
-
-            return drmInfo;
-        }
-        return null;
-    }
-
-    /**
-     * Prepares the DRM for the given data source
-     * <p>
-     * If {@link DrmEventCallback} is registered, it will be called during
-     * preparation to allow configuration of the DRM properties before opening the
-     * DRM session. It should be used only for a series of
-     * {@link #getDrmPropertyString(DataSourceDesc, String)} and
-     * {@link #setDrmPropertyString(DataSourceDesc, String, String)} calls
-     * and refrain from any lengthy operation.
-     * <p>
-     * If the device has not been provisioned before, this call also provisions the device
-     * which involves accessing the provisioning server and can take a variable time to
-     * complete depending on the network connectivity.
-     * When needed, the provisioning will be launched  in the background.
-     * The listener {@link DrmEventCallback#onDrmPrepared}
-     * will be called when provisioning and preparation are finished. The application should
-     * check the status code returned with {@link DrmEventCallback#onDrmPrepared} to proceed.
-     * <p>
-     * The registered {@link DrmEventCallback#onDrmPrepared} is called to indicate the DRM
-     * session being ready. The application should not make any assumption about its call
-     * sequence (e.g., before or after prepareDrm returns).
-     * <p>
-     *
-     * @param dsd The DRM protected data source
-     *
-     * @param uuid The UUID of the crypto scheme. If not known beforehand, it can be retrieved
-     * from the source listening to {@link DrmEventCallback#onDrmInfo}.
-     *
-     * @return a token which can be used to cancel the operation later with {@link #cancelCommand}.
-     * @hide
-     */
-    // This is an asynchronous call.
-    @TestApi
-    public @NonNull Object prepareDrm(@NonNull DataSourceDesc dsd, @NonNull UUID uuid) {
-        return addTask(newPrepareDrmTask(dsd, uuid));
-    }
-
-    private Task newPrepareDrmTask(DataSourceDesc dsd, UUID uuid) {
-        return new Task(CALL_COMPLETED_PREPARE_DRM, true) {
-            @Override
-            void process() {
-                final SourceInfo sourceInfo = getSourceInfo(dsd);
-                int status = PREPARE_DRM_STATUS_PREPARATION_ERROR;
-                boolean finishPrepare = true;
-
-                if (sourceInfo == null) {
-                    Log.e(TAG, "prepareDrm(): DataSource not found.");
-                } else if (sourceInfo.mDrmInfo == null) {
-                    // only allowing if tied to a protected source;
-                    // might relax for releasing offline keys
-                    Log.e(TAG, "prepareDrm(): Wrong usage: The player must be prepared and "
-                            + "DRM info be retrieved before this call.");
-                } else {
-                    status = PREPARE_DRM_STATUS_SUCCESS;
-                }
-
-                try {
-                    if (status == PREPARE_DRM_STATUS_SUCCESS) {
-                        sourceInfo.mDrmHandle.prepare(uuid);
-                    }
-                } catch (ResourceBusyException e) {
-                    status = PREPARE_DRM_STATUS_RESOURCE_BUSY;
-                } catch (UnsupportedSchemeException e) {
-                    status = PREPARE_DRM_STATUS_UNSUPPORTED_SCHEME;
-                } catch (NotProvisionedException e) {
-                    Log.w(TAG, "prepareDrm: NotProvisionedException");
-
-                    // handle provisioning internally; it'll reset mPrepareDrmInProgress
-                    status = sourceInfo.mDrmHandle.handleProvisioninig(uuid, mTaskId);
-
-                    if (status == PREPARE_DRM_STATUS_SUCCESS) {
-                        // License will be setup in provisioning
-                        finishPrepare = false;
-                    } else {
-                        synchronized (sourceInfo.mDrmHandle) {
-                            sourceInfo.mDrmHandle.cleanDrmObj();
-                        }
-
-                        switch (status) {
-                            case PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR:
-                                Log.e(TAG, "prepareDrm: Provisioning was required but failed "
-                                        + "due to a network error.");
-                                break;
-
-                            case PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR:
-                                Log.e(TAG, "prepareDrm: Provisioning was required but the request "
-                                        + "was denied by the server.");
-                                break;
-
-                            case PREPARE_DRM_STATUS_PREPARATION_ERROR:
-                            default:
-                                Log.e(TAG, "prepareDrm: Post-provisioning preparation failed.");
-                                break;
-                        }
-                    }
-                } catch (Exception e) {
-                    status = PREPARE_DRM_STATUS_PREPARATION_ERROR;
-                }
-
-                if (finishPrepare) {
-                    sourceInfo.mDrmHandle.finishPrepare(status);
-                    synchronized (mTaskLock) {
-                        mCurrentTask = null;
-                        processPendingTask_l();
-                    }
-                }
-
-            }
-        };
-    }
-
-    /**
-     * Releases the DRM session for the given data source
-     * <p>
-     * The player has to have an active DRM session and be in stopped, or prepared
-     * state before this call is made.
-     * A {@link #reset()} call will release the DRM session implicitly.
-     *
-     * @param dsd The DRM protected data source
-     *
-     * @throws NoDrmSchemeException if there is no active DRM session to release
-     * @hide
-     */
-    // This is a synchronous call.
-    @TestApi
-    public void releaseDrm(@NonNull DataSourceDesc dsd)
-            throws NoDrmSchemeException {
-        final SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo != null) {
-            sourceInfo.mDrmHandle.release();
-        }
-    }
-
-    private native void native_releaseDrm(long mSrcId);
-
-    /**
-     * A key request/response exchange occurs between the app and a license server
-     * to obtain or release keys used to decrypt the given data source.
-     * <p>
-     * {@code getDrmKeyRequest()} is used to obtain an opaque key request byte array that is
-     * delivered to the license server.  The opaque key request byte array is returned
-     * in KeyRequest.data.  The recommended URL to deliver the key request to is
-     * returned in {@code KeyRequest.defaultUrl}.
-     * <p>
-     * After the app has received the key request response from the server,
-     * it should deliver to the response to the DRM engine plugin using the method
-     * {@link #provideDrmKeyResponse(DataSourceDesc, byte[], byte[])}.
-     *
-     * @param dsd the DRM protected data source
-     *
-     * @param keySetId is the key-set identifier of the offline keys being released when keyType is
-     * {@link MediaDrm#KEY_TYPE_RELEASE}. It should be set to null for other key requests, when
-     * keyType is {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}.
-     *
-     * @param initData is the container-specific initialization data when the keyType is
-     * {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}. Its meaning is
-     * interpreted based on the mime type provided in the mimeType parameter.  It could
-     * contain, for example, the content ID, key ID or other data obtained from the content
-     * metadata that is required in generating the key request.
-     * When the keyType is {@link MediaDrm#KEY_TYPE_RELEASE}, it should be set to null.
-     *
-     * @param mimeType identifies the mime type of the content
-     *
-     * @param keyType specifies the type of the request. The request may be to acquire
-     * keys for streaming, {@link MediaDrm#KEY_TYPE_STREAMING}, or for offline content
-     * {@link MediaDrm#KEY_TYPE_OFFLINE}, or to release previously acquired
-     * keys ({@link MediaDrm#KEY_TYPE_RELEASE}), which are identified by a keySetId.
-     *
-     * @param optionalParameters are included in the key request message to
-     * allow a client application to provide additional message parameters to the server.
-     * This may be {@code null} if no additional parameters are to be sent.
-     *
-     * @throws NoDrmSchemeException if there is no active DRM session
-     * @hide
-     */
-    @TestApi
-    public MediaDrm.KeyRequest getDrmKeyRequest(
-            @NonNull DataSourceDesc dsd,
-            @Nullable byte[] keySetId, @Nullable byte[] initData,
-            @Nullable String mimeType, @MediaDrmKeyType int keyType,
-            @Nullable Map<String, String> optionalParameters)
-            throws NoDrmSchemeException {
-        Log.v(TAG, "getDrmKeyRequest: " +
-                " keySetId: " + keySetId + " initData:" + initData + " mimeType: " + mimeType +
-                " keyType: " + keyType + " optionalParameters: " + optionalParameters);
-
-        final SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo != null) {
-            return sourceInfo.mDrmHandle.getDrmKeyRequest(
-                    keySetId, initData, mimeType, keyType, optionalParameters);
-        }
-        return null;
-    }
-
-    /**
-     * A key response is received from the license server by the app for the given DRM protected
-     * data source, then provided to the DRM engine plugin using {@code provideDrmKeyResponse}.
-     * <p>
-     * When the response is for an offline key request, a key-set identifier is returned that
-     * can be used to later restore the keys to a new session with the method
-     * {@link #restoreDrmKeys(DataSourceDesc, byte[])}.
-     * When the response is for a streaming or release request, null is returned.
-     *
-     * @param dsd the DRM protected data source
-     *
-     * @param keySetId When the response is for a release request, keySetId identifies the saved
-     * key associated with the release request (i.e., the same keySetId passed to the earlier
-     * {@link # getDrmKeyRequest(DataSourceDesc, byte[], byte[], String, int, Map)} call).
-     * It MUST be null when the response is for either streaming or offline key requests.
-     *
-     * @param response the byte array response from the server
-     *
-     * @throws NoDrmSchemeException if there is no active DRM session
-     * @throws DeniedByServerException if the response indicates that the
-     * server rejected the request
-     * @hide
-     */
-    // This is a synchronous call.
-    @TestApi
-    public byte[] provideDrmKeyResponse(
-            @NonNull DataSourceDesc dsd,
-            @Nullable byte[] keySetId, @NonNull byte[] response)
-            throws NoDrmSchemeException, DeniedByServerException {
-        Log.v(TAG, "provideDrmKeyResponse: keySetId: " + keySetId + " response: " + response);
-
-        final SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo != null) {
-            return sourceInfo.mDrmHandle.provideDrmKeyResponse(keySetId, response);
-        }
-        return null;
-    }
-
-    /**
-     * Restore persisted offline keys into a new session for the given DRM protected data source.
-     * {@code keySetId} identifies the keys to load, obtained from a prior call to
-     * {@link #provideDrmKeyResponse(DataSourceDesc, byte[], byte[])}.
-     *
-     * @param dsd the DRM protected data source
-     *
-     * @param keySetId identifies the saved key set to restore
-     *
-     * @throws NoDrmSchemeException if there is no active DRM session
-     * @hide
-     */
-    // This is a synchronous call.
-    @TestApi
-    public void restoreDrmKeys(
-            @NonNull DataSourceDesc dsd,
-            @NonNull byte[] keySetId)
-            throws NoDrmSchemeException {
-        Log.v(TAG, "restoreDrmKeys: keySetId: " + keySetId);
-
-        final SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo != null) {
-            sourceInfo.mDrmHandle.restoreDrmKeys(keySetId);
-        }
-    }
-
-    /**
-     * Read a DRM engine plugin String property value, given the DRM protected data source
-     * and property name string.
-     *
-     * @param dsd the DRM protected data source
-     *
-     * @param propertyName the property name
-     *
-     * Standard fields names are:
-     * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
-     * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
-     *
-     * @throws NoDrmSchemeException if there is no active DRM session
-     * @hide
-     */
-    @TestApi
-    public String getDrmPropertyString(
-            @NonNull DataSourceDesc dsd,
-            @NonNull @MediaDrmStringProperty String propertyName)
-            throws NoDrmSchemeException {
-        Log.v(TAG, "getDrmPropertyString: propertyName: " + propertyName);
-
-        final SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo != null) {
-            return sourceInfo.mDrmHandle.getDrmPropertyString(propertyName);
-        }
-        return null;
-    }
-
-    /**
-     * Set a DRM engine plugin String property value for the given data source.
-     *
-     * @param dsd the DRM protected data source
-     * @param propertyName the property name
-     * @param value the property value
-     *
-     * Standard fields names are:
-     * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
-     * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
-     *
-     * @throws NoDrmSchemeException if there is no active DRM session
-     * @hide
-     */
-    // This is a synchronous call.
-    @TestApi
-    public void setDrmPropertyString(
-            @NonNull DataSourceDesc dsd,
-            @NonNull @MediaDrmStringProperty String propertyName, @NonNull String value)
-            throws NoDrmSchemeException {
-        // TODO: this implementation only works when dsd is the only data source
-        Log.v(TAG, "setDrmPropertyString: propertyName: " + propertyName + " value: " + value);
-
-        final SourceInfo sourceInfo = getSourceInfo(dsd);
-        if (sourceInfo != null) {
-            sourceInfo.mDrmHandle.setDrmPropertyString(propertyName, value);
-        }
-    }
-
-    /**
-     * Encapsulates the DRM properties of the source.
-     */
-    public static final class DrmInfo {
-        private Map<UUID, byte[]> mMapPssh;
-        private UUID[] mSupportedSchemes;
-
-        /**
-         * Returns the PSSH info of the data source for each supported DRM scheme.
-         */
-        public @NonNull Map<UUID, byte[]> getPssh() {
-            return mMapPssh;
-        }
-
-        /**
-         * Returns the intersection of the data source and the device DRM schemes.
-         * It effectively identifies the subset of the source's DRM schemes which
-         * are supported by the device too.
-         */
-        public @NonNull List<UUID> getSupportedSchemes() {
-            return Arrays.asList(mSupportedSchemes);
-        }
-
-        private DrmInfo(Map<UUID, byte[]> pssh, UUID[] supportedSchemes) {
-            mMapPssh = pssh;
-            mSupportedSchemes = supportedSchemes;
-        }
-
-        private static DrmInfo create(PlayerMessage msg) {
-            Log.v(TAG, "DrmInfo.create(" + msg + ")");
-
-            Iterator<Value> in = msg.getValuesList().iterator();
-            byte[] pssh = in.next().getBytesValue().toByteArray();
-
-            Log.v(TAG, "DrmInfo.create() PSSH: " + DrmInfo.arrToHex(pssh));
-            Map<UUID, byte[]> mapPssh = DrmInfo.parsePSSH(pssh, pssh.length);
-            Log.v(TAG, "DrmInfo.create() PSSH: " + mapPssh);
-
-            int supportedDRMsCount = in.next().getInt32Value();
-            UUID[] supportedSchemes = new UUID[supportedDRMsCount];
-            for (int i = 0; i < supportedDRMsCount; i++) {
-                byte[] uuid = new byte[16];
-                in.next().getBytesValue().copyTo(uuid, 0);
-
-                supportedSchemes[i] = DrmInfo.bytesToUUID(uuid);
-
-                Log.v(TAG, "DrmInfo() supportedScheme[" + i + "]: " + supportedSchemes[i]);
-            }
-
-            Log.v(TAG, "DrmInfo.create() psshsize: " + pssh.length
-                    + " supportedDRMsCount: " + supportedDRMsCount);
-            return new DrmInfo(mapPssh, supportedSchemes);
-        }
-
-        private DrmInfo makeCopy() {
-            return new DrmInfo(this.mMapPssh, this.mSupportedSchemes);
-        }
-
-        private static String arrToHex(byte[] bytes) {
-            String out = "0x";
-            for (int i = 0; i < bytes.length; i++) {
-                out += String.format("%02x", bytes[i]);
-            }
-
-            return out;
-        }
-
-        private static UUID bytesToUUID(byte[] uuid) {
-            long msb = 0, lsb = 0;
-            for (int i = 0; i < 8; i++) {
-                msb |= (((long) uuid[i]     & 0xff) << (8 * (7 - i)));
-                lsb |= (((long) uuid[i + 8] & 0xff) << (8 * (7 - i)));
-            }
-
-            return new UUID(msb, lsb);
-        }
-
-        private static Map<UUID, byte[]> parsePSSH(byte[] pssh, int psshsize) {
-            Map<UUID, byte[]> result = new HashMap<UUID, byte[]>();
-
-            final int uuidSize = 16;
-            final int dataLenSize = 4;
-
-            int len = psshsize;
-            int numentries = 0;
-            int i = 0;
-
-            while (len > 0) {
-                if (len < uuidSize) {
-                    Log.w(TAG, String.format("parsePSSH: len is too short to parse "
-                                             + "UUID: (%d < 16) pssh: %d", len, psshsize));
-                    return null;
-                }
-
-                byte[] subset = Arrays.copyOfRange(pssh, i, i + uuidSize);
-                UUID uuid = bytesToUUID(subset);
-                i += uuidSize;
-                len -= uuidSize;
-
-                // get data length
-                if (len < 4) {
-                    Log.w(TAG, String.format("parsePSSH: len is too short to parse "
-                                             + "datalen: (%d < 4) pssh: %d", len, psshsize));
-                    return null;
-                }
-
-                subset = Arrays.copyOfRange(pssh, i, i + dataLenSize);
-                int datalen = (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN)
-                        ? ((subset[3] & 0xff) << 24) | ((subset[2] & 0xff) << 16)
-                        | ((subset[1] & 0xff) <<  8) |  (subset[0] & 0xff)        :
-                        ((subset[0] & 0xff) << 24) | ((subset[1] & 0xff) << 16)
-                        | ((subset[2] & 0xff) <<  8) |  (subset[3] & 0xff);
-                i += dataLenSize;
-                len -= dataLenSize;
-
-                if (len < datalen) {
-                    Log.w(TAG, String.format("parsePSSH: len is too short to parse "
-                                             + "data: (%d < %d) pssh: %d", len, datalen, psshsize));
-                    return null;
-                }
-
-                byte[] data = Arrays.copyOfRange(pssh, i, i + datalen);
-
-                // skip the data
-                i += datalen;
-                len -= datalen;
-
-                Log.v(TAG, String.format("parsePSSH[%d]: <%s, %s> pssh: %d",
-                                         numentries, uuid, arrToHex(data), psshsize));
-                numentries++;
-                result.put(uuid, data);
-            }
-
-            return result;
-        }
-    };  // DrmInfo
-
-    /**
-     * Thrown when a DRM method is called when there is no active DRM session.
-     * Extends MediaDrm.MediaDrmException
-     */
-    public static final class NoDrmSchemeException extends MediaDrmException {
-        public NoDrmSchemeException(@Nullable String detailMessage) {
-            super(detailMessage);
-        }
-    }
-
-    private native void native_prepareDrm(
-            long srcId, @NonNull byte[] uuid, @NonNull byte[] drmSessionId);
-
-    // Instantiated from the native side
-    @SuppressWarnings("unused")
-    private static class StreamEventCallback extends AudioTrack.StreamEventCallback {
-        public long mJAudioTrackPtr;
-        public long mNativeCallbackPtr;
-        public long mUserDataPtr;
-
-        StreamEventCallback(long jAudioTrackPtr, long nativeCallbackPtr, long userDataPtr) {
-            super();
-            mJAudioTrackPtr = jAudioTrackPtr;
-            mNativeCallbackPtr = nativeCallbackPtr;
-            mUserDataPtr = userDataPtr;
-        }
-
-        @Override
-        public void onTearDown(AudioTrack track) {
-            native_stream_event_onTearDown(mNativeCallbackPtr, mUserDataPtr);
-        }
-
-        @Override
-        public void onPresentationEnded(AudioTrack track) {
-            native_stream_event_onStreamPresentationEnd(mNativeCallbackPtr, mUserDataPtr);
-        }
-
-        @Override
-        public void onDataRequest(AudioTrack track, int size) {
-            native_stream_event_onStreamDataRequest(
-                    mJAudioTrackPtr, mNativeCallbackPtr, mUserDataPtr);
-        }
-    }
-
-    /**
-     * Returns a byte[] containing the remainder of 'in', closing it when done.
-     */
-    private static byte[] readInputStreamFully(InputStream in) throws IOException {
-        try {
-            return readInputStreamFullyNoClose(in);
-        } finally {
-            in.close();
-        }
-    }
-
-    /**
-     * Returns a byte[] containing the remainder of 'in'.
-     */
-    private static byte[] readInputStreamFullyNoClose(InputStream in) throws IOException {
-        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
-        byte[] buffer = new byte[1024];
-        int count;
-        while ((count = in.read(buffer)) != -1) {
-            bytes.write(buffer, 0, count);
-        }
-        return bytes.toByteArray();
-    }
-
-    private static byte[] getByteArrayFromUUID(@NonNull UUID uuid) {
-        long msb = uuid.getMostSignificantBits();
-        long lsb = uuid.getLeastSignificantBits();
-
-        byte[] uuidBytes = new byte[16];
-        for (int i = 0; i < 8; ++i) {
-            uuidBytes[i] = (byte) (msb >>> (8 * (7 - i)));
-            uuidBytes[8 + i] = (byte) (lsb >>> (8 * (7 - i)));
-        }
-
-        return uuidBytes;
-    }
-
-    private static class TimedTextUtil {
-        // These keys must be in sync with the keys in TextDescription2.h
-        private static final int KEY_START_TIME                     = 7; // int
-        private static final int KEY_STRUCT_TEXT_POS               = 14; // TextPos
-        private static final int KEY_STRUCT_TEXT                   = 16; // Text
-        private static final int KEY_GLOBAL_SETTING               = 101;
-        private static final int KEY_LOCAL_SETTING                = 102;
-
-        private static TimedText parsePlayerMessage(PlayerMessage playerMsg) {
-            if (playerMsg.getValuesCount() == 0) {
-                return null;
-            }
-
-            String textChars = null;
-            Rect textBounds = null;
-            Iterator<Value> in = playerMsg.getValuesList().iterator();
-            int type = in.next().getInt32Value();
-            if (type == KEY_LOCAL_SETTING) {
-                type = in.next().getInt32Value();
-                if (type != KEY_START_TIME) {
-                    return null;
-                }
-                int startTimeMs = in.next().getInt32Value();
-
-                type = in.next().getInt32Value();
-                if (type != KEY_STRUCT_TEXT) {
-                    return null;
-                }
-
-                byte[] text = in.next().getBytesValue().toByteArray();
-                if (text == null || text.length == 0) {
-                    textChars = null;
-                } else {
-                    textChars = new String(text);
-                }
-
-            } else if (type != KEY_GLOBAL_SETTING) {
-                Log.w(TAG, "Invalid timed text key found: " + type);
-                return null;
-            }
-            if (in.hasNext()) {
-                type = in.next().getInt32Value();
-                if (type == KEY_STRUCT_TEXT_POS) {
-                    int top = in.next().getInt32Value();
-                    int left = in.next().getInt32Value();
-                    int bottom = in.next().getInt32Value();
-                    int right = in.next().getInt32Value();
-                    textBounds = new Rect(left, top, right, bottom);
-                }
-            }
-            return null;
-            /* TimedText c-tor usage is temporarily commented out.
-             * TODO(b/117527789): use SUBTITLE path for MEDIA_MIMETYPE_TEXT_3GPP track
-             *                    and remove TimedText path from MediaPlayer2.
-            return new TimedText(textChars, textBounds);
-            */
-        }
-    }
-
-    private Object addTask(Task task) {
-        synchronized (mTaskLock) {
-            mPendingTasks.add(task);
-            processPendingTask_l();
-        }
-        return task;
-    }
-
-    @GuardedBy("mTaskLock")
-    private void processPendingTask_l() {
-        if (mCurrentTask != null) {
-            return;
-        }
-        if (!mPendingTasks.isEmpty()) {
-            Task task = mPendingTasks.remove(0);
-            mCurrentTask = task;
-            mTaskHandler.post(task);
-        }
-    }
-
-    private abstract class Task implements Runnable {
-        final long mTaskId = mTaskIdGenerator.getAndIncrement();
-        private final int mMediaCallType;
-        private final boolean mNeedToWaitForEventToComplete;
-        private DataSourceDesc mDSD;
-
-        Task(int mediaCallType, boolean needToWaitForEventToComplete) {
-            mMediaCallType = mediaCallType;
-            mNeedToWaitForEventToComplete = needToWaitForEventToComplete;
-        }
-
-        abstract void process() throws IOException, NoDrmSchemeException;
-
-        @Override
-        public void run() {
-            int status = CALL_STATUS_NO_ERROR;
-            try {
-                if (mMediaCallType != CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED
-                        && getState() == PLAYER_STATE_ERROR) {
-                    status = CALL_STATUS_INVALID_OPERATION;
-                } else {
-                    if (mMediaCallType == CALL_COMPLETED_SEEK_TO) {
-                        synchronized (mTaskLock) {
-                            if (!mPendingTasks.isEmpty()) {
-                                Task nextTask = mPendingTasks.get(0);
-                                if (nextTask.mMediaCallType == mMediaCallType) {
-                                    throw new CommandSkippedException(
-                                            "consecutive seekTo is skipped except last one");
-                                }
-                            }
-                        }
-                    }
-                    process();
-                }
-            } catch (IllegalStateException e) {
-                status = CALL_STATUS_INVALID_OPERATION;
-            } catch (IllegalArgumentException e) {
-                status = CALL_STATUS_BAD_VALUE;
-            } catch (SecurityException e) {
-                status = CALL_STATUS_PERMISSION_DENIED;
-            } catch (IOException e) {
-                status = CALL_STATUS_ERROR_IO;
-            } catch (NoDrmSchemeException e) {
-                status = CALL_STATUS_NO_DRM_SCHEME;
-            } catch (CommandSkippedException e) {
-                status = CALL_STATUS_SKIPPED;
-            } catch (Exception e) {
-                status = CALL_STATUS_ERROR_UNKNOWN;
-            }
-            mDSD = getCurrentDataSource();
-
-            if (mMediaCallType != CALL_COMPLETED_SEEK_TO) {
-                synchronized (mTaskLock) {
-                    mIsPreviousCommandSeekTo = false;
-                }
-            }
-
-            // TODO: Make native implementations asynchronous and let them send notifications.
-            if (!mNeedToWaitForEventToComplete || status != CALL_STATUS_NO_ERROR) {
-
-                sendCompleteNotification(status);
-
-                synchronized (mTaskLock) {
-                    mCurrentTask = null;
-                    processPendingTask_l();
-                }
-            }
-        }
-
-        private void sendCompleteNotification(int status) {
-            // In {@link #notifyWhenCommandLabelReached} case, a separate callback
-            // {@link #onCommandLabelReached} is already called in {@code process()}.
-            // CALL_COMPLETED_PREPARE_DRM is sent via DrmEventCallback#onDrmPrepared
-            if (mMediaCallType == CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED
-                    || mMediaCallType == CALL_COMPLETED_PREPARE_DRM) {
-                return;
-            }
-            sendEvent(new EventNotifier() {
-                @Override
-                public void notify(EventCallback callback) {
-                    callback.onCallCompleted(
-                            MediaPlayer2.this, mDSD, mMediaCallType, status);
-                }
-            });
-        }
-    };
-
-    private final class CommandSkippedException extends RuntimeException {
-        CommandSkippedException(String detailMessage) {
-            super(detailMessage);
-        }
-    };
-
-    // Modular DRM
-    private final Map<UUID, MediaDrm> mDrmObjs = Collections.synchronizedMap(new HashMap<>());
-    private class DrmHandle {
-
-        static final int PROVISION_TIMEOUT_MS = 60000;
-
-        final DataSourceDesc mDSD;
-        final long mSrcId;
-
-        //--- guarded by |this| start
-        MediaDrm mDrmObj;
-        byte[] mDrmSessionId;
-        UUID mActiveDrmUUID;
-        boolean mDrmConfigAllowed;
-        boolean mDrmProvisioningInProgress;
-        boolean mPrepareDrmInProgress;
-        Future<?> mProvisionResult;
-        DrmPreparationInfo mPrepareInfo;
-        //--- guarded by |this| end
-
-        DrmHandle(DataSourceDesc dsd, long srcId) {
-            mDSD = dsd;
-            mSrcId = srcId;
-        }
-
-        void prepare(UUID uuid) throws UnsupportedSchemeException,
-                ResourceBusyException, NotProvisionedException, InterruptedException,
-                ExecutionException, TimeoutException {
-            Log.v(TAG, "prepareDrm: uuid: " + uuid);
-
-            synchronized (this) {
-                if (mActiveDrmUUID != null) {
-                    final String msg = "prepareDrm(): Wrong usage: There is already "
-                            + "an active DRM scheme with " + uuid;
-                    Log.e(TAG, msg);
-                    throw new IllegalStateException(msg);
-                }
-
-                if (mPrepareDrmInProgress) {
-                    final String msg = "prepareDrm(): Wrong usage: There is already "
-                            + "a pending prepareDrm call.";
-                    Log.e(TAG, msg);
-                    throw new IllegalStateException(msg);
-                }
-
-                if (mDrmProvisioningInProgress) {
-                    final String msg = "prepareDrm(): Unexpectd: Provisioning already in progress";
-                    Log.e(TAG, msg);
-                    throw new IllegalStateException(msg);
-                }
-
-                // shouldn't need this; just for safeguard
-                cleanDrmObj();
-
-                mPrepareDrmInProgress = true;
-
-                try {
-                    // only creating the DRM object to allow pre-openSession configuration
-                    prepareDrm_createDrmStep(uuid);
-                } catch (Exception e) {
-                    Log.w(TAG, "prepareDrm(): Exception ", e);
-                    mPrepareDrmInProgress = false;
-                    throw e;
-                }
-
-                mDrmConfigAllowed = true;
-            }  // synchronized
-
-            // call the callback outside the lock
-            sendDrmEventWait(new DrmEventNotifier<Void>() {
-                @Override
-                public Void notifyWait(DrmEventCallback callback) {
-                    callback.onDrmConfig(MediaPlayer2.this, mDSD, mDrmObj);
-                    return null;
-                }
-            });
-
-            synchronized (this) {
-                mDrmConfigAllowed = false;
-                boolean earlyExit = false;
-
-                try {
-                    prepareDrm_openSessionStep(uuid);
-
-                    this.mActiveDrmUUID = uuid;
-                    mPrepareDrmInProgress = false;
-                } catch (IllegalStateException e) {
-                    final String msg = "prepareDrm(): Wrong usage: The player must be "
-                            + "in the prepared state to call prepareDrm().";
-                    Log.e(TAG, msg);
-                    earlyExit = true;
-                    mPrepareDrmInProgress = false;
-                    throw new IllegalStateException(msg);
-                } catch (NotProvisionedException e) {
-                    Log.w(TAG, "prepareDrm: NotProvisionedException", e);
-                    throw e;
-                } catch (Exception e) {
-                    Log.e(TAG, "prepareDrm: Exception " + e);
-                    earlyExit = true;
-                    mPrepareDrmInProgress = false;
-                    throw e;
-                } finally {
-                    if (earlyExit) {  // clean up object if didn't succeed
-                        cleanDrmObj();
-                    }
-                }  // finally
-            }  // synchronized
-        }
-
-        void prepareDrm_createDrmStep(UUID uuid)
-                throws UnsupportedSchemeException {
-            Log.v(TAG, "prepareDrm_createDrmStep: UUID: " + uuid);
-
-            try {
-                mDrmObj = mDrmObjs.computeIfAbsent(uuid, scheme -> {
-                    try {
-                        return new MediaDrm(scheme);
-                    } catch (UnsupportedSchemeException e) {
-                        throw new IllegalArgumentException(e);
-                    }
-                });
-                Log.v(TAG, "prepareDrm_createDrmStep: Created mDrmObj=" + mDrmObj);
-            } catch (Exception e) { // UnsupportedSchemeException
-                Log.e(TAG, "prepareDrm_createDrmStep: MediaDrm failed with " + e);
-                throw e;
-            }
-        }
-
-        void prepareDrm_openSessionStep(UUID uuid)
-                throws NotProvisionedException, ResourceBusyException {
-            Log.v(TAG, "prepareDrm_openSessionStep: uuid: " + uuid);
-
-            // TODO:
-            // don't need an open session for a future specialKeyReleaseDrm mode but we should do
-            // it anyway so it raises provisioning error if needed. We'd rather handle provisioning
-            // at prepareDrm/openSession rather than getDrmKeyRequest/provideDrmKeyResponse
-            try {
-                mDrmSessionId = mDrmObj.openSession();
-                Log.v(TAG, "prepareDrm_openSessionStep: mDrmSessionId=" + mDrmSessionId);
-
-                // Sending it down to native/mediaserver to create the crypto object
-                // This call could simply fail due to bad player state, e.g., after play().
-                final MediaPlayer2 mp2 = MediaPlayer2.this;
-                mp2.native_prepareDrm(mSrcId, getByteArrayFromUUID(uuid), mDrmSessionId);
-                Log.v(TAG, "prepareDrm_openSessionStep: native_prepareDrm/Crypto succeeded");
-
-            } catch (Exception e) { //ResourceBusyException, NotProvisionedException
-                Log.e(TAG, "prepareDrm_openSessionStep: open/crypto failed with " + e);
-                throw e;
-            }
-
-        }
-
-        int handleProvisioninig(UUID uuid, long taskId) {
-            synchronized (this) {
-                if (mDrmProvisioningInProgress) {
-                    Log.e(TAG, "handleProvisioninig: Unexpected mDrmProvisioningInProgress");
-                    return PREPARE_DRM_STATUS_PREPARATION_ERROR;
-                }
-
-                MediaDrm.ProvisionRequest provReq = mDrmObj.getProvisionRequest();
-                if (provReq == null) {
-                    Log.e(TAG, "handleProvisioninig: getProvisionRequest returned null.");
-                    return PREPARE_DRM_STATUS_PREPARATION_ERROR;
-                }
-
-                Log.v(TAG, "handleProvisioninig provReq "
-                        + " data: " + provReq.getData() + " url: " + provReq.getDefaultUrl());
-
-                // networking in a background thread
-                mDrmProvisioningInProgress = true;
-
-                mProvisionResult = sDrmThreadPool.submit(newProvisioningTask(uuid, taskId));
-
-                return PREPARE_DRM_STATUS_SUCCESS;
-            }
-        }
-
-        void provision(UUID uuid, long taskId) {
-
-            MediaDrm.ProvisionRequest provReq = mDrmObj.getProvisionRequest();
-            String urlStr = provReq.getDefaultUrl();
-            urlStr += "&signedRequest=" + new String(provReq.getData());
-            Log.v(TAG, "handleProvisioninig: Thread is initialised url: " + urlStr);
-
-            byte[] response = null;
-            boolean provisioningSucceeded = false;
-            int status = PREPARE_DRM_STATUS_PREPARATION_ERROR;
-            try {
-                URL url = new URL(urlStr);
-                final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
-                try {
-                    connection.setRequestMethod("POST");
-                    connection.setDoOutput(false);
-                    connection.setDoInput(true);
-                    connection.setConnectTimeout(PROVISION_TIMEOUT_MS);
-                    connection.setReadTimeout(PROVISION_TIMEOUT_MS);
-
-                    connection.connect();
-                    response = readInputStreamFully(connection.getInputStream());
-
-                    Log.v(TAG, "handleProvisioninig: Thread run: response " +
-                            response.length + " " + response);
-                } catch (Exception e) {
-                    status = PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR;
-                    Log.w(TAG, "handleProvisioninig: Thread run: connect " + e + " url: " + url);
-                } finally {
-                    connection.disconnect();
-                }
-            } catch (Exception e)   {
-                status = PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR;
-                Log.w(TAG, "handleProvisioninig: Thread run: openConnection " + e);
-            }
-
-            if (response != null) {
-                try {
-                    mDrmObj.provideProvisionResponse(response);
-                    Log.v(TAG, "handleProvisioninig: Thread run: " +
-                            "provideProvisionResponse SUCCEEDED!");
-
-                    provisioningSucceeded = true;
-                } catch (Exception e) {
-                    status = PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR;
-                    Log.w(TAG, "handleProvisioninig: Thread run: " +
-                            "provideProvisionResponse " + e);
-                }
-            }
-
-            boolean succeeded = false;
-
-            synchronized (this) {
-                // continuing with prepareDrm
-                if (provisioningSucceeded) {
-                    succeeded = resumePrepare(uuid);
-                    status = (succeeded) ?
-                            PREPARE_DRM_STATUS_SUCCESS :
-                            PREPARE_DRM_STATUS_PREPARATION_ERROR;
-                }
-                mDrmProvisioningInProgress = false;
-                mPrepareDrmInProgress = false;
-                if (!succeeded) {
-                    cleanDrmObj();  // cleaning up if it hasn't gone through while in the lock
-                }
-            }  // synchronized
-
-            // calling the callback outside the lock
-            finishPrepare(status);
-
-            synchronized (mTaskLock) {
-                if (mCurrentTask != null
-                        && mCurrentTask.mTaskId == taskId
-                        && mCurrentTask.mMediaCallType == CALL_COMPLETED_PREPARE_DRM
-                        && mCurrentTask.mNeedToWaitForEventToComplete) {
-                    mCurrentTask = null;
-                    processPendingTask_l();
-                }
-            }
-        }
-
-        Runnable newProvisioningTask(UUID uuid, long taskId) {
-            return new Runnable() {
-                @Override
-                public void run() {
-                    provision(uuid, taskId);
-                }
-            };
-        }
-
-        boolean resumePrepare(UUID uuid) {
-            Log.v(TAG, "resumePrepareDrm: uuid: " + uuid);
-
-            // mDrmLock is guaranteed to be held
-            boolean success = false;
-            try {
-                // resuming
-                prepareDrm_openSessionStep(uuid);
-
-                this.mActiveDrmUUID = uuid;
-
-                success = true;
-            } catch (Exception e) {
-                Log.w(TAG, "handleProvisioninig: Thread run native_prepareDrm resume failed:" + e);
-                // mDrmObj clean up is done by the caller
-            }
-
-            return success;
-        }
-
-        synchronized boolean setPreparationInfo(DrmPreparationInfo prepareInfo) {
-            if (prepareInfo == null || !prepareInfo.isValid() || mPrepareInfo != null) {
-                return false;
-            }
-            mPrepareInfo = prepareInfo;
-            return true;
-        }
-
-        void finishPrepare(int status) {
-            if (status != PREPARE_DRM_STATUS_SUCCESS) {
-                notifyPrepared(status, null);
-                return;
-            }
-
-            if (mPrepareInfo == null) {
-                // Deprecated: this can only happen when using MediaPlayer Version 1 APIs
-                notifyPrepared(status, null);
-                return;
-            }
-
-            final byte[] keySetId = mPrepareInfo.mKeySetId;
-            if (keySetId != null) {
-                try {
-                    mDrmObj.restoreKeys(mDrmSessionId, keySetId);
-                    notifyPrepared(PREPARE_DRM_STATUS_SUCCESS, keySetId);
-                } catch (Exception e) {
-                    notifyPrepared(PREPARE_DRM_STATUS_RESTORE_ERROR, keySetId);
-                }
-                return;
-            }
-
-            sDrmThreadPool.submit(newKeyExchangeTask());
-        }
-
-        Runnable newKeyExchangeTask() {
-            return new Runnable() {
-                @Override
-                public void run() {
-                    final byte[] initData = mPrepareInfo.mInitData;
-                    final String mimeType = mPrepareInfo.mMimeType;
-                    final int keyType = mPrepareInfo.mKeyType;
-                    final Map<String, String> optionalParams = mPrepareInfo.mOptionalParameters;
-                    byte[] keySetId = null;
-                    try {
-                        KeyRequest req;
-                        req = getDrmKeyRequest(null, initData, mimeType, keyType, optionalParams);
-                        byte[] response = sendDrmEventWait(new DrmEventNotifier<byte[]>() {
-                            @Override
-                            public byte[] notifyWait(DrmEventCallback callback) {
-                                final MediaPlayer2 mp = MediaPlayer2.this;
-                                return callback.onDrmKeyRequest(mp, mDSD, req);
-                            }
-                        });
-                        keySetId = provideDrmKeyResponse(null, response);
-                    } catch (Exception e) {
-                    }
-                    if (keySetId == null) {
-                        notifyPrepared(PREPARE_DRM_STATUS_KEY_EXCHANGE_ERROR, null);
-                    } else {
-                        notifyPrepared(PREPARE_DRM_STATUS_SUCCESS, keySetId);
-                    }
-                }
-            };
-        }
-
-        void notifyPrepared(final int status, byte[] keySetId) {
-
-            Message msg;
-            if (status == PREPARE_DRM_STATUS_SUCCESS) {
-                msg = mTaskHandler.obtainMessage(
-                        MEDIA_DRM_PREPARED, 0, 0, null);
-            } else {
-                msg = mTaskHandler.obtainMessage(
-                        MEDIA_ERROR, status, MEDIA_ERROR_UNKNOWN, null);
-            }
-            mTaskHandler.post(new Runnable() {
-                @Override
-                public void run() {
-                    mTaskHandler.handleMessage(msg, mSrcId);
-                }
-            });
-
-            sendDrmEvent(new DrmEventNotifier() {
-                @Override
-                public void notify(DrmEventCallback callback) {
-                    callback.onDrmPrepared(MediaPlayer2.this, mDSD, status,
-                            keySetId);
-                }
-            });
-
-        }
-
-        void cleanDrmObj() {
-            // the caller holds mDrmLock
-            Log.v(TAG, "cleanDrmObj: mDrmObj=" + mDrmObj + " mDrmSessionId=" + mDrmSessionId);
-
-            if (mDrmSessionId != null)    {
-                mDrmObj.closeSession(mDrmSessionId);
-                mDrmSessionId = null;
-            }
-        }
-
-        void release() throws NoDrmSchemeException {
-            synchronized (this) {
-                Log.v(TAG, "releaseDrm:");
-
-                if (mActiveDrmUUID == null) {
-                    Log.e(TAG, "releaseDrm(): No active DRM scheme to release.");
-                    throw new NoDrmSchemeException(
-                            "releaseDrm: No active DRM scheme to release.");
-                }
-
-                try {
-                    // we don't have the player's state in this layer. The below call raises
-                    // exception if we're in a non-stopped/prepared state.
-
-                    // for cleaning native/mediaserver crypto object
-                    native_releaseDrm(mSrcId);
-
-                    // for cleaning client-side MediaDrm object; only called if above has succeeded
-                    cleanDrmObj();
-
-                    this.mActiveDrmUUID = null;
-                } catch (IllegalStateException e) {
-                    Log.w(TAG, "releaseDrm: Exception ", e);
-                    throw new IllegalStateException(
-                            "releaseDrm: The player is not in a valid state.");
-                } catch (Exception e) {
-                    Log.e(TAG, "releaseDrm: Exception ", e);
-                }
-            }  // synchronized
-        }
-
-        void cleanup() {
-            synchronized (this) {
-                Log.v(TAG, "cleanupDrm: " +
-                        " mProvisioningTask=" + mProvisionResult +
-                        " mPrepareDrmInProgress=" + mPrepareDrmInProgress +
-                        " mActiveDrmScheme=" + mActiveDrmUUID);
-
-                if (mProvisionResult != null) {
-                    // timeout; relying on HttpUrlConnection
-                    try {
-                        mProvisionResult.get();
-                    }
-                    catch (InterruptedException | ExecutionException e) {
-                        Log.w(TAG, "resetDrmState: ProvThread.join Exception " + e);
-                    }
-                }
-
-                // set to false to avoid duplicate release calls
-                this.mActiveDrmUUID = null;
-
-                native_releaseDrm(mSrcId);
-                cleanDrmObj();
-            }   // synchronized
-        }
-
-        Runnable newCleanupTask() {
-            return new Runnable() {
-                @Override
-                public void run() {
-                    cleanup();
-                }
-            };
-        }
-
-        MediaDrm.KeyRequest getDrmKeyRequest(
-                byte[] keySetId, byte[] initData,
-                String mimeType, int keyType,
-                Map<String, String> optionalParameters)
-                throws NoDrmSchemeException {
-            synchronized (this) {
-                if (mActiveDrmUUID == null) {
-                    Log.e(TAG, "getDrmKeyRequest NoDrmSchemeException");
-                    throw new NoDrmSchemeException(
-                            "getDrmKeyRequest: Has to set a DRM scheme first.");
-                }
-
-                try {
-                    byte[] scope = (keyType != MediaDrm.KEY_TYPE_RELEASE) ?
-                            mDrmSessionId : // sessionId for KEY_TYPE_STREAMING/OFFLINE
-                            keySetId;                  // keySetId for KEY_TYPE_RELEASE
-
-                    HashMap<String, String> hmapOptionalParameters =
-                            (optionalParameters != null)
-                            ? new HashMap<String, String>(optionalParameters)
-                            : null;
-
-                    MediaDrm.KeyRequest request = mDrmObj.getKeyRequest(
-                            scope, initData, mimeType, keyType, hmapOptionalParameters);
-                    Log.v(TAG, "getDrmKeyRequest:   --> request: " + request);
-
-                    return request;
-
-                } catch (NotProvisionedException e) {
-                    Log.w(TAG, "getDrmKeyRequest NotProvisionedException: " +
-                            "Unexpected. Shouldn't have reached here.");
-                    throw new IllegalStateException("getDrmKeyRequest: provisioning error.");
-                } catch (Exception e) {
-                    Log.w(TAG, "getDrmKeyRequest Exception " + e);
-                    throw e;
-                }
-
-            }
-        }
-
-        byte[] provideDrmKeyResponse(byte[] keySetId, byte[] response)
-                throws NoDrmSchemeException, DeniedByServerException {
-            synchronized (this) {
-
-                if (mActiveDrmUUID == null) {
-                    Log.e(TAG, "getDrmKeyRequest NoDrmSchemeException");
-                    throw new NoDrmSchemeException(
-                            "getDrmKeyRequest: Has to set a DRM scheme first.");
-                }
-
-                try {
-                    byte[] scope = (keySetId == null) ?
-                                    mDrmSessionId : // sessionId for KEY_TYPE_STREAMING/OFFLINE
-                                    keySetId;                  // keySetId for KEY_TYPE_RELEASE
-
-                    byte[] keySetResult = mDrmObj.provideKeyResponse(scope, response);
-
-                    Log.v(TAG, "provideDrmKeyResponse: keySetId: " + keySetId
-                            + " response: " + response + " --> " + keySetResult);
-
-
-                    return keySetResult;
-
-                } catch (NotProvisionedException e) {
-                    Log.w(TAG, "provideDrmKeyResponse NotProvisionedException: " +
-                            "Unexpected. Shouldn't have reached here.");
-                    throw new IllegalStateException("provideDrmKeyResponse: " +
-                            "Unexpected provisioning error.");
-                } catch (Exception e) {
-                    Log.w(TAG, "provideDrmKeyResponse Exception " + e);
-                    throw e;
-                }
-            }
-        }
-
-        void restoreDrmKeys(byte[] keySetId)
-                throws NoDrmSchemeException {
-            synchronized (this) {
-                if (mActiveDrmUUID == null) {
-                    Log.w(TAG, "restoreDrmKeys NoDrmSchemeException");
-                    throw new NoDrmSchemeException(
-                            "restoreDrmKeys: Has to set a DRM scheme first.");
-                }
-
-                try {
-                    mDrmObj.restoreKeys(mDrmSessionId, keySetId);
-                } catch (Exception e) {
-                    Log.w(TAG, "restoreKeys Exception " + e);
-                    throw e;
-                }
-            }
-        }
-
-        String getDrmPropertyString(String propertyName)
-                throws NoDrmSchemeException {
-            String v;
-            synchronized (this) {
-
-                if (mActiveDrmUUID == null && !mDrmConfigAllowed) {
-                    Log.w(TAG, "getDrmPropertyString NoDrmSchemeException");
-                    throw new NoDrmSchemeException(
-                            "getDrmPropertyString: Has to prepareDrm() first.");
-                }
-
-                try {
-                    v = mDrmObj.getPropertyString(propertyName);
-                } catch (Exception e) {
-                    Log.w(TAG, "getDrmPropertyString Exception " + e);
-                    throw e;
-                }
-            }   // synchronized
-
-            Log.v(TAG, "getDrmPropertyString: propertyName: " + propertyName + " --> value: " + v);
-
-            return v;
-        }
-
-        void setDrmPropertyString(String propertyName, String value)
-                throws NoDrmSchemeException {
-            synchronized (this) {
-
-                if ( mActiveDrmUUID == null && !mDrmConfigAllowed ) {
-                    Log.w(TAG, "setDrmPropertyString NoDrmSchemeException");
-                    throw new NoDrmSchemeException(
-                            "setDrmPropertyString: Has to prepareDrm() first.");
-                }
-
-                try {
-                    mDrmObj.setPropertyString(propertyName, value);
-                } catch ( Exception e ) {
-                    Log.w(TAG, "setDrmPropertyString Exception " + e);
-                    throw e;
-                }
-            }
-        }
-
-    }
-
-    final class SourceInfo {
-        final DataSourceDesc mDSD;
-        final long mId = mSrcIdGenerator.getAndIncrement();
-        AtomicInteger mBufferedPercentage = new AtomicInteger(0);
-        boolean mClosed = false;
-        int mPrepareBarrier = 1;
-
-        // m*AsNextSource (below) only applies to pending data sources in the playlist;
-        // the meanings of mCurrentSourceInfo.{mStateAsNextSource,mPlayPendingAsNextSource}
-        // are undefined.
-        int mStateAsNextSource = NEXT_SOURCE_STATE_INIT;
-        boolean mPlayPendingAsNextSource = false;
-
-        // Modular DRM
-        final DrmHandle mDrmHandle;
-        DrmInfo mDrmInfo;
-        boolean mDrmInfoResolved;
-
-        SourceInfo(DataSourceDesc dsd) {
-            this.mDSD = dsd;
-            mDrmHandle = new DrmHandle(dsd, mId);
-        }
-
-        void close() {
-            synchronized (this) {
-                if (!mClosed) {
-                    if (mDSD != null) {
-                        mDSD.close();
-                    }
-                    mClosed = true;
-                }
-            }
-        }
-
-        @Override
-        public String toString() {
-            return String.format("%s(%d)", SourceInfo.class.getName(), mId);
-        }
-
-    }
-
-    private SourceInfo getSourceInfo(long srcId) {
-        synchronized (mSrcLock) {
-            if (isCurrentSource(srcId)) {
-                return mCurrentSourceInfo;
-            }
-            if (isNextSource(srcId)) {
-                return mNextSourceInfos.peek();
-            }
-        }
-        return null;
-    }
-
-    private SourceInfo getSourceInfo(DataSourceDesc dsd) {
-        synchronized (mSrcLock) {
-            if (isCurrentSource(dsd)) {
-                return mCurrentSourceInfo;
-            }
-            if (isNextSource(dsd)) {
-                return mNextSourceInfos.peek();
-            }
-        }
-        return null;
-    }
-
-    private boolean isCurrentSource(long srcId) {
-        synchronized (mSrcLock) {
-            return mCurrentSourceInfo != null && mCurrentSourceInfo.mId == srcId;
-        }
-    }
-
-    private boolean isCurrentSource(DataSourceDesc dsd) {
-        synchronized (mSrcLock) {
-            return mCurrentSourceInfo != null && mCurrentSourceInfo.mDSD == dsd;
-        }
-    }
-
-    private boolean isNextSource(long srcId) {
-        SourceInfo nextSourceInfo = mNextSourceInfos.peek();
-        return nextSourceInfo != null && nextSourceInfo.mId == srcId;
-    }
-
-    private boolean isNextSource(DataSourceDesc dsd) {
-        SourceInfo nextSourceInfo = mNextSourceInfos.peek();
-        return nextSourceInfo != null && nextSourceInfo.mDSD == dsd;
-    }
-
-    @GuardedBy("mSrcLock")
-    private void setCurrentSourceInfo_l(SourceInfo sourceInfo) {
-        cleanupSourceInfo(mCurrentSourceInfo);
-        mCurrentSourceInfo = sourceInfo;
-    }
-
-    @GuardedBy("mSrcLock")
-    private void clearNextSourceInfos_l() {
-        while (!mNextSourceInfos.isEmpty()) {
-            cleanupSourceInfo(mNextSourceInfos.poll());
-        }
-    }
-
-    private void cleanupSourceInfo(SourceInfo sourceInfo) {
-        if (sourceInfo != null) {
-            sourceInfo.close();
-            Runnable task = sourceInfo.mDrmHandle.newCleanupTask();
-            sDrmThreadPool.submit(task);
-        }
-    }
-
-    private void clearSourceInfos() {
-        synchronized (mSrcLock) {
-            setCurrentSourceInfo_l(null);
-            clearNextSourceInfos_l();
-        }
-    }
-
-    public static final class MetricsConstants {
-        private MetricsConstants() {}
-
-        /**
-         * Key to extract the MIME type of the video track
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is a String.
-         */
-        public static final String MIME_TYPE_VIDEO = "android.media.mediaplayer.video.mime";
-
-        /**
-         * Key to extract the codec being used to decode the video track
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is a String.
-         */
-        public static final String CODEC_VIDEO = "android.media.mediaplayer.video.codec";
-
-        /**
-         * Key to extract the width (in pixels) of the video track
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is an integer.
-         */
-        public static final String WIDTH = "android.media.mediaplayer.width";
-
-        /**
-         * Key to extract the height (in pixels) of the video track
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is an integer.
-         */
-        public static final String HEIGHT = "android.media.mediaplayer.height";
-
-        /**
-         * Key to extract the count of video frames played
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is an integer.
-         */
-        public static final String FRAMES = "android.media.mediaplayer.frames";
-
-        /**
-         * Key to extract the count of video frames dropped
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is an integer.
-         */
-        public static final String FRAMES_DROPPED = "android.media.mediaplayer.dropped";
-
-        /**
-         * Key to extract the MIME type of the audio track
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is a String.
-         */
-        public static final String MIME_TYPE_AUDIO = "android.media.mediaplayer.audio.mime";
-
-        /**
-         * Key to extract the codec being used to decode the audio track
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is a String.
-         */
-        public static final String CODEC_AUDIO = "android.media.mediaplayer.audio.codec";
-
-        /**
-         * Key to extract the duration (in milliseconds) of the
-         * media being played
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is a long.
-         */
-        public static final String DURATION = "android.media.mediaplayer.durationMs";
-
-        /**
-         * Key to extract the playing time (in milliseconds) of the
-         * media being played
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is a long.
-         */
-        public static final String PLAYING = "android.media.mediaplayer.playingMs";
-
-        /**
-         * Key to extract the count of errors encountered while
-         * playing the media
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is an integer.
-         */
-        public static final String ERRORS = "android.media.mediaplayer.err";
-
-        /**
-         * Key to extract an (optional) error code detected while
-         * playing the media
-         * from the {@link MediaPlayer2#getMetrics} return value.
-         * The value is an integer.
-         */
-        public static final String ERROR_CODE = "android.media.mediaplayer.errcode";
-
-    }
-
-    private void keepAudioSessionIdAlive(int sessionId) {
-        synchronized (mSessionIdLock) {
-            if (mDummyAudioTrack != null) {
-                if (mDummyAudioTrack.getAudioSessionId() == sessionId) {
-                    return;
-                }
-                mDummyAudioTrack.release();
-            }
-            // TODO: parameters can be optimized
-            mDummyAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
-                    AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, 2,
-                    AudioTrack.MODE_STATIC, sessionId);
-        }
-    }
-
-    private void keepAudioSessionIdAlive(AudioTrack at) {
-        synchronized (mSessionIdLock) {
-            if (mDummyAudioTrack != null) {
-                if (mDummyAudioTrack.getAudioSessionId() == at.getAudioSessionId()) {
-                    at.release();
-                    return;
-                }
-                mDummyAudioTrack.release();
-            }
-            mDummyAudioTrack = at;
-        }
-    }
-}
diff --git a/media/apex/java/android/media/MediaPlayer2Utils.java b/media/apex/java/android/media/MediaPlayer2Utils.java
deleted file mode 100644
index ac34260..0000000
--- a/media/apex/java/android/media/MediaPlayer2Utils.java
+++ /dev/null
@@ -1,43 +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 android.media;
-
-/**
- * Helper class used by native code to reduce JNI calls from native side.
- * @hide
- */
-public class MediaPlayer2Utils {
-    /**
-     * Returns whether audio offloading is supported for the given audio format.
-     *
-     * @param encoding the type of encoding defined in {@link AudioFormat}
-     * @param sampleRate the sampling rate of the stream
-     * @param channelMask the channel mask defined in {@link AudioFormat}
-     */
-    // @CalledByNative
-    public static boolean isOffloadedAudioPlaybackSupported(
-            int encoding, int sampleRate, int channelMask) {
-        final AudioFormat format = new AudioFormat.Builder()
-                .setEncoding(encoding)
-                .setSampleRate(sampleRate)
-                .setChannelMask(channelMask)
-                .build();
-        //TODO MP2 needs to pass AudioAttributes for this query, instead of using default attr
-        return AudioManager.isOffloadedPlaybackSupported(format,
-                (new AudioAttributes.Builder()).build());
-    }
-}
diff --git a/media/apex/java/android/media/UriDataSourceDesc.java b/media/apex/java/android/media/UriDataSourceDesc.java
deleted file mode 100644
index adf7a7d..0000000
--- a/media/apex/java/android/media/UriDataSourceDesc.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright 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.media;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.Uri;
-
-import java.net.HttpCookie;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Structure of data source descriptor for sources using URI.
- *
- * Used by {@link MediaPlayer2#setDataSource}, {@link MediaPlayer2#setNextDataSource} and
- * {@link MediaPlayer2#setNextDataSources} to set data source for playback.
- *
- * <p>Users should use {@link Builder} to change {@link UriDataSourceDesc}.
- * @hide
- */
-public class UriDataSourceDesc extends DataSourceDesc {
-    private Uri mUri;
-    private Map<String, String> mHeader;
-    private List<HttpCookie> mCookies;
-
-    UriDataSourceDesc(String mediaId, long startPositionMs, long endPositionMs,
-            Uri uri, Map<String, String> header, List<HttpCookie> cookies) {
-        super(mediaId, startPositionMs, endPositionMs);
-        mUri = uri;
-        mHeader = header;
-        mCookies = cookies;
-    }
-
-    /**
-     * Return the Uri of this data source.
-     * @return the Uri of this data source
-     */
-    public @NonNull Uri getUri() {
-        return mUri;
-    }
-
-    /**
-     * Return the Uri headers of this data source.
-     * @return the Uri headers of this data source
-     */
-    public @Nullable Map<String, String> getHeaders() {
-        if (mHeader == null) {
-            return null;
-        }
-        return new HashMap<String, String>(mHeader);
-    }
-
-    /**
-     * Return the Uri cookies of this data source.
-     * @return the Uri cookies of this data source
-     */
-    public @Nullable List<HttpCookie> getCookies() {
-        if (mCookies == null) {
-            return null;
-        }
-        return new ArrayList<HttpCookie>(mCookies);
-    }
-}
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index 2d6cd24..f797da7 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -1857,12 +1857,37 @@
     }
 
     /**
+     * @hide
+     * Sets the microphone from switch mute on or off.
+     * <p>
+     * This method should only be used by InputManager to notify
+     * Audio Subsystem about Microphone Mute switch state.
+     *
+     * @param on set <var>true</var> to mute the microphone;
+     *           <var>false</var> to turn mute off
+     */
+    @UnsupportedAppUsage
+    public void setMicrophoneMuteFromSwitch(boolean on) {
+        final IAudioService service = getService();
+        try {
+            service.setMicrophoneMuteFromSwitch(on);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Checks whether the microphone mute is on or off.
      *
      * @return true if microphone is muted, false if it's not
      */
     public boolean isMicrophoneMute() {
-        return AudioSystem.isMicrophoneMuted();
+        final IAudioService service = getService();
+        try {
+            return service.isMicrophoneMuted();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
     }
 
     /**
diff --git a/media/java/android/media/ExifInterface.java b/media/java/android/media/ExifInterface.java
index 5b53565..5341d07 100644
--- a/media/java/android/media/ExifInterface.java
+++ b/media/java/android/media/ExifInterface.java
@@ -494,6 +494,19 @@
     // See http://www.exiv2.org/makernote.html#R11
     private static final int PEF_MAKER_NOTE_SKIP_SIZE = 6;
 
+    // See PNG (Portable Network Graphics) Specification, Version 1.2,
+    // 3.1. PNG file signature
+    private static final byte[] PNG_SIGNATURE = new byte[] {(byte) 0x89, (byte) 0x50, (byte) 0x4e,
+            (byte) 0x47, (byte) 0x0d, (byte) 0x0a, (byte) 0x1a, (byte) 0x0a};
+    // See PNG (Portable Network Graphics) Specification, Version 1.2,
+    // 3.7. eXIf Exchangeable Image File (Exif) Profile
+    private static final byte[] PNG_CHUNK_TYPE_EXIF = new byte[]{(byte) 0x65, (byte) 0x58,
+            (byte) 0x49, (byte) 0x66};
+    private static final byte[] PNG_CHUNK_TYPE_IEND = new byte[]{(byte) 0x49, (byte) 0x45,
+            (byte) 0x4e, (byte) 0x44};
+    private static final int PNG_CHUNK_LENGTH_BYTE_LENGTH = 4;
+    private static final int PNG_CHUNK_CRC_BYTE_LENGTH = 4;
+
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
     private static SimpleDateFormat sFormatter;
     private static SimpleDateFormat sFormatterTz;
@@ -1311,6 +1324,7 @@
     private static final int IMAGE_TYPE_RW2 = 10;
     private static final int IMAGE_TYPE_SRW = 11;
     private static final int IMAGE_TYPE_HEIF = 12;
+    private static final int IMAGE_TYPE_PNG = 13;
 
     static {
         sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
@@ -1343,6 +1357,7 @@
     private AssetManager.AssetInputStream mAssetInputStream;
     private boolean mIsInputStream;
     private int mMimeType;
+    private boolean mIsStandalone;
     @UnsupportedAppUsage
     private final HashMap[] mAttributes = new HashMap[EXIF_TAGS.length];
     private Set<Integer> mHandledIfdOffsets = new HashSet<>(EXIF_TAGS.length);
@@ -1397,6 +1412,7 @@
         if (fileDescriptor == null) {
             throw new NullPointerException("fileDescriptor cannot be null");
         }
+
         mAssetInputStream = null;
         mFilename = null;
         // When FileDescriptor is duplicated and set to FileInputStream, ownership needs to be
@@ -1428,26 +1444,61 @@
 
     /**
      * Reads Exif tags from the specified image input stream. Attribute mutation is not supported
-     * for input streams. The given input stream will proceed its current position. Developers
+     * for input streams. The given input stream will proceed from its current position. Developers
      * should close the input stream after use.
      */
     public ExifInterface(@NonNull InputStream inputStream) throws IOException {
+        this(inputStream, false);
+    }
+
+    /**
+     * Reads Exif tags from the specified standalone input stream. Standalone data refers to Exif
+     * data that exists by itself and is not contained in a file format such as jpeg or png.
+     * The format of the standalone data must follow the below structure:
+     *     Exif Identifier Code ("Exif\0\0") + TIFF header + IFD data
+     * See JEITA CP-3451C Section 4.5.2 and 4.5.4 specifications for more details.
+     * <p>
+     * Attribute mutation is not supported for this constructor. The given input stream will proceed
+     * from its current position. Developers should close the input stream after use. This
+     * constructor is not intended to be used with an input stream that performs any networking
+     * operations.
+     *
+     * @throws IOException if the data does not follow the aforementioned structure.
+     */
+    @NonNull
+    public static ExifInterface fromStandalone(@NonNull InputStream inputStream)
+            throws IOException {
+        if (isStandalone(inputStream)) {
+            return new ExifInterface(inputStream, true);
+        }
+        throw new IOException("Given data does not follow the structure of a standalone exif "
+                + "data.");
+    }
+
+    private ExifInterface(@NonNull InputStream inputStream, boolean isFromStandalone)
+            throws IOException {
         if (inputStream == null) {
             throw new NullPointerException("inputStream cannot be null");
         }
         mFilename = null;
-        if (inputStream instanceof AssetManager.AssetInputStream) {
-            mAssetInputStream = (AssetManager.AssetInputStream) inputStream;
-            mSeekableFileDescriptor = null;
-        } else if (inputStream instanceof FileInputStream
-                && isSeekableFD(((FileInputStream) inputStream).getFD())) {
+
+        if (isFromStandalone) {
+            mIsStandalone = true;
             mAssetInputStream = null;
-            mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD();
+            mSeekableFileDescriptor = null;
         } else {
-            mAssetInputStream = null;
-            mSeekableFileDescriptor = null;
+            if (inputStream instanceof AssetManager.AssetInputStream) {
+                mAssetInputStream = (AssetManager.AssetInputStream) inputStream;
+                mSeekableFileDescriptor = null;
+            } else if (inputStream instanceof FileInputStream
+                    && (isSeekableFD(((FileInputStream) inputStream).getFD()))) {
+                mAssetInputStream = null;
+                mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD();
+            } else {
+                mAssetInputStream = null;
+                mSeekableFileDescriptor = null;
+            }
         }
-        mIsInputStream = true;
         loadAttributes(inputStream);
     }
 
@@ -1784,47 +1835,57 @@
             }
 
             // Check file type
-            in = new BufferedInputStream(in, SIGNATURE_CHECK_SIZE);
-            mMimeType = getMimeType((BufferedInputStream) in);
+            if (!mIsStandalone) {
+                in = new BufferedInputStream(in, SIGNATURE_CHECK_SIZE);
+                mMimeType = getMimeType((BufferedInputStream) in);
+            }
 
             // Create byte-ordered input stream
             ByteOrderedDataInputStream inputStream = new ByteOrderedDataInputStream(in);
 
-            switch (mMimeType) {
-                case IMAGE_TYPE_JPEG: {
-                    getJpegAttributes(inputStream, 0, IFD_TYPE_PRIMARY); // 0 is offset
-                    break;
+            if (!mIsStandalone) {
+                switch (mMimeType) {
+                    case IMAGE_TYPE_JPEG: {
+                        getJpegAttributes(inputStream, 0, IFD_TYPE_PRIMARY); // 0 is offset
+                        break;
+                    }
+                    case IMAGE_TYPE_RAF: {
+                        getRafAttributes(inputStream);
+                        break;
+                    }
+                    case IMAGE_TYPE_HEIF: {
+                        getHeifAttributes(inputStream);
+                        break;
+                    }
+                    case IMAGE_TYPE_ORF: {
+                        getOrfAttributes(inputStream);
+                        break;
+                    }
+                    case IMAGE_TYPE_RW2: {
+                        getRw2Attributes(inputStream);
+                        break;
+                    }
+                    case IMAGE_TYPE_PNG: {
+                        getPngAttributes(inputStream);
+                        break;
+                    }
+                    case IMAGE_TYPE_ARW:
+                    case IMAGE_TYPE_CR2:
+                    case IMAGE_TYPE_DNG:
+                    case IMAGE_TYPE_NEF:
+                    case IMAGE_TYPE_NRW:
+                    case IMAGE_TYPE_PEF:
+                    case IMAGE_TYPE_SRW:
+                    case IMAGE_TYPE_UNKNOWN: {
+                        getRawAttributes(inputStream);
+                        break;
+                    }
+                    default: {
+                        break;
+                    }
                 }
-                case IMAGE_TYPE_RAF: {
-                    getRafAttributes(inputStream);
-                    break;
-                }
-                case IMAGE_TYPE_HEIF: {
-                    getHeifAttributes(inputStream);
-                    break;
-                }
-                case IMAGE_TYPE_ORF: {
-                    getOrfAttributes(inputStream);
-                    break;
-                }
-                case IMAGE_TYPE_RW2: {
-                    getRw2Attributes(inputStream);
-                    break;
-                }
-                case IMAGE_TYPE_ARW:
-                case IMAGE_TYPE_CR2:
-                case IMAGE_TYPE_DNG:
-                case IMAGE_TYPE_NEF:
-                case IMAGE_TYPE_NRW:
-                case IMAGE_TYPE_PEF:
-                case IMAGE_TYPE_SRW:
-                case IMAGE_TYPE_UNKNOWN: {
-                    getRawAttributes(inputStream);
-                    break;
-                }
-                default: {
-                    break;
-                }
+            } else {
+                getStandaloneAttributes(inputStream);
             }
             // Set thumbnail image offset and length
             setThumbnailData(inputStream);
@@ -2024,6 +2085,7 @@
             if (in.skip(mThumbnailOffset) != mThumbnailOffset) {
                 throw new IOException("Corrupted image");
             }
+            // TODO: Need to handle potential OutOfMemoryError
             byte[] buffer = new byte[mThumbnailLength];
             if (in.read(buffer) != mThumbnailLength) {
                 throw new IOException("Corrupted image");
@@ -2105,6 +2167,9 @@
         }
 
         if (mHasThumbnail) {
+            if (mIsStandalone) {
+                return new long[] { mThumbnailOffset + mExifOffset, mThumbnailLength };
+            }
             return new long[] { mThumbnailOffset, mThumbnailLength };
         } else {
             return null;
@@ -2349,6 +2414,7 @@
 
     // Checks the type of image file
     private int getMimeType(BufferedInputStream in) throws IOException {
+        // TODO (b/142218289): Need to handle case where input stream does not support mark
         in.mark(SIGNATURE_CHECK_SIZE);
         byte[] signatureCheckBytes = new byte[SIGNATURE_CHECK_SIZE];
         in.read(signatureCheckBytes);
@@ -2363,6 +2429,8 @@
             return IMAGE_TYPE_ORF;
         } else if (isRw2Format(signatureCheckBytes)) {
             return IMAGE_TYPE_RW2;
+        } else if (isPngFormat(signatureCheckBytes)) {
+            return IMAGE_TYPE_PNG;
         }
         // Certain file formats (PEF) are identified in readImageFileDirectory()
         return IMAGE_TYPE_UNKNOWN;
@@ -2478,16 +2546,24 @@
      * http://fileformats.archiveteam.org/wiki/Olympus_ORF
      */
     private boolean isOrfFormat(byte[] signatureCheckBytes) throws IOException {
-        ByteOrderedDataInputStream signatureInputStream =
-                new ByteOrderedDataInputStream(signatureCheckBytes);
-        // Read byte order
-        mExifByteOrder = readByteOrder(signatureInputStream);
-        // Set byte order
-        signatureInputStream.setByteOrder(mExifByteOrder);
+        ByteOrderedDataInputStream signatureInputStream = null;
 
-        short orfSignature = signatureInputStream.readShort();
-        if (orfSignature == ORF_SIGNATURE_1 || orfSignature == ORF_SIGNATURE_2) {
-            return true;
+        try {
+            signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes);
+
+            // Read byte order
+            mExifByteOrder = readByteOrder(signatureInputStream);
+            // Set byte order
+            signatureInputStream.setByteOrder(mExifByteOrder);
+
+            short orfSignature = signatureInputStream.readShort();
+            return orfSignature == ORF_SIGNATURE_1 || orfSignature == ORF_SIGNATURE_2;
+        } catch (Exception e) {
+            // Do nothing
+        } finally {
+            if (signatureInputStream != null) {
+                signatureInputStream.close();
+            }
         }
         return false;
     }
@@ -2497,21 +2573,55 @@
      * See http://lclevy.free.fr/raw/
      */
     private boolean isRw2Format(byte[] signatureCheckBytes) throws IOException {
-        ByteOrderedDataInputStream signatureInputStream =
-                new ByteOrderedDataInputStream(signatureCheckBytes);
-        // Read byte order
-        mExifByteOrder = readByteOrder(signatureInputStream);
-        // Set byte order
-        signatureInputStream.setByteOrder(mExifByteOrder);
+        ByteOrderedDataInputStream signatureInputStream = null;
 
-        short signatureByte = signatureInputStream.readShort();
-        if (signatureByte == RW2_SIGNATURE) {
-            return true;
+        try {
+            signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes);
+
+            // Read byte order
+            mExifByteOrder = readByteOrder(signatureInputStream);
+            // Set byte order
+            signatureInputStream.setByteOrder(mExifByteOrder);
+
+            short signatureByte = signatureInputStream.readShort();
+            signatureInputStream.close();
+            return signatureByte == RW2_SIGNATURE;
+        } catch (Exception e) {
+            // Do nothing
+        } finally {
+            if (signatureInputStream != null) {
+                signatureInputStream.close();
+            }
         }
         return false;
     }
 
     /**
+     * PNG's file signature is first 8 bytes.
+     * See PNG (Portable Network Graphics) Specification, Version 1.2, 3.1. PNG file signature
+     */
+    private boolean isPngFormat(byte[] signatureCheckBytes) throws IOException {
+        for (int i = 0; i < PNG_SIGNATURE.length; i++) {
+            if (signatureCheckBytes[i] != PNG_SIGNATURE[i]) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private static boolean isStandalone(InputStream inputStream) throws IOException {
+        byte[] signatureCheckBytes = new byte[IDENTIFIER_EXIF_APP1.length];
+        inputStream.read(signatureCheckBytes);
+
+        for (int i = 0; i < IDENTIFIER_EXIF_APP1.length; i++) {
+            if (signatureCheckBytes[i] != IDENTIFIER_EXIF_APP1[i]) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
      * Loads EXIF attributes from a JPEG input stream.
      *
      * @param in The input stream that starts with the JPEG data.
@@ -2582,10 +2692,9 @@
                         final long offset = start + IDENTIFIER_EXIF_APP1.length;
                         final byte[] value = Arrays.copyOfRange(bytes,
                                 IDENTIFIER_EXIF_APP1.length, bytes.length);
-
                         readExifSegment(value, imageType);
 
-                        // Save offset values for createJpegThumbnailBitmap() function
+                        // Save offset values for handleThumbnailFromJfif() function
                         mExifOffset = (int) offset;
                     } else if (ArrayUtils.startsWith(bytes, IDENTIFIER_XMP_APP1)) {
                         // See XMP Specification Part 3: Storage in Files, 1.1.3 JPEG, Table 6
@@ -2886,6 +2995,7 @@
                     throw new IOException("Invalid identifier");
                 }
 
+                // TODO: Need to handle potential OutOfMemoryError
                 byte[] bytes = new byte[length];
                 if (in.read(bytes) != length) {
                     throw new IOException("Can't read exif");
@@ -2901,6 +3011,16 @@
         }
     }
 
+    private void getStandaloneAttributes(ByteOrderedDataInputStream in) throws IOException {
+        // TODO: Need to handle potential OutOfMemoryError
+        byte[] data = new byte[in.available()];
+        in.readFully(data);
+        readExifSegment(data, IFD_TYPE_PRIMARY);
+
+        // Save offset values for handleThumbnailFromJfif() function
+        mExifOffset = IDENTIFIER_EXIF_APP1.length;
+    }
+
     /**
      * ORF files contains a primary image data and a MakerNote data that contains preview/thumbnail
      * images. Both data takes the form of IFDs and can therefore be read with the
@@ -3012,6 +3132,64 @@
         }
     }
 
+    // PNG contains the EXIF data as a Special-Purpose Chunk
+    private void getPngAttributes(ByteOrderedDataInputStream in) throws IOException {
+        if (DEBUG) {
+            Log.d(TAG, "getPngAttributes starting with: " + in);
+        }
+
+        // PNG uses Big Endian by default.
+        // See PNG (Portable Network Graphics) Specification, Version 1.2,
+        // 2.1. Integers and byte order
+        in.setByteOrder(ByteOrder.BIG_ENDIAN);
+
+        // Skip the signature bytes
+        in.seek(PNG_SIGNATURE.length);
+
+        try {
+            while (true) {
+                // Each chunk is made up of four parts:
+                //   1) Length: 4-byte unsigned integer indicating the number of bytes in the
+                //   Chunk Data field. Excludes Chunk Type and CRC bytes.
+                //   2) Chunk Type: 4-byte chunk type code.
+                //   3) Chunk Data: The data bytes. Can be zero-length.
+                //   4) CRC: 4-byte data calculated on the preceding bytes in the chunk. Always
+                //   present.
+                // --> 4 (length bytes) + 4 (type bytes) + X (data bytes) + 4 (CRC bytes)
+                // See PNG (Portable Network Graphics) Specification, Version 1.2,
+                // 3.2. Chunk layout
+                int length = in.readInt();
+
+                byte[] type = new byte[PNG_CHUNK_LENGTH_BYTE_LENGTH];
+                if (in.read(type) != type.length) {
+                    throw new IOException("Encountered invalid length while parsing PNG chunk"
+                            + "type");
+                }
+
+                if (Arrays.equals(type, PNG_CHUNK_TYPE_IEND)) {
+                    // IEND marks the end of the image.
+                    break;
+                } else if (Arrays.equals(type, PNG_CHUNK_TYPE_EXIF)) {
+                    // TODO: Need to handle potential OutOfMemoryError
+                    byte[] data = new byte[length];
+                    if (in.read(data) != length) {
+                        throw new IOException("Failed to read given length for given PNG chunk "
+                                + "type: " + byteArrayToHexString(type));
+                    }
+                    readExifSegment(data, IFD_TYPE_PRIMARY);
+                    break;
+                } else {
+                    // Skip to next chunk
+                    in.skipBytes(length + PNG_CHUNK_CRC_BYTE_LENGTH);
+                }
+            }
+        } catch (EOFException e) {
+            // Should not reach here. Will only reach here if the file is corrupted or
+            // does not follow the PNG specifications
+            throw new IOException("Encountered corrupt PNG file.");
+        }
+    }
+
     // Stores a new JPEG image with EXIF attributes into a given output stream.
     private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream)
             throws IOException {
@@ -3496,8 +3674,6 @@
             int thumbnailOffset = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder);
             int thumbnailLength = jpegInterchangeFormatLengthAttribute.getIntValue(mExifByteOrder);
 
-            // The following code limits the size of thumbnail size not to overflow EXIF data area.
-            thumbnailLength = Math.min(thumbnailLength, in.getLength() - thumbnailOffset);
             if (mMimeType == IMAGE_TYPE_JPEG || mMimeType == IMAGE_TYPE_RAF
                     || mMimeType == IMAGE_TYPE_RW2) {
                 thumbnailOffset += mExifOffset;
@@ -3505,6 +3681,9 @@
                 // Update offset value since RAF files have IFD data preceding MakerNote data.
                 thumbnailOffset += mOrfMakerNoteOffset;
             }
+            // The following code limits the size of thumbnail size not to overflow EXIF data area.
+            thumbnailLength = Math.min(thumbnailLength, in.getLength() - thumbnailOffset);
+
             if (DEBUG) {
                 Log.d(TAG, "Setting thumbnail attributes with offset: " + thumbnailOffset
                         + ", length: " + thumbnailLength);
@@ -3517,6 +3696,7 @@
 
                 if (mFilename == null && mAssetInputStream == null
                         && mSeekableFileDescriptor == null) {
+                    // TODO: Need to handle potential OutOfMemoryError
                     // Save the thumbnail in memory if the input doesn't support reading again.
                     byte[] thumbnailBytes = new byte[thumbnailLength];
                     in.seek(thumbnailOffset);
@@ -3550,6 +3730,7 @@
                 return;
             }
 
+            // TODO: Need to handle potential OutOfMemoryError
             // Set thumbnail byte array data for non-consecutive strip bytes
             byte[] totalStripBytes =
                     new byte[(int) Arrays.stream(stripByteCounts).sum()];
@@ -3568,6 +3749,7 @@
                 in.seek(skipBytes);
                 bytesRead += skipBytes;
 
+                // TODO: Need to handle potential OutOfMemoryError
                 // Read strip bytes
                 byte[] stripBytes = new byte[stripByteCount];
                 in.read(stripBytes);
@@ -4010,6 +4192,7 @@
             mDataInputStream = new DataInputStream(in);
             mLength = mDataInputStream.available();
             mPosition = 0;
+            // TODO (b/142218289): Need to handle case where input stream does not support mark
             mDataInputStream.mark(mLength);
         }
 
@@ -4025,6 +4208,7 @@
             if (mPosition > byteCount) {
                 mPosition = 0;
                 mDataInputStream.reset();
+                // TODO (b/142218289): Need to handle case where input stream does not support mark
                 mDataInputStream.mark(mLength);
             } else {
                 byteCount -= mPosition;
@@ -4367,4 +4551,12 @@
         }
         return null;
     }
+
+    private static String byteArrayToHexString(byte[] bytes) {
+        StringBuilder sb = new StringBuilder(bytes.length * 2);
+        for (int i = 0; i < bytes.length; i++) {
+            sb.append(String.format("%02x", bytes[i]));
+        }
+        return sb.toString();
+    }
 }
diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl
index 71f52a1..fc05610 100644
--- a/media/java/android/media/IAudioService.aidl
+++ b/media/java/android/media/IAudioService.aidl
@@ -106,8 +106,12 @@
 
     List<AudioProductStrategy> getAudioProductStrategies();
 
+    boolean isMicrophoneMuted();
+
     void setMicrophoneMute(boolean on, String callingPackage, int userId);
 
+    oneway void setMicrophoneMuteFromSwitch(boolean on);
+
     void setRingerModeExternal(int ringerMode, String caller);
 
     void setRingerModeInternal(int ringerMode, String caller);
diff --git a/media/java/android/media/IMediaRouterService.aidl b/media/java/android/media/IMediaRouterService.aidl
index 1b713b6..81213b9 100644
--- a/media/java/android/media/IMediaRouterService.aidl
+++ b/media/java/android/media/IMediaRouterService.aidl
@@ -40,6 +40,7 @@
     void setSelectedRoute(IMediaRouterClient client, String routeId, boolean explicit);
     void requestSetVolume(IMediaRouterClient client, String routeId, int volume);
     void requestUpdateVolume(IMediaRouterClient client, String routeId, int direction);
+    void setControlCategories(IMediaRouterClient client, in List<String> categories);
 
     // Methods for media router 2
     void registerClient2(IMediaRouter2Client client, String packageName);
@@ -52,7 +53,7 @@
      * @param route the route to be selected
      */
     void selectRoute2(IMediaRouter2Client client, in @nullable MediaRoute2Info route);
-    void setControlCategories(IMediaRouter2Client client, in List<String> categories);
+    void setControlCategories2(IMediaRouter2Client client, in List<String> categories);
 
     void registerManager(IMediaRouter2Manager manager, String packageName);
     void unregisterManager(IMediaRouter2Manager manager);
diff --git a/media/java/android/media/MediaFile.java b/media/java/android/media/MediaFile.java
index 8887c7c..09221a37 100644
--- a/media/java/android/media/MediaFile.java
+++ b/media/java/android/media/MediaFile.java
@@ -23,7 +23,7 @@
 import android.annotation.UnsupportedAppUsage;
 import android.mtp.MtpConstants;
 
-import libcore.net.MimeMap;
+import libcore.content.type.MimeMap;
 
 import java.util.HashMap;
 
diff --git a/media/java/android/media/MediaMetadataRetriever.java b/media/java/android/media/MediaMetadataRetriever.java
index 0346010..f421029 100644
--- a/media/java/android/media/MediaMetadataRetriever.java
+++ b/media/java/android/media/MediaMetadataRetriever.java
@@ -227,6 +227,44 @@
     public native String extractMetadata(int keyCode);
 
     /**
+     * This method is similar to {@link #getFrameAtTime(long, int, BitmapParams)}
+     * except that the device will choose the actual {@link Bitmap.Config} to use.
+     *
+     * @param timeUs The time position where the frame will be retrieved.
+     * When retrieving the frame at the given time position, there is no
+     * guarantee that the data source has a frame located at the position.
+     * When this happens, a frame nearby will be returned. If timeUs is
+     * negative, time position and option will ignored, and any frame
+     * that the implementation considers as representative may be returned.
+     *
+     * @param option a hint on how the frame is found. Use
+     * {@link #OPTION_PREVIOUS_SYNC} if one wants to retrieve a sync frame
+     * that has a timestamp earlier than or the same as timeUs. Use
+     * {@link #OPTION_NEXT_SYNC} if one wants to retrieve a sync frame
+     * that has a timestamp later than or the same as timeUs. Use
+     * {@link #OPTION_CLOSEST_SYNC} if one wants to retrieve a sync frame
+     * that has a timestamp closest to or the same as timeUs. Use
+     * {@link #OPTION_CLOSEST} if one wants to retrieve a frame that may
+     * or may not be a sync frame but is closest to or the same as timeUs.
+     * {@link #OPTION_CLOSEST} often has larger performance overhead compared
+     * to the other options if there is no sync frame located at timeUs.
+     *
+     * @return A Bitmap containing a representative video frame, which can be null,
+     *         if such a frame cannot be retrieved. {@link Bitmap#getConfig()} can
+     *         be used to query the actual {@link Bitmap.Config}.
+     *
+     * @see {@link #getFrameAtTime(long, int, BitmapParams)}
+     */
+    public Bitmap getFrameAtTime(long timeUs, @Option int option) {
+        if (option < OPTION_PREVIOUS_SYNC ||
+            option > OPTION_CLOSEST) {
+            throw new IllegalArgumentException("Unsupported option: " + option);
+        }
+
+        return _getFrameAtTime(timeUs, option, -1 /*dst_width*/, -1 /*dst_height*/, null);
+    }
+
+    /**
      * Call this method after setDataSource(). This method finds a
      * representative frame close to the given time position by considering
      * the given option if possible, and returns it as a bitmap.
@@ -255,16 +293,60 @@
      * {@link #OPTION_CLOSEST} often has larger performance overhead compared
      * to the other options if there is no sync frame located at timeUs.
      *
+     * @param params BitmapParams that controls the returned bitmap config
+     *        (such as pixel formats).
+     *
      * @return A Bitmap containing a representative video frame, which
      *         can be null, if such a frame cannot be retrieved.
+     *
+     * @see {@link #getFrameAtTime(long, int)}
      */
-    public Bitmap getFrameAtTime(long timeUs, @Option int option) {
+    public Bitmap getFrameAtTime(
+            long timeUs, @Option int option, @NonNull BitmapParams params) {
         if (option < OPTION_PREVIOUS_SYNC ||
             option > OPTION_CLOSEST) {
             throw new IllegalArgumentException("Unsupported option: " + option);
         }
 
-        return _getFrameAtTime(timeUs, option, -1 /*dst_width*/, -1 /*dst_height*/);
+        return _getFrameAtTime(timeUs, option, -1 /*dst_width*/, -1 /*dst_height*/, params);
+    }
+
+    /**
+     * This method is similar to {@link #getScaledFrameAtTime(long, int, int, int, BitmapParams)}
+     * except that the device will choose the actual {@link Bitmap.Config} to use.
+     *
+     * @param timeUs The time position in microseconds where the frame will be retrieved.
+     * When retrieving the frame at the given time position, there is no
+     * guarantee that the data source has a frame located at the position.
+     * When this happens, a frame nearby will be returned. If timeUs is
+     * negative, time position and option will ignored, and any frame
+     * that the implementation considers as representative may be returned.
+     *
+     * @param option a hint on how the frame is found. Use
+     * {@link #OPTION_PREVIOUS_SYNC} if one wants to retrieve a sync frame
+     * that has a timestamp earlier than or the same as timeUs. Use
+     * {@link #OPTION_NEXT_SYNC} if one wants to retrieve a sync frame
+     * that has a timestamp later than or the same as timeUs. Use
+     * {@link #OPTION_CLOSEST_SYNC} if one wants to retrieve a sync frame
+     * that has a timestamp closest to or the same as timeUs. Use
+     * {@link #OPTION_CLOSEST} if one wants to retrieve a frame that may
+     * or may not be a sync frame but is closest to or the same as timeUs.
+     * {@link #OPTION_CLOSEST} often has larger performance overhead compared
+     * to the other options if there is no sync frame located at timeUs.
+     *
+     * @param dstWidth expected output bitmap width
+     * @param dstHeight expected output bitmap height
+     * @return A Bitmap containing a representative video frame, which can be null,
+     *         if such a frame cannot be retrieved. {@link Bitmap#getConfig()} can
+     *         be used to query the actual {@link Bitmap.Config}.
+     * @throws IllegalArgumentException if passed in invalid option or width by height
+     *         is less than or equal to 0.
+     * @see {@link #getScaledFrameAtTime(long, int, int, int, BitmapParams)}
+     */
+    public Bitmap getScaledFrameAtTime(
+            long timeUs, @Option int option, int dstWidth, int dstHeight) {
+        validate(option, dstWidth, dstHeight);
+        return _getFrameAtTime(timeUs, option, dstWidth, dstHeight, null);
     }
 
     /**
@@ -297,15 +379,23 @@
      *
      * @param dstWidth expected output bitmap width
      * @param dstHeight expected output bitmap height
+     * @param params BitmapParams that controls the returned bitmap config
+     *        (such as pixel formats).
+     *
      * @return A Bitmap of size not larger than dstWidth by dstHeight containing a
      *         scaled video frame, which can be null, if such a frame cannot be retrieved.
      * @throws IllegalArgumentException if passed in invalid option or width by height
      *         is less than or equal to 0.
+     * @see {@link #getScaledFrameAtTime(long, int, int, int)}
      */
-    public Bitmap getScaledFrameAtTime(
-            long timeUs, @Option int option, int dstWidth, int dstHeight) {
-        if (option < OPTION_PREVIOUS_SYNC ||
-            option > OPTION_CLOSEST) {
+    public Bitmap getScaledFrameAtTime(long timeUs, @Option int option,
+            int dstWidth, int dstHeight, @NonNull BitmapParams params) {
+        validate(option, dstWidth, dstHeight);
+        return _getFrameAtTime(timeUs, option, dstWidth, dstHeight, params);
+    }
+
+    private void validate(@Option int option, int dstWidth, int dstHeight) {
+        if (option < OPTION_PREVIOUS_SYNC || option > OPTION_CLOSEST) {
             throw new IllegalArgumentException("Unsupported option: " + option);
         }
         if (dstWidth <= 0) {
@@ -314,8 +404,6 @@
         if (dstHeight <= 0) {
             throw new IllegalArgumentException("Invalid height: " + dstHeight);
         }
-
-        return _getFrameAtTime(timeUs, option, dstWidth, dstHeight);
     }
 
     /**
@@ -365,10 +453,12 @@
      * @see #getFrameAtTime(long, int)
      */
     public Bitmap getFrameAtTime() {
-        return _getFrameAtTime(-1, OPTION_CLOSEST_SYNC, -1 /*dst_width*/, -1 /*dst_height*/);
+        return _getFrameAtTime(
+                -1, OPTION_CLOSEST_SYNC, -1 /*dst_width*/, -1 /*dst_height*/, null);
     }
 
-    private native Bitmap _getFrameAtTime(long timeUs, int option, int width, int height);
+    private native Bitmap _getFrameAtTime(
+            long timeUs, int option, int width, int height, @Nullable BitmapParams params);
 
     public static final class BitmapParams {
         private Bitmap.Config inPreferredConfig = Bitmap.Config.ARGB_8888;
diff --git a/media/java/android/media/MediaRouter.java b/media/java/android/media/MediaRouter.java
index d72231f..9cb7869 100644
--- a/media/java/android/media/MediaRouter.java
+++ b/media/java/android/media/MediaRouter.java
@@ -49,6 +49,8 @@
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Objects;
@@ -82,6 +84,7 @@
 
         final ArrayList<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
         final ArrayList<RouteCategory> mCategories = new ArrayList<RouteCategory>();
+        List<String> mControlCategories = Collections.emptyList();
 
         final RouteCategory mSystemCategory;
 
@@ -358,6 +361,18 @@
             return mDisplayService.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION);
         }
 
+        public void setControlCategories(Collection<String> controlCategories) {
+            List<String> newControlCategories = new ArrayList<>(controlCategories);
+            mControlCategories = newControlCategories;
+            if (mClient != null) {
+                try {
+                    mMediaRouterService.setControlCategories(mClient, newControlCategories);
+                } catch (RemoteException ex) {
+                    Log.e(TAG, "Unable to set control categories.", ex);
+                }
+            }
+        }
+
         private void updatePresentationDisplays(int changedDisplayId) {
             final int count = mRoutes.size();
             for (int i = 0; i < count; i++) {
@@ -406,6 +421,7 @@
                 try {
                     Client client = new Client();
                     mMediaRouterService.registerClientAsUser(client, mPackageName, userId);
+                    mMediaRouterService.setControlCategories(client, mControlCategories);
                     mClient = client;
                 } catch (RemoteException ex) {
                     Log.e(TAG, "Unable to register media router client.", ex);
@@ -1302,6 +1318,19 @@
         sStatic.rebindAsUser(userId);
     }
 
+    /**
+     * Sets the control categories of the application.
+     * Routes that support at least one of the given control categories only exists and are handled
+     * by the media router.
+     *
+     * @hide
+     */
+    public void setControlCategories(@NonNull Collection<String> controlCategories) {
+        Objects.requireNonNull(controlCategories, "control categories must not be null");
+
+        sStatic.setControlCategories(controlCategories);
+    }
+
     static void updateRoute(final RouteInfo info) {
         dispatchRouteChanged(info);
     }
diff --git a/media/java/android/media/MediaRouter2.java b/media/java/android/media/MediaRouter2.java
index 8e29e34..ed35ef6 100644
--- a/media/java/android/media/MediaRouter2.java
+++ b/media/java/android/media/MediaRouter2.java
@@ -129,7 +129,7 @@
                 Client client = new Client();
                 try {
                     mMediaRouterService.registerClient2(client, mPackageName);
-                    mMediaRouterService.setControlCategories(client, mControlCategories);
+                    mMediaRouterService.setControlCategories2(client, mControlCategories);
                     mClient = client;
                 } catch (RemoteException ex) {
                     Log.e(TAG, "Unable to register media router.", ex);
@@ -188,7 +188,7 @@
         }
         if (client != null) {
             try {
-                mMediaRouterService.setControlCategories(client, newControlCategories);
+                mMediaRouterService.setControlCategories2(client, newControlCategories);
             } catch (RemoteException ex) {
                 Log.e(TAG, "Unable to set control categories.", ex);
             }
diff --git a/media/jni/Android.bp b/media/jni/Android.bp
index 84fe27d..45ee210 100644
--- a/media/jni/Android.bp
+++ b/media/jni/Android.bp
@@ -34,6 +34,7 @@
         "libutils",
         "libbinder",
         "libmedia",
+        "libmedia_codeclist",
         "libmedia_jni_utils",
         "libmedia_omx",
         "libmediametrics",
@@ -58,7 +59,10 @@
         "android.hidl.token@1.0-utils",
     ],
 
-    header_libs: ["libhardware_headers"],
+    header_libs: [
+        "libhardware_headers",
+        "libmediadrm_headers",
+    ],
 
     static_libs: ["libgrallocusage"],
 
@@ -113,88 +117,6 @@
     ],
 }
 
-cc_library_shared {
-    name: "libmedia2_jni",
-
-    srcs: [
-        "android_media_DataSourceCallback.cpp",
-        "android_media_MediaMetricsJNI.cpp",
-        "android_media_MediaPlayer2.cpp",
-        "android_media_SyncParams.cpp",
-    ],
-
-    shared_libs: [
-        // NDK or LLNDK or NDK-compliant
-        "libandroid",
-        "libbinder_ndk",
-        "libcgrouprc",
-        "libmediandk",
-        "libmediametrics",
-        "libnativehelper_compat_libc++",
-        "liblog",
-        "libvndksupport",
-    ],
-
-    header_libs: [
-        "libhardware_headers",
-        "libnativewindow_headers",
-    ],
-
-    static_libs: [
-        // MediaCas
-        "android.hidl.allocator@1.0",
-        "android.hidl.memory@1.0",
-        "libhidlbase",
-        "libhidlmemory",
-        "libbinderthreadstate",
-
-        // MediaPlayer2 implementation
-        "libbase",
-        "libcrypto",
-        "libcutils",
-        "libjsoncpp",
-        "libmedia_player2_util",
-        "libmediaplayer2",
-        "libmediaplayer2-protos",
-        "libmediandk_utils",
-        "libmediautils",
-        "libprocessgroup",
-        "libprotobuf-cpp-lite",
-        "libstagefright_esds",
-        "libstagefright_foundation_without_imemory",
-        "libstagefright_httplive",
-        "libstagefright_id3",
-        "libstagefright_mpeg2support",
-        "libstagefright_nuplayer2",
-        "libstagefright_player2",
-        "libstagefright_rtsp_player2",
-        "libstagefright_timedtext2",
-        "libutils",
-        "libmedia2_jni_core",
-    ],
-
-    group_static_libs: true,
-
-    include_dirs: [
-        "frameworks/base/core/jni",
-        "frameworks/native/include/media/openmax",
-        "system/media/camera/include",
-    ],
-
-    export_include_dirs: ["."],
-
-    cflags: [
-        "-Wall",
-        "-Werror",
-        "-Wno-error=deprecated-declarations",
-        "-Wunused",
-        "-Wunreachable-code",
-        "-fvisibility=hidden",
-    ],
-
-    ldflags: ["-Wl,--exclude-libs=ALL,-error-limit=0"],
-}
-
 subdirs = [
     "audioeffect",
     "soundpool",
diff --git a/media/jni/android_media_DataSourceCallback.cpp b/media/jni/android_media_DataSourceCallback.cpp
deleted file mode 100644
index c91d409..0000000
--- a/media/jni/android_media_DataSourceCallback.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright 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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "JDataSourceCallback-JNI"
-#include <utils/Log.h>
-
-#include "android_media_DataSourceCallback.h"
-
-#include "log/log.h"
-#include "jni.h"
-#include <nativehelper/JNIHelp.h>
-
-#include <drm/drm_framework_common.h>
-#include <mediaplayer2/JavaVMHelper.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <nativehelper/ScopedLocalRef.h>
-
-namespace android {
-
-static const size_t kBufferSize = 64 * 1024;
-
-JDataSourceCallback::JDataSourceCallback(JNIEnv* env, jobject source)
-    : mJavaObjStatus(OK),
-      mSizeIsCached(false),
-      mCachedSize(0) {
-    mDataSourceCallbackObj = env->NewGlobalRef(source);
-    CHECK(mDataSourceCallbackObj != NULL);
-
-    ScopedLocalRef<jclass> media2DataSourceClass(env, env->GetObjectClass(mDataSourceCallbackObj));
-    CHECK(media2DataSourceClass.get() != NULL);
-
-    mReadAtMethod = env->GetMethodID(media2DataSourceClass.get(), "readAt", "(J[BII)I");
-    CHECK(mReadAtMethod != NULL);
-    mGetSizeMethod = env->GetMethodID(media2DataSourceClass.get(), "getSize", "()J");
-    CHECK(mGetSizeMethod != NULL);
-    mCloseMethod = env->GetMethodID(media2DataSourceClass.get(), "close", "()V");
-    CHECK(mCloseMethod != NULL);
-
-    ScopedLocalRef<jbyteArray> tmp(env, env->NewByteArray(kBufferSize));
-    mByteArrayObj = (jbyteArray)env->NewGlobalRef(tmp.get());
-    CHECK(mByteArrayObj != NULL);
-}
-
-JDataSourceCallback::~JDataSourceCallback() {
-    JNIEnv* env = JavaVMHelper::getJNIEnv();
-    env->DeleteGlobalRef(mDataSourceCallbackObj);
-    env->DeleteGlobalRef(mByteArrayObj);
-}
-
-status_t JDataSourceCallback::initCheck() const {
-    return OK;
-}
-
-ssize_t JDataSourceCallback::readAt(off64_t offset, void *data, size_t size) {
-    Mutex::Autolock lock(mLock);
-
-    if (mJavaObjStatus != OK) {
-        return -1;
-    }
-    if (size > kBufferSize) {
-        size = kBufferSize;
-    }
-
-    JNIEnv* env = JavaVMHelper::getJNIEnv();
-    jint numread = env->CallIntMethod(mDataSourceCallbackObj, mReadAtMethod,
-            (jlong)offset, mByteArrayObj, (jint)0, (jint)size);
-    if (env->ExceptionCheck()) {
-        ALOGW("An exception occurred in readAt()");
-        jniLogException(env, ANDROID_LOG_WARN, LOG_TAG);
-        env->ExceptionClear();
-        mJavaObjStatus = UNKNOWN_ERROR;
-        return -1;
-    }
-    if (numread < 0) {
-        if (numread != -1) {
-            ALOGW("An error occurred in readAt()");
-            mJavaObjStatus = UNKNOWN_ERROR;
-            return -1;
-        } else {
-            // numread == -1 indicates EOF
-            return 0;
-        }
-    }
-    if ((size_t)numread > size) {
-        ALOGE("readAt read too many bytes.");
-        mJavaObjStatus = UNKNOWN_ERROR;
-        return -1;
-    }
-
-    ALOGV("readAt %lld / %zu => %d.", (long long)offset, size, numread);
-    env->GetByteArrayRegion(mByteArrayObj, 0, numread, (jbyte*)data);
-    return numread;
-}
-
-status_t JDataSourceCallback::getSize(off64_t* size) {
-    Mutex::Autolock lock(mLock);
-
-    if (mJavaObjStatus != OK) {
-        return UNKNOWN_ERROR;
-    }
-    if (mSizeIsCached) {
-        *size = mCachedSize;
-        return OK;
-    }
-
-    JNIEnv* env = JavaVMHelper::getJNIEnv();
-    *size = env->CallLongMethod(mDataSourceCallbackObj, mGetSizeMethod);
-    if (env->ExceptionCheck()) {
-        ALOGW("An exception occurred in getSize()");
-        jniLogException(env, ANDROID_LOG_WARN, LOG_TAG);
-        env->ExceptionClear();
-        // After returning an error, size shouldn't be used by callers.
-        *size = UNKNOWN_ERROR;
-        mJavaObjStatus = UNKNOWN_ERROR;
-        return UNKNOWN_ERROR;
-    }
-
-    // The minimum size should be -1, which indicates unknown size.
-    if (*size < 0) {
-        *size = -1;
-    }
-
-    mCachedSize = *size;
-    mSizeIsCached = true;
-    return OK;
-}
-
-void JDataSourceCallback::close() {
-    Mutex::Autolock lock(mLock);
-
-    JNIEnv* env = JavaVMHelper::getJNIEnv();
-    env->CallVoidMethod(mDataSourceCallbackObj, mCloseMethod);
-    // The closed state is effectively the same as an error state.
-    mJavaObjStatus = UNKNOWN_ERROR;
-}
-
-String8 JDataSourceCallback::toString() {
-    return String8::format("JDataSourceCallback(pid %d, uid %d)", getpid(), getuid());
-}
-
-String8 JDataSourceCallback::getMIMEType() const {
-    return String8("application/octet-stream");
-}
-
-}  // namespace android
diff --git a/media/jni/android_media_DataSourceCallback.h b/media/jni/android_media_DataSourceCallback.h
deleted file mode 100644
index 5bde682..0000000
--- a/media/jni/android_media_DataSourceCallback.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 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.
- */
-
-#ifndef _ANDROID_MEDIA_DATASOURCECALLBACK_H_
-#define _ANDROID_MEDIA_DATASOURCECALLBACK_H_
-
-#include "jni.h"
-
-#include <media/DataSource.h>
-#include <media/stagefright/foundation/ABase.h>
-#include <utils/Errors.h>
-#include <utils/Mutex.h>
-
-namespace android {
-
-// The native counterpart to a Java android.media.DataSourceCallback. It inherits from
-// DataSource.
-//
-// If the java DataSource returns an error or throws an exception it
-// will be considered to be in a broken state, and the only further call this
-// will make is to close().
-class JDataSourceCallback : public DataSource {
-public:
-    JDataSourceCallback(JNIEnv *env, jobject source);
-    virtual ~JDataSourceCallback();
-
-    virtual status_t initCheck() const override;
-    virtual ssize_t readAt(off64_t offset, void *data, size_t size) override;
-    virtual status_t getSize(off64_t *size) override;
-
-    virtual String8 toString() override;
-    virtual String8 getMIMEType() const override;
-    virtual void close() override;
-private:
-    // Protect all member variables with mLock because this object will be
-    // accessed on different threads.
-    Mutex mLock;
-
-    // The status of the java DataSource. Set to OK unless an error occurred or
-    // close() was called.
-    status_t mJavaObjStatus;
-    // Only call the java getSize() once so the app can't change the size on us.
-    bool mSizeIsCached;
-    off64_t mCachedSize;
-
-    jobject mDataSourceCallbackObj;
-    jmethodID mReadAtMethod;
-    jmethodID mGetSizeMethod;
-    jmethodID mCloseMethod;
-    jbyteArray mByteArrayObj;
-
-    DISALLOW_EVIL_CONSTRUCTORS(JDataSourceCallback);
-};
-
-}  // namespace android
-
-#endif  // _ANDROID_MEDIA_DATASOURCECALLBACK_H_
diff --git a/media/jni/android_media_MediaDrm.h b/media/jni/android_media_MediaDrm.h
index 5ebac1d..684069b 100644
--- a/media/jni/android_media_MediaDrm.h
+++ b/media/jni/android_media_MediaDrm.h
@@ -20,15 +20,12 @@
 #include "jni.h"
 
 #include <media/stagefright/foundation/ABase.h>
-#include <media/IDrm.h>
-#include <media/IDrmClient.h>
+#include <mediadrm/IDrm.h>
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
 
 namespace android {
 
-struct IDrm;
-
 class DrmListener: virtual public RefBase
 {
 public:
diff --git a/media/jni/android_media_MediaMetadataRetriever.cpp b/media/jni/android_media_MediaMetadataRetriever.cpp
index 18fd1a0..bc4bceb 100644
--- a/media/jni/android_media_MediaMetadataRetriever.cpp
+++ b/media/jni/android_media_MediaMetadataRetriever.cpp
@@ -350,9 +350,10 @@
     return jBitmap;
 }
 
-static int getColorFormat(JNIEnv *env, jobject options) {
+static int getColorFormat(JNIEnv *env, jobject options,
+        int defaultPreferred = HAL_PIXEL_FORMAT_RGBA_8888) {
     if (options == NULL) {
-        return HAL_PIXEL_FORMAT_RGBA_8888;
+        return defaultPreferred;
     }
 
     ScopedLocalRef<jobject> inConfig(env, env->GetObjectField(options, fields.inPreferredConfig));
@@ -383,7 +384,8 @@
 }
 
 static jobject android_media_MediaMetadataRetriever_getFrameAtTime(
-        JNIEnv *env, jobject thiz, jlong timeUs, jint option, jint dst_width, jint dst_height)
+        JNIEnv *env, jobject thiz, jlong timeUs, jint option,
+        jint dst_width, jint dst_height, jobject params)
 {
     ALOGV("getFrameAtTime: %lld us option: %d dst width: %d heigh: %d",
             (long long)timeUs, option, dst_width, dst_height);
@@ -392,10 +394,13 @@
         jniThrowException(env, "java/lang/IllegalStateException", "No retriever available");
         return NULL;
     }
+    // For getFrameAtTime family of calls, default to HAL_PIXEL_FORMAT_RGB_565
+    // to keep the behavior consistent with older releases
+    int colorFormat = getColorFormat(env, params, HAL_PIXEL_FORMAT_RGB_565);
 
     // Call native method to retrieve a video frame
     VideoFrame *videoFrame = NULL;
-    sp<IMemory> frameMemory = retriever->getFrameAtTime(timeUs, option);
+    sp<IMemory> frameMemory = retriever->getFrameAtTime(timeUs, option, colorFormat);
     // TODO: Using unsecurePointer() has some associated security pitfalls
     //       (see declaration for details).
     //       Either document why it is safe in this case or address the
@@ -408,7 +413,9 @@
         return NULL;
     }
 
-    return getBitmapFromVideoFrame(env, videoFrame, dst_width, dst_height, kRGB_565_SkColorType);
+    SkColorType outColorType = setOutColorType(env, colorFormat, params);
+
+    return getBitmapFromVideoFrame(env, videoFrame, dst_width, dst_height, outColorType);
 }
 
 static jobject android_media_MediaMetadataRetriever_getImageAtIndex(
@@ -739,7 +746,7 @@
                 (void *)android_media_MediaMetadataRetriever_setDataSourceFD},
         {"_setDataSource",   "(Landroid/media/MediaDataSource;)V",
                 (void *)android_media_MediaMetadataRetriever_setDataSourceCallback},
-        {"_getFrameAtTime", "(JIII)Landroid/graphics/Bitmap;",
+        {"_getFrameAtTime", "(JIIILandroid/media/MediaMetadataRetriever$BitmapParams;)Landroid/graphics/Bitmap;",
                 (void *)android_media_MediaMetadataRetriever_getFrameAtTime},
         {
             "_getImageAtIndex",
diff --git a/media/jni/android_media_MediaMetricsJNI.cpp b/media/jni/android_media_MediaMetricsJNI.cpp
index de60b08..e7487c3 100644
--- a/media/jni/android_media_MediaMetricsJNI.cpp
+++ b/media/jni/android_media_MediaMetricsJNI.cpp
@@ -23,9 +23,8 @@
 #include <media/MediaAnalyticsItem.h>
 
 
-// This source file is compiled and linked into both:
+// This source file is compiled and linked into:
 // core/jni/ (libandroid_runtime.so)
-// media/jni (libmedia2_jni.so)
 
 namespace android {
 
diff --git a/media/jni/android_media_MediaPlayer2.cpp b/media/jni/android_media_MediaPlayer2.cpp
deleted file mode 100644
index 3069161..0000000
--- a/media/jni/android_media_MediaPlayer2.cpp
+++ /dev/null
@@ -1,1477 +0,0 @@
-/*
-**
-** Copyright 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.
-*/
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "MediaPlayer2-JNI"
-#include "utils/Log.h"
-
-#include <sys/stat.h>
-
-#include <media/AudioResamplerPublic.h>
-#include <media/DataSourceDesc.h>
-#include <media/MediaHTTPService.h>
-#include <media/MediaAnalyticsItem.h>
-#include <media/NdkWrapper.h>
-#include <media/stagefright/Utils.h>
-#include <media/stagefright/foundation/ByteUtils.h>  // for FOURCC definition
-#include <mediaplayer2/JAudioTrack.h>
-#include <mediaplayer2/JavaVMHelper.h>
-#include <mediaplayer2/JMedia2HTTPService.h>
-#include <mediaplayer2/mediaplayer2.h>
-#include <stdio.h>
-#include <assert.h>
-#include <limits.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <utils/threads.h>
-#include "jni.h"
-#include <nativehelper/JNIHelp.h>
-#include "android/native_window_jni.h"
-#include "log/log.h"
-#include "utils/Errors.h"  // for status_t
-#include "utils/KeyedVector.h"
-#include "utils/String8.h"
-#include "android_media_BufferingParams.h"
-#include "android_media_DataSourceCallback.h"
-#include "android_media_MediaMetricsJNI.h"
-#include "android_media_PlaybackParams.h"
-#include "android_media_SyncParams.h"
-#include "android_media_VolumeShaper.h"
-
-#include "android_os_Parcel.h"
-#include "android_util_Binder.h"
-#include <binder/Parcel.h>
-
-#include "mediaplayer2.pb.h"
-
-using android::media::MediaPlayer2Proto::PlayerMessage;
-
-// Modular DRM begin
-#define FIND_CLASS(var, className) \
-var = env->FindClass(className); \
-LOG_FATAL_IF(! (var), "Unable to find class " className);
-
-#define GET_METHOD_ID(var, clazz, fieldName, fieldDescriptor) \
-var = env->GetMethodID(clazz, fieldName, fieldDescriptor); \
-LOG_FATAL_IF(! (var), "Unable to find method " fieldName);
-
-struct StateExceptionFields {
-    jmethodID init;
-    jclass classId;
-};
-
-static StateExceptionFields gStateExceptionFields;
-// Modular DRM end
-
-// ----------------------------------------------------------------------------
-
-using namespace android;
-
-using media::VolumeShaper;
-
-// ----------------------------------------------------------------------------
-
-struct fields_t {
-    jfieldID    context;               // passed from Java to native, used for creating JWakeLock
-    jfieldID    nativeContext;         // mNativeContext in MediaPlayer2.java
-    jfieldID    surface_texture;
-
-    jmethodID   post_event;
-
-    jmethodID   proxyConfigGetHost;
-    jmethodID   proxyConfigGetPort;
-    jmethodID   proxyConfigGetExclusionList;
-};
-static fields_t fields;
-
-static BufferingParams::fields_t gBufferingParamsFields;
-static PlaybackParams::fields_t gPlaybackParamsFields;
-static SyncParams::fields_t gSyncParamsFields;
-static VolumeShaperHelper::fields_t gVolumeShaperFields;
-
-static Mutex sLock;
-
-static bool ConvertKeyValueArraysToKeyedVector(
-        JNIEnv *env, jobjectArray keys, jobjectArray values,
-        KeyedVector<String8, String8>* keyedVector) {
-
-    int nKeyValuePairs = 0;
-    bool failed = false;
-    if (keys != NULL && values != NULL) {
-        nKeyValuePairs = env->GetArrayLength(keys);
-        failed = (nKeyValuePairs != env->GetArrayLength(values));
-    }
-
-    if (!failed) {
-        failed = ((keys != NULL && values == NULL) ||
-                  (keys == NULL && values != NULL));
-    }
-
-    if (failed) {
-        ALOGE("keys and values arrays have different length");
-        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
-        return false;
-    }
-
-    for (int i = 0; i < nKeyValuePairs; ++i) {
-        // No need to check on the ArrayIndexOutOfBoundsException, since
-        // it won't happen here.
-        jstring key = (jstring) env->GetObjectArrayElement(keys, i);
-        jstring value = (jstring) env->GetObjectArrayElement(values, i);
-
-        const char* keyStr = env->GetStringUTFChars(key, NULL);
-        if (!keyStr) {  // OutOfMemoryError
-            return false;
-        }
-
-        const char* valueStr = env->GetStringUTFChars(value, NULL);
-        if (!valueStr) {  // OutOfMemoryError
-            env->ReleaseStringUTFChars(key, keyStr);
-            return false;
-        }
-
-        keyedVector->add(String8(keyStr), String8(valueStr));
-
-        env->ReleaseStringUTFChars(key, keyStr);
-        env->ReleaseStringUTFChars(value, valueStr);
-        env->DeleteLocalRef(key);
-        env->DeleteLocalRef(value);
-    }
-    return true;
-}
-
-// ----------------------------------------------------------------------------
-// ref-counted object for callbacks
-class JNIMediaPlayer2Listener: public MediaPlayer2Listener
-{
-public:
-    JNIMediaPlayer2Listener(JNIEnv* env, jobject thiz, jobject weak_thiz);
-    ~JNIMediaPlayer2Listener();
-    virtual void notify(int64_t srcId, int msg, int ext1, int ext2,
-                        const PlayerMessage *obj = NULL) override;
-private:
-    JNIMediaPlayer2Listener();
-    jclass      mClass;     // Reference to MediaPlayer2 class
-    jobject     mObject;    // Weak ref to MediaPlayer2 Java object to call on
-};
-
-JNIMediaPlayer2Listener::JNIMediaPlayer2Listener(JNIEnv* env, jobject thiz, jobject weak_thiz)
-{
-
-    // Hold onto the MediaPlayer2 class for use in calling the static method
-    // that posts events to the application thread.
-    jclass clazz = env->GetObjectClass(thiz);
-    if (clazz == NULL) {
-        ALOGE("Can't find android/media/MediaPlayer2");
-        jniThrowException(env, "java/lang/Exception", NULL);
-        return;
-    }
-    mClass = (jclass)env->NewGlobalRef(clazz);
-
-    // We use a weak reference so the MediaPlayer2 object can be garbage collected.
-    // The reference is only used as a proxy for callbacks.
-    mObject  = env->NewGlobalRef(weak_thiz);
-}
-
-JNIMediaPlayer2Listener::~JNIMediaPlayer2Listener()
-{
-    // remove global references
-    JNIEnv *env = JavaVMHelper::getJNIEnv();
-    env->DeleteGlobalRef(mObject);
-    env->DeleteGlobalRef(mClass);
-}
-
-void JNIMediaPlayer2Listener::notify(int64_t srcId, int msg, int ext1, int ext2,
-        const PlayerMessage* obj)
-{
-    JNIEnv *env = JavaVMHelper::getJNIEnv();
-    if (obj != NULL) {
-        int size = obj->ByteSize();
-        jbyte* temp = new jbyte[size];
-        obj->SerializeToArray(temp, size);
-
-        // return the response as a byte array.
-        jbyteArray out = env->NewByteArray(size);
-        env->SetByteArrayRegion(out, 0, size, temp);
-        env->CallStaticVoidMethod(mClass, fields.post_event, mObject,
-                srcId, msg, ext1, ext2, out);
-        delete[] temp;
-    } else {
-        env->CallStaticVoidMethod(mClass, fields.post_event, mObject,
-                srcId, msg, ext1, ext2, NULL);
-    }
-    if (env->ExceptionCheck()) {
-        ALOGW("An exception occurred while notifying an event.");
-        jniLogException(env, ANDROID_LOG_WARN, LOG_TAG);
-        env->ExceptionClear();
-    }
-}
-
-// ----------------------------------------------------------------------------
-
-static sp<MediaPlayer2> getMediaPlayer(JNIEnv* env, jobject thiz)
-{
-    Mutex::Autolock l(sLock);
-    MediaPlayer2* const p = (MediaPlayer2*)env->GetLongField(thiz, fields.nativeContext);
-    return sp<MediaPlayer2>(p);
-}
-
-static sp<MediaPlayer2> setMediaPlayer(JNIEnv* env, jobject thiz, const sp<MediaPlayer2>& player)
-{
-    Mutex::Autolock l(sLock);
-    sp<MediaPlayer2> old = (MediaPlayer2*)env->GetLongField(thiz, fields.nativeContext);
-    if (player.get()) {
-        player->incStrong((void*)setMediaPlayer);
-    }
-    if (old != 0) {
-        old->decStrong((void*)setMediaPlayer);
-    }
-    env->SetLongField(thiz, fields.nativeContext, (jlong)player.get());
-    return old;
-}
-
-// If exception is NULL and opStatus is not OK, this method sends an error
-// event to the client application; otherwise, if exception is not NULL and
-// opStatus is not OK, this method throws the given exception to the client
-// application.
-static void process_media_player_call(
-    JNIEnv *env, jobject thiz, status_t opStatus, const char* exception, const char *message)
-{
-    if (exception == NULL) {  // Don't throw exception. Instead, send an event.
-        if (opStatus != (status_t) OK) {
-            sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-            if (mp != 0) {
-                int64_t srcId = 0;
-                mp->getSrcId(&srcId);
-                mp->notify(srcId, MEDIA2_ERROR, opStatus, 0);
-            }
-        }
-    } else {  // Throw exception!
-        if ( opStatus == (status_t) INVALID_OPERATION ) {
-            jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        } else if ( opStatus == (status_t) BAD_VALUE ) {
-            jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
-        } else if ( opStatus == (status_t) PERMISSION_DENIED ) {
-            jniThrowException(env, "java/lang/SecurityException", NULL);
-        } else if ( opStatus != (status_t) OK ) {
-            if (strlen(message) > 230) {
-               // if the message is too long, don't bother displaying the status code
-               jniThrowException( env, exception, message);
-            } else {
-               char msg[256];
-                // append the status code to the message
-               sprintf(msg, "%s: status=0x%X", message, opStatus);
-               jniThrowException( env, exception, msg);
-            }
-        }
-    }
-}
-
-static void
-android_media_MediaPlayer2_handleDataSourceUrl(
-        JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId,
-        jobject httpServiceObj, jstring path, jobjectArray keys, jobjectArray values,
-        jlong startPos, jlong endPos) {
-
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    if (path == NULL) {
-        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
-        return;
-    }
-
-    const char *tmp = env->GetStringUTFChars(path, NULL);
-    if (tmp == NULL) {  // Out of memory
-        return;
-    }
-    ALOGV("handleDataSourceUrl: path %s, srcId %lld, start %lld, end %lld",
-          tmp, (long long)srcId, (long long)startPos, (long long)endPos);
-
-    if (strncmp(tmp, "content://", 10) == 0) {
-        ALOGE("handleDataSourceUrl: content scheme is not supported in native code");
-        jniThrowException(env, "java/io/IOException",
-                          "content scheme is not supported in native code");
-        return;
-    }
-
-    sp<DataSourceDesc> dsd = new DataSourceDesc();
-    dsd->mId = srcId;
-    dsd->mType = DataSourceDesc::TYPE_URL;
-    dsd->mUrl = tmp;
-    dsd->mStartPositionMs = startPos;
-    dsd->mEndPositionMs = endPos;
-
-    env->ReleaseStringUTFChars(path, tmp);
-    tmp = NULL;
-
-    // We build a KeyedVector out of the key and val arrays
-    if (!ConvertKeyValueArraysToKeyedVector(
-            env, keys, values, &dsd->mHeaders)) {
-        return;
-    }
-
-    sp<MediaHTTPService> httpService;
-    if (httpServiceObj != NULL) {
-        httpService = new JMedia2HTTPService(env, httpServiceObj);
-    }
-    dsd->mHttpService = httpService;
-
-    status_t err;
-    if (isCurrent) {
-        err = mp->setDataSource(dsd);
-    } else {
-        err = mp->prepareNextDataSource(dsd);
-    }
-    process_media_player_call(env, thiz, err,
-            "java/io/IOException", "handleDataSourceUrl failed." );
-}
-
-static void
-android_media_MediaPlayer2_handleDataSourceFD(
-        JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId,
-        jobject fileDescriptor, jlong offset, jlong length,
-        jlong startPos, jlong endPos) {
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    if (fileDescriptor == NULL) {
-        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
-        return;
-    }
-    int fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
-    ALOGV("handleDataSourceFD: srcId=%lld, fd=%d (%s), offset=%lld, length=%lld, "
-          "start=%lld, end=%lld",
-          (long long)srcId, fd, nameForFd(fd).c_str(), (long long)offset, (long long)length,
-          (long long)startPos, (long long)endPos);
-
-    struct stat sb;
-    int ret = fstat(fd, &sb);
-    if (ret != 0) {
-        ALOGE("handleDataSourceFD: fstat(%d) failed: %d, %s", fd, ret, strerror(errno));
-        jniThrowException(env, "java/io/IOException", "handleDataSourceFD failed fstat");
-        return;
-    }
-
-    ALOGV("st_dev  = %llu", static_cast<unsigned long long>(sb.st_dev));
-    ALOGV("st_mode = %u", sb.st_mode);
-    ALOGV("st_uid  = %lu", static_cast<unsigned long>(sb.st_uid));
-    ALOGV("st_gid  = %lu", static_cast<unsigned long>(sb.st_gid));
-    ALOGV("st_size = %llu", static_cast<unsigned long long>(sb.st_size));
-
-    if (offset >= sb.st_size) {
-        ALOGE("handleDataSourceFD: offset is out of range");
-        jniThrowException(env, "java/lang/IllegalArgumentException",
-                          "handleDataSourceFD failed, offset is out of range.");
-        return;
-    }
-    if (offset + length > sb.st_size) {
-        length = sb.st_size - offset;
-        ALOGV("handleDataSourceFD: adjusted length = %lld", (long long)length);
-    }
-
-    sp<DataSourceDesc> dsd = new DataSourceDesc();
-    dsd->mId = srcId;
-    dsd->mType = DataSourceDesc::TYPE_FD;
-    dsd->mFD = fd;
-    dsd->mFDOffset = offset;
-    dsd->mFDLength = length;
-    dsd->mStartPositionMs = startPos;
-    dsd->mEndPositionMs = endPos;
-
-    status_t err;
-    if (isCurrent) {
-        err = mp->setDataSource(dsd);
-    } else {
-        err = mp->prepareNextDataSource(dsd);
-    }
-    process_media_player_call(env, thiz, err,
-            "java/io/IOException", "handleDataSourceFD failed." );
-}
-
-static void
-android_media_MediaPlayer2_handleDataSourceCallback(
-    JNIEnv *env, jobject thiz, jboolean isCurrent, jlong srcId, jobject dataSource,
-    jlong startPos, jlong endPos)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    if (dataSource == NULL) {
-        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
-        return;
-    }
-    sp<DataSource> callbackDataSource = new JDataSourceCallback(env, dataSource);
-    sp<DataSourceDesc> dsd = new DataSourceDesc();
-    dsd->mId = srcId;
-    dsd->mType = DataSourceDesc::TYPE_CALLBACK;
-    dsd->mCallbackSource = callbackDataSource;
-    dsd->mStartPositionMs = startPos;
-    dsd->mEndPositionMs = endPos;
-
-    status_t err;
-    if (isCurrent) {
-        err = mp->setDataSource(dsd);
-    } else {
-        err = mp->prepareNextDataSource(dsd);
-    }
-    process_media_player_call(env, thiz, err,
-            "java/lang/RuntimeException", "handleDataSourceCallback failed." );
-}
-
-static sp<ANativeWindowWrapper>
-getVideoSurfaceTexture(JNIEnv* env, jobject thiz) {
-    ANativeWindow * const p = (ANativeWindow*)env->GetLongField(thiz, fields.surface_texture);
-    return new ANativeWindowWrapper(p);
-}
-
-static void
-decVideoSurfaceRef(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        return;
-    }
-
-    ANativeWindow * const old_anw = (ANativeWindow*)env->GetLongField(thiz, fields.surface_texture);
-    if (old_anw != NULL) {
-        ANativeWindow_release(old_anw);
-        env->SetLongField(thiz, fields.surface_texture, (jlong)NULL);
-    }
-}
-
-static void
-setVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface, jboolean mediaPlayerMustBeAlive)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        if (mediaPlayerMustBeAlive) {
-            jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        }
-        return;
-    }
-
-    decVideoSurfaceRef(env, thiz);
-
-    ANativeWindow* anw = NULL;
-    if (jsurface) {
-        anw = ANativeWindow_fromSurface(env, jsurface);
-        if (anw == NULL) {
-            jniThrowException(env, "java/lang/IllegalArgumentException",
-                    "The surface has been released");
-            return;
-        }
-    }
-
-    env->SetLongField(thiz, fields.surface_texture, (jlong)anw);
-
-    // This will fail if the media player has not been initialized yet. This
-    // can be the case if setDisplay() on MediaPlayer2.java has been called
-    // before setDataSource(). The redundant call to setVideoSurfaceTexture()
-    // in prepare/prepare covers for this case.
-    mp->setVideoSurfaceTexture(new ANativeWindowWrapper(anw));
-}
-
-static void
-android_media_MediaPlayer2_setVideoSurface(JNIEnv *env, jobject thiz, jobject jsurface)
-{
-    setVideoSurface(env, thiz, jsurface, true /* mediaPlayerMustBeAlive */);
-}
-
-static jobject
-android_media_MediaPlayer2_getBufferingParams(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return NULL;
-    }
-
-    BufferingParams bp;
-    BufferingSettings &settings = bp.settings;
-    process_media_player_call(
-            env, thiz, mp->getBufferingSettings(&settings),
-            "java/lang/IllegalStateException", "unexpected error");
-    if (env->ExceptionCheck()) {
-        return nullptr;
-    }
-    ALOGV("getBufferingSettings:{%s}", settings.toString().string());
-
-    return bp.asJobject(env, gBufferingParamsFields);
-}
-
-static void
-android_media_MediaPlayer2_setBufferingParams(JNIEnv *env, jobject thiz, jobject params)
-{
-    if (params == NULL) {
-        return;
-    }
-
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    BufferingParams bp;
-    bp.fillFromJobject(env, gBufferingParamsFields, params);
-    ALOGV("setBufferingParams:{%s}", bp.settings.toString().string());
-
-    process_media_player_call(
-            env, thiz, mp->setBufferingSettings(bp.settings),
-            "java/lang/IllegalStateException", "unexpected error");
-}
-
-static void
-android_media_MediaPlayer2_playNextDataSource(JNIEnv *env, jobject thiz, jlong srcId)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    process_media_player_call(env, thiz, mp->playNextDataSource((int64_t)srcId),
-            "java/io/IOException", "playNextDataSource failed." );
-}
-
-static void
-android_media_MediaPlayer2_prepare(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    // Handle the case where the display surface was set before the mp was
-    // initialized. We try again to make it stick.
-    sp<ANativeWindowWrapper> st = getVideoSurfaceTexture(env, thiz);
-    mp->setVideoSurfaceTexture(st);
-
-    process_media_player_call( env, thiz, mp->prepareAsync(), "java/io/IOException", "Prepare Async failed." );
-}
-
-static void
-android_media_MediaPlayer2_start(JNIEnv *env, jobject thiz)
-{
-    ALOGV("start");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->start(), NULL, NULL );
-}
-
-static void
-android_media_MediaPlayer2_pause(JNIEnv *env, jobject thiz)
-{
-    ALOGV("pause");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->pause(), NULL, NULL );
-}
-
-static void
-android_media_MediaPlayer2_setPlaybackParams(JNIEnv *env, jobject thiz, jobject params)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    PlaybackParams pbp;
-    pbp.fillFromJobject(env, gPlaybackParamsFields, params);
-    ALOGV("setPlaybackParams: %d:%f %d:%f %d:%u %d:%u",
-            pbp.speedSet, pbp.audioRate.mSpeed,
-            pbp.pitchSet, pbp.audioRate.mPitch,
-            pbp.audioFallbackModeSet, pbp.audioRate.mFallbackMode,
-            pbp.audioStretchModeSet, pbp.audioRate.mStretchMode);
-
-    AudioPlaybackRate rate;
-    status_t err = mp->getPlaybackSettings(&rate);
-    if (err == OK) {
-        bool updatedRate = false;
-        if (pbp.speedSet) {
-            rate.mSpeed = pbp.audioRate.mSpeed;
-            updatedRate = true;
-        }
-        if (pbp.pitchSet) {
-            rate.mPitch = pbp.audioRate.mPitch;
-            updatedRate = true;
-        }
-        if (pbp.audioFallbackModeSet) {
-            rate.mFallbackMode = pbp.audioRate.mFallbackMode;
-            updatedRate = true;
-        }
-        if (pbp.audioStretchModeSet) {
-            rate.mStretchMode = pbp.audioRate.mStretchMode;
-            updatedRate = true;
-        }
-        if (updatedRate) {
-            err = mp->setPlaybackSettings(rate);
-        }
-    }
-    process_media_player_call(
-            env, thiz, err,
-            "java/lang/IllegalStateException", "unexpected error");
-}
-
-static jobject
-android_media_MediaPlayer2_getPlaybackParams(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return NULL;
-    }
-
-    PlaybackParams pbp;
-    AudioPlaybackRate &audioRate = pbp.audioRate;
-    process_media_player_call(
-            env, thiz, mp->getPlaybackSettings(&audioRate),
-            "java/lang/IllegalStateException", "unexpected error");
-    if (env->ExceptionCheck()) {
-        return nullptr;
-    }
-    ALOGV("getPlaybackSettings: %f %f %d %d",
-            audioRate.mSpeed, audioRate.mPitch, audioRate.mFallbackMode, audioRate.mStretchMode);
-
-    pbp.speedSet = true;
-    pbp.pitchSet = true;
-    pbp.audioFallbackModeSet = true;
-    pbp.audioStretchModeSet = true;
-
-    return pbp.asJobject(env, gPlaybackParamsFields);
-}
-
-static void
-android_media_MediaPlayer2_setSyncParams(JNIEnv *env, jobject thiz, jobject params)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    SyncParams scp;
-    scp.fillFromJobject(env, gSyncParamsFields, params);
-    ALOGV("setSyncParams: %d:%d %d:%d %d:%f %d:%f",
-          scp.syncSourceSet, scp.sync.mSource,
-          scp.audioAdjustModeSet, scp.sync.mAudioAdjustMode,
-          scp.toleranceSet, scp.sync.mTolerance,
-          scp.frameRateSet, scp.frameRate);
-
-    AVSyncSettings avsync;
-    float videoFrameRate;
-    status_t err = mp->getSyncSettings(&avsync, &videoFrameRate);
-    if (err == OK) {
-        bool updatedSync = scp.frameRateSet;
-        if (scp.syncSourceSet) {
-            avsync.mSource = scp.sync.mSource;
-            updatedSync = true;
-        }
-        if (scp.audioAdjustModeSet) {
-            avsync.mAudioAdjustMode = scp.sync.mAudioAdjustMode;
-            updatedSync = true;
-        }
-        if (scp.toleranceSet) {
-            avsync.mTolerance = scp.sync.mTolerance;
-            updatedSync = true;
-        }
-        if (updatedSync) {
-            err = mp->setSyncSettings(avsync, scp.frameRateSet ? scp.frameRate : -1.f);
-        }
-    }
-    process_media_player_call(
-            env, thiz, err,
-            "java/lang/IllegalStateException", "unexpected error");
-}
-
-static jobject
-android_media_MediaPlayer2_getSyncParams(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return NULL;
-    }
-
-    SyncParams scp;
-    scp.frameRate = -1.f;
-    process_media_player_call(
-            env, thiz, mp->getSyncSettings(&scp.sync, &scp.frameRate),
-            "java/lang/IllegalStateException", "unexpected error");
-    if (env->ExceptionCheck()) {
-        return nullptr;
-    }
-
-    ALOGV("getSyncSettings: %d %d %f %f",
-            scp.sync.mSource, scp.sync.mAudioAdjustMode, scp.sync.mTolerance, scp.frameRate);
-
-    // sanity check params
-    if (scp.sync.mSource >= AVSYNC_SOURCE_MAX
-            || scp.sync.mAudioAdjustMode >= AVSYNC_AUDIO_ADJUST_MODE_MAX
-            || scp.sync.mTolerance < 0.f
-            || scp.sync.mTolerance >= AVSYNC_TOLERANCE_MAX) {
-        jniThrowException(env,  "java/lang/IllegalStateException", NULL);
-        return NULL;
-    }
-
-    scp.syncSourceSet = true;
-    scp.audioAdjustModeSet = true;
-    scp.toleranceSet = true;
-    scp.frameRateSet = scp.frameRate >= 0.f;
-
-    return scp.asJobject(env, gSyncParamsFields);
-}
-
-static void
-android_media_MediaPlayer2_seekTo(JNIEnv *env, jobject thiz, jlong msec, jint mode)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    ALOGV("seekTo: %lld(msec), mode=%d", (long long)msec, mode);
-    process_media_player_call(env, thiz, mp->seekTo((int64_t)msec, (MediaPlayer2SeekMode)mode),
-                              NULL, NULL);
-}
-
-static jint
-android_media_MediaPlayer2_getState(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        return MEDIAPLAYER2_STATE_IDLE;
-    }
-    return (jint)mp->getState();
-}
-
-static jobject
-android_media_MediaPlayer2_native_getMetrics(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return 0;
-    }
-
-    char *buffer = NULL;
-    size_t length = 0;
-    status_t status = mp->getMetrics(&buffer, &length);
-    if (status != OK) {
-        ALOGD("getMetrics() failed: %d", status);
-        return (jobject) NULL;
-    }
-
-    jobject mybundle = MediaMetricsJNI::writeAttributesToBundle(env, NULL, buffer, length);
-
-    free(buffer);
-
-    return mybundle;
-}
-
-static jlong
-android_media_MediaPlayer2_getCurrentPosition(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return 0;
-    }
-    int64_t msec;
-    process_media_player_call( env, thiz, mp->getCurrentPosition(&msec), NULL, NULL );
-    ALOGV("getCurrentPosition: %lld (msec)", (long long)msec);
-    return (jlong) msec;
-}
-
-static jlong
-android_media_MediaPlayer2_getDuration(JNIEnv *env, jobject thiz, jlong srcId)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return 0;
-    }
-    int64_t msec;
-    process_media_player_call( env, thiz, mp->getDuration(srcId, &msec), NULL, NULL );
-    ALOGV("getDuration: %lld (msec)", (long long)msec);
-    return (jlong) msec;
-}
-
-static void
-android_media_MediaPlayer2_reset(JNIEnv *env, jobject thiz)
-{
-    ALOGV("reset");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->reset(), NULL, NULL );
-}
-
-static jboolean
-android_media_MediaPlayer2_setAudioAttributes(JNIEnv *env, jobject thiz, jobject attributes)
-{
-    ALOGV("setAudioAttributes");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return false;
-    }
-    status_t err = mp->setAudioAttributes(attributes);
-    return err == OK;
-}
-
-static jobject
-android_media_MediaPlayer2_getAudioAttributes(JNIEnv *env, jobject thiz)
-{
-    ALOGV("getAudioAttributes");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return NULL;
-    }
-
-    return mp->getAudioAttributes();
-}
-
-static void
-android_media_MediaPlayer2_setLooping(JNIEnv *env, jobject thiz, jboolean looping)
-{
-    ALOGV("setLooping: %d", looping);
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->setLooping(looping), NULL, NULL );
-}
-
-static jboolean
-android_media_MediaPlayer2_isLooping(JNIEnv *env, jobject thiz)
-{
-    ALOGV("isLooping");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return JNI_FALSE;
-    }
-    return mp->isLooping() ? JNI_TRUE : JNI_FALSE;
-}
-
-static void
-android_media_MediaPlayer2_setVolume(JNIEnv *env, jobject thiz, jfloat volume)
-{
-    ALOGV("setVolume: volume %f", (float) volume);
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->setVolume((float) volume), NULL, NULL );
-}
-
-static jbyteArray
-android_media_MediaPlayer2_invoke(JNIEnv *env, jobject thiz, jbyteArray requestData) {
-    sp<MediaPlayer2> media_player = getMediaPlayer(env, thiz);
-    if (media_player == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return NULL;
-    }
-
-    // Get the byte[] pointer and data length.
-    jbyte* pData = env->GetByteArrayElements(requestData, NULL);
-    jsize pDataLen = env->GetArrayLength(requestData);
-
-    // Deserialize from the byte stream.
-    PlayerMessage request;
-    PlayerMessage response;
-    request.ParseFromArray(pData, pDataLen);
-
-    process_media_player_call( env, thiz, media_player->invoke(request, &response),
-            "java.lang.RuntimeException", NULL );
-    if (env->ExceptionCheck()) {
-        return NULL;
-    }
-
-    int size = response.ByteSize();
-    jbyte* temp = new jbyte[size];
-    response.SerializeToArray(temp, size);
-
-    // return the response as a byte array.
-    jbyteArray out = env->NewByteArray(size);
-    env->SetByteArrayRegion(out, 0, size, temp);
-    delete[] temp;
-
-    return out;
-}
-
-// This function gets some field IDs, which in turn causes class initialization.
-// It is called from a static block in MediaPlayer2, which won't run until the
-// first time an instance of this class is used.
-static void
-android_media_MediaPlayer2_native_init(JNIEnv *env)
-{
-    jclass clazz;
-
-    clazz = env->FindClass("android/media/MediaPlayer2");
-    if (clazz == NULL) {
-        return;
-    }
-
-    fields.context = env->GetFieldID(clazz, "mContext", "Landroid/content/Context;");
-    if (fields.context == NULL) {
-        return;
-    }
-
-    fields.nativeContext = env->GetFieldID(clazz, "mNativeContext", "J");
-    if (fields.nativeContext == NULL) {
-        return;
-    }
-
-    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
-                                               "(Ljava/lang/Object;JIII[B)V");
-    if (fields.post_event == NULL) {
-        return;
-    }
-
-    fields.surface_texture = env->GetFieldID(clazz, "mNativeSurfaceTexture", "J");
-    if (fields.surface_texture == NULL) {
-        return;
-    }
-
-    env->DeleteLocalRef(clazz);
-
-    clazz = env->FindClass("android/net/ProxyInfo");
-    if (clazz == NULL) {
-        return;
-    }
-
-    fields.proxyConfigGetHost =
-        env->GetMethodID(clazz, "getHost", "()Ljava/lang/String;");
-
-    fields.proxyConfigGetPort =
-        env->GetMethodID(clazz, "getPort", "()I");
-
-    fields.proxyConfigGetExclusionList =
-        env->GetMethodID(clazz, "getExclusionListAsString", "()Ljava/lang/String;");
-
-    env->DeleteLocalRef(clazz);
-
-    gBufferingParamsFields.init(env);
-
-    // Modular DRM
-    FIND_CLASS(clazz, "android/media/MediaDrm$MediaDrmStateException");
-    if (clazz) {
-        GET_METHOD_ID(gStateExceptionFields.init, clazz, "<init>", "(ILjava/lang/String;)V");
-        gStateExceptionFields.classId = static_cast<jclass>(env->NewGlobalRef(clazz));
-
-        env->DeleteLocalRef(clazz);
-    } else {
-        ALOGE("JNI android_media_MediaPlayer2_native_init couldn't "
-              "get clazz android/media/MediaDrm$MediaDrmStateException");
-    }
-
-    gPlaybackParamsFields.init(env);
-    gSyncParamsFields.init(env);
-    gVolumeShaperFields.init(env);
-}
-
-static void
-android_media_MediaPlayer2_native_setup(JNIEnv *env, jobject thiz,
-        jint sessionId, jobject weak_this)
-{
-    ALOGV("native_setup");
-    jobject context = env->GetObjectField(thiz, fields.context);
-    sp<MediaPlayer2> mp = MediaPlayer2::Create(sessionId, context);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
-        return;
-    }
-
-    // create new listener and give it to MediaPlayer2
-    sp<JNIMediaPlayer2Listener> listener = new JNIMediaPlayer2Listener(env, thiz, weak_this);
-    mp->setListener(listener);
-
-    // Stow our new C++ MediaPlayer2 in an opaque field in the Java object.
-    setMediaPlayer(env, thiz, mp);
-}
-
-static void
-android_media_MediaPlayer2_release(JNIEnv *env, jobject thiz)
-{
-    ALOGV("release");
-    decVideoSurfaceRef(env, thiz);
-    sp<MediaPlayer2> mp = setMediaPlayer(env, thiz, 0);
-    if (mp != NULL) {
-        // this prevents native callbacks after the object is released
-        mp->setListener(0);
-        mp->disconnect();
-    }
-}
-
-static void
-android_media_MediaPlayer2_native_finalize(JNIEnv *env, jobject thiz)
-{
-    ALOGV("native_finalize");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp != NULL) {
-        ALOGW("MediaPlayer2 finalized without being released");
-    }
-    android_media_MediaPlayer2_release(env, thiz);
-}
-
-static void android_media_MediaPlayer2_setAudioSessionId(JNIEnv *env,  jobject thiz,
-        jint sessionId) {
-    ALOGV("setAudioSessionId(): %d", sessionId);
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->setAudioSessionId((audio_session_t) sessionId), NULL,
-            NULL);
-}
-
-static jint android_media_MediaPlayer2_getAudioSessionId(JNIEnv *env,  jobject thiz) {
-    ALOGV("getAudioSessionId()");
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return 0;
-    }
-
-    return (jint) mp->getAudioSessionId();
-}
-
-static void
-android_media_MediaPlayer2_setAuxEffectSendLevel(JNIEnv *env, jobject thiz, jfloat level)
-{
-    ALOGV("setAuxEffectSendLevel: level %f", level);
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->setAuxEffectSendLevel(level), NULL, NULL );
-}
-
-static void android_media_MediaPlayer2_attachAuxEffect(JNIEnv *env,  jobject thiz, jint effectId) {
-    ALOGV("attachAuxEffect(): %d", effectId);
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-    process_media_player_call( env, thiz, mp->attachAuxEffect(effectId), NULL, NULL );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////
-// Modular DRM begin
-
-// TODO: investigate if these can be shared with their MediaDrm counterparts
-static void throwDrmStateException(JNIEnv *env, const char *msg, status_t err)
-{
-    ALOGE("Illegal DRM state exception: %s (%d)", msg, err);
-
-    jobject exception = env->NewObject(gStateExceptionFields.classId,
-            gStateExceptionFields.init, static_cast<int>(err),
-            env->NewStringUTF(msg));
-    env->Throw(static_cast<jthrowable>(exception));
-}
-
-// TODO: investigate if these can be shared with their MediaDrm counterparts
-static bool throwDrmExceptionAsNecessary(JNIEnv *env, status_t err, const char *msg = NULL)
-{
-    const char *drmMessage = "Unknown DRM Msg";
-
-    switch (err) {
-    case ERROR_DRM_UNKNOWN:
-        drmMessage = "General DRM error";
-        break;
-    case ERROR_DRM_NO_LICENSE:
-        drmMessage = "No license";
-        break;
-    case ERROR_DRM_LICENSE_EXPIRED:
-        drmMessage = "License expired";
-        break;
-    case ERROR_DRM_SESSION_NOT_OPENED:
-        drmMessage = "Session not opened";
-        break;
-    case ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED:
-        drmMessage = "Not initialized";
-        break;
-    case ERROR_DRM_DECRYPT:
-        drmMessage = "Decrypt error";
-        break;
-    case ERROR_DRM_CANNOT_HANDLE:
-        drmMessage = "Unsupported scheme or data format";
-        break;
-    case ERROR_DRM_TAMPER_DETECTED:
-        drmMessage = "Invalid state";
-        break;
-    default:
-        break;
-    }
-
-    String8 vendorMessage;
-    if (err >= ERROR_DRM_VENDOR_MIN && err <= ERROR_DRM_VENDOR_MAX) {
-        vendorMessage = String8::format("DRM vendor-defined error: %d", err);
-        drmMessage = vendorMessage.string();
-    }
-
-    if (err == BAD_VALUE) {
-        jniThrowException(env, "java/lang/IllegalArgumentException", msg);
-        return true;
-    } else if (err == ERROR_DRM_NOT_PROVISIONED) {
-        jniThrowException(env, "android/media/NotProvisionedException", msg);
-        return true;
-    } else if (err == ERROR_DRM_RESOURCE_BUSY) {
-        jniThrowException(env, "android/media/ResourceBusyException", msg);
-        return true;
-    } else if (err == ERROR_DRM_DEVICE_REVOKED) {
-        jniThrowException(env, "android/media/DeniedByServerException", msg);
-        return true;
-    } else if (err == DEAD_OBJECT) {
-        jniThrowException(env, "android/media/MediaDrmResetException",
-                          "mediaserver died");
-        return true;
-    } else if (err != OK) {
-        String8 errbuf;
-        if (drmMessage != NULL) {
-            if (msg == NULL) {
-                msg = drmMessage;
-            } else {
-                errbuf = String8::format("%s: %s", msg, drmMessage);
-                msg = errbuf.string();
-            }
-        }
-        throwDrmStateException(env, msg, err);
-        return true;
-    }
-    return false;
-}
-
-static Vector<uint8_t> JByteArrayToVector(JNIEnv *env, jbyteArray const &byteArray)
-{
-    Vector<uint8_t> vector;
-    size_t length = env->GetArrayLength(byteArray);
-    vector.insertAt((size_t)0, length);
-    env->GetByteArrayRegion(byteArray, 0, length, (jbyte *)vector.editArray());
-    return vector;
-}
-
-static void android_media_MediaPlayer2_prepareDrm(JNIEnv *env, jobject thiz,
-                    jlong srcId, jbyteArray uuidObj, jbyteArray drmSessionIdObj)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    if (uuidObj == NULL) {
-        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
-        return;
-    }
-
-    Vector<uint8_t> uuid = JByteArrayToVector(env, uuidObj);
-
-    if (uuid.size() != 16) {
-        jniThrowException(
-                          env,
-                          "java/lang/IllegalArgumentException",
-                          "invalid UUID size, expected 16 bytes");
-        return;
-    }
-
-    Vector<uint8_t> drmSessionId = JByteArrayToVector(env, drmSessionIdObj);
-
-    if (drmSessionId.size() == 0) {
-        jniThrowException(
-                          env,
-                          "java/lang/IllegalArgumentException",
-                          "empty drmSessionId");
-        return;
-    }
-
-    status_t err = mp->prepareDrm(srcId, uuid.array(), drmSessionId);
-    if (err != OK) {
-        if (err == INVALID_OPERATION) {
-            jniThrowException(
-                              env,
-                              "java/lang/IllegalStateException",
-                              "The player must be in prepared state.");
-        } else if (err == ERROR_DRM_CANNOT_HANDLE) {
-            jniThrowException(
-                              env,
-                              "android/media/UnsupportedSchemeException",
-                              "Failed to instantiate drm object.");
-        } else {
-            throwDrmExceptionAsNecessary(env, err, "Failed to prepare DRM scheme");
-        }
-    }
-}
-
-static void android_media_MediaPlayer2_releaseDrm(JNIEnv *env, jobject thiz, jlong srcId)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL ) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        return;
-    }
-
-    status_t err = mp->releaseDrm(srcId);
-    if (err != OK) {
-        if (err == INVALID_OPERATION) {
-            jniThrowException(
-                              env,
-                              "java/lang/IllegalStateException",
-                              "Can not release DRM in an active player state.");
-        }
-    }
-}
-// Modular DRM end
-// ----------------------------------------------------------------------------
-
-/////////////////////////////////////////////////////////////////////////////////////
-// AudioRouting begin
-static jboolean android_media_MediaPlayer2_setPreferredDevice(JNIEnv *env, jobject thiz, jobject device)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        return false;
-    }
-    return mp->setPreferredDevice(device) == NO_ERROR;
-}
-
-static jobject android_media_MediaPlayer2_getRoutedDevice(JNIEnv *env, jobject thiz)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        return nullptr;
-    }
-    return mp->getRoutedDevice();
-}
-
-static void android_media_MediaPlayer2_addDeviceCallback(
-        JNIEnv* env, jobject thiz, jobject routingDelegate)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        return;
-    }
-
-    status_t status = mp->addAudioDeviceCallback(routingDelegate);
-    if (status != NO_ERROR) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        ALOGE("enable device callback failed: %d", status);
-    }
-}
-
-static void android_media_MediaPlayer2_removeDeviceCallback(
-        JNIEnv* env, jobject thiz, jobject listener)
-{
-    sp<MediaPlayer2> mp = getMediaPlayer(env, thiz);
-    if (mp == NULL) {
-        return;
-    }
-
-    status_t status = mp->removeAudioDeviceCallback(listener);
-    if (status != NO_ERROR) {
-        jniThrowException(env, "java/lang/IllegalStateException", NULL);
-        ALOGE("enable device callback failed: %d", status);
-    }
-}
-
-// AudioRouting end
-// ----------------------------------------------------------------------------
-
-/////////////////////////////////////////////////////////////////////////////////////
-// AudioTrack.StreamEventCallback begin
-static void android_media_MediaPlayer2_native_on_tear_down(JNIEnv *env __unused,
-        jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
-{
-    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
-    if (callback != NULL) {
-        callback(JAudioTrack::EVENT_NEW_IAUDIOTRACK, (void *) userDataPtr, NULL);
-    }
-}
-
-static void android_media_MediaPlayer2_native_on_stream_presentation_end(JNIEnv *env __unused,
-        jobject thiz __unused, jlong callbackPtr, jlong userDataPtr)
-{
-    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
-    if (callback != NULL) {
-        callback(JAudioTrack::EVENT_STREAM_END, (void *) userDataPtr, NULL);
-    }
-}
-
-static void android_media_MediaPlayer2_native_on_stream_data_request(JNIEnv *env __unused,
-        jobject thiz __unused, jlong jAudioTrackPtr, jlong callbackPtr, jlong userDataPtr)
-{
-    JAudioTrack::callback_t callback = (JAudioTrack::callback_t) callbackPtr;
-    JAudioTrack* track = (JAudioTrack *) jAudioTrackPtr;
-    if (callback != NULL && track != NULL) {
-        JAudioTrack::Buffer* buffer = new JAudioTrack::Buffer();
-
-        size_t bufferSizeInFrames = track->frameCount();
-        audio_format_t format = track->format();
-
-        size_t bufferSizeInBytes;
-        if (audio_has_proportional_frames(format)) {
-            bufferSizeInBytes =
-                    bufferSizeInFrames * audio_bytes_per_sample(format) * track->channelCount();
-        } else {
-            // See Javadoc of AudioTrack::getBufferSizeInFrames().
-            bufferSizeInBytes = bufferSizeInFrames;
-        }
-
-        uint8_t* byteBuffer = new uint8_t[bufferSizeInBytes];
-        buffer->mSize = bufferSizeInBytes;
-        buffer->mData = (void *) byteBuffer;
-
-        callback(JAudioTrack::EVENT_MORE_DATA, (void *) userDataPtr, buffer);
-
-        if (buffer->mSize > 0 && buffer->mData == byteBuffer) {
-            track->write(buffer->mData, buffer->mSize, true /* Blocking */);
-        }
-
-        delete[] byteBuffer;
-        delete buffer;
-    }
-}
-
-
-// AudioTrack.StreamEventCallback end
-// ----------------------------------------------------------------------------
-
-static const JNINativeMethod gMethods[] = {
-    {
-        "nativeHandleDataSourceUrl",
-        "(ZJLandroid/media/Media2HTTPService;Ljava/lang/String;[Ljava/lang/String;"
-        "[Ljava/lang/String;JJ)V",
-        (void *)android_media_MediaPlayer2_handleDataSourceUrl
-    },
-    {
-        "nativeHandleDataSourceFD",
-        "(ZJLjava/io/FileDescriptor;JJJJ)V",
-        (void *)android_media_MediaPlayer2_handleDataSourceFD
-    },
-    {
-        "nativeHandleDataSourceCallback",
-        "(ZJLandroid/media/DataSourceCallback;JJ)V",
-        (void *)android_media_MediaPlayer2_handleDataSourceCallback
-    },
-    {"nativePlayNextDataSource", "(J)V",                        (void *)android_media_MediaPlayer2_playNextDataSource},
-    {"native_setVideoSurface", "(Landroid/view/Surface;)V",     (void *)android_media_MediaPlayer2_setVideoSurface},
-    {"getBufferingParams", "()Landroid/media/BufferingParams;", (void *)android_media_MediaPlayer2_getBufferingParams},
-    {"native_setBufferingParams", "(Landroid/media/BufferingParams;)V", (void *)android_media_MediaPlayer2_setBufferingParams},
-    {"native_prepare",      "()V",                              (void *)android_media_MediaPlayer2_prepare},
-    {"native_start",        "()V",                              (void *)android_media_MediaPlayer2_start},
-    {"native_getState",     "()I",                              (void *)android_media_MediaPlayer2_getState},
-    {"native_getMetrics",   "()Landroid/os/PersistableBundle;", (void *)android_media_MediaPlayer2_native_getMetrics},
-    {"native_setPlaybackParams", "(Landroid/media/PlaybackParams;)V", (void *)android_media_MediaPlayer2_setPlaybackParams},
-    {"getPlaybackParams", "()Landroid/media/PlaybackParams;",   (void *)android_media_MediaPlayer2_getPlaybackParams},
-    {"native_setSyncParams",     "(Landroid/media/SyncParams;)V",     (void *)android_media_MediaPlayer2_setSyncParams},
-    {"getSyncParams",     "()Landroid/media/SyncParams;",       (void *)android_media_MediaPlayer2_getSyncParams},
-    {"native_seekTo",       "(JI)V",                            (void *)android_media_MediaPlayer2_seekTo},
-    {"native_pause",        "()V",                              (void *)android_media_MediaPlayer2_pause},
-    {"getCurrentPosition",  "()J",                              (void *)android_media_MediaPlayer2_getCurrentPosition},
-    {"native_getDuration",  "(J)J",                             (void *)android_media_MediaPlayer2_getDuration},
-    {"native_release",      "()V",                              (void *)android_media_MediaPlayer2_release},
-    {"native_reset",        "()V",                              (void *)android_media_MediaPlayer2_reset},
-    {"native_setAudioAttributes", "(Landroid/media/AudioAttributes;)Z", (void *)android_media_MediaPlayer2_setAudioAttributes},
-    {"native_getAudioAttributes", "()Landroid/media/AudioAttributes;", (void *)android_media_MediaPlayer2_getAudioAttributes},
-    {"setLooping",          "(Z)V",                             (void *)android_media_MediaPlayer2_setLooping},
-    {"isLooping",           "()Z",                              (void *)android_media_MediaPlayer2_isLooping},
-    {"native_setVolume",    "(F)V",                             (void *)android_media_MediaPlayer2_setVolume},
-    {"native_invoke",       "([B)[B",                           (void *)android_media_MediaPlayer2_invoke},
-    {"native_init",         "()V",                              (void *)android_media_MediaPlayer2_native_init},
-    {"native_setup",        "(ILjava/lang/Object;)V",           (void *)android_media_MediaPlayer2_native_setup},
-    {"native_finalize",     "()V",                              (void *)android_media_MediaPlayer2_native_finalize},
-    {"getAudioSessionId",   "()I",                              (void *)android_media_MediaPlayer2_getAudioSessionId},
-    {"native_setAudioSessionId", "(I)V",                        (void *)android_media_MediaPlayer2_setAudioSessionId},
-    {"native_setAuxEffectSendLevel", "(F)V",                    (void *)android_media_MediaPlayer2_setAuxEffectSendLevel},
-    {"native_attachAuxEffect", "(I)V",                          (void *)android_media_MediaPlayer2_attachAuxEffect},
-    // Modular DRM
-    { "native_prepareDrm", "(J[B[B)V",                          (void *)android_media_MediaPlayer2_prepareDrm },
-    { "native_releaseDrm", "(J)V",                              (void *)android_media_MediaPlayer2_releaseDrm },
-
-    // AudioRouting
-    {"native_setPreferredDevice", "(Landroid/media/AudioDeviceInfo;)Z", (void *)android_media_MediaPlayer2_setPreferredDevice},
-    {"getRoutedDevice", "()Landroid/media/AudioDeviceInfo;", (void *)android_media_MediaPlayer2_getRoutedDevice},
-    {"native_addDeviceCallback", "(Landroid/media/RoutingDelegate;)V", (void *)android_media_MediaPlayer2_addDeviceCallback},
-    {"native_removeDeviceCallback", "(Landroid/media/AudioRouting$OnRoutingChangedListener;)V",
-            (void *)android_media_MediaPlayer2_removeDeviceCallback},
-
-    // StreamEventCallback for JAudioTrack
-    {"native_stream_event_onTearDown",                "(JJ)V",  (void *)android_media_MediaPlayer2_native_on_tear_down},
-    {"native_stream_event_onStreamPresentationEnd",   "(JJ)V",  (void *)android_media_MediaPlayer2_native_on_stream_presentation_end},
-    {"native_stream_event_onStreamDataRequest",       "(JJJ)V", (void *)android_media_MediaPlayer2_native_on_stream_data_request},
-};
-
-// This function only registers the native methods
-static int register_android_media_MediaPlayer2(JNIEnv *env)
-{
-    return jniRegisterNativeMethods(env, "android/media/MediaPlayer2", gMethods, NELEM(gMethods));
-}
-
-jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
-{
-    JNIEnv* env = NULL;
-    jint result = -1;
-
-    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
-        ALOGE("ERROR: GetEnv failed\n");
-        goto bail;
-    }
-    assert(env != NULL);
-
-    if (register_android_media_MediaPlayer2(env) < 0) {
-        ALOGE("ERROR: MediaPlayer2 native registration failed\n");
-        goto bail;
-    }
-
-    JavaVMHelper::setJavaVM(vm);
-
-    /* success -- return valid version number */
-    result = JNI_VERSION_1_4;
-
-bail:
-    return result;
-}
-
-// KTHXBYE
diff --git a/media/lib/signer/Android.bp b/media/lib/signer/Android.bp
index 2286c53..6b03e4d 100644
--- a/media/lib/signer/Android.bp
+++ b/media/lib/signer/Android.bp
@@ -16,9 +16,8 @@
 
 java_sdk_library {
     name: "com.android.mediadrm.signer",
-    srcs: [
-        "java/**/*.java",
-        ":framework-all-sources",
-    ],
+    srcs: ["java/**/*.java"],
+    api_srcs: [":framework-all-sources"],
+    libs: ["framework-all"],
     api_packages: ["com.android.mediadrm.signer"],
 }
diff --git a/media/proto/Android.bp b/media/proto/Android.bp
deleted file mode 100644
index 2dc0d57..0000000
--- a/media/proto/Android.bp
+++ /dev/null
@@ -1,20 +0,0 @@
-java_library_static {
-    name: "mediaplayer2-protos",
-    host_supported: true,
-    proto: {
-        type: "lite",
-    },
-    srcs: ["mediaplayer2.proto"],
-    jarjar_rules: "jarjar-rules.txt",
-    sdk_version: "28",
-}
-
-cc_library_static {
-    name: "libmediaplayer2-protos",
-    host_supported: true,
-    proto: {
-        export_proto_headers: true,
-        type: "lite",
-    },
-    srcs: ["mediaplayer2.proto"],
-}
diff --git a/media/proto/jarjar-rules.txt b/media/proto/jarjar-rules.txt
deleted file mode 100644
index e73f86d..0000000
--- a/media/proto/jarjar-rules.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-rule com.google.protobuf.** android.media.protobuf.@1
-
diff --git a/media/proto/mediaplayer2.proto b/media/proto/mediaplayer2.proto
deleted file mode 100644
index 6287d6c..0000000
--- a/media/proto/mediaplayer2.proto
+++ /dev/null
@@ -1,53 +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.
- */
-
-syntax = "proto2";
-
-option optimize_for = LITE_RUNTIME;
-
-// C++ namespace: android::media:MediaPlayer2Proto:
-package android.media.MediaPlayer2Proto;
-
-option java_package = "android.media";
-option java_outer_classname = "MediaPlayer2Proto";
-
-message Value {
-    // The kind of value.
-    oneof kind {
-        // Represents a boolean value.
-        bool bool_value = 1;
-        // Represents an int32 value.
-        int32 int32_value = 2;
-        // Represents an uint32 value.
-        uint32 uint32_value = 3;
-        // Represents an int64 value.
-        int64 int64_value = 4;
-        // Represents an uint64 value.
-        uint64 uint64_value = 5;
-        // Represents a float value.
-        double float_value = 6;
-        // Represents a double value.
-        double double_value = 7;
-        // Represents a string value.
-        string string_value = 8;
-        // Represents a bytes value.
-        bytes bytes_value = 9;
-    }
-}
-
-message PlayerMessage {
-    repeated Value values = 1;
-}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaFileTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaFileTest.java
index 38f0175..481f479 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaFileTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaFileTest.java
@@ -31,7 +31,7 @@
 
 import androidx.test.runner.AndroidJUnit4;
 
-import libcore.net.MimeMap;
+import libcore.content.type.MimeMap;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java
index 3abf0a4..a3ed07a 100644
--- a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java
+++ b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouterManagerTest.java
@@ -27,6 +27,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.media.MediaRoute2Info;
+import android.media.MediaRouter;
 import android.media.MediaRouter2;
 import android.media.MediaRouter2Manager;
 import android.support.test.InstrumentationRegistry;
@@ -72,7 +73,8 @@
 
     private Context mContext;
     private MediaRouter2Manager mManager;
-    private MediaRouter2 mRouter;
+    private MediaRouter mRouter;
+    private MediaRouter2 mRouter2;
     private Executor mExecutor;
     private String mPackageName;
 
@@ -89,7 +91,8 @@
     public void setUp() throws Exception {
         mContext = InstrumentationRegistry.getTargetContext();
         mManager = MediaRouter2Manager.getInstance(mContext);
-        mRouter = MediaRouter2.getInstance(mContext);
+        mRouter = (MediaRouter) mContext.getSystemService(Context.MEDIA_ROUTER_SERVICE);
+        mRouter2 = MediaRouter2.getInstance(mContext);
         //TODO: If we need to support thread pool executors, change this to thread pool executor.
         mExecutor = Executors.newSingleThreadExecutor();
         mPackageName = mContext.getPackageName();
@@ -131,12 +134,12 @@
 
         //TODO: Figure out a more proper way to test.
         // (Control requests shouldn't be used in this way.)
-        mRouter.setControlCategories(CONTROL_CATEGORIES_ALL);
-        mRouter.registerCallback(mExecutor, mockRouterCallback);
-        mRouter.sendControlRequest(
+        mRouter2.setControlCategories(CONTROL_CATEGORIES_ALL);
+        mRouter2.registerCallback(mExecutor, mockRouterCallback);
+        mRouter2.sendControlRequest(
                 new MediaRoute2Info.Builder(ROUTE_ID2, ROUTE_NAME2).build(),
                 new Intent(ACTION_REMOVE_ROUTE));
-        mRouter.unregisterCallback(mockRouterCallback);
+        mRouter2.unregisterCallback(mockRouterCallback);
 
         verify(mockCallback, timeout(TIMEOUT_MS)).onRouteRemoved(argThat(
                 (MediaRoute2Info info) ->
@@ -148,15 +151,41 @@
      * Tests if we get proper routes for application that has special control category.
      */
     @Test
+    public void testControlCategoryWithMediaRouter() throws Exception {
+        MediaRouter2Manager.Callback mockCallback = mock(MediaRouter2Manager.Callback.class);
+        mManager.registerCallback(mExecutor, mockCallback);
+
+        MediaRouter.Callback mockRouterCallback = mock(MediaRouter.Callback.class);
+
+        mRouter.setControlCategories(CONTROL_CATEGORIES_SPECIAL);
+        mRouter.addCallback(MediaRouter.ROUTE_TYPE_USER, mockRouterCallback);
+
+        verify(mockCallback, timeout(TIMEOUT_MS))
+                .onRoutesChanged(argThat(routes -> routes.size() > 0));
+
+        Map<String, MediaRoute2Info> routes =
+                createRouteMap(mManager.getAvailableRoutes(mPackageName));
+
+        Assert.assertEquals(1, routes.size());
+        Assert.assertNotNull(routes.get(ROUTE_ID_SPECIAL_CATEGORY));
+
+        mRouter.removeCallback(mockRouterCallback);
+        mManager.unregisterCallback(mockCallback);
+    }
+
+    /**
+     * Tests if we get proper routes for application that has special control category.
+     */
+    @Test
     public void testControlCategory() throws Exception {
         MediaRouter2Manager.Callback mockCallback = mock(MediaRouter2Manager.Callback.class);
         mManager.registerCallback(mExecutor, mockCallback);
 
         MediaRouter2.Callback mockRouterCallback = mock(MediaRouter2.Callback.class);
 
-        mRouter.setControlCategories(CONTROL_CATEGORIES_SPECIAL);
-        mRouter.registerCallback(mExecutor, mockRouterCallback);
-        mRouter.unregisterCallback(mockRouterCallback);
+        mRouter2.setControlCategories(CONTROL_CATEGORIES_SPECIAL);
+        mRouter2.registerCallback(mExecutor, mockRouterCallback);
+        mRouter2.unregisterCallback(mockRouterCallback);
 
         verify(mockCallback, timeout(TIMEOUT_MS))
                 .onRoutesChanged(argThat(routes -> routes.size() > 0));
@@ -177,15 +206,15 @@
     public void testGetRoutes() throws Exception {
         MediaRouter2.Callback mockCallback = mock(MediaRouter2.Callback.class);
 
-        mRouter.setControlCategories(CONTROL_CATEGORIES_SPECIAL);
-        mRouter.registerCallback(mExecutor, mockCallback);
+        mRouter2.setControlCategories(CONTROL_CATEGORIES_SPECIAL);
+        mRouter2.registerCallback(mExecutor, mockCallback);
         verify(mockCallback, timeout(TIMEOUT_MS).atLeastOnce())
                 .onRoutesChanged(argThat(routes -> routes.size() > 0));
-        Map<String, MediaRoute2Info> routes = createRouteMap(mRouter.getRoutes());
+        Map<String, MediaRoute2Info> routes = createRouteMap(mRouter2.getRoutes());
         Assert.assertEquals(1, routes.size());
         Assert.assertNotNull(routes.get(ROUTE_ID_SPECIAL_CATEGORY));
 
-        mRouter.unregisterCallback(mockCallback);
+        mRouter2.unregisterCallback(mockCallback);
     }
 
     @Test
@@ -194,8 +223,8 @@
         MediaRouter2Manager.Callback managerCallback = mock(MediaRouter2Manager.Callback.class);
 
         mManager.registerCallback(mExecutor, managerCallback);
-        mRouter.setControlCategories(CONTROL_CATEGORIES_ALL);
-        mRouter.registerCallback(mExecutor, mockRouterCallback);
+        mRouter2.setControlCategories(CONTROL_CATEGORIES_ALL);
+        mRouter2.registerCallback(mExecutor, mockRouterCallback);
 
         verify(managerCallback, timeout(TIMEOUT_MS))
                 .onRoutesChanged(argThat(routes -> routes.size() > 0));
@@ -211,7 +240,7 @@
                 .onRouteAdded(argThat(route -> route.equals(routeToSelect)));
 
         mManager.unregisterCallback(managerCallback);
-        mRouter.unregisterCallback(mockRouterCallback);
+        mRouter2.unregisterCallback(mockRouterCallback);
     }
 
     /**
@@ -223,8 +252,8 @@
         MediaRouter2.Callback routerCallback = mock(MediaRouter2.Callback.class);
 
         mManager.registerCallback(mExecutor, managerCallback);
-        mRouter.setControlCategories(CONTROL_CATEGORIES_ALL);
-        mRouter.registerCallback(mExecutor, routerCallback);
+        mRouter2.setControlCategories(CONTROL_CATEGORIES_ALL);
+        mRouter2.registerCallback(mExecutor, routerCallback);
 
         verify(managerCallback, timeout(TIMEOUT_MS))
                 .onRoutesChanged(argThat(routes -> routes.size() > 0));
@@ -248,7 +277,7 @@
                 .onRouteChanged(argThat(routeInfo -> TextUtils.equals(ROUTE_ID2, routeInfo.getId())
                         && TextUtils.equals(routeInfo.getClientPackageName(), null)));
 
-        mRouter.unregisterCallback(routerCallback);
+        mRouter2.unregisterCallback(routerCallback);
         mManager.unregisterCallback(managerCallback);
     }
 
diff --git a/mime/Android.bp b/mime/Android.bp
new file mode 100644
index 0000000..23a8fbf
--- /dev/null
+++ b/mime/Android.bp
@@ -0,0 +1,121 @@
+// Copyright (C) 2019 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.
+
+
+java_defaults {
+    name: "mimemap-defaults",
+    srcs: [
+        "java/android/content/type/DefaultMimeMapFactory.java",
+    ],
+    sdk_version: "core_platform",
+}
+
+java_library {
+    name: "mimemap",
+    defaults: ["mimemap-defaults"],
+    static_libs: ["mimemap-res.jar"],
+    visibility: [
+        "//frameworks/base:__subpackages__",
+    ],
+}
+
+java_library {
+    name: "mimemap-testing",
+    defaults: ["mimemap-defaults"],
+    static_libs: ["mimemap-testing-res.jar"],
+    jarjar_rules: "jarjar-rules.txt",
+    visibility: [
+        "//cts/tests/tests/mimemap:__subpackages__",
+        "//frameworks/base:__subpackages__",
+    ],
+}
+
+// The mimemap-res.jar and mimemap-testing-res.jar genrules produce a .jar that
+// has the resource file in a subdirectory res/ and testres/, respectively.
+// They need to be in different paths because one of them ends up in a
+// bootclasspath jar whereas the other one ends up in a test jar. Bootclasspath
+// resources hide test or application resources under the same path because
+// ClassLoader.getResource(String) consults the parent ClassLoader first.
+//
+// Further notes:
+//  - the "cp" command will flatten any directory paths that occur in $(in),
+//    but here they happen to already be in the root directory. If we needed
+//    to preserve sub paths then we might want to zip the files first and then
+//    unzip them below the new parent directory.
+//  - the path names "res/" and "testres/" and duplicated in .java source files
+//    (DefaultMimeMapFactory.java and MimeMapTest.java, as of October 2019).
+java_genrule {
+    name: "mimemap-res.jar",
+    tools: [
+        "soong_zip",
+    ],
+    srcs: [":mime.types.minimized"],
+    out: ["mimemap-res.jar"],
+    cmd: "mkdir $(genDir)/res/ && cp $(in) $(genDir)/res/ && $(location soong_zip) -C $(genDir) -o $(out) -D $(genDir)/res/",
+}
+
+// The same as mimemap-res.jar except that the resources are placed in a different directory.
+// They get bundled with CTS so that CTS can compare a device's MimeMap implementation vs.
+// the stock Android one from when CTS was built.
+java_genrule {
+    name: "mimemap-testing-res.jar",
+    tools: [
+        "soong_zip",
+    ],
+    srcs: [":mime.types.minimized"],
+    out: ["mimemap-testing-res.jar"],
+    cmd: "mkdir $(genDir)/testres/ && cp $(in) $(genDir)/testres/ && $(location soong_zip) -C $(genDir) -o $(out) -D $(genDir)/testres/",
+}
+
+// Combination of all *mime.types.minimized resources.
+filegroup {
+    name: "mime.types.minimized",
+    visibility: [
+        "//visibility:private",
+    ],
+    srcs: [
+        ":debian.mime.types.minimized",
+        ":android.mime.types.minimized",
+        ":vendor.mime.types.minimized",
+    ],
+}
+
+java_genrule {
+    name: "android.mime.types.minimized",
+    visibility: [
+        "//visibility:private",
+    ],
+    out: ["android.mime.types"],
+    srcs: [
+        "java-res/android.mime.types",
+    ],
+    //    strip comments            normalize whitepace       drop empty lines
+    cmd: "awk '{gsub(/#.*$$/,\"\"); $$1=$$1; print;}' $(in) | grep ' ' > $(out)",
+}
+
+// Unlike the other *mime.types files, vendor.mime.types gets '?' prepended to
+// every field so that its mappings will never overwrite earlier mappings by
+// the other resource files. http://b/141842825
+java_genrule {
+    name: "vendor.mime.types.minimized",
+    visibility: [
+        "//visibility:private",
+    ],
+    out: ["vendor.mime.types"],
+    srcs: [
+        "java-res/vendor.mime.types",
+    ],
+    //    strip comments            normalize whitepace       drop empty lines   prepend ? to fields that are missing it
+    cmd: "awk '{gsub(/#.*$$/,\"\"); $$1=$$1; print;}' $(in) | grep ' '         | awk '{for(i=1;i<=NF;i++) { sub(/^\\??/, \"?\", $$i); }; print}' > $(out)",
+}
diff --git a/mime/TEST_MAPPING b/mime/TEST_MAPPING
new file mode 100644
index 0000000..8daab75
--- /dev/null
+++ b/mime/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsMimeMapTestCases"
+    }
+  ]
+}
diff --git a/mime/jarjar-rules.txt b/mime/jarjar-rules.txt
new file mode 100644
index 0000000..145d1db
--- /dev/null
+++ b/mime/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.content.type.DefaultMimeMapFactory android.content.type.cts.StockAndroidMimeMapFactory
\ No newline at end of file
diff --git a/mime/java-res/android.mime.types b/mime/java-res/android.mime.types
new file mode 100644
index 0000000..7a5299f
--- /dev/null
+++ b/mime/java-res/android.mime.types
@@ -0,0 +1,146 @@
+
+###############################################################################
+#
+# Android-specific MIME type <-> extension mappings
+#
+# Each line below defines a mapping from one MIME type to the first of the
+# listed extensions, and from listed extension back to the MIME type.
+# A mapping overrides any previous mapping _from_ that same MIME type or
+# extension (put() semantics), unless that MIME type / extension is prefixed with '?'
+# (putIfAbsent() semantics).
+#
+#
+###############################################################################
+#
+# EXAMPLES
+#
+# A line of the form:
+#
+#    ?mime ext1 ?ext2 ext3
+#
+# affects the current mappings along the lines of the following pseudo code:
+#
+#    mimeToExt.putIfAbsent("mime", "ext1");
+#    extToMime.put("ext1", "mime");
+#    extToMime.putIfAbsent("ext2", "mime");
+#    extToMime.put("ext3", "mime");
+#
+# The line:
+#
+#     ?text/plain txt
+#
+# leaves any earlier mapping for "text/plain" untouched, or maps that MIME type
+# to the file extension ".txt" if there is no earlier mapping. The line also
+# sets the mapping from file extension ".txt" to be the MIME type "text/plain",
+# regardless of whether a previous mapping existed.
+#
+###############################################################################
+
+
+# File extensions that Android wants to override to point to the given MIME type.
+#
+# After processing a line of the form:
+# ?<mimeType> <extension1> <extension2>
+# If <mimeType> was not already mapped to an extension then it will be
+# mapped to <extension1>.
+# <extension1> and <extension2> are mapped (or remapped) to <mimeType>.
+
+?application/epub+zip epub
+?application/pkix-cert cer
+?application/rss+xml rss
+?application/vnd.android.ota ota
+?application/vnd.apple.mpegurl m3u8
+?application/vnd.ms-pki.stl stl
+?application/vnd.ms-powerpoint pot
+?application/vnd.ms-wpl wpl
+?application/vnd.stardivision.impress sdp
+?application/vnd.stardivision.writer vor
+?application/vnd.youtube.yt yt
+?application/x-android-drm-fl fl
+?application/x-flac flac
+?application/x-font pcf
+?application/x-mpegurl m3u m3u8
+?application/x-pem-file pem
+?application/x-pkcs12 p12 pfx
+?application/x-webarchive webarchive
+?application/x-webarchive-xml webarchivexml
+?application/x-x509-server-cert crt
+?application/x-x509-user-cert crt
+
+?audio/3gpp 3gpp
+?audio/aac-adts aac
+?audio/imelody imy
+?audio/midi rtttl xmf
+?audio/mobile-xmf mxmf
+?audio/mp4 m4a
+?audio/mpegurl m3u
+?audio/sp-midi smf
+?audio/x-matroska mka
+?audio/x-pn-realaudio ra
+
+?image/bmp bmp
+?image/heic heic
+?image/heic-sequence heics
+?image/heif heif hif
+?image/heif-sequence heifs
+?image/ico cur
+?image/webp webp
+?image/x-adobe-dng dng
+?image/x-fuji-raf raf
+?image/x-icon ico
+?image/x-nikon-nrw nrw
+?image/x-panasonic-rw2 rw2
+?image/x-pentax-pef pef
+?image/x-samsung-srw srw
+?image/x-sony-arw arw
+
+?text/comma-separated-values csv
+?text/plain diff po
+?text/rtf rtf
+?text/text phps
+?text/xml xml
+?text/x-vcard vcf
+
+?video/3gpp2 3gpp2 3g2
+?video/3gpp 3gpp
+?video/avi avi
+?video/m4v m4v
+?video/mp2p mpeg
+?video/mp2t m2ts mts
+?video/mp2ts ts
+?video/vnd.youtube.yt yt
+?video/x-webex wrf
+
+# Optional additions that should not override any previous mapping.
+
+?application/x-wifi-config ?xml
+
+# Special cases where Android has a strong opinion about mappings, so we
+# define them very last and make them override in both directions (no "?").
+#
+# Lines here are of the form:
+# <mimeType> <extension1> <extension2> ...
+#
+# After processing each line,
+#   <mimeType> is mapped to <extension1>
+#   <extension1>, <extension2>, ... are all mapped to <mimeType>
+# This overrides any mappings for this <mimeType> / for these extensions
+# that may have been defined earlier.
+
+application/pgp-signature pgp
+application/x-x509-ca-cert crt
+audio/aac aac
+audio/basic snd
+audio/flac flac
+audio/midi rtx
+audio/mpeg mp3 m4a m4r
+audio/x-mpegurl m3u m3u8
+image/jpeg jpg
+image/x-ms-bmp bmp
+text/plain txt
+text/x-c++hdr hpp
+text/x-c++src cpp
+video/3gpp 3gpp
+video/mpeg mpeg
+video/quicktime mov
+video/x-matroska mkv
diff --git a/mime/java-res/vendor.mime.types b/mime/java-res/vendor.mime.types
new file mode 100644
index 0000000..afb8f9e
--- /dev/null
+++ b/mime/java-res/vendor.mime.types
@@ -0,0 +1,41 @@
+###############################################################################
+#
+# Vendor-specific MIME type <-> extension mappings
+#
+# Each line below defines a mapping from one MIME type to the first of the
+# listed extensions, and from listed extension back to the MIME type.
+#
+# This file can _add_ additional mappings that are not in the default set,
+# but it it cannot _modify_ (replace or remove) any platform default mapping
+# (defined in files mime.types and android.mime.types).
+#
+###############################################################################
+#
+# EXAMPLES
+#
+# A line of the form (without the leading '#''):
+#
+#    mime ext1 ext2 ext3
+#
+# affects the current mappings along the lines of the following pseudo code:
+#
+#    mimeToExt.putIfAbsent("mime", "ext1");
+#    extToMime.putIfAbsent("ext1", "mime");
+#    extToMime.putIfAbsent("ext2", "mime");
+#    extToMime.putIfAbsent("ext3", "mime");
+#
+# Optionally, MIME types or extensions may be prefixed by a single '?', which
+# will be ignored. I.e., the following example lines all have the same semantics:
+#
+#    mime ext1 ext2 ext3
+#    ?mime ext1 ext2 ext3
+#    mime ?ext1 ext2 ?ext3
+#    ?mime ?ext1 ?ext2 ?ext3
+#
+# By default, this file contains no mappings (which means that the platform
+# default mapping is used unmodified).
+#
+###############################################################################
+#
+# Add your custom mappings below this line (with no "#" at the start of the line):
+
diff --git a/mime/java/android/content/type/DefaultMimeMapFactory.java b/mime/java/android/content/type/DefaultMimeMapFactory.java
new file mode 100644
index 0000000..11d20d4
--- /dev/null
+++ b/mime/java/android/content/type/DefaultMimeMapFactory.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2019 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.content.type;
+
+import libcore.content.type.MimeMap;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+
+/**
+ * Creates the framework default {@link MimeMap}, a bidirectional mapping
+ * between MIME types and file extensions.
+ *
+ * This default mapping is loaded from data files that start with some mappings
+ * recognized by IANA plus some custom extensions and overrides.
+ *
+ * @hide
+ */
+public class DefaultMimeMapFactory {
+
+    private DefaultMimeMapFactory() {
+    }
+
+    /**
+     * Creates and returns a new {@link MimeMap} instance that implements.
+     * Android's default mapping between MIME types and extensions.
+     */
+    public static MimeMap create() {
+        Class c = DefaultMimeMapFactory.class;
+        // The resources are placed into the res/ path by the "mimemap-res.jar" genrule.
+        return create(resourceName -> c.getResourceAsStream("/res/" + resourceName));
+    }
+
+    /**
+     * Creates a {@link MimeMap} instance whose resources are loaded from the
+     * InputStreams looked up in {@code resourceSupplier}.
+     *
+     * @hide
+     */
+    public static MimeMap create(Function<String, InputStream> resourceSupplier) {
+        MimeMap.Builder builder = MimeMap.builder();
+        // The files loaded here must be in minimized format with lines of the
+        // form "mime/type ext1 ext2 ext3", i.e. no comments, no empty lines, no
+        // leading/trailing whitespace and with a single space between entries on
+        // each line.  See http://b/142267887
+        //
+        // Note: the order here matters - later entries can overwrite earlier ones
+        // (except that vendor.mime.types entries are prefixed with '?' which makes
+        // them never overwrite).
+        parseTypes(builder, resourceSupplier, "debian.mime.types");
+        parseTypes(builder, resourceSupplier, "android.mime.types");
+        parseTypes(builder, resourceSupplier, "vendor.mime.types");
+        return builder.build();
+    }
+
+    private static void parseTypes(MimeMap.Builder builder,
+            Function<String, InputStream> resourceSupplier, String resourceName) {
+        try (InputStream inputStream = Objects.requireNonNull(resourceSupplier.apply(resourceName));
+             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
+            String line;
+            List<String> specs = new ArrayList<>(10); // re-use for each line
+            while ((line = reader.readLine()) != null) {
+                specs.clear();
+                // Lines are of the form "mimeSpec extSpec extSpec[...]" with a single space
+                // separating them and no leading/trailing spaces and no empty lines.
+                int startIdx = 0;
+                do {
+                    int endIdx = line.indexOf(' ', startIdx);
+                    if (endIdx < 0) {
+                        endIdx = line.length();
+                    }
+                    String spec = line.substring(startIdx, endIdx);
+                    if (spec.isEmpty()) {
+                        throw new IllegalArgumentException("Malformed line: " + line);
+                    }
+                    specs.add(spec);
+                    startIdx = endIdx + 1; // skip over the space
+                } while (startIdx < line.length());
+                builder.put(specs.get(0), specs.subList(1, specs.size()));
+            }
+        } catch (IOException | RuntimeException e) {
+            throw new RuntimeException("Failed to parse " + resourceName, e);
+        }
+    }
+
+}
diff --git a/mms/OWNERS b/mms/OWNERS
new file mode 100644
index 0000000..ba00d5d
--- /dev/null
+++ b/mms/OWNERS
@@ -0,0 +1,14 @@
+set noparent
+
+tgunn@google.com
+breadley@google.com
+hallliu@google.com
+rgreenwalt@google.com
+amitmahajan@google.com
+fionaxu@google.com
+jackyu@google.com
+jminjie@google.com
+satk@google.com
+shuoq@google.com
+refuhoo@google.com
+nazaninb@google.com
diff --git a/mms/java/android/telephony/MmsManager.java b/mms/java/android/telephony/MmsManager.java
new file mode 100644
index 0000000..4bcf046
--- /dev/null
+++ b/mms/java/android/telephony/MmsManager.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2019 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.telephony;
+
+import android.app.ActivityThread;
+import android.app.PendingIntent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+
+import com.android.internal.telephony.IMms;
+
+/**
+ * Manages MMS operations such as sending multimedia messages.
+ * Get this object by calling the static method {@link #getInstance()}.
+ * @hide
+ */
+public class MmsManager {
+    private static final String TAG = "MmsManager";
+
+    /** Singleton object constructed during class initialization. */
+    private static final MmsManager sInstance = new MmsManager();
+
+    /**
+     * Get the MmsManager singleton instance.
+     *
+     * @return the {@link MmsManager} singleton instance.
+     */
+    public static MmsManager getInstance() {
+        return sInstance;
+    }
+
+    /**
+     * Send an MMS message
+     *
+     * @param subId the subscription id
+     * @param contentUri the content Uri from which the message pdu will be read
+     * @param locationUrl the optional location url where message should be sent to
+     * @param configOverrides the carrier-specific messaging configuration values to override for
+     *                        sending the message.
+     * @param sentIntent if not NULL this <code>PendingIntent</code> is broadcast when the message
+     *                   is successfully sent, or failed
+     */
+    public void sendMultimediaMessage(int subId, Uri contentUri, String locationUrl,
+            Bundle configOverrides, PendingIntent sentIntent) {
+        try {
+            final IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
+            if (iMms == null) {
+                return;
+            }
+
+            iMms.sendMessage(subId, ActivityThread.currentPackageName(), contentUri,
+                    locationUrl, configOverrides, sentIntent);
+        } catch (RemoteException e) {
+            // Ignore it
+        }
+    }
+
+    /**
+     * Download an MMS message from carrier by a given location URL
+     *
+     * @param subId the subscription id
+     * @param locationUrl the location URL of the MMS message to be downloaded, usually obtained
+     *  from the MMS WAP push notification
+     * @param contentUri the content uri to which the downloaded pdu will be written
+     * @param configOverrides the carrier-specific messaging configuration values to override for
+     *  downloading the message.
+     * @param downloadedIntent if not NULL this <code>PendingIntent</code> is
+     *  broadcast when the message is downloaded, or the download is failed
+     * @throws IllegalArgumentException if locationUrl or contentUri is empty
+     */
+    public void downloadMultimediaMessage(int subId, String locationUrl, Uri contentUri,
+            Bundle configOverrides, PendingIntent downloadedIntent) {
+        try {
+            final IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
+            if (iMms == null) {
+                return;
+            }
+            iMms.downloadMessage(subId, ActivityThread.currentPackageName(),
+                    locationUrl, contentUri, configOverrides, downloadedIntent);
+        } catch (RemoteException e) {
+            // Ignore it
+        }
+    }
+
+    /**
+     * Get carrier-dependent configuration values.
+     *
+     * @param subId the subscription id
+     * @return bundle key/values pairs of configuration values
+     */
+    public Bundle getCarrierConfigValues(int subId) {
+        try {
+            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
+            if (iMms != null) {
+                return iMms.getCarrierConfigValues(subId);
+            }
+        } catch (RemoteException ex) {
+            // ignore it
+        }
+        return null;
+    }
+}
diff --git a/telephony/java/com/android/internal/telephony/IMms.aidl b/mms/java/com/android/internal/telephony/IMms.aidl
similarity index 100%
rename from telephony/java/com/android/internal/telephony/IMms.aidl
rename to mms/java/com/android/internal/telephony/IMms.aidl
diff --git a/opengl/java/android/opengl/GLUtils.java b/opengl/java/android/opengl/GLUtils.java
index ca8d5ac..cc46514 100644
--- a/opengl/java/android/opengl/GLUtils.java
+++ b/opengl/java/android/opengl/GLUtils.java
@@ -44,7 +44,7 @@
         if (bitmap.isRecycled()) {
             throw new IllegalArgumentException("bitmap is recycled");
         }
-        int result = native_getInternalFormat(bitmap.getNativeInstance());
+        int result = native_getInternalFormat(bitmap);
         if (result < 0) {
             throw new IllegalArgumentException("Unknown internalformat");
         }
@@ -66,7 +66,7 @@
         if (bitmap.isRecycled()) {
             throw new IllegalArgumentException("bitmap is recycled");
         }
-        int result = native_getType(bitmap.getNativeInstance());
+        int result = native_getType(bitmap);
         if (result < 0) {
             throw new IllegalArgumentException("Unknown type");
         }
@@ -103,8 +103,7 @@
         if (bitmap.isRecycled()) {
             throw new IllegalArgumentException("bitmap is recycled");
         }
-        if (native_texImage2D(target, level, internalformat, bitmap.getNativeInstance(), -1,
-                border) != 0) {
+        if (native_texImage2D(target, level, internalformat, bitmap, -1, border) != 0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
     }
@@ -130,8 +129,7 @@
         if (bitmap.isRecycled()) {
             throw new IllegalArgumentException("bitmap is recycled");
         }
-        if (native_texImage2D(target, level, internalformat, bitmap.getNativeInstance(), type,
-              border) != 0) {
+        if (native_texImage2D(target, level, internalformat, bitmap, type, border) != 0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
     }
@@ -153,7 +151,7 @@
         if (bitmap.isRecycled()) {
             throw new IllegalArgumentException("bitmap is recycled");
         }
-        if (native_texImage2D(target, level, -1, bitmap.getNativeInstance(), -1, border) != 0) {
+        if (native_texImage2D(target, level, -1, bitmap, -1, border) != 0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
     }
@@ -189,8 +187,7 @@
             throw new IllegalArgumentException("bitmap is recycled");
         }
         int type = getType(bitmap);
-        if (native_texSubImage2D(target, level, xoffset, yoffset, bitmap.getNativeInstance(), -1,
-                type) != 0) {
+        if (native_texSubImage2D(target, level, xoffset, yoffset, bitmap, -1, type) != 0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
     }
@@ -214,8 +211,7 @@
         if (bitmap.isRecycled()) {
             throw new IllegalArgumentException("bitmap is recycled");
         }
-        if (native_texSubImage2D(target, level, xoffset, yoffset, bitmap.getNativeInstance(),
-                format, type) != 0) {
+        if (native_texSubImage2D(target, level, xoffset, yoffset, bitmap, format, type) != 0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
     }
@@ -265,10 +261,10 @@
         }
     }
 
-    native private static int native_getInternalFormat(long bitmapHandle);
-    native private static int native_getType(long bitmapHandle);
-    native private static int native_texImage2D(int target, int level, int internalformat,
-            long bitmapHandle, int type, int border);
-    native private static int native_texSubImage2D(int target, int level, int xoffset, int yoffset,
-            long bitmapHandle, int format, int type);
+    private static native int native_getInternalFormat(Bitmap bitmap);
+    private static native int native_getType(Bitmap bitmap);
+    private static native int native_texImage2D(int target, int level, int internalformat,
+            Bitmap bitmap, int type, int border);
+    private static native int native_texSubImage2D(int target, int level, int xoffset, int yoffset,
+            Bitmap bitmap, int format, int type);
 }
diff --git a/packages/BackupEncryption/Android.bp b/packages/BackupEncryption/Android.bp
index 9bcd677..342d796 100644
--- a/packages/BackupEncryption/Android.bp
+++ b/packages/BackupEncryption/Android.bp
@@ -18,6 +18,7 @@
     name: "BackupEncryption",
     srcs: ["src/**/*.java"],
     libs: ["backup-encryption-protos"],
+    static_libs: ["backuplib"],
     optimize: { enabled: false },
     platform_apis: true,
     certificate: "platform",
diff --git a/packages/BackupEncryption/AndroidManifest.xml b/packages/BackupEncryption/AndroidManifest.xml
index a705df5..4d174e3 100644
--- a/packages/BackupEncryption/AndroidManifest.xml
+++ b/packages/BackupEncryption/AndroidManifest.xml
@@ -20,5 +20,14 @@
     package="com.android.server.backup.encryption"
     android:sharedUserId="android.uid.system" >
 
-    <application android:allowBackup="false" />
+    <application android:allowBackup="false" >
+        <!-- This service does not need to be exported because it shares uid with the system server
+        which is the only client. -->
+        <service android:name=".BackupEncryptionService"
+                 android:exported="false">
+            <intent-filter>
+                <action android:name="android.encryption.BACKUP_ENCRYPTION" />
+            </intent-filter>
+        </service>
+    </application>
 </manifest>
diff --git a/packages/BackupEncryption/proto/key_value_listing.proto b/packages/BackupEncryption/proto/key_value_listing.proto
new file mode 100644
index 0000000..001e697
--- /dev/null
+++ b/packages/BackupEncryption/proto/key_value_listing.proto
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2019 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
+ */
+
+syntax = "proto2";
+
+package android_backup_crypto;
+
+option java_package = "com.android.server.backup.encryption.protos";
+option java_outer_classname = "KeyValueListingProto";
+
+// An entry of a key-value pair.
+message KeyValueEntry {
+  // Plaintext key of the key-value pair.
+  optional string key = 1;
+  // SHA-256 MAC of the plaintext of the chunk containing the pair
+  optional bytes hash = 2;
+}
+
+// Describes the key/value pairs currently in the backup blob, mapping from the
+// plaintext key to the hash of the chunk containing the pair.
+//
+// This is local state stored on the device. It is never sent to the
+// backup server. See ChunkOrdering for how the device restores the
+// key-value pairs in the correct order.
+message KeyValueListing {
+  repeated KeyValueEntry entries = 1;
+}
diff --git a/packages/BackupEncryption/proto/key_value_pair.proto b/packages/BackupEncryption/proto/key_value_pair.proto
new file mode 100644
index 0000000..177fa30
--- /dev/null
+++ b/packages/BackupEncryption/proto/key_value_pair.proto
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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
+ */
+
+syntax = "proto2";
+
+package android_backup_crypto;
+
+option java_package = "com.android.server.backup.encryption.protos";
+option java_outer_classname = "KeyValuePairProto";
+
+// Serialized form of a key-value pair, when it is to be encrypted in a blob.
+// The backup blob for a key-value database consists of repeated encrypted
+// key-value pairs like this, in a randomized order. See ChunkOrdering for how
+// these are then reconstructed during a restore.
+message KeyValuePair {
+  optional string key = 1;
+  optional bytes value = 2;
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/BackupEncryptionService.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/BackupEncryptionService.java
new file mode 100644
index 0000000..84fb0e6
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/BackupEncryptionService.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.util.Log;
+
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.encryption.transport.IntermediateEncryptingTransport;
+import com.android.server.backup.encryption.transport.IntermediateEncryptingTransportManager;
+
+/**
+ * This service provides encryption of backup data. For an intent used to bind to this service, it
+ * provides an {@link IntermediateEncryptingTransport} which is an implementation of {@link
+ * IBackupTransport} that encrypts (or decrypts) the data when sending it (or receiving it) from the
+ * real {@link IBackupTransport}.
+ */
+public class BackupEncryptionService extends Service {
+    public static final String TAG = "BackupEncryption";
+    private static IntermediateEncryptingTransportManager sTransportManager = null;
+
+    @Override
+    public void onCreate() {
+        Log.i(TAG, "onCreate:" + this);
+        if (sTransportManager == null) {
+            Log.i(TAG, "Creating IntermediateEncryptingTransportManager");
+            sTransportManager = new IntermediateEncryptingTransportManager(this);
+        }
+    }
+
+    @Override
+    public void onDestroy() {
+        Log.i(TAG, "onDestroy:" + this);
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        // TODO (b141536117): Check connection with TransportClient.connect and return null on fail.
+        return sTransportManager.get(intent);
+    }
+
+    @Override
+    public boolean onUnbind(Intent intent) {
+        sTransportManager.cleanup(intent);
+        return false;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/FullBackupDataProcessor.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/FullBackupDataProcessor.java
new file mode 100644
index 0000000..f3ab2bd
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/FullBackupDataProcessor.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption;
+
+import android.app.backup.BackupTransport;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/** Accepts the full backup data stream and sends it to the server. */
+public interface FullBackupDataProcessor {
+    /**
+     * Prepares the upload.
+     *
+     * <p>After this, call {@link #start()} to establish the connection.
+     *
+     * @param inputStream to read the backup data from, calling {@link #finish} or {@link #cancel}
+     *     will close the stream
+     * @return {@code true} if the connection was set up successfully, otherwise {@code false}
+     */
+    boolean initiate(InputStream inputStream) throws IOException;
+
+    /**
+     * Starts the upload, establishing the connection to the server.
+     *
+     * <p>After this, call {@link #pushData(int)} to request that the processor reads data from the
+     * socket, and uploads it to the server.
+     *
+     * <p>After this you must call one of {@link #cancel()}, {@link #finish()}, {@link
+     * #handleCheckSizeRejectionZeroBytes()}, {@link #handleCheckSizeRejectionQuotaExceeded()} or
+     * {@link #handleSendBytesQuotaExceeded()} to close the upload.
+     */
+    void start();
+
+    /**
+     * Requests that the processor read {@code numBytes} from the input stream passed in {@link
+     * #initiate(InputStream)} and upload them to the server.
+     *
+     * @return {@link BackupTransport#TRANSPORT_OK} if the upload succeeds, or {@link
+     *     BackupTransport#TRANSPORT_QUOTA_EXCEEDED} if the upload exceeded the server-side app size
+     *     quota, or {@link BackupTransport#TRANSPORT_PACKAGE_REJECTED} for other errors.
+     */
+    int pushData(int numBytes);
+
+    /** Cancels the upload and tears down the connection. */
+    void cancel();
+
+    /**
+     * Finish the upload and tear down the connection.
+     *
+     * <p>Call this after there is no more data to push with {@link #pushData(int)}.
+     *
+     * @return One of {@link BackupTransport#TRANSPORT_OK} if the app upload succeeds, {@link
+     *     BackupTransport#TRANSPORT_QUOTA_EXCEEDED} if the upload exceeded the server-side app size
+     *     quota, {@link BackupTransport#TRANSPORT_ERROR} for server 500s, or {@link
+     *     BackupTransport#TRANSPORT_PACKAGE_REJECTED} for other errors.
+     */
+    int finish();
+
+    /**
+     * Notifies the processor that the current upload should be terminated because the estimated
+     * size is zero.
+     */
+    void handleCheckSizeRejectionZeroBytes();
+
+    /**
+     * Notifies the processor that the current upload should be terminated because the estimated
+     * size exceeds the quota.
+     */
+    void handleCheckSizeRejectionQuotaExceeded();
+
+    /**
+     * Notifies this class that the current upload should be terminated because the quota was
+     * exceeded during upload.
+     */
+    void handleSendBytesQuotaExceeded();
+
+    /**
+     * Attaches {@link FullBackupCallbacks} which the processor will notify when the backup
+     * succeeds.
+     */
+    void attachCallbacks(FullBackupCallbacks fullBackupCallbacks);
+
+    /**
+     * Implemented by the caller of the processor to receive notification of when the backup
+     * succeeds.
+     */
+    interface FullBackupCallbacks {
+        /** The processor calls this to indicate that the current backup has succeeded. */
+        void onSuccess();
+
+        /** The processor calls this if the upload failed for a non-transient reason. */
+        void onTransferFailed();
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/FullRestoreDataProcessor.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/FullRestoreDataProcessor.java
new file mode 100644
index 0000000..e4c4049
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/FullRestoreDataProcessor.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption;
+
+import java.io.IOException;
+
+/**
+ * Retrieves the data during a full restore, decrypting it if necessary.
+ *
+ * <p>Use {@link FullRestoreDataProcessorFactory} to construct the encrypted or unencrypted
+ * processor as appropriate during restore.
+ */
+public interface FullRestoreDataProcessor {
+    /** Return value of {@link #readNextChunk} when there is no more data to download. */
+    int END_OF_STREAM = -1;
+
+    /**
+     * Reads the next chunk of restore data and writes it to the given buffer.
+     *
+     * <p>Where necessary, will open the connection to the server and/or decrypt the backup file.
+     *
+     * <p>The implementation may retry various errors. If the retries fail it will throw the
+     * relevant exception.
+     *
+     * @return the number of bytes read, or {@link #END_OF_STREAM} if there is no more data
+     * @throws IOException when downloading from the network or writing to disk
+     */
+    int readNextChunk(byte[] buffer) throws IOException;
+
+    /**
+     * Closes the connection to the server, deletes any temporary files and optionally sends a log
+     * with the given finish type.
+     *
+     * @param finishType one of {@link FullRestoreDownloader.FinishType}
+     */
+    void finish(FullRestoreDownloader.FinishType finishType);
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/FullRestoreDownloader.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/FullRestoreDownloader.java
new file mode 100644
index 0000000..afcca79
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/FullRestoreDownloader.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption;
+
+import java.io.IOException;
+
+/** Interface for classes which will provide backup data */
+public abstract class FullRestoreDownloader {
+    /** Enum to provide information on why a download finished */
+    public enum FinishType {
+        UNKNOWN_FINISH(0),
+        // Finish the downloading and successfully write data to Android OS.
+        FINISHED(1),
+        // Download failed with any kind of exception.
+        TRANSFER_FAILURE(2),
+        // Download failed due to auth failure on the device.
+        AUTH_FAILURE(3),
+        // Aborted by Android Framework.
+        FRAMEWORK_ABORTED(4);
+
+        private int mValue;
+
+        FinishType(int value) {
+            mValue = value;
+        }
+    }
+
+    /** Get the next data chunk from the backing store */
+    public abstract int readNextChunk(byte[] buffer) throws IOException;
+
+    /** Called when we've finished restoring the data */
+    public abstract void finish(FinishType finishType);
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/StreamUtils.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/StreamUtils.java
new file mode 100644
index 0000000..66be25b
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/StreamUtils.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/** Utility methods for dealing with Streams */
+public class StreamUtils {
+    private static final int MAX_COPY_BUFFER_SIZE = 1024; // 1k copy buffer size.
+
+    /**
+     * Close a Closeable and silently ignore any IOExceptions.
+     *
+     * @param closeable The closeable to close
+     */
+    public static void closeQuietly(Closeable closeable) {
+        try {
+            closeable.close();
+        } catch (IOException ioe) {
+            // Silently ignore
+        }
+    }
+
+    /**
+     * Copy data from an InputStream to an OutputStream upto a given number of bytes.
+     *
+     * @param in The source InputStream
+     * @param out The destination OutputStream
+     * @param limit The maximum number of bytes to copy
+     * @throws IOException Thrown if there is a problem performing the copy.
+     */
+    public static void copyStream(InputStream in, OutputStream out, int limit) throws IOException {
+        int bufferSize = Math.min(MAX_COPY_BUFFER_SIZE, limit);
+        byte[] buffer = new byte[bufferSize];
+
+        int copied = 0;
+        while (copied < limit) {
+            int maxReadSize = Math.min(bufferSize, limit - copied);
+            int read = in.read(buffer, 0, maxReadSize);
+            if (read < 0) {
+                return; // Reached the stream end before the limit
+            }
+            out.write(buffer, 0, read);
+            copied += read;
+        }
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/BackupFileBuilder.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/BackupFileBuilder.java
new file mode 100644
index 0000000..3d3fb55
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/BackupFileBuilder.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.chunking;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+import static com.android.internal.util.Preconditions.checkState;
+
+import android.annotation.Nullable;
+import android.util.Slog;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunk.ChunkListingMap;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Writes batches of {@link EncryptedChunk} to a diff script, and generates the associated {@link
+ * ChunksMetadataProto.ChunkListing} and {@link ChunksMetadataProto.ChunkOrdering}.
+ */
+public class BackupFileBuilder {
+    private static final String TAG = "BackupFileBuilder";
+
+    private static final int BYTES_PER_KILOBYTE = 1024;
+
+    private final BackupWriter mBackupWriter;
+    private final EncryptedChunkEncoder mEncryptedChunkEncoder;
+    private final ChunkListingMap mOldChunkListing;
+    private final ChunksMetadataProto.ChunkListing mNewChunkListing;
+    private final ChunksMetadataProto.ChunkOrdering mChunkOrdering;
+    private final List<ChunksMetadataProto.Chunk> mKnownChunks = new ArrayList<>();
+    private final List<Integer> mKnownStarts = new ArrayList<>();
+    private final Map<ChunkHash, Long> mChunkStartPositions;
+
+    private long mNewChunksSizeBytes;
+    private boolean mFinished;
+
+    /**
+     * Constructs a new instance which writes raw data to the given {@link OutputStream}, without
+     * generating a diff.
+     *
+     * <p>This class never closes the output stream.
+     */
+    public static BackupFileBuilder createForNonIncremental(OutputStream outputStream) {
+        return new BackupFileBuilder(
+                new RawBackupWriter(outputStream), new ChunksMetadataProto.ChunkListing());
+    }
+
+    /**
+     * Constructs a new instance which writes a diff script to the given {@link OutputStream} using
+     * a {@link SingleStreamDiffScriptWriter}.
+     *
+     * <p>This class never closes the output stream.
+     *
+     * @param oldChunkListing against which the diff will be generated.
+     */
+    public static BackupFileBuilder createForIncremental(
+            OutputStream outputStream, ChunksMetadataProto.ChunkListing oldChunkListing) {
+        return new BackupFileBuilder(
+                DiffScriptBackupWriter.newInstance(outputStream), oldChunkListing);
+    }
+
+    private BackupFileBuilder(
+            BackupWriter backupWriter, ChunksMetadataProto.ChunkListing oldChunkListing) {
+        this.mBackupWriter = backupWriter;
+        // TODO(b/77188289): Use InlineLengthsEncryptedChunkEncoder for key-value backups
+        this.mEncryptedChunkEncoder = new LengthlessEncryptedChunkEncoder();
+        this.mOldChunkListing = ChunkListingMap.fromProto(oldChunkListing);
+
+        mNewChunkListing = new ChunksMetadataProto.ChunkListing();
+        mNewChunkListing.cipherType = ChunksMetadataProto.AES_256_GCM;
+        mNewChunkListing.chunkOrderingType = ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+
+        mChunkOrdering = new ChunksMetadataProto.ChunkOrdering();
+        mChunkStartPositions = new HashMap<>();
+    }
+
+    /**
+     * Writes the given chunks to the output stream, and adds them to the new chunk listing and
+     * chunk ordering.
+     *
+     * <p>Sorts the chunks in lexicographical order before writing.
+     *
+     * @param allChunks The hashes of all the chunks, in the order they appear in the plaintext.
+     * @param newChunks A map from hash to {@link EncryptedChunk} containing the new chunks not
+     *     present in the previous backup.
+     */
+    public void writeChunks(List<ChunkHash> allChunks, Map<ChunkHash, EncryptedChunk> newChunks)
+            throws IOException {
+        checkState(!mFinished, "Cannot write chunks after flushing.");
+
+        List<ChunkHash> sortedChunks = new ArrayList<>(allChunks);
+        Collections.sort(sortedChunks);
+        for (ChunkHash chunkHash : sortedChunks) {
+            // As we have already included this chunk in the backup file, don't add it again to
+            // deduplicate identical chunks.
+            if (!mChunkStartPositions.containsKey(chunkHash)) {
+                // getBytesWritten() gives us the start of the chunk.
+                mChunkStartPositions.put(chunkHash, mBackupWriter.getBytesWritten());
+
+                writeChunkToFileAndListing(chunkHash, newChunks);
+            }
+        }
+
+        long totalSizeKb = mBackupWriter.getBytesWritten() / BYTES_PER_KILOBYTE;
+        long newChunksSizeKb = mNewChunksSizeBytes / BYTES_PER_KILOBYTE;
+        Slog.d(
+                TAG,
+                "Total backup size: "
+                        + totalSizeKb
+                        + " kb, new chunks size: "
+                        + newChunksSizeKb
+                        + " kb");
+
+        for (ChunkHash chunkHash : allChunks) {
+            mKnownStarts.add(mChunkStartPositions.get(chunkHash).intValue());
+        }
+    }
+
+    /**
+     * Returns a new listing for all of the chunks written so far, setting the given fingerprint
+     * mixer salt (this overrides the {@link ChunksMetadataProto.ChunkListing#fingerprintMixerSalt}
+     * in the old {@link ChunksMetadataProto.ChunkListing} passed into the
+     * {@link #BackupFileBuilder).
+     */
+    public ChunksMetadataProto.ChunkListing getNewChunkListing(
+            @Nullable byte[] fingerprintMixerSalt) {
+        // TODO: b/141537803 Add check to ensure this is called only once per instance
+        mNewChunkListing.fingerprintMixerSalt =
+                fingerprintMixerSalt != null
+                        ? Arrays.copyOf(fingerprintMixerSalt, fingerprintMixerSalt.length)
+                        : new byte[0];
+        mNewChunkListing.chunks = mKnownChunks.toArray(new ChunksMetadataProto.Chunk[0]);
+        return mNewChunkListing;
+    }
+
+    /** Returns a new ordering for all of the chunks written so far, setting the given checksum. */
+    public ChunksMetadataProto.ChunkOrdering getNewChunkOrdering(byte[] checksum) {
+        // TODO: b/141537803 Add check to ensure this is called only once per instance
+        mChunkOrdering.starts = new int[mKnownStarts.size()];
+        for (int i = 0; i < mKnownStarts.size(); i++) {
+            mChunkOrdering.starts[i] = mKnownStarts.get(i).intValue();
+        }
+        mChunkOrdering.checksum = Arrays.copyOf(checksum, checksum.length);
+        return mChunkOrdering;
+    }
+
+    /**
+     * Finishes the backup file by writing the chunk metadata and metadata position.
+     *
+     * <p>Once this is called, calling {@link #writeChunks(List, Map)} will throw {@link
+     * IllegalStateException}.
+     */
+    public void finish(ChunksMetadataProto.ChunksMetadata metadata) throws IOException {
+        checkNotNull(metadata, "Metadata cannot be null");
+
+        long startOfMetadata = mBackupWriter.getBytesWritten();
+        mBackupWriter.writeBytes(ChunksMetadataProto.ChunksMetadata.toByteArray(metadata));
+        mBackupWriter.writeBytes(toByteArray(startOfMetadata));
+
+        mBackupWriter.flush();
+        mFinished = true;
+    }
+
+    /**
+     * Checks if the given chunk hash references an existing chunk or a new chunk, and adds this
+     * chunk to the backup file and new chunk listing.
+     */
+    private void writeChunkToFileAndListing(
+            ChunkHash chunkHash, Map<ChunkHash, EncryptedChunk> newChunks) throws IOException {
+        checkNotNull(chunkHash, "Hash cannot be null");
+
+        if (mOldChunkListing.hasChunk(chunkHash)) {
+            ChunkListingMap.Entry oldChunk = mOldChunkListing.getChunkEntry(chunkHash);
+            mBackupWriter.writeChunk(oldChunk.getStart(), oldChunk.getLength());
+
+            checkArgument(oldChunk.getLength() >= 0, "Chunk must have zero or positive length");
+            addChunk(chunkHash.getHash(), oldChunk.getLength());
+        } else if (newChunks.containsKey(chunkHash)) {
+            EncryptedChunk newChunk = newChunks.get(chunkHash);
+            mEncryptedChunkEncoder.writeChunkToWriter(mBackupWriter, newChunk);
+            int length = mEncryptedChunkEncoder.getEncodedLengthOfChunk(newChunk);
+            mNewChunksSizeBytes += length;
+
+            checkArgument(length >= 0, "Chunk must have zero or positive length");
+            addChunk(chunkHash.getHash(), length);
+        } else {
+            throw new IllegalArgumentException(
+                    "Chunk did not exist in old chunks or new chunks: " + chunkHash);
+        }
+    }
+
+    private void addChunk(byte[] chunkHash, int length) {
+        ChunksMetadataProto.Chunk chunk = new ChunksMetadataProto.Chunk();
+        chunk.hash = Arrays.copyOf(chunkHash, chunkHash.length);
+        chunk.length = length;
+        mKnownChunks.add(chunk);
+    }
+
+    private static byte[] toByteArray(long value) {
+        // Note that this code needs to stay compatible with GWT, which has known
+        // bugs when narrowing byte casts of long values occur.
+        byte[] result = new byte[8];
+        for (int i = 7; i >= 0; i--) {
+            result[i] = (byte) (value & 0xffL);
+            value >>= 8;
+        }
+        return result;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/ProtoStore.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/ProtoStore.java
new file mode 100644
index 0000000..3ba5f2b
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/chunking/ProtoStore.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.chunking;
+
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import android.content.Context;
+import android.text.TextUtils;
+import android.util.AtomicFile;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+
+import com.google.protobuf.nano.MessageNano;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Optional;
+
+/**
+ * Stores a nano proto for each package, persisting the proto to disk.
+ *
+ * <p>This is used to store {@link ChunksMetadataProto.ChunkListing}.
+ *
+ * @param <T> the type of nano proto to store.
+ */
+public class ProtoStore<T extends MessageNano> {
+    private static final String CHUNK_LISTING_FOLDER = "backup_chunk_listings";
+    private static final String KEY_VALUE_LISTING_FOLDER = "backup_kv_listings";
+
+    private static final String TAG = "BupEncProtoStore";
+
+    private final File mStoreFolder;
+    private final Class<T> mClazz;
+
+    /** Creates a new instance which stores chunk listings at the default location. */
+    public static ProtoStore<ChunksMetadataProto.ChunkListing> createChunkListingStore(
+            Context context) throws IOException {
+        return new ProtoStore<>(
+                ChunksMetadataProto.ChunkListing.class,
+                new File(context.getFilesDir().getAbsoluteFile(), CHUNK_LISTING_FOLDER));
+    }
+
+    /** Creates a new instance which stores key value listings in the default location. */
+    public static ProtoStore<KeyValueListingProto.KeyValueListing> createKeyValueListingStore(
+            Context context) throws IOException {
+        return new ProtoStore<>(
+                KeyValueListingProto.KeyValueListing.class,
+                new File(context.getFilesDir().getAbsoluteFile(), KEY_VALUE_LISTING_FOLDER));
+    }
+
+    /**
+     * Creates a new instance which stores protos in the given folder.
+     *
+     * @param storeFolder The location where the serialized form is stored.
+     */
+    @VisibleForTesting
+    ProtoStore(Class<T> clazz, File storeFolder) throws IOException {
+        mClazz = checkNotNull(clazz);
+        mStoreFolder = ensureDirectoryExistsOrThrow(storeFolder);
+    }
+
+    private static File ensureDirectoryExistsOrThrow(File directory) throws IOException {
+        if (directory.exists() && !directory.isDirectory()) {
+            throw new IOException("Store folder already exists, but isn't a directory.");
+        }
+
+        if (!directory.exists() && !directory.mkdir()) {
+            throw new IOException("Unable to create store folder.");
+        }
+
+        return directory;
+    }
+
+    /**
+     * Returns the chunk listing for the given package, or {@link Optional#empty()} if no listing
+     * exists.
+     */
+    public Optional<T> loadProto(String packageName)
+            throws IOException, IllegalAccessException, InstantiationException,
+            NoSuchMethodException, InvocationTargetException {
+        File file = getFileForPackage(packageName);
+
+        if (!file.exists()) {
+            Slog.d(
+                    TAG,
+                    "No chunk listing existed for " + packageName + ", returning empty listing.");
+            return Optional.empty();
+        }
+
+        AtomicFile protoStore = new AtomicFile(file);
+        byte[] data = protoStore.readFully();
+
+        Constructor<T> constructor = mClazz.getDeclaredConstructor();
+        T proto = constructor.newInstance();
+        MessageNano.mergeFrom(proto, data);
+        return Optional.of(proto);
+    }
+
+    /** Saves a proto to disk, associating it with the given package. */
+    public void saveProto(String packageName, T proto) throws IOException {
+        checkNotNull(proto);
+        File file = getFileForPackage(packageName);
+
+        try (FileOutputStream os = new FileOutputStream(file)) {
+            os.write(MessageNano.toByteArray(proto));
+        } catch (IOException e) {
+            Slog.e(
+                    TAG,
+                    "Exception occurred when saving the listing for "
+                            + packageName
+                            + ", deleting saved listing.",
+                    e);
+
+            // If a problem occurred when writing the listing then it might be corrupt, so delete
+            // it.
+            file.delete();
+
+            throw e;
+        }
+    }
+
+    /** Deletes the proto for the given package, or does nothing if the package has no proto. */
+    public void deleteProto(String packageName) {
+        File file = getFileForPackage(packageName);
+        file.delete();
+    }
+
+    /** Deletes every proto of this type, for all package names. */
+    public void deleteAllProtos() {
+        File[] files = mStoreFolder.listFiles();
+
+        // We ensure that the storeFolder exists in the constructor, but check just in case it has
+        // mysteriously disappeared.
+        if (files == null) {
+            return;
+        }
+
+        for (File file : files) {
+            file.delete();
+        }
+    }
+
+    private File getFileForPackage(String packageName) {
+        checkPackageName(packageName);
+        return new File(mStoreFolder, packageName);
+    }
+
+    private static void checkPackageName(String packageName) {
+        if (TextUtils.isEmpty(packageName) || packageName.contains("/")) {
+            throw new IllegalArgumentException(
+                    "Package name must not contain '/' or be empty: " + packageName);
+        }
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/client/CryptoBackupServer.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/client/CryptoBackupServer.java
new file mode 100644
index 0000000..d7f7dc7
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/client/CryptoBackupServer.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.client;
+
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.util.Map;
+
+/**
+ * Contains methods for communicating with the parts of the backup server relevant to encryption.
+ */
+public interface CryptoBackupServer {
+    /**
+     * Uploads an incremental backup to the server.
+     *
+     * <p>Handles setting up and tearing down the connection.
+     *
+     * @param packageName the package to associate the data with
+     * @param oldDocId the id of the previous backup doc in Drive
+     * @param diffScript containing the actual backup data
+     * @param tertiaryKey the wrapped key used to encrypt this backup
+     * @return the id of the new backup doc in Drive.
+     */
+    String uploadIncrementalBackup(
+            String packageName,
+            String oldDocId,
+            byte[] diffScript,
+            WrappedKeyProto.WrappedKey tertiaryKey);
+
+    /**
+     * Uploads non-incremental backup to the server.
+     *
+     * <p>Handles setting up and tearing down the connection.
+     *
+     * @param packageName the package to associate the data with
+     * @param data the actual backup data
+     * @param tertiaryKey the wrapped key used to encrypt this backup
+     * @return the id of the new backup doc in Drive.
+     */
+    String uploadNonIncrementalBackup(
+            String packageName, byte[] data, WrappedKeyProto.WrappedKey tertiaryKey);
+
+    /**
+     * Sets the alias of the active secondary key. This is the alias used to refer to the key in the
+     * {@link java.security.KeyStore}. It is also used to key storage for tertiary keys on the
+     * backup server. Also has to upload all existing tertiary keys, wrapped with the new key.
+     *
+     * @param keyAlias The ID of the secondary key.
+     * @param tertiaryKeys The tertiary keys, wrapped with the new secondary key.
+     */
+    void setActiveSecondaryKeyAlias(
+            String keyAlias, Map<String, WrappedKeyProto.WrappedKey> tertiaryKeys);
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/client/UnexpectedActiveSecondaryOnServerException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/client/UnexpectedActiveSecondaryOnServerException.java
new file mode 100644
index 0000000..9e31385
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/client/UnexpectedActiveSecondaryOnServerException.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.client;
+
+/**
+ * Error thrown when the user attempts to retrieve a key set from the server, but is asking for keys
+ * from an inactive secondary.
+ *
+ * <p>Although we could just return old keys, there is no good reason to do this. It almost
+ * certainly indicates a logic error on the client.
+ */
+public class UnexpectedActiveSecondaryOnServerException extends Exception {
+    public UnexpectedActiveSecondaryOnServerException(String message) {
+        super(message);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/kv/DecryptedChunkKvOutput.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/kv/DecryptedChunkKvOutput.java
new file mode 100644
index 0000000..56e1c05
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/kv/DecryptedChunkKvOutput.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.kv;
+
+import static com.android.internal.util.Preconditions.checkState;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto;
+import com.android.server.backup.encryption.tasks.DecryptedChunkOutput;
+
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Builds a key value backup set from plaintext chunks. Computes a digest over the sorted SHA-256
+ * hashes of the chunks.
+ */
+public class DecryptedChunkKvOutput implements DecryptedChunkOutput {
+    @VisibleForTesting static final String DIGEST_ALGORITHM = "SHA-256";
+
+    private final ChunkHasher mChunkHasher;
+    private final List<KeyValuePairProto.KeyValuePair> mUnsortedPairs = new ArrayList<>();
+    private final List<ChunkHash> mUnsortedHashes = new ArrayList<>();
+    private boolean mClosed;
+
+    /** Constructs a new instance which computers the digest using the given hasher. */
+    public DecryptedChunkKvOutput(ChunkHasher chunkHasher) {
+        mChunkHasher = chunkHasher;
+    }
+
+    @Override
+    public DecryptedChunkOutput open() {
+        // As we don't have any resources there is nothing to open.
+        return this;
+    }
+
+    @Override
+    public void processChunk(byte[] plaintextBuffer, int length)
+            throws IOException, InvalidKeyException {
+        checkState(!mClosed, "Cannot process chunk after close()");
+        KeyValuePairProto.KeyValuePair kvPair = new KeyValuePairProto.KeyValuePair();
+        KeyValuePairProto.KeyValuePair.mergeFrom(kvPair, plaintextBuffer, 0, length);
+        mUnsortedPairs.add(kvPair);
+        // TODO(b/71492289): Update ChunkHasher to accept offset and length so we don't have to copy
+        // the buffer into a smaller array.
+        mUnsortedHashes.add(mChunkHasher.computeHash(Arrays.copyOf(plaintextBuffer, length)));
+    }
+
+    @Override
+    public void close() {
+        // As we don't have any resources there is nothing to close.
+        mClosed = true;
+    }
+
+    @Override
+    public byte[] getDigest() throws NoSuchAlgorithmException {
+        checkState(mClosed, "Must close() before getDigest()");
+        MessageDigest digest = getMessageDigest();
+        Collections.sort(mUnsortedHashes);
+        for (ChunkHash hash : mUnsortedHashes) {
+            digest.update(hash.getHash());
+        }
+        return digest.digest();
+    }
+
+    private static MessageDigest getMessageDigest() throws NoSuchAlgorithmException {
+        return MessageDigest.getInstance(DIGEST_ALGORITHM);
+    }
+
+    /**
+     * Returns the key value pairs from the backup, sorted lexicographically by key.
+     *
+     * <p>You must call {@link #close} first.
+     */
+    public List<KeyValuePairProto.KeyValuePair> getPairs() {
+        checkState(mClosed, "Must close() before getPairs()");
+        Collections.sort(
+                mUnsortedPairs,
+                new Comparator<KeyValuePairProto.KeyValuePair>() {
+                    @Override
+                    public int compare(
+                            KeyValuePairProto.KeyValuePair o1, KeyValuePairProto.KeyValuePair o2) {
+                        return o1.key.compareTo(o2.key);
+                    }
+                });
+        return mUnsortedPairs;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/kv/KeyValueListingBuilder.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/kv/KeyValueListingBuilder.java
new file mode 100644
index 0000000..b3518e1
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/kv/KeyValueListingBuilder.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.kv;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * Builds a {@link KeyValueListingProto.KeyValueListing}, which is a nano proto and so has no
+ * builder.
+ */
+public class KeyValueListingBuilder {
+    private final List<KeyValueListingProto.KeyValueEntry> mEntries = new ArrayList<>();
+
+    /** Adds a new pair entry to the listing. */
+    public KeyValueListingBuilder addPair(String key, ChunkHash hash) {
+        checkArgument(key.length() != 0, "Key must have non-zero length");
+        checkNotNull(hash, "Hash must not be null");
+
+        KeyValueListingProto.KeyValueEntry entry = new KeyValueListingProto.KeyValueEntry();
+        entry.key = key;
+        entry.hash = hash.getHash();
+        mEntries.add(entry);
+
+        return this;
+    }
+
+    /** Adds all pairs contained in a map, where the map is from key to hash. */
+    public KeyValueListingBuilder addAll(Map<String, ChunkHash> map) {
+        for (Entry<String, ChunkHash> entry : map.entrySet()) {
+            addPair(entry.getKey(), entry.getValue());
+        }
+
+        return this;
+    }
+
+    /** Returns a new listing containing all the pairs added so far. */
+    public KeyValueListingProto.KeyValueListing build() {
+        if (mEntries.size() == 0) {
+            return emptyListing();
+        }
+
+        KeyValueListingProto.KeyValueListing listing = new KeyValueListingProto.KeyValueListing();
+        listing.entries = new KeyValueListingProto.KeyValueEntry[mEntries.size()];
+        mEntries.toArray(listing.entries);
+        return listing;
+    }
+
+    /** Returns a new listing which does not contain any pairs. */
+    public static KeyValueListingProto.KeyValueListing emptyListing() {
+        KeyValueListingProto.KeyValueListing listing = new KeyValueListingProto.KeyValueListing();
+        listing.entries = KeyValueListingProto.KeyValueEntry.emptyArray();
+        return listing;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/ActiveSecondaryNotInKeychainException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/ActiveSecondaryNotInKeychainException.java
new file mode 100644
index 0000000..2e8a61f
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/ActiveSecondaryNotInKeychainException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+/**
+ * Error thrown when the server's active secondary key does not exist in the user's recoverable
+ * keychain. This means the backup data cannot be decrypted, and should be wiped.
+ */
+public class ActiveSecondaryNotInKeychainException extends Exception {
+    public ActiveSecondaryNotInKeychainException(String message) {
+        super(message);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/BackupFileDecryptorTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/BackupFileDecryptorTask.java
new file mode 100644
index 0000000..9bf148d
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/BackupFileDecryptorTask.java
@@ -0,0 +1,378 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import android.util.Slog;
+import android.util.SparseIntArray;
+
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkOrdering;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunksMetadata;
+
+import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.Locale;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.ShortBufferException;
+import javax.crypto.spec.GCMParameterSpec;
+
+/**
+ * A backup file consists of, in order:
+ *
+ * <ul>
+ *   <li>A randomly ordered sequence of encrypted chunks
+ *   <li>A plaintext {@link ChunksMetadata} proto, containing the bytes of an encrypted {@link
+ *       ChunkOrdering} proto.
+ *   <li>A 64-bit long denoting the offset of the file at which the ChunkOrdering proto starts.
+ * </ul>
+ *
+ * <p>This task decrypts such a blob and writes the plaintext to another file.
+ *
+ * <p>The backup file has two formats to indicate the boundaries of the chunks in the encrypted
+ * file. In {@link ChunksMetadataProto#EXPLICIT_STARTS} mode the chunk ordering contains the start
+ * positions of each chunk and the decryptor outputs the chunks in the order they appeared in the
+ * plaintext file. In {@link ChunksMetadataProto#INLINE_LENGTHS} mode the length of each encrypted
+ * chunk is prepended to the chunk in the file and the decryptor outputs the chunks in no specific
+ * order.
+ *
+ * <p>{@link ChunksMetadataProto#EXPLICIT_STARTS} is for use with full backup (Currently used for
+ * all backups as b/77188289 is not implemented yet), {@link ChunksMetadataProto#INLINE_LENGTHS}
+ * will be used for kv backup (once b/77188289 is implemented) to avoid re-uploading the chunk
+ * ordering (see b/70782620).
+ */
+public class BackupFileDecryptorTask {
+    private static final String TAG = "BackupFileDecryptorTask";
+
+    private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+    private static final int GCM_NONCE_LENGTH_BYTES = 12;
+    private static final int GCM_TAG_LENGTH_BYTES = 16;
+    private static final int BITS_PER_BYTE = 8;
+    private static final String READ_MODE = "r";
+    private static final int BYTES_PER_LONG = 64 / BITS_PER_BYTE;
+
+    private final Cipher mCipher;
+    private final SecretKey mSecretKey;
+
+    /**
+     * A new instance.
+     *
+     * @param secretKey The tertiary key used to encrypt the backup blob.
+     */
+    public BackupFileDecryptorTask(SecretKey secretKey)
+            throws NoSuchPaddingException, NoSuchAlgorithmException {
+        this.mCipher = Cipher.getInstance(CIPHER_ALGORITHM);
+        this.mSecretKey = secretKey;
+    }
+
+    /**
+     * Runs the task, reading the encrypted data from {@code input} and writing the plaintext data
+     * to {@code output}.
+     *
+     * @param inputFile The encrypted backup file.
+     * @param decryptedChunkOutput Unopened output to write the plaintext to, which this class will
+     *     open and close during decryption.
+     * @throws IOException if an error occurred reading the encrypted file or writing the plaintext,
+     *     or if one of the protos could not be deserialized.
+     */
+    public void decryptFile(File inputFile, DecryptedChunkOutput decryptedChunkOutput)
+            throws IOException, EncryptedRestoreException, IllegalBlockSizeException,
+                    BadPaddingException, InvalidAlgorithmParameterException, InvalidKeyException,
+                    ShortBufferException, NoSuchAlgorithmException {
+        RandomAccessFile input = new RandomAccessFile(inputFile, READ_MODE);
+
+        long metadataOffset = getChunksMetadataOffset(input);
+        ChunksMetadataProto.ChunksMetadata chunksMetadata =
+                getChunksMetadata(input, metadataOffset);
+        ChunkOrdering chunkOrdering = decryptChunkOrdering(chunksMetadata);
+
+        if (chunksMetadata.chunkOrderingType == ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED
+                || chunksMetadata.chunkOrderingType == ChunksMetadataProto.EXPLICIT_STARTS) {
+            Slog.d(TAG, "Using explicit starts");
+            decryptFileWithExplicitStarts(
+                    input, decryptedChunkOutput, chunkOrdering, metadataOffset);
+
+        } else if (chunksMetadata.chunkOrderingType == ChunksMetadataProto.INLINE_LENGTHS) {
+            Slog.d(TAG, "Using inline lengths");
+            decryptFileWithInlineLengths(input, decryptedChunkOutput, metadataOffset);
+
+        } else {
+            throw new UnsupportedEncryptedFileException(
+                    "Unknown chunk ordering type:" + chunksMetadata.chunkOrderingType);
+        }
+
+        if (!Arrays.equals(decryptedChunkOutput.getDigest(), chunkOrdering.checksum)) {
+            throw new MessageDigestMismatchException("Checksums did not match");
+        }
+    }
+
+    private void decryptFileWithExplicitStarts(
+            RandomAccessFile input,
+            DecryptedChunkOutput decryptedChunkOutput,
+            ChunkOrdering chunkOrdering,
+            long metadataOffset)
+            throws IOException, InvalidKeyException, IllegalBlockSizeException,
+                    InvalidAlgorithmParameterException, ShortBufferException, BadPaddingException,
+                    NoSuchAlgorithmException {
+        SparseIntArray chunkLengthsByPosition =
+                getChunkLengths(chunkOrdering.starts, (int) metadataOffset);
+        int largestChunkLength = getLargestChunkLength(chunkLengthsByPosition);
+        byte[] encryptedChunkBuffer = new byte[largestChunkLength];
+        // largestChunkLength is 0 if the backup file contains zero chunks e.g. 0 kv pairs.
+        int plaintextBufferLength =
+                Math.max(0, largestChunkLength - GCM_NONCE_LENGTH_BYTES - GCM_TAG_LENGTH_BYTES);
+        byte[] plaintextChunkBuffer = new byte[plaintextBufferLength];
+
+        try (DecryptedChunkOutput output = decryptedChunkOutput.open()) {
+            for (int start : chunkOrdering.starts) {
+                int length = chunkLengthsByPosition.get(start);
+
+                input.seek(start);
+                input.readFully(encryptedChunkBuffer, 0, length);
+                int plaintextLength =
+                        decryptChunk(encryptedChunkBuffer, length, plaintextChunkBuffer);
+                outputChunk(output, plaintextChunkBuffer, plaintextLength);
+            }
+        }
+    }
+
+    private void decryptFileWithInlineLengths(
+            RandomAccessFile input, DecryptedChunkOutput decryptedChunkOutput, long metadataOffset)
+            throws MalformedEncryptedFileException, IOException, IllegalBlockSizeException,
+                    BadPaddingException, InvalidAlgorithmParameterException, ShortBufferException,
+                    InvalidKeyException, NoSuchAlgorithmException {
+        input.seek(0);
+        try (DecryptedChunkOutput output = decryptedChunkOutput.open()) {
+            while (input.getFilePointer() < metadataOffset) {
+                long start = input.getFilePointer();
+                int encryptedChunkLength = input.readInt();
+
+                if (encryptedChunkLength <= 0) {
+                    // If the length of the encrypted chunk is not positive we will not make
+                    // progress reading the file and so will loop forever.
+                    throw new MalformedEncryptedFileException(
+                            "Encrypted chunk length not positive:" + encryptedChunkLength);
+                }
+
+                if (start + encryptedChunkLength > metadataOffset) {
+                    throw new MalformedEncryptedFileException(
+                            String.format(
+                                    Locale.US,
+                                    "Encrypted chunk longer (%d) than file (%d)",
+                                    encryptedChunkLength,
+                                    metadataOffset));
+                }
+
+                byte[] plaintextChunk = new byte[encryptedChunkLength];
+                byte[] plaintext =
+                        new byte
+                                [encryptedChunkLength
+                                        - GCM_NONCE_LENGTH_BYTES
+                                        - GCM_TAG_LENGTH_BYTES];
+
+                input.readFully(plaintextChunk);
+
+                int plaintextChunkLength =
+                        decryptChunk(plaintextChunk, encryptedChunkLength, plaintext);
+                outputChunk(output, plaintext, plaintextChunkLength);
+            }
+        }
+    }
+
+    private void outputChunk(
+            DecryptedChunkOutput output, byte[] plaintextChunkBuffer, int plaintextLength)
+            throws IOException, InvalidKeyException, NoSuchAlgorithmException {
+        output.processChunk(plaintextChunkBuffer, plaintextLength);
+    }
+
+    /**
+     * Decrypts chunk and returns the length of the plaintext.
+     *
+     * @param encryptedChunkBuffer The encrypted data, prefixed by the nonce.
+     * @param encryptedChunkBufferLength The length of the encrypted chunk (including nonce).
+     * @param plaintextChunkBuffer The buffer into which to write the plaintext chunk.
+     * @return The length of the plaintext chunk.
+     */
+    private int decryptChunk(
+            byte[] encryptedChunkBuffer,
+            int encryptedChunkBufferLength,
+            byte[] plaintextChunkBuffer)
+            throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException,
+                    ShortBufferException, IllegalBlockSizeException {
+
+        mCipher.init(
+                Cipher.DECRYPT_MODE,
+                mSecretKey,
+                new GCMParameterSpec(
+                        GCM_TAG_LENGTH_BYTES * BITS_PER_BYTE,
+                        encryptedChunkBuffer,
+                        0,
+                        GCM_NONCE_LENGTH_BYTES));
+
+        return mCipher.doFinal(
+                encryptedChunkBuffer,
+                GCM_NONCE_LENGTH_BYTES,
+                encryptedChunkBufferLength - GCM_NONCE_LENGTH_BYTES,
+                plaintextChunkBuffer);
+    }
+
+    /** Given all the lengths, returns the largest length. */
+    private int getLargestChunkLength(SparseIntArray lengths) {
+        int maxSeen = 0;
+        for (int i = 0; i < lengths.size(); i++) {
+            maxSeen = Math.max(maxSeen, lengths.valueAt(i));
+        }
+        return maxSeen;
+    }
+
+    /**
+     * From a list of the starting position of each chunk in the correct order of the backup data,
+     * calculates a mapping from start position to length of that chunk.
+     *
+     * @param starts The start positions of chunks, in order.
+     * @param chunkOrderingPosition Where the {@link ChunkOrdering} proto starts, used to calculate
+     *     the length of the last chunk.
+     * @return The mapping.
+     */
+    private SparseIntArray getChunkLengths(int[] starts, int chunkOrderingPosition) {
+        int[] boundaries = Arrays.copyOf(starts, starts.length + 1);
+        boundaries[boundaries.length - 1] = chunkOrderingPosition;
+        Arrays.sort(boundaries);
+
+        SparseIntArray lengths = new SparseIntArray();
+        for (int i = 0; i < boundaries.length - 1; i++) {
+            lengths.put(boundaries[i], boundaries[i + 1] - boundaries[i]);
+        }
+        return lengths;
+    }
+
+    /**
+     * Reads and decrypts the {@link ChunkOrdering} from the {@link ChunksMetadata}.
+     *
+     * @param metadata The metadata.
+     * @return The ordering.
+     * @throws InvalidProtocolBufferNanoException if there is an issue deserializing the proto.
+     */
+    private ChunkOrdering decryptChunkOrdering(ChunksMetadata metadata)
+            throws InvalidProtocolBufferNanoException, InvalidAlgorithmParameterException,
+                    InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
+                    UnsupportedEncryptedFileException {
+        assertCryptoSupported(metadata);
+
+        mCipher.init(
+                Cipher.DECRYPT_MODE,
+                mSecretKey,
+                new GCMParameterSpec(
+                        GCM_TAG_LENGTH_BYTES * BITS_PER_BYTE,
+                        metadata.chunkOrdering,
+                        0,
+                        GCM_NONCE_LENGTH_BYTES));
+
+        byte[] decrypted =
+                mCipher.doFinal(
+                        metadata.chunkOrdering,
+                        GCM_NONCE_LENGTH_BYTES,
+                        metadata.chunkOrdering.length - GCM_NONCE_LENGTH_BYTES);
+
+        return ChunkOrdering.parseFrom(decrypted);
+    }
+
+    /**
+     * Asserts that the Cipher and MessageDigest algorithms in the backup metadata are supported.
+     * For now we only support SHA-256 for checksum and 256-bit AES/GCM/NoPadding for the Cipher.
+     *
+     * @param chunksMetadata The file metadata.
+     * @throws UnsupportedEncryptedFileException if any algorithm is unsupported.
+     */
+    private void assertCryptoSupported(ChunksMetadata chunksMetadata)
+            throws UnsupportedEncryptedFileException {
+        if (chunksMetadata.checksumType != ChunksMetadataProto.SHA_256) {
+            // For now we only support SHA-256.
+            throw new UnsupportedEncryptedFileException(
+                    "Unrecognized checksum type for backup (this version of backup only supports"
+                        + " SHA-256): "
+                            + chunksMetadata.checksumType);
+        }
+
+        if (chunksMetadata.cipherType != ChunksMetadataProto.AES_256_GCM) {
+            throw new UnsupportedEncryptedFileException(
+                    "Unrecognized cipher type for backup (this version of backup only supports"
+                        + " AES-256-GCM: "
+                            + chunksMetadata.cipherType);
+        }
+    }
+
+    /**
+     * Reads the offset of the {@link ChunksMetadata} proto from the end of the file.
+     *
+     * @return The offset.
+     * @throws IOException if there is an error reading.
+     */
+    private long getChunksMetadataOffset(RandomAccessFile input) throws IOException {
+        input.seek(input.length() - BYTES_PER_LONG);
+        return input.readLong();
+    }
+
+    /**
+     * Reads the {@link ChunksMetadata} proto from the given position in the file.
+     *
+     * @param input The encrypted file.
+     * @param position The position where the proto starts.
+     * @return The proto.
+     * @throws IOException if there is an issue reading the file or deserializing the proto.
+     */
+    private ChunksMetadata getChunksMetadata(RandomAccessFile input, long position)
+            throws IOException, MalformedEncryptedFileException {
+        long length = input.length();
+        if (position >= length || position < 0) {
+            throw new MalformedEncryptedFileException(
+                    String.format(
+                            Locale.US,
+                            "%d is not valid position for chunks metadata in file of %d bytes",
+                            position,
+                            length));
+        }
+
+        // Read chunk ordering bytes
+        input.seek(position);
+        long chunksMetadataLength = input.length() - BYTES_PER_LONG - position;
+        byte[] chunksMetadataBytes = new byte[(int) chunksMetadataLength];
+        input.readFully(chunksMetadataBytes);
+
+        try {
+            return ChunksMetadata.parseFrom(chunksMetadataBytes);
+        } catch (InvalidProtocolBufferNanoException e) {
+            throw new MalformedEncryptedFileException(
+                    String.format(
+                            Locale.US,
+                            "Could not read chunks metadata at position %d of file of %d bytes",
+                            position,
+                            length));
+        }
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/DecryptedChunkOutput.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/DecryptedChunkOutput.java
index e3df3c1..f67f100 100644
--- a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/DecryptedChunkOutput.java
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/DecryptedChunkOutput.java
@@ -19,6 +19,7 @@
 import java.io.Closeable;
 import java.io.IOException;
 import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
 
 /**
  * Accepts the plaintext bytes of decrypted chunks and writes them to some output. Also keeps track
@@ -30,7 +31,7 @@
      *
      * @return {@code this}, to allow use with try-with-resources
      */
-    DecryptedChunkOutput open() throws IOException;
+    DecryptedChunkOutput open() throws IOException, NoSuchAlgorithmException;
 
     /**
      * Writes the plaintext bytes of chunk to whatever output the implementation chooses. Also
@@ -43,12 +44,13 @@
      *     at index 0.
      * @param length The length in bytes of the plaintext contained in {@code plaintextBuffer}.
      */
-    void processChunk(byte[] plaintextBuffer, int length) throws IOException, InvalidKeyException;
+    void processChunk(byte[] plaintextBuffer, int length)
+            throws IOException, InvalidKeyException, NoSuchAlgorithmException;
 
     /**
      * Returns the message digest of all the chunks processed by {@link #processChunk}.
      *
      * <p>You must call {@link Closeable#close()} before calling this method.
      */
-    byte[] getDigest();
+    byte[] getDigest() throws NoSuchAlgorithmException;
 }
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedBackupTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedBackupTask.java
new file mode 100644
index 0000000..ef13f23
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedBackupTask.java
@@ -0,0 +1,243 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import android.annotation.Nullable;
+import android.annotation.TargetApi;
+import android.os.Build.VERSION_CODES;
+import android.util.Slog;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.BackupFileBuilder;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.ShortBufferException;
+import javax.crypto.spec.GCMParameterSpec;
+
+/**
+ * Task which reads encrypted chunks from a {@link BackupEncrypter}, builds a backup file and
+ * uploads it to the server.
+ */
+@TargetApi(VERSION_CODES.P)
+public class EncryptedBackupTask {
+    private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+    private static final int GCM_NONCE_LENGTH_BYTES = 12;
+    private static final int GCM_TAG_LENGTH_BYTES = 16;
+    private static final int BITS_PER_BYTE = 8;
+
+    private static final String TAG = "EncryptedBackupTask";
+
+    private final CryptoBackupServer mCryptoBackupServer;
+    private final SecureRandom mSecureRandom;
+    private final String mPackageName;
+    private final ByteArrayOutputStream mBackupDataOutput;
+    private final BackupEncrypter mBackupEncrypter;
+    private final AtomicBoolean mCancelled;
+
+    /** Creates a new instance which reads data from the given input stream. */
+    public EncryptedBackupTask(
+            CryptoBackupServer cryptoBackupServer,
+            SecureRandom secureRandom,
+            String packageName,
+            BackupEncrypter backupEncrypter) {
+        mCryptoBackupServer = cryptoBackupServer;
+        mSecureRandom = secureRandom;
+        mPackageName = packageName;
+        mBackupEncrypter = backupEncrypter;
+
+        mBackupDataOutput = new ByteArrayOutputStream();
+        mCancelled = new AtomicBoolean(false);
+    }
+
+    /**
+     * Creates a non-incremental backup file and uploads it to the server.
+     *
+     * @param fingerprintMixerSalt Fingerprint mixer salt used for content-defined chunking during a
+     *     full backup. May be {@code null} for a key-value backup.
+     */
+    public ChunksMetadataProto.ChunkListing performNonIncrementalBackup(
+            SecretKey tertiaryKey,
+            WrappedKeyProto.WrappedKey wrappedTertiaryKey,
+            @Nullable byte[] fingerprintMixerSalt)
+            throws IOException, GeneralSecurityException {
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                performBackup(
+                        tertiaryKey,
+                        fingerprintMixerSalt,
+                        BackupFileBuilder.createForNonIncremental(mBackupDataOutput),
+                        new HashSet<>());
+
+        throwIfCancelled();
+
+        newChunkListing.documentId =
+                mCryptoBackupServer.uploadNonIncrementalBackup(
+                        mPackageName, mBackupDataOutput.toByteArray(), wrappedTertiaryKey);
+
+        return newChunkListing;
+    }
+
+    /** Creates an incremental backup file and uploads it to the server. */
+    public ChunksMetadataProto.ChunkListing performIncrementalBackup(
+            SecretKey tertiaryKey,
+            WrappedKeyProto.WrappedKey wrappedTertiaryKey,
+            ChunksMetadataProto.ChunkListing oldChunkListing)
+            throws IOException, GeneralSecurityException {
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                performBackup(
+                        tertiaryKey,
+                        oldChunkListing.fingerprintMixerSalt,
+                        BackupFileBuilder.createForIncremental(mBackupDataOutput, oldChunkListing),
+                        getChunkHashes(oldChunkListing));
+
+        throwIfCancelled();
+
+        String oldDocumentId = oldChunkListing.documentId;
+        Slog.v(TAG, "Old doc id: " + oldDocumentId);
+
+        newChunkListing.documentId =
+                mCryptoBackupServer.uploadIncrementalBackup(
+                        mPackageName,
+                        oldDocumentId,
+                        mBackupDataOutput.toByteArray(),
+                        wrappedTertiaryKey);
+        return newChunkListing;
+    }
+
+    /**
+     * Signals to the task that the backup has been cancelled. If the upload has not yet started
+     * then the task will not upload any data to the server or save the new chunk listing.
+     */
+    public void cancel() {
+        mCancelled.getAndSet(true);
+    }
+
+    private void throwIfCancelled() {
+        if (mCancelled.get()) {
+            throw new CancellationException("EncryptedBackupTask was cancelled");
+        }
+    }
+
+    private ChunksMetadataProto.ChunkListing performBackup(
+            SecretKey tertiaryKey,
+            @Nullable byte[] fingerprintMixerSalt,
+            BackupFileBuilder backupFileBuilder,
+            Set<ChunkHash> existingChunkHashes)
+            throws IOException, GeneralSecurityException {
+        BackupEncrypter.Result result =
+                mBackupEncrypter.backup(tertiaryKey, fingerprintMixerSalt, existingChunkHashes);
+        backupFileBuilder.writeChunks(result.getAllChunks(), buildChunkMap(result.getNewChunks()));
+
+        ChunksMetadataProto.ChunkOrdering chunkOrdering =
+                backupFileBuilder.getNewChunkOrdering(result.getDigest());
+        backupFileBuilder.finish(buildMetadata(tertiaryKey, chunkOrdering));
+
+        return backupFileBuilder.getNewChunkListing(fingerprintMixerSalt);
+    }
+
+    /** Returns a set containing the hashes of every chunk in the given listing. */
+    private static Set<ChunkHash> getChunkHashes(ChunksMetadataProto.ChunkListing chunkListing) {
+        Set<ChunkHash> hashes = new HashSet<>();
+        for (ChunksMetadataProto.Chunk chunk : chunkListing.chunks) {
+            hashes.add(new ChunkHash(chunk.hash));
+        }
+        return hashes;
+    }
+
+    /** Returns a map from chunk hash to chunk containing every chunk in the given list. */
+    private static Map<ChunkHash, EncryptedChunk> buildChunkMap(List<EncryptedChunk> chunks) {
+        Map<ChunkHash, EncryptedChunk> chunkMap = new HashMap<>();
+        for (EncryptedChunk chunk : chunks) {
+            chunkMap.put(chunk.key(), chunk);
+        }
+        return chunkMap;
+    }
+
+    private ChunksMetadataProto.ChunksMetadata buildMetadata(
+            SecretKey tertiaryKey, ChunksMetadataProto.ChunkOrdering chunkOrdering)
+            throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
+                    InvalidAlgorithmParameterException, NoSuchAlgorithmException,
+                    ShortBufferException, NoSuchPaddingException {
+        ChunksMetadataProto.ChunksMetadata metaData = new ChunksMetadataProto.ChunksMetadata();
+        metaData.cipherType = ChunksMetadataProto.AES_256_GCM;
+        metaData.checksumType = ChunksMetadataProto.SHA_256;
+        metaData.chunkOrdering = encryptChunkOrdering(tertiaryKey, chunkOrdering);
+        return metaData;
+    }
+
+    private byte[] encryptChunkOrdering(
+            SecretKey tertiaryKey, ChunksMetadataProto.ChunkOrdering chunkOrdering)
+            throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
+                    NoSuchPaddingException, NoSuchAlgorithmException,
+                    InvalidAlgorithmParameterException, ShortBufferException {
+        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+
+        byte[] nonce = generateNonce();
+
+        cipher.init(
+                Cipher.ENCRYPT_MODE,
+                tertiaryKey,
+                new GCMParameterSpec(GCM_TAG_LENGTH_BYTES * BITS_PER_BYTE, nonce));
+
+        byte[] orderingBytes = ChunksMetadataProto.ChunkOrdering.toByteArray(chunkOrdering);
+        // We prepend the nonce to the ordering.
+        byte[] output =
+                Arrays.copyOf(
+                        nonce,
+                        GCM_NONCE_LENGTH_BYTES + orderingBytes.length + GCM_TAG_LENGTH_BYTES);
+
+        cipher.doFinal(
+                orderingBytes,
+                /*inputOffset=*/ 0,
+                /*inputLen=*/ orderingBytes.length,
+                output,
+                /*outputOffset=*/ GCM_NONCE_LENGTH_BYTES);
+
+        return output;
+    }
+
+    private byte[] generateNonce() {
+        byte[] nonce = new byte[GCM_NONCE_LENGTH_BYTES];
+        mSecureRandom.nextBytes(nonce);
+        return nonce;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupDataProcessor.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupDataProcessor.java
new file mode 100644
index 0000000..0baec8b
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupDataProcessor.java
@@ -0,0 +1,210 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.internal.util.Preconditions.checkNotNull;
+import static com.android.internal.util.Preconditions.checkState;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupTransport;
+import android.content.Context;
+import android.util.Slog;
+
+import com.android.server.backup.encryption.FullBackupDataProcessor;
+import com.android.server.backup.encryption.StreamUtils;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.security.SecureRandom;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+
+/**
+ * Accepts backup data from a {@link InputStream} and passes it to the encrypted full data backup
+ * path.
+ */
+public class EncryptedFullBackupDataProcessor implements FullBackupDataProcessor {
+
+    private static final String TAG = "EncryptedFullBackupDP";
+
+    private final Context mContext;
+    private final ExecutorService mExecutorService;
+    private final CryptoBackupServer mCryptoBackupServer;
+    private final SecureRandom mSecureRandom;
+    private final RecoverableKeyStoreSecondaryKey mSecondaryKey;
+    private final String mPackageName;
+
+    @Nullable private InputStream mInputStream;
+    @Nullable private PipedOutputStream mOutputStream;
+    @Nullable private EncryptedFullBackupTask mBackupTask;
+    @Nullable private Future<Void> mBackupTaskFuture;
+    @Nullable private FullBackupCallbacks mFullBackupCallbacks;
+
+    public EncryptedFullBackupDataProcessor(
+            Context context,
+            ExecutorService executorService,
+            CryptoBackupServer cryptoBackupServer,
+            SecureRandom secureRandom,
+            RecoverableKeyStoreSecondaryKey secondaryKey,
+            String packageName) {
+        mContext = checkNotNull(context);
+        mExecutorService = checkNotNull(executorService);
+        mCryptoBackupServer = checkNotNull(cryptoBackupServer);
+        mSecureRandom = checkNotNull(secureRandom);
+        mSecondaryKey = checkNotNull(secondaryKey);
+        mPackageName = checkNotNull(packageName);
+    }
+
+    @Override
+    public boolean initiate(InputStream inputStream) throws IOException {
+        checkState(mBackupTask == null, "initiate() twice");
+
+        this.mInputStream = inputStream;
+        mOutputStream = new PipedOutputStream();
+
+        mBackupTask =
+                EncryptedFullBackupTask.newInstance(
+                        mContext,
+                        mCryptoBackupServer,
+                        mSecureRandom,
+                        mSecondaryKey,
+                        mPackageName,
+                        new PipedInputStream(mOutputStream));
+
+        return true;
+    }
+
+    @Override
+    public void start() {
+        checkState(mBackupTask != null, "start() before initiate()");
+        mBackupTaskFuture = mExecutorService.submit(mBackupTask);
+    }
+
+    @Override
+    public int pushData(int numBytes) {
+        checkState(
+                mBackupTaskFuture != null && mInputStream != null && mOutputStream != null,
+                "pushData() before start()");
+
+        // If the upload has failed then stop without pushing any more bytes.
+        if (mBackupTaskFuture.isDone()) {
+            Optional<Exception> exception = getTaskException();
+            Slog.e(TAG, "Encrypted upload failed", exception.orElse(null));
+            if (exception.isPresent()) {
+                reportNetworkFailureIfNecessary(exception.get());
+
+                if (exception.get().getCause() instanceof SizeQuotaExceededException) {
+                    return BackupTransport.TRANSPORT_QUOTA_EXCEEDED;
+                }
+            }
+
+            return BackupTransport.TRANSPORT_ERROR;
+        }
+
+        try {
+            StreamUtils.copyStream(mInputStream, mOutputStream, numBytes);
+        } catch (IOException e) {
+            Slog.e(TAG, "IOException when processing backup", e);
+            return BackupTransport.TRANSPORT_ERROR;
+        }
+
+        return BackupTransport.TRANSPORT_OK;
+    }
+
+    @Override
+    public void cancel() {
+        checkState(mBackupTaskFuture != null && mBackupTask != null, "cancel() before start()");
+        mBackupTask.cancel();
+        closeStreams();
+    }
+
+    @Override
+    public int finish() {
+        checkState(mBackupTaskFuture != null, "finish() before start()");
+
+        // getTaskException() waits for the task to finish. We must close the streams first, which
+        // causes the task to finish, otherwise it will block forever.
+        closeStreams();
+        Optional<Exception> exception = getTaskException();
+
+        if (exception.isPresent()) {
+            Slog.e(TAG, "Exception during encrypted full backup", exception.get());
+            reportNetworkFailureIfNecessary(exception.get());
+
+            if (exception.get().getCause() instanceof SizeQuotaExceededException) {
+                return BackupTransport.TRANSPORT_QUOTA_EXCEEDED;
+            }
+            return BackupTransport.TRANSPORT_ERROR;
+
+        } else {
+            if (mFullBackupCallbacks != null) {
+                mFullBackupCallbacks.onSuccess();
+            }
+
+            return BackupTransport.TRANSPORT_OK;
+        }
+    }
+
+    private void closeStreams() {
+        StreamUtils.closeQuietly(mInputStream);
+        StreamUtils.closeQuietly(mOutputStream);
+    }
+
+    @Override
+    public void handleCheckSizeRejectionZeroBytes() {
+        cancel();
+    }
+
+    @Override
+    public void handleCheckSizeRejectionQuotaExceeded() {
+        cancel();
+    }
+
+    @Override
+    public void handleSendBytesQuotaExceeded() {
+        cancel();
+    }
+
+    @Override
+    public void attachCallbacks(FullBackupCallbacks fullBackupCallbacks) {
+        this.mFullBackupCallbacks = fullBackupCallbacks;
+    }
+
+    private void reportNetworkFailureIfNecessary(Exception exception) {
+        if (!(exception.getCause() instanceof SizeQuotaExceededException)
+                && mFullBackupCallbacks != null) {
+            mFullBackupCallbacks.onTransferFailed();
+        }
+    }
+
+    private Optional<Exception> getTaskException() {
+        if (mBackupTaskFuture != null) {
+            try {
+                mBackupTaskFuture.get();
+            } catch (InterruptedException | ExecutionException e) {
+                return Optional.of(e);
+            }
+        }
+        return Optional.empty();
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupTask.java
new file mode 100644
index 0000000..a938d71
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupTask.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import android.content.Context;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.backup.encryption.StreamUtils;
+import com.android.server.backup.encryption.chunking.ProtoStore;
+import com.android.server.backup.encryption.chunking.cdc.FingerprintMixer;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.TertiaryKeyManager;
+import com.android.server.backup.encryption.keys.TertiaryKeyRotationScheduler;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkListing;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+
+import javax.crypto.SecretKey;
+
+/**
+ * Task which reads a stream of plaintext full backup data, chunks it, encrypts it and uploads it to
+ * the server.
+ *
+ * <p>Once the backup completes or fails, closes the input stream.
+ */
+public class EncryptedFullBackupTask implements Callable<Void> {
+    private static final String TAG = "EncryptedFullBackupTask";
+
+    private static final int MIN_CHUNK_SIZE_BYTES = 2 * 1024;
+    private static final int MAX_CHUNK_SIZE_BYTES = 64 * 1024;
+    private static final int AVERAGE_CHUNK_SIZE_BYTES = 4 * 1024;
+
+    // TODO(b/69350270): Remove this hard-coded salt and related logic once we feel confident that
+    // incremental backup has happened at least once for all existing packages/users since we moved
+    // to
+    // using a randomly generated salt.
+    //
+    // The hard-coded fingerprint mixer salt was used for a short time period before replaced by one
+    // that is randomly generated on initial non-incremental backup and stored in ChunkListing to be
+    // reused for succeeding incremental backups. If an old ChunkListing does not have a
+    // fingerprint_mixer_salt, we assume that it was last backed up before a randomly generated salt
+    // is used so we use the hardcoded salt and set ChunkListing#fingerprint_mixer_salt to this
+    // value.
+    // Eventually all backup ChunkListings will have this field set and then we can remove the
+    // default
+    // value in the code.
+    static final byte[] DEFAULT_FINGERPRINT_MIXER_SALT =
+            Arrays.copyOf(new byte[] {20, 23}, FingerprintMixer.SALT_LENGTH_BYTES);
+
+    private final ProtoStore<ChunkListing> mChunkListingStore;
+    private final TertiaryKeyManager mTertiaryKeyManager;
+    private final InputStream mInputStream;
+    private final EncryptedBackupTask mTask;
+    private final String mPackageName;
+    private final SecureRandom mSecureRandom;
+
+    /** Creates a new instance with the default min, max and average chunk sizes. */
+    public static EncryptedFullBackupTask newInstance(
+            Context context,
+            CryptoBackupServer cryptoBackupServer,
+            SecureRandom secureRandom,
+            RecoverableKeyStoreSecondaryKey secondaryKey,
+            String packageName,
+            InputStream inputStream)
+            throws IOException {
+        EncryptedBackupTask encryptedBackupTask =
+                new EncryptedBackupTask(
+                        cryptoBackupServer,
+                        secureRandom,
+                        packageName,
+                        new BackupStreamEncrypter(
+                                inputStream,
+                                MIN_CHUNK_SIZE_BYTES,
+                                MAX_CHUNK_SIZE_BYTES,
+                                AVERAGE_CHUNK_SIZE_BYTES));
+        TertiaryKeyManager tertiaryKeyManager =
+                new TertiaryKeyManager(
+                        context,
+                        secureRandom,
+                        TertiaryKeyRotationScheduler.getInstance(context),
+                        secondaryKey,
+                        packageName);
+
+        return new EncryptedFullBackupTask(
+                ProtoStore.createChunkListingStore(context),
+                tertiaryKeyManager,
+                encryptedBackupTask,
+                inputStream,
+                packageName,
+                new SecureRandom());
+    }
+
+    @VisibleForTesting
+    EncryptedFullBackupTask(
+            ProtoStore<ChunkListing> chunkListingStore,
+            TertiaryKeyManager tertiaryKeyManager,
+            EncryptedBackupTask task,
+            InputStream inputStream,
+            String packageName,
+            SecureRandom secureRandom) {
+        mChunkListingStore = chunkListingStore;
+        mTertiaryKeyManager = tertiaryKeyManager;
+        mInputStream = inputStream;
+        mTask = task;
+        mPackageName = packageName;
+        mSecureRandom = secureRandom;
+    }
+
+    @Override
+    public Void call() throws Exception {
+        try {
+            Optional<ChunkListing> maybeOldChunkListing =
+                    mChunkListingStore.loadProto(mPackageName);
+
+            if (maybeOldChunkListing.isPresent()) {
+                Slog.i(TAG, "Found previous chunk listing for " + mPackageName);
+            }
+
+            // If the key has been rotated then we must re-encrypt all of the backup data.
+            if (mTertiaryKeyManager.wasKeyRotated()) {
+                Slog.i(
+                        TAG,
+                        "Key was rotated or newly generated for "
+                                + mPackageName
+                                + ", so performing a full backup.");
+                maybeOldChunkListing = Optional.empty();
+                mChunkListingStore.deleteProto(mPackageName);
+            }
+
+            SecretKey tertiaryKey = mTertiaryKeyManager.getKey();
+            WrappedKeyProto.WrappedKey wrappedTertiaryKey = mTertiaryKeyManager.getWrappedKey();
+
+            ChunkListing newChunkListing;
+            if (!maybeOldChunkListing.isPresent()) {
+                byte[] fingerprintMixerSalt = new byte[FingerprintMixer.SALT_LENGTH_BYTES];
+                mSecureRandom.nextBytes(fingerprintMixerSalt);
+                newChunkListing =
+                        mTask.performNonIncrementalBackup(
+                                tertiaryKey, wrappedTertiaryKey, fingerprintMixerSalt);
+            } else {
+                ChunkListing oldChunkListing = maybeOldChunkListing.get();
+
+                if (oldChunkListing.fingerprintMixerSalt == null
+                        || oldChunkListing.fingerprintMixerSalt.length == 0) {
+                    oldChunkListing.fingerprintMixerSalt = DEFAULT_FINGERPRINT_MIXER_SALT;
+                }
+
+                newChunkListing =
+                        mTask.performIncrementalBackup(
+                                tertiaryKey, wrappedTertiaryKey, oldChunkListing);
+            }
+
+            mChunkListingStore.saveProto(mPackageName, newChunkListing);
+            Slog.v(TAG, "Saved chunk listing for " + mPackageName);
+        } catch (IOException e) {
+            Slog.e(TAG, "Storage exception, wiping state");
+            mChunkListingStore.deleteProto(mPackageName);
+            throw e;
+        } finally {
+            StreamUtils.closeQuietly(mInputStream);
+        }
+
+        return null;
+    }
+
+    /**
+     * Signals to the task that the backup has been cancelled. If the upload has not yet started
+     * then the task will not upload any data to the server or save the new chunk listing.
+     *
+     * <p>You must then terminate the input stream.
+     */
+    public void cancel() {
+        mTask.cancel();
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullRestoreTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullRestoreTask.java
new file mode 100644
index 0000000..04381af
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedFullRestoreTask.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+
+import android.annotation.Nullable;
+import android.content.Context;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.backup.encryption.FullRestoreDataProcessor;
+import com.android.server.backup.encryption.FullRestoreDownloader;
+import com.android.server.backup.encryption.StreamUtils;
+import com.android.server.backup.encryption.chunking.DecryptedChunkFileOutput;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.ShortBufferException;
+
+/** Downloads the encrypted backup file, decrypts it and passes the data to backup manager. */
+public class EncryptedFullRestoreTask implements FullRestoreDataProcessor {
+    private static final String DEFAULT_TEMPORARY_FOLDER = "encrypted_restore_temp";
+    private static final String ENCRYPTED_FILE_NAME = "encrypted_restore";
+    private static final String DECRYPTED_FILE_NAME = "decrypted_restore";
+
+    private final FullRestoreToFileTask mFullRestoreToFileTask;
+    private final BackupFileDecryptorTask mBackupFileDecryptorTask;
+    private final File mEncryptedFile;
+    private final File mDecryptedFile;
+    @Nullable private InputStream mDecryptedFileInputStream;
+
+    /**
+     * Creates a new task which stores temporary files in the files directory.
+     *
+     * @param fullRestoreDownloader which will download the backup file
+     * @param tertiaryKey which the backup file is encrypted with
+     */
+    public static EncryptedFullRestoreTask newInstance(
+            Context context, FullRestoreDownloader fullRestoreDownloader, SecretKey tertiaryKey)
+            throws NoSuchAlgorithmException, NoSuchPaddingException {
+        File temporaryFolder = new File(context.getFilesDir(), DEFAULT_TEMPORARY_FOLDER);
+        temporaryFolder.mkdirs();
+        return new EncryptedFullRestoreTask(
+                temporaryFolder, fullRestoreDownloader, new BackupFileDecryptorTask(tertiaryKey));
+    }
+
+    @VisibleForTesting
+    EncryptedFullRestoreTask(
+            File temporaryFolder,
+            FullRestoreDownloader fullRestoreDownloader,
+            BackupFileDecryptorTask backupFileDecryptorTask) {
+        checkArgument(temporaryFolder.isDirectory(), "Temporary folder must be existing directory");
+
+        mEncryptedFile = new File(temporaryFolder, ENCRYPTED_FILE_NAME);
+        mDecryptedFile = new File(temporaryFolder, DECRYPTED_FILE_NAME);
+
+        mFullRestoreToFileTask = new FullRestoreToFileTask(fullRestoreDownloader);
+        mBackupFileDecryptorTask = backupFileDecryptorTask;
+    }
+
+    /**
+     * Reads the next decrypted bytes into the given buffer.
+     *
+     * <p>During the first call this method will download the backup file from the server, decrypt
+     * it and save it to disk. It will then read the bytes from the file on disk.
+     *
+     * <p>Once this method has read all the bytes of the file, the caller must call {@link #finish}
+     * to clean up.
+     *
+     * @return the number of bytes read, or {@code -1} on reaching the end of the file
+     */
+    @Override
+    public int readNextChunk(byte[] buffer) throws IOException {
+        if (mDecryptedFileInputStream == null) {
+            try {
+                mDecryptedFileInputStream = downloadAndDecryptBackup();
+            } catch (BadPaddingException
+                    | InvalidKeyException
+                    | NoSuchAlgorithmException
+                    | IllegalBlockSizeException
+                    | ShortBufferException
+                    | EncryptedRestoreException
+                    | InvalidAlgorithmParameterException e) {
+                throw new IOException("Encryption issue", e);
+            }
+        }
+
+        return mDecryptedFileInputStream.read(buffer);
+    }
+
+    private InputStream downloadAndDecryptBackup()
+            throws IOException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException,
+                    IllegalBlockSizeException, ShortBufferException, EncryptedRestoreException,
+                    InvalidAlgorithmParameterException {
+        mFullRestoreToFileTask.restoreToFile(mEncryptedFile);
+        mBackupFileDecryptorTask.decryptFile(
+                mEncryptedFile, new DecryptedChunkFileOutput(mDecryptedFile));
+        mEncryptedFile.delete();
+        return new BufferedInputStream(new FileInputStream(mDecryptedFile));
+    }
+
+    /** Cleans up temporary files. */
+    @Override
+    public void finish(FullRestoreDownloader.FinishType unusedFinishType) {
+        // The download is finished and log sent during RestoreToFileTask#restoreToFile(), so we
+        // don't need to do either of those things here.
+
+        StreamUtils.closeQuietly(mDecryptedFileInputStream);
+        mEncryptedFile.delete();
+        mDecryptedFile.delete();
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedKvBackupTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedKvBackupTask.java
new file mode 100644
index 0000000..619438c
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedKvBackupTask.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupDataInput;
+import android.content.Context;
+import android.os.ParcelFileDescriptor;
+import android.security.keystore.recovery.InternalRecoveryServiceException;
+import android.security.keystore.recovery.LockScreenRequiredException;
+import android.util.Pair;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.backup.encryption.CryptoSettings;
+import com.android.server.backup.encryption.chunking.ProtoStore;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKeyManager;
+import com.android.server.backup.encryption.keys.TertiaryKeyManager;
+import com.android.server.backup.encryption.keys.TertiaryKeyRotationScheduler;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.security.GeneralSecurityException;
+import java.security.InvalidKeyException;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+import java.util.Optional;
+
+// TODO(b/141975695): Create a base class for EncryptedKvBackupTask and EncryptedFullBackupTask.
+/** Performs encrypted key value backup, handling rotating the tertiary key as necessary. */
+public class EncryptedKvBackupTask {
+    private static final String TAG = "EncryptedKvBackupTask";
+
+    private final TertiaryKeyManager mTertiaryKeyManager;
+    private final RecoverableKeyStoreSecondaryKey mSecondaryKey;
+    private final ProtoStore<KeyValueListingProto.KeyValueListing> mKeyValueListingStore;
+    private final ProtoStore<ChunksMetadataProto.ChunkListing> mChunkListingStore;
+    private final KvBackupEncrypter mKvBackupEncrypter;
+    private final EncryptedBackupTask mEncryptedBackupTask;
+    private final String mPackageName;
+
+    /** Constructs new instances of {@link EncryptedKvBackupTask}. */
+    public static class EncryptedKvBackupTaskFactory {
+        /**
+         * Creates a new instance.
+         *
+         * <p>Either initializes encrypted backup or loads an existing secondary key as necessary.
+         *
+         * @param cryptoSettings to load secondary key state from
+         * @param fileDescriptor to read the backup data from
+         */
+        public EncryptedKvBackupTask newInstance(
+                Context context,
+                SecureRandom secureRandom,
+                CryptoBackupServer cryptoBackupServer,
+                CryptoSettings cryptoSettings,
+                RecoverableKeyStoreSecondaryKeyManager
+                                .RecoverableKeyStoreSecondaryKeyManagerProvider
+                        recoverableSecondaryKeyManagerProvider,
+                ParcelFileDescriptor fileDescriptor,
+                String packageName)
+                throws IOException, UnrecoverableKeyException, LockScreenRequiredException,
+                        InternalRecoveryServiceException, InvalidKeyException {
+            RecoverableKeyStoreSecondaryKey secondaryKey =
+                    new InitializeRecoverableSecondaryKeyTask(
+                                    context,
+                                    cryptoSettings,
+                                    recoverableSecondaryKeyManagerProvider.get(),
+                                    cryptoBackupServer)
+                            .run();
+            KvBackupEncrypter backupEncrypter =
+                    new KvBackupEncrypter(new BackupDataInput(fileDescriptor.getFileDescriptor()));
+            TertiaryKeyManager tertiaryKeyManager =
+                    new TertiaryKeyManager(
+                            context,
+                            secureRandom,
+                            TertiaryKeyRotationScheduler.getInstance(context),
+                            secondaryKey,
+                            packageName);
+
+            return new EncryptedKvBackupTask(
+                    tertiaryKeyManager,
+                    ProtoStore.createKeyValueListingStore(context),
+                    secondaryKey,
+                    ProtoStore.createChunkListingStore(context),
+                    backupEncrypter,
+                    new EncryptedBackupTask(
+                            cryptoBackupServer, secureRandom, packageName, backupEncrypter),
+                    packageName);
+        }
+    }
+
+    @VisibleForTesting
+    EncryptedKvBackupTask(
+            TertiaryKeyManager tertiaryKeyManager,
+            ProtoStore<KeyValueListingProto.KeyValueListing> keyValueListingStore,
+            RecoverableKeyStoreSecondaryKey secondaryKey,
+            ProtoStore<ChunksMetadataProto.ChunkListing> chunkListingStore,
+            KvBackupEncrypter kvBackupEncrypter,
+            EncryptedBackupTask encryptedBackupTask,
+            String packageName) {
+        mTertiaryKeyManager = tertiaryKeyManager;
+        mSecondaryKey = secondaryKey;
+        mKeyValueListingStore = keyValueListingStore;
+        mChunkListingStore = chunkListingStore;
+        mKvBackupEncrypter = kvBackupEncrypter;
+        mEncryptedBackupTask = encryptedBackupTask;
+        mPackageName = packageName;
+    }
+
+    /**
+     * Reads backup data from the file descriptor provided in the construtor, encrypts it and
+     * uploads it to the server.
+     *
+     * <p>The {@code incremental} flag indicates if the backup data provided is incremental or a
+     * complete set. Incremental backup is not possible if no previous crypto state exists, or the
+     * tertiary key must be rotated in the next backup. If the caller requests incremental backup
+     * but it is not possible, then the backup will not start and this method will throw {@link
+     * NonIncrementalBackupRequiredException}.
+     *
+     * <p>TODO(b/70704456): Update return code to indicate that we require non-incremental backup.
+     *
+     * @param incremental {@code true} if the data provided is a diff from the previous backup,
+     *     {@code false} if it is a complete set
+     * @throws NonIncrementalBackupRequiredException if the caller provides an incremental backup but the task
+     *     requires non-incremental backup
+     */
+    public void performBackup(boolean incremental)
+            throws GeneralSecurityException, IOException, NoSuchMethodException,
+            InstantiationException, IllegalAccessException, InvocationTargetException,
+            NonIncrementalBackupRequiredException {
+        if (mTertiaryKeyManager.wasKeyRotated()) {
+            Slog.d(TAG, "Tertiary key is new so clearing package state.");
+            deleteListings(mPackageName);
+        }
+
+        Optional<Pair<KeyValueListingProto.KeyValueListing, ChunksMetadataProto.ChunkListing>>
+                oldListings = getListingsAndEnsureConsistency(mPackageName);
+
+        if (oldListings.isPresent() && !incremental) {
+            Slog.d(
+                    TAG,
+                    "Non-incremental backup requested but incremental state existed, clearing it");
+            deleteListings(mPackageName);
+            oldListings = Optional.empty();
+        }
+
+        if (!oldListings.isPresent() && incremental) {
+            // If we don't have any state then we require a non-incremental backup, but this backup
+            // is incremental.
+            throw new NonIncrementalBackupRequiredException();
+        }
+
+        if (oldListings.isPresent()) {
+            mKvBackupEncrypter.setOldKeyValueListing(oldListings.get().first);
+        }
+
+        ChunksMetadataProto.ChunkListing newChunkListing;
+        if (oldListings.isPresent()) {
+            Slog.v(TAG, "Old listings existed, performing incremental backup");
+            newChunkListing =
+                    mEncryptedBackupTask.performIncrementalBackup(
+                            mTertiaryKeyManager.getKey(),
+                            mTertiaryKeyManager.getWrappedKey(),
+                            oldListings.get().second);
+        } else {
+            Slog.v(TAG, "Old listings did not exist, performing non-incremental backup");
+            // kv backups don't use this salt because they don't involve content-defined chunking.
+            byte[] fingerprintMixerSalt = null;
+            newChunkListing =
+                    mEncryptedBackupTask.performNonIncrementalBackup(
+                            mTertiaryKeyManager.getKey(),
+                            mTertiaryKeyManager.getWrappedKey(),
+                            fingerprintMixerSalt);
+        }
+
+        Slog.v(TAG, "Backup and upload succeeded, saving new listings");
+        saveListings(mPackageName, mKvBackupEncrypter.getNewKeyValueListing(), newChunkListing);
+    }
+
+    private Optional<Pair<KeyValueListingProto.KeyValueListing, ChunksMetadataProto.ChunkListing>>
+            getListingsAndEnsureConsistency(String packageName)
+                    throws IOException, InvocationTargetException, NoSuchMethodException,
+                            InstantiationException, IllegalAccessException {
+        Optional<KeyValueListingProto.KeyValueListing> keyValueListing =
+                mKeyValueListingStore.loadProto(packageName);
+        Optional<ChunksMetadataProto.ChunkListing> chunkListing =
+                mChunkListingStore.loadProto(packageName);
+
+        // Normally either both protos exist or neither exist, but we correct this just in case.
+        boolean bothPresent = keyValueListing.isPresent() && chunkListing.isPresent();
+        if (!bothPresent) {
+            Slog.d(
+                    TAG,
+                    "Both listing were not present, clearing state, key value="
+                            + keyValueListing.isPresent()
+                            + ", chunk="
+                            + chunkListing.isPresent());
+            deleteListings(packageName);
+            return Optional.empty();
+        }
+
+        return Optional.of(Pair.create(keyValueListing.get(), chunkListing.get()));
+    }
+
+    private void saveListings(
+            String packageName,
+            KeyValueListingProto.KeyValueListing keyValueListing,
+            ChunksMetadataProto.ChunkListing chunkListing) {
+        try {
+            mKeyValueListingStore.saveProto(packageName, keyValueListing);
+            mChunkListingStore.saveProto(packageName, chunkListing);
+        } catch (IOException e) {
+            // If a problem occurred while saving either listing then they may be inconsistent, so
+            // delete
+            // both.
+            Slog.w(TAG, "Unable to save listings, deleting both for consistency", e);
+            deleteListings(packageName);
+        }
+    }
+
+    private void deleteListings(String packageName) {
+        mKeyValueListingStore.deleteProto(packageName);
+        mChunkListingStore.deleteProto(packageName);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedKvRestoreTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedKvRestoreTask.java
new file mode 100644
index 0000000..12b4459
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/EncryptedKvRestoreTask.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+
+import android.app.backup.BackupDataOutput;
+import android.content.Context;
+import android.os.ParcelFileDescriptor;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.backup.encryption.FullRestoreDownloader;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKeyManager;
+import com.android.server.backup.encryption.keys.RestoreKeyFetcher;
+import com.android.server.backup.encryption.kv.DecryptedChunkKvOutput;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.io.File;
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.KeyException;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.ShortBufferException;
+
+/**
+ * Performs a key value restore by downloading the backup set, decrypting it and writing it to the
+ * file provided by backup manager.
+ */
+public class EncryptedKvRestoreTask {
+    private static final String ENCRYPTED_FILE_NAME = "encrypted_kv";
+
+    private final File mTemporaryFolder;
+    private final ChunkHasher mChunkHasher;
+    private final FullRestoreToFileTask mFullRestoreToFileTask;
+    private final BackupFileDecryptorTask mBackupFileDecryptorTask;
+
+    /** Constructs new instances of the task. */
+    public static class EncryptedKvRestoreTaskFactory {
+        /**
+         * Constructs a new instance.
+         *
+         * <p>Fetches the appropriate secondary key and uses this to unwrap the tertiary key. Stores
+         * temporary files in {@link Context#getFilesDir()}.
+         */
+        public EncryptedKvRestoreTask newInstance(
+                Context context,
+                RecoverableKeyStoreSecondaryKeyManager
+                                .RecoverableKeyStoreSecondaryKeyManagerProvider
+                        recoverableSecondaryKeyManagerProvider,
+                FullRestoreDownloader fullRestoreDownloader,
+                String secondaryKeyAlias,
+                WrappedKeyProto.WrappedKey wrappedTertiaryKey)
+                throws EncryptedRestoreException, NoSuchAlgorithmException, NoSuchPaddingException,
+                        KeyException, InvalidAlgorithmParameterException {
+            SecretKey tertiaryKey =
+                    RestoreKeyFetcher.unwrapTertiaryKey(
+                            recoverableSecondaryKeyManagerProvider,
+                            secondaryKeyAlias,
+                            wrappedTertiaryKey);
+
+            return new EncryptedKvRestoreTask(
+                    context.getFilesDir(),
+                    new ChunkHasher(tertiaryKey),
+                    new FullRestoreToFileTask(fullRestoreDownloader),
+                    new BackupFileDecryptorTask(tertiaryKey));
+        }
+    }
+
+    @VisibleForTesting
+    EncryptedKvRestoreTask(
+            File temporaryFolder,
+            ChunkHasher chunkHasher,
+            FullRestoreToFileTask fullRestoreToFileTask,
+            BackupFileDecryptorTask backupFileDecryptorTask) {
+        checkArgument(
+                temporaryFolder.isDirectory(), "Temporary folder must be an existing directory");
+
+        mTemporaryFolder = temporaryFolder;
+        mChunkHasher = chunkHasher;
+        mFullRestoreToFileTask = fullRestoreToFileTask;
+        mBackupFileDecryptorTask = backupFileDecryptorTask;
+    }
+
+    /**
+     * Runs the restore, writing the pairs in lexicographical order to the given file descriptor.
+     *
+     * <p>This will block for the duration of the restore.
+     *
+     * @throws EncryptedRestoreException if there is a problem decrypting or verifying the backup
+     */
+    public void getRestoreData(ParcelFileDescriptor output)
+            throws IOException, EncryptedRestoreException, BadPaddingException,
+                    InvalidAlgorithmParameterException, NoSuchAlgorithmException,
+                    IllegalBlockSizeException, ShortBufferException, InvalidKeyException {
+        File encryptedFile = new File(mTemporaryFolder, ENCRYPTED_FILE_NAME);
+        try {
+            downloadDecryptAndWriteBackup(encryptedFile, output);
+        } finally {
+            encryptedFile.delete();
+        }
+    }
+
+    private void downloadDecryptAndWriteBackup(File encryptedFile, ParcelFileDescriptor output)
+            throws EncryptedRestoreException, IOException, BadPaddingException, InvalidKeyException,
+                    NoSuchAlgorithmException, IllegalBlockSizeException, ShortBufferException,
+                    InvalidAlgorithmParameterException {
+        mFullRestoreToFileTask.restoreToFile(encryptedFile);
+        DecryptedChunkKvOutput decryptedChunkKvOutput = new DecryptedChunkKvOutput(mChunkHasher);
+        mBackupFileDecryptorTask.decryptFile(encryptedFile, decryptedChunkKvOutput);
+
+        BackupDataOutput backupDataOutput = new BackupDataOutput(output.getFileDescriptor());
+        for (KeyValuePairProto.KeyValuePair pair : decryptedChunkKvOutput.getPairs()) {
+            backupDataOutput.writeEntityHeader(pair.key, pair.value.length);
+            backupDataOutput.writeEntityData(pair.value, pair.value.length);
+        }
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/FullRestoreToFileTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/FullRestoreToFileTask.java
new file mode 100644
index 0000000..82f83f9
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/FullRestoreToFileTask.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.backup.encryption.FullRestoreDownloader;
+import com.android.server.backup.encryption.FullRestoreDownloader.FinishType;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+/**
+ * Reads a stream from a {@link FullRestoreDownloader} and writes it to a file for consumption by
+ * {@link BackupFileDecryptorTask}.
+ */
+public class FullRestoreToFileTask {
+    /**
+     * Maximum number of bytes which the framework can request from the full restore data stream in
+     * one call to {@link BackupTransport#getNextFullRestoreDataChunk}.
+     */
+    public static final int MAX_BYTES_FULL_RESTORE_CHUNK = 1024 * 32;
+
+    /** Returned when the end of a backup stream has been reached. */
+    private static final int END_OF_STREAM = -1;
+
+    private final FullRestoreDownloader mFullRestoreDownloader;
+    private final int mBufferSize;
+
+    /**
+     * Constructs a new instance which reads from the given package wrapper, using a buffer of size
+     * {@link #MAX_BYTES_FULL_RESTORE_CHUNK}.
+     */
+    public FullRestoreToFileTask(FullRestoreDownloader fullRestoreDownloader) {
+        this(fullRestoreDownloader, MAX_BYTES_FULL_RESTORE_CHUNK);
+    }
+
+    @VisibleForTesting
+    FullRestoreToFileTask(FullRestoreDownloader fullRestoreDownloader, int bufferSize) {
+        checkArgument(bufferSize > 0, "Buffer must have positive size");
+
+        this.mFullRestoreDownloader = fullRestoreDownloader;
+        this.mBufferSize = bufferSize;
+    }
+
+    /**
+     * Downloads the backup file from the server and writes it to the given file.
+     *
+     * <p>At the end of the download (success or failure), closes the connection and sends a
+     * Clearcut log.
+     */
+    public void restoreToFile(File targetFile) throws IOException {
+        try (BufferedOutputStream outputStream =
+                new BufferedOutputStream(new FileOutputStream(targetFile))) {
+            byte[] buffer = new byte[mBufferSize];
+            int bytesRead = mFullRestoreDownloader.readNextChunk(buffer);
+            while (bytesRead != END_OF_STREAM) {
+                outputStream.write(buffer, /* off=*/ 0, bytesRead);
+                bytesRead = mFullRestoreDownloader.readNextChunk(buffer);
+            }
+
+            outputStream.flush();
+
+            mFullRestoreDownloader.finish(FinishType.FINISHED);
+        } catch (IOException e) {
+            mFullRestoreDownloader.finish(FinishType.TRANSFER_FAILURE);
+            throw e;
+        }
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/InitializeRecoverableSecondaryKeyTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/InitializeRecoverableSecondaryKeyTask.java
new file mode 100644
index 0000000..d436554
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/InitializeRecoverableSecondaryKeyTask.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import android.content.Context;
+import android.security.keystore.recovery.InternalRecoveryServiceException;
+import android.security.keystore.recovery.LockScreenRequiredException;
+import android.security.keystore.recovery.RecoveryController;
+import android.util.Slog;
+
+import com.android.server.backup.encryption.CryptoSettings;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKeyManager;
+
+import java.security.InvalidKeyException;
+import java.security.UnrecoverableKeyException;
+import java.util.Collections;
+import java.util.Optional;
+
+/**
+ * Initializes the device for encrypted backup, through generating a secondary key, and setting its
+ * alias in the settings.
+ *
+ * <p>If the device is already initialized, this is a no-op.
+ */
+public class InitializeRecoverableSecondaryKeyTask {
+    private static final String TAG = "InitializeRecoverableSecondaryKeyTask";
+
+    private final Context mContext;
+    private final CryptoSettings mCryptoSettings;
+    private final RecoverableKeyStoreSecondaryKeyManager mSecondaryKeyManager;
+    private final CryptoBackupServer mBackupServer;
+
+    /**
+     * A new instance.
+     *
+     * @param cryptoSettings Settings to store the active key alias.
+     * @param secondaryKeyManager Key manager to generate the new active secondary key.
+     * @param backupServer Server with which to sync the active key alias.
+     */
+    public InitializeRecoverableSecondaryKeyTask(
+            Context context,
+            CryptoSettings cryptoSettings,
+            RecoverableKeyStoreSecondaryKeyManager secondaryKeyManager,
+            CryptoBackupServer backupServer) {
+        mContext = context;
+        mCryptoSettings = cryptoSettings;
+        mSecondaryKeyManager = secondaryKeyManager;
+        mBackupServer = backupServer;
+    }
+
+    /**
+     * Initializes the device for encrypted backup, by generating a recoverable secondary key, then
+     * sending that alias to the backup server and saving it in local settings.
+     *
+     * <p>If there is already an active secondary key then does nothing. If the active secondary key
+     * is destroyed then throws {@link InvalidKeyException}.
+     *
+     * <p>If a key rotation is pending and able to finish (i.e., the new key has synced with the
+     * remote trusted hardware module), then it completes the rotation before returning the key.
+     *
+     * @return The active secondary key.
+     * @throws InvalidKeyException if the secondary key is in a bad state.
+     */
+    public RecoverableKeyStoreSecondaryKey run()
+            throws InvalidKeyException, LockScreenRequiredException, UnrecoverableKeyException,
+                    InternalRecoveryServiceException {
+        // Complete any pending key rotations
+        new RotateSecondaryKeyTask(
+                        mContext,
+                        mSecondaryKeyManager,
+                        mBackupServer,
+                        mCryptoSettings,
+                        RecoveryController.getInstance(mContext))
+                .run();
+
+        return runInternal();
+    }
+
+    private RecoverableKeyStoreSecondaryKey runInternal()
+            throws InvalidKeyException, LockScreenRequiredException, UnrecoverableKeyException,
+                    InternalRecoveryServiceException {
+        Optional<RecoverableKeyStoreSecondaryKey> maybeActiveKey = loadFromSetting();
+
+        if (maybeActiveKey.isPresent()) {
+            assertKeyNotDestroyed(maybeActiveKey.get());
+            Slog.d(TAG, "Secondary key already initialized: " + maybeActiveKey.get().getAlias());
+            return maybeActiveKey.get();
+        }
+
+        Slog.v(TAG, "Initializing for crypto: generating a secondary key.");
+        RecoverableKeyStoreSecondaryKey key = mSecondaryKeyManager.generate();
+
+        String alias = key.getAlias();
+        Slog.i(TAG, "Generated new secondary key " + alias);
+
+        // No tertiary keys yet as we are creating a brand new secondary (without rotation).
+        mBackupServer.setActiveSecondaryKeyAlias(alias, /*tertiaryKeys=*/ Collections.emptyMap());
+        Slog.v(TAG, "Successfully synced %s " + alias + " with server.");
+
+        mCryptoSettings.initializeWithKeyAlias(alias);
+        Slog.v(TAG, "Successfully saved " + alias + " as active secondary to disk.");
+
+        return key;
+    }
+
+    private void assertKeyNotDestroyed(RecoverableKeyStoreSecondaryKey key)
+            throws InvalidKeyException {
+        if (key.getStatus(mContext) == RecoverableKeyStoreSecondaryKey.Status.DESTROYED) {
+            throw new InvalidKeyException("Key destroyed: " + key.getAlias());
+        }
+    }
+
+    private Optional<RecoverableKeyStoreSecondaryKey> loadFromSetting()
+            throws InvalidKeyException, UnrecoverableKeyException,
+                    InternalRecoveryServiceException {
+
+        // TODO: b/141856950.
+        if (!mCryptoSettings.getIsInitialized()) {
+            return Optional.empty();
+        }
+
+        Optional<String> maybeAlias = mCryptoSettings.getActiveSecondaryKeyAlias();
+        if (!maybeAlias.isPresent()) {
+            throw new InvalidKeyException(
+                    "Settings said crypto was initialized, but there was no active secondary"
+                            + " alias");
+        }
+
+        String alias = maybeAlias.get();
+
+        Optional<RecoverableKeyStoreSecondaryKey> key;
+        key = mSecondaryKeyManager.get(alias);
+
+        if (!key.isPresent()) {
+            throw new InvalidKeyException(
+                    "Initialized with key but it was not in key store: " + alias);
+        }
+
+        return key;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/KvBackupEncrypter.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/KvBackupEncrypter.java
new file mode 100644
index 0000000..d20cd4c
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/KvBackupEncrypter.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.internal.util.Preconditions.checkState;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupDataInput;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkEncryptor;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.kv.KeyValueListingBuilder;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.InvalidKeyException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.SecretKey;
+
+/**
+ * Reads key value backup data from an input, converts each pair into a chunk and encrypts the
+ * chunks.
+ *
+ * <p>The caller should pass in the key value listing from the previous backup, if there is one.
+ * This class emits chunks for both existing and new pairs, using the provided listing to
+ * determine the hashes of pairs that already exist. During the backup it computes the new listing,
+ * which the caller should store on disk and pass in at the start of the next backup.
+ *
+ * <p>Also computes the message digest, which is {@code SHA-256(chunk hashes sorted
+ * lexicographically)}.
+ */
+public class KvBackupEncrypter implements BackupEncrypter {
+    private final BackupDataInput mBackupDataInput;
+
+    private KeyValueListingProto.KeyValueListing mOldKeyValueListing;
+    @Nullable private KeyValueListingBuilder mNewKeyValueListing;
+
+    /**
+     * Constructs a new instance which reads data from the given input.
+     *
+     * <p>By default this performs non-incremental backup, call {@link #setOldKeyValueListing} to
+     * perform incremental backup.
+     */
+    public KvBackupEncrypter(BackupDataInput backupDataInput) {
+        mBackupDataInput = backupDataInput;
+        mOldKeyValueListing = KeyValueListingBuilder.emptyListing();
+    }
+
+    /** Sets the old listing to perform incremental backup against. */
+    public void setOldKeyValueListing(KeyValueListingProto.KeyValueListing oldKeyValueListing) {
+        mOldKeyValueListing = oldKeyValueListing;
+    }
+
+    @Override
+    public Result backup(
+            SecretKey secretKey,
+            @Nullable byte[] unusedFingerprintMixerSalt,
+            Set<ChunkHash> unusedExistingChunks)
+            throws IOException, GeneralSecurityException {
+        ChunkHasher chunkHasher = new ChunkHasher(secretKey);
+        ChunkEncryptor chunkEncryptor = new ChunkEncryptor(secretKey, new SecureRandom());
+        mNewKeyValueListing = new KeyValueListingBuilder();
+        List<ChunkHash> allChunks = new ArrayList<>();
+        List<EncryptedChunk> newChunks = new ArrayList<>();
+
+        Map<String, ChunkHash> existingChunksToReuse = buildPairMap(mOldKeyValueListing);
+
+        while (mBackupDataInput.readNextHeader()) {
+            String key = mBackupDataInput.getKey();
+            Optional<byte[]> value = readEntireValue(mBackupDataInput);
+
+            // As this pair exists in the new backup, we don't need to add it from the previous
+            // backup.
+            existingChunksToReuse.remove(key);
+
+            // If the value is not present then this key has been deleted.
+            if (value.isPresent()) {
+                EncryptedChunk newChunk =
+                        createEncryptedChunk(chunkHasher, chunkEncryptor, key, value.get());
+                allChunks.add(newChunk.key());
+                newChunks.add(newChunk);
+                mNewKeyValueListing.addPair(key, newChunk.key());
+            }
+        }
+
+        allChunks.addAll(existingChunksToReuse.values());
+
+        mNewKeyValueListing.addAll(existingChunksToReuse);
+
+        return new Result(allChunks, newChunks, createMessageDigest(allChunks));
+    }
+
+    /**
+     * Returns a listing containing the pairs in the new backup.
+     *
+     * <p>You must call {@link #backup} first.
+     */
+    public KeyValueListingProto.KeyValueListing getNewKeyValueListing() {
+        checkState(mNewKeyValueListing != null, "Must call backup() first");
+        return mNewKeyValueListing.build();
+    }
+
+    private static Map<String, ChunkHash> buildPairMap(
+            KeyValueListingProto.KeyValueListing listing) {
+        Map<String, ChunkHash> map = new HashMap<>();
+        for (KeyValueListingProto.KeyValueEntry entry : listing.entries) {
+            map.put(entry.key, new ChunkHash(entry.hash));
+        }
+        return map;
+    }
+
+    private EncryptedChunk createEncryptedChunk(
+            ChunkHasher chunkHasher, ChunkEncryptor chunkEncryptor, String key, byte[] value)
+            throws InvalidKeyException, IllegalBlockSizeException {
+        KeyValuePairProto.KeyValuePair pair = new KeyValuePairProto.KeyValuePair();
+        pair.key = key;
+        pair.value = Arrays.copyOf(value, value.length);
+
+        byte[] plaintext = KeyValuePairProto.KeyValuePair.toByteArray(pair);
+        return chunkEncryptor.encrypt(chunkHasher.computeHash(plaintext), plaintext);
+    }
+
+    private static byte[] createMessageDigest(List<ChunkHash> allChunks)
+            throws NoSuchAlgorithmException {
+        MessageDigest messageDigest =
+                MessageDigest.getInstance(BackupEncrypter.MESSAGE_DIGEST_ALGORITHM);
+        // TODO:b/141531271 Extract sorted chunks code to utility class
+        List<ChunkHash> sortedChunks = new ArrayList<>(allChunks);
+        Collections.sort(sortedChunks);
+        for (ChunkHash hash : sortedChunks) {
+            messageDigest.update(hash.getHash());
+        }
+        return messageDigest.digest();
+    }
+
+    private static Optional<byte[]> readEntireValue(BackupDataInput input) throws IOException {
+        // A negative data size indicates that this key should be deleted.
+        if (input.getDataSize() < 0) {
+            return Optional.empty();
+        }
+
+        byte[] value = new byte[input.getDataSize()];
+        int bytesRead = 0;
+        while (bytesRead < value.length) {
+            bytesRead += input.readEntityData(value, bytesRead, value.length - bytesRead);
+        }
+        return Optional.of(value);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/MalformedEncryptedFileException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/MalformedEncryptedFileException.java
new file mode 100644
index 0000000..78c370b
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/MalformedEncryptedFileException.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+/** Exception thrown when we cannot parse the encrypted backup file. */
+public class MalformedEncryptedFileException extends EncryptedRestoreException {
+    public MalformedEncryptedFileException(String message) {
+        super(message);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/MessageDigestMismatchException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/MessageDigestMismatchException.java
new file mode 100644
index 0000000..1e4f43b
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/MessageDigestMismatchException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+/**
+ * Error thrown if the message digest of the plaintext backup does not match that in the {@link
+ * com.android.server.backup.encryption.protos.ChunksMetadataProto.ChunkOrdering}.
+ */
+public class MessageDigestMismatchException extends EncryptedRestoreException {
+    public MessageDigestMismatchException(String message) {
+        super(message);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/NoActiveSecondaryKeyException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/NoActiveSecondaryKeyException.java
new file mode 100644
index 0000000..72e8a89
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/NoActiveSecondaryKeyException.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+/**
+ * Error thrown if attempting to rotate key when there is no current active secondary key set
+ * locally. This means the device needs to re-initialize, asking the backup server what the active
+ * secondary key is.
+ */
+public class NoActiveSecondaryKeyException extends Exception {
+    public NoActiveSecondaryKeyException(String message) {
+        super(message);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/NonIncrementalBackupRequiredException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/NonIncrementalBackupRequiredException.java
new file mode 100644
index 0000000..a3eda7d
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/NonIncrementalBackupRequiredException.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+// TODO(141840878): Update documentation.
+/**
+ * Exception thrown when the framework provides an incremental backup but the transport requires a
+ * non-incremental backup.
+ */
+public class NonIncrementalBackupRequiredException extends Exception {}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/RotateSecondaryKeyTask.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/RotateSecondaryKeyTask.java
new file mode 100644
index 0000000..d58cb66
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/RotateSecondaryKeyTask.java
@@ -0,0 +1,270 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static android.os.Build.VERSION_CODES.P;
+
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import android.content.Context;
+import android.security.keystore.recovery.InternalRecoveryServiceException;
+import android.security.keystore.recovery.RecoveryController;
+import android.util.Slog;
+
+import com.android.server.backup.encryption.CryptoSettings;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.KeyWrapUtils;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKeyManager;
+import com.android.server.backup.encryption.keys.TertiaryKeyStore;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+
+/**
+ * Finishes a rotation for a {@link
+ * com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey}.
+ */
+public class RotateSecondaryKeyTask {
+    private static final String TAG = "RotateSecondaryKeyTask";
+
+    private final Context mContext;
+    private final RecoverableKeyStoreSecondaryKeyManager mSecondaryKeyManager;
+    private final CryptoBackupServer mBackupServer;
+    private final CryptoSettings mCryptoSettings;
+    private final RecoveryController mRecoveryController;
+
+    /**
+     * A new instance.
+     *
+     * @param secondaryKeyManager For loading the currently active and next secondary key.
+     * @param backupServer For loading and storing tertiary keys and for setting active secondary
+     *     key.
+     * @param cryptoSettings For checking the stored aliases for the next and active key.
+     * @param recoveryController For communicating with the Framework apis.
+     */
+    public RotateSecondaryKeyTask(
+            Context context,
+            RecoverableKeyStoreSecondaryKeyManager secondaryKeyManager,
+            CryptoBackupServer backupServer,
+            CryptoSettings cryptoSettings,
+            RecoveryController recoveryController) {
+        mContext = context;
+        mSecondaryKeyManager = checkNotNull(secondaryKeyManager);
+        mCryptoSettings = checkNotNull(cryptoSettings);
+        mBackupServer = checkNotNull(backupServer);
+        mRecoveryController = checkNotNull(recoveryController);
+    }
+
+    /** Runs the task. */
+    public void run() {
+        // Never run more than one of these at the same time.
+        synchronized (RotateSecondaryKeyTask.class) {
+            runInternal();
+        }
+    }
+
+    private void runInternal() {
+        Optional<RecoverableKeyStoreSecondaryKey> maybeNextKey;
+        try {
+            maybeNextKey = getNextKey();
+        } catch (Exception e) {
+            Slog.e(TAG, "Error checking for next key", e);
+            return;
+        }
+
+        if (!maybeNextKey.isPresent()) {
+            Slog.d(TAG, "No secondary key rotation task pending. Exiting.");
+            return;
+        }
+
+        RecoverableKeyStoreSecondaryKey nextKey = maybeNextKey.get();
+        boolean isReady;
+        try {
+            isReady = isSecondaryKeyRotationReady(nextKey);
+        } catch (InternalRecoveryServiceException e) {
+            Slog.e(TAG, "Error encountered checking whether next secondary key is synced", e);
+            return;
+        }
+
+        if (!isReady) {
+            return;
+        }
+
+        try {
+            rotateToKey(nextKey);
+        } catch (Exception e) {
+            Slog.e(TAG, "Error trying to rotate to new secondary key", e);
+        }
+    }
+
+    private Optional<RecoverableKeyStoreSecondaryKey> getNextKey()
+            throws InternalRecoveryServiceException, UnrecoverableKeyException {
+        Optional<String> maybeNextAlias = mCryptoSettings.getNextSecondaryKeyAlias();
+        if (!maybeNextAlias.isPresent()) {
+            return Optional.empty();
+        }
+        return mSecondaryKeyManager.get(maybeNextAlias.get());
+    }
+
+    private boolean isSecondaryKeyRotationReady(RecoverableKeyStoreSecondaryKey nextKey)
+            throws InternalRecoveryServiceException {
+        String nextAlias = nextKey.getAlias();
+        Slog.i(TAG, "Key rotation to " + nextAlias + " is pending. Checking key sync status.");
+        int status = mRecoveryController.getRecoveryStatus(nextAlias);
+
+        if (status == RecoveryController.RECOVERY_STATUS_PERMANENT_FAILURE) {
+            Slog.e(
+                    TAG,
+                    "Permanent failure to sync " + nextAlias + ". Cannot possibly rotate to it.");
+            mCryptoSettings.removeNextSecondaryKeyAlias();
+            return false;
+        }
+
+        if (status == RecoveryController.RECOVERY_STATUS_SYNCED) {
+            Slog.i(TAG, "Secondary key " + nextAlias + " has now synced! Commencing rotation.");
+        } else {
+            Slog.i(TAG, "Sync still pending for " + nextAlias);
+        }
+        return status == RecoveryController.RECOVERY_STATUS_SYNCED;
+    }
+
+    /**
+     * @throws ActiveSecondaryNotInKeychainException if the currently active secondary key is not in
+     *     the keychain.
+     * @throws IOException if there is an IO issue communicating with the server or loading from
+     *     disk.
+     * @throws NoActiveSecondaryKeyException if there is no active key set.
+     * @throws IllegalBlockSizeException if there is an issue decrypting a tertiary key.
+     * @throws InvalidKeyException if any of the secondary keys cannot be used for wrapping or
+     *     unwrapping tertiary keys.
+     */
+    private void rotateToKey(RecoverableKeyStoreSecondaryKey newSecondaryKey)
+            throws ActiveSecondaryNotInKeychainException, IOException,
+                    NoActiveSecondaryKeyException, IllegalBlockSizeException, InvalidKeyException,
+                    InternalRecoveryServiceException, UnrecoverableKeyException,
+                    InvalidAlgorithmParameterException, NoSuchAlgorithmException,
+                    NoSuchPaddingException {
+        RecoverableKeyStoreSecondaryKey activeSecondaryKey = getActiveSecondaryKey();
+        String activeSecondaryKeyAlias = activeSecondaryKey.getAlias();
+        String newSecondaryKeyAlias = newSecondaryKey.getAlias();
+        if (newSecondaryKeyAlias.equals(activeSecondaryKeyAlias)) {
+            Slog.i(TAG, activeSecondaryKeyAlias + " was already the active alias.");
+            return;
+        }
+
+        TertiaryKeyStore tertiaryKeyStore =
+                TertiaryKeyStore.newInstance(mContext, activeSecondaryKey);
+        Map<String, SecretKey> tertiaryKeys = tertiaryKeyStore.getAll();
+
+        if (tertiaryKeys.isEmpty()) {
+            Slog.i(
+                    TAG,
+                    "No tertiary keys for " + activeSecondaryKeyAlias + ". No need to rewrap. ");
+            mBackupServer.setActiveSecondaryKeyAlias(
+                    newSecondaryKeyAlias, /*tertiaryKeys=*/ Collections.emptyMap());
+        } else {
+            Map<String, WrappedKeyProto.WrappedKey> rewrappedTertiaryKeys =
+                    rewrapAll(newSecondaryKey, tertiaryKeys);
+            TertiaryKeyStore.newInstance(mContext, newSecondaryKey).putAll(rewrappedTertiaryKeys);
+            Slog.i(
+                    TAG,
+                    "Successfully rewrapped " + rewrappedTertiaryKeys.size() + " tertiary keys");
+            mBackupServer.setActiveSecondaryKeyAlias(newSecondaryKeyAlias, rewrappedTertiaryKeys);
+            Slog.i(
+                    TAG,
+                    "Successfully uploaded new set of tertiary keys to "
+                            + newSecondaryKeyAlias
+                            + " alias");
+        }
+
+        mCryptoSettings.setActiveSecondaryKeyAlias(newSecondaryKeyAlias);
+        mCryptoSettings.removeNextSecondaryKeyAlias();
+        try {
+            mRecoveryController.removeKey(activeSecondaryKeyAlias);
+        } catch (InternalRecoveryServiceException e) {
+            Slog.e(TAG, "Error removing old secondary key from RecoverableKeyStoreLoader", e);
+        }
+    }
+
+    private RecoverableKeyStoreSecondaryKey getActiveSecondaryKey()
+            throws NoActiveSecondaryKeyException, ActiveSecondaryNotInKeychainException,
+                    InternalRecoveryServiceException, UnrecoverableKeyException {
+
+        Optional<String> activeSecondaryAlias = mCryptoSettings.getActiveSecondaryKeyAlias();
+
+        if (!activeSecondaryAlias.isPresent()) {
+            Slog.i(
+                    TAG,
+                    "Was asked to rotate secondary key, but local config did not have a secondary "
+                            + "key alias set.");
+            throw new NoActiveSecondaryKeyException("No local active secondary key set.");
+        }
+
+        String activeSecondaryKeyAlias = activeSecondaryAlias.get();
+        Optional<RecoverableKeyStoreSecondaryKey> secondaryKey =
+                mSecondaryKeyManager.get(activeSecondaryKeyAlias);
+
+        if (!secondaryKey.isPresent()) {
+            throw new ActiveSecondaryNotInKeychainException(
+                    String.format(
+                            Locale.US,
+                            "Had local active recoverable key alias of %s but key was not in"
+                                + " user's keychain.",
+                            activeSecondaryKeyAlias));
+        }
+
+        return secondaryKey.get();
+    }
+
+    /**
+     * Rewraps all the tertiary keys.
+     *
+     * @param newSecondaryKey The secondary key with which to rewrap the tertiaries.
+     * @param tertiaryKeys The tertiary keys, by package name.
+     * @return The newly wrapped tertiary keys, by package name.
+     * @throws InvalidKeyException if any key is unusable.
+     * @throws IllegalBlockSizeException if could not decrypt.
+     */
+    private Map<String, WrappedKeyProto.WrappedKey> rewrapAll(
+            RecoverableKeyStoreSecondaryKey newSecondaryKey, Map<String, SecretKey> tertiaryKeys)
+            throws InvalidKeyException, IllegalBlockSizeException, NoSuchPaddingException,
+                    NoSuchAlgorithmException {
+        Map<String, WrappedKeyProto.WrappedKey> wrappedKeys = new HashMap<>();
+
+        for (String packageName : tertiaryKeys.keySet()) {
+            SecretKey tertiaryKey = tertiaryKeys.get(packageName);
+            wrappedKeys.put(
+                    packageName, KeyWrapUtils.wrap(newSecondaryKey.getSecretKey(), tertiaryKey));
+        }
+
+        return wrappedKeys;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/SizeQuotaExceededException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/SizeQuotaExceededException.java
new file mode 100644
index 0000000..515db86
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/SizeQuotaExceededException.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+/** Exception thrown when aa backup has exceeded the space allowed for that user */
+public class SizeQuotaExceededException extends RuntimeException {
+    public SizeQuotaExceededException() {
+        super("Backup size quota exceeded.");
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/UnsupportedEncryptedFileException.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/UnsupportedEncryptedFileException.java
new file mode 100644
index 0000000..9a97e38
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/tasks/UnsupportedEncryptedFileException.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+/**
+ * Thrown when the backup file provided by the server uses encryption algorithms this version of
+ * backup does not support. This could happen if the backup was created with a newer version of the
+ * code.
+ */
+public class UnsupportedEncryptedFileException extends EncryptedRestoreException {
+    public UnsupportedEncryptedFileException(String message) {
+        super(message);
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransport.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransport.java
new file mode 100644
index 0000000..1d0224d
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransport.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.transport;
+
+import static com.android.server.backup.encryption.BackupEncryptionService.TAG;
+
+import android.os.RemoteException;
+import android.util.Log;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.transport.DelegatingTransport;
+import com.android.server.backup.transport.TransportClient;
+
+/**
+ * This is an implementation of {@link IBackupTransport} that encrypts (or decrypts) the data when
+ * sending it (or receiving it) from the {@link IBackupTransport} returned by {@link
+ * TransportClient.connect(String)}.
+ */
+public class IntermediateEncryptingTransport extends DelegatingTransport {
+    private final TransportClient mTransportClient;
+    private final Object mConnectLock = new Object();
+    private volatile IBackupTransport mRealTransport;
+
+    @VisibleForTesting
+    IntermediateEncryptingTransport(TransportClient transportClient) {
+        mTransportClient = transportClient;
+    }
+
+    @Override
+    protected IBackupTransport getDelegate() throws RemoteException {
+        if (mRealTransport == null) {
+            connect();
+        }
+        return mRealTransport;
+    }
+
+    private void connect() throws RemoteException {
+        Log.i(TAG, "connecting " + mTransportClient);
+        synchronized (mConnectLock) {
+            if (mRealTransport == null) {
+                mRealTransport = mTransportClient.connect("IntermediateEncryptingTransport");
+                if (mRealTransport == null) {
+                    throw new RemoteException("Could not connect: " + mTransportClient);
+                }
+            }
+        }
+    }
+
+    @VisibleForTesting
+    TransportClient getClient() {
+        return mTransportClient;
+    }
+}
diff --git a/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManager.java b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManager.java
new file mode 100644
index 0000000..6e6d571
--- /dev/null
+++ b/packages/BackupEncryption/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManager.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.transport;
+
+import static com.android.server.backup.encryption.BackupEncryptionService.TAG;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.os.UserHandle;
+import android.util.Log;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.transport.TransportClientManager;
+import com.android.server.backup.transport.TransportStats;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Handles creation and cleanup of {@link IntermediateEncryptingTransport} instances.
+ */
+public class IntermediateEncryptingTransportManager {
+    private static final String CALLER = "IntermediateEncryptingTransportManager";
+    private final TransportClientManager mTransportClientManager;
+    private final Object mTransportsLock = new Object();
+    private final Map<ComponentName, IntermediateEncryptingTransport> mTransports = new HashMap<>();
+
+    @VisibleForTesting
+    IntermediateEncryptingTransportManager(TransportClientManager transportClientManager) {
+        mTransportClientManager = transportClientManager;
+    }
+
+    public IntermediateEncryptingTransportManager(Context context) {
+        this(new TransportClientManager(UserHandle.myUserId(), context, new TransportStats()));
+    }
+
+    /**
+     * Extract the {@link ComponentName} corresponding to the real {@link IBackupTransport}, and
+     * provide a {@link IntermediateEncryptingTransport} which is an implementation of {@link
+     * IBackupTransport} that encrypts (or decrypts) the data when sending it (or receiving it) from
+     * the real {@link IBackupTransport}.
+     * @param intent {@link Intent} created with a call to {@link
+     * TransportClientManager.getEncryptingTransportIntent(ComponentName)}.
+     * @return
+     */
+    public IntermediateEncryptingTransport get(Intent intent) {
+        Intent transportIntent = TransportClientManager.getRealTransportIntent(intent);
+        Log.i(TAG, "get: intent:" + intent + " transportIntent:" + transportIntent);
+        synchronized (mTransportsLock) {
+            return mTransports.computeIfAbsent(transportIntent.getComponent(),
+                    c -> create(transportIntent));
+        }
+    }
+
+    /**
+     * Create an instance of {@link IntermediateEncryptingTransport}.
+     */
+    private IntermediateEncryptingTransport create(Intent realTransportIntent) {
+        Log.d(TAG, "create: intent:" + realTransportIntent);
+        return new IntermediateEncryptingTransport(mTransportClientManager.getTransportClient(
+                realTransportIntent.getComponent(), realTransportIntent.getExtras(), CALLER));
+    }
+
+    /**
+     * Cleanup the {@link IntermediateEncryptingTransport} which was created by a call to
+     * {@link #get(Intent)} with this {@link Intent}.
+     */
+    public void cleanup(Intent intent) {
+        Intent transportIntent = TransportClientManager.getRealTransportIntent(intent);
+        Log.i(TAG, "cleanup: intent:" + intent + " transportIntent:" + transportIntent);
+
+        IntermediateEncryptingTransport transport;
+        synchronized (mTransportsLock) {
+            transport = mTransports.remove(transportIntent.getComponent());
+        }
+        if (transport != null) {
+            mTransportClientManager.disposeOfTransportClient(transport.getClient(), CALLER);
+        } else {
+            Log.i(TAG, "Could not find IntermediateEncryptingTransport");
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric-integration/Android.bp b/packages/BackupEncryption/test/robolectric-integration/Android.bp
new file mode 100644
index 0000000..67365df
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric-integration/Android.bp
@@ -0,0 +1,34 @@
+// Copyright (C) 2019 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.
+
+android_robolectric_test {
+    name: "BackupEncryptionRoboIntegTests",
+    srcs: [
+        "src/**/*.java",
+    ],
+    java_resource_dirs: ["config"],
+    libs: [
+        "backup-encryption-protos",
+        "platform-test-annotations",
+        "testng",
+        "truth-prebuilt",
+        "BackupEncryptionRoboTests",
+    ],
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.runner",
+        "androidx.test.rules",
+    ],
+    instrumentation_for: "BackupEncryption",
+}
diff --git a/packages/BackupEncryption/test/robolectric-integration/AndroidManifest.xml b/packages/BackupEncryption/test/robolectric-integration/AndroidManifest.xml
new file mode 100644
index 0000000..c3930cc
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric-integration/AndroidManifest.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          coreApp="true"
+          package="com.android.server.backup.encryption.robointeg">
+
+    <application/>
+
+</manifest>
diff --git a/packages/BackupEncryption/test/robolectric-integration/config/robolectric.properties b/packages/BackupEncryption/test/robolectric-integration/config/robolectric.properties
new file mode 100644
index 0000000..26fceb3
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric-integration/config/robolectric.properties
@@ -0,0 +1,17 @@
+#
+# Copyright (C) 2019 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.
+#
+
+sdk=NEWEST_SDK
diff --git a/packages/BackupEncryption/test/robolectric-integration/src/com/android/server/backup/encryption/RoundTripTest.java b/packages/BackupEncryption/test/robolectric-integration/src/com/android/server/backup/encryption/RoundTripTest.java
new file mode 100644
index 0000000..a432d91
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric-integration/src/com/android/server/backup/encryption/RoundTripTest.java
@@ -0,0 +1,321 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Context;
+import android.os.ParcelFileDescriptor;
+import android.security.keystore.recovery.InternalRecoveryServiceException;
+import android.security.keystore.recovery.RecoveryController;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.KeyWrapUtils;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKeyManager;
+import com.android.server.backup.encryption.keys.TertiaryKeyManager;
+import com.android.server.backup.encryption.keys.TertiaryKeyRotationScheduler;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+import com.android.server.backup.encryption.tasks.EncryptedFullBackupTask;
+import com.android.server.backup.encryption.tasks.EncryptedFullRestoreTask;
+import com.android.server.backup.encryption.tasks.EncryptedKvBackupTask;
+import com.android.server.backup.encryption.tasks.EncryptedKvRestoreTask;
+import com.android.server.testing.shadows.DataEntity;
+import com.android.server.testing.shadows.ShadowBackupDataInput;
+import com.android.server.testing.shadows.ShadowBackupDataOutput;
+import com.android.server.testing.shadows.ShadowRecoveryController;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Optional;
+import java.util.Map;
+import java.util.Set;
+
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.KeyGenerator;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+
+@Config(
+        shadows = {
+            ShadowBackupDataInput.class,
+            ShadowBackupDataOutput.class,
+            ShadowRecoveryController.class
+        })
+@RunWith(RobolectricTestRunner.class)
+public class RoundTripTest {
+    private static final DataEntity[] KEY_VALUE_DATA = {
+        new DataEntity("test_key_1", "test_value_1"),
+        new DataEntity("test_key_2", "test_value_2"),
+        new DataEntity("test_key_3", "test_value_3")
+    };
+
+    /** Amount of data we want to round trip in this test */
+    private static final int TEST_DATA_SIZE = 1024 * 1024; // 1MB
+
+    /** Buffer size used when reading data from the restore task */
+    private static final int READ_BUFFER_SIZE = 1024; // 1024 byte buffer.
+
+    /** Key parameters used for the secondary encryption key */
+    private static final String KEY_ALGORITHM = "AES";
+
+    private static final int KEY_SIZE_BITS = 256;
+
+    /** Package name for our test package */
+    private static final String TEST_PACKAGE_NAME = "com.android.backup.test";
+
+    /** The name we use to refer to our secondary key */
+    private static final String TEST_KEY_ALIAS = "test/backup/KEY_ALIAS";
+
+    /** Original data used for comparison after round trip */
+    private final byte[] mOriginalData = new byte[TEST_DATA_SIZE];
+
+    /** App context, used to store the key data and chunk listings */
+    private Context mContext;
+
+    /** The secondary key we're using for the test */
+    private RecoverableKeyStoreSecondaryKey mSecondaryKey;
+
+    /** Source of random material which is considered non-predictable in its' generation */
+    private final SecureRandom mSecureRandom = new SecureRandom();
+
+    private RecoverableKeyStoreSecondaryKeyManager.RecoverableKeyStoreSecondaryKeyManagerProvider
+            mSecondaryKeyManagerProvider;
+    private DummyServer mDummyServer;
+    private RecoveryController mRecoveryController;
+
+    @Mock private ParcelFileDescriptor mParcelFileDescriptor;
+
+    @Before
+    public void setUp() throws NoSuchAlgorithmException, InternalRecoveryServiceException {
+        MockitoAnnotations.initMocks(this);
+
+        ShadowBackupDataInput.reset();
+        ShadowBackupDataOutput.reset();
+
+        mContext = ApplicationProvider.getApplicationContext();
+        mSecondaryKey = new RecoverableKeyStoreSecondaryKey(TEST_KEY_ALIAS, generateAesKey());
+        mDummyServer = new DummyServer();
+        mSecondaryKeyManagerProvider =
+                () ->
+                        new RecoverableKeyStoreSecondaryKeyManager(
+                                RecoveryController.getInstance(mContext), mSecureRandom);
+
+        fillBuffer(mOriginalData);
+    }
+
+    @Test
+    public void testFull_nonIncrementalBackupAndRestoreAreSuccessful() throws Exception {
+        byte[] backupData = performFullBackup(mOriginalData);
+        assertThat(backupData).isNotEqualTo(mOriginalData);
+        byte[] restoredData = performFullRestore(backupData);
+        assertThat(restoredData).isEqualTo(mOriginalData);
+    }
+
+    @Test
+    public void testKeyValue_nonIncrementalBackupAndRestoreAreSuccessful() throws Exception {
+        byte[] backupData = performNonIncrementalKeyValueBackup(KEY_VALUE_DATA);
+
+        // Get the secondary key used to do backup.
+        Optional<RecoverableKeyStoreSecondaryKey> secondaryKey =
+                mSecondaryKeyManagerProvider.get().get(mDummyServer.mSecondaryKeyAlias);
+        assertThat(secondaryKey.isPresent()).isTrue();
+
+        Set<DataEntity> restoredData = performKeyValueRestore(backupData, secondaryKey.get());
+
+        assertThat(restoredData).containsExactly(KEY_VALUE_DATA).inOrder();
+    }
+
+    /** Perform a key/value backup and return the backed-up representation of the data */
+    private byte[] performNonIncrementalKeyValueBackup(DataEntity[] backupData)
+            throws Exception {
+        // Populate test key/value data.
+        for (DataEntity entity : backupData) {
+            ShadowBackupDataInput.addEntity(entity);
+        }
+
+        EncryptedKvBackupTask.EncryptedKvBackupTaskFactory backupTaskFactory =
+                new EncryptedKvBackupTask.EncryptedKvBackupTaskFactory();
+        EncryptedKvBackupTask backupTask =
+                backupTaskFactory.newInstance(
+                        mContext,
+                        mSecureRandom,
+                        mDummyServer,
+                        CryptoSettings.getInstance(mContext),
+                        mSecondaryKeyManagerProvider,
+                        mParcelFileDescriptor,
+                        TEST_PACKAGE_NAME);
+
+        backupTask.performBackup(/* incremental */ false);
+
+        return mDummyServer.mStoredData;
+    }
+
+    /** Perform a full backup and return the backed-up representation of the data */
+    private byte[] performFullBackup(byte[] backupData) throws Exception {
+        DummyServer dummyServer = new DummyServer();
+        EncryptedFullBackupTask backupTask =
+                EncryptedFullBackupTask.newInstance(
+                        mContext,
+                        dummyServer,
+                        mSecureRandom,
+                        mSecondaryKey,
+                        TEST_PACKAGE_NAME,
+                        new ByteArrayInputStream(backupData));
+        backupTask.call();
+        return dummyServer.mStoredData;
+    }
+
+    private Set<DataEntity> performKeyValueRestore(
+            byte[] backupData, RecoverableKeyStoreSecondaryKey secondaryKey) throws Exception {
+        EncryptedKvRestoreTask.EncryptedKvRestoreTaskFactory restoreTaskFactory =
+                new EncryptedKvRestoreTask.EncryptedKvRestoreTaskFactory();
+        EncryptedKvRestoreTask restoreTask =
+                restoreTaskFactory.newInstance(
+                        mContext,
+                        mSecondaryKeyManagerProvider,
+                        new FakeFullRestoreDownloader(backupData),
+                        secondaryKey.getAlias(),
+                        KeyWrapUtils.wrap(
+                                secondaryKey.getSecretKey(), getTertiaryKey(secondaryKey)));
+        restoreTask.getRestoreData(mParcelFileDescriptor);
+        return ShadowBackupDataOutput.getEntities();
+    }
+
+    /** Perform a full restore and return the bytes obtained from the restore process */
+    private byte[] performFullRestore(byte[] backupData)
+            throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
+                    InvalidAlgorithmParameterException, InvalidKeyException,
+                    IllegalBlockSizeException {
+        ByteArrayOutputStream decryptedOutput = new ByteArrayOutputStream();
+
+        EncryptedFullRestoreTask restoreTask =
+                EncryptedFullRestoreTask.newInstance(
+                        mContext,
+                        new FakeFullRestoreDownloader(backupData),
+                        getTertiaryKey(mSecondaryKey));
+
+        byte[] buffer = new byte[READ_BUFFER_SIZE];
+        int bytesRead = restoreTask.readNextChunk(buffer);
+        while (bytesRead != -1) {
+            decryptedOutput.write(buffer, 0, bytesRead);
+            bytesRead = restoreTask.readNextChunk(buffer);
+        }
+
+        return decryptedOutput.toByteArray();
+    }
+
+    /** Get the tertiary key for our test package from the key manager */
+    private SecretKey getTertiaryKey(RecoverableKeyStoreSecondaryKey secondaryKey)
+            throws IllegalBlockSizeException, InvalidAlgorithmParameterException,
+                    NoSuchAlgorithmException, IOException, NoSuchPaddingException,
+                    InvalidKeyException {
+        TertiaryKeyManager tertiaryKeyManager =
+                new TertiaryKeyManager(
+                        mContext,
+                        mSecureRandom,
+                        TertiaryKeyRotationScheduler.getInstance(mContext),
+                        secondaryKey,
+                        TEST_PACKAGE_NAME);
+        return tertiaryKeyManager.getKey();
+    }
+
+    /** Fill a buffer with data in a predictable way */
+    private void fillBuffer(byte[] buffer) {
+        byte loopingCounter = 0;
+        for (int i = 0; i < buffer.length; i++) {
+            buffer[i] = loopingCounter;
+            loopingCounter++;
+        }
+    }
+
+    /** Generate a new, random, AES key */
+    public static SecretKey generateAesKey() throws NoSuchAlgorithmException {
+        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
+        keyGenerator.init(KEY_SIZE_BITS);
+        return keyGenerator.generateKey();
+    }
+
+    /**
+     * Dummy backup data endpoint. This stores the data so we can use it in subsequent test steps.
+     */
+    private static class DummyServer implements CryptoBackupServer {
+        private static final String DUMMY_DOC_ID = "DummyDoc";
+
+        byte[] mStoredData = null;
+        String mSecondaryKeyAlias;
+
+        @Override
+        public String uploadIncrementalBackup(
+                String packageName,
+                String oldDocId,
+                byte[] diffScript,
+                WrappedKeyProto.WrappedKey tertiaryKey) {
+            throw new RuntimeException("Not Implemented");
+        }
+
+        @Override
+        public String uploadNonIncrementalBackup(
+                String packageName, byte[] data, WrappedKeyProto.WrappedKey tertiaryKey) {
+            assertThat(packageName).isEqualTo(TEST_PACKAGE_NAME);
+            mStoredData = data;
+            return DUMMY_DOC_ID;
+        }
+
+        @Override
+        public void setActiveSecondaryKeyAlias(
+                String keyAlias, Map<String, WrappedKeyProto.WrappedKey> tertiaryKeys) {
+            mSecondaryKeyAlias = keyAlias;
+        }
+    }
+
+    /** Fake package wrapper which returns data from a byte array. */
+    private static class FakeFullRestoreDownloader extends FullRestoreDownloader {
+        private final ByteArrayInputStream mData;
+
+        FakeFullRestoreDownloader(byte[] data) {
+            // We override all methods of the superclass, so it does not require any collaborators.
+            super();
+            mData = new ByteArrayInputStream(data);
+        }
+
+        @Override
+        public int readNextChunk(byte[] buffer) throws IOException {
+            return mData.read(buffer);
+        }
+
+        @Override
+        public void finish(FinishType finishType) {
+            // Do nothing.
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/Android.bp b/packages/BackupEncryption/test/robolectric/Android.bp
index 4e42ce7..2a36dcf 100644
--- a/packages/BackupEncryption/test/robolectric/Android.bp
+++ b/packages/BackupEncryption/test/robolectric/Android.bp
@@ -16,7 +16,7 @@
     name: "BackupEncryptionRoboTests",
     srcs: [
         "src/**/*.java",
-        ":FrameworksServicesRoboShadows",
+//        ":FrameworksServicesRoboShadows",
     ],
     java_resource_dirs: ["config"],
     libs: [
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/StreamUtilsTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/StreamUtilsTest.java
new file mode 100644
index 0000000..a95e87e
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/StreamUtilsTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+@RunWith(RobolectricTestRunner.class)
+public class StreamUtilsTest {
+    private static final int SOURCE_DATA_SIZE = 64;
+
+    private byte[] mSourceData;
+
+    private InputStream mSource;
+    private ByteArrayOutputStream mDestination;
+
+    @Before
+    public void setUp() {
+        mSourceData = new byte[SOURCE_DATA_SIZE];
+        for (byte i = 0; i < SOURCE_DATA_SIZE; i++) {
+            mSourceData[i] = i;
+        }
+        mSource = new ByteArrayInputStream(mSourceData);
+        mDestination = new ByteArrayOutputStream();
+    }
+
+    @Test
+    public void copyStream_copiesAllBytesIfAsked() throws IOException {
+        StreamUtils.copyStream(mSource, mDestination, mSourceData.length);
+        assertOutputHasBytes(mSourceData.length);
+    }
+
+    @Test
+    public void copyStream_stopsShortIfAsked() throws IOException {
+        StreamUtils.copyStream(mSource, mDestination, mSourceData.length - 10);
+        assertOutputHasBytes(mSourceData.length - 10);
+    }
+
+    @Test
+    public void copyStream_stopsShortIfAskedToCopyMoreThanAvailable() throws IOException {
+        StreamUtils.copyStream(mSource, mDestination, mSourceData.length + 10);
+        assertOutputHasBytes(mSourceData.length);
+    }
+
+    private void assertOutputHasBytes(int count) {
+        byte[] output = mDestination.toByteArray();
+        assertThat(output.length).isEqualTo(count);
+        for (int i = 0; i < count; i++) {
+            assertThat(output[i]).isEqualTo(mSourceData[i]);
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/BackupFileBuilderTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/BackupFileBuilderTest.java
new file mode 100644
index 0000000..590938e
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/BackupFileBuilderTest.java
@@ -0,0 +1,614 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.chunking;
+
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.AES_256_GCM;
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+import static com.android.server.backup.testing.CryptoTestUtils.newChunk;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static junit.framework.Assert.fail;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.testng.Assert.assertThrows;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.testing.DiffScriptProcessor;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.io.Files;
+import com.google.common.primitives.Bytes;
+import com.google.common.primitives.Longs;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class BackupFileBuilderTest {
+    private static final String TEST_DATA_1 =
+            "I'm already there or close to [T7-9/executive level] in terms of big-picture vision";
+    private static final String TEST_DATA_2 =
+            "I was known for Real Games and should have been brought in for advice";
+    private static final String TEST_DATA_3 =
+            "Pride is rooted in the delusional belief held by all humans in an unchanging self";
+
+    private static final byte[] TEST_FINGERPRINT_MIXER_SALT =
+            Arrays.copyOf(new byte[] {22}, ChunkHash.HASH_LENGTH_BYTES);
+
+    private static final ChunkHash TEST_HASH_1 =
+            new ChunkHash(Arrays.copyOf(new byte[] {0}, EncryptedChunk.KEY_LENGTH_BYTES));
+    private static final ChunkHash TEST_HASH_2 =
+            new ChunkHash(Arrays.copyOf(new byte[] {1}, EncryptedChunk.KEY_LENGTH_BYTES));
+    private static final ChunkHash TEST_HASH_3 =
+            new ChunkHash(Arrays.copyOf(new byte[] {2}, EncryptedChunk.KEY_LENGTH_BYTES));
+
+    private static final byte[] TEST_NONCE =
+            Arrays.copyOf(new byte[] {3}, EncryptedChunk.NONCE_LENGTH_BYTES);
+
+    private static final EncryptedChunk TEST_CHUNK_1 =
+            EncryptedChunk.create(TEST_HASH_1, TEST_NONCE, TEST_DATA_1.getBytes(UTF_8));
+    private static final EncryptedChunk TEST_CHUNK_2 =
+            EncryptedChunk.create(TEST_HASH_2, TEST_NONCE, TEST_DATA_2.getBytes(UTF_8));
+    private static final EncryptedChunk TEST_CHUNK_3 =
+            EncryptedChunk.create(TEST_HASH_3, TEST_NONCE, TEST_DATA_3.getBytes(UTF_8));
+
+    private static final byte[] TEST_CHECKSUM = {1, 2, 3, 4, 5, 6};
+
+    @Rule public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
+
+    private File mOldFile;
+    private ChunksMetadataProto.ChunkListing mOldChunkListing;
+    private EncryptedChunkEncoder mEncryptedChunkEncoder;
+
+    @Before
+    public void setUp() {
+        mEncryptedChunkEncoder = new LengthlessEncryptedChunkEncoder();
+    }
+
+    @Test
+    public void writeChunks_nonIncremental_writesCorrectRawData() throws Exception {
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        BackupFileBuilder backupFileBuilder = BackupFileBuilder.createForNonIncremental(output);
+
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+                getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+
+        byte[] actual = output.toByteArray();
+        byte[] expected =
+                Bytes.concat(
+                        TEST_CHUNK_1.nonce(),
+                        TEST_CHUNK_1.encryptedBytes(),
+                        TEST_CHUNK_2.nonce(),
+                        TEST_CHUNK_2.encryptedBytes());
+        assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+    }
+
+    @Test
+    public void writeChunks_nonIncrementalWithDuplicates_writesEachChunkOnlyOnce()
+            throws Exception {
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        BackupFileBuilder backupFileBuilder = BackupFileBuilder.createForNonIncremental(output);
+
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_1),
+                getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+
+        byte[] actual = output.toByteArray();
+        byte[] expected =
+                Bytes.concat(
+                        TEST_CHUNK_1.nonce(),
+                        TEST_CHUNK_1.encryptedBytes(),
+                        TEST_CHUNK_2.nonce(),
+                        TEST_CHUNK_2.encryptedBytes());
+        assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+    }
+
+    @Test
+    public void writeChunks_incremental_writesParsableDiffScript() throws Exception {
+        // We will insert chunk 2 in between chunks 1 and 3.
+        setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+        ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(diffOutputStream, mOldChunkListing);
+
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+                getNewChunkMap(TEST_HASH_2));
+        backupFileBuilder.finish(getTestMetadata());
+
+        byte[] actual =
+                stripMetadataAndPositionFromOutput(parseDiffScript(diffOutputStream.toByteArray()));
+        byte[] expected =
+                Bytes.concat(
+                        TEST_CHUNK_1.nonce(),
+                        TEST_CHUNK_1.encryptedBytes(),
+                        TEST_CHUNK_2.nonce(),
+                        TEST_CHUNK_2.encryptedBytes(),
+                        TEST_CHUNK_3.nonce(),
+                        TEST_CHUNK_3.encryptedBytes());
+        assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+    }
+
+    @Test
+    public void writeChunks_incrementalWithDuplicates_writesEachChunkOnlyOnce() throws Exception {
+        // We will insert chunk 2 twice in between chunks 1 and 3.
+        setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+        ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(diffOutputStream, mOldChunkListing);
+
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_2, TEST_HASH_3),
+                getNewChunkMap(TEST_HASH_2));
+        backupFileBuilder.finish(getTestMetadata());
+
+        byte[] actual =
+                stripMetadataAndPositionFromOutput(parseDiffScript(diffOutputStream.toByteArray()));
+        byte[] expected =
+                Bytes.concat(
+                        TEST_CHUNK_1.nonce(),
+                        TEST_CHUNK_1.encryptedBytes(),
+                        TEST_CHUNK_2.nonce(),
+                        TEST_CHUNK_2.encryptedBytes(),
+                        TEST_CHUNK_3.nonce(),
+                        TEST_CHUNK_3.encryptedBytes());
+        assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+    }
+
+    @Test
+    public void writeChunks_writesChunksInOrderOfHash() throws Exception {
+        setUpOldBackupWithChunks(ImmutableList.of());
+        ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(diffOutputStream, mOldChunkListing);
+
+        // Write chunks out of order.
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_2, TEST_HASH_1),
+                getNewChunkMap(TEST_HASH_2, TEST_HASH_1));
+        backupFileBuilder.finish(getTestMetadata());
+
+        byte[] actual =
+                stripMetadataAndPositionFromOutput(parseDiffScript(diffOutputStream.toByteArray()));
+        byte[] expected =
+                Bytes.concat(
+                        TEST_CHUNK_1.nonce(),
+                        TEST_CHUNK_1.encryptedBytes(),
+                        TEST_CHUNK_2.nonce(),
+                        TEST_CHUNK_2.encryptedBytes());
+        assertThat(actual).asList().containsExactlyElementsIn(Bytes.asList(expected)).inOrder();
+    }
+
+    @Test
+    public void writeChunks_alreadyFlushed_throwsException() throws Exception {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+        backupFileBuilder.finish(getTestMetadata());
+
+        assertThrows(
+                IllegalStateException.class,
+                () -> backupFileBuilder.writeChunks(ImmutableList.of(), getNewChunkMap()));
+    }
+
+    @Test
+    public void getNewChunkListing_hasChunksInOrderOfKey() throws Exception {
+        // We will insert chunk 2 in between chunks 1 and 3.
+        setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), mOldChunkListing);
+
+        // Write chunks out of order.
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_3, TEST_HASH_2),
+                getNewChunkMap(TEST_HASH_2));
+        backupFileBuilder.finish(getTestMetadata());
+
+        ChunksMetadataProto.ChunkListing expected = expectedChunkListing();
+        ChunksMetadataProto.ChunkListing actual =
+                backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+        assertListingsEqual(actual, expected);
+    }
+
+    @Test
+    public void getNewChunkListing_writeChunksInTwoBatches_returnsListingContainingAllChunks()
+            throws Exception {
+        // We will insert chunk 2 in between chunks 1 and 3.
+        setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_3));
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), mOldChunkListing);
+
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2), getNewChunkMap(TEST_HASH_2));
+        backupFileBuilder.writeChunks(ImmutableList.of(TEST_HASH_3), getNewChunkMap(TEST_HASH_2));
+        backupFileBuilder.finish(getTestMetadata());
+
+        ChunksMetadataProto.ChunkListing expected = expectedChunkListing();
+        ChunksMetadataProto.ChunkListing actual =
+                backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+        assertListingsEqual(actual, expected);
+    }
+
+    @Test
+    public void getNewChunkListing_writeDuplicateChunks_writesEachChunkOnlyOnce() throws Exception {
+        // We will append [2][3][3][2] onto [1].
+        setUpOldBackupWithChunks(ImmutableList.of(TEST_CHUNK_1));
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), mOldChunkListing);
+
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+                getNewChunkMap(TEST_HASH_3, TEST_HASH_2));
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_3, TEST_HASH_2),
+                getNewChunkMap(TEST_HASH_3, TEST_HASH_2));
+        backupFileBuilder.finish(getTestMetadata());
+
+        ChunksMetadataProto.ChunkListing expected = expectedChunkListing();
+        ChunksMetadataProto.ChunkListing actual =
+                backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+        assertListingsEqual(actual, expected);
+    }
+
+    @Test
+    public void getNewChunkListing_nonIncrementalWithNoSalt_doesNotThrowOnSerialisation() {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+        // Does not throw.
+        ChunksMetadataProto.ChunkListing.toByteArray(newChunkListing);
+    }
+
+    @Test
+    public void getNewChunkListing_incrementalWithNoSalt_doesNotThrowOnSerialisation()
+            throws Exception {
+
+        setUpOldBackupWithChunks(ImmutableList.of());
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), mOldChunkListing);
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+        // Does not throw.
+        ChunksMetadataProto.ChunkListing.toByteArray(newChunkListing);
+    }
+
+    @Test
+    public void getNewChunkListing_nonIncrementalWithNoSalt_hasEmptySalt() {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+        assertThat(newChunkListing.fingerprintMixerSalt).isEmpty();
+    }
+
+    @Test
+    public void getNewChunkListing_incrementalWithNoSalt_hasEmptySalt() throws Exception {
+        setUpOldBackupWithChunks(ImmutableList.of());
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), mOldChunkListing);
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+        assertThat(newChunkListing.fingerprintMixerSalt).isEmpty();
+    }
+
+    @Test
+    public void getNewChunkListing_nonIncrementalWithSalt_hasGivenSalt() {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+
+        assertThat(newChunkListing.fingerprintMixerSalt).isEqualTo(TEST_FINGERPRINT_MIXER_SALT);
+    }
+
+    @Test
+    public void getNewChunkListing_incrementalWithSalt_hasGivenSalt() throws Exception {
+        setUpOldBackupWithChunks(ImmutableList.of());
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), mOldChunkListing);
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(TEST_FINGERPRINT_MIXER_SALT);
+
+        assertThat(newChunkListing.fingerprintMixerSalt).isEqualTo(TEST_FINGERPRINT_MIXER_SALT);
+    }
+
+    @Test
+    public void getNewChunkListing_nonIncremental_hasCorrectCipherTypeAndChunkOrderingType() {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForNonIncremental(new ByteArrayOutputStream());
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+        assertThat(newChunkListing.cipherType).isEqualTo(ChunksMetadataProto.AES_256_GCM);
+        assertThat(newChunkListing.chunkOrderingType)
+                .isEqualTo(ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED);
+    }
+
+    @Test
+    public void getNewChunkListing_incremental_hasCorrectCipherTypeAndChunkOrderingType()
+            throws Exception {
+        setUpOldBackupWithChunks(ImmutableList.of());
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), mOldChunkListing);
+
+        ChunksMetadataProto.ChunkListing newChunkListing =
+                backupFileBuilder.getNewChunkListing(/*fingerprintMixerSalt=*/ null);
+
+        assertThat(newChunkListing.cipherType).isEqualTo(ChunksMetadataProto.AES_256_GCM);
+        assertThat(newChunkListing.chunkOrderingType)
+                .isEqualTo(ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED);
+    }
+
+    @Test
+    public void getNewChunkOrdering_chunksHaveCorrectStartPositions() throws Exception {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+
+        // Write out of order by key to check that ordering is maintained.
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_3, TEST_HASH_2),
+                getNewChunkMap(TEST_HASH_1, TEST_HASH_3, TEST_HASH_2));
+        backupFileBuilder.finish(getTestMetadata());
+
+        ChunksMetadataProto.ChunkOrdering actual =
+                backupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM);
+        // The chunks are listed in the order they are written above, but the start positions are
+        // determined by the order in the encrypted blob (which is lexicographical by key).
+        int chunk1Start = 0;
+        int chunk2Start =
+                chunk1Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_1);
+        int chunk3Start =
+                chunk2Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_2);
+
+        int[] expected = {chunk1Start, chunk3Start, chunk2Start};
+        assertThat(actual.starts.length).isEqualTo(expected.length);
+        for (int i = 0; i < actual.starts.length; i++) {
+            assertThat(expected[i]).isEqualTo(actual.starts[i]);
+        }
+    }
+
+    @Test
+    public void getNewChunkOrdering_duplicateChunks_writesDuplicates() throws Exception {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_2),
+                getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+        backupFileBuilder.writeChunks(
+                ImmutableList.of(TEST_HASH_3, TEST_HASH_3), getNewChunkMap(TEST_HASH_3));
+        backupFileBuilder.finish(getTestMetadata());
+
+        ChunksMetadataProto.ChunkOrdering actual =
+                backupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM);
+        int chunk1Start = 0;
+        int chunk2Start =
+                chunk1Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_1);
+        int chunk3Start =
+                chunk2Start + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_2);
+
+        int[] expected = {chunk1Start, chunk2Start, chunk2Start, chunk3Start, chunk3Start};
+        assertThat(actual.starts.length).isEqualTo(expected.length);
+        for (int i = 0; i < actual.starts.length; i++) {
+            assertThat(expected[i]).isEqualTo(actual.starts[i]);
+        }
+    }
+
+    @Test
+    public void getNewChunkOrdering_returnsOrderingWithChecksum() throws Exception {
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        new ByteArrayOutputStream(), new ChunksMetadataProto.ChunkListing());
+
+        backupFileBuilder.writeChunks(ImmutableList.of(TEST_HASH_1), getNewChunkMap(TEST_HASH_1));
+        backupFileBuilder.finish(getTestMetadata());
+
+        ChunksMetadataProto.ChunkOrdering actual =
+                backupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM);
+        assertThat(actual.checksum).isEqualTo(TEST_CHECKSUM);
+    }
+
+    @Test
+    public void finish_writesMetadata() throws Exception {
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        BackupFileBuilder builder = BackupFileBuilder.createForNonIncremental(output);
+        ChunksMetadataProto.ChunksMetadata expectedMetadata = getTestMetadata();
+
+        builder.finish(expectedMetadata);
+
+        // The output is [metadata]+[long giving size of metadata].
+        byte[] metadataBytes =
+                Arrays.copyOfRange(output.toByteArray(), 0, output.size() - Long.BYTES);
+        ChunksMetadataProto.ChunksMetadata actualMetadata =
+                ChunksMetadataProto.ChunksMetadata.parseFrom(metadataBytes);
+        assertThat(actualMetadata.checksumType).isEqualTo(ChunksMetadataProto.SHA_256);
+        assertThat(actualMetadata.cipherType).isEqualTo(ChunksMetadataProto.AES_256_GCM);
+    }
+
+    @Test
+    public void finish_writesMetadataPosition() throws Exception {
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        BackupFileBuilder builder = BackupFileBuilder.createForNonIncremental(output);
+
+        builder.writeChunks(
+                ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+                getNewChunkMap(TEST_HASH_1, TEST_HASH_2));
+        builder.writeChunks(ImmutableList.of(TEST_HASH_3), getNewChunkMap(TEST_HASH_3));
+        builder.finish(getTestMetadata());
+
+        long expectedPosition =
+                (long) mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_1)
+                        + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_2)
+                        + mEncryptedChunkEncoder.getEncodedLengthOfChunk(TEST_CHUNK_3);
+        long actualPosition =
+                Longs.fromByteArray(
+                        Arrays.copyOfRange(
+                                output.toByteArray(), output.size() - Long.BYTES, output.size()));
+        assertThat(actualPosition).isEqualTo(expectedPosition);
+    }
+
+    @Test
+    public void finish_flushesOutputStream() throws Exception {
+        OutputStream diffOutputStream = mock(OutputStream.class);
+        BackupFileBuilder backupFileBuilder =
+                BackupFileBuilder.createForIncremental(
+                        diffOutputStream, new ChunksMetadataProto.ChunkListing());
+
+        backupFileBuilder.writeChunks(ImmutableList.of(TEST_HASH_1), getNewChunkMap(TEST_HASH_1));
+        diffOutputStream.flush();
+
+        verify(diffOutputStream).flush();
+    }
+
+    private void setUpOldBackupWithChunks(List<EncryptedChunk> chunks) throws Exception {
+        mOldFile = mTemporaryFolder.newFile();
+        ChunksMetadataProto.ChunkListing chunkListing = new ChunksMetadataProto.ChunkListing();
+        chunkListing.fingerprintMixerSalt =
+                Arrays.copyOf(TEST_FINGERPRINT_MIXER_SALT, TEST_FINGERPRINT_MIXER_SALT.length);
+        chunkListing.cipherType = AES_256_GCM;
+        chunkListing.chunkOrderingType = CHUNK_ORDERING_TYPE_UNSPECIFIED;
+
+        List<ChunksMetadataProto.Chunk> knownChunks = new ArrayList<>();
+        try (FileOutputStream outputStream = new FileOutputStream(mOldFile)) {
+            for (EncryptedChunk chunk : chunks) {
+                // Chunks are encoded in the format [nonce]+[data].
+                outputStream.write(chunk.nonce());
+                outputStream.write(chunk.encryptedBytes());
+
+                knownChunks.add(createChunkFor(chunk));
+            }
+
+            outputStream.flush();
+        }
+
+        chunkListing.chunks = knownChunks.toArray(new ChunksMetadataProto.Chunk[0]);
+        mOldChunkListing = chunkListing;
+    }
+
+    private byte[] parseDiffScript(byte[] diffScript) throws Exception {
+        File newFile = mTemporaryFolder.newFile();
+        new DiffScriptProcessor(mOldFile, newFile).process(new ByteArrayInputStream(diffScript));
+        return Files.toByteArray(newFile);
+    }
+
+    private void assertListingsEqual(
+            ChunksMetadataProto.ChunkListing result, ChunksMetadataProto.ChunkListing expected) {
+        assertThat(result.chunks.length).isEqualTo(expected.chunks.length);
+        for (int i = 0; i < result.chunks.length; i++) {
+            assertWithMessage("Chunk " + i)
+                    .that(result.chunks[i].length)
+                    .isEqualTo(expected.chunks[i].length);
+            assertWithMessage("Chunk " + i)
+                    .that(result.chunks[i].hash)
+                    .isEqualTo(expected.chunks[i].hash);
+        }
+    }
+
+    private static ImmutableMap<ChunkHash, EncryptedChunk> getNewChunkMap(ChunkHash... hashes) {
+        ImmutableMap.Builder<ChunkHash, EncryptedChunk> builder = ImmutableMap.builder();
+        for (ChunkHash hash : hashes) {
+            if (TEST_HASH_1.equals(hash)) {
+                builder.put(TEST_HASH_1, TEST_CHUNK_1);
+            } else if (TEST_HASH_2.equals(hash)) {
+                builder.put(TEST_HASH_2, TEST_CHUNK_2);
+            } else if (TEST_HASH_3.equals(hash)) {
+                builder.put(TEST_HASH_3, TEST_CHUNK_3);
+            } else {
+                fail("Hash was not recognised: " + hash);
+            }
+        }
+        return builder.build();
+    }
+
+    private static ChunksMetadataProto.ChunksMetadata getTestMetadata() {
+        ChunksMetadataProto.ChunksMetadata metadata = new ChunksMetadataProto.ChunksMetadata();
+        metadata.checksumType = ChunksMetadataProto.SHA_256;
+        metadata.cipherType = AES_256_GCM;
+        return metadata;
+    }
+
+    private static byte[] stripMetadataAndPositionFromOutput(byte[] output) {
+        long metadataStart =
+                Longs.fromByteArray(
+                        Arrays.copyOfRange(output, output.length - Long.BYTES, output.length));
+        return Arrays.copyOfRange(output, 0, (int) metadataStart);
+    }
+
+    private ChunksMetadataProto.ChunkListing expectedChunkListing() {
+        ChunksMetadataProto.ChunkListing chunkListing = new ChunksMetadataProto.ChunkListing();
+        chunkListing.fingerprintMixerSalt =
+                Arrays.copyOf(TEST_FINGERPRINT_MIXER_SALT, TEST_FINGERPRINT_MIXER_SALT.length);
+        chunkListing.cipherType = AES_256_GCM;
+        chunkListing.chunkOrderingType = CHUNK_ORDERING_TYPE_UNSPECIFIED;
+        chunkListing.chunks = new ChunksMetadataProto.Chunk[3];
+        chunkListing.chunks[0] = createChunkFor(TEST_CHUNK_1);
+        chunkListing.chunks[1] = createChunkFor(TEST_CHUNK_2);
+        chunkListing.chunks[2] = createChunkFor(TEST_CHUNK_3);
+        return chunkListing;
+    }
+
+    private ChunksMetadataProto.Chunk createChunkFor(EncryptedChunk encryptedChunk) {
+        byte[] chunkHash = encryptedChunk.key().getHash();
+        byte[] hashCopy = Arrays.copyOf(chunkHash, chunkHash.length);
+        return newChunk(hashCopy, mEncryptedChunkEncoder.getEncodedLengthOfChunk(encryptedChunk));
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/ProtoStoreTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/ProtoStoreTest.java
new file mode 100644
index 0000000..d73c8e4
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/chunking/ProtoStoreTest.java
@@ -0,0 +1,264 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.chunking;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.testng.Assert.assertThrows;
+
+import android.content.Context;
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+
+import com.google.common.collect.ImmutableMap;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Optional;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class ProtoStoreTest {
+    private static final String TEST_KEY_1 = "test_key_1";
+    private static final ChunkHash TEST_HASH_1 =
+            new ChunkHash(Arrays.copyOf(new byte[] {1}, EncryptedChunk.KEY_LENGTH_BYTES));
+    private static final ChunkHash TEST_HASH_2 =
+            new ChunkHash(Arrays.copyOf(new byte[] {2}, EncryptedChunk.KEY_LENGTH_BYTES));
+    private static final int TEST_LENGTH_1 = 10;
+    private static final int TEST_LENGTH_2 = 18;
+
+    private static final String TEST_PACKAGE_1 = "com.example.test1";
+    private static final String TEST_PACKAGE_2 = "com.example.test2";
+
+    @Rule public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
+
+    private File mStoreFolder;
+    private ProtoStore<ChunksMetadataProto.ChunkListing> mProtoStore;
+
+    @Before
+    public void setUp() throws Exception {
+        mStoreFolder = mTemporaryFolder.newFolder();
+        mProtoStore = new ProtoStore<>(ChunksMetadataProto.ChunkListing.class, mStoreFolder);
+    }
+
+    @Test
+    public void differentStoreTypes_operateSimultaneouslyWithoutInterfering() throws Exception {
+        ChunksMetadataProto.ChunkListing chunkListing =
+                createChunkListing(ImmutableMap.of(TEST_HASH_1, TEST_LENGTH_1));
+        KeyValueListingProto.KeyValueListing keyValueListing =
+                new KeyValueListingProto.KeyValueListing();
+        keyValueListing.entries = new KeyValueListingProto.KeyValueEntry[1];
+        keyValueListing.entries[0] = new KeyValueListingProto.KeyValueEntry();
+        keyValueListing.entries[0].key = TEST_KEY_1;
+        keyValueListing.entries[0].hash = TEST_HASH_1.getHash();
+
+        Context application = ApplicationProvider.getApplicationContext();
+        ProtoStore<ChunksMetadataProto.ChunkListing> chunkListingStore =
+                ProtoStore.createChunkListingStore(application);
+        ProtoStore<KeyValueListingProto.KeyValueListing> keyValueListingStore =
+                ProtoStore.createKeyValueListingStore(application);
+
+        chunkListingStore.saveProto(TEST_PACKAGE_1, chunkListing);
+        keyValueListingStore.saveProto(TEST_PACKAGE_1, keyValueListing);
+
+        ChunksMetadataProto.ChunkListing actualChunkListing =
+                chunkListingStore.loadProto(TEST_PACKAGE_1).get();
+        KeyValueListingProto.KeyValueListing actualKeyValueListing =
+                keyValueListingStore.loadProto(TEST_PACKAGE_1).get();
+        assertListingsEqual(actualChunkListing, chunkListing);
+        assertThat(actualKeyValueListing.entries.length).isEqualTo(1);
+        assertThat(actualKeyValueListing.entries[0].key).isEqualTo(TEST_KEY_1);
+        assertThat(actualKeyValueListing.entries[0].hash).isEqualTo(TEST_HASH_1.getHash());
+    }
+
+    @Test
+    public void construct_storeLocationIsFile_throws() throws Exception {
+        assertThrows(
+                IOException.class,
+                () ->
+                        new ProtoStore<>(
+                                ChunksMetadataProto.ChunkListing.class,
+                                mTemporaryFolder.newFile()));
+    }
+
+    @Test
+    public void loadChunkListing_noListingExists_returnsEmptyListing() throws Exception {
+        Optional<ChunksMetadataProto.ChunkListing> chunkListing =
+                mProtoStore.loadProto(TEST_PACKAGE_1);
+        assertThat(chunkListing.isPresent()).isFalse();
+    }
+
+    @Test
+    public void loadChunkListing_listingExists_returnsExistingListing() throws Exception {
+        ChunksMetadataProto.ChunkListing expected =
+                createChunkListing(
+                        ImmutableMap.of(TEST_HASH_1, TEST_LENGTH_1, TEST_HASH_2, TEST_LENGTH_2));
+        mProtoStore.saveProto(TEST_PACKAGE_1, expected);
+
+        ChunksMetadataProto.ChunkListing result = mProtoStore.loadProto(TEST_PACKAGE_1).get();
+
+        assertListingsEqual(result, expected);
+    }
+
+    @Test
+    public void loadProto_emptyPackageName_throwsException() throws Exception {
+        assertThrows(IllegalArgumentException.class, () -> mProtoStore.loadProto(""));
+    }
+
+    @Test
+    public void loadProto_nullPackageName_throwsException() throws Exception {
+        assertThrows(IllegalArgumentException.class, () -> mProtoStore.loadProto(null));
+    }
+
+    @Test
+    public void loadProto_packageNameContainsSlash_throwsException() throws Exception {
+        assertThrows(
+                IllegalArgumentException.class, () -> mProtoStore.loadProto(TEST_PACKAGE_1 + "/"));
+    }
+
+    @Test
+    public void saveProto_persistsToNewInstance() throws Exception {
+        ChunksMetadataProto.ChunkListing expected =
+                createChunkListing(
+                        ImmutableMap.of(TEST_HASH_1, TEST_LENGTH_1, TEST_HASH_2, TEST_LENGTH_2));
+        mProtoStore.saveProto(TEST_PACKAGE_1, expected);
+        mProtoStore = new ProtoStore<>(ChunksMetadataProto.ChunkListing.class, mStoreFolder);
+
+        ChunksMetadataProto.ChunkListing result = mProtoStore.loadProto(TEST_PACKAGE_1).get();
+
+        assertListingsEqual(result, expected);
+    }
+
+    @Test
+    public void saveProto_emptyPackageName_throwsException() throws Exception {
+        assertThrows(
+                IllegalArgumentException.class,
+                () -> mProtoStore.saveProto("", new ChunksMetadataProto.ChunkListing()));
+    }
+
+    @Test
+    public void saveProto_nullPackageName_throwsException() throws Exception {
+        assertThrows(
+                IllegalArgumentException.class,
+                () -> mProtoStore.saveProto(null, new ChunksMetadataProto.ChunkListing()));
+    }
+
+    @Test
+    public void saveProto_packageNameContainsSlash_throwsException() throws Exception {
+        assertThrows(
+                IllegalArgumentException.class,
+                () ->
+                        mProtoStore.saveProto(
+                                TEST_PACKAGE_1 + "/", new ChunksMetadataProto.ChunkListing()));
+    }
+
+    @Test
+    public void saveProto_nullListing_throwsException() throws Exception {
+        assertThrows(NullPointerException.class, () -> mProtoStore.saveProto(TEST_PACKAGE_1, null));
+    }
+
+    @Test
+    public void deleteProto_noListingExists_doesNothing() throws Exception {
+        ChunksMetadataProto.ChunkListing listing =
+                createChunkListing(ImmutableMap.of(TEST_HASH_1, TEST_LENGTH_1));
+        mProtoStore.saveProto(TEST_PACKAGE_1, listing);
+
+        mProtoStore.deleteProto(TEST_PACKAGE_2);
+
+        assertThat(mProtoStore.loadProto(TEST_PACKAGE_1).get().chunks.length).isEqualTo(1);
+    }
+
+    @Test
+    public void deleteProto_listingExists_deletesListing() throws Exception {
+        ChunksMetadataProto.ChunkListing listing =
+                createChunkListing(ImmutableMap.of(TEST_HASH_1, TEST_LENGTH_1));
+        mProtoStore.saveProto(TEST_PACKAGE_1, listing);
+
+        mProtoStore.deleteProto(TEST_PACKAGE_1);
+
+        assertThat(mProtoStore.loadProto(TEST_PACKAGE_1).isPresent()).isFalse();
+    }
+
+    @Test
+    public void deleteAllProtos_deletesAllProtos() throws Exception {
+        ChunksMetadataProto.ChunkListing listing1 =
+                createChunkListing(ImmutableMap.of(TEST_HASH_1, TEST_LENGTH_1));
+        ChunksMetadataProto.ChunkListing listing2 =
+                createChunkListing(ImmutableMap.of(TEST_HASH_2, TEST_LENGTH_2));
+        mProtoStore.saveProto(TEST_PACKAGE_1, listing1);
+        mProtoStore.saveProto(TEST_PACKAGE_2, listing2);
+
+        mProtoStore.deleteAllProtos();
+
+        assertThat(mProtoStore.loadProto(TEST_PACKAGE_1).isPresent()).isFalse();
+        assertThat(mProtoStore.loadProto(TEST_PACKAGE_2).isPresent()).isFalse();
+    }
+
+    @Test
+    public void deleteAllProtos_folderDeleted_doesNotCrash() throws Exception {
+        mStoreFolder.delete();
+
+        mProtoStore.deleteAllProtos();
+    }
+
+    private static ChunksMetadataProto.ChunkListing createChunkListing(
+            ImmutableMap<ChunkHash, Integer> chunks) {
+        ChunksMetadataProto.ChunkListing listing = new ChunksMetadataProto.ChunkListing();
+        listing.cipherType = ChunksMetadataProto.AES_256_GCM;
+        listing.chunkOrderingType = ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+
+        List<ChunksMetadataProto.Chunk> chunkProtos = new ArrayList<>();
+        for (Entry<ChunkHash, Integer> entry : chunks.entrySet()) {
+            ChunksMetadataProto.Chunk chunk = new ChunksMetadataProto.Chunk();
+            chunk.hash = entry.getKey().getHash();
+            chunk.length = entry.getValue();
+            chunkProtos.add(chunk);
+        }
+        listing.chunks = chunkProtos.toArray(new ChunksMetadataProto.Chunk[0]);
+        return listing;
+    }
+
+    private void assertListingsEqual(
+            ChunksMetadataProto.ChunkListing result, ChunksMetadataProto.ChunkListing expected) {
+        assertThat(result.chunks.length).isEqualTo(expected.chunks.length);
+        for (int i = 0; i < result.chunks.length; i++) {
+            assertWithMessage("Chunk " + i)
+                    .that(result.chunks[i].length)
+                    .isEqualTo(expected.chunks[i].length);
+            assertWithMessage("Chunk " + i)
+                    .that(result.chunks[i].hash)
+                    .isEqualTo(expected.chunks[i].hash);
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/kv/DecryptedChunkKvOutputTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/kv/DecryptedChunkKvOutputTest.java
new file mode 100644
index 0000000..215e1cb
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/kv/DecryptedChunkKvOutputTest.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.kv;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.os.Debug;
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+
+import java.security.MessageDigest;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Stream;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class DecryptedChunkKvOutputTest {
+    private static final String TEST_KEY_1 = "key_1";
+    private static final String TEST_KEY_2 = "key_2";
+    private static final byte[] TEST_VALUE_1 = {1, 2, 3};
+    private static final byte[] TEST_VALUE_2 = {10, 11, 12, 13};
+    private static final byte[] TEST_PAIR_1 = toByteArray(createPair(TEST_KEY_1, TEST_VALUE_1));
+    private static final byte[] TEST_PAIR_2 = toByteArray(createPair(TEST_KEY_2, TEST_VALUE_2));
+    private static final int TEST_BUFFER_SIZE = Math.max(TEST_PAIR_1.length, TEST_PAIR_2.length);
+
+    @Mock private ChunkHasher mChunkHasher;
+    private DecryptedChunkKvOutput mOutput;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        when(mChunkHasher.computeHash(any()))
+                .thenAnswer(invocation -> fakeHash(invocation.getArgument(0)));
+        mOutput = new DecryptedChunkKvOutput(mChunkHasher);
+    }
+
+    @Test
+    public void open_returnsInstance() throws Exception {
+        assertThat(mOutput.open()).isEqualTo(mOutput);
+    }
+
+    @Test
+    public void processChunk_alreadyClosed_throws() throws Exception {
+        mOutput.open();
+        mOutput.close();
+
+        assertThrows(
+                IllegalStateException.class,
+                () -> mOutput.processChunk(TEST_PAIR_1, TEST_PAIR_1.length));
+    }
+
+    @Test
+    public void getDigest_beforeClose_throws() throws Exception {
+        // TODO: b/141356823 We should add a test which calls .open() here
+        assertThrows(IllegalStateException.class, () -> mOutput.getDigest());
+    }
+
+    @Test
+    public void getDigest_returnsDigestOfSortedHashes() throws Exception {
+        mOutput.open();
+        Debug.waitForDebugger();
+        mOutput.processChunk(Arrays.copyOf(TEST_PAIR_1, TEST_BUFFER_SIZE), TEST_PAIR_1.length);
+        mOutput.processChunk(Arrays.copyOf(TEST_PAIR_2, TEST_BUFFER_SIZE), TEST_PAIR_2.length);
+        mOutput.close();
+
+        byte[] actualDigest = mOutput.getDigest();
+
+        MessageDigest digest = MessageDigest.getInstance(DecryptedChunkKvOutput.DIGEST_ALGORITHM);
+        Stream.of(TEST_PAIR_1, TEST_PAIR_2)
+                .map(DecryptedChunkKvOutputTest::fakeHash)
+                .sorted(Comparator.naturalOrder())
+                .forEachOrdered(hash -> digest.update(hash.getHash()));
+        assertThat(actualDigest).isEqualTo(digest.digest());
+    }
+
+    @Test
+    public void getPairs_beforeClose_throws() throws Exception {
+        // TODO: b/141356823 We should add a test which calls .open() here
+        assertThrows(IllegalStateException.class, () -> mOutput.getPairs());
+    }
+
+    @Test
+    public void getPairs_returnsPairsSortedByKey() throws Exception {
+        mOutput.open();
+        // Write out of order to check that it sorts the chunks.
+        mOutput.processChunk(Arrays.copyOf(TEST_PAIR_2, TEST_BUFFER_SIZE), TEST_PAIR_2.length);
+        mOutput.processChunk(Arrays.copyOf(TEST_PAIR_1, TEST_BUFFER_SIZE), TEST_PAIR_1.length);
+        mOutput.close();
+
+        List<KeyValuePairProto.KeyValuePair> pairs = mOutput.getPairs();
+
+        assertThat(
+                        isInOrder(
+                                pairs,
+                                Comparator.comparing(
+                                        (KeyValuePairProto.KeyValuePair pair) -> pair.key)))
+                .isTrue();
+        assertThat(pairs).hasSize(2);
+        assertThat(pairs.get(0).key).isEqualTo(TEST_KEY_1);
+        assertThat(pairs.get(0).value).isEqualTo(TEST_VALUE_1);
+        assertThat(pairs.get(1).key).isEqualTo(TEST_KEY_2);
+        assertThat(pairs.get(1).value).isEqualTo(TEST_VALUE_2);
+    }
+
+    private static KeyValuePairProto.KeyValuePair createPair(String key, byte[] value) {
+        KeyValuePairProto.KeyValuePair pair = new KeyValuePairProto.KeyValuePair();
+        pair.key = key;
+        pair.value = value;
+        return pair;
+    }
+
+    private boolean isInOrder(
+            List<KeyValuePairProto.KeyValuePair> list,
+            Comparator<KeyValuePairProto.KeyValuePair> comparator) {
+        if (list.size() < 2) {
+            return true;
+        }
+
+        List<KeyValuePairProto.KeyValuePair> sortedList = new ArrayList<>(list);
+        Collections.sort(sortedList, comparator);
+        return list.equals(sortedList);
+    }
+
+    private static byte[] toByteArray(KeyValuePairProto.KeyValuePair nano) {
+        return KeyValuePairProto.KeyValuePair.toByteArray(nano);
+    }
+
+    private static ChunkHash fakeHash(byte[] data) {
+        return new ChunkHash(Arrays.copyOf(data, ChunkHash.HASH_LENGTH_BYTES));
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/kv/KeyValueListingBuilderTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/kv/KeyValueListingBuilderTest.java
new file mode 100644
index 0000000..acc6628
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/kv/KeyValueListingBuilderTest.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.kv;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+
+import com.google.common.collect.ImmutableMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+import java.util.Arrays;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class KeyValueListingBuilderTest {
+    private static final String TEST_KEY_1 = "test_key_1";
+    private static final String TEST_KEY_2 = "test_key_2";
+    private static final ChunkHash TEST_HASH_1 =
+            new ChunkHash(Arrays.copyOf(new byte[] {1, 2}, ChunkHash.HASH_LENGTH_BYTES));
+    private static final ChunkHash TEST_HASH_2 =
+            new ChunkHash(Arrays.copyOf(new byte[] {5, 6}, ChunkHash.HASH_LENGTH_BYTES));
+
+    private KeyValueListingBuilder mBuilder;
+
+    @Before
+    public void setUp() {
+        mBuilder = new KeyValueListingBuilder();
+    }
+
+    @Test
+    public void addPair_nullKey_throws() {
+        assertThrows(NullPointerException.class, () -> mBuilder.addPair(null, TEST_HASH_1));
+    }
+
+    @Test
+    public void addPair_emptyKey_throws() {
+        assertThrows(IllegalArgumentException.class, () -> mBuilder.addPair("", TEST_HASH_1));
+    }
+
+    @Test
+    public void addPair_nullHash_throws() {
+        assertThrows(NullPointerException.class, () -> mBuilder.addPair(TEST_KEY_1, null));
+    }
+
+    @Test
+    public void build_noPairs_buildsEmptyListing() {
+        KeyValueListingProto.KeyValueListing listing = mBuilder.build();
+
+        assertThat(listing.entries).isEmpty();
+    }
+
+    @Test
+    public void build_returnsCorrectListing() {
+        mBuilder.addPair(TEST_KEY_1, TEST_HASH_1);
+
+        KeyValueListingProto.KeyValueListing listing = mBuilder.build();
+
+        assertThat(listing.entries.length).isEqualTo(1);
+        assertThat(listing.entries[0].key).isEqualTo(TEST_KEY_1);
+        assertThat(listing.entries[0].hash).isEqualTo(TEST_HASH_1.getHash());
+    }
+
+    @Test
+    public void addAll_addsAllPairsInMap() {
+        ImmutableMap<String, ChunkHash> pairs =
+                new ImmutableMap.Builder<String, ChunkHash>()
+                        .put(TEST_KEY_1, TEST_HASH_1)
+                        .put(TEST_KEY_2, TEST_HASH_2)
+                        .build();
+
+        mBuilder.addAll(pairs);
+        KeyValueListingProto.KeyValueListing listing = mBuilder.build();
+
+        assertThat(listing.entries.length).isEqualTo(2);
+        assertThat(listing.entries[0].key).isEqualTo(TEST_KEY_1);
+        assertThat(listing.entries[0].hash).isEqualTo(TEST_HASH_1.getHash());
+        assertThat(listing.entries[1].key).isEqualTo(TEST_KEY_2);
+        assertThat(listing.entries[1].hash).isEqualTo(TEST_HASH_2.getHash());
+    }
+
+    @Test
+    public void emptyListing_returnsListingWithoutAnyPairs() {
+        KeyValueListingProto.KeyValueListing emptyListing = KeyValueListingBuilder.emptyListing();
+        assertThat(emptyListing.entries).isEmpty();
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/BackupFileDecryptorTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/BackupFileDecryptorTaskTest.java
new file mode 100644
index 0000000..07a6fd2
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/BackupFileDecryptorTaskTest.java
@@ -0,0 +1,583 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.server.backup.testing.CryptoTestUtils.generateAesKey;
+import static com.android.server.backup.testing.CryptoTestUtils.newChunkOrdering;
+import static com.android.server.backup.testing.CryptoTestUtils.newChunksMetadata;
+import static com.android.server.backup.testing.CryptoTestUtils.newPair;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.expectThrows;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupDataInput;
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.chunking.DecryptedChunkFileOutput;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.chunking.cdc.FingerprintMixer;
+import com.android.server.backup.encryption.kv.DecryptedChunkKvOutput;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkOrdering;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunksMetadata;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto.KeyValuePair;
+import com.android.server.backup.encryption.tasks.BackupEncrypter.Result;
+import com.android.server.backup.testing.CryptoTestUtils;
+import com.android.server.testing.shadows.ShadowBackupDataInput;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.protobuf.nano.MessageNano;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.RandomAccessFile;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Random;
+import java.util.Set;
+
+import javax.crypto.AEADBadTagException;
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+
+@Config(shadows = {ShadowBackupDataInput.class})
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class BackupFileDecryptorTaskTest {
+    private static final String READ_WRITE_MODE = "rw";
+    private static final int BYTES_PER_KILOBYTE = 1024;
+    private static final int MIN_CHUNK_SIZE_BYTES = 2 * BYTES_PER_KILOBYTE;
+    private static final int AVERAGE_CHUNK_SIZE_BYTES = 4 * BYTES_PER_KILOBYTE;
+    private static final int MAX_CHUNK_SIZE_BYTES = 64 * BYTES_PER_KILOBYTE;
+    private static final int BACKUP_DATA_SIZE_BYTES = 60 * BYTES_PER_KILOBYTE;
+    private static final int GCM_NONCE_LENGTH_BYTES = 12;
+    private static final int GCM_TAG_LENGTH_BYTES = 16;
+    private static final int BITS_PER_BYTE = 8;
+    private static final int CHECKSUM_LENGTH_BYTES = 256 / BITS_PER_BYTE;
+    @Nullable private static final FileDescriptor NULL_FILE_DESCRIPTOR = null;
+
+    private static final Set<KeyValuePair> TEST_KV_DATA = new HashSet<>();
+
+    static {
+        TEST_KV_DATA.add(newPair("key1", "value1"));
+        TEST_KV_DATA.add(newPair("key2", "value2"));
+    }
+
+    @Rule public final TemporaryFolder mTemporaryFolder = new TemporaryFolder();
+
+    private SecretKey mTertiaryKey;
+    private SecretKey mChunkEncryptionKey;
+    private File mInputFile;
+    private File mOutputFile;
+    private DecryptedChunkOutput mFileOutput;
+    private DecryptedChunkKvOutput mKvOutput;
+    private Random mRandom;
+    private BackupFileDecryptorTask mTask;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        mRandom = new Random();
+        mTertiaryKey = generateAesKey();
+        // In good situations it's always the same. We allow changing it for testing when somehow it
+        // has become mismatched that we throw an error.
+        mChunkEncryptionKey = mTertiaryKey;
+        mInputFile = mTemporaryFolder.newFile();
+        mOutputFile = mTemporaryFolder.newFile();
+        mFileOutput = new DecryptedChunkFileOutput(mOutputFile);
+        mKvOutput = new DecryptedChunkKvOutput(new ChunkHasher(mTertiaryKey));
+        mTask = new BackupFileDecryptorTask(mTertiaryKey);
+    }
+
+    @Test
+    public void decryptFile_throwsForNonExistentInput() throws Exception {
+        assertThrows(
+                FileNotFoundException.class,
+                () ->
+                        mTask.decryptFile(
+                                new File(mTemporaryFolder.newFolder(), "nonexistent"),
+                                mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_throwsForDirectoryInputFile() throws Exception {
+        assertThrows(
+                FileNotFoundException.class,
+                () -> mTask.decryptFile(mTemporaryFolder.newFolder(), mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_withExplicitStarts_decryptsEncryptedData() throws Exception {
+        byte[] backupData = randomData(BACKUP_DATA_SIZE_BYTES);
+        createEncryptedFileUsingExplicitStarts(backupData);
+
+        mTask.decryptFile(mInputFile, mFileOutput);
+
+        assertThat(Files.readAllBytes(Paths.get(mOutputFile.toURI()))).isEqualTo(backupData);
+    }
+
+    @Test
+    public void decryptFile_withInlineLengths_decryptsEncryptedData() throws Exception {
+        createEncryptedFileUsingInlineLengths(
+                TEST_KV_DATA, chunkOrdering -> chunkOrdering, chunksMetadata -> chunksMetadata);
+        mTask.decryptFile(mInputFile, mKvOutput);
+        assertThat(asMap(mKvOutput.getPairs())).containsExactlyEntriesIn(asMap(TEST_KV_DATA));
+    }
+
+    @Test
+    public void decryptFile_withNoChunkOrderingType_decryptsUsingExplicitStarts() throws Exception {
+        byte[] backupData = randomData(BACKUP_DATA_SIZE_BYTES);
+        createEncryptedFileUsingExplicitStarts(
+                backupData,
+                chunkOrdering -> chunkOrdering,
+                chunksMetadata -> {
+                    ChunksMetadata metadata = CryptoTestUtils.clone(chunksMetadata);
+                    metadata.chunkOrderingType =
+                            ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+                    return metadata;
+                });
+
+        mTask.decryptFile(mInputFile, mFileOutput);
+
+        assertThat(Files.readAllBytes(Paths.get(mOutputFile.toURI()))).isEqualTo(backupData);
+    }
+
+    @Test
+    public void decryptFile_withInlineLengths_throwsForZeroLengths() throws Exception {
+        createEncryptedFileUsingInlineLengths(
+                TEST_KV_DATA, chunkOrdering -> chunkOrdering, chunksMetadata -> chunksMetadata);
+
+        // Set the length of the first chunk to zero.
+        RandomAccessFile raf = new RandomAccessFile(mInputFile, READ_WRITE_MODE);
+        raf.seek(0);
+        raf.writeInt(0);
+
+        assertThrows(
+                MalformedEncryptedFileException.class,
+                () -> mTask.decryptFile(mInputFile, mKvOutput));
+    }
+
+    @Test
+    public void decryptFile_withInlineLengths_throwsForLongLengths() throws Exception {
+        createEncryptedFileUsingInlineLengths(
+                TEST_KV_DATA, chunkOrdering -> chunkOrdering, chunksMetadata -> chunksMetadata);
+
+        // Set the length of the first chunk to zero.
+        RandomAccessFile raf = new RandomAccessFile(mInputFile, READ_WRITE_MODE);
+        raf.seek(0);
+        raf.writeInt((int) mInputFile.length());
+
+        assertThrows(
+                MalformedEncryptedFileException.class,
+                () -> mTask.decryptFile(mInputFile, mKvOutput));
+    }
+
+    @Test
+    public void decryptFile_throwsForBadKey() throws Exception {
+        createEncryptedFileUsingExplicitStarts(randomData(BACKUP_DATA_SIZE_BYTES));
+
+        assertThrows(
+                AEADBadTagException.class,
+                () ->
+                        new BackupFileDecryptorTask(generateAesKey())
+                                .decryptFile(mInputFile, mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_withExplicitStarts_throwsForMangledOrdering() throws Exception {
+        createEncryptedFileUsingExplicitStarts(
+                randomData(BACKUP_DATA_SIZE_BYTES),
+                chunkOrdering -> {
+                    ChunkOrdering ordering = CryptoTestUtils.clone(chunkOrdering);
+                    Arrays.sort(ordering.starts);
+                    return ordering;
+                });
+
+        assertThrows(
+                MessageDigestMismatchException.class,
+                () -> mTask.decryptFile(mInputFile, mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_withExplicitStarts_noChunks_returnsNoData() throws Exception {
+        byte[] backupData = randomData(/*length=*/ 0);
+        createEncryptedFileUsingExplicitStarts(
+                backupData,
+                chunkOrdering -> {
+                    ChunkOrdering ordering = CryptoTestUtils.clone(chunkOrdering);
+                    ordering.starts = new int[0];
+                    return ordering;
+                });
+
+        mTask.decryptFile(mInputFile, mFileOutput);
+
+        assertThat(Files.readAllBytes(Paths.get(mOutputFile.toURI()))).isEqualTo(backupData);
+    }
+
+    @Test
+    public void decryptFile_throwsForMismatchedChecksum() throws Exception {
+        createEncryptedFileUsingExplicitStarts(
+                randomData(BACKUP_DATA_SIZE_BYTES),
+                chunkOrdering -> {
+                    ChunkOrdering ordering = CryptoTestUtils.clone(chunkOrdering);
+                    ordering.checksum =
+                            Arrays.copyOf(randomData(CHECKSUM_LENGTH_BYTES), CHECKSUM_LENGTH_BYTES);
+                    return ordering;
+                });
+
+        assertThrows(
+                MessageDigestMismatchException.class,
+                () -> mTask.decryptFile(mInputFile, mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_throwsForBadChunksMetadataOffset() throws Exception {
+        createEncryptedFileUsingExplicitStarts(randomData(BACKUP_DATA_SIZE_BYTES));
+
+        // Replace the metadata with all 1s.
+        RandomAccessFile raf = new RandomAccessFile(mInputFile, READ_WRITE_MODE);
+        raf.seek(raf.length() - Long.BYTES);
+        int metadataOffset = (int) raf.readLong();
+        int metadataLength = (int) raf.length() - metadataOffset - Long.BYTES;
+
+        byte[] allOnes = new byte[metadataLength];
+        Arrays.fill(allOnes, (byte) 1);
+
+        raf.seek(metadataOffset);
+        raf.write(allOnes, /*off=*/ 0, metadataLength);
+
+        MalformedEncryptedFileException thrown =
+                expectThrows(
+                        MalformedEncryptedFileException.class,
+                        () -> mTask.decryptFile(mInputFile, mFileOutput));
+        assertThat(thrown)
+                .hasMessageThat()
+                .isEqualTo(
+                        "Could not read chunks metadata at position "
+                                + metadataOffset
+                                + " of file of "
+                                + raf.length()
+                                + " bytes");
+    }
+
+    @Test
+    public void decryptFile_throwsForChunksMetadataOffsetBeyondEndOfFile() throws Exception {
+        createEncryptedFileUsingExplicitStarts(randomData(BACKUP_DATA_SIZE_BYTES));
+
+        RandomAccessFile raf = new RandomAccessFile(mInputFile, READ_WRITE_MODE);
+        raf.seek(raf.length() - Long.BYTES);
+        raf.writeLong(raf.length());
+
+        MalformedEncryptedFileException thrown =
+                expectThrows(
+                        MalformedEncryptedFileException.class,
+                        () -> mTask.decryptFile(mInputFile, mFileOutput));
+        assertThat(thrown)
+                .hasMessageThat()
+                .isEqualTo(
+                        raf.length()
+                                + " is not valid position for chunks metadata in file of "
+                                + raf.length()
+                                + " bytes");
+    }
+
+    @Test
+    public void decryptFile_throwsForChunksMetadataOffsetBeforeBeginningOfFile() throws Exception {
+        createEncryptedFileUsingExplicitStarts(randomData(BACKUP_DATA_SIZE_BYTES));
+
+        RandomAccessFile raf = new RandomAccessFile(mInputFile, READ_WRITE_MODE);
+        raf.seek(raf.length() - Long.BYTES);
+        raf.writeLong(-1);
+
+        MalformedEncryptedFileException thrown =
+                expectThrows(
+                        MalformedEncryptedFileException.class,
+                        () -> mTask.decryptFile(mInputFile, mFileOutput));
+        assertThat(thrown)
+                .hasMessageThat()
+                .isEqualTo(
+                        "-1 is not valid position for chunks metadata in file of "
+                                + raf.length()
+                                + " bytes");
+    }
+
+    @Test
+    public void decryptFile_throwsForMangledChunks() throws Exception {
+        createEncryptedFileUsingExplicitStarts(randomData(BACKUP_DATA_SIZE_BYTES));
+
+        // Mess up some bits in a random byte
+        RandomAccessFile raf = new RandomAccessFile(mInputFile, READ_WRITE_MODE);
+        raf.seek(50);
+        byte fiftiethByte = raf.readByte();
+        raf.seek(50);
+        raf.write(~fiftiethByte);
+
+        assertThrows(AEADBadTagException.class, () -> mTask.decryptFile(mInputFile, mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_throwsForBadChunkEncryptionKey() throws Exception {
+        mChunkEncryptionKey = generateAesKey();
+
+        createEncryptedFileUsingExplicitStarts(randomData(BACKUP_DATA_SIZE_BYTES));
+
+        assertThrows(AEADBadTagException.class, () -> mTask.decryptFile(mInputFile, mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_throwsForUnsupportedCipherType() throws Exception {
+        createEncryptedFileUsingExplicitStarts(
+                randomData(BACKUP_DATA_SIZE_BYTES),
+                chunkOrdering -> chunkOrdering,
+                chunksMetadata -> {
+                    ChunksMetadata metadata = CryptoTestUtils.clone(chunksMetadata);
+                    metadata.cipherType = ChunksMetadataProto.UNKNOWN_CIPHER_TYPE;
+                    return metadata;
+                });
+
+        assertThrows(
+                UnsupportedEncryptedFileException.class,
+                () -> mTask.decryptFile(mInputFile, mFileOutput));
+    }
+
+    @Test
+    public void decryptFile_throwsForUnsupportedMessageDigestType() throws Exception {
+        createEncryptedFileUsingExplicitStarts(
+                randomData(BACKUP_DATA_SIZE_BYTES),
+                chunkOrdering -> chunkOrdering,
+                chunksMetadata -> {
+                    ChunksMetadata metadata = CryptoTestUtils.clone(chunksMetadata);
+                    metadata.checksumType = ChunksMetadataProto.UNKNOWN_CHECKSUM_TYPE;
+                    return metadata;
+                });
+
+        assertThrows(
+                UnsupportedEncryptedFileException.class,
+                () -> mTask.decryptFile(mInputFile, mFileOutput));
+    }
+
+    /**
+     * Creates an encrypted backup file from the given data.
+     *
+     * @param data The plaintext content.
+     */
+    private void createEncryptedFileUsingExplicitStarts(byte[] data) throws Exception {
+        createEncryptedFileUsingExplicitStarts(data, chunkOrdering -> chunkOrdering);
+    }
+
+    /**
+     * Creates an encrypted backup file from the given data.
+     *
+     * @param data The plaintext content.
+     * @param chunkOrderingTransformer Transforms the ordering before it's encrypted.
+     */
+    private void createEncryptedFileUsingExplicitStarts(
+            byte[] data, Transformer<ChunkOrdering> chunkOrderingTransformer) throws Exception {
+        createEncryptedFileUsingExplicitStarts(
+                data, chunkOrderingTransformer, chunksMetadata -> chunksMetadata);
+    }
+
+    /**
+     * Creates an encrypted backup file from the given data in mode {@link
+     * ChunksMetadataProto#EXPLICIT_STARTS}.
+     *
+     * @param data The plaintext content.
+     * @param chunkOrderingTransformer Transforms the ordering before it's encrypted.
+     * @param chunksMetadataTransformer Transforms the metadata before it's written.
+     */
+    private void createEncryptedFileUsingExplicitStarts(
+            byte[] data,
+            Transformer<ChunkOrdering> chunkOrderingTransformer,
+            Transformer<ChunksMetadata> chunksMetadataTransformer)
+            throws Exception {
+        Result result = backupFullData(data);
+
+        ArrayList<EncryptedChunk> chunks = new ArrayList<>(result.getNewChunks());
+        Collections.shuffle(chunks);
+        HashMap<ChunkHash, Integer> startPositions = new HashMap<>();
+
+        try (FileOutputStream fos = new FileOutputStream(mInputFile);
+                DataOutputStream dos = new DataOutputStream(fos)) {
+            int position = 0;
+
+            for (EncryptedChunk chunk : chunks) {
+                startPositions.put(chunk.key(), position);
+                dos.write(chunk.nonce());
+                dos.write(chunk.encryptedBytes());
+                position += chunk.nonce().length + chunk.encryptedBytes().length;
+            }
+
+            int[] starts = new int[chunks.size()];
+            List<ChunkHash> chunkListing = result.getAllChunks();
+
+            for (int i = 0; i < chunks.size(); i++) {
+                starts[i] = startPositions.get(chunkListing.get(i));
+            }
+
+            ChunkOrdering chunkOrdering = newChunkOrdering(starts, result.getDigest());
+            chunkOrdering = chunkOrderingTransformer.accept(chunkOrdering);
+
+            ChunksMetadata metadata =
+                    newChunksMetadata(
+                            ChunksMetadataProto.AES_256_GCM,
+                            ChunksMetadataProto.SHA_256,
+                            ChunksMetadataProto.EXPLICIT_STARTS,
+                            encrypt(chunkOrdering));
+            metadata = chunksMetadataTransformer.accept(metadata);
+
+            dos.write(MessageNano.toByteArray(metadata));
+            dos.writeLong(position);
+        }
+    }
+
+    /**
+     * Creates an encrypted backup file from the given data in mode {@link
+     * ChunksMetadataProto#INLINE_LENGTHS}.
+     *
+     * @param data The plaintext key value pairs to back up.
+     * @param chunkOrderingTransformer Transforms the ordering before it's encrypted.
+     * @param chunksMetadataTransformer Transforms the metadata before it's written.
+     */
+    private void createEncryptedFileUsingInlineLengths(
+            Set<KeyValuePair> data,
+            Transformer<ChunkOrdering> chunkOrderingTransformer,
+            Transformer<ChunksMetadata> chunksMetadataTransformer)
+            throws Exception {
+        Result result = backupKvData(data);
+
+        List<EncryptedChunk> chunks = new ArrayList<>(result.getNewChunks());
+        System.out.println("we have chunk count " + chunks.size());
+        Collections.shuffle(chunks);
+
+        try (FileOutputStream fos = new FileOutputStream(mInputFile);
+                DataOutputStream dos = new DataOutputStream(fos)) {
+            for (EncryptedChunk chunk : chunks) {
+                dos.writeInt(chunk.nonce().length + chunk.encryptedBytes().length);
+                dos.write(chunk.nonce());
+                dos.write(chunk.encryptedBytes());
+            }
+
+            ChunkOrdering chunkOrdering = newChunkOrdering(null, result.getDigest());
+            chunkOrdering = chunkOrderingTransformer.accept(chunkOrdering);
+
+            ChunksMetadata metadata =
+                    newChunksMetadata(
+                            ChunksMetadataProto.AES_256_GCM,
+                            ChunksMetadataProto.SHA_256,
+                            ChunksMetadataProto.INLINE_LENGTHS,
+                            encrypt(chunkOrdering));
+            metadata = chunksMetadataTransformer.accept(metadata);
+
+            int metadataStart = dos.size();
+            dos.write(MessageNano.toByteArray(metadata));
+            dos.writeLong(metadataStart);
+        }
+    }
+
+    /** Performs a full backup of the given data, and returns the chunks. */
+    private BackupEncrypter.Result backupFullData(byte[] data) throws Exception {
+        BackupStreamEncrypter encrypter =
+                new BackupStreamEncrypter(
+                        new ByteArrayInputStream(data),
+                        MIN_CHUNK_SIZE_BYTES,
+                        MAX_CHUNK_SIZE_BYTES,
+                        AVERAGE_CHUNK_SIZE_BYTES);
+        return encrypter.backup(
+                mChunkEncryptionKey,
+                randomData(FingerprintMixer.SALT_LENGTH_BYTES),
+                new HashSet<>());
+    }
+
+    private Result backupKvData(Set<KeyValuePair> data) throws Exception {
+        ShadowBackupDataInput.reset();
+        for (KeyValuePair pair : data) {
+            ShadowBackupDataInput.addEntity(pair.key, pair.value);
+        }
+        KvBackupEncrypter encrypter =
+                new KvBackupEncrypter(new BackupDataInput(NULL_FILE_DESCRIPTOR));
+        return encrypter.backup(
+                mChunkEncryptionKey,
+                randomData(FingerprintMixer.SALT_LENGTH_BYTES),
+                Collections.EMPTY_SET);
+    }
+
+    /** Encrypts {@code chunkOrdering} using {@link #mTertiaryKey}. */
+    private byte[] encrypt(ChunkOrdering chunkOrdering) throws Exception {
+        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+        byte[] nonce = randomData(GCM_NONCE_LENGTH_BYTES);
+        cipher.init(
+                Cipher.ENCRYPT_MODE,
+                mTertiaryKey,
+                new GCMParameterSpec(GCM_TAG_LENGTH_BYTES * BITS_PER_BYTE, nonce));
+        byte[] nanoBytes = MessageNano.toByteArray(chunkOrdering);
+        byte[] encryptedBytes = cipher.doFinal(nanoBytes);
+
+        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+            out.write(nonce);
+            out.write(encryptedBytes);
+            return out.toByteArray();
+        }
+    }
+
+    /** Returns {@code length} random bytes. */
+    private byte[] randomData(int length) {
+        byte[] data = new byte[length];
+        mRandom.nextBytes(data);
+        return data;
+    }
+
+    private static ImmutableMap<String, String> asMap(Collection<KeyValuePair> pairs) {
+        ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
+        for (KeyValuePair pair : pairs) {
+            map.put(pair.key, new String(pair.value, Charset.forName("UTF-8")));
+        }
+        return map.build();
+    }
+
+    private interface Transformer<T> {
+        T accept(T t);
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedBackupTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedBackupTaskTest.java
new file mode 100644
index 0000000..f6914ef
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedBackupTaskTest.java
@@ -0,0 +1,397 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.AES_256_GCM;
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED;
+import static com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.SHA_256;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.BackupFileBuilder;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.chunking.EncryptedChunkEncoder;
+import com.android.server.backup.encryption.chunking.LengthlessEncryptedChunkEncoder;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.TertiaryKeyGenerator;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkListing;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkOrdering;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunksMetadata;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto.WrappedKey;
+import com.android.server.backup.encryption.tasks.BackupEncrypter.Result;
+import com.android.server.backup.testing.CryptoTestUtils;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.protobuf.nano.MessageNano;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import java.io.OutputStream;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.concurrent.CancellationException;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+
+@Config(shadows = {EncryptedBackupTaskTest.ShadowBackupFileBuilder.class})
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class EncryptedBackupTaskTest {
+
+    private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+    private static final int GCM_NONCE_LENGTH_BYTES = 12;
+    private static final int GCM_TAG_LENGTH_BYTES = 16;
+    private static final int BITS_PER_BYTE = 8;
+
+    private static final byte[] TEST_FINGERPRINT_MIXER_SALT =
+            Arrays.copyOf(new byte[] {22}, ChunkHash.HASH_LENGTH_BYTES);
+
+    private static final byte[] TEST_NONCE =
+            Arrays.copyOf(new byte[] {55}, EncryptedChunk.NONCE_LENGTH_BYTES);
+
+    private static final ChunkHash TEST_HASH_1 =
+            new ChunkHash(Arrays.copyOf(new byte[] {1}, ChunkHash.HASH_LENGTH_BYTES));
+    private static final ChunkHash TEST_HASH_2 =
+            new ChunkHash(Arrays.copyOf(new byte[] {2}, ChunkHash.HASH_LENGTH_BYTES));
+    private static final ChunkHash TEST_HASH_3 =
+            new ChunkHash(Arrays.copyOf(new byte[] {3}, ChunkHash.HASH_LENGTH_BYTES));
+
+    private static final EncryptedChunk TEST_CHUNK_1 =
+            EncryptedChunk.create(TEST_HASH_1, TEST_NONCE, new byte[] {1, 2, 3, 4, 5});
+    private static final EncryptedChunk TEST_CHUNK_2 =
+            EncryptedChunk.create(TEST_HASH_2, TEST_NONCE, new byte[] {6, 7, 8, 9, 10});
+    private static final EncryptedChunk TEST_CHUNK_3 =
+            EncryptedChunk.create(TEST_HASH_3, TEST_NONCE, new byte[] {11, 12, 13, 14, 15});
+
+    private static final byte[] TEST_CHECKSUM = Arrays.copyOf(new byte[] {10}, 258 / 8);
+    private static final String TEST_PACKAGE_NAME = "com.example.package";
+    private static final String TEST_OLD_DOCUMENT_ID = "old_doc_1";
+    private static final String TEST_NEW_DOCUMENT_ID = "new_doc_1";
+
+    @Captor private ArgumentCaptor<ChunksMetadata> mMetadataCaptor;
+
+    @Mock private CryptoBackupServer mCryptoBackupServer;
+    @Mock private BackupEncrypter mBackupEncrypter;
+    @Mock private BackupFileBuilder mBackupFileBuilder;
+
+    private ChunkListing mOldChunkListing;
+    private SecretKey mTertiaryKey;
+    private WrappedKey mWrappedTertiaryKey;
+    private EncryptedChunkEncoder mEncryptedChunkEncoder;
+    private EncryptedBackupTask mTask;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        SecureRandom secureRandom = new SecureRandom();
+        mTertiaryKey = new TertiaryKeyGenerator(secureRandom).generate();
+        mWrappedTertiaryKey = new WrappedKey();
+
+        mEncryptedChunkEncoder = new LengthlessEncryptedChunkEncoder();
+
+        ShadowBackupFileBuilder.sInstance = mBackupFileBuilder;
+
+        mTask =
+                new EncryptedBackupTask(
+                        mCryptoBackupServer, secureRandom, TEST_PACKAGE_NAME, mBackupEncrypter);
+    }
+
+    @Test
+    public void performNonIncrementalBackup_performsBackup() throws Exception {
+        setUpWithoutExistingBackup();
+
+        // Chunk listing and ordering don't matter for this test.
+        when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+        when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+        when(mCryptoBackupServer.uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), any()))
+                .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+        mTask.performNonIncrementalBackup(
+                mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT);
+
+        verify(mBackupFileBuilder)
+                .writeChunks(
+                        ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+                        ImmutableMap.of(TEST_HASH_1, TEST_CHUNK_1, TEST_HASH_2, TEST_CHUNK_2));
+        verify(mBackupFileBuilder).finish(any());
+        verify(mCryptoBackupServer)
+                .uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), eq(mWrappedTertiaryKey));
+    }
+
+    @Test
+    public void performIncrementalBackup_performsBackup() throws Exception {
+        setUpWithExistingBackup();
+
+        // Chunk listing and ordering don't matter for this test.
+        when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+        when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+        when(mCryptoBackupServer.uploadIncrementalBackup(
+                        eq(TEST_PACKAGE_NAME), eq(TEST_OLD_DOCUMENT_ID), any(), any()))
+                .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+        mTask.performIncrementalBackup(mTertiaryKey, mWrappedTertiaryKey, mOldChunkListing);
+
+        verify(mBackupFileBuilder)
+                .writeChunks(
+                        ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+                        ImmutableMap.of(TEST_HASH_2, TEST_CHUNK_2));
+        verify(mBackupFileBuilder).finish(any());
+        verify(mCryptoBackupServer)
+                .uploadIncrementalBackup(
+                        eq(TEST_PACKAGE_NAME),
+                        eq(TEST_OLD_DOCUMENT_ID),
+                        any(),
+                        eq(mWrappedTertiaryKey));
+    }
+
+    @Test
+    public void performIncrementalBackup_returnsNewChunkListingWithDocId() throws Exception {
+        setUpWithExistingBackup();
+
+        ChunkListing chunkListingWithoutDocId =
+                CryptoTestUtils.newChunkListingWithoutDocId(
+                        TEST_FINGERPRINT_MIXER_SALT,
+                        AES_256_GCM,
+                        CHUNK_ORDERING_TYPE_UNSPECIFIED,
+                        createChunkProtoFor(TEST_HASH_1, TEST_CHUNK_1),
+                        createChunkProtoFor(TEST_HASH_2, TEST_CHUNK_2));
+        when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(chunkListingWithoutDocId);
+
+        // Chunk ordering doesn't matter for this test.
+        when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+        when(mCryptoBackupServer.uploadIncrementalBackup(
+                        eq(TEST_PACKAGE_NAME), eq(TEST_OLD_DOCUMENT_ID), any(), any()))
+                .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+        ChunkListing actualChunkListing =
+                mTask.performIncrementalBackup(mTertiaryKey, mWrappedTertiaryKey, mOldChunkListing);
+
+        ChunkListing expectedChunkListing = CryptoTestUtils.clone(chunkListingWithoutDocId);
+        expectedChunkListing.documentId = TEST_NEW_DOCUMENT_ID;
+        assertChunkListingsAreEqual(actualChunkListing, expectedChunkListing);
+    }
+
+    @Test
+    public void performNonIncrementalBackup_returnsNewChunkListingWithDocId() throws Exception {
+        setUpWithoutExistingBackup();
+
+        ChunkListing chunkListingWithoutDocId =
+                CryptoTestUtils.newChunkListingWithoutDocId(
+                        TEST_FINGERPRINT_MIXER_SALT,
+                        AES_256_GCM,
+                        CHUNK_ORDERING_TYPE_UNSPECIFIED,
+                        createChunkProtoFor(TEST_HASH_1, TEST_CHUNK_1),
+                        createChunkProtoFor(TEST_HASH_2, TEST_CHUNK_2));
+        when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(chunkListingWithoutDocId);
+
+        // Chunk ordering doesn't matter for this test.
+        when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+        when(mCryptoBackupServer.uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), any()))
+                .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+        ChunkListing actualChunkListing =
+                mTask.performNonIncrementalBackup(
+                        mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT);
+
+        ChunkListing expectedChunkListing = CryptoTestUtils.clone(chunkListingWithoutDocId);
+        expectedChunkListing.documentId = TEST_NEW_DOCUMENT_ID;
+        assertChunkListingsAreEqual(actualChunkListing, expectedChunkListing);
+    }
+
+    @Test
+    public void performNonIncrementalBackup_buildsCorrectChunkMetadata() throws Exception {
+        setUpWithoutExistingBackup();
+
+        // Chunk listing doesn't matter for this test.
+        when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+
+        ChunkOrdering expectedOrdering =
+                CryptoTestUtils.newChunkOrdering(new int[10], TEST_CHECKSUM);
+        when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(expectedOrdering);
+
+        when(mCryptoBackupServer.uploadNonIncrementalBackup(eq(TEST_PACKAGE_NAME), any(), any()))
+                .thenReturn(TEST_NEW_DOCUMENT_ID);
+
+        mTask.performNonIncrementalBackup(
+                mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT);
+
+        verify(mBackupFileBuilder).finish(mMetadataCaptor.capture());
+
+        ChunksMetadata actualMetadata = mMetadataCaptor.getValue();
+        assertThat(actualMetadata.checksumType).isEqualTo(SHA_256);
+        assertThat(actualMetadata.cipherType).isEqualTo(AES_256_GCM);
+
+        ChunkOrdering actualOrdering = decryptChunkOrdering(actualMetadata.chunkOrdering);
+        assertThat(actualOrdering.checksum).isEqualTo(TEST_CHECKSUM);
+        assertThat(actualOrdering.starts).isEqualTo(expectedOrdering.starts);
+    }
+
+    @Test
+    public void cancel_incrementalBackup_doesNotUploadOrSaveChunkListing() throws Exception {
+        setUpWithExistingBackup();
+
+        // Chunk listing and ordering don't matter for this test.
+        when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+        when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+        mTask.cancel();
+        assertThrows(
+                CancellationException.class,
+                () ->
+                        mTask.performIncrementalBackup(
+                                mTertiaryKey, mWrappedTertiaryKey, mOldChunkListing));
+
+        verify(mCryptoBackupServer, never()).uploadIncrementalBackup(any(), any(), any(), any());
+        verify(mCryptoBackupServer, never()).uploadNonIncrementalBackup(any(), any(), any());
+    }
+
+    @Test
+    public void cancel_nonIncrementalBackup_doesNotUploadOrSaveChunkListing() throws Exception {
+        setUpWithoutExistingBackup();
+
+        // Chunk listing and ordering don't matter for this test.
+        when(mBackupFileBuilder.getNewChunkListing(any())).thenReturn(new ChunkListing());
+        when(mBackupFileBuilder.getNewChunkOrdering(TEST_CHECKSUM)).thenReturn(new ChunkOrdering());
+
+        mTask.cancel();
+        assertThrows(
+                CancellationException.class,
+                () ->
+                        mTask.performNonIncrementalBackup(
+                                mTertiaryKey, mWrappedTertiaryKey, TEST_FINGERPRINT_MIXER_SALT));
+
+        verify(mCryptoBackupServer, never()).uploadIncrementalBackup(any(), any(), any(), any());
+        verify(mCryptoBackupServer, never()).uploadNonIncrementalBackup(any(), any(), any());
+    }
+
+    /** Sets up a backup of [CHUNK 1][CHUNK 2] with no existing data. */
+    private void setUpWithoutExistingBackup() throws Exception {
+        Result result =
+                new Result(
+                        ImmutableList.of(TEST_HASH_1, TEST_HASH_2),
+                        ImmutableList.of(TEST_CHUNK_1, TEST_CHUNK_2),
+                        TEST_CHECKSUM);
+        when(mBackupEncrypter.backup(any(), eq(TEST_FINGERPRINT_MIXER_SALT), eq(ImmutableSet.of())))
+                .thenReturn(result);
+    }
+
+    /**
+     * Sets up a backup of [CHUNK 1][CHUNK 2][CHUNK 3] where the previous backup contained [CHUNK
+     * 1][CHUNK 3].
+     */
+    private void setUpWithExistingBackup() throws Exception {
+        mOldChunkListing =
+                CryptoTestUtils.newChunkListing(
+                        TEST_OLD_DOCUMENT_ID,
+                        TEST_FINGERPRINT_MIXER_SALT,
+                        AES_256_GCM,
+                        CHUNK_ORDERING_TYPE_UNSPECIFIED,
+                        createChunkProtoFor(TEST_HASH_1, TEST_CHUNK_1),
+                        createChunkProtoFor(TEST_HASH_3, TEST_CHUNK_3));
+
+        Result result =
+                new Result(
+                        ImmutableList.of(TEST_HASH_1, TEST_HASH_2, TEST_HASH_3),
+                        ImmutableList.of(TEST_CHUNK_2),
+                        TEST_CHECKSUM);
+        when(mBackupEncrypter.backup(
+                        any(),
+                        eq(TEST_FINGERPRINT_MIXER_SALT),
+                        eq(ImmutableSet.of(TEST_HASH_1, TEST_HASH_3))))
+                .thenReturn(result);
+    }
+
+    private ChunksMetadataProto.Chunk createChunkProtoFor(
+            ChunkHash chunkHash, EncryptedChunk encryptedChunk) {
+        return CryptoTestUtils.newChunk(
+                chunkHash, mEncryptedChunkEncoder.getEncodedLengthOfChunk(encryptedChunk));
+    }
+
+    private ChunkOrdering decryptChunkOrdering(byte[] encryptedOrdering) throws Exception {
+        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+        cipher.init(
+                Cipher.DECRYPT_MODE,
+                mTertiaryKey,
+                new GCMParameterSpec(
+                        GCM_TAG_LENGTH_BYTES * BITS_PER_BYTE,
+                        encryptedOrdering,
+                        /*offset=*/ 0,
+                        GCM_NONCE_LENGTH_BYTES));
+        byte[] decrypted =
+                cipher.doFinal(
+                        encryptedOrdering,
+                        GCM_NONCE_LENGTH_BYTES,
+                        encryptedOrdering.length - GCM_NONCE_LENGTH_BYTES);
+        return ChunkOrdering.parseFrom(decrypted);
+    }
+
+    // This method is needed because nano protobuf generated classes dont implmenent
+    // .equals
+    private void assertChunkListingsAreEqual(ChunkListing a, ChunkListing b) {
+        byte[] aBytes = MessageNano.toByteArray(a);
+        byte[] bBytes = MessageNano.toByteArray(b);
+
+        assertThat(aBytes).isEqualTo(bBytes);
+    }
+
+    @Implements(BackupFileBuilder.class)
+    public static class ShadowBackupFileBuilder {
+
+        private static BackupFileBuilder sInstance;
+
+        @Implementation
+        public static BackupFileBuilder createForNonIncremental(OutputStream outputStream) {
+            return sInstance;
+        }
+
+        @Implementation
+        public static BackupFileBuilder createForIncremental(
+                OutputStream outputStream, ChunkListing oldChunkListing) {
+            return sInstance;
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupDataProcessorTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupDataProcessorTest.java
new file mode 100644
index 0000000..675d03f
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupDataProcessorTest.java
@@ -0,0 +1,387 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.testng.Assert.assertThrows;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupTransport;
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.server.backup.encryption.FullBackupDataProcessor;
+import com.android.server.backup.encryption.chunking.ProtoStore;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.TertiaryKeyManager;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.testing.QueuingNonAutomaticExecutorService;
+
+import com.google.common.io.ByteStreams;
+import com.google.common.primitives.Bytes;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+
+import javax.crypto.spec.SecretKeySpec;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+@Config(
+        shadows = {
+            EncryptedFullBackupDataProcessorTest.ShadowEncryptedFullBackupTask.class,
+        })
+public class EncryptedFullBackupDataProcessorTest {
+
+    private static final String KEY_GENERATOR_ALGORITHM = "AES";
+
+    private static final String TEST_PACKAGE = "com.example.app1";
+    private static final byte[] TEST_DATA_1 = {1, 2, 3, 4};
+    private static final byte[] TEST_DATA_2 = {5, 6, 7, 8};
+
+    private final RecoverableKeyStoreSecondaryKey mTestSecondaryKey =
+            new RecoverableKeyStoreSecondaryKey(
+                    /*alias=*/ "test_key",
+                    new SecretKeySpec(
+                            new byte[] {
+                                1, 2, 3,
+                            },
+                            KEY_GENERATOR_ALGORITHM));
+
+    private QueuingNonAutomaticExecutorService mExecutorService;
+    private FullBackupDataProcessor mFullBackupDataProcessor;
+    @Mock private FullBackupDataProcessor.FullBackupCallbacks mFullBackupCallbacks;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+
+        mExecutorService = new QueuingNonAutomaticExecutorService();
+        mFullBackupDataProcessor =
+                new EncryptedFullBackupDataProcessor(
+                        ApplicationProvider.getApplicationContext(),
+                        mExecutorService,
+                        mock(CryptoBackupServer.class),
+                        new SecureRandom(),
+                        mTestSecondaryKey,
+                        TEST_PACKAGE);
+    }
+
+    @After
+    public void tearDown() {
+        ShadowEncryptedFullBackupTask.reset();
+    }
+
+    @Test
+    public void initiate_callTwice_throws() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(new byte[10]));
+
+        assertThrows(
+                IllegalStateException.class,
+                () -> mFullBackupDataProcessor.initiate(new ByteArrayInputStream(new byte[10])));
+    }
+
+    @Test
+    public void pushData_writesDataToTask() throws Exception {
+        byte[] inputData = Bytes.concat(TEST_DATA_1, TEST_DATA_2);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(inputData));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        mFullBackupDataProcessor.pushData(TEST_DATA_2.length);
+        finishBackupTask();
+        mFullBackupDataProcessor.finish();
+
+        byte[] result = ByteStreams.toByteArray(ShadowEncryptedFullBackupTask.sInputStream);
+        assertThat(result).isEqualTo(Bytes.concat(TEST_DATA_1, TEST_DATA_2));
+    }
+
+    @Test
+    public void pushData_noError_returnsOk() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        int result = mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTask();
+        mFullBackupDataProcessor.finish();
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_OK);
+    }
+
+    @Test
+    public void pushData_ioExceptionOnCopy_returnsError() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+
+        // Close the stream so there's an IO error when the processor tries to write to it.
+        ShadowEncryptedFullBackupTask.sInputStream.close();
+        int result = mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+
+        finishBackupTask();
+        mFullBackupDataProcessor.finish();
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_ERROR);
+    }
+
+    @Test
+    public void pushData_exceptionDuringUpload_returnsError() throws Exception {
+        byte[] inputData = Bytes.concat(TEST_DATA_1, TEST_DATA_2);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(inputData));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTaskWithException(new IOException("Test exception"));
+        int result = mFullBackupDataProcessor.pushData(TEST_DATA_2.length);
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_ERROR);
+    }
+
+    @Test
+    public void pushData_quotaExceptionDuringUpload_doesNotLogAndReturnsQuotaExceeded()
+            throws Exception {
+        mFullBackupDataProcessor.attachCallbacks(mFullBackupCallbacks);
+        byte[] inputData = Bytes.concat(TEST_DATA_1, TEST_DATA_2);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(inputData));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTaskWithException(new SizeQuotaExceededException());
+        int result = mFullBackupDataProcessor.pushData(TEST_DATA_2.length);
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_QUOTA_EXCEEDED);
+
+        verify(mFullBackupCallbacks, never()).onSuccess();
+        verify(mFullBackupCallbacks, never())
+                .onTransferFailed(); // FullBackupSession will handle this.
+    }
+
+    @Test
+    public void pushData_unexpectedEncryptedBackup_logs() throws Exception {
+        byte[] inputData = Bytes.concat(TEST_DATA_1, TEST_DATA_2);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(inputData));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTaskWithException(new GeneralSecurityException());
+        int result = mFullBackupDataProcessor.pushData(TEST_DATA_2.length);
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_ERROR);
+    }
+
+    @Test
+    public void pushData_permanentExceptionDuringUpload_callsErrorCallback() throws Exception {
+        mFullBackupDataProcessor.attachCallbacks(mFullBackupCallbacks);
+        byte[] inputData = Bytes.concat(TEST_DATA_1, TEST_DATA_2);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(inputData));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTaskWithException(new IOException());
+        mFullBackupDataProcessor.pushData(TEST_DATA_2.length);
+
+        verify(mFullBackupCallbacks, never()).onSuccess();
+        verify(mFullBackupCallbacks).onTransferFailed();
+    }
+
+    @Test
+    public void pushData_beforeInitiate_throws() {
+        assertThrows(
+                IllegalStateException.class,
+                () -> mFullBackupDataProcessor.pushData(/*numBytes=*/ 10));
+    }
+
+    @Test
+    public void cancel_cancelsTask() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        mFullBackupDataProcessor.cancel();
+
+        assertThat(ShadowEncryptedFullBackupTask.sCancelled).isTrue();
+    }
+
+    @Test
+    public void cancel_beforeInitiate_throws() {
+        assertThrows(IllegalStateException.class, () -> mFullBackupDataProcessor.cancel());
+    }
+
+    @Test
+    public void finish_noException_returnsTransportOk() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTask();
+        int result = mFullBackupDataProcessor.finish();
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_OK);
+    }
+
+    @Test
+    public void finish_exceptionDuringUpload_returnsTransportError() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTaskWithException(new IOException("Test exception"));
+        int result = mFullBackupDataProcessor.finish();
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_ERROR);
+    }
+
+    @Test
+    public void finish_successfulBackup_callsSuccessCallback() throws Exception {
+        mFullBackupDataProcessor.attachCallbacks(mFullBackupCallbacks);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTask();
+        mFullBackupDataProcessor.finish();
+
+        verify(mFullBackupCallbacks).onSuccess();
+        verify(mFullBackupCallbacks, never()).onTransferFailed();
+    }
+
+    @Test
+    public void finish_backupFailedWithPermanentError_callsErrorCallback() throws Exception {
+        mFullBackupDataProcessor.attachCallbacks(mFullBackupCallbacks);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTaskWithException(new IOException());
+        mFullBackupDataProcessor.finish();
+
+        verify(mFullBackupCallbacks, never()).onSuccess();
+        verify(mFullBackupCallbacks).onTransferFailed();
+    }
+
+    @Test
+    public void finish_backupFailedWithQuotaException_doesNotCallbackAndReturnsQuotaExceeded()
+            throws Exception {
+        mFullBackupDataProcessor.attachCallbacks(mFullBackupCallbacks);
+
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        finishBackupTaskWithException(new SizeQuotaExceededException());
+        int result = mFullBackupDataProcessor.finish();
+
+        assertThat(result).isEqualTo(BackupTransport.TRANSPORT_QUOTA_EXCEEDED);
+        verify(mFullBackupCallbacks, never()).onSuccess();
+        verify(mFullBackupCallbacks, never())
+                .onTransferFailed(); // FullBackupSession will handle this.
+    }
+
+    @Test
+    public void finish_beforeInitiate_throws() {
+        assertThrows(IllegalStateException.class, () -> mFullBackupDataProcessor.finish());
+    }
+
+    @Test
+    public void handleCheckSizeRejectionZeroBytes_cancelsTask() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(new byte[10]));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.handleCheckSizeRejectionZeroBytes();
+
+        assertThat(ShadowEncryptedFullBackupTask.sCancelled).isTrue();
+    }
+
+    @Test
+    public void handleCheckSizeRejectionQuotaExceeded_cancelsTask() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        mFullBackupDataProcessor.handleCheckSizeRejectionQuotaExceeded();
+
+        assertThat(ShadowEncryptedFullBackupTask.sCancelled).isTrue();
+    }
+
+    @Test
+    public void handleSendBytesQuotaExceeded_cancelsTask() throws Exception {
+        mFullBackupDataProcessor.initiate(new ByteArrayInputStream(TEST_DATA_1));
+        mFullBackupDataProcessor.start();
+        mFullBackupDataProcessor.pushData(TEST_DATA_1.length);
+        mFullBackupDataProcessor.handleSendBytesQuotaExceeded();
+
+        assertThat(ShadowEncryptedFullBackupTask.sCancelled).isTrue();
+    }
+
+    private void finishBackupTask() {
+        mExecutorService.runNext();
+    }
+
+    private void finishBackupTaskWithException(Exception exception) {
+        ShadowEncryptedFullBackupTask.sOnCallException = exception;
+        finishBackupTask();
+    }
+
+    @Implements(EncryptedFullBackupTask.class)
+    public static class ShadowEncryptedFullBackupTask {
+
+        private static InputStream sInputStream;
+        @Nullable private static Exception sOnCallException;
+        private static boolean sCancelled;
+
+        public void __constructor__(
+                ProtoStore<ChunksMetadataProto.ChunkListing> chunkListingStore,
+                TertiaryKeyManager tertiaryKeyManager,
+                EncryptedBackupTask task,
+                InputStream inputStream,
+                String packageName,
+                SecureRandom secureRandom) {
+            sInputStream = inputStream;
+        }
+
+        @Implementation
+        public Void call() throws Exception {
+            if (sOnCallException != null) {
+                throw sOnCallException;
+            }
+
+            return null;
+        }
+
+        @Implementation
+        public void cancel() {
+            sCancelled = true;
+        }
+
+        public static void reset() {
+            sOnCallException = null;
+            sCancelled = false;
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupTaskTest.java
new file mode 100644
index 0000000..096b2da
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullBackupTaskTest.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ProtoStore;
+import com.android.server.backup.encryption.chunking.cdc.FingerprintMixer;
+import com.android.server.backup.encryption.keys.TertiaryKeyManager;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto.ChunkListing;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto.WrappedKey;
+import com.android.server.backup.testing.CryptoTestUtils;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.Optional;
+
+import javax.crypto.SecretKey;
+
+@Config(shadows = {EncryptedBackupTaskTest.ShadowBackupFileBuilder.class})
+@RunWith(RobolectricTestRunner.class)
+public class EncryptedFullBackupTaskTest {
+    private static final String TEST_PACKAGE_NAME = "com.example.package";
+    private static final byte[] TEST_EXISTING_FINGERPRINT_MIXER_SALT =
+            Arrays.copyOf(new byte[] {11}, ChunkHash.HASH_LENGTH_BYTES);
+    private static final byte[] TEST_GENERATED_FINGERPRINT_MIXER_SALT =
+            Arrays.copyOf(new byte[] {22}, ChunkHash.HASH_LENGTH_BYTES);
+    private static final ChunkHash TEST_CHUNK_HASH_1 =
+            new ChunkHash(Arrays.copyOf(new byte[] {1}, ChunkHash.HASH_LENGTH_BYTES));
+    private static final ChunkHash TEST_CHUNK_HASH_2 =
+            new ChunkHash(Arrays.copyOf(new byte[] {2}, ChunkHash.HASH_LENGTH_BYTES));
+    private static final int TEST_CHUNK_LENGTH_1 = 20;
+    private static final int TEST_CHUNK_LENGTH_2 = 40;
+
+    @Mock private ProtoStore<ChunkListing> mChunkListingStore;
+    @Mock private TertiaryKeyManager mTertiaryKeyManager;
+    @Mock private InputStream mInputStream;
+    @Mock private EncryptedBackupTask mEncryptedBackupTask;
+    @Mock private SecretKey mTertiaryKey;
+    @Mock private SecureRandom mSecureRandom;
+
+    private EncryptedFullBackupTask mTask;
+    private ChunkListing mOldChunkListing;
+    private ChunkListing mNewChunkListing;
+    private WrappedKey mWrappedTertiaryKey;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        mWrappedTertiaryKey = new WrappedKey();
+        when(mTertiaryKeyManager.getKey()).thenReturn(mTertiaryKey);
+        when(mTertiaryKeyManager.getWrappedKey()).thenReturn(mWrappedTertiaryKey);
+
+        mOldChunkListing =
+                CryptoTestUtils.newChunkListing(
+                        /* docId */ null,
+                        TEST_EXISTING_FINGERPRINT_MIXER_SALT,
+                        ChunksMetadataProto.AES_256_GCM,
+                        ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED,
+                        CryptoTestUtils.newChunk(TEST_CHUNK_HASH_1.getHash(), TEST_CHUNK_LENGTH_1));
+        mNewChunkListing =
+                CryptoTestUtils.newChunkListing(
+                        /* docId */ null,
+                        /* fingerprintSalt */ null,
+                        ChunksMetadataProto.AES_256_GCM,
+                        ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED,
+                        CryptoTestUtils.newChunk(TEST_CHUNK_HASH_1.getHash(), TEST_CHUNK_LENGTH_1),
+                        CryptoTestUtils.newChunk(TEST_CHUNK_HASH_2.getHash(), TEST_CHUNK_LENGTH_2));
+        when(mEncryptedBackupTask.performNonIncrementalBackup(any(), any(), any()))
+                .thenReturn(mNewChunkListing);
+        when(mEncryptedBackupTask.performIncrementalBackup(any(), any(), any()))
+                .thenReturn(mNewChunkListing);
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME)).thenReturn(Optional.empty());
+
+        doAnswer(invocation -> {
+            byte[] byteArray = (byte[]) invocation.getArguments()[0];
+            System.arraycopy(
+                    TEST_GENERATED_FINGERPRINT_MIXER_SALT,
+                    /* srcPos */ 0,
+                    byteArray,
+                    /* destPos */ 0,
+                    FingerprintMixer.SALT_LENGTH_BYTES);
+            return null;
+        })
+                .when(mSecureRandom)
+                .nextBytes(any(byte[].class));
+
+        mTask =
+                new EncryptedFullBackupTask(
+                        mChunkListingStore,
+                        mTertiaryKeyManager,
+                        mEncryptedBackupTask,
+                        mInputStream,
+                        TEST_PACKAGE_NAME,
+                        mSecureRandom);
+    }
+
+    @Test
+    public void call_existingChunkListingButTertiaryKeyRotated_performsNonIncrementalBackup()
+            throws Exception {
+        when(mTertiaryKeyManager.wasKeyRotated()).thenReturn(true);
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME))
+                .thenReturn(Optional.of(mOldChunkListing));
+
+        mTask.call();
+
+        verify(mEncryptedBackupTask)
+                .performNonIncrementalBackup(
+                        eq(mTertiaryKey),
+                        eq(mWrappedTertiaryKey),
+                        eq(TEST_GENERATED_FINGERPRINT_MIXER_SALT));
+    }
+
+    @Test
+    public void call_noExistingChunkListing_performsNonIncrementalBackup() throws Exception {
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME)).thenReturn(Optional.empty());
+        mTask.call();
+        verify(mEncryptedBackupTask)
+                .performNonIncrementalBackup(
+                        eq(mTertiaryKey),
+                        eq(mWrappedTertiaryKey),
+                        eq(TEST_GENERATED_FINGERPRINT_MIXER_SALT));
+    }
+
+    @Test
+    public void call_existingChunkListing_performsIncrementalBackup() throws Exception {
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME))
+                .thenReturn(Optional.of(mOldChunkListing));
+        mTask.call();
+        verify(mEncryptedBackupTask)
+                .performIncrementalBackup(
+                        eq(mTertiaryKey), eq(mWrappedTertiaryKey), eq(mOldChunkListing));
+    }
+
+    @Test
+    public void
+            call_existingChunkListingWithNoFingerprintMixerSalt_doesntSetSaltBeforeIncBackup()
+                    throws Exception {
+        mOldChunkListing.fingerprintMixerSalt = new byte[0];
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME))
+                .thenReturn(Optional.of(mOldChunkListing));
+
+        mTask.call();
+
+        verify(mEncryptedBackupTask)
+                .performIncrementalBackup(
+                        eq(mTertiaryKey), eq(mWrappedTertiaryKey), eq(mOldChunkListing));
+    }
+
+    @Test
+    public void call_noExistingChunkListing_storesNewChunkListing() throws Exception {
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME)).thenReturn(Optional.empty());
+        mTask.call();
+        verify(mChunkListingStore).saveProto(TEST_PACKAGE_NAME, mNewChunkListing);
+    }
+
+    @Test
+    public void call_existingChunkListing_storesNewChunkListing() throws Exception {
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME))
+                .thenReturn(Optional.of(mOldChunkListing));
+        mTask.call();
+        verify(mChunkListingStore).saveProto(TEST_PACKAGE_NAME, mNewChunkListing);
+    }
+
+    @Test
+    public void call_exceptionDuringBackup_doesNotSaveNewChunkListing() throws Exception {
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME)).thenReturn(Optional.empty());
+        when(mEncryptedBackupTask.performNonIncrementalBackup(any(), any(), any()))
+                .thenThrow(GeneralSecurityException.class);
+
+        assertThrows(Exception.class, () -> mTask.call());
+
+        assertThat(mChunkListingStore.loadProto(TEST_PACKAGE_NAME).isPresent()).isFalse();
+    }
+
+    @Test
+    public void call_incrementalThrowsPermanentException_clearsState() throws Exception {
+        when(mChunkListingStore.loadProto(TEST_PACKAGE_NAME))
+                .thenReturn(Optional.of(mOldChunkListing));
+        when(mEncryptedBackupTask.performIncrementalBackup(any(), any(), any()))
+                .thenThrow(IOException.class);
+
+        assertThrows(IOException.class, () -> mTask.call());
+
+        verify(mChunkListingStore).deleteProto(TEST_PACKAGE_NAME);
+    }
+
+    @Test
+    public void call_closesInputStream() throws Exception {
+        mTask.call();
+        verify(mInputStream).close();
+    }
+
+    @Test
+    public void cancel_cancelsTask() throws Exception {
+        mTask.cancel();
+        verify(mEncryptedBackupTask).cancel();
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullRestoreTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullRestoreTaskTest.java
new file mode 100644
index 0000000..0affacd
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedFullRestoreTaskTest.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+import static java.util.stream.Collectors.toList;
+
+import com.android.server.backup.encryption.FullRestoreDownloader;
+
+import com.google.common.io.Files;
+import com.google.common.primitives.Bytes;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+
+@RunWith(RobolectricTestRunner.class)
+public class EncryptedFullRestoreTaskTest {
+    private static final int TEST_BUFFER_SIZE = 10;
+    private static final byte[] TEST_ENCRYPTED_DATA = {1, 2, 3, 4, 5, 6};
+    private static final byte[] TEST_DECRYPTED_DATA = fakeDecrypt(TEST_ENCRYPTED_DATA);
+
+    @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+    @Mock private BackupFileDecryptorTask mDecryptorTask;
+
+    private File mFolder;
+    private FakeFullRestoreDownloader mFullRestorePackageWrapper;
+    private EncryptedFullRestoreTask mTask;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        mFolder = temporaryFolder.newFolder();
+        mFullRestorePackageWrapper = new FakeFullRestoreDownloader(TEST_ENCRYPTED_DATA);
+
+        doAnswer(
+            invocation -> {
+                File source = invocation.getArgument(0);
+                DecryptedChunkOutput target = invocation.getArgument(1);
+                byte[] decrypted = fakeDecrypt(Files.toByteArray(source));
+                target.open();
+                target.processChunk(decrypted, decrypted.length);
+                target.close();
+                return null;
+            })
+                .when(mDecryptorTask)
+                .decryptFile(any(), any());
+
+        mTask = new EncryptedFullRestoreTask(mFolder, mFullRestorePackageWrapper, mDecryptorTask);
+    }
+
+    @Test
+    public void readNextChunk_downloadsAndDecryptsBackup() throws Exception {
+        ByteArrayOutputStream decryptedOutput = new ByteArrayOutputStream();
+
+        byte[] buffer = new byte[TEST_BUFFER_SIZE];
+        int bytesRead = mTask.readNextChunk(buffer);
+        while (bytesRead != -1) {
+            decryptedOutput.write(buffer, 0, bytesRead);
+            bytesRead = mTask.readNextChunk(buffer);
+        }
+
+        assertThat(decryptedOutput.toByteArray()).isEqualTo(TEST_DECRYPTED_DATA);
+    }
+
+    @Test
+    public void finish_deletesTemporaryFiles() throws Exception {
+        mTask.readNextChunk(new byte[10]);
+        mTask.finish(FullRestoreDownloader.FinishType.UNKNOWN_FINISH);
+
+        assertThat(mFolder.listFiles()).isEmpty();
+    }
+
+    /** Fake package wrapper which returns data from a byte array. */
+    private static class FakeFullRestoreDownloader extends FullRestoreDownloader {
+        private final ByteArrayInputStream mData;
+
+        FakeFullRestoreDownloader(byte[] data) {
+            // We override all methods of the superclass, so it does not require any collaborators.
+            super();
+            mData = new ByteArrayInputStream(data);
+        }
+
+        @Override
+        public int readNextChunk(byte[] buffer) throws IOException {
+            return mData.read(buffer);
+        }
+
+        @Override
+        public void finish(FinishType finishType) {
+            // Nothing to do.
+        }
+    }
+
+    /** Fake decrypts a byte array by subtracting 1 from each byte. */
+    private static byte[] fakeDecrypt(byte[] input) {
+        return Bytes.toArray(Bytes.asList(input).stream().map(b -> b + 1).collect(toList()));
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedKvBackupTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedKvBackupTaskTest.java
new file mode 100644
index 0000000..fa4fef5
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedKvBackupTaskTest.java
@@ -0,0 +1,356 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertThrows;
+
+import android.app.Application;
+import android.util.Pair;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ProtoStore;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.TertiaryKeyManager;
+import com.android.server.backup.encryption.kv.KeyValueListingBuilder;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+import com.android.server.backup.testing.CryptoTestUtils;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.crypto.SecretKey;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+
+@RunWith(RobolectricTestRunner.class)
+public class EncryptedKvBackupTaskTest {
+    private static final boolean INCREMENTAL = true;
+    private static final boolean NON_INCREMENTAL = false;
+
+    private static final String TEST_PACKAGE_1 = "com.example.app1";
+    private static final String TEST_KEY_1 = "key_1";
+    private static final String TEST_KEY_2 = "key_2";
+    private static final ChunkHash TEST_HASH_1 =
+            new ChunkHash(Arrays.copyOf(new byte[] {1}, ChunkHash.HASH_LENGTH_BYTES));
+    private static final ChunkHash TEST_HASH_2 =
+            new ChunkHash(Arrays.copyOf(new byte[] {2}, ChunkHash.HASH_LENGTH_BYTES));
+    private static final int TEST_LENGTH_1 = 200;
+    private static final int TEST_LENGTH_2 = 300;
+
+    @Rule public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
+
+    @Captor private ArgumentCaptor<ChunksMetadataProto.ChunkListing> mChunkListingCaptor;
+
+    @Mock private TertiaryKeyManager mTertiaryKeyManager;
+    @Mock private RecoverableKeyStoreSecondaryKey mSecondaryKey;
+    @Mock private ProtoStore<KeyValueListingProto.KeyValueListing> mKeyValueListingStore;
+    @Mock private ProtoStore<ChunksMetadataProto.ChunkListing> mChunkListingStore;
+    @Mock private KvBackupEncrypter mKvBackupEncrypter;
+    @Mock private EncryptedBackupTask mEncryptedBackupTask;
+    @Mock private SecretKey mTertiaryKey;
+
+    private WrappedKeyProto.WrappedKey mWrappedTertiaryKey;
+    private KeyValueListingProto.KeyValueListing mNewKeyValueListing;
+    private ChunksMetadataProto.ChunkListing mNewChunkListing;
+    private EncryptedKvBackupTask mTask;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        Application application = ApplicationProvider.getApplicationContext();
+        mKeyValueListingStore = ProtoStore.createKeyValueListingStore(application);
+        mChunkListingStore = ProtoStore.createChunkListingStore(application);
+
+        mWrappedTertiaryKey = new WrappedKeyProto.WrappedKey();
+
+        when(mTertiaryKeyManager.wasKeyRotated()).thenReturn(false);
+        when(mTertiaryKeyManager.getKey()).thenReturn(mTertiaryKey);
+        when(mTertiaryKeyManager.getWrappedKey()).thenReturn(mWrappedTertiaryKey);
+
+        mNewKeyValueListing =
+                createKeyValueListing(
+                        CryptoTestUtils.mapOf(
+                                new Pair<>(TEST_KEY_1, TEST_HASH_1),
+                                new Pair<>(TEST_KEY_2, TEST_HASH_2)));
+        mNewChunkListing =
+                createChunkListing(
+                        CryptoTestUtils.mapOf(
+                                new Pair<>(TEST_HASH_1, TEST_LENGTH_1),
+                                new Pair<>(TEST_HASH_2, TEST_LENGTH_2)));
+        when(mKvBackupEncrypter.getNewKeyValueListing()).thenReturn(mNewKeyValueListing);
+        when(mEncryptedBackupTask.performIncrementalBackup(
+                        eq(mTertiaryKey), eq(mWrappedTertiaryKey), any()))
+                .thenReturn(mNewChunkListing);
+        when(mEncryptedBackupTask.performNonIncrementalBackup(
+                        eq(mTertiaryKey), eq(mWrappedTertiaryKey), any()))
+                .thenReturn(mNewChunkListing);
+
+        mTask =
+                new EncryptedKvBackupTask(
+                        mTertiaryKeyManager,
+                        mKeyValueListingStore,
+                        mSecondaryKey,
+                        mChunkListingStore,
+                        mKvBackupEncrypter,
+                        mEncryptedBackupTask,
+                        TEST_PACKAGE_1);
+    }
+
+    @Test
+    public void testPerformBackup_rotationRequired_deletesListings() throws Exception {
+        mKeyValueListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createKeyValueListing(CryptoTestUtils.mapOf(new Pair<>(TEST_KEY_1, TEST_HASH_1))));
+        mChunkListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createChunkListing(CryptoTestUtils.mapOf(new Pair<>(TEST_HASH_1, TEST_LENGTH_1))));
+
+        when(mTertiaryKeyManager.wasKeyRotated()).thenReturn(true);
+        // Throw an IOException so it aborts before saving the new listings.
+        when(mEncryptedBackupTask.performNonIncrementalBackup(any(), any(), any()))
+                .thenThrow(IOException.class);
+
+        assertThrows(IOException.class, () -> mTask.performBackup(NON_INCREMENTAL));
+
+        assertFalse(mKeyValueListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+        assertFalse(mChunkListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+    }
+
+    @Test
+    public void testPerformBackup_rotationRequiredButIncremental_throws() throws Exception {
+        mKeyValueListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createKeyValueListing(CryptoTestUtils.mapOf(new Pair<>(TEST_KEY_1, TEST_HASH_1))));
+        mChunkListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createChunkListing(CryptoTestUtils.mapOf(new Pair<>(TEST_HASH_1, TEST_LENGTH_1))));
+
+        when(mTertiaryKeyManager.wasKeyRotated()).thenReturn(true);
+
+        assertThrows(NonIncrementalBackupRequiredException.class,
+                () -> mTask.performBackup(INCREMENTAL));
+    }
+
+    @Test
+    public void testPerformBackup_rotationRequiredAndNonIncremental_performsNonIncrementalBackup()
+            throws Exception {
+        mKeyValueListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createKeyValueListing(CryptoTestUtils.mapOf(new Pair<>(TEST_KEY_1, TEST_HASH_1))));
+        mChunkListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createChunkListing(CryptoTestUtils.mapOf(new Pair<>(TEST_HASH_1, TEST_LENGTH_1))));
+
+        when(mTertiaryKeyManager.wasKeyRotated()).thenReturn(true);
+
+        mTask.performBackup(NON_INCREMENTAL);
+
+        verify(mEncryptedBackupTask)
+                .performNonIncrementalBackup(eq(mTertiaryKey), eq(mWrappedTertiaryKey), any());
+    }
+
+    @Test
+    public void testPerformBackup_existingStateButNonIncremental_deletesListings() throws Exception {
+        mKeyValueListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createKeyValueListing(CryptoTestUtils.mapOf(new Pair<>(TEST_KEY_1, TEST_HASH_1))));
+        mChunkListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createChunkListing(CryptoTestUtils.mapOf(new Pair<>(TEST_HASH_1, TEST_LENGTH_1))));
+
+        // Throw an IOException so it aborts before saving the new listings.
+        when(mEncryptedBackupTask.performNonIncrementalBackup(any(), any(), any()))
+                .thenThrow(IOException.class);
+
+        assertThrows(IOException.class, () -> mTask.performBackup(NON_INCREMENTAL));
+
+        assertFalse(mKeyValueListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+        assertFalse(mChunkListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+    }
+
+    @Test
+    public void testPerformBackup_keyValueListingMissing_deletesChunkListingAndPerformsNonIncremental()
+            throws Exception {
+        mChunkListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createChunkListing(CryptoTestUtils.mapOf(new Pair<>(TEST_HASH_1, TEST_LENGTH_1))));
+
+        // Throw an IOException so it aborts before saving the new listings.
+        when(mEncryptedBackupTask.performNonIncrementalBackup(any(), any(), any()))
+                .thenThrow(IOException.class);
+
+        assertThrows(IOException.class, () -> mTask.performBackup(NON_INCREMENTAL));
+
+        verify(mEncryptedBackupTask).performNonIncrementalBackup(any(), any(), any());
+        assertFalse(mKeyValueListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+        assertFalse(mChunkListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+    }
+
+    @Test
+    public void testPerformBackup_chunkListingMissing_deletesKeyValueListingAndPerformsNonIncremental()
+            throws Exception {
+        mKeyValueListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createKeyValueListing(CryptoTestUtils.mapOf(new Pair<>(TEST_KEY_1, TEST_HASH_1))));
+
+        // Throw an IOException so it aborts before saving the new listings.
+        when(mEncryptedBackupTask.performNonIncrementalBackup(any(), any(), any()))
+                .thenThrow(IOException.class);
+
+        assertThrows(IOException.class, () -> mTask.performBackup(NON_INCREMENTAL));
+
+        verify(mEncryptedBackupTask).performNonIncrementalBackup(any(), any(), any());
+        assertFalse(mKeyValueListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+        assertFalse(mChunkListingStore.loadProto(TEST_PACKAGE_1).isPresent());
+    }
+
+    @Test
+    public void testPerformBackup_existingStateAndIncremental_performsIncrementalBackup()
+            throws Exception {
+        mKeyValueListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createKeyValueListing(CryptoTestUtils.mapOf(new Pair<>(TEST_KEY_1, TEST_HASH_1))));
+        ChunksMetadataProto.ChunkListing oldChunkListing =
+                createChunkListing(CryptoTestUtils.mapOf(new Pair<>(TEST_HASH_1, TEST_LENGTH_1)));
+        mChunkListingStore.saveProto(TEST_PACKAGE_1, oldChunkListing);
+
+        mTask.performBackup(INCREMENTAL);
+
+        verify(mEncryptedBackupTask)
+                .performIncrementalBackup(
+                        eq(mTertiaryKey), eq(mWrappedTertiaryKey), mChunkListingCaptor.capture());
+        assertChunkListingsEqual(mChunkListingCaptor.getValue(), oldChunkListing);
+    }
+
+    @Test
+    public void testPerformBackup_noExistingStateAndNonIncremental_performsNonIncrementalBackup()
+            throws Exception {
+        mTask.performBackup(NON_INCREMENTAL);
+
+        verify(mEncryptedBackupTask)
+                .performNonIncrementalBackup(eq(mTertiaryKey), eq(mWrappedTertiaryKey), eq(null));
+    }
+
+    @Test
+    public void testPerformBackup_incremental_savesNewListings() throws Exception {
+        mKeyValueListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createKeyValueListing(CryptoTestUtils.mapOf(new Pair<>(TEST_KEY_1, TEST_HASH_1))));
+        mChunkListingStore.saveProto(
+                TEST_PACKAGE_1,
+                createChunkListing(CryptoTestUtils.mapOf(new Pair<>(TEST_HASH_1, TEST_LENGTH_1))));
+
+        mTask.performBackup(INCREMENTAL);
+
+        KeyValueListingProto.KeyValueListing actualKeyValueListing =
+                mKeyValueListingStore.loadProto(TEST_PACKAGE_1).get();
+        ChunksMetadataProto.ChunkListing actualChunkListing =
+                mChunkListingStore.loadProto(TEST_PACKAGE_1).get();
+        assertKeyValueListingsEqual(actualKeyValueListing, mNewKeyValueListing);
+        assertChunkListingsEqual(actualChunkListing, mNewChunkListing);
+    }
+
+    @Test
+    public void testPerformBackup_nonIncremental_savesNewListings() throws Exception {
+        mTask.performBackup(NON_INCREMENTAL);
+
+        KeyValueListingProto.KeyValueListing actualKeyValueListing =
+                mKeyValueListingStore.loadProto(TEST_PACKAGE_1).get();
+        ChunksMetadataProto.ChunkListing actualChunkListing =
+                mChunkListingStore.loadProto(TEST_PACKAGE_1).get();
+        assertKeyValueListingsEqual(actualKeyValueListing, mNewKeyValueListing);
+        assertChunkListingsEqual(actualChunkListing, mNewChunkListing);
+    }
+
+    private static KeyValueListingProto.KeyValueListing createKeyValueListing(
+            Map<String, ChunkHash> pairs) {
+        return new KeyValueListingBuilder().addAll(pairs).build();
+    }
+
+    private static ChunksMetadataProto.ChunkListing createChunkListing(
+            Map<ChunkHash, Integer> chunks) {
+        ChunksMetadataProto.Chunk[] listingChunks = new ChunksMetadataProto.Chunk[chunks.size()];
+        int chunksAdded = 0;
+        for (Entry<ChunkHash, Integer> entry : chunks.entrySet()) {
+            listingChunks[chunksAdded] = CryptoTestUtils.newChunk(entry.getKey(), entry.getValue());
+            chunksAdded++;
+        }
+        return CryptoTestUtils.newChunkListingWithoutDocId(
+                /* fingerprintSalt */ new byte[0],
+                ChunksMetadataProto.AES_256_GCM,
+                ChunksMetadataProto.CHUNK_ORDERING_TYPE_UNSPECIFIED,
+                listingChunks);
+    }
+
+    private static void assertKeyValueListingsEqual(
+            KeyValueListingProto.KeyValueListing actual,
+            KeyValueListingProto.KeyValueListing expected) {
+        KeyValueListingProto.KeyValueEntry[] actualEntries = actual.entries;
+        KeyValueListingProto.KeyValueEntry[] expectedEntries = expected.entries;
+        assertThat(actualEntries.length).isEqualTo(expectedEntries.length);
+        for (int i = 0; i < actualEntries.length; i++) {
+            assertWithMessage("entry " + i)
+                    .that(actualEntries[i].key)
+                    .isEqualTo(expectedEntries[i].key);
+            assertWithMessage("entry " + i)
+                    .that(actualEntries[i].hash)
+                    .isEqualTo(expectedEntries[i].hash);
+        }
+    }
+
+    private static void assertChunkListingsEqual(
+            ChunksMetadataProto.ChunkListing actual, ChunksMetadataProto.ChunkListing expected) {
+        ChunksMetadataProto.Chunk[] actualChunks = actual.chunks;
+        ChunksMetadataProto.Chunk[] expectedChunks = expected.chunks;
+        assertThat(actualChunks.length).isEqualTo(expectedChunks.length);
+        for (int i = 0; i < actualChunks.length; i++) {
+            assertWithMessage("chunk " + i)
+                    .that(actualChunks[i].hash)
+                    .isEqualTo(expectedChunks[i].hash);
+            assertWithMessage("chunk " + i)
+                    .that(actualChunks[i].length)
+                    .isEqualTo(expectedChunks[i].length);
+        }
+        assertThat(actual.cipherType).isEqualTo(expected.cipherType);
+        assertThat(actual.documentId)
+                .isEqualTo(expected.documentId == null ? "" : expected.documentId);
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedKvRestoreTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedKvRestoreTaskTest.java
new file mode 100644
index 0000000..6666d95
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/EncryptedKvRestoreTaskTest.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.os.ParcelFileDescriptor;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.testing.CryptoTestUtils;
+import com.android.server.testing.shadows.DataEntity;
+import com.android.server.testing.shadows.ShadowBackupDataOutput;
+
+import com.google.protobuf.nano.MessageNano;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+@Config(shadows = {ShadowBackupDataOutput.class})
+@RunWith(RobolectricTestRunner.class)
+public class EncryptedKvRestoreTaskTest {
+    private static final String TEST_KEY_1 = "test_key_1";
+    private static final String TEST_KEY_2 = "test_key_2";
+    private static final String TEST_KEY_3 = "test_key_3";
+    private static final byte[] TEST_VALUE_1 = {1, 2, 3};
+    private static final byte[] TEST_VALUE_2 = {4, 5, 6};
+    private static final byte[] TEST_VALUE_3 = {20, 25, 30, 35};
+
+    @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+    private File temporaryDirectory;
+
+    @Mock private ParcelFileDescriptor mParcelFileDescriptor;
+    @Mock private ChunkHasher mChunkHasher;
+    @Mock private FullRestoreToFileTask mFullRestoreToFileTask;
+    @Mock private BackupFileDecryptorTask mBackupFileDecryptorTask;
+
+    private EncryptedKvRestoreTask task;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        when(mChunkHasher.computeHash(any()))
+                .thenAnswer(invocation -> fakeHash(invocation.getArgument(0)));
+        doAnswer(invocation -> writeTestPairsToFile(invocation.getArgument(0)))
+                .when(mFullRestoreToFileTask)
+                .restoreToFile(any());
+        doAnswer(
+                        invocation ->
+                                readPairsFromFile(
+                                        invocation.getArgument(0), invocation.getArgument(1)))
+                .when(mBackupFileDecryptorTask)
+                .decryptFile(any(), any());
+
+        temporaryDirectory = temporaryFolder.newFolder();
+        task =
+                new EncryptedKvRestoreTask(
+                        temporaryDirectory,
+                        mChunkHasher,
+                        mFullRestoreToFileTask,
+                        mBackupFileDecryptorTask);
+    }
+
+    @Test
+    public void testGetRestoreData_writesPairsToOutputInOrder() throws Exception {
+        task.getRestoreData(mParcelFileDescriptor);
+
+        assertThat(ShadowBackupDataOutput.getEntities())
+                .containsExactly(
+                        new DataEntity(TEST_KEY_1, TEST_VALUE_1),
+                        new DataEntity(TEST_KEY_2, TEST_VALUE_2),
+                        new DataEntity(TEST_KEY_3, TEST_VALUE_3))
+                .inOrder();
+    }
+
+    @Test
+    public void testGetRestoreData_exceptionDuringDecryption_throws() throws Exception {
+        doThrow(IOException.class).when(mBackupFileDecryptorTask).decryptFile(any(), any());
+        assertThrows(IOException.class, () -> task.getRestoreData(mParcelFileDescriptor));
+    }
+
+    @Test
+    public void testGetRestoreData_exceptionDuringDownload_throws() throws Exception {
+        doThrow(IOException.class).when(mFullRestoreToFileTask).restoreToFile(any());
+        assertThrows(IOException.class, () -> task.getRestoreData(mParcelFileDescriptor));
+    }
+
+    @Test
+    public void testGetRestoreData_exceptionDuringDecryption_deletesTemporaryFiles() throws Exception {
+        doThrow(InvalidKeyException.class).when(mBackupFileDecryptorTask).decryptFile(any(), any());
+        assertThrows(InvalidKeyException.class, () -> task.getRestoreData(mParcelFileDescriptor));
+        assertThat(temporaryDirectory.listFiles()).isEmpty();
+    }
+
+    @Test
+    public void testGetRestoreData_exceptionDuringDownload_deletesTemporaryFiles() throws Exception {
+        doThrow(IOException.class).when(mFullRestoreToFileTask).restoreToFile(any());
+        assertThrows(IOException.class, () -> task.getRestoreData(mParcelFileDescriptor));
+        assertThat(temporaryDirectory.listFiles()).isEmpty();
+    }
+
+    private static Void writeTestPairsToFile(File file) throws IOException {
+        // Write the pairs out of order to check the task sorts them.
+        Set<byte[]> pairs =
+                new HashSet<>(
+                        Arrays.asList(
+                                createPair(TEST_KEY_1, TEST_VALUE_1),
+                                createPair(TEST_KEY_3, TEST_VALUE_3),
+                                createPair(TEST_KEY_2, TEST_VALUE_2)));
+
+        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
+            oos.writeObject(pairs);
+        }
+        return null;
+    }
+
+    private static Void readPairsFromFile(File file, DecryptedChunkOutput decryptedChunkOutput)
+            throws IOException, ClassNotFoundException, InvalidKeyException,
+                    NoSuchAlgorithmException {
+        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
+                DecryptedChunkOutput output = decryptedChunkOutput.open()) {
+            Set<byte[]> pairs = readPairs(ois);
+            for (byte[] pair : pairs) {
+                output.processChunk(pair, pair.length);
+            }
+        }
+
+        return null;
+    }
+
+    private static byte[] createPair(String key, byte[] value) {
+        return MessageNano.toByteArray(CryptoTestUtils.newPair(key, value));
+    }
+
+    @SuppressWarnings("unchecked") // deserialization.
+    private static Set<byte[]> readPairs(ObjectInputStream ois)
+            throws IOException, ClassNotFoundException {
+        return (Set<byte[]>) ois.readObject();
+    }
+
+    private static ChunkHash fakeHash(byte[] data) {
+        return new ChunkHash(Arrays.copyOf(data, ChunkHash.HASH_LENGTH_BYTES));
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/FullRestoreToFileTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/FullRestoreToFileTaskTest.java
new file mode 100644
index 0000000..de8b734
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/FullRestoreToFileTaskTest.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.platform.test.annotations.Presubmit;
+
+import com.android.server.backup.encryption.FullRestoreDownloader;
+import com.android.server.backup.encryption.FullRestoreDownloader.FinishType;
+
+import com.google.common.io.Files;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.util.Random;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+public class FullRestoreToFileTaskTest {
+    private static final int TEST_RANDOM_SEED = 34;
+    private static final int TEST_MAX_CHUNK_SIZE_BYTES = 5;
+    private static final int TEST_DATA_LENGTH_BYTES = TEST_MAX_CHUNK_SIZE_BYTES * 20;
+
+    @Rule public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
+
+    private byte[] mTestData;
+    private File mTargetFile;
+    private FakeFullRestoreDownloader mFakeFullRestoreDownloader;
+    @Mock private FullRestoreDownloader mMockFullRestoreDownloader;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        mTargetFile = mTemporaryFolder.newFile();
+
+        mTestData = new byte[TEST_DATA_LENGTH_BYTES];
+        new Random(TEST_RANDOM_SEED).nextBytes(mTestData);
+        mFakeFullRestoreDownloader = new FakeFullRestoreDownloader(mTestData);
+    }
+
+    private FullRestoreToFileTask createTaskWithFakeDownloader() {
+        return new FullRestoreToFileTask(mFakeFullRestoreDownloader, TEST_MAX_CHUNK_SIZE_BYTES);
+    }
+
+    private FullRestoreToFileTask createTaskWithMockDownloader() {
+        return new FullRestoreToFileTask(mMockFullRestoreDownloader, TEST_MAX_CHUNK_SIZE_BYTES);
+    }
+
+    @Test
+    public void restoreToFile_readsDataAndWritesToFile() throws Exception {
+        FullRestoreToFileTask task = createTaskWithFakeDownloader();
+        task.restoreToFile(mTargetFile);
+        assertThat(Files.toByteArray(mTargetFile)).isEqualTo(mTestData);
+    }
+
+    @Test
+    public void restoreToFile_noErrors_closesDownloaderWithFinished() throws Exception {
+        FullRestoreToFileTask task = createTaskWithMockDownloader();
+        when(mMockFullRestoreDownloader.readNextChunk(any())).thenReturn(-1);
+
+        task.restoreToFile(mTargetFile);
+
+        verify(mMockFullRestoreDownloader).finish(FinishType.FINISHED);
+    }
+
+    @Test
+    public void restoreToFile_ioException_closesDownloaderWithTransferFailure() throws Exception {
+        FullRestoreToFileTask task = createTaskWithMockDownloader();
+        when(mMockFullRestoreDownloader.readNextChunk(any())).thenThrow(IOException.class);
+
+        assertThrows(IOException.class, () -> task.restoreToFile(mTargetFile));
+
+        verify(mMockFullRestoreDownloader).finish(FinishType.TRANSFER_FAILURE);
+    }
+
+    /** Fake package wrapper which returns data from a byte array. */
+    private static class FakeFullRestoreDownloader extends FullRestoreDownloader {
+
+        private final ByteArrayInputStream mData;
+
+        FakeFullRestoreDownloader(byte[] data) {
+            // We override all methods of the superclass, so it does not require any collaborators.
+            super();
+            this.mData = new ByteArrayInputStream(data);
+        }
+
+        @Override
+        public int readNextChunk(byte[] buffer) throws IOException {
+            return mData.read(buffer);
+        }
+
+        @Override
+        public void finish(FinishType finishType) {
+            // Do nothing.
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/InitializeRecoverableSecondaryKeyTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/InitializeRecoverableSecondaryKeyTaskTest.java
new file mode 100644
index 0000000..4a7ae03
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/InitializeRecoverableSecondaryKeyTaskTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static android.security.keystore.recovery.RecoveryController.RECOVERY_STATUS_PERMANENT_FAILURE;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.app.Application;
+import android.security.keystore.recovery.RecoveryController;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.server.backup.encryption.CryptoSettings;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKeyManager;
+import com.android.server.testing.fakes.FakeCryptoBackupServer;
+import com.android.server.testing.shadows.ShadowRecoveryController;
+
+import java.security.InvalidKeyException;
+import java.security.SecureRandom;
+import java.util.Optional;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+@Config(shadows = {ShadowRecoveryController.class})
+@RunWith(RobolectricTestRunner.class)
+public class InitializeRecoverableSecondaryKeyTaskTest {
+    @Mock private CryptoSettings mMockCryptoSettings;
+
+    private Application mApplication;
+    private InitializeRecoverableSecondaryKeyTask mTask;
+    private CryptoSettings mCryptoSettings;
+    private FakeCryptoBackupServer mFakeCryptoBackupServer;
+    private RecoverableKeyStoreSecondaryKeyManager mSecondaryKeyManager;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        ShadowRecoveryController.reset();
+
+        mApplication = ApplicationProvider.getApplicationContext();
+        mFakeCryptoBackupServer = new FakeCryptoBackupServer();
+        mCryptoSettings = CryptoSettings.getInstanceForTesting(mApplication);
+        mSecondaryKeyManager =
+                new RecoverableKeyStoreSecondaryKeyManager(
+                        RecoveryController.getInstance(mApplication), new SecureRandom());
+
+        mTask =
+                new InitializeRecoverableSecondaryKeyTask(
+                        mApplication, mCryptoSettings, mSecondaryKeyManager, mFakeCryptoBackupServer);
+    }
+
+    @Test
+    public void testRun_generatesNewKeyInRecoveryController() throws Exception {
+        RecoverableKeyStoreSecondaryKey key = mTask.run();
+
+        assertThat(RecoveryController.getInstance(mApplication).getAliases())
+                .contains(key.getAlias());
+    }
+
+    @Test
+    public void testRun_setsAliasOnServer() throws Exception {
+        RecoverableKeyStoreSecondaryKey key = mTask.run();
+
+        assertThat(mFakeCryptoBackupServer.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(key.getAlias());
+    }
+
+    @Test
+    public void testRun_setsAliasInSettings() throws Exception {
+        RecoverableKeyStoreSecondaryKey key = mTask.run();
+
+        assertThat(mCryptoSettings.getActiveSecondaryKeyAlias().get()).isEqualTo(key.getAlias());
+    }
+
+    @Test
+    public void testRun_initializesSettings() throws Exception {
+        mTask.run();
+
+        assertThat(mCryptoSettings.getIsInitialized()).isTrue();
+    }
+
+    @Test
+    public void testRun_initializeSettingsFails_throws() throws Exception {
+        useMockCryptoSettings();
+        doThrow(IllegalArgumentException.class)
+                .when(mMockCryptoSettings)
+                .initializeWithKeyAlias(any());
+
+
+        assertThrows(IllegalArgumentException.class, () -> mTask.run());
+    }
+
+    @Test
+    public void testRun_doesNotGenerateANewKeyIfOneIsAvailable() throws Exception {
+        RecoverableKeyStoreSecondaryKey key1 = mTask.run();
+        RecoverableKeyStoreSecondaryKey key2 = mTask.run();
+
+        assertThat(key1.getAlias()).isEqualTo(key2.getAlias());
+        assertThat(key2.getSecretKey()).isEqualTo(key2.getSecretKey());
+    }
+
+    @Test
+    public void testRun_existingKeyButDestroyed_throws() throws Exception {
+        RecoverableKeyStoreSecondaryKey key = mTask.run();
+        ShadowRecoveryController.setRecoveryStatus(
+                key.getAlias(), RECOVERY_STATUS_PERMANENT_FAILURE);
+
+        assertThrows(InvalidKeyException.class, () -> mTask.run());
+    }
+
+    @Test
+    public void testRun_settingsInitializedButNotSecondaryKeyAlias_throws() {
+        useMockCryptoSettings();
+        when(mMockCryptoSettings.getIsInitialized()).thenReturn(true);
+        when(mMockCryptoSettings.getActiveSecondaryKeyAlias()).thenReturn(Optional.empty());
+
+        assertThrows(InvalidKeyException.class, () -> mTask.run());
+    }
+
+    @Test
+    public void testRun_keyAliasSetButNotInStore_throws() {
+        useMockCryptoSettings();
+        when(mMockCryptoSettings.getIsInitialized()).thenReturn(true);
+        when(mMockCryptoSettings.getActiveSecondaryKeyAlias())
+                .thenReturn(Optional.of("missingAlias"));
+
+        assertThrows(InvalidKeyException.class, () -> mTask.run());
+    }
+
+    private void useMockCryptoSettings() {
+        mTask =
+                new InitializeRecoverableSecondaryKeyTask(
+                        mApplication,
+                        mMockCryptoSettings,
+                        mSecondaryKeyManager,
+                        mFakeCryptoBackupServer);
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/KvBackupEncrypterTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/KvBackupEncrypterTest.java
new file mode 100644
index 0000000..ccfbfa4
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/KvBackupEncrypterTest.java
@@ -0,0 +1,287 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+import android.app.backup.BackupDataInput;
+import android.platform.test.annotations.Presubmit;
+import android.util.Pair;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.chunking.ChunkHasher;
+import com.android.server.backup.encryption.chunking.EncryptedChunk;
+import com.android.server.backup.encryption.kv.KeyValueListingBuilder;
+import com.android.server.backup.encryption.protos.nano.KeyValueListingProto.KeyValueListing;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto.KeyValuePair;
+import com.android.server.backup.encryption.tasks.BackupEncrypter.Result;
+import com.android.server.testing.shadows.DataEntity;
+import com.android.server.testing.shadows.ShadowBackupDataInput;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Ordering;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+import java.security.MessageDigest;
+import java.util.Arrays;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+@Config(shadows = {ShadowBackupDataInput.class})
+public class KvBackupEncrypterTest {
+    private static final String KEY_ALGORITHM = "AES";
+    private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
+    private static final int GCM_TAG_LENGTH_BYTES = 16;
+
+    private static final byte[] TEST_TERTIARY_KEY = Arrays.copyOf(new byte[0], 256 / Byte.SIZE);
+    private static final String TEST_KEY_1 = "test_key_1";
+    private static final String TEST_KEY_2 = "test_key_2";
+    private static final String TEST_KEY_3 = "test_key_3";
+    private static final byte[] TEST_VALUE_1 = {10, 11, 12};
+    private static final byte[] TEST_VALUE_2 = {13, 14, 15};
+    private static final byte[] TEST_VALUE_2B = {13, 14, 15, 16};
+    private static final byte[] TEST_VALUE_3 = {16, 17, 18};
+
+    private SecretKey mSecretKey;
+    private ChunkHasher mChunkHasher;
+
+    @Before
+    public void setUp() {
+        mSecretKey = new SecretKeySpec(TEST_TERTIARY_KEY, KEY_ALGORITHM);
+        mChunkHasher = new ChunkHasher(mSecretKey);
+
+        ShadowBackupDataInput.reset();
+    }
+
+    private KvBackupEncrypter createEncrypter(KeyValueListing keyValueListing) {
+        KvBackupEncrypter encrypter = new KvBackupEncrypter(new BackupDataInput(null));
+        encrypter.setOldKeyValueListing(keyValueListing);
+        return encrypter;
+    }
+
+    @Test
+    public void backup_noExistingBackup_encryptsAllPairs() throws Exception {
+        ShadowBackupDataInput.addEntity(TEST_KEY_1, TEST_VALUE_1);
+        ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2);
+
+        KeyValueListing emptyKeyValueListing = new KeyValueListingBuilder().build();
+        ImmutableSet<ChunkHash> emptyExistingChunks = ImmutableSet.of();
+        KvBackupEncrypter encrypter = createEncrypter(emptyKeyValueListing);
+
+        Result result =
+                encrypter.backup(
+                        mSecretKey, /*unusedFingerprintMixerSalt=*/ null, emptyExistingChunks);
+
+        assertThat(result.getAllChunks()).hasSize(2);
+        EncryptedChunk chunk1 = result.getNewChunks().get(0);
+        EncryptedChunk chunk2 = result.getNewChunks().get(1);
+        assertThat(chunk1.key()).isEqualTo(getChunkHash(TEST_KEY_1, TEST_VALUE_1));
+        KeyValuePair pair1 = decryptChunk(chunk1);
+        assertThat(pair1.key).isEqualTo(TEST_KEY_1);
+        assertThat(pair1.value).isEqualTo(TEST_VALUE_1);
+        assertThat(chunk2.key()).isEqualTo(getChunkHash(TEST_KEY_2, TEST_VALUE_2));
+        KeyValuePair pair2 = decryptChunk(chunk2);
+        assertThat(pair2.key).isEqualTo(TEST_KEY_2);
+        assertThat(pair2.value).isEqualTo(TEST_VALUE_2);
+    }
+
+    @Test
+    public void backup_existingBackup_encryptsNewAndUpdatedPairs() throws Exception {
+        Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+        // Update key 2 and add the new key 3.
+        ShadowBackupDataInput.reset();
+        ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2B);
+        ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+        KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+        BackupEncrypter.Result secondResult =
+                encrypter.backup(
+                        mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+        assertThat(secondResult.getAllChunks()).hasSize(3);
+        assertThat(secondResult.getNewChunks()).hasSize(2);
+        EncryptedChunk newChunk2 = secondResult.getNewChunks().get(0);
+        EncryptedChunk newChunk3 = secondResult.getNewChunks().get(1);
+        assertThat(newChunk2.key()).isEqualTo(getChunkHash(TEST_KEY_2, TEST_VALUE_2B));
+        assertThat(decryptChunk(newChunk2).value).isEqualTo(TEST_VALUE_2B);
+        assertThat(newChunk3.key()).isEqualTo(getChunkHash(TEST_KEY_3, TEST_VALUE_3));
+        assertThat(decryptChunk(newChunk3).value).isEqualTo(TEST_VALUE_3);
+    }
+
+    @Test
+    public void backup_allChunksContainsHashesOfAllChunks() throws Exception {
+        Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+        ShadowBackupDataInput.reset();
+        ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+        KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+        BackupEncrypter.Result secondResult =
+                encrypter.backup(
+                        mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+        assertThat(secondResult.getAllChunks())
+                .containsExactly(
+                        getChunkHash(TEST_KEY_1, TEST_VALUE_1),
+                        getChunkHash(TEST_KEY_2, TEST_VALUE_2),
+                        getChunkHash(TEST_KEY_3, TEST_VALUE_3));
+    }
+
+    @Test
+    public void backup_negativeSize_deletesKeyFromExistingBackup() throws Exception {
+        Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+        ShadowBackupDataInput.reset();
+        ShadowBackupDataInput.addEntity(new DataEntity(TEST_KEY_2));
+
+        KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+        Result secondResult =
+                encrypter.backup(
+                        mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+        assertThat(secondResult.getAllChunks())
+                .containsExactly(getChunkHash(TEST_KEY_1, TEST_VALUE_1));
+        assertThat(secondResult.getNewChunks()).isEmpty();
+    }
+
+    @Test
+    public void backup_returnsMessageDigestOverChunkHashes() throws Exception {
+        Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+        ShadowBackupDataInput.reset();
+        ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+        KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+        Result secondResult =
+                encrypter.backup(
+                        mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+        MessageDigest messageDigest =
+                MessageDigest.getInstance(BackupEncrypter.MESSAGE_DIGEST_ALGORITHM);
+        ImmutableList<ChunkHash> sortedHashes =
+                Ordering.natural()
+                        .immutableSortedCopy(
+                                ImmutableList.of(
+                                        getChunkHash(TEST_KEY_1, TEST_VALUE_1),
+                                        getChunkHash(TEST_KEY_2, TEST_VALUE_2),
+                                        getChunkHash(TEST_KEY_3, TEST_VALUE_3)));
+        messageDigest.update(sortedHashes.get(0).getHash());
+        messageDigest.update(sortedHashes.get(1).getHash());
+        messageDigest.update(sortedHashes.get(2).getHash());
+        assertThat(secondResult.getDigest()).isEqualTo(messageDigest.digest());
+    }
+
+    @Test
+    public void getNewKeyValueListing_noExistingBackup_returnsCorrectListing() throws Exception {
+        KeyValueListing keyValueListing = runInitialBackupOfPairs1And2().first;
+
+        assertThat(keyValueListing.entries.length).isEqualTo(2);
+        assertThat(keyValueListing.entries[0].key).isEqualTo(TEST_KEY_1);
+        assertThat(keyValueListing.entries[0].hash)
+                .isEqualTo(getChunkHash(TEST_KEY_1, TEST_VALUE_1).getHash());
+        assertThat(keyValueListing.entries[1].key).isEqualTo(TEST_KEY_2);
+        assertThat(keyValueListing.entries[1].hash)
+                .isEqualTo(getChunkHash(TEST_KEY_2, TEST_VALUE_2).getHash());
+    }
+
+    @Test
+    public void getNewKeyValueListing_existingBackup_returnsCorrectListing() throws Exception {
+        Pair<KeyValueListing, Set<ChunkHash>> initialResult = runInitialBackupOfPairs1And2();
+
+        ShadowBackupDataInput.reset();
+        ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2B);
+        ShadowBackupDataInput.addEntity(TEST_KEY_3, TEST_VALUE_3);
+
+        KvBackupEncrypter encrypter = createEncrypter(initialResult.first);
+        encrypter.backup(mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialResult.second);
+
+        ImmutableMap<String, ChunkHash> keyValueListing =
+                listingToMap(encrypter.getNewKeyValueListing());
+        assertThat(keyValueListing).hasSize(3);
+        assertThat(keyValueListing)
+                .containsEntry(TEST_KEY_1, getChunkHash(TEST_KEY_1, TEST_VALUE_1));
+        assertThat(keyValueListing)
+                .containsEntry(TEST_KEY_2, getChunkHash(TEST_KEY_2, TEST_VALUE_2B));
+        assertThat(keyValueListing)
+                .containsEntry(TEST_KEY_3, getChunkHash(TEST_KEY_3, TEST_VALUE_3));
+    }
+
+    @Test
+    public void getNewKeyValueChunkListing_beforeBackup_throws() throws Exception {
+        KvBackupEncrypter encrypter = createEncrypter(new KeyValueListing());
+        assertThrows(IllegalStateException.class, encrypter::getNewKeyValueListing);
+    }
+
+    private ImmutableMap<String, ChunkHash> listingToMap(KeyValueListing listing) {
+        // We can't use the ImmutableMap collector directly because it isn't supported in Android
+        // guava.
+        return ImmutableMap.copyOf(
+                Arrays.stream(listing.entries)
+                        .collect(
+                                Collectors.toMap(
+                                        entry -> entry.key, entry -> new ChunkHash(entry.hash))));
+    }
+
+    private Pair<KeyValueListing, Set<ChunkHash>> runInitialBackupOfPairs1And2() throws Exception {
+        ShadowBackupDataInput.addEntity(TEST_KEY_1, TEST_VALUE_1);
+        ShadowBackupDataInput.addEntity(TEST_KEY_2, TEST_VALUE_2);
+
+        KeyValueListing initialKeyValueListing = new KeyValueListingBuilder().build();
+        ImmutableSet<ChunkHash> initialExistingChunks = ImmutableSet.of();
+        KvBackupEncrypter encrypter = createEncrypter(initialKeyValueListing);
+        Result firstResult =
+                encrypter.backup(
+                        mSecretKey, /*unusedFingerprintMixerSalt=*/ null, initialExistingChunks);
+
+        return Pair.create(
+                encrypter.getNewKeyValueListing(), ImmutableSet.copyOf(firstResult.getAllChunks()));
+    }
+
+    private ChunkHash getChunkHash(String key, byte[] value) throws Exception {
+        KeyValuePair pair = new KeyValuePair();
+        pair.key = key;
+        pair.value = Arrays.copyOf(value, value.length);
+        return mChunkHasher.computeHash(KeyValuePair.toByteArray(pair));
+    }
+
+    private KeyValuePair decryptChunk(EncryptedChunk encryptedChunk) throws Exception {
+        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+        cipher.init(
+                Cipher.DECRYPT_MODE,
+                mSecretKey,
+                new GCMParameterSpec(GCM_TAG_LENGTH_BYTES * Byte.SIZE, encryptedChunk.nonce()));
+        byte[] decryptedBytes = cipher.doFinal(encryptedChunk.encryptedBytes());
+        return KeyValuePair.parseFrom(decryptedBytes);
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/RotateSecondaryKeyTaskTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/RotateSecondaryKeyTaskTest.java
new file mode 100644
index 0000000..cda7317
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/tasks/RotateSecondaryKeyTaskTest.java
@@ -0,0 +1,363 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.tasks;
+
+import static com.android.server.backup.testing.CryptoTestUtils.generateAesKey;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertFalse;
+
+import android.app.Application;
+import android.platform.test.annotations.Presubmit;
+import android.security.keystore.recovery.RecoveryController;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.server.backup.encryption.CryptoSettings;
+import com.android.server.backup.encryption.keys.KeyWrapUtils;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKey;
+import com.android.server.backup.encryption.keys.RecoverableKeyStoreSecondaryKeyManager;
+import com.android.server.backup.encryption.keys.TertiaryKeyStore;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+import com.android.server.testing.fakes.FakeCryptoBackupServer;
+import com.android.server.testing.shadows.ShadowRecoveryController;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.crypto.SecretKey;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.annotation.Config;
+
+@RunWith(RobolectricTestRunner.class)
+@Presubmit
+@Config(shadows = {ShadowRecoveryController.class, ShadowRecoveryController.class})
+public class RotateSecondaryKeyTaskTest {
+    private static final String APP_1 = "app1";
+    private static final String APP_2 = "app2";
+    private static final String APP_3 = "app3";
+
+    private static final String CURRENT_SECONDARY_KEY_ALIAS =
+            "recoverablekey.alias/d524796bd07de3c2225c63d434eff698";
+    private static final String NEXT_SECONDARY_KEY_ALIAS =
+            "recoverablekey.alias/6c6d198a7f12e662b6bc45f4849db170";
+
+    private Application mApplication;
+    private RotateSecondaryKeyTask mTask;
+    private RecoveryController mRecoveryController;
+    private FakeCryptoBackupServer mBackupServer;
+    private CryptoSettings mCryptoSettings;
+    private Map<String, SecretKey> mTertiaryKeysByPackageName;
+    private RecoverableKeyStoreSecondaryKeyManager mRecoverableSecondaryKeyManager;
+
+    @Before
+    public void setUp() throws Exception {
+        mApplication = ApplicationProvider.getApplicationContext();
+
+        mTertiaryKeysByPackageName = new HashMap<>();
+        mTertiaryKeysByPackageName.put(APP_1, generateAesKey());
+        mTertiaryKeysByPackageName.put(APP_2, generateAesKey());
+        mTertiaryKeysByPackageName.put(APP_3, generateAesKey());
+
+        mRecoveryController = RecoveryController.getInstance(mApplication);
+        mRecoverableSecondaryKeyManager =
+                new RecoverableKeyStoreSecondaryKeyManager(
+                        RecoveryController.getInstance(mApplication), new SecureRandom());
+        mBackupServer = new FakeCryptoBackupServer();
+        mCryptoSettings = CryptoSettings.getInstanceForTesting(mApplication);
+        addNextSecondaryKeyToRecoveryController();
+        mCryptoSettings.setNextSecondaryAlias(NEXT_SECONDARY_KEY_ALIAS);
+
+        mTask =
+                new RotateSecondaryKeyTask(
+                        mApplication,
+                        mRecoverableSecondaryKeyManager,
+                        mBackupServer,
+                        mCryptoSettings,
+                        mRecoveryController);
+
+        ShadowRecoveryController.reset();
+    }
+
+    @Test
+    public void run_failsIfThereIsNoActiveSecondaryKey() throws Exception {
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertFalse(mCryptoSettings.getActiveSecondaryKeyAlias().isPresent());
+    }
+
+    @Test
+    public void run_failsIfActiveSecondaryIsNotInRecoveryController() throws Exception {
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        // Have to add it first as otherwise CryptoSettings throws an exception when trying to set
+        // it
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertThat(mCryptoSettings.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(CURRENT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_doesNothingIfFlagIsDisabled() throws Exception {
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+        addWrappedTertiaries();
+
+        mTask.run();
+
+        assertThat(mCryptoSettings.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(CURRENT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_setsActiveSecondary() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+        addWrappedTertiaries();
+
+        mTask.run();
+
+        assertThat(mBackupServer.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(NEXT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_rewrapsExistingTertiaryKeys() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+        addWrappedTertiaries();
+
+        mTask.run();
+
+        Map<String, WrappedKeyProto.WrappedKey> rewrappedKeys =
+                mBackupServer.getAllTertiaryKeys(NEXT_SECONDARY_KEY_ALIAS);
+        SecretKey secondaryKey = (SecretKey) mRecoveryController.getKey(NEXT_SECONDARY_KEY_ALIAS);
+        for (String packageName : mTertiaryKeysByPackageName.keySet()) {
+            WrappedKeyProto.WrappedKey rewrappedKey = rewrappedKeys.get(packageName);
+            assertThat(KeyWrapUtils.unwrap(secondaryKey, rewrappedKey))
+                    .isEqualTo(mTertiaryKeysByPackageName.get(packageName));
+        }
+    }
+
+    @Test
+    public void run_persistsRewrappedKeysToDisk() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+        addWrappedTertiaries();
+
+        mTask.run();
+
+        RecoverableKeyStoreSecondaryKey secondaryKey = getRecoverableKey(NEXT_SECONDARY_KEY_ALIAS);
+        Map<String, SecretKey> keys =
+                TertiaryKeyStore.newInstance(mApplication, secondaryKey).getAll();
+        for (String packageName : mTertiaryKeysByPackageName.keySet()) {
+            SecretKey tertiaryKey = mTertiaryKeysByPackageName.get(packageName);
+            SecretKey newlyWrappedKey = keys.get(packageName);
+            assertThat(tertiaryKey.getEncoded()).isEqualTo(newlyWrappedKey.getEncoded());
+        }
+    }
+
+    @Test
+    public void run_stillSetsActiveSecondaryIfNoTertiaries() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertThat(mBackupServer.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(NEXT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_setsActiveSecondaryKeyAliasInSettings() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertThat(mCryptoSettings.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(NEXT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_removesNextSecondaryKeyAliasInSettings() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertFalse(mCryptoSettings.getNextSecondaryKeyAlias().isPresent());
+    }
+
+    @Test
+    public void run_deletesOldKeyFromRecoverableKeyStoreLoader() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNCED);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertThat(mRecoveryController.getKey(CURRENT_SECONDARY_KEY_ALIAS)).isNull();
+    }
+
+    @Test
+    public void run_doesNotRotateIfNoNextAlias() throws Exception {
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+        mCryptoSettings.removeNextSecondaryKeyAlias();
+
+        mTask.run();
+
+        assertThat(mCryptoSettings.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(CURRENT_SECONDARY_KEY_ALIAS);
+        assertFalse(mCryptoSettings.getNextSecondaryKeyAlias().isPresent());
+    }
+
+    @Test
+    public void run_doesNotRotateIfKeyIsNotSyncedYet() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNC_IN_PROGRESS);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertThat(mCryptoSettings.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(CURRENT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_doesNotClearNextKeyIfSyncIsJustPending() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_SYNC_IN_PROGRESS);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertThat(mCryptoSettings.getNextSecondaryKeyAlias().get())
+                .isEqualTo(NEXT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_doesNotRotateIfPermanentFailure() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_PERMANENT_FAILURE);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertThat(mCryptoSettings.getActiveSecondaryKeyAlias().get())
+                .isEqualTo(CURRENT_SECONDARY_KEY_ALIAS);
+    }
+
+    @Test
+    public void run_removesNextKeyIfPermanentFailure() throws Exception {
+        addNextSecondaryKeyToRecoveryController();
+        setNextKeyRecoveryStatus(RecoveryController.RECOVERY_STATUS_PERMANENT_FAILURE);
+        addCurrentSecondaryKeyToRecoveryController();
+        mCryptoSettings.setActiveSecondaryKeyAlias(CURRENT_SECONDARY_KEY_ALIAS);
+        mBackupServer.setActiveSecondaryKeyAlias(
+                CURRENT_SECONDARY_KEY_ALIAS, Collections.emptyMap());
+
+        mTask.run();
+
+        assertFalse(mCryptoSettings.getNextSecondaryKeyAlias().isPresent());
+    }
+
+    private void setNextKeyRecoveryStatus(int status) throws Exception {
+        mRecoveryController.setRecoveryStatus(NEXT_SECONDARY_KEY_ALIAS, status);
+    }
+
+    private void addCurrentSecondaryKeyToRecoveryController() throws Exception {
+        mRecoveryController.generateKey(CURRENT_SECONDARY_KEY_ALIAS);
+    }
+
+    private void addNextSecondaryKeyToRecoveryController() throws Exception {
+        mRecoveryController.generateKey(NEXT_SECONDARY_KEY_ALIAS);
+    }
+
+    private void addWrappedTertiaries() throws Exception {
+        TertiaryKeyStore tertiaryKeyStore =
+                TertiaryKeyStore.newInstance(
+                        mApplication, getRecoverableKey(CURRENT_SECONDARY_KEY_ALIAS));
+
+        for (String packageName : mTertiaryKeysByPackageName.keySet()) {
+            tertiaryKeyStore.save(packageName, mTertiaryKeysByPackageName.get(packageName));
+        }
+    }
+
+    private RecoverableKeyStoreSecondaryKey getRecoverableKey(String alias) throws Exception {
+        return mRecoverableSecondaryKeyManager.get(alias).get();
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/DiffScriptProcessor.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/DiffScriptProcessor.java
new file mode 100644
index 0000000..faddb6c
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/DiffScriptProcessor.java
@@ -0,0 +1,256 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.testing;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+/**
+ * To be used as part of a fake backup server. Processes a Scotty diff script.
+ *
+ * <p>A Scotty diff script consists of an ASCII line denoting a command, optionally followed by a
+ * range of bytes. Command format is either
+ *
+ * <ul>
+ *   <li>A single 64-bit integer, followed by a new line: this denotes that the given number of
+ *       bytes are to follow in the stream. These bytes should be written directly to the new file.
+ *   <li>Two 64-bit integers, separated by a hyphen, followed by a new line: this says that the
+ *       given range of bytes from the original file ought to be copied into the new file.
+ * </ul>
+ */
+public class DiffScriptProcessor {
+
+    private static final int COPY_BUFFER_SIZE = 1024;
+
+    private static final String READ_MODE = "r";
+    private static final Pattern VALID_COMMAND_PATTERN = Pattern.compile("^\\d+(-\\d+)?$");
+
+    private final File mInput;
+    private final File mOutput;
+    private final long mInputLength;
+
+    /**
+     * A new instance, with {@code input} as previous file, and {@code output} as new file.
+     *
+     * @param input Previous file from which ranges of bytes are to be copied. This file should be
+     *     immutable.
+     * @param output Output file, to which the new data should be written.
+     * @throws IllegalArgumentException if input does not exist.
+     */
+    public DiffScriptProcessor(File input, File output) {
+        checkArgument(input.exists(), "input file did not exist.");
+        mInput = input;
+        mInputLength = input.length();
+        mOutput = checkNotNull(output);
+    }
+
+    public void process(InputStream diffScript) throws IOException, MalformedDiffScriptException {
+        RandomAccessFile randomAccessInput = new RandomAccessFile(mInput, READ_MODE);
+
+        try (FileOutputStream outputStream = new FileOutputStream(mOutput)) {
+            while (true) {
+                Optional<String> commandString = readCommand(diffScript);
+                if (!commandString.isPresent()) {
+                    return;
+                }
+                Command command = Command.parse(commandString.get());
+
+                if (command.mIsRange) {
+                    checkFileRange(command.mCount, command.mLimit);
+                    copyRange(randomAccessInput, outputStream, command.mCount, command.mLimit);
+                } else {
+                    long bytesCopied = copyBytes(diffScript, outputStream, command.mCount);
+                    if (bytesCopied < command.mCount) {
+                        throw new MalformedDiffScriptException(
+                                String.format(
+                                        Locale.US,
+                                        "Command to copy %d bytes from diff script, but only %d"
+                                            + " bytes available",
+                                        command.mCount,
+                                        bytesCopied));
+                    }
+                    if (diffScript.read() != '\n') {
+                        throw new MalformedDiffScriptException("Expected new line after bytes.");
+                    }
+                }
+            }
+        }
+    }
+
+    private void checkFileRange(long start, long end) throws MalformedDiffScriptException {
+        if (end < start) {
+            throw new MalformedDiffScriptException(
+                    String.format(
+                            Locale.US,
+                            "Command to copy %d-%d bytes from original file, but %2$d < %1$d.",
+                            start,
+                            end));
+        }
+
+        if (end >= mInputLength) {
+            throw new MalformedDiffScriptException(
+                    String.format(
+                            Locale.US,
+                            "Command to copy %d-%d bytes from original file, but file is only %d"
+                                + " bytes long.",
+                            start,
+                            end,
+                            mInputLength));
+        }
+    }
+
+    /**
+     * Reads a command from the input stream.
+     *
+     * @param inputStream The input.
+     * @return Optional of command, or empty if EOF.
+     */
+    private static Optional<String> readCommand(InputStream inputStream) throws IOException {
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+
+        int b;
+        while (!isEndOfCommand(b = inputStream.read())) {
+            byteArrayOutputStream.write(b);
+        }
+
+        byte[] bytes = byteArrayOutputStream.toByteArray();
+        if (bytes.length == 0) {
+            return Optional.empty();
+        } else {
+            return Optional.of(new String(bytes, UTF_8));
+        }
+    }
+
+    /**
+     * If the given output from {@link InputStream#read()} is the end of a command - i.e., a new
+     * line or the EOF.
+     *
+     * @param b The byte or -1.
+     * @return {@code true} if ends the command.
+     */
+    private static boolean isEndOfCommand(int b) {
+        return b == -1 || b == '\n';
+    }
+
+    /**
+     * Copies {@code n} bytes from {@code inputStream} to {@code outputStream}.
+     *
+     * @return The number of bytes copied.
+     * @throws IOException if there was a problem reading or writing.
+     */
+    private static long copyBytes(InputStream inputStream, OutputStream outputStream, long n)
+            throws IOException {
+        byte[] buffer = new byte[COPY_BUFFER_SIZE];
+        long copied = 0;
+        while (n - copied > COPY_BUFFER_SIZE) {
+            long read = copyBlock(inputStream, outputStream, buffer, COPY_BUFFER_SIZE);
+            if (read <= 0) {
+                return copied;
+            }
+        }
+        while (n - copied > 0) {
+            copied += copyBlock(inputStream, outputStream, buffer, (int) (n - copied));
+        }
+        return copied;
+    }
+
+    private static long copyBlock(
+            InputStream inputStream, OutputStream outputStream, byte[] buffer, int size)
+            throws IOException {
+        int read = inputStream.read(buffer, 0, size);
+        outputStream.write(buffer, 0, read);
+        return read;
+    }
+
+    /**
+     * Copies the given range of bytes from the input file to the output stream.
+     *
+     * @param input The input file.
+     * @param output The output stream.
+     * @param start Start position in the input file.
+     * @param end End position in the output file (inclusive).
+     * @throws IOException if there was a problem reading or writing.
+     */
+    private static void copyRange(RandomAccessFile input, OutputStream output, long start, long end)
+            throws IOException {
+        input.seek(start);
+
+        // Inefficient but obviously correct. If tests become slow, optimize.
+        for (; start <= end; start++) {
+            output.write(input.read());
+        }
+    }
+
+    /** Error thrown for a malformed diff script. */
+    public static class MalformedDiffScriptException extends Exception {
+        public MalformedDiffScriptException(String message) {
+            super(message);
+        }
+    }
+
+    /**
+     * A command telling the processor either to insert n bytes, which follow, or copy n-m bytes
+     * from the original file.
+     */
+    private static class Command {
+        private final long mCount;
+        private final long mLimit;
+        private final boolean mIsRange;
+
+        private Command(long count, long limit, boolean isRange) {
+            mCount = count;
+            mLimit = limit;
+            mIsRange = isRange;
+        }
+
+        /**
+         * Attempts to parse the command string into a usable structure.
+         *
+         * @param command The command string, without a new line at the end.
+         * @throws MalformedDiffScriptException if the command is not a valid diff script command.
+         * @return The parsed command.
+         */
+        private static Command parse(String command) throws MalformedDiffScriptException {
+            if (!VALID_COMMAND_PATTERN.matcher(command).matches()) {
+                throw new MalformedDiffScriptException("Bad command: " + command);
+            }
+
+            Scanner commandScanner = new Scanner(command);
+            commandScanner.useDelimiter("-");
+            long n = commandScanner.nextLong();
+            if (!commandScanner.hasNextLong()) {
+                return new Command(n, 0L, /*isRange=*/ false);
+            }
+            long m = commandScanner.nextLong();
+            return new Command(n, m, /*isRange=*/ true);
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/QueuingNonAutomaticExecutorService.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/QueuingNonAutomaticExecutorService.java
new file mode 100644
index 0000000..9d2272e
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/backup/encryption/testing/QueuingNonAutomaticExecutorService.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.testing;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.AbstractExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * ExecutorService which needs to be stepped through the jobs in its' queue.
+ *
+ * <p>This is a deliberately simple implementation because it's only used in testing. The queued
+ * jobs are run on the main thread to eliminate any race condition bugs.
+ */
+public class QueuingNonAutomaticExecutorService extends AbstractExecutorService {
+
+    private List<Runnable> mWaitingJobs = new ArrayList<>();
+    private int mWaitingJobCount = 0;
+
+    @Override
+    public void shutdown() {
+        mWaitingJobCount = mWaitingJobs.size();
+        mWaitingJobs = null; // This will force an error if jobs are submitted after shutdown
+    }
+
+    @Override
+    public List<Runnable> shutdownNow() {
+        List<Runnable> queuedJobs = mWaitingJobs;
+        shutdown();
+        return queuedJobs;
+    }
+
+    @Override
+    public boolean isShutdown() {
+        return mWaitingJobs == null;
+    }
+
+    @Override
+    public boolean isTerminated() {
+        return mWaitingJobs == null && mWaitingJobCount == 0;
+    }
+
+    @Override
+    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+        long expiry = System.currentTimeMillis() + unit.toMillis(timeout);
+        for (Runnable job : mWaitingJobs) {
+            if (System.currentTimeMillis() > expiry) {
+                return false;
+            }
+
+            job.run();
+        }
+        return true;
+    }
+
+    @Override
+    public void execute(Runnable command) {
+        mWaitingJobs.add(command);
+    }
+
+    public void runNext() {
+        if (mWaitingJobs.isEmpty()) {
+            throw new IllegalStateException("Attempted to run jobs on an empty paused executor");
+        }
+
+        mWaitingJobs.remove(0).run();
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java
index 3f3494d..b0c02ba 100644
--- a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/CryptoTestUtils.java
@@ -16,7 +16,17 @@
 
 package com.android.server.backup.testing;
 
+import android.util.Pair;
+
+import com.android.server.backup.encryption.chunk.ChunkHash;
+import com.android.server.backup.encryption.protos.nano.ChunksMetadataProto;
+import com.android.server.backup.encryption.protos.nano.KeyValuePairProto;
+
+import java.nio.charset.Charset;
 import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.Random;
 
 import javax.crypto.KeyGenerator;
@@ -42,4 +52,126 @@
         random.nextBytes(bytes);
         return bytes;
     }
+
+    public static ChunksMetadataProto.Chunk newChunk(ChunkHash hash, int length) {
+        return newChunk(hash.getHash(), length);
+    }
+
+    public static ChunksMetadataProto.Chunk newChunk(byte[] hash, int length) {
+        ChunksMetadataProto.Chunk newChunk = new ChunksMetadataProto.Chunk();
+        newChunk.hash = Arrays.copyOf(hash, hash.length);
+        newChunk.length = length;
+        return newChunk;
+    }
+
+    public static ChunksMetadataProto.ChunkListing newChunkListing(
+            String docId,
+            byte[] fingerprintSalt,
+            int cipherType,
+            int orderingType,
+            ChunksMetadataProto.Chunk... chunks) {
+        ChunksMetadataProto.ChunkListing chunkListing =
+                newChunkListingWithoutDocId(fingerprintSalt, cipherType, orderingType, chunks);
+        chunkListing.documentId = docId;
+        return chunkListing;
+    }
+
+    public static ChunksMetadataProto.ChunkListing newChunkListingWithoutDocId(
+            byte[] fingerprintSalt,
+            int cipherType,
+            int orderingType,
+            ChunksMetadataProto.Chunk... chunks) {
+        ChunksMetadataProto.ChunkListing chunkListing = new ChunksMetadataProto.ChunkListing();
+        chunkListing.fingerprintMixerSalt =
+                fingerprintSalt == null
+                        ? null
+                        : Arrays.copyOf(fingerprintSalt, fingerprintSalt.length);
+        chunkListing.cipherType = cipherType;
+        chunkListing.chunkOrderingType = orderingType;
+        chunkListing.chunks = chunks;
+        return chunkListing;
+    }
+
+    public static ChunksMetadataProto.ChunkOrdering newChunkOrdering(
+            int[] starts, byte[] checksum) {
+        ChunksMetadataProto.ChunkOrdering chunkOrdering = new ChunksMetadataProto.ChunkOrdering();
+        chunkOrdering.starts = starts == null ? null : Arrays.copyOf(starts, starts.length);
+        chunkOrdering.checksum =
+                checksum == null ? checksum : Arrays.copyOf(checksum, checksum.length);
+        return chunkOrdering;
+    }
+
+    public static ChunksMetadataProto.ChunksMetadata newChunksMetadata(
+            int cipherType, int checksumType, int chunkOrderingType, byte[] chunkOrdering) {
+        ChunksMetadataProto.ChunksMetadata metadata = new ChunksMetadataProto.ChunksMetadata();
+        metadata.cipherType = cipherType;
+        metadata.checksumType = checksumType;
+        metadata.chunkOrdering = Arrays.copyOf(chunkOrdering, chunkOrdering.length);
+        metadata.chunkOrderingType = chunkOrderingType;
+        return metadata;
+    }
+
+    public static KeyValuePairProto.KeyValuePair newPair(String key, String value) {
+        return newPair(key, value.getBytes(Charset.forName("UTF-8")));
+    }
+
+    public static KeyValuePairProto.KeyValuePair newPair(String key, byte[] value) {
+        KeyValuePairProto.KeyValuePair newPair = new KeyValuePairProto.KeyValuePair();
+        newPair.key = key;
+        newPair.value = value;
+        return newPair;
+    }
+
+    public static ChunksMetadataProto.ChunkListing clone(
+            ChunksMetadataProto.ChunkListing original) {
+        ChunksMetadataProto.Chunk[] clonedChunks;
+        if (original.chunks == null) {
+            clonedChunks = null;
+        } else {
+            clonedChunks = new ChunksMetadataProto.Chunk[original.chunks.length];
+            for (int i = 0; i < original.chunks.length; i++) {
+                clonedChunks[i] = clone(original.chunks[i]);
+            }
+        }
+
+        return newChunkListing(
+                original.documentId,
+                original.fingerprintMixerSalt,
+                original.cipherType,
+                original.chunkOrderingType,
+                clonedChunks);
+    }
+
+    public static ChunksMetadataProto.Chunk clone(ChunksMetadataProto.Chunk original) {
+        return newChunk(original.hash, original.length);
+    }
+
+    public static ChunksMetadataProto.ChunksMetadata clone(
+            ChunksMetadataProto.ChunksMetadata original) {
+        ChunksMetadataProto.ChunksMetadata cloneMetadata = new ChunksMetadataProto.ChunksMetadata();
+        cloneMetadata.chunkOrderingType = original.chunkOrderingType;
+        cloneMetadata.chunkOrdering =
+                original.chunkOrdering == null
+                        ? null
+                        : Arrays.copyOf(original.chunkOrdering, original.chunkOrdering.length);
+        cloneMetadata.checksumType = original.checksumType;
+        cloneMetadata.cipherType = original.cipherType;
+        return cloneMetadata;
+    }
+
+    public static ChunksMetadataProto.ChunkOrdering clone(
+            ChunksMetadataProto.ChunkOrdering original) {
+        ChunksMetadataProto.ChunkOrdering clone = new ChunksMetadataProto.ChunkOrdering();
+        clone.starts = Arrays.copyOf(original.starts, original.starts.length);
+        clone.checksum = Arrays.copyOf(original.checksum, original.checksum.length);
+        return clone;
+    }
+
+    public static <K, V> Map<K, V> mapOf(Pair<K, V>... pairs) {
+        Map<K, V> map = new HashMap<>();
+        for (Pair<K, V> pair : pairs) {
+            map.put(pair.first, pair.second);
+        }
+        return map;
+    }
 }
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/TestFileUtils.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/TestFileUtils.java
new file mode 100644
index 0000000..e5d73ba
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/TestFileUtils.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+import com.google.common.io.ByteStreams;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+/** Utility methods for use in tests */
+public class TestFileUtils {
+    /** Read the contents of a file into a byte array */
+    public static byte[] toByteArray(File file) throws IOException {
+        try (FileInputStream fis = new FileInputStream(file)) {
+            return ByteStreams.toByteArray(fis);
+        }
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/fakes/FakeCryptoBackupServer.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/fakes/FakeCryptoBackupServer.java
new file mode 100644
index 0000000..3329060
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/fakes/FakeCryptoBackupServer.java
@@ -0,0 +1,90 @@
+/*
+ * 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.testing.fakes;
+
+import android.annotation.Nullable;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.server.backup.encryption.client.CryptoBackupServer;
+import com.android.server.backup.encryption.client.UnexpectedActiveSecondaryOnServerException;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+
+/** Fake {@link CryptoBackupServer}, for tests. Stores tertiary keys in memory. */
+public class FakeCryptoBackupServer implements CryptoBackupServer {
+    @GuardedBy("this")
+    @Nullable
+    private String mActiveSecondaryKeyAlias;
+
+    // Secondary key alias -> (package name -> tertiary key)
+    @GuardedBy("this")
+    private Map<String, Map<String, WrappedKeyProto.WrappedKey>> mWrappedKeyStore = new HashMap<>();
+
+    @Override
+    public String uploadIncrementalBackup(
+            String packageName,
+            String oldDocId,
+            byte[] diffScript,
+            WrappedKeyProto.WrappedKey tertiaryKey) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String uploadNonIncrementalBackup(
+            String packageName, byte[] data, WrappedKeyProto.WrappedKey tertiaryKey) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public synchronized void setActiveSecondaryKeyAlias(
+            String keyAlias, Map<String, WrappedKeyProto.WrappedKey> tertiaryKeys) {
+        mActiveSecondaryKeyAlias = keyAlias;
+
+        mWrappedKeyStore.putIfAbsent(keyAlias, new HashMap<>());
+        Map<String, WrappedKeyProto.WrappedKey> keyStore = mWrappedKeyStore.get(keyAlias);
+
+        for (String packageName : tertiaryKeys.keySet()) {
+            keyStore.put(packageName, tertiaryKeys.get(packageName));
+        }
+    }
+
+    public synchronized Optional<String> getActiveSecondaryKeyAlias() {
+        return Optional.ofNullable(mActiveSecondaryKeyAlias);
+    }
+
+    public synchronized Map<String, WrappedKeyProto.WrappedKey> getAllTertiaryKeys(
+            String secondaryKeyAlias) throws UnexpectedActiveSecondaryOnServerException {
+        if (!secondaryKeyAlias.equals(mActiveSecondaryKeyAlias)) {
+            throw new UnexpectedActiveSecondaryOnServerException(
+                    String.format(
+                            Locale.US,
+                            "Requested tertiary keys wrapped with %s but %s was active secondary.",
+                            secondaryKeyAlias,
+                            mActiveSecondaryKeyAlias));
+        }
+
+        if (!mWrappedKeyStore.containsKey(secondaryKeyAlias)) {
+            return Collections.emptyMap();
+        }
+        return new HashMap<>(mWrappedKeyStore.get(secondaryKeyAlias));
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/fakes/FakeCryptoBackupServerTest.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/fakes/FakeCryptoBackupServerTest.java
new file mode 100644
index 0000000..4cd8333b
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/fakes/FakeCryptoBackupServerTest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2019 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.testing.fakes;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertThrows;
+
+import android.util.Pair;
+
+import com.android.server.backup.encryption.client.UnexpectedActiveSecondaryOnServerException;
+import com.android.server.backup.encryption.protos.nano.WrappedKeyProto;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.nio.charset.Charset;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public class FakeCryptoBackupServerTest {
+    private static final String PACKAGE_NAME_1 = "package1";
+    private static final String PACKAGE_NAME_2 = "package2";
+    private static final String PACKAGE_NAME_3 = "package3";
+    private static final WrappedKeyProto.WrappedKey PACKAGE_KEY_1 = createWrappedKey("key1");
+    private static final WrappedKeyProto.WrappedKey PACKAGE_KEY_2 = createWrappedKey("key2");
+    private static final WrappedKeyProto.WrappedKey PACKAGE_KEY_3 = createWrappedKey("key3");
+
+    private FakeCryptoBackupServer mServer;
+
+    @Before
+    public void setUp() {
+        mServer = new FakeCryptoBackupServer();
+    }
+
+    @Test
+    public void getActiveSecondaryKeyAlias_isInitiallyAbsent() throws Exception {
+        assertFalse(mServer.getActiveSecondaryKeyAlias().isPresent());
+    }
+
+    @Test
+    public void setActiveSecondaryKeyAlias_setsTheKeyAlias() throws Exception {
+        String keyAlias = "test";
+        mServer.setActiveSecondaryKeyAlias(keyAlias, Collections.emptyMap());
+        assertThat(mServer.getActiveSecondaryKeyAlias().get()).isEqualTo(keyAlias);
+    }
+
+    @Test
+    public void getAllTertiaryKeys_returnsWrappedKeys() throws Exception {
+        Map<String, WrappedKeyProto.WrappedKey> entries =
+                createKeyMap(
+                        new Pair<>(PACKAGE_NAME_1, PACKAGE_KEY_1),
+                        new Pair<>(PACKAGE_NAME_2, PACKAGE_KEY_2));
+        String secondaryKeyAlias = "doge";
+        mServer.setActiveSecondaryKeyAlias(secondaryKeyAlias, entries);
+
+        assertThat(mServer.getAllTertiaryKeys(secondaryKeyAlias)).containsExactlyEntriesIn(entries);
+    }
+
+    @Test
+    public void addTertiaryKeys_updatesExistingSet() throws Exception {
+        String keyId = "karlin";
+        WrappedKeyProto.WrappedKey replacementKey = createWrappedKey("some replacement bytes");
+
+        mServer.setActiveSecondaryKeyAlias(
+                keyId,
+                createKeyMap(
+                        new Pair<>(PACKAGE_NAME_1, PACKAGE_KEY_1),
+                        new Pair<>(PACKAGE_NAME_2, PACKAGE_KEY_2)));
+
+        mServer.setActiveSecondaryKeyAlias(
+                keyId,
+                createKeyMap(
+                        new Pair<>(PACKAGE_NAME_1, replacementKey),
+                        new Pair<>(PACKAGE_NAME_3, PACKAGE_KEY_3)));
+
+        assertThat(mServer.getAllTertiaryKeys(keyId))
+                .containsExactlyEntriesIn(
+                        createKeyMap(
+                                new Pair<>(PACKAGE_NAME_1, replacementKey),
+                                new Pair<>(PACKAGE_NAME_2, PACKAGE_KEY_2),
+                                new Pair<>(PACKAGE_NAME_3, PACKAGE_KEY_3)));
+    }
+
+    @Test
+    public void getAllTertiaryKeys_throwsForUnknownSecondaryKeyAlias() throws Exception {
+        assertThrows(
+                UnexpectedActiveSecondaryOnServerException.class,
+                () -> mServer.getAllTertiaryKeys("unknown"));
+    }
+
+    @Test
+    public void uploadIncrementalBackup_throwsUnsupportedOperationException() {
+        assertThrows(
+                UnsupportedOperationException.class,
+                () ->
+                        mServer.uploadIncrementalBackup(
+                                PACKAGE_NAME_1,
+                                "docid",
+                                new byte[0],
+                                new WrappedKeyProto.WrappedKey()));
+    }
+
+    @Test
+    public void uploadNonIncrementalBackup_throwsUnsupportedOperationException() {
+        assertThrows(
+                UnsupportedOperationException.class,
+                () ->
+                        mServer.uploadNonIncrementalBackup(
+                                PACKAGE_NAME_1, new byte[0], new WrappedKeyProto.WrappedKey()));
+    }
+
+    private static WrappedKeyProto.WrappedKey createWrappedKey(String data) {
+        WrappedKeyProto.WrappedKey wrappedKey = new WrappedKeyProto.WrappedKey();
+        wrappedKey.key = data.getBytes(Charset.forName("UTF-8"));
+        return wrappedKey;
+    }
+
+    private Map<String, WrappedKeyProto.WrappedKey> createKeyMap(
+            Pair<String, WrappedKeyProto.WrappedKey>... pairs) {
+        Map<String, WrappedKeyProto.WrappedKey> map = new HashMap<>();
+        for (Pair<String, WrappedKeyProto.WrappedKey> pair : pairs) {
+            map.put(pair.first, pair.second);
+        }
+        return map;
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/DataEntity.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/DataEntity.java
new file mode 100644
index 0000000..6d3b5e9
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/DataEntity.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2019 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.testing.shadows;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+/**
+ * Represents a key value pair in {@link ShadowBackupDataInput} and {@link ShadowBackupDataOutput}.
+ */
+public class DataEntity {
+    public final String mKey;
+    public final byte[] mValue;
+    public final int mSize;
+
+    /**
+     * Constructs a pair with a string value. The value will be converted to a byte array in {@link
+     * StandardCharsets#UTF_8}.
+     */
+    public DataEntity(String key, String value) {
+        this.mKey = checkNotNull(key);
+        this.mValue = value.getBytes(StandardCharsets.UTF_8);
+        mSize = this.mValue.length;
+    }
+
+    /**
+     * Constructs a new entity with the given key but a negative size. This represents a deleted
+     * pair.
+     */
+    public DataEntity(String key) {
+        this.mKey = checkNotNull(key);
+        mSize = -1;
+        mValue = null;
+    }
+
+    /** Constructs a new entity where the size of the value is the entire array. */
+    public DataEntity(String key, byte[] value) {
+        this(key, value, value.length);
+    }
+
+    /**
+     * Constructs a new entity.
+     *
+     * @param key the key of the pair
+     * @param data the value to associate with the key
+     * @param size the length of the value in bytes
+     */
+    public DataEntity(String key, byte[] data, int size) {
+        this.mKey = checkNotNull(key);
+        this.mSize = size;
+        mValue = new byte[size];
+        for (int i = 0; i < size; i++) {
+            mValue[i] = data[i];
+        }
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        DataEntity that = (DataEntity) o;
+
+        if (mSize != that.mSize) {
+            return false;
+        }
+        if (!mKey.equals(that.mKey)) {
+            return false;
+        }
+        return Arrays.equals(mValue, that.mValue);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = mKey.hashCode();
+        result = 31 * result + Arrays.hashCode(mValue);
+        result = 31 * result + mSize;
+        return result;
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataInput.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataInput.java
new file mode 100644
index 0000000..7ac6ec4
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataInput.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2019 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.testing.shadows;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import android.annotation.Nullable;
+import android.app.backup.BackupDataInput;
+
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import java.io.ByteArrayInputStream;
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Shadow for BackupDataInput. */
+@Implements(BackupDataInput.class)
+public class ShadowBackupDataInput {
+    private static final List<DataEntity> ENTITIES = new ArrayList<>();
+    @Nullable private static IOException sReadNextHeaderException;
+
+    @Nullable private ByteArrayInputStream mCurrentEntityInputStream;
+    private int mCurrentEntity = -1;
+
+    /** Resets the shadow, clearing any entities or exception. */
+    public static void reset() {
+        ENTITIES.clear();
+        sReadNextHeaderException = null;
+    }
+
+    /** Sets the exception which the input will throw for any call to {@link #readNextHeader}. */
+    public static void setReadNextHeaderException(@Nullable IOException readNextHeaderException) {
+        ShadowBackupDataInput.sReadNextHeaderException = readNextHeaderException;
+    }
+
+    /** Adds the given entity to the input. */
+    public static void addEntity(DataEntity e) {
+        ENTITIES.add(e);
+    }
+
+    /** Adds an entity to the input with the given key and value. */
+    public static void addEntity(String key, byte[] value) {
+        ENTITIES.add(new DataEntity(key, value, value.length));
+    }
+
+    public void __constructor__(FileDescriptor fd) {}
+
+    @Implementation
+    public boolean readNextHeader() throws IOException {
+        if (sReadNextHeaderException != null) {
+            throw sReadNextHeaderException;
+        }
+
+        mCurrentEntity++;
+
+        if (mCurrentEntity >= ENTITIES.size()) {
+            return false;
+        }
+
+        byte[] value = ENTITIES.get(mCurrentEntity).mValue;
+        if (value == null) {
+            mCurrentEntityInputStream = new ByteArrayInputStream(new byte[0]);
+        } else {
+            mCurrentEntityInputStream = new ByteArrayInputStream(value);
+        }
+        return true;
+    }
+
+    @Implementation
+    public String getKey() {
+        return ENTITIES.get(mCurrentEntity).mKey;
+    }
+
+    @Implementation
+    public int getDataSize() {
+        return ENTITIES.get(mCurrentEntity).mSize;
+    }
+
+    @Implementation
+    public void skipEntityData() {
+        // Do nothing.
+    }
+
+    @Implementation
+    public int readEntityData(byte[] data, int offset, int size) {
+        checkState(mCurrentEntityInputStream != null, "Must call readNextHeader() first");
+        return mCurrentEntityInputStream.read(data, offset, size);
+    }
+}
diff --git a/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataOutput.java b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataOutput.java
new file mode 100644
index 0000000..2302e55
--- /dev/null
+++ b/packages/BackupEncryption/test/robolectric/src/com/android/server/testing/shadows/ShadowBackupDataOutput.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2019 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.testing.shadows;
+
+import android.app.backup.BackupDataOutput;
+
+import java.io.FileDescriptor;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Assert;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+/** Shadow for BackupDataOutput. */
+@Implements(BackupDataOutput.class)
+public class ShadowBackupDataOutput {
+    private static final List<DataEntity> ENTRIES = new ArrayList<>();
+
+    private String mCurrentKey;
+    private int mDataSize;
+
+    public static void reset() {
+        ENTRIES.clear();
+    }
+
+    public static Set<DataEntity> getEntities() {
+        return new LinkedHashSet<>(ENTRIES);
+    }
+
+    public void __constructor__(FileDescriptor fd) {}
+
+    public void __constructor__(FileDescriptor fd, long quota) {}
+
+    public void __constructor__(FileDescriptor fd, long quota, int transportFlags) {}
+
+    @Implementation
+    public int writeEntityHeader(String key, int size) {
+        mCurrentKey = key;
+        mDataSize = size;
+        return 0;
+    }
+
+    @Implementation
+    public int writeEntityData(byte[] data, int size) {
+        Assert.assertEquals("ShadowBackupDataOutput expects size = mDataSize", size, mDataSize);
+        ENTRIES.add(new DataEntity(mCurrentKey, data, mDataSize));
+        return 0;
+    }
+}
diff --git a/packages/BackupEncryption/test/unittest/Android.bp b/packages/BackupEncryption/test/unittest/Android.bp
new file mode 100644
index 0000000..d7c510b
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/Android.bp
@@ -0,0 +1,22 @@
+android_test {
+    name: "BackupEncryptionUnitTests",
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "androidx.test.runner",
+        "androidx.test.rules",
+        "mockito-target-minus-junit4",
+        "platform-test-annotations",
+        "truth-prebuilt",
+        "testables",
+        "testng",
+    ],
+    libs: [
+        "android.test.mock",
+        "android.test.base",
+        "android.test.runner",
+        "BackupEncryption",
+    ],
+    test_suites: ["device-tests"],
+    instrumentation_for: "BackupEncryption",
+    certificate: "platform",
+}
\ No newline at end of file
diff --git a/packages/BackupEncryption/test/unittest/AndroidManifest.xml b/packages/BackupEncryption/test/unittest/AndroidManifest.xml
new file mode 100644
index 0000000..39ac8aa
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.server.backup.encryption.unittests"
+          android:sharedUserId="android.uid.system" >
+    <application android:testOnly="true">
+        <uses-library android:name="android.test.runner" />
+    </application>
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.server.backup.encryption"
+        android:label="Backup Encryption Unit Tests" />
+</manifest>
\ No newline at end of file
diff --git a/packages/BackupEncryption/test/unittest/AndroidTest.xml b/packages/BackupEncryption/test/unittest/AndroidTest.xml
new file mode 100644
index 0000000..c9c812a
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/AndroidTest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+<configuration description="Runs Backup Encryption Unit Tests.">
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="install-arg" value="-t" />
+        <option name="test-file-name" value="BackupEncryptionUnitTests.apk" />
+    </target_preparer>
+
+    <option name="test-tag" value="BackupEncryptionUnitTests" />
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="com.android.server.backup.encryption.unittests" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+    </test>
+</configuration>
diff --git a/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManagerTest.java b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManagerTest.java
new file mode 100644
index 0000000..0d43a19
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportManagerTest.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.transport;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNotSame;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.content.ComponentName;
+import android.content.Intent;
+import android.os.Bundle;
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.backup.transport.TransportClient;
+import com.android.server.backup.transport.TransportClientManager;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+public class IntermediateEncryptingTransportManagerTest {
+    @Mock private TransportClient mTransportClient;
+    @Mock private TransportClientManager mTransportClientManager;
+
+    private final ComponentName mTransportComponent = new ComponentName("pkg", "class");
+    private final Bundle mExtras = new Bundle();
+    private Intent mEncryptingTransportIntent;
+    private IntermediateEncryptingTransportManager mIntermediateEncryptingTransportManager;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        mExtras.putInt("test", 1);
+        mEncryptingTransportIntent =
+                TransportClientManager.getEncryptingTransportIntent(mTransportComponent)
+                        .putExtras(mExtras);
+        mIntermediateEncryptingTransportManager =
+                new IntermediateEncryptingTransportManager(mTransportClientManager);
+    }
+
+    @Test
+    public void testGet_createsClientWithRealTransportComponentAndExtras() {
+        when(mTransportClientManager.getTransportClient(any(), any(), any()))
+                .thenReturn(mTransportClient);
+
+        IntermediateEncryptingTransport intermediateEncryptingTransport =
+                mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+
+        assertEquals(mTransportClient, intermediateEncryptingTransport.getClient());
+        verify(mTransportClientManager, times(1))
+                .getTransportClient(eq(mTransportComponent), argThat(mExtras::kindofEquals), any());
+        verifyNoMoreInteractions(mTransportClientManager);
+    }
+
+    @Test
+    public void testGet_callTwice_returnsSameTransport() {
+        IntermediateEncryptingTransport transport1 =
+                mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+        IntermediateEncryptingTransport transport2 =
+                mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+
+        assertEquals(transport1, transport2);
+    }
+
+    @Test
+    public void testCleanup_disposesTransportClient() {
+        when(mTransportClientManager.getTransportClient(any(), any(), any()))
+                .thenReturn(mTransportClient);
+
+        IntermediateEncryptingTransport transport =
+                mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+        mIntermediateEncryptingTransportManager.cleanup(mEncryptingTransportIntent);
+
+        verify(mTransportClientManager, times(1)).getTransportClient(any(), any(), any());
+        verify(mTransportClientManager, times(1))
+                .disposeOfTransportClient(eq(mTransportClient), any());
+        verifyNoMoreInteractions(mTransportClientManager);
+    }
+
+    @Test
+    public void testCleanup_removesCachedTransport() {
+        when(mTransportClientManager.getTransportClient(any(), any(), any()))
+                .thenReturn(mTransportClient);
+
+        IntermediateEncryptingTransport transport1 =
+                mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+        mIntermediateEncryptingTransportManager.cleanup(mEncryptingTransportIntent);
+        IntermediateEncryptingTransport transport2 =
+                mIntermediateEncryptingTransportManager.get(mEncryptingTransportIntent);
+
+        assertNotSame(transport1, transport2);
+    }
+}
diff --git a/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportTest.java b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportTest.java
new file mode 100644
index 0000000..cc4b0ab
--- /dev/null
+++ b/packages/BackupEncryption/test/unittest/src/com/android/server/backup/encryption/transport/IntermediateEncryptingTransportTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2019 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.backup.encryption.transport;
+
+import static junit.framework.Assert.assertEquals;
+
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.transport.TransportClient;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+public class IntermediateEncryptingTransportTest {
+    @Mock private IBackupTransport mRealTransport;
+    @Mock private TransportClient mTransportClient;
+
+    private IntermediateEncryptingTransport mIntermediateEncryptingTransport;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        mIntermediateEncryptingTransport = new IntermediateEncryptingTransport(mTransportClient);
+    }
+
+    @Test
+    public void testGetDelegate_callsConnect() throws Exception {
+        when(mTransportClient.connect(anyString())).thenReturn(mRealTransport);
+
+        IBackupTransport ret = mIntermediateEncryptingTransport.getDelegate();
+
+        assertEquals(mRealTransport, ret);
+        verify(mTransportClient, times(1)).connect(anyString());
+        verifyNoMoreInteractions(mTransportClient);
+    }
+
+    @Test
+    public void testGetDelegate_callTwice_callsConnectOnce() throws Exception {
+        when(mTransportClient.connect(anyString())).thenReturn(mRealTransport);
+
+        IBackupTransport ret1 = mIntermediateEncryptingTransport.getDelegate();
+        IBackupTransport ret2 = mIntermediateEncryptingTransport.getDelegate();
+
+        assertEquals(mRealTransport, ret1);
+        assertEquals(mRealTransport, ret2);
+        verify(mTransportClient, times(1)).connect(anyString());
+        verifyNoMoreInteractions(mTransportClient);
+    }
+}
diff --git a/packages/BackupRestoreConfirmation/res/values-fi/strings.xml b/packages/BackupRestoreConfirmation/res/values-fi/strings.xml
index 4517410..bc9dbde 100644
--- a/packages/BackupRestoreConfirmation/res/values-fi/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-fi/strings.xml
@@ -27,7 +27,7 @@
     <string name="current_password_text" msgid="8268189555578298067">"Kirjoita nykyinen varmuuskopioinnin salasana alla:"</string>
     <string name="device_encryption_restore_text" msgid="1570864916855208992">"Kirjoita laitteen salauksen salasana alle."</string>
     <string name="device_encryption_backup_text" msgid="5866590762672844664">"Kirjoita laitteen salauksen salasana alle. Salasanaa käytetään myös varmuuskopioarkiston salaamiseen."</string>
-    <string name="backup_enc_password_text" msgid="4981585714795233099">"Anna salasana kaikkien varmuuskopiotietojen salaamiseksi. Jos tämä jätetään tyhjäksi, nykyistä varmuuskopioinnin salasanaa käytetään:"</string>
+    <string name="backup_enc_password_text" msgid="4981585714795233099">"Lisää salasana kaikkien varmuuskopiotietojen salaamiseksi. Jos tämä jätetään tyhjäksi, nykyistä varmuuskopioinnin salasanaa käytetään:"</string>
     <string name="backup_enc_password_optional" msgid="1350137345907579306">"Jos haluat salata kaikki varmuuskopiotiedot, kirjoita salasana alle:"</string>
     <string name="backup_enc_password_required" msgid="7889652203371654149">"Koska laite on salattu, myös varmuuskopiointi on salattava. Kirjoita salasana alle:"</string>
     <string name="restore_enc_password_text" msgid="6140898525580710823">"Jos palautustiedot on salattu, anna salasana alla:"</string>
diff --git a/packages/BackupRestoreConfirmation/res/values-in/strings.xml b/packages/BackupRestoreConfirmation/res/values-in/strings.xml
index 63a3772..5c82adf 100644
--- a/packages/BackupRestoreConfirmation/res/values-in/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-in/strings.xml
@@ -16,9 +16,9 @@
 
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="backup_confirm_title" msgid="827563724209303345">"Backup sepenuhnya"</string>
+    <string name="backup_confirm_title" msgid="827563724209303345">"Pencadangan lengkap"</string>
     <string name="restore_confirm_title" msgid="5469365809567486602">"Pemulihan sepenuhnya"</string>
-    <string name="backup_confirm_text" msgid="1878021282758896593">"Backup lengkap semua data ke komputer yang tersambung telah diminta. Apakah Anda ingin mengizinkan hal ini dilakukan?\n\nJika Anda tidak meminta backup ini, jangan izinkan operasi dilanjutkan."</string>
+    <string name="backup_confirm_text" msgid="1878021282758896593">"Pencadangan semua data ke komputer yang tersambung telah diminta. Apakah Anda ingin mengizinkan hal ini dilakukan?\n\nJika Anda tidak meminta pencadangan ini, jangan izinkan operasi dilanjutkan."</string>
     <string name="allow_backup_button_label" msgid="4217228747769644068">"Cadangkan data saya"</string>
     <string name="deny_backup_button_label" msgid="6009119115581097708">"Jangan mencadangkan"</string>
     <string name="restore_confirm_text" msgid="7499866728030461776">"Pemulihan lengkap semua data dari komputer desktop yang tersambung telah diminta. Apakah Anda ingin mengizinkan hal ini?\n\nJika Anda tidak meminta pemulihan ini, jangan izinkan operasi dilanjutkan. Operasi ini akan mengganti data apa pun yang saat ini ada dalam perangkat!"</string>
@@ -31,8 +31,8 @@
     <string name="backup_enc_password_optional" msgid="1350137345907579306">"Jika Anda ingin mengenkripsi data cadangan lengkap, masukkan sandi di bawah:"</string>
     <string name="backup_enc_password_required" msgid="7889652203371654149">"Karena perangkat Anda dienkripsi, Anda perlu mengenkripsi cadangan. Masukkan sandi di bawah:"</string>
     <string name="restore_enc_password_text" msgid="6140898525580710823">"Jika data pemulihan dienkripsi, masukkan sandi di bawah:"</string>
-    <string name="toast_backup_started" msgid="550354281452756121">"Backup dimulai..."</string>
-    <string name="toast_backup_ended" msgid="3818080769548726424">"Backup selesai"</string>
+    <string name="toast_backup_started" msgid="550354281452756121">"Pencadangan dimulai..."</string>
+    <string name="toast_backup_ended" msgid="3818080769548726424">"Pencadangan selesai"</string>
     <string name="toast_restore_started" msgid="7881679218971277385">"Pemulihan dimulai..."</string>
     <string name="toast_restore_ended" msgid="1764041639199696132">"Pemulihan berakhir"</string>
     <string name="toast_timeout" msgid="5276598587087626877">"Waktu tunggu operasi habis"</string>
diff --git a/packages/CarSystemUI/res/layout/super_status_bar.xml b/packages/CarSystemUI/res/layout/super_status_bar.xml
index e1bcc2e..08d48bf 100644
--- a/packages/CarSystemUI/res/layout/super_status_bar.xml
+++ b/packages/CarSystemUI/res/layout/super_status_bar.xml
@@ -93,7 +93,7 @@
         android:layout_height="match_parent"
         android:visibility="invisible"/>
 
-    <include layout="@layout/status_bar_expanded"
+    <ViewStub android:id="@+id/status_bar_expanded"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:visibility="invisible"/>
diff --git a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
index 9a063aa..5ec1bae 100644
--- a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
+++ b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
@@ -29,6 +29,7 @@
 import com.android.systemui.power.EnhancedEstimatesImpl;
 import com.android.systemui.statusbar.NotificationLockscreenUserManager;
 import com.android.systemui.statusbar.NotificationLockscreenUserManagerImpl;
+import com.android.systemui.statusbar.car.CarStatusBar;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
 import com.android.systemui.statusbar.notification.collection.NotificationData;
@@ -42,6 +43,8 @@
 import dagger.Binds;
 import dagger.Module;
 import dagger.Provides;
+import dagger.multibindings.ClassKey;
+import dagger.multibindings.IntoMap;
 
 @Module
 abstract class CarSystemUIModule {
@@ -94,4 +97,9 @@
     @Binds
     abstract SystemUIRootComponent bindSystemUIRootComponent(
             CarSystemUIRootComponent systemUIRootComponent);
+
+    @Binds
+    @IntoMap
+    @ClassKey(StatusBar.class)
+    public abstract SystemUI providesStatusBar(CarStatusBar statusBar);
 }
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationEntryManager.java b/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationEntryManager.java
index a107dd7..53a88a9 100644
--- a/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationEntryManager.java
+++ b/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationEntryManager.java
@@ -15,11 +15,12 @@
  */
 package com.android.systemui.car;
 
-import android.content.Context;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
 
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.collection.NotificationData;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 
 import javax.inject.Inject;
 import javax.inject.Singleton;
@@ -34,8 +35,8 @@
 public class CarNotificationEntryManager extends NotificationEntryManager {
 
     @Inject
-    public CarNotificationEntryManager(Context context) {
-        super(context);
+    public CarNotificationEntryManager(NotificationData notificationData, NotifLog notifLog) {
+        super(notificationData, notifLog);
     }
 
     @Override
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationInterruptionStateProvider.java b/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationInterruptionStateProvider.java
index afd722b..447e579 100644
--- a/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationInterruptionStateProvider.java
+++ b/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationInterruptionStateProvider.java
@@ -22,6 +22,7 @@
 import com.android.systemui.statusbar.notification.NotificationFilter;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.policy.BatteryController;
 
 import javax.inject.Inject;
 import javax.inject.Singleton;
@@ -34,8 +35,9 @@
     @Inject
     public CarNotificationInterruptionStateProvider(Context context,
             NotificationFilter filter,
-            StatusBarStateController stateController) {
-        super(context, filter, stateController);
+            StatusBarStateController stateController,
+            BatteryController batteryController) {
+        super(context, filter, stateController, batteryController);
     }
 
     @Override
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarBatteryController.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarBatteryController.java
index 58f80a4..d79849c 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarBatteryController.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarBatteryController.java
@@ -257,6 +257,11 @@
         return false;
     }
 
+    @Override
+    public boolean isAodPowerSave() {
+        return false;
+    }
+
     private void notifyBatteryLevelChanged() {
         for (int i = 0, size = mChangeCallbacks.size(); i < size; i++) {
             mChangeCallbacks.get(i)
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index b0ab5b4..681d8f5 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -16,6 +16,8 @@
 
 package com.android.systemui.statusbar.car;
 
+import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME;
+
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
 import android.animation.ValueAnimator;
@@ -34,6 +36,7 @@
 import android.graphics.drawable.Drawable;
 import android.inputmethodservice.InputMethodService;
 import android.os.IBinder;
+import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.Display;
 import android.view.GestureDetector;
@@ -57,36 +60,85 @@
 import com.android.car.notification.NotificationDataManager;
 import com.android.car.notification.NotificationViewController;
 import com.android.car.notification.PreprocessingManager;
+import com.android.internal.logging.MetricsLogger;
 import com.android.internal.statusbar.RegisterStatusBarResult;
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.BatteryMeterView;
 import com.android.systemui.CarSystemUIFactory;
 import com.android.systemui.Dependency;
+import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
 import com.android.systemui.SystemUIFactory;
+import com.android.systemui.UiOffloadThread;
+import com.android.systemui.appops.AppOpsController;
+import com.android.systemui.assist.AssistManager;
+import com.android.systemui.broadcast.BroadcastDispatcher;
+import com.android.systemui.bubbles.BubbleController;
 import com.android.systemui.classifier.FalsingLog;
+import com.android.systemui.colorextraction.SysuiColorExtractor;
+import com.android.systemui.doze.DozeLog;
 import com.android.systemui.fragments.FragmentHostManager;
+import com.android.systemui.keyguard.KeyguardViewMediator;
 import com.android.systemui.keyguard.ScreenLifecycle;
+import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.FalsingManager;
 import com.android.systemui.plugins.qs.QS;
 import com.android.systemui.qs.car.CarQSFragment;
 import com.android.systemui.shared.system.ActivityManagerWrapper;
 import com.android.systemui.shared.system.TaskStackChangeListener;
 import com.android.systemui.statusbar.FlingAnimationUtils;
+import com.android.systemui.statusbar.NavigationBarController;
+import com.android.systemui.statusbar.NotificationListener;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
+import com.android.systemui.statusbar.NotificationMediaManager;
+import com.android.systemui.statusbar.NotificationRemoteInputManager;
+import com.android.systemui.statusbar.NotificationViewHierarchyManager;
+import com.android.systemui.statusbar.PulseExpansionHandler;
 import com.android.systemui.statusbar.StatusBarState;
+import com.android.systemui.statusbar.SysuiStatusBarStateController;
+import com.android.systemui.statusbar.VibratorHelper;
 import com.android.systemui.statusbar.car.hvac.HvacController;
 import com.android.systemui.statusbar.car.hvac.TemperatureView;
+import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
+import com.android.systemui.statusbar.notification.DynamicPrivacyController;
+import com.android.systemui.statusbar.notification.NotifPipelineInitializer;
+import com.android.systemui.statusbar.notification.NotificationAlertingManager;
+import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
+import com.android.systemui.statusbar.notification.VisualStabilityManager;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
+import com.android.systemui.statusbar.notification.logging.NotificationLogger;
+import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
+import com.android.systemui.statusbar.phone.AutoHideController;
 import com.android.systemui.statusbar.phone.CollapsedStatusBarFragment;
+import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
+import com.android.systemui.statusbar.phone.KeyguardBypassController;
+import com.android.systemui.statusbar.phone.LightBarController;
+import com.android.systemui.statusbar.phone.NotificationGroupAlertTransferHelper;
+import com.android.systemui.statusbar.phone.NotificationGroupManager;
 import com.android.systemui.statusbar.phone.StatusBar;
+import com.android.systemui.statusbar.phone.StatusBarIconController;
+import com.android.systemui.statusbar.phone.StatusBarWindowController;
+import com.android.systemui.statusbar.phone.StatusBarWindowViewController;
 import com.android.systemui.statusbar.policy.BatteryController;
+import com.android.systemui.statusbar.policy.ConfigurationController;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
+import com.android.systemui.statusbar.policy.NetworkController;
+import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler;
 import com.android.systemui.statusbar.policy.UserSwitcherController;
+import com.android.systemui.statusbar.policy.ZenModeController;
+import com.android.systemui.util.InjectionInflationController;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.Map;
 
+import javax.inject.Inject;
+import javax.inject.Named;
+
 /**
  * A status bar (and navigation bar) tailored for the automotive use case.
  */
@@ -175,6 +227,8 @@
     private boolean mHideNavBarForKeyboard;
     private boolean mBottomNavBarVisible;
 
+    private final NavigationBarController mNavigationBarController;
+
     private final CarPowerStateListener mCarPowerStateListener =
             (int state) -> {
                 // When the car powers on, clear all notifications and mute/unread states.
@@ -189,6 +243,120 @@
                 }
             };
 
+    @Inject
+    public CarStatusBar(
+            LightBarController lightBarController,
+            AutoHideController autoHideController,
+            KeyguardUpdateMonitor keyguardUpdateMonitor,
+            StatusBarIconController statusBarIconController,
+            DozeLog dozeLog,
+            InjectionInflationController injectionInflationController,
+            PulseExpansionHandler pulseExpansionHandler,
+            NotificationWakeUpCoordinator notificationWakeUpCoordinator,
+            KeyguardBypassController keyguardBypassController,
+            KeyguardStateController keyguardStateController,
+            HeadsUpManagerPhone headsUpManagerPhone,
+            DynamicPrivacyController dynamicPrivacyController,
+            BypassHeadsUpNotifier bypassHeadsUpNotifier,
+            @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowNotificationLongPress,
+            NotifPipelineInitializer notifPipelineInitializer,
+            FalsingManager falsingManager,
+            BroadcastDispatcher broadcastDispatcher,
+            RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler,
+            NotificationGutsManager notificationGutsManager,
+            NotificationLogger notificationLogger,
+            NotificationEntryManager notificationEntryManager,
+            NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+            NotificationViewHierarchyManager notificationViewHierarchyManager,
+            ForegroundServiceController foregroundServiceController,
+            AppOpsController appOpsController,
+            KeyguardViewMediator keyguardViewMediator,
+            ZenModeController zenModeController,
+            NotificationAlertingManager notificationAlertingManager,
+            DisplayMetrics displayMetrics,
+            MetricsLogger metricsLogger,
+            UiOffloadThread uiOffloadThread,
+            NotificationMediaManager notificationMediaManager,
+            NotificationLockscreenUserManager lockScreenUserManager,
+            NotificationRemoteInputManager remoteInputManager,
+            UserSwitcherController userSwitcherController,
+            NetworkController networkController,
+            BatteryController batteryController,
+            SysuiColorExtractor colorExtractor,
+            ScreenLifecycle screenLifecycle,
+            WakefulnessLifecycle wakefulnessLifecycle,
+            SysuiStatusBarStateController statusBarStateController,
+            VibratorHelper vibratorHelper,
+            BubbleController bubbleController,
+            NotificationGroupManager groupManager,
+            NotificationGroupAlertTransferHelper groupAlertTransferHelper,
+            VisualStabilityManager visualStabilityManager,
+            DeviceProvisionedController deviceProvisionedController,
+            NavigationBarController navigationBarController,
+            AssistManager assistManager,
+            NotificationListener notificationListener,
+            ConfigurationController configurationController,
+            StatusBarWindowController statusBarWindowController,
+            StatusBarWindowViewController.Builder statusBarWindowViewControllerBuild,
+            NotifLog notifLog) {
+        super(
+                lightBarController,
+                autoHideController,
+                keyguardUpdateMonitor,
+                statusBarIconController,
+                dozeLog,
+                injectionInflationController,
+                pulseExpansionHandler,
+                notificationWakeUpCoordinator,
+                keyguardBypassController,
+                keyguardStateController,
+                headsUpManagerPhone,
+                dynamicPrivacyController,
+                bypassHeadsUpNotifier,
+                allowNotificationLongPress,
+                notifPipelineInitializer,
+                falsingManager,
+                broadcastDispatcher,
+                remoteInputQuickSettingsDisabler,
+                notificationGutsManager,
+                notificationLogger,
+                notificationEntryManager,
+                notificationInterruptionStateProvider,
+                notificationViewHierarchyManager,
+                foregroundServiceController,
+                appOpsController,
+                keyguardViewMediator,
+                zenModeController,
+                notificationAlertingManager,
+                displayMetrics,
+                metricsLogger,
+                uiOffloadThread,
+                notificationMediaManager,
+                lockScreenUserManager,
+                remoteInputManager,
+                userSwitcherController,
+                networkController,
+                batteryController,
+                colorExtractor,
+                screenLifecycle,
+                wakefulnessLifecycle,
+                statusBarStateController,
+                vibratorHelper,
+                bubbleController,
+                groupManager,
+                groupAlertTransferHelper,
+                visualStabilityManager,
+                deviceProvisionedController,
+                navigationBarController,
+                assistManager,
+                notificationListener,
+                configurationController,
+                statusBarWindowController,
+                statusBarWindowViewControllerBuild,
+                notifLog);
+        mNavigationBarController = navigationBarController;
+    }
+
     @Override
     public void start() {
         // get the provisioned state before calling the parent class since it's that flow that
@@ -616,7 +784,7 @@
             return;
         }
         mStatusBarWindowController.setStatusBarFocusable(false);
-        mStatusBarWindow.cancelExpandHelper();
+        mStatusBarWindowViewController.cancelExpandHelper();
         mStatusBarView.collapsePanel(true /* animate */, delayed, speedUpFactor);
 
         animateNotificationPanel(mClosingVelocity, true);
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java
index 827a59e..743ab47 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/UserGridRecyclerView.java
@@ -23,13 +23,17 @@
 import android.app.AlertDialog.Builder;
 import android.app.Dialog;
 import android.car.userlib.CarUserManagerHelper;
+import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.UserInfo;
 import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.Rect;
 import android.os.AsyncTask;
+import android.os.UserHandle;
 import android.util.AttributeSet;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -53,13 +57,19 @@
  * Displays a GridLayout with icons for the users in the system to allow switching between users.
  * One of the uses of this is for the lock screen in auto.
  */
-public class UserGridRecyclerView extends RecyclerView implements
-        CarUserManagerHelper.OnUsersUpdateListener {
+public class UserGridRecyclerView extends RecyclerView {
     private UserSelectionListener mUserSelectionListener;
     private UserAdapter mAdapter;
     private CarUserManagerHelper mCarUserManagerHelper;
     private Context mContext;
 
+    private final BroadcastReceiver mUserUpdateReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            onUsersUpdate();
+        }
+    };
+
     public UserGridRecyclerView(Context context, AttributeSet attrs) {
         super(context, attrs);
         mContext = context;
@@ -75,7 +85,7 @@
     @Override
     public void onFinishInflate() {
         super.onFinishInflate();
-        mCarUserManagerHelper.registerOnUsersUpdateListener(this);
+        registerForUserEvents();
     }
 
     /**
@@ -84,7 +94,7 @@
     @Override
     public void onDetachedFromWindow() {
         super.onDetachedFromWindow();
-        mCarUserManagerHelper.unregisterOnUsersUpdateListener(this);
+        unregisterForUserEvents();
     }
 
     /**
@@ -161,13 +171,32 @@
         mUserSelectionListener = userSelectionListener;
     }
 
-    @Override
-    public void onUsersUpdate() {
+    private void onUsersUpdate() {
         mAdapter.clearUsers();
         mAdapter.updateUsers(createUserRecords(mCarUserManagerHelper.getAllUsers()));
         mAdapter.notifyDataSetChanged();
     }
 
+    private void registerForUserEvents() {
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(Intent.ACTION_USER_REMOVED);
+        filter.addAction(Intent.ACTION_USER_ADDED);
+        filter.addAction(Intent.ACTION_USER_INFO_CHANGED);
+        filter.addAction(Intent.ACTION_USER_SWITCHED);
+        filter.addAction(Intent.ACTION_USER_STOPPED);
+        filter.addAction(Intent.ACTION_USER_UNLOCKED);
+        mContext.registerReceiverAsUser(
+                mUserUpdateReceiver,
+                UserHandle.ALL,
+                filter,
+                /* broadcastPermission= */ null,
+                /* scheduler= */ null);
+    }
+
+    private void unregisterForUserEvents() {
+        mContext.unregisterReceiver(mUserUpdateReceiver);
+    }
+
     /**
      * Adapter to populate the grid layout with the available user profiles
      */
diff --git a/packages/SettingsLib/SearchWidget/res/values-km/strings.xml b/packages/SettingsLib/SearchWidget/res/values-km/strings.xml
index f012e3a..7ac9cb1 100644
--- a/packages/SettingsLib/SearchWidget/res/values-km/strings.xml
+++ b/packages/SettingsLib/SearchWidget/res/values-km/strings.xml
@@ -17,5 +17,5 @@
 
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="search_menu" msgid="1604061903696928905">"ការកំណត់ការ​ស្វែងរក"</string>
+    <string name="search_menu" msgid="1604061903696928905">"​ស្វែងរកការកំណត់"</string>
 </resources>
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ActivityTile.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ActivityTile.java
new file mode 100644
index 0000000..06a4a45
--- /dev/null
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/ActivityTile.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2019 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.settingslib.drawer;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ComponentInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.Parcel;
+import android.util.Log;
+
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Description of a single dashboard tile which is generated from an activity.
+ */
+public class ActivityTile extends Tile {
+    private static final String TAG = "ActivityTile";
+
+    public ActivityTile(ComponentInfo info, String category) {
+        super(info, category);
+        setMetaData(info.metaData);
+    }
+
+    ActivityTile(Parcel in) {
+        super(in);
+    }
+
+    @Override
+    public int getId() {
+        return Objects.hash(getPackageName(), getComponentName());
+    }
+
+    @Override
+    public String getDescription() {
+        return getPackageName() + "/" + getComponentName();
+    }
+
+    @Override
+    protected CharSequence getComponentLabel(Context context) {
+        final PackageManager pm = context.getPackageManager();
+        final ComponentInfo info = getComponentInfo(context);
+        return info == null
+                ? null
+                : info.loadLabel(pm);
+    }
+
+    @Override
+    protected ComponentInfo getComponentInfo(Context context) {
+        if (mComponentInfo == null) {
+            final PackageManager pm = context.getApplicationContext().getPackageManager();
+            final Intent intent = getIntent();
+            final List<ResolveInfo> infoList =
+                    pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
+            if (infoList != null && !infoList.isEmpty()) {
+                mComponentInfo = infoList.get(0).activityInfo;
+                setMetaData(mComponentInfo.metaData);
+            } else {
+                Log.e(TAG, "Cannot find package info for "
+                        + intent.getComponent().flattenToString());
+            }
+        }
+        return mComponentInfo;
+    }
+}
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/Tile.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/Tile.java
index ca2d1ed..722f734 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/Tile.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/Tile.java
@@ -30,9 +30,8 @@
 
 import android.content.Context;
 import android.content.Intent;
-import android.content.pm.ActivityInfo;
+import android.content.pm.ComponentInfo;
 import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.graphics.drawable.Icon;
@@ -47,13 +46,11 @@
 
 import java.util.ArrayList;
 import java.util.Comparator;
-import java.util.List;
-import java.util.Objects;
 
 /**
  * Description of a single dashboard tile that the user can select.
  */
-public class Tile implements Parcelable {
+public abstract class Tile implements Parcelable {
 
     private static final String TAG = "Tile";
 
@@ -64,28 +61,27 @@
 
     @VisibleForTesting
     long mLastUpdateTime;
-    private final String mActivityPackage;
-    private final String mActivityName;
+    private final String mComponentPackage;
+    private final String mComponentName;
     private final Intent mIntent;
 
-    private ActivityInfo mActivityInfo;
+    protected ComponentInfo mComponentInfo;
     private CharSequence mSummaryOverride;
     private Bundle mMetaData;
     private String mCategory;
 
-    public Tile(ActivityInfo activityInfo, String category) {
-        mActivityInfo = activityInfo;
-        mActivityPackage = mActivityInfo.packageName;
-        mActivityName = mActivityInfo.name;
-        mMetaData = activityInfo.metaData;
+    public Tile(ComponentInfo info, String category) {
+        mComponentInfo = info;
+        mComponentPackage = mComponentInfo.packageName;
+        mComponentName = mComponentInfo.name;
         mCategory = category;
-        mIntent = new Intent().setClassName(mActivityPackage, mActivityName);
+        mIntent = new Intent().setClassName(mComponentPackage, mComponentName);
     }
 
     Tile(Parcel in) {
-        mActivityPackage = in.readString();
-        mActivityName = in.readString();
-        mIntent = new Intent().setClassName(mActivityPackage, mActivityName);
+        mComponentPackage = in.readString();
+        mComponentName = in.readString();
+        mIntent = new Intent().setClassName(mComponentPackage, mComponentName);
         final int number = in.readInt();
         for (int i = 0; i < number; i++) {
             userHandle.add(UserHandle.CREATOR.createFromParcel(in));
@@ -101,8 +97,8 @@
 
     @Override
     public void writeToParcel(Parcel dest, int flags) {
-        dest.writeString(mActivityPackage);
-        dest.writeString(mActivityName);
+        dest.writeString(mComponentPackage);
+        dest.writeString(mComponentName);
         final int size = userHandle.size();
         dest.writeInt(size);
         for (int i = 0; i < size; i++) {
@@ -112,16 +108,22 @@
         dest.writeBundle(mMetaData);
     }
 
-    public int getId() {
-        return Objects.hash(mActivityPackage, mActivityName);
-    }
+    /**
+     * Unique ID of the tile
+     */
+    public abstract int getId();
 
-    public String getDescription() {
-        return mActivityPackage + "/" + mActivityName;
-    }
+    /**
+     * Human-readable description of the tile
+     */
+    public abstract String getDescription();
 
     public String getPackageName() {
-        return mActivityPackage;
+        return mComponentPackage;
+    }
+
+    public String getComponentName() {
+        return mComponentName;
     }
 
     /**
@@ -154,7 +156,7 @@
     }
 
     /**
-     * Check whether title has order.
+     * Check whether tile has order.
      */
     public boolean hasOrder() {
         return mMetaData.containsKey(META_DATA_KEY_ORDER)
@@ -170,14 +172,14 @@
         final PackageManager packageManager = context.getPackageManager();
         if (mMetaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
             if (mMetaData.containsKey(META_DATA_PREFERENCE_TITLE_URI)) {
-                // If has as uri to provide dynamic summary, skip loading here. UI will later load
+                // If has as uri to provide dynamic title, skip loading here. UI will later load
                 // at tile binding time.
                 return null;
             }
             if (mMetaData.get(META_DATA_PREFERENCE_TITLE) instanceof Integer) {
                 try {
                     final Resources res =
-                            packageManager.getResourcesForApplication(mActivityPackage);
+                            packageManager.getResourcesForApplication(mComponentPackage);
                     title = res.getString(mMetaData.getInt(META_DATA_PREFERENCE_TITLE));
                 } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
                     Log.w(TAG, "Couldn't find info", e);
@@ -186,18 +188,15 @@
                 title = mMetaData.getString(META_DATA_PREFERENCE_TITLE);
             }
         }
-        // Set the preference title to the activity's label if no
-        // meta-data is found
+        // Set the preference title by the component if no meta-data is found
         if (title == null) {
-            final ActivityInfo activityInfo = getActivityInfo(context);
-            if (activityInfo == null) {
-                return null;
-            }
-            title = activityInfo.loadLabel(packageManager);
+            title = getComponentLabel(context);
         }
         return title;
     }
 
+    protected abstract CharSequence getComponentLabel(Context context);
+
     /**
      * Overrides the summary. This can happen when injected tile wants to provide dynamic summary.
      */
@@ -225,7 +224,7 @@
                 if (mMetaData.get(META_DATA_PREFERENCE_SUMMARY) instanceof Integer) {
                     try {
                         final Resources res =
-                                packageManager.getResourcesForApplication(mActivityPackage);
+                                packageManager.getResourcesForApplication(mComponentPackage);
                         summary = res.getString(mMetaData.getInt(META_DATA_PREFERENCE_SUMMARY));
                     } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
                         Log.d(TAG, "Couldn't find info", e);
@@ -281,24 +280,24 @@
             return null;
         }
         ensureMetadataNotStale(context);
-        final ActivityInfo activityInfo = getActivityInfo(context);
-        if (activityInfo == null) {
-            Log.w(TAG, "Cannot find ActivityInfo for " + getDescription());
+        final ComponentInfo componentInfo = getComponentInfo(context);
+        if (componentInfo == null) {
+            Log.w(TAG, "Cannot find ComponentInfo for " + getDescription());
             return null;
         }
 
         int iconResId = mMetaData.getInt(META_DATA_PREFERENCE_ICON);
         // Set the icon
         if (iconResId == 0) {
-            // Only fallback to activityinfo.icon if metadata does not contain ICON_URI.
+            // Only fallback to componentInfo.icon if metadata does not contain ICON_URI.
             // ICON_URI should be loaded in app UI when need the icon object. Handling IPC at this
             // level is too complex because we don't have a strong threading contract for this class
             if (!mMetaData.containsKey(META_DATA_PREFERENCE_ICON_URI)) {
-                iconResId = activityInfo.icon;
+                iconResId = componentInfo.icon;
             }
         }
         if (iconResId != 0) {
-            final Icon icon = Icon.createWithResource(activityInfo.packageName, iconResId);
+            final Icon icon = Icon.createWithResource(componentInfo.packageName, iconResId);
             if (isIconTintable(context)) {
                 final TypedArray a = context.obtainStyledAttributes(new int[]{
                         android.R.attr.colorControlNormal});
@@ -331,41 +330,26 @@
         final PackageManager pm = context.getApplicationContext().getPackageManager();
 
         try {
-            final long lastUpdateTime = pm.getPackageInfo(mActivityPackage,
+            final long lastUpdateTime = pm.getPackageInfo(mComponentPackage,
                     PackageManager.GET_META_DATA).lastUpdateTime;
             if (lastUpdateTime == mLastUpdateTime) {
                 // All good. Do nothing
                 return;
             }
             // App has been updated since we load metadata last time. Reload metadata.
-            mActivityInfo = null;
-            getActivityInfo(context);
+            mComponentInfo = null;
+            getComponentInfo(context);
             mLastUpdateTime = lastUpdateTime;
         } catch (PackageManager.NameNotFoundException e) {
             Log.d(TAG, "Can't find package, probably uninstalled.");
         }
     }
 
-    private ActivityInfo getActivityInfo(Context context) {
-        if (mActivityInfo == null) {
-            final PackageManager pm = context.getApplicationContext().getPackageManager();
-            final Intent intent = new Intent().setClassName(mActivityPackage, mActivityName);
-            final List<ResolveInfo> infoList =
-                    pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
-            if (infoList != null && !infoList.isEmpty()) {
-                mActivityInfo = infoList.get(0).activityInfo;
-                mMetaData = mActivityInfo.metaData;
-            } else {
-                Log.e(TAG, "Cannot find package info for "
-                        + intent.getComponent().flattenToString());
-            }
-        }
-        return mActivityInfo;
-    }
+    protected abstract ComponentInfo getComponentInfo(Context context);
 
     public static final Creator<Tile> CREATOR = new Creator<Tile>() {
         public Tile createFromParcel(Parcel source) {
-            return new Tile(source);
+            return new ActivityTile(source);
         }
 
         public Tile[] newArray(int size) {
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
index aced5ef..c4df2e8 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
@@ -20,6 +20,7 @@
 import android.content.IContentProvider;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
+import android.content.pm.ComponentInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.net.Uri;
@@ -127,6 +128,7 @@
      */
     public static final String META_DATA_PREFERENCE_ICON_BACKGROUND_HINT =
             "com.android.settings.bg.hint";
+
     /**
      * Name of the meta-data item that should be set in the AndroidManifest.xml
      * to specify the icon background color as raw ARGB.
@@ -220,10 +222,11 @@
     public static List<DashboardCategory> getCategories(Context context,
             Map<Pair<String, String>, Tile> cache) {
         final long startTime = System.currentTimeMillis();
-        boolean setup = Global.getInt(context.getContentResolver(), Global.DEVICE_PROVISIONED, 0)
-                != 0;
-        ArrayList<Tile> tiles = new ArrayList<>();
-        UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
+        final boolean setup =
+                Global.getInt(context.getContentResolver(), Global.DEVICE_PROVISIONED, 0) != 0;
+        final ArrayList<Tile> tiles = new ArrayList<>();
+        final UserManager userManager = (UserManager) context.getSystemService(
+                Context.USER_SERVICE);
         for (UserHandle user : userManager.getUserProfiles()) {
             // TODO: Needs much optimization, too many PM queries going on here.
             if (user.getIdentifier() == ActivityManager.getCurrentUser()) {
@@ -240,7 +243,7 @@
             }
         }
 
-        HashMap<String, DashboardCategory> categoryMap = new HashMap<>();
+        final HashMap<String, DashboardCategory> categoryMap = new HashMap<>();
         for (Tile tile : tiles) {
             final String categoryKey = tile.getCategory();
             DashboardCategory category = categoryMap.get(categoryKey);
@@ -255,7 +258,7 @@
             }
             category.addTile(tile);
         }
-        ArrayList<DashboardCategory> categories = new ArrayList<>(categoryMap.values());
+        final ArrayList<DashboardCategory> categories = new ArrayList<>(categoryMap.values());
         for (DashboardCategory category : categories) {
             category.sortTiles();
         }
@@ -275,63 +278,90 @@
         if (requireSettings) {
             intent.setPackage(SETTING_PKG);
         }
+        getActivityTiles(context, user, addedCache, defaultCategory, outTiles, intent);
+    }
+
+    private static void getActivityTiles(Context context,
+            UserHandle user, Map<Pair<String, String>, Tile> addedCache,
+            String defaultCategory, List<Tile> outTiles, Intent intent) {
         final PackageManager pm = context.getPackageManager();
-        List<ResolveInfo> results = pm.queryIntentActivitiesAsUser(intent,
+        final List<ResolveInfo> results = pm.queryIntentActivitiesAsUser(intent,
                 PackageManager.GET_META_DATA, user.getIdentifier());
         for (ResolveInfo resolved : results) {
             if (!resolved.system) {
                 // Do not allow any app to add to settings, only system ones.
                 continue;
             }
-            ActivityInfo activityInfo = resolved.activityInfo;
-            Bundle metaData = activityInfo.metaData;
-            String categoryKey = defaultCategory;
-
-            // Load category
-            if ((metaData == null || !metaData.containsKey(EXTRA_CATEGORY_KEY))
-                    && categoryKey == null) {
-                Log.w(LOG_TAG, "Found " + resolved.activityInfo.name + " for intent "
-                        + intent + " missing metadata "
-                        + (metaData == null ? "" : EXTRA_CATEGORY_KEY));
-                continue;
-            } else {
-                categoryKey = metaData.getString(EXTRA_CATEGORY_KEY);
-            }
-
-            Pair<String, String> key = new Pair<>(activityInfo.packageName, activityInfo.name);
-            Tile tile = addedCache.get(key);
-            if (tile == null) {
-                tile = new Tile(activityInfo, categoryKey);
-                addedCache.put(key, tile);
-            } else {
-                tile.setMetaData(metaData);
-            }
-
-            if (!tile.userHandle.contains(user)) {
-                tile.userHandle.add(user);
-            }
-            if (!outTiles.contains(tile)) {
-                outTiles.add(tile);
-            }
+            final ActivityInfo activityInfo = resolved.activityInfo;
+            final Bundle metaData = activityInfo.metaData;
+            getTile(user, addedCache, defaultCategory, outTiles, intent, metaData, activityInfo);
         }
     }
 
+    private static void getTile(UserHandle user, Map<Pair<String, String>, Tile> addedCache,
+            String defaultCategory, List<Tile> outTiles, Intent intent, Bundle metaData,
+            ComponentInfo componentInfo) {
+        String categoryKey = defaultCategory;
+        // Load category
+        if ((metaData == null || !metaData.containsKey(EXTRA_CATEGORY_KEY))
+                && categoryKey == null) {
+            Log.w(LOG_TAG, "Found " + componentInfo.name + " for intent "
+                    + intent + " missing metadata "
+                    + (metaData == null ? "" : EXTRA_CATEGORY_KEY));
+            return;
+        } else {
+            categoryKey = metaData.getString(EXTRA_CATEGORY_KEY);
+        }
+
+        final Pair<String, String> key = new Pair<>(componentInfo.packageName, componentInfo.name);
+        Tile tile = addedCache.get(key);
+        if (tile == null) {
+            tile = new ActivityTile(componentInfo, categoryKey);
+            addedCache.put(key, tile);
+        } else {
+            tile.setMetaData(metaData);
+        }
+
+        if (!tile.userHandle.contains(user)) {
+            tile.userHandle.add(user);
+        }
+        if (!outTiles.contains(tile)) {
+            outTiles.add(tile);
+        }
+    }
+
+    /**
+     * Returns the complete uri from the meta data key of the tile.
+
+     * @param tile          Tile which contains meta data
+     * @param metaDataKey   Key mapping to the uri in meta data
+     * @return Uri associated with the key
+     */
+    public static Uri getCompleteUri(Tile tile, String metaDataKey) {
+        final String uriString = tile.getMetaData().getString(metaDataKey);
+        if (TextUtils.isEmpty(uriString)) {
+            return null;
+        }
+
+        return Uri.parse(uriString);
+    }
+
     /**
      * Gets the icon package name and resource id from content provider.
      *
      * @param context     context
      * @param packageName package name of the target activity
-     * @param uriString   URI for the content provider
+     * @param uri         URI for the content provider
      * @param providerMap Maps URI authorities to providers
      * @return package name and resource id of the icon specified
      */
     public static Pair<String, Integer> getIconFromUri(Context context, String packageName,
-            String uriString, Map<String, IContentProvider> providerMap) {
-        Bundle bundle = getBundleFromUri(context, uriString, providerMap);
+            Uri uri, Map<String, IContentProvider> providerMap) {
+        final Bundle bundle = getBundleFromUri(context, uri, providerMap, null);
         if (bundle == null) {
             return null;
         }
-        String iconPackageName = bundle.getString(EXTRA_PREFERENCE_ICON_PACKAGE);
+        final String iconPackageName = bundle.getString(EXTRA_PREFERENCE_ICON_PACKAGE);
         if (TextUtils.isEmpty(iconPackageName)) {
             return null;
         }
@@ -342,7 +372,7 @@
         // Icon can either come from the target package or from the Settings app.
         if (iconPackageName.equals(packageName)
                 || iconPackageName.equals(context.getPackageName())) {
-            return Pair.create(iconPackageName, bundle.getInt(META_DATA_PREFERENCE_ICON, 0));
+            return Pair.create(iconPackageName, resId);
         }
         return null;
     }
@@ -351,34 +381,33 @@
      * Gets text associated with the input key from the content provider.
      *
      * @param context     context
-     * @param uriString   URI for the content provider
+     * @param uri         URI for the content provider
      * @param providerMap Maps URI authorities to providers
      * @param key         Key mapping to the text in bundle returned by the content provider
      * @return Text associated with the key, if returned by the content provider
      */
-    public static String getTextFromUri(Context context, String uriString,
+    public static String getTextFromUri(Context context, Uri uri,
             Map<String, IContentProvider> providerMap, String key) {
-        Bundle bundle = getBundleFromUri(context, uriString, providerMap);
+        final Bundle bundle = getBundleFromUri(context, uri, providerMap, null);
         return (bundle != null) ? bundle.getString(key) : null;
     }
 
-    private static Bundle getBundleFromUri(Context context, String uriString,
-            Map<String, IContentProvider> providerMap) {
-        if (TextUtils.isEmpty(uriString)) {
+    private static Bundle getBundleFromUri(Context context, Uri uri,
+            Map<String, IContentProvider> providerMap, Bundle bundle) {
+        if (uri == null) {
             return null;
         }
-        Uri uri = Uri.parse(uriString);
-        String method = getMethodFromUri(uri);
+        final String method = getMethodFromUri(uri);
         if (TextUtils.isEmpty(method)) {
             return null;
         }
-        IContentProvider provider = getProviderFromUri(context, uri, providerMap);
+        final IContentProvider provider = getProviderFromUri(context, uri, providerMap);
         if (provider == null) {
             return null;
         }
         try {
             return provider.call(context.getPackageName(), uri.getAuthority(),
-                    method, uriString, null);
+                    method, uri.toString(), bundle);
         } catch (RemoteException e) {
             return null;
         }
@@ -389,7 +418,7 @@
         if (uri == null) {
             return null;
         }
-        String authority = uri.getAuthority();
+        final String authority = uri.getAuthority();
         if (TextUtils.isEmpty(authority)) {
             return null;
         }
@@ -400,7 +429,7 @@
     }
 
     /** Returns the first path segment of the uri if it exists as the method, otherwise null. */
-    static String getMethodFromUri(Uri uri) {
+    private static String getMethodFromUri(Uri uri) {
         if (uri == null) {
             return null;
         }
diff --git a/packages/SettingsLib/res/values-af/strings.xml b/packages/SettingsLib/res/values-af/strings.xml
index 4cedc93..245ca14 100644
--- a/packages/SettingsLib/res/values-af/strings.xml
+++ b/packages/SettingsLib/res/values-af/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet kan binnekort afgaan (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Toestel kan binnekort afgaan (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> oor tot vol gelaai"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> tot vol gelaai"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> oor tot battery gelaai is"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> tot battery gelaai is"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Onbekend"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Laai"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"laai tans"</string>
diff --git a/packages/SettingsLib/res/values-am/strings.xml b/packages/SettingsLib/res/values-am/strings.xml
index 3b7abdb..bfd3196 100644
--- a/packages/SettingsLib/res/values-am/strings.xml
+++ b/packages/SettingsLib/res/values-am/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ጡባዊው በቅርቡ ሊዘጋ ይችላል (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"መሣሪያው በቅርቡ ሊዘጋ ይችላል (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"ሙሉ ኃይል እስኪሞላ ድረስ <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - ሙሉ ለሙሉ እስኪሞላ ድረስ <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> ኃይል እስከሚሞላ ድረስ ይቀራል"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ኃይል እስከሚሞላ ድረስ"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"ያልታወቀ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ኃይል በመሙላት ላይ"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ኃይል በመሙላት ላይ"</string>
diff --git a/packages/SettingsLib/res/values-ar/strings.xml b/packages/SettingsLib/res/values-ar/strings.xml
index df1ec30..8b67b0b 100644
--- a/packages/SettingsLib/res/values-ar/strings.xml
+++ b/packages/SettingsLib/res/values-ar/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"قد يتم إغلاق الجهاز اللوحي بعد قليل (<xliff:g id="LEVEL">%1$s</xliff:g>)."</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"قد يتم إغلاق الجهاز بعد قليل (<xliff:g id="LEVEL">%1$s</xliff:g>)."</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"يتبقى <xliff:g id="TIME">%1$s</xliff:g> لشحن البطارية بالكامل"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> حتى يكتمل الشحن"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> إلى أن يتم شحن الجهاز بالكامل"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> إلى أن يتم شحن الجهاز بالكامل"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"غير معروف"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"جارٍ الشحن"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"جارٍ الشحن"</string>
diff --git a/packages/SettingsLib/res/values-as/strings.xml b/packages/SettingsLib/res/values-as/strings.xml
index 9c25b66..f3ca337 100644
--- a/packages/SettingsLib/res/values-as/strings.xml
+++ b/packages/SettingsLib/res/values-as/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"টেবলেটটো সোনকালেই বন্ধ হ\'ব পাৰে (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ডিভাইচটো সোনকালেই বন্ধ হ\'ব পাৰে (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"সম্পূৰ্ণকৈ চ্চাৰ্জ হ\'বলৈ <xliff:g id="TIME">%1$s</xliff:g> বাকী"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> সম্পূৰ্ণৰূপে চ্চাৰ্জ হোৱা পৰ্যন্ত"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"চাৰ্জ হ’বলৈ <xliff:g id="TIME">%1$s</xliff:g> বাকী আছে"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> চাৰ্জ হ\'বলৈ"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"অজ্ঞাত"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"চাৰ্জ কৰি থকা হৈছে"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"চ্চাৰ্জ হৈ আছে"</string>
diff --git a/packages/SettingsLib/res/values-az/strings.xml b/packages/SettingsLib/res/values-az/strings.xml
index 3a6d301..d35dfe8 100644
--- a/packages/SettingsLib/res/values-az/strings.xml
+++ b/packages/SettingsLib/res/values-az/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Planşet tezliklə sönə bilər (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Cihaz tezliklə sönə bilər (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Tam enerji yığmağına <xliff:g id="TIME">%1$s</xliff:g> qalıb"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> tam enerji yığana kimi"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Enerjinin dolmasına <xliff:g id="TIME">%1$s</xliff:g> qalıb"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - Enerjinin dolmasına <xliff:g id="TIME">%2$s</xliff:g> qalıb"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Naməlum"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Enerji doldurma"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"enerji yığır"</string>
diff --git a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
index a8808fa..448de4b 100644
--- a/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
+++ b/packages/SettingsLib/res/values-b+sr+Latn/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet će se uskoro isključiti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Uređaj će se uskoro isključiti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> do potpunog punjenja"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do potpunog punjenja"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Napuniće se za <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – napuniće se za <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Nepoznato"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Puni se"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"puni se"</string>
diff --git a/packages/SettingsLib/res/values-be/strings.xml b/packages/SettingsLib/res/values-be/strings.xml
index 05d9a5d..d68c0f3 100644
--- a/packages/SettingsLib/res/values-be/strings.xml
+++ b/packages/SettingsLib/res/values-be/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Узровень зараду батарэі: <xliff:g id="LEVEL">%1$s</xliff:g>. Планшэт хутка спыніць працу."</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Узровень зараду батарэі: <xliff:g id="LEVEL">%1$s</xliff:g>. Прылада хутка спыніць працу."</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Да поўнай зарадкі засталося <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> да поўнай зарадкі"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Засталося <xliff:g id="TIME">%1$s</xliff:g> да поўнай зарадкі"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> да поўнай зарадкі"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Невядома"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Зарадка"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ідзе зарадка"</string>
diff --git a/packages/SettingsLib/res/values-bg/strings.xml b/packages/SettingsLib/res/values-bg/strings.xml
index 7fa5b06..cb99f64 100644
--- a/packages/SettingsLib/res/values-bg/strings.xml
+++ b/packages/SettingsLib/res/values-bg/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Възможно е таблетът да се изключи скоро (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Възможно е устройството да се изключи скоро (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Оставащо време до пълно зареждане: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> до пълно зареждане"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Оставащо време до пълно зареждане: <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> до пълно зареждане"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Неизвестно"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Зарежда се"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"зарежда се"</string>
diff --git a/packages/SettingsLib/res/values-bn/strings.xml b/packages/SettingsLib/res/values-bn/strings.xml
index f1fc9f9..f2f4f52 100644
--- a/packages/SettingsLib/res/values-bn/strings.xml
+++ b/packages/SettingsLib/res/values-bn/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ট্যাবলেটটি শীঘ্রই বন্ধ হয়ে যেতে পারে (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ডিভাইসটি শীঘ্রই বন্ধ হয়ে যেতে পারে (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"সম্পূর্ণ চার্জ হতে <xliff:g id="TIME">%1$s</xliff:g> বাকি"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - সম্পূর্ণ চার্জ হতে <xliff:g id="TIME">%2$s</xliff:g> লাগবে"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"সম্পূর্ণ চার্জ হতে <xliff:g id="TIME">%1$s</xliff:g> বাকি আছে"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g>-এ সম্পূর্ণ চার্জ হয়ে যাবে"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"অজানা"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"চার্জ হচ্ছে"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"চার্জ হচ্ছে"</string>
diff --git a/packages/SettingsLib/res/values-bs/strings.xml b/packages/SettingsLib/res/values-bs/strings.xml
index 02b2a8b..45b8dd9 100644
--- a/packages/SettingsLib/res/values-bs/strings.xml
+++ b/packages/SettingsLib/res/values-bs/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet će se uskoro isključiti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Uređaj će se uskoro isključiti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Još <xliff:g id="TIME">%1$s</xliff:g> do potpune napunjenosti"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> do potpune napunjenosti"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Napunit će se za <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – napunit će se za <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Nepoznato"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Punjenje"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"punjenje"</string>
diff --git a/packages/SettingsLib/res/values-ca/strings.xml b/packages/SettingsLib/res/values-ca/strings.xml
index afdb105..bd1ed6a 100644
--- a/packages/SettingsLib/res/values-ca/strings.xml
+++ b/packages/SettingsLib/res/values-ca/strings.xml
@@ -385,10 +385,10 @@
     <string name="power_discharging_duration_enhanced" msgid="1992003260664804080">"Temps restant aproximat segons l\'ús que en fas: <xliff:g id="TIME_REMAINING">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
     <!-- no translation found for power_remaining_duration_only_short (9183070574408359726) -->
     <skip />
-    <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"La bateria hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g> segons l\'ús que en fas (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"La bateria hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g> segons l\'ús que en fas"</string>
-    <string name="power_discharge_by" msgid="6453537733650125582">"La bateria hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only" msgid="107616694963545745">"La bateria hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"Hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g> segons l\'ús que en facis (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
+    <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"Hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g> segons l\'ús que en facis"</string>
+    <string name="power_discharge_by" msgid="6453537733650125582">"Hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
+    <string name="power_discharge_by_only" msgid="107616694963545745">"Hauria de durar aproximadament fins a les <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by_only_short" msgid="1372817269546888804">"Fins a les <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_suggestion_extend_battery" msgid="4401408879069551485">"Allarga la durada de la bateria després de les <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_remaining_less_than_duration_only" msgid="5996752448813295329">"Temps restant inferior a <xliff:g id="THRESHOLD">%1$s</xliff:g>"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"És possible que la tauleta s\'apagui aviat (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"És possible que el dispositiu s\'apagui aviat (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g>: <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> per completar la càrrega"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g>: <xliff:g id="TIME">%2$s</xliff:g> per completar la càrrega"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> per completar la càrrega"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g>: <xliff:g id="TIME">%2$s</xliff:g> per completar la càrrega"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Desconegut"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"S\'està carregant"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"s\'està carregant"</string>
diff --git a/packages/SettingsLib/res/values-cs/strings.xml b/packages/SettingsLib/res/values-cs/strings.xml
index 5256399..042e12a 100644
--- a/packages/SettingsLib/res/values-cs/strings.xml
+++ b/packages/SettingsLib/res/values-cs/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet se brzy vypne (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Zařízení se brzy vypne (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Plně se nabije za <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – plně se nabije za <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Do nabití zbývá: <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do nabití"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Neznámé"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Nabíjí se"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"nabíjení"</string>
diff --git a/packages/SettingsLib/res/values-da/strings.xml b/packages/SettingsLib/res/values-da/strings.xml
index 1884f64..4723293 100644
--- a/packages/SettingsLib/res/values-da/strings.xml
+++ b/packages/SettingsLib/res/values-da/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Denne tablet lukker muligvis snart ned (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Enheden lukker muligvis snart ned (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"fuldt opladet om <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – fuldt opladet om <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Opladet om <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – opladet om <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Ukendt"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Oplader"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"oplader"</string>
diff --git a/packages/SettingsLib/res/values-de/strings.xml b/packages/SettingsLib/res/values-de/strings.xml
index d8da638..4f5a965 100644
--- a/packages/SettingsLib/res/values-de/strings.xml
+++ b/packages/SettingsLib/res/values-de/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet wird eventuell bald ausgeschaltet (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Gerät wird eventuell bald ausgeschaltet (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> bis zur vollständigen Aufladung"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> bis vollständig geladen"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Noch <xliff:g id="TIME">%1$s</xliff:g> bis zur Aufladung"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> bis zur Aufladung"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Unbekannt"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Wird aufgeladen"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"wird aufgeladen..."</string>
diff --git a/packages/SettingsLib/res/values-el/strings.xml b/packages/SettingsLib/res/values-el/strings.xml
index b1b1be6..753dea8 100644
--- a/packages/SettingsLib/res/values-el/strings.xml
+++ b/packages/SettingsLib/res/values-el/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Το tablet μπορεί να απενεργοποιηθεί σύντομα (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Η συσκευή μπορεί να απενεργοποιηθεί σύντομα (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Απομένουν <xliff:g id="TIME">%1$s</xliff:g> έως την πλήρη φόρτιση"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> για πλήρη φόρτιση"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Απομένουν <xliff:g id="TIME">%1$s</xliff:g> για ολοκλήρωση της φόρτισης"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> για την ολοκλήρωση της φόρτισης"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Άγνωστο"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Φόρτιση"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"φόρτιση"</string>
diff --git a/packages/SettingsLib/res/values-en-rAU/strings.xml b/packages/SettingsLib/res/values-en-rAU/strings.xml
index 63463b1..dd3d278 100644
--- a/packages/SettingsLib/res/values-en-rAU/strings.xml
+++ b/packages/SettingsLib/res/values-en-rAU/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Device may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> left until fully charged"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> until fully charged"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> left until charged"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> until charged"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Unknown"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Charging"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"charging"</string>
diff --git a/packages/SettingsLib/res/values-en-rCA/strings.xml b/packages/SettingsLib/res/values-en-rCA/strings.xml
index 63463b1..dd3d278 100644
--- a/packages/SettingsLib/res/values-en-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-en-rCA/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Device may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> left until fully charged"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> until fully charged"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> left until charged"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> until charged"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Unknown"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Charging"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"charging"</string>
diff --git a/packages/SettingsLib/res/values-en-rGB/strings.xml b/packages/SettingsLib/res/values-en-rGB/strings.xml
index 63463b1..dd3d278 100644
--- a/packages/SettingsLib/res/values-en-rGB/strings.xml
+++ b/packages/SettingsLib/res/values-en-rGB/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Device may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> left until fully charged"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> until fully charged"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> left until charged"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> until charged"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Unknown"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Charging"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"charging"</string>
diff --git a/packages/SettingsLib/res/values-en-rIN/strings.xml b/packages/SettingsLib/res/values-en-rIN/strings.xml
index 63463b1..dd3d278 100644
--- a/packages/SettingsLib/res/values-en-rIN/strings.xml
+++ b/packages/SettingsLib/res/values-en-rIN/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Device may shutdown soon (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> left until fully charged"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> until fully charged"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> left until charged"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> until charged"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Unknown"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Charging"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"charging"</string>
diff --git a/packages/SettingsLib/res/values-en-rXC/strings.xml b/packages/SettingsLib/res/values-en-rXC/strings.xml
index e5a0bda..d9f61d8 100644
--- a/packages/SettingsLib/res/values-en-rXC/strings.xml
+++ b/packages/SettingsLib/res/values-en-rXC/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‏‎‎‏‏‏‏‎‎‏‏‏‏‎‎‏‎‎‎‏‏‏‏‏‎‎‎‏‏‎‎‎‏‎‎‎‎‏‎‏‎‏‏‏‏‎‎‏‏‏‎‏‎‎‏‏‏‏‏‎‎‎‎Tablet may shutdown soon (‎‏‎‎‏‏‎<xliff:g id="LEVEL">%1$s</xliff:g>‎‏‎‎‏‏‏‎)‎‏‎‎‏‎"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‎‎‏‎‎‎‎‏‏‎‎‎‎‏‏‎‎‏‏‎‏‎‎‏‎‏‎‏‏‎‏‎‎‎‏‏‏‎‏‏‏‎‏‏‏‎‏‎‏‏‏‎‎‎‏‏‏‎‎‎‎‏‎Device may shutdown soon (‎‏‎‎‏‏‎<xliff:g id="LEVEL">%1$s</xliff:g>‎‏‎‎‏‏‏‎)‎‏‎‎‏‎"</string>
     <string name="power_charging" msgid="1779532561355864267">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‎‏‏‏‎‎‎‏‎‏‏‎‎‏‎‎‎‏‎‏‎‏‏‎‏‏‎‏‏‏‏‏‎‏‎‏‎‎‏‏‏‎‏‏‎‏‏‎‏‏‏‏‎‎‎‏‏‎‎‏‎‏‏‎‎‏‎‎‏‏‎<xliff:g id="LEVEL">%1$s</xliff:g>‎‏‎‎‏‏‏‎ - ‎‏‎‎‏‏‎<xliff:g id="STATE">%2$s</xliff:g>‎‏‎‎‏‏‏‎‎‏‎‎‏‎"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‎‏‏‎‎‏‏‏‎‏‏‏‎‎‎‏‏‎‎‎‏‎‏‎‎‏‎‎‏‏‏‏‏‎‏‏‎‏‏‎‏‎‏‏‏‏‏‏‎‏‎‏‏‏‎‏‏‎‏‎‏‏‎‎‎‏‎‎‏‏‎<xliff:g id="TIME">%1$s</xliff:g>‎‏‎‎‏‏‏‎ left until fully charged‎‏‎‎‏‎"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‎‎‎‎‎‏‏‏‎‏‎‎‎‎‎‎‎‏‎‏‎‏‎‏‏‎‎‏‏‏‏‏‏‎‎‎‎‎‏‏‎‏‏‎‏‏‏‎‎‏‏‏‎‎‎‏‎‎‎‏‏‎‎‏‎‎‏‏‎<xliff:g id="LEVEL">%1$s</xliff:g>‎‏‎‎‏‏‏‎ - ‎‏‎‎‏‏‎<xliff:g id="TIME">%2$s</xliff:g>‎‏‎‎‏‏‏‎ until fully charged‎‏‎‎‏‎"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‏‏‏‎‎‏‎‎‏‏‎‎‎‏‎‎‎‏‏‏‎‎‏‎‏‎‏‏‏‎‎‏‎‏‏‏‎‎‏‏‏‎‎‏‏‏‏‎‏‏‏‏‎‎‏‎‏‏‎‎‏‎‎‏‎‎‏‏‎<xliff:g id="TIME">%1$s</xliff:g>‎‏‎‎‏‏‏‎ left until charged‎‏‎‎‏‎"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‎‏‎‎‎‏‎‎‏‏‎‎‏‎‎‎‎‎‏‎‏‏‎‏‎‎‏‎‏‏‎‏‎‏‎‏‏‎‎‎‏‎‎‎‏‎‎‏‏‏‏‏‎‎‏‏‏‎‎‏‎‏‎‎‏‎‎‏‏‎<xliff:g id="LEVEL">%1$s</xliff:g>‎‏‎‎‏‏‏‎ - ‎‏‎‎‏‏‎<xliff:g id="TIME">%2$s</xliff:g>‎‏‎‎‏‏‏‎ until charged‎‏‎‎‏‎"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‎‏‎‏‎‏‎‏‏‏‎‎‎‏‏‎‎‏‎‏‏‏‎‏‏‏‏‏‎‎‎‎‎‏‏‏‎‎‏‏‏‏‏‏‏‎‎‏‏‎‎‏‏‎‎‏‏‎‎‏‏‎Unknown‎‏‎‎‏‎"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‎‏‏‎‏‏‏‏‎‏‎‏‎‏‎‎‎‎‎‎‏‎‎‎‎‏‎‎‎‎‎‏‏‏‎‏‎‏‏‏‎‎‎‏‎‏‎‏‏‎‏‏‏‏‏‏‎‏‎‎‏‎‎‎Charging‎‏‎‎‏‎"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‏‏‏‎‎‎‏‎‎‏‏‎‎‎‎‏‎‎‎‎‏‏‏‏‏‏‏‎‎‎‎‎‎‏‏‎‏‏‎‎‏‎‏‎‏‎‏‏‏‎‎‎‏‏‎‏‏‎‏‎‏‎‎charging‎‏‎‎‏‎"</string>
diff --git a/packages/SettingsLib/res/values-es-rUS/strings.xml b/packages/SettingsLib/res/values-es-rUS/strings.xml
index 7874aeb..30cb0a1 100644
--- a/packages/SettingsLib/res/values-es-rUS/strings.xml
+++ b/packages/SettingsLib/res/values-es-rUS/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Es posible que pronto se apague la tablet (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Es posible que pronto se apague el dispositivo (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g>: <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> para completar la carga"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> (<xliff:g id="TIME">%2$s</xliff:g> para completar la carga)"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> para completar la carga"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> para completar la carga"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Desconocido"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Cargando"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"cargando"</string>
diff --git a/packages/SettingsLib/res/values-es/strings.xml b/packages/SettingsLib/res/values-es/strings.xml
index 8baf7a2..32905df 100644
--- a/packages/SettingsLib/res/values-es/strings.xml
+++ b/packages/SettingsLib/res/values-es/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Es posible que el tablet se apague pronto (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Es posible que el dispositivo se apague pronto (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Tiempo restante hasta carga completa: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> para completar la carga"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> hasta que termine de cargarse"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> (<xliff:g id="TIME">%2$s</xliff:g> hasta que termine de cargarse)"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Desconocido"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Cargando"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"cargando"</string>
diff --git a/packages/SettingsLib/res/values-et/strings.xml b/packages/SettingsLib/res/values-et/strings.xml
index 090b28d..79b8a84 100644
--- a/packages/SettingsLib/res/values-et/strings.xml
+++ b/packages/SettingsLib/res/values-et/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tahvelarvuti võib peagi välja lülituda (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Seade võib peagi välja lülituda (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> täislaadimiseni"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> täislaadimiseni"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Täislaadimiseni on jäänud <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> täislaadimiseni"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Tundmatu"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Laadimine"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"laadimine"</string>
diff --git a/packages/SettingsLib/res/values-eu/strings.xml b/packages/SettingsLib/res/values-eu/strings.xml
index fd3936d..bab4cde 100644
--- a/packages/SettingsLib/res/values-eu/strings.xml
+++ b/packages/SettingsLib/res/values-eu/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Baliteke tableta laster itzaltzea (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Baliteke gailua laster itzaltzea (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> falta dira guztiz kargatu arte"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> guztiz kargatu arte"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> guztiz kargatu arte"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> guztiz kargatu arte"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Ezezaguna"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Kargatzen"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"kargatzen"</string>
diff --git a/packages/SettingsLib/res/values-fa/strings.xml b/packages/SettingsLib/res/values-fa/strings.xml
index 352c276..9d84090 100644
--- a/packages/SettingsLib/res/values-fa/strings.xml
+++ b/packages/SettingsLib/res/values-fa/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ممکن است رایانه لوحی به‌زودی خاموش شود (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ممکن است دستگاه به‌زودی خاموش شود (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - ‏<xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> تا شارژ شدن کامل باقی مانده است"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> مانده تا شارژ کامل"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> مانده تا شارژ کامل"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> تا شارژ کامل"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"ناشناس"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"در حال شارژ شدن"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"درحال شارژ شدن"</string>
diff --git a/packages/SettingsLib/res/values-fi/strings.xml b/packages/SettingsLib/res/values-fi/strings.xml
index 0d522c4..929e101 100644
--- a/packages/SettingsLib/res/values-fi/strings.xml
+++ b/packages/SettingsLib/res/values-fi/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tabletti voi pian sammua (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Laite voi pian sammua (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> kunnes täynnä"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> täyteen lataukseen"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> jäljellä täyteen lataukseen"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> täyteen lataukseen"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Tuntematon"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Ladataan"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ladataan"</string>
diff --git a/packages/SettingsLib/res/values-fr-rCA/strings.xml b/packages/SettingsLib/res/values-fr-rCA/strings.xml
index 1dde863..d3bfc96 100644
--- a/packages/SettingsLib/res/values-fr-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-fr-rCA/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Il se peut que la tablette s\'éteigne bientôt (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Il se peut que l\'appareil s\'éteigne bientôt (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> jusqu\'à la charge complète"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> : <xliff:g id="TIME">%2$s</xliff:g> jusqu\'à la charge complète"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> jusqu\'à la charge complète"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> : <xliff:g id="TIME">%2$s</xliff:g> jusqu\'à la charge complète"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Inconnu"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Charge en cours…"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"en cours de charge"</string>
diff --git a/packages/SettingsLib/res/values-fr/strings.xml b/packages/SettingsLib/res/values-fr/strings.xml
index cf4ee13..b5706ce 100644
--- a/packages/SettingsLib/res/values-fr/strings.xml
+++ b/packages/SettingsLib/res/values-fr/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Il est possible que la tablette s\'éteigne bientôt (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Il est possible que l\'appareil s\'éteigne bientôt (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> avant charge complète"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> jusqu\'à la charge complète"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> jusqu\'à ce que la batterie soit chargée"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> jusqu\'à la charge complète"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Inconnu"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Batterie en charge"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"en charge…"</string>
diff --git a/packages/SettingsLib/res/values-gl/strings.xml b/packages/SettingsLib/res/values-gl/strings.xml
index b998a74..2aa1604 100644
--- a/packages/SettingsLib/res/values-gl/strings.xml
+++ b/packages/SettingsLib/res/values-gl/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"É posible que a tableta se apague en breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"É posible que o dispositivo se apague en breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Tempo que queda para completar a carga: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> para completar a carga"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> para completar a carga"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g>: <xliff:g id="TIME">%2$s</xliff:g> para completar a carga"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Descoñecido"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Cargando"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"cargando"</string>
diff --git a/packages/SettingsLib/res/values-gu/strings.xml b/packages/SettingsLib/res/values-gu/strings.xml
index cf0e201..c2cc4c5 100644
--- a/packages/SettingsLib/res/values-gu/strings.xml
+++ b/packages/SettingsLib/res/values-gu/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ટૅબ્લેટ થોડીક જ વારમાં બંધ થઈ શકે છે (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ઉપકરણ થોડીક જ વારમાં બંધ થઈ શકે છે (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"સંપૂર્ણપણે ચાર્જ થવામાં <xliff:g id="TIME">%1$s</xliff:g> બાકી"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - સંપૂર્ણપણે ચાર્જ થવા માટે <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"ચાર્જ થવામાં <xliff:g id="TIME">%1$s</xliff:g> બાકી છે"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - ચાર્જ થવા માટે <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"અજાણ્યું"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ચાર્જ થઈ રહ્યું છે"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ચાર્જ થઈ રહ્યું છે"</string>
diff --git a/packages/SettingsLib/res/values-hi/strings.xml b/packages/SettingsLib/res/values-hi/strings.xml
index 3a20d04..61e1997 100644
--- a/packages/SettingsLib/res/values-hi/strings.xml
+++ b/packages/SettingsLib/res/values-hi/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"टैबलेट जल्दी ही बंद हो सकता है (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"डिवाइस जल्दी ही बंद हो सकता है (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"पूरी तरह से चार्ज होने में <xliff:g id="TIME">%1$s</xliff:g> शेष"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> पूरी तरह से चार्ज होने तक"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"चार्ज पूरा होने में <xliff:g id="TIME">%1$s</xliff:g> बचा है"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> में पूरा चार्ज हो जाएगा"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"अज्ञात"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"चार्ज हो रही है"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"चार्ज किया जा रहा है"</string>
diff --git a/packages/SettingsLib/res/values-hr/strings.xml b/packages/SettingsLib/res/values-hr/strings.xml
index 6d957dc..0fc16f8 100644
--- a/packages/SettingsLib/res/values-hr/strings.xml
+++ b/packages/SettingsLib/res/values-hr/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet bi se uskoro mogao isključiti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Uređaj bi se uskoro mogao isključiti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Još <xliff:g id="TIME">%1$s</xliff:g> do potpune napunjenosti"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do potpune napunjenosti"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Napunit će se za <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – napunit će se za <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Nepoznato"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Punjenje"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"punjenje"</string>
diff --git a/packages/SettingsLib/res/values-hu/strings.xml b/packages/SettingsLib/res/values-hu/strings.xml
index 39b5da2..45cd379 100644
--- a/packages/SettingsLib/res/values-hu/strings.xml
+++ b/packages/SettingsLib/res/values-hu/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Előfordulhat, hogy a táblagép hamarosan leáll (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Előfordulhat, hogy az eszköz hamarosan leáll (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> a teljes töltöttségig"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> a teljes feltöltésig"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> van hátra a feltöltésig"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> a feltöltésig"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Ismeretlen"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Töltés"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"töltés"</string>
diff --git a/packages/SettingsLib/res/values-hy/strings.xml b/packages/SettingsLib/res/values-hy/strings.xml
index a74b4ae..2145adb 100644
--- a/packages/SettingsLib/res/values-hy/strings.xml
+++ b/packages/SettingsLib/res/values-hy/strings.xml
@@ -169,7 +169,7 @@
     <string name="tts_engine_security_warning" msgid="8786238102020223650">"Այս խոսքային սինթեզի գործիքը կարող է հավաքել այն ամենը, ինչ արտասանված է, այդ թվում` անձնական տվյալներ, ինչպիսիք են գաղտնաբառն ու բանկային քարտի համարները: Սկզբնաբյուրը <xliff:g id="TTS_PLUGIN_ENGINE_NAME">%s</xliff:g> շարժիչն է: Միացնե՞լ խոսքի սինթեզի շարժիչի օգտագործումը:"</string>
     <string name="tts_engine_network_required" msgid="1190837151485314743">"Այս լեզուն պահանջում է աշխատող ցանցային կապ գրվածքից խոսք ելքի համար:"</string>
     <string name="tts_default_sample_string" msgid="4040835213373086322">"Սա խոսքային սինթեզի մի նմուշ է:"</string>
-    <string name="tts_status_title" msgid="7268566550242584413">"Լռելյայն լեզվի կարգավիճակը"</string>
+    <string name="tts_status_title" msgid="7268566550242584413">"Կանխադրված լեզվի կարգավիճակը"</string>
     <string name="tts_status_ok" msgid="1309762510278029765">"<xliff:g id="LOCALE">%1$s</xliff:g>-ը լիովին աջակցվում է"</string>
     <string name="tts_status_requires_network" msgid="6042500821503226892">"<xliff:g id="LOCALE">%1$s</xliff:g>-ը պահանջում է ցանցային կապ"</string>
     <string name="tts_status_not_supported" msgid="4491154212762472495">"<xliff:g id="LOCALE">%1$s</xliff:g>-ը չի աջակցվում"</string>
@@ -201,9 +201,9 @@
     <string name="vpn_settings_not_available" msgid="956841430176985598">"VPN-ի կարգավորումները հասանելի չեն այս օգտատիրոջը"</string>
     <string name="tethering_settings_not_available" msgid="6765770438438291012">"Այս օգտատերը չի կարող փոխել մոդեմի ռեժիմի կարգավորումները"</string>
     <string name="apn_settings_not_available" msgid="7873729032165324000">"Մուտքի կետի անվան կարգավորումները հասանելի չեն այս օգտատիրոջը"</string>
-    <string name="enable_adb" msgid="7982306934419797485">"USB վրիպազերծում"</string>
+    <string name="enable_adb" msgid="7982306934419797485">"USB-ով վրիպազերծում"</string>
     <string name="enable_adb_summary" msgid="4881186971746056635">"Միացնել վրիպազերծման ռեժիմը, երբ USB-ն միացված է"</string>
-    <string name="clear_adb_keys" msgid="4038889221503122743">"Չեղարկել USB վրիպազերծման լիազորումները"</string>
+    <string name="clear_adb_keys" msgid="4038889221503122743">"Չեղարկել USB-ով վրիպազերծման թույլտվությունները"</string>
     <string name="bugreport_in_power" msgid="7923901846375587241">"Սխալի հաղորդման դյուրանցում"</string>
     <string name="bugreport_in_power_summary" msgid="1778455732762984579">"Գործարկման ցանկում ցույց տալ կոճակը՝ վրիպակների հաղորդման համար"</string>
     <string name="keep_screen_on" msgid="1146389631208760344">"Մնալ արթուն"</string>
@@ -263,9 +263,9 @@
     <string name="debug_view_attributes" msgid="6485448367803310384">"Միացնել ցուցադրման հատկանիշների ստուգումը"</string>
     <string name="mobile_data_always_on_summary" msgid="8149773901431697910">"Միշտ ակտիվացրած պահել բջջային տվյալները, նույնիսկ Wi‑Fi-ը միացրած ժամանակ (ցանցերի միջև արագ փոխարկման համար):"</string>
     <string name="tethering_hardware_offload_summary" msgid="7726082075333346982">"Օգտագործել սարքակազմի արագացման միացումը, եթե հասանելի է"</string>
-    <string name="adb_warning_title" msgid="6234463310896563253">"Թույլատրե՞լ USB վրիպազերծումը:"</string>
-    <string name="adb_warning_message" msgid="7316799925425402244">"USB վրիպազերծումը միայն ծրագրավորման նպատակների համար է: Օգտագործեք այն ձեր համակարգչից տվյալները ձեր սարք պատճենելու համար, առանց ծանուցման ձեր սարքի վրա ծրագրեր տեղադրելու և տվյալների մատյանը ընթերցելու համար:"</string>
-    <string name="adb_keys_warning_message" msgid="5659849457135841625">"Փակե՞լ USB-ի վրիպազերծման մուտքը` անջատելով այն բոլոր համակարգիչներից, որտեղ նախկինում թույլատրել էիք:"</string>
+    <string name="adb_warning_title" msgid="6234463310896563253">"Թույլատրե՞լ USB-ով վրիպազերծումը:"</string>
+    <string name="adb_warning_message" msgid="7316799925425402244">"USB-ով վրիպազերծումը միայն ծրագրավորման նպատակների համար է: Օգտագործեք այն ձեր համակարգչից տվյալները ձեր սարք պատճենելու համար, առանց ծանուցման ձեր սարքի վրա ծրագրեր տեղադրելու և տվյալների մատյանը ընթերցելու համար:"</string>
+    <string name="adb_keys_warning_message" msgid="5659849457135841625">"Չեղարկե՞լ USB-ով վրիպազերծման հասանելիությունը` անջատելով այն բոլոր համակարգիչներից, որտեղ նախկինում թույլատրել էիք:"</string>
     <string name="dev_settings_warning_title" msgid="7244607768088540165">"Ընդունե՞լ ծրագրավորման կարգավորումներ:"</string>
     <string name="dev_settings_warning_message" msgid="2298337781139097964">"Այս կարգավորումները միայն ծրագրավորման նպատակների համար են նախատեսված: Դրանք կարող են խանգարել ձեր սարքի կամ ծրագրի աշխատանքին:"</string>
     <string name="verify_apps_over_usb_title" msgid="4177086489869041953">"Ստուգել հավելվածները USB-ի նկատմամբ"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Պլանշետը շուտով կանջատվի (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Սարքը շուտով կանջատվի (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Մինչև լրիվ լիցքավորումը մնացել է <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> մինչև լրիվ լիցքավորումը"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> մինչև լիցքավորումը"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> մինչև լիցքավորումը"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Անհայտ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Լիցքավորում"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"լիցքավորում"</string>
diff --git a/packages/SettingsLib/res/values-in/strings.xml b/packages/SettingsLib/res/values-in/strings.xml
index 7fe1ef9..15b6da5 100644
--- a/packages/SettingsLib/res/values-in/strings.xml
+++ b/packages/SettingsLib/res/values-in/strings.xml
@@ -336,8 +336,8 @@
     <string name="force_resizable_activities_summary" msgid="6667493494706124459">"Buat semua aktivitas dapat diubah ukurannya untuk banyak jendela, terlepas dari nilai manifes."</string>
     <string name="enable_freeform_support" msgid="1461893351278940416">"Aktifkan jendela berformat bebas"</string>
     <string name="enable_freeform_support_summary" msgid="8247310463288834487">"Aktifkan dukungan untuk jendela eksperimental berformat bebas."</string>
-    <string name="local_backup_password_title" msgid="3860471654439418822">"Sandi backup desktop"</string>
-    <string name="local_backup_password_summary_none" msgid="6951095485537767956">"Saat ini backup desktop sepenuhnya tidak dilindungi"</string>
+    <string name="local_backup_password_title" msgid="3860471654439418822">"Sandi cadangan desktop"</string>
+    <string name="local_backup_password_summary_none" msgid="6951095485537767956">"Saat ini cadangan desktop penuh tidak dilindungi"</string>
     <string name="local_backup_password_summary_change" msgid="5376206246809190364">"Ketuk guna mengubah atau menghapus sandi untuk cadangan lengkap desktop"</string>
     <string name="local_backup_password_toast_success" msgid="582016086228434290">"Sandi cadangan baru telah disetel"</string>
     <string name="local_backup_password_toast_confirmation_mismatch" msgid="7805892532752708288">"Sandi baru dan konfirmasinya tidak cocok."</string>
@@ -387,8 +387,8 @@
     <skip />
     <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"Akan bertahan kira-kira sampai <xliff:g id="TIME">%1$s</xliff:g> berdasarkan penggunaan Anda (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
     <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"Akan bertahan kira-kira sampai <xliff:g id="TIME">%1$s</xliff:g> berdasarkan penggunaan Anda"</string>
-    <string name="power_discharge_by" msgid="6453537733650125582">"Akan bertahan kira-kira sampai <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only" msgid="107616694963545745">"Akan bertahan kira-kira sampai <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_discharge_by" msgid="6453537733650125582">"Akan bertahan kira-kira sampai pukul <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
+    <string name="power_discharge_by_only" msgid="107616694963545745">"Akan bertahan kira-kira sampai pukul <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by_only_short" msgid="1372817269546888804">"Hingga <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_suggestion_extend_battery" msgid="4401408879069551485">"Perpanjang masa pakai baterai hingga <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_remaining_less_than_duration_only" msgid="5996752448813295329">"Tersisa kurang dari <xliff:g id="THRESHOLD">%1$s</xliff:g>"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet mungkin segera dimatikan (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Perangkat mungkin segera dimatikan (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> lagi hingga terisi penuh"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> lagi terisi penuh"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Sisa <xliff:g id="TIME">%1$s</xliff:g> hingga terisi penuh"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> lagi terisi penuh"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Tidak diketahui"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Mengisi daya"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"mengisi daya baterai"</string>
diff --git a/packages/SettingsLib/res/values-is/strings.xml b/packages/SettingsLib/res/values-is/strings.xml
index 11d69571..eede117 100644
--- a/packages/SettingsLib/res/values-is/strings.xml
+++ b/packages/SettingsLib/res/values-is/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Spjaldtölvan gæti slökkt á sér fljótlega (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Tækið gæti slökkt á sér fljótlega (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> þar til hleðslu er lokið"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> þar til fullri hleðslu er náð"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> að fullri hleðslu"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> að fullri hleðslu"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Óþekkt"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Í hleðslu"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"í hleðslu"</string>
diff --git a/packages/SettingsLib/res/values-it/strings.xml b/packages/SettingsLib/res/values-it/strings.xml
index 68c0f17..2c64ec2 100644
--- a/packages/SettingsLib/res/values-it/strings.xml
+++ b/packages/SettingsLib/res/values-it/strings.xml
@@ -240,7 +240,7 @@
     <string name="bluetooth_select_a2dp_codec_streaming_label" msgid="5347862512596240506">"Streaming: <xliff:g id="STREAMING_PARAMETER">%1$s</xliff:g>"</string>
     <string name="select_private_dns_configuration_title" msgid="3700456559305263922">"DNS privato"</string>
     <string name="select_private_dns_configuration_dialog_title" msgid="9221994415765826811">"Seleziona modalità DNS privato"</string>
-    <string name="private_dns_mode_off" msgid="8236575187318721684">"Non attivo"</string>
+    <string name="private_dns_mode_off" msgid="8236575187318721684">"Off"</string>
     <string name="private_dns_mode_opportunistic" msgid="8314986739896927399">"Automatico"</string>
     <string name="private_dns_mode_provider" msgid="8354935160639360804">"Nome host del provider DNS privato"</string>
     <string name="private_dns_mode_provider_hostname_hint" msgid="2487492386970928143">"Inserisci il nome host del provider DNS"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Il tablet potrebbe spegnersi a breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Il dispositivo potrebbe spegnersi a breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Tempo rimanente alla carica completa: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> alla carica completa"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Tempo rimanente alla carica completa: <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> alla carica completa"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Sconosciuta"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"In carica"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"in carica"</string>
diff --git a/packages/SettingsLib/res/values-iw/strings.xml b/packages/SettingsLib/res/values-iw/strings.xml
index ead0bfb..30d6a4a 100644
--- a/packages/SettingsLib/res/values-iw/strings.xml
+++ b/packages/SettingsLib/res/values-iw/strings.xml
@@ -342,7 +342,7 @@
     <string name="local_backup_password_toast_success" msgid="582016086228434290">"הוגדרה סיסמת גיבוי חדשה"</string>
     <string name="local_backup_password_toast_confirmation_mismatch" msgid="7805892532752708288">"הסיסמה החדשה והאישור אינם תואמים"</string>
     <string name="local_backup_password_toast_validation_failure" msgid="5646377234895626531">"הגדרת סיסמת גיבוי נכשלה"</string>
-    <string name="loading_injected_setting_summary" msgid="4095178591461231376">"טוען…"</string>
+    <string name="loading_injected_setting_summary" msgid="4095178591461231376">"בטעינה…"</string>
   <string-array name="color_mode_names">
     <item msgid="2425514299220523812">"דינמי (ברירת מחדל)"</item>
     <item msgid="8446070607501413455">"טבעי"</item>
@@ -402,10 +402,10 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ייתכן שהטאבלט ייכבה בקרוב (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ייתכן שהמכשיר ייכבה בקרוב (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g>‏ - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> עד לטעינה מלאה"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> עד לטעינה מלאה"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"נשארו <xliff:g id="TIME">%1$s</xliff:g> עד הטעינה"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> עד הטעינה"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"לא ידוע"</string>
-    <string name="battery_info_status_charging" msgid="1705179948350365604">"טוען"</string>
+    <string name="battery_info_status_charging" msgid="1705179948350365604">"בטעינה"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"בטעינה"</string>
     <string name="battery_info_status_discharging" msgid="310932812698268588">"לא בטעינה"</string>
     <string name="battery_info_status_not_charging" msgid="8523453668342598579">"המכשיר מחובר, אבל לא ניתן לטעון עכשיו"</string>
diff --git a/packages/SettingsLib/res/values-ja/strings.xml b/packages/SettingsLib/res/values-ja/strings.xml
index 50543d8..6cb5514 100644
--- a/packages/SettingsLib/res/values-ja/strings.xml
+++ b/packages/SettingsLib/res/values-ja/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"タブレットの電源がもうすぐ切れます(<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"デバイスの電源がもうすぐ切れます(<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"フル充電まであと <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - フル充電まで <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"充電完了まであと <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - 充電完了まで <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"不明"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"充電中"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"充電しています"</string>
diff --git a/packages/SettingsLib/res/values-ka/strings.xml b/packages/SettingsLib/res/values-ka/strings.xml
index 8b9b6b6..4c78a38 100644
--- a/packages/SettingsLib/res/values-ka/strings.xml
+++ b/packages/SettingsLib/res/values-ka/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ტაბლეტი შეიძლება მალე გაითიშოს (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"მოწყობილობა შეიძლება მალე გაითიშოს (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"სრულ დატენვამდე დარჩენილია <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> — სრულ დატენვამდე დარჩა <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"დატენვამდე დარჩა <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> დატენვამდე"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"უცნობი"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"იტენება"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"იტენება"</string>
diff --git a/packages/SettingsLib/res/values-kk/strings.xml b/packages/SettingsLib/res/values-kk/strings.xml
index 246e3eb..ce08657 100644
--- a/packages/SettingsLib/res/values-kk/strings.xml
+++ b/packages/SettingsLib/res/values-kk/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Планшет көп ұзамай өшуі мүмкін (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Құрылғы көп ұзамай өшуі мүмкін (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Толық зарядталуына <xliff:g id="TIME">%1$s</xliff:g> қалды"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – толық зарядталғанға дейін <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Зарядталғанға дейін <xliff:g id="TIME">%1$s</xliff:g> қалды"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – зарядталғанға дейін <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Белгісіз"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Зарядталуда"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"зарядталуда"</string>
diff --git a/packages/SettingsLib/res/values-km/strings.xml b/packages/SettingsLib/res/values-km/strings.xml
index 36cf2d4..43c9282 100644
--- a/packages/SettingsLib/res/values-km/strings.xml
+++ b/packages/SettingsLib/res/values-km/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ថេប្លេត​អាចនឹង​បិទក្នុង​ពេលបន្តិច​ទៀត (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ឧបករណ៍​អាចនឹង​បិទក្នុង​ពេលបន្តិច​ទៀត (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> ទៀតទើបសាកថ្មពេញ"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ទៀតទើបសាកថ្មពេញ"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> ទៀតទើប​ត្រូវសាក"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ទៀតទើប​ត្រូវសាក"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"មិន​ស្គាល់"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"កំពុងបញ្ចូល​ថ្ម"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"កំពុង​សាក​ថ្ម"</string>
diff --git a/packages/SettingsLib/res/values-kn/strings.xml b/packages/SettingsLib/res/values-kn/strings.xml
index 97eed0f..3fe9855 100644
--- a/packages/SettingsLib/res/values-kn/strings.xml
+++ b/packages/SettingsLib/res/values-kn/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ಟ್ಯಾಬ್ಲೆಟ್‌‌ ಶೀಘ್ರದಲ್ಲೇ ಶಟ್ ಡೌನ್ ಆಗಬಹುದು (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ಸಾಧನವು ಶೀಘ್ರದಲ್ಲೇ ಶಟ್ ಡೌನ್ ಆಗಬಹುದು (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"ಸಂಪೂರ್ಣ ಚಾರ್ಜ್ ಆಗಲು <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - ಸಂಪೂರ್ಣ ಚಾರ್ಜ್ ಆಗಲು <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"ಚಾರ್ಜ್ ಆಗಲು <xliff:g id="TIME">%1$s</xliff:g> ಸಮಯ ಬಾಕಿ ಇದೆ"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - ಚಾರ್ಜ್ ಆಗಲು <xliff:g id="TIME">%2$s</xliff:g> ಸಮಯ ಬೇಕು"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"ಅಪರಿಚಿತ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ಚಾರ್ಜ್ ಆಗುತ್ತಿದೆ"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ಚಾರ್ಜ್ ಆಗುತ್ತಿದೆ"</string>
diff --git a/packages/SettingsLib/res/values-ko/arrays.xml b/packages/SettingsLib/res/values-ko/arrays.xml
index e2d8e02..15e11db 100644
--- a/packages/SettingsLib/res/values-ko/arrays.xml
+++ b/packages/SettingsLib/res/values-ko/arrays.xml
@@ -226,7 +226,7 @@
   </string-array>
   <string-array name="enable_opengl_traces_entries">
     <item msgid="3191973083884253830">"없음"</item>
-    <item msgid="9089630089455370183">"로그캣"</item>
+    <item msgid="9089630089455370183">"Logcat"</item>
     <item msgid="5397807424362304288">"Systrace(그래픽)"</item>
     <item msgid="1340692776955662664">"glGetError의 스택 호출"</item>
   </string-array>
diff --git a/packages/SettingsLib/res/values-ko/strings.xml b/packages/SettingsLib/res/values-ko/strings.xml
index 8f8bbc1..ac44c0d 100644
--- a/packages/SettingsLib/res/values-ko/strings.xml
+++ b/packages/SettingsLib/res/values-ko/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"태블릿이 곧 종료될 수 있음(<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"기기가 곧 종료될 수 있음(<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"충전 완료까지 <xliff:g id="TIME">%1$s</xliff:g> 남음"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - 충전 완료까지 <xliff:g id="TIME">%2$s</xliff:g> 남음"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"충전 완료까지 <xliff:g id="TIME">%1$s</xliff:g> 남음"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - 충전 완료까지 <xliff:g id="TIME">%2$s</xliff:g> 남음"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"알 수 없음"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"충전 중"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"충전 중"</string>
diff --git a/packages/SettingsLib/res/values-ky/strings.xml b/packages/SettingsLib/res/values-ky/strings.xml
index 435ce53..72b2159 100644
--- a/packages/SettingsLib/res/values-ky/strings.xml
+++ b/packages/SettingsLib/res/values-ky/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Планшет бир аздан кийин өчүп калышы мүмкүн (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Түзмөк бир аздан кийин өчүп калышы мүмкүн (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Батарея толгонго чейин калган убакыт: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> кийин толук кубатталат"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> кийин кубатталат"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> кийин кубатталат"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Белгисиз"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Кубатталууда"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"кубатталууда"</string>
diff --git a/packages/SettingsLib/res/values-lo/strings.xml b/packages/SettingsLib/res/values-lo/strings.xml
index ed88bc5..28e8111 100644
--- a/packages/SettingsLib/res/values-lo/strings.xml
+++ b/packages/SettingsLib/res/values-lo/strings.xml
@@ -385,10 +385,10 @@
     <string name="power_discharging_duration_enhanced" msgid="1992003260664804080">"ເຫຼືອອີກປະມານ <xliff:g id="TIME_REMAINING">%1$s</xliff:g> ອ້າງອີງຈາກການນຳໃຊ້ຂອງທ່ານ (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
     <!-- no translation found for power_remaining_duration_only_short (9183070574408359726) -->
     <skip />
-    <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"Should last until about <xliff:g id="TIME">%1$s</xliff:g> based on your usage (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"Should last until about <xliff:g id="TIME">%1$s</xliff:g> based on your usage"</string>
-    <string name="power_discharge_by" msgid="6453537733650125582">"Should last until about <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only" msgid="107616694963545745">"Should last until about <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"ໜ້າຈະໃຊ້ໄດ້ຈົນຮອດປະມານ <xliff:g id="TIME">%1$s</xliff:g> ໂດຍອ້າງອີງຈາກການນຳໃຊ້ຂອງທ່ານ (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
+    <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"ໜ້າຈະໃຊ້ໄດ້ຈົນຮອດປະມານ <xliff:g id="TIME">%1$s</xliff:g> ໂດຍອ້າງອີງຈາກການນຳໃຊ້ຂອງທ່ານ"</string>
+    <string name="power_discharge_by" msgid="6453537733650125582">"ໜ້າຈະໃຊ້ໄດ້ຈົນຮອດປະມານ <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
+    <string name="power_discharge_by_only" msgid="107616694963545745">"ໜ້າຈະໃຊ້ໄດ້ຈົນຮອດປະມານ <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by_only_short" msgid="1372817269546888804">"ຈົນກວ່າຈະຮອດ <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_suggestion_extend_battery" msgid="4401408879069551485">"ຂະຫຍາຍອາຍຸແບັດເຕີຣີກາຍ <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_remaining_less_than_duration_only" msgid="5996752448813295329">"ຍັງເຫຼືອໜ້ອຍກວ່າ <xliff:g id="THRESHOLD">%1$s</xliff:g>"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ແທັບເລັດອາດຈະປິດໃນໄວໆນີ້ (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ອຸປະກອນອາດຈະປິດໃນໄວໆນີ້ (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> ຈົນກວ່າຈະສາກເຕັມ"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ຈົນກວ່າຈະສາກເຕັມ"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> ຈົນກວ່າຈະສາກເຕັມ"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ຈົນກວ່າຈະສາກເຕັມ"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"ບໍ່ຮູ້ຈັກ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ກຳລັງສາກໄຟ"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ກຳລັງສາກໄຟ"</string>
diff --git a/packages/SettingsLib/res/values-lt/strings.xml b/packages/SettingsLib/res/values-lt/strings.xml
index c10bd00..93fcaa7 100644
--- a/packages/SettingsLib/res/values-lt/strings.xml
+++ b/packages/SettingsLib/res/values-lt/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Planšetinis kompiuteris netrukus gali būti išjungtas (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Įrenginys netrukus gali būti išjungtas (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Iki visiškos įkrovos liko <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> iki visiško įkrovimo"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Iki visiškos įkrovos liko <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – iki visiškos įkrovos liko <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Nežinomas"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Kraunasi..."</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"įkraunama"</string>
diff --git a/packages/SettingsLib/res/values-lv/strings.xml b/packages/SettingsLib/res/values-lv/strings.xml
index 8feb5ab..c12d097 100644
--- a/packages/SettingsLib/res/values-lv/strings.xml
+++ b/packages/SettingsLib/res/values-lv/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Iespējams, planšetdators drīz izslēgsies (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Iespējams, ierīce drīz izslēgsies (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> — <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Atlikušais laiks līdz pilnai uzlādei: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g>, kamēr pilnībā uzlādēts"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Vēl <xliff:g id="TIME">%1$s</xliff:g> līdz pilnai uzlādei"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> — <xliff:g id="TIME">%2$s</xliff:g> līdz pilnai uzlādei"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Nezināms"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Uzlāde"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"notiek uzlāde"</string>
diff --git a/packages/SettingsLib/res/values-mk/strings.xml b/packages/SettingsLib/res/values-mk/strings.xml
index dda3462..9a76a0a 100644
--- a/packages/SettingsLib/res/values-mk/strings.xml
+++ b/packages/SettingsLib/res/values-mk/strings.xml
@@ -153,7 +153,7 @@
     <string name="launch_defaults_some" msgid="313159469856372621">"Поставени се некои стандардни вредности"</string>
     <string name="launch_defaults_none" msgid="4241129108140034876">"Нема поставено стандардни вредности"</string>
     <string name="tts_settings" msgid="8186971894801348327">"Поставки на текст-во-говор"</string>
-    <string name="tts_settings_title" msgid="1237820681016639683">"Излез текст-во-говор"</string>
+    <string name="tts_settings_title" msgid="1237820681016639683">"Претворање текст во говор"</string>
     <string name="tts_default_rate_title" msgid="6030550998379310088">"Брзина на говор"</string>
     <string name="tts_default_rate_summary" msgid="4061815292287182801">"Брзина со која се кажува текстот"</string>
     <string name="tts_default_pitch_title" msgid="6135942113172488671">"Интензитет"</string>
@@ -167,7 +167,7 @@
     <string name="tts_install_data_title" msgid="4264378440508149986">"Инсталирај гласовни податоци"</string>
     <string name="tts_install_data_summary" msgid="5742135732511822589">"Инсталирај ги гласовните податоци потребни за синтеза на говор"</string>
     <string name="tts_engine_security_warning" msgid="8786238102020223650">"Овој софтвер за синтеза на говор може да го собере сиот текст што ќе се говори, вклучувајќи и лични податоци како што се лозинки и броеви на кредитни картички. Тоа го прави апликацијата <xliff:g id="TTS_PLUGIN_ENGINE_NAME">%s</xliff:g>. Употреби го овој софтвер за синтеза на говор?"</string>
-    <string name="tts_engine_network_required" msgid="1190837151485314743">"За овој јазик е потребно поврување со мрежа што функционира на излез за текст-во-говор."</string>
+    <string name="tts_engine_network_required" msgid="1190837151485314743">"За претворање текст во говор на овој јазик, потребна е активна мрежна врска."</string>
     <string name="tts_default_sample_string" msgid="4040835213373086322">"Ова е пример на синтеза на говор"</string>
     <string name="tts_status_title" msgid="7268566550242584413">"Статус на стандарден јазик"</string>
     <string name="tts_status_ok" msgid="1309762510278029765">"<xliff:g id="LOCALE">%1$s</xliff:g> е целосно поддржан"</string>
@@ -375,7 +375,7 @@
     <string name="daltonizer_mode_deuteranomaly" msgid="5475532989673586329">"Девтераномалија (слепило за црвена и зелена)"</string>
     <string name="daltonizer_mode_protanomaly" msgid="8424148009038666065">"Протаномалија (слепило за црвена и зелена)"</string>
     <string name="daltonizer_mode_tritanomaly" msgid="481725854987912389">"Тританомалија (слепило за сина и жолта)"</string>
-    <string name="accessibility_display_daltonizer_preference_title" msgid="5800761362678707872">"Корекција на боја"</string>
+    <string name="accessibility_display_daltonizer_preference_title" msgid="5800761362678707872">"Корекција на бои"</string>
     <string name="accessibility_display_daltonizer_preference_subtitle" msgid="3484969015295282911">"Функцијата е експериментална и може да влијае на изведбата."</string>
     <string name="daltonizer_type_overridden" msgid="3116947244410245916">"Прескокнато според <xliff:g id="TITLE">%1$s</xliff:g>"</string>
     <string name="power_remaining_settings_home_page" msgid="4845022416859002011">"<xliff:g id="PERCENTAGE">%1$s</xliff:g> - <xliff:g id="TIME_STRING">%2$s</xliff:g>"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Таблетот може да се исклучи наскоро (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Уредот може да се исклучи наскоро (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Преостануваат <xliff:g id="TIME">%1$s</xliff:g> дури се наполни целосно"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> дури се наполни целосно"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Уште <xliff:g id="TIME">%1$s</xliff:g> до целосно полнење"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> до целосно полнење"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Непознато"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Се полни"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"се полни"</string>
diff --git a/packages/SettingsLib/res/values-ml/strings.xml b/packages/SettingsLib/res/values-ml/strings.xml
index 7016b7f..bb76295 100644
--- a/packages/SettingsLib/res/values-ml/strings.xml
+++ b/packages/SettingsLib/res/values-ml/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ടാബ്‌ലെറ്റ് ഉടൻ ഷട്ട് ഡൗൺ ആയേക്കാം (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ഉപകരണം ഉടൻ ഷട്ട്ഡൗൺ ആയേക്കാം (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"മുഴുവൻ ചാർജാകാൻ <xliff:g id="TIME">%1$s</xliff:g> ശേഷിക്കുന്നു"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - ഫുൾ ചാർജാകാൻ <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"പൂർണ്ണമായി ചാർജാവാൻ <xliff:g id="TIME">%1$s</xliff:g> ശേഷിക്കുന്നു"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - പൂർണ്ണമായി ചാർജാവാൻ <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"അജ്ഞാതം"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ചാർജ് ചെയ്യുന്നു"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ചാർജ് ചെയ്യുന്നു"</string>
diff --git a/packages/SettingsLib/res/values-mn/strings.xml b/packages/SettingsLib/res/values-mn/strings.xml
index 80e78a3..65a8ca6 100644
--- a/packages/SettingsLib/res/values-mn/strings.xml
+++ b/packages/SettingsLib/res/values-mn/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Таблет удахгүй унтарна (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Төхөөрөмж удахгүй унтарна (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Бүрэн цэнэглэх хүртэл <xliff:g id="TIME">%1$s</xliff:g> үлдсэн"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"бүрэн цэнэглэх хүртэл <xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Цэнэглэх хүртэл үлдсэн <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - цэнэглэх хүртэл <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Тодорхойгүй"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Цэнэглэж байна"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"цэнэглэж байна"</string>
diff --git a/packages/SettingsLib/res/values-mr/strings.xml b/packages/SettingsLib/res/values-mr/strings.xml
index 54723a8..3d75ad6 100644
--- a/packages/SettingsLib/res/values-mr/strings.xml
+++ b/packages/SettingsLib/res/values-mr/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"टॅबलेट लवकरच बंद होऊ शकतो (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"डिव्हाइस लवकरच बंद पडू शकते (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"पूर्णपणे चार्ज होण्यास <xliff:g id="TIME">%1$s</xliff:g> शिल्‍लक"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - पूर्णपणे चार्ज होण्यात <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> पर्यंत पूर्ण चार्ज होईल"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> पर्यंत पूर्ण चार्ज होईल"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"अज्ञात"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"चार्ज होत आहे"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"चार्ज होत आहे"</string>
diff --git a/packages/SettingsLib/res/values-ms/strings.xml b/packages/SettingsLib/res/values-ms/strings.xml
index 3841a3b..0b2a4b0 100644
--- a/packages/SettingsLib/res/values-ms/strings.xml
+++ b/packages/SettingsLib/res/values-ms/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet mungkin ditutup tidak lama lagi (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Peranti mungkin ditutup tidak lama lagi (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> lagi sehingga dicas penuh"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> sehingga dicas penuh"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> lagi sehingga dicas penuh"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> sehingga dicas"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Tidak diketahui"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Mengecas"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"mengecas"</string>
diff --git a/packages/SettingsLib/res/values-my/strings.xml b/packages/SettingsLib/res/values-my/strings.xml
index 38f128a..6fde69a 100644
--- a/packages/SettingsLib/res/values-my/strings.xml
+++ b/packages/SettingsLib/res/values-my/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"မကြာမီ တက်ဘလက် ပိတ်သွားနိုင်သည် (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"မကြာမီ စက်ပိတ်သွားနိုင်သည် (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"အားပြည့်ရန် <xliff:g id="TIME">%1$s</xliff:g> လိုပါသည်"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> − အားပြည့်ရန် <xliff:g id="TIME">%2$s</xliff:g> ကျန်သည်"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"အားပြည့်ရန် <xliff:g id="TIME">%1$s</xliff:g> ကျန်သည်"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - အားပြည့်ရန် <xliff:g id="TIME">%2$s</xliff:g> ကျန်သည်"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"မသိ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"အားသွင်းနေပါသည်"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"အားသွင်းနေပါသည်"</string>
diff --git a/packages/SettingsLib/res/values-nb/strings.xml b/packages/SettingsLib/res/values-nb/strings.xml
index 144d4c2..66ad20e 100644
--- a/packages/SettingsLib/res/values-nb/strings.xml
+++ b/packages/SettingsLib/res/values-nb/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Nettbrettet slås kanskje av snart (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Enheten slås kanskje av snart (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> til det er fulladet"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> til det er fulladet"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> til batteriet er fulladet"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> til batteriet er fulladet"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Ukjent"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Lader"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"lader"</string>
diff --git a/packages/SettingsLib/res/values-ne/strings.xml b/packages/SettingsLib/res/values-ne/strings.xml
index f1934c3..860e9bf 100644
--- a/packages/SettingsLib/res/values-ne/strings.xml
+++ b/packages/SettingsLib/res/values-ne/strings.xml
@@ -153,7 +153,7 @@
     <string name="launch_defaults_some" msgid="313159469856372621">"केही पूर्वनिर्धारितहरू सेट गरिएका छन्"</string>
     <string name="launch_defaults_none" msgid="4241129108140034876">"कुनै पूर्वनिर्धारित सेट गरिएको छैन"</string>
     <string name="tts_settings" msgid="8186971894801348327">"पाठ-वाचन सेटिङहरू"</string>
-    <string name="tts_settings_title" msgid="1237820681016639683">"पाठवाचकको उत्पादन"</string>
+    <string name="tts_settings_title" msgid="1237820681016639683">"पाठवाचकको आउटपुट"</string>
     <string name="tts_default_rate_title" msgid="6030550998379310088">"वाणी दर"</string>
     <string name="tts_default_rate_summary" msgid="4061815292287182801">"पाठ वाचन हुने गति"</string>
     <string name="tts_default_pitch_title" msgid="6135942113172488671">"पिच"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ट्याब्लेट चाँडै बन्द हुन सक्छ (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"यन्त्र चाँडै बन्द हुन सक्छ (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"पूर्णरूपमा चार्ज हुन <xliff:g id="TIME">%1$s</xliff:g> बाँकी"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - पूर्णरूपमा चार्ज हुन <xliff:g id="TIME">%2$s</xliff:g> बाँकी"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"पूर्ण चार्ज हुन <xliff:g id="TIME">%1$s</xliff:g> बाँकी"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"पूर्ण चार्ज हुन <xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> लाग्छ"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"अज्ञात"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"चार्ज हुँदै"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"चार्ज हुँदै"</string>
diff --git a/packages/SettingsLib/res/values-nl/strings.xml b/packages/SettingsLib/res/values-nl/strings.xml
index c50b43a..2fff3283 100644
--- a/packages/SettingsLib/res/values-nl/strings.xml
+++ b/packages/SettingsLib/res/values-nl/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet wordt binnenkort mogelijk uitgeschakeld (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Apparaat wordt binnenkort mogelijk uitgeschakeld (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Nog <xliff:g id="TIME">%1$s</xliff:g> tot volledig opgeladen"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> tot volledig opgeladen"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Nog <xliff:g id="TIME">%1$s</xliff:g> tot opgeladen"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> tot opgeladen"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Onbekend"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Opladen"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"opladen"</string>
diff --git a/packages/SettingsLib/res/values-or/strings.xml b/packages/SettingsLib/res/values-or/strings.xml
index 5725c22..ff2a534 100644
--- a/packages/SettingsLib/res/values-or/strings.xml
+++ b/packages/SettingsLib/res/values-or/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ଖୁବ୍ ଶୀଘ୍ର ଟାବଲେଟ୍‌ଟି ବନ୍ଦ ହୋଇଯାଇପାରେ (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ଖୁବ୍ ଶୀଘ୍ର ଡିଭାଇସ୍‌ଟି ବନ୍ଦ ହୋଇଯାଇପାରେ(<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"ସମ୍ପୂର୍ଣ୍ଣ ଚାର୍ଜ ହେବାପାଇଁ <xliff:g id="TIME">%1$s</xliff:g> ଅବଶିଷ୍ଟ ଅଛି"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ପୂର୍ଣ୍ଣ ଚାର୍ଜ ହେବା ପର୍ଯ୍ୟନ୍ତ"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"ଚାର୍ଜ ହେବା ପାଇଁ <xliff:g id="TIME">%1$s</xliff:g> ବାକି ଅଛି"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ଚାର୍ଜ ହେବା ପର୍ଯ୍ୟନ୍ତ"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"ଅଜ୍ଞାତ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ଚାର୍ଜ ହେଉଛି"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ଚାର୍ଜ ହେଉଛି"</string>
diff --git a/packages/SettingsLib/res/values-pa/strings.xml b/packages/SettingsLib/res/values-pa/strings.xml
index faccda7..0cf95753 100644
--- a/packages/SettingsLib/res/values-pa/strings.xml
+++ b/packages/SettingsLib/res/values-pa/strings.xml
@@ -388,7 +388,7 @@
     <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"ਤੁਹਾਡੀ ਵਰਤੋਂ ਦੇ ਆਧਾਰ \'ਤੇ ਲਗਭਗ <xliff:g id="TIME">%1$s</xliff:g> ਚੱਲੇਗਾ (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
     <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"ਤੁਹਾਡੀ ਵਰਤੋਂ ਦੇ ਆਧਾਰ \'ਤੇ ਲਗਭਗ <xliff:g id="TIME">%1$s</xliff:g> ਚੱਲੇਗਾ"</string>
     <string name="power_discharge_by" msgid="6453537733650125582">"ਲਗਭਗ <xliff:g id="TIME">%1$s</xliff:g> ਚੱਲੇਗਾ (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only" msgid="107616694963545745">"ਲਗਭਗ <xliff:g id="TIME">%1$s</xliff:g> ਚੱਲੇਗਾ"</string>
+    <string name="power_discharge_by_only" msgid="107616694963545745">"ਲਗਭਗ <xliff:g id="TIME">%1$s</xliff:g> ਤੱਕ ਚੱਲੇਗੀ"</string>
     <string name="power_discharge_by_only_short" msgid="1372817269546888804">"<xliff:g id="TIME">%1$s</xliff:g> ਤੱਕ"</string>
     <string name="power_suggestion_extend_battery" msgid="4401408879069551485">"ਬੈਟਰੀ ਲਾਈਫ਼ <xliff:g id="TIME">%1$s</xliff:g> ਤੋਂ ਬਾਅਦ ਤੱਕ ਵਧਾਓ"</string>
     <string name="power_remaining_less_than_duration_only" msgid="5996752448813295329">"<xliff:g id="THRESHOLD">%1$s</xliff:g> ਤੋਂ ਘੱਟ ਸਮਾਂ ਬਾਕੀ"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ਟੈਬਲੈੱਟ ਛੇਤੀ ਹੀ ਬੰਦ ਹੋ ਸਕਦਾ ਹੈ (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"ਡੀਵਾਈਸ ਛੇਤੀ ਹੀ ਬੰਦ ਹੋ ਸਕਦਾ ਹੈ (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"ਪੂਰੀ ਤਰ੍ਹਾਂ ਚਾਰਜ ਹੋਣ ਲਈ <xliff:g id="TIME">%1$s</xliff:g> ਬਾਕੀ"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - ਪੂਰੀ ਤਰ੍ਹਾਂ ਚਾਰਜ ਹੋਣ ਵਿੱਚ <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"ਚਾਰਜ ਹੋਣ ਵਿੱਚ <xliff:g id="TIME">%1$s</xliff:g> ਬਾਕੀ"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ਤੱਕ ਚਾਰਜ ਹੋ ਜਾਵੇਗੀ"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"ਅਗਿਆਤ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ਚਾਰਜ ਹੋ ਰਿਹਾ ਹੈ"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ਚਾਰਜ ਕੀਤਾ ਜਾ ਰਿਹਾ ਹੈ"</string>
diff --git a/packages/SettingsLib/res/values-pl/strings.xml b/packages/SettingsLib/res/values-pl/strings.xml
index 60a4c53..caed8c3 100644
--- a/packages/SettingsLib/res/values-pl/strings.xml
+++ b/packages/SettingsLib/res/values-pl/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet może się wkrótce wyłączyć (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Urządzenie może się wkrótce wyłączyć (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> do pełnego naładowania"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do pełnego naładowania"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Do naładowania <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – do naładowania <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Nieznane"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Ładowanie"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ładowanie"</string>
diff --git a/packages/SettingsLib/res/values-pt-rBR/strings.xml b/packages/SettingsLib/res/values-pt-rBR/strings.xml
index dd0a75b..04a24f1 100644
--- a/packages/SettingsLib/res/values-pt-rBR/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rBR/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"O tablet pode ser desligado em breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"O dispositivo pode ser desligado em breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> restante(s) até a carga completa"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> até a carga completa"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Tempo restante até a carga completa: <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g>: <xliff:g id="TIME">%2$s</xliff:g> até a carga completa"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Desconhecido"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Carregando"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"carregando"</string>
diff --git a/packages/SettingsLib/res/values-pt-rPT/strings.xml b/packages/SettingsLib/res/values-pt-rPT/strings.xml
index 501cf50..a206d1a 100644
--- a/packages/SettingsLib/res/values-pt-rPT/strings.xml
+++ b/packages/SettingsLib/res/values-pt-rPT/strings.xml
@@ -387,8 +387,8 @@
     <skip />
     <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"Deve durar até cerca da(s) <xliff:g id="TIME">%1$s</xliff:g> com base na sua utilização (<xliff:g id="LEVEL">%2$s</xliff:g>)."</string>
     <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"Deve durar até cerca da(s) <xliff:g id="TIME">%1$s</xliff:g> com base na sua utilização."</string>
-    <string name="power_discharge_by" msgid="6453537733650125582">"Deve durar até cerca da(s) <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)."</string>
-    <string name="power_discharge_by_only" msgid="107616694963545745">"Deve durar até cerca da(s) <xliff:g id="TIME">%1$s</xliff:g>."</string>
+    <string name="power_discharge_by" msgid="6453537733650125582">"Deve durar até cerca da(s) <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
+    <string name="power_discharge_by_only" msgid="107616694963545745">"Deve durar até cerca da(s) <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by_only_short" msgid="1372817269546888804">"Até à(s) <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_suggestion_extend_battery" msgid="4401408879069551485">"Prolongar a autonomia da bateria após <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_remaining_less_than_duration_only" msgid="5996752448813295329">"Resta(m) menos de <xliff:g id="THRESHOLD">%1$s</xliff:g>."</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"O tablet poderá ser encerrado em breve (<xliff:g id="LEVEL">%1$s</xliff:g>)."</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"O dispositivo poderá ser encerrado em breve (<xliff:g id="LEVEL">%1$s</xliff:g>)."</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Falta(m) <xliff:g id="TIME">%1$s</xliff:g> para concluir o carregamento"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> até ficar totalmente carregada"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Falta(m) <xliff:g id="TIME">%1$s</xliff:g> até ficar carregada"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> até ficar carregada"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Desconhecido"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"A carregar"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"a carregar…"</string>
diff --git a/packages/SettingsLib/res/values-pt/strings.xml b/packages/SettingsLib/res/values-pt/strings.xml
index dd0a75b..04a24f1 100644
--- a/packages/SettingsLib/res/values-pt/strings.xml
+++ b/packages/SettingsLib/res/values-pt/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"O tablet pode ser desligado em breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"O dispositivo pode ser desligado em breve (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> restante(s) até a carga completa"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> até a carga completa"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Tempo restante até a carga completa: <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g>: <xliff:g id="TIME">%2$s</xliff:g> até a carga completa"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Desconhecido"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Carregando"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"carregando"</string>
diff --git a/packages/SettingsLib/res/values-ro/strings.xml b/packages/SettingsLib/res/values-ro/strings.xml
index fb020e2..76a56e5 100644
--- a/packages/SettingsLib/res/values-ro/strings.xml
+++ b/packages/SettingsLib/res/values-ro/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tableta se poate închide în curând (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Dispozitivul se poate închide în curând (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Timp rămas până la încărcarea completă: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> până la încărcarea completă"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Au mai rămas <xliff:g id="TIME">%1$s</xliff:g> până la încărcare"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> până la încărcare"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Necunoscut"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Se încarcă"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"se încarcă"</string>
diff --git a/packages/SettingsLib/res/values-ru/strings.xml b/packages/SettingsLib/res/values-ru/strings.xml
index 806be6e..3e3768a 100644
--- a/packages/SettingsLib/res/values-ru/strings.xml
+++ b/packages/SettingsLib/res/values-ru/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Уровень заряда батареи: <xliff:g id="LEVEL">%1$s</xliff:g>. Планшет скоро завершит работу."</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Уровень заряда батареи: <xliff:g id="LEVEL">%1$s</xliff:g>. Устройство скоро завершит работу."</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Ещё <xliff:g id="TIME">%1$s</xliff:g> до полной зарядки"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> до полной зарядки"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> до полной зарядки"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> до полной зарядки"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Неизвестно"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Идет зарядка"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"заряжается"</string>
diff --git a/packages/SettingsLib/res/values-si/strings.xml b/packages/SettingsLib/res/values-si/strings.xml
index 925d5b4..186c23a 100644
--- a/packages/SettingsLib/res/values-si/strings.xml
+++ b/packages/SettingsLib/res/values-si/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ටැබ්ලටය ඉක්මනින් වැසිය හැකිය (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"උපාංගය ඉක්මනින් වැසිය හැකිය (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"පූර්ණව ආරෝපණය වන තෙක් <xliff:g id="TIME">%1$s</xliff:g> ඉතිරියි"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> සම්පූර්ණයෙන් ආරෝපණය වන තෙක්"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"ආරෝපණය වන තෙක් <xliff:g id="TIME">%1$s</xliff:g> ඇත"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - ආරෝපණය වන තෙක් <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"නොදනී"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ආරෝපණය වෙමින්"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ආරෝපණය වේ"</string>
diff --git a/packages/SettingsLib/res/values-sk/strings.xml b/packages/SettingsLib/res/values-sk/strings.xml
index e28825c..9559975 100644
--- a/packages/SettingsLib/res/values-sk/strings.xml
+++ b/packages/SettingsLib/res/values-sk/strings.xml
@@ -385,10 +385,10 @@
     <string name="power_discharging_duration_enhanced" msgid="1992003260664804080">"Zostáva približne <xliff:g id="TIME_REMAINING">%1$s</xliff:g> – závisí to od intenzity využitia (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
     <!-- no translation found for power_remaining_duration_only_short (9183070574408359726) -->
     <skip />
-    <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"Mal by vydržať približne do <xliff:g id="TIME">%1$s</xliff:g> v závislosti od využitia (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"Mal by vydržať približne do <xliff:g id="TIME">%1$s</xliff:g> v závislosti od využitia"</string>
-    <string name="power_discharge_by" msgid="6453537733650125582">"Mal by vydržať približne <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only" msgid="107616694963545745">"Mal by vydržať približne do <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"Podľa vášho využitia (<xliff:g id="LEVEL">%2$s</xliff:g>) vydrží asi do <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"Podľa vášho využitia vydrží asi do <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_discharge_by" msgid="6453537733650125582">"Vydrží asi do <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
+    <string name="power_discharge_by_only" msgid="107616694963545745">"Vydrží asi do <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by_only_short" msgid="1372817269546888804">"Do <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_suggestion_extend_battery" msgid="4401408879069551485">"Predĺžiť výdrž batérie minimálne do <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_remaining_less_than_duration_only" msgid="5996752448813295329">"Zostáva menej ako <xliff:g id="THRESHOLD">%1$s</xliff:g>"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet sa môže čoskoro vypnúť (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Zariadenie sa môže čoskoro vypnúť (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Zostávajúci čas do úplného nabitia: <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do úplného nabitia"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Zostávajúci čas do úplného nabitia: <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do úplného nabitia"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Neznáme"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Nabíja sa"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"nabíja sa"</string>
diff --git a/packages/SettingsLib/res/values-sl/strings.xml b/packages/SettingsLib/res/values-sl/strings.xml
index b16d5d9..62e4ad1 100644
--- a/packages/SettingsLib/res/values-sl/strings.xml
+++ b/packages/SettingsLib/res/values-sl/strings.xml
@@ -388,7 +388,7 @@
     <string name="power_discharge_by_enhanced" msgid="2095821536747992464">"Naprava bi morala glede na način uporabe (<xliff:g id="LEVEL">%2$s</xliff:g>) delovati do približno <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by_only_enhanced" msgid="2175151772952365149">"Naprava bi morala glede na način uporabe delovati do približno <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by" msgid="6453537733650125582">"Naprava bi morala delovati do približno <xliff:g id="TIME">%1$s</xliff:g> (<xliff:g id="LEVEL">%2$s</xliff:g>)"</string>
-    <string name="power_discharge_by_only" msgid="107616694963545745">"Naprava bi morala delovati do približno <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_discharge_by_only" msgid="107616694963545745">"Moralo bi zadostovati do približno <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_discharge_by_only_short" msgid="1372817269546888804">"Do <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_suggestion_extend_battery" msgid="4401408879069551485">"Podaljšanje časa delovanja akumulatorja za dlje kot <xliff:g id="TIME">%1$s</xliff:g>"</string>
     <string name="power_remaining_less_than_duration_only" msgid="5996752448813295329">"Preostalo manj kot <xliff:g id="THRESHOLD">%1$s</xliff:g>"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablični računalnik se bo morda kmalu zaustavil (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Naprava se bo morda kmalu zaustavila (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Še <xliff:g id="TIME">%1$s</xliff:g> do polne napolnjenosti"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do napolnjenosti"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Še <xliff:g id="TIME">%1$s</xliff:g> do polne napolnjenosti"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> do polne napolnjenosti"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Neznano"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Polnjenje"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"polnjenje"</string>
diff --git a/packages/SettingsLib/res/values-sq/strings.xml b/packages/SettingsLib/res/values-sq/strings.xml
index 7a054bb..0498f31 100644
--- a/packages/SettingsLib/res/values-sq/strings.xml
+++ b/packages/SettingsLib/res/values-sq/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tableti mund të fiket së shpejti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Pajisja mund të fiket së shpejti (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> të mbetura deri në ngarkimin e plotë"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> derisa të mbushet plotësisht"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> të mbetura për karikimin"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> deri sa të karikohen"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"I panjohur"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Po karikohet"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"po karikohet"</string>
diff --git a/packages/SettingsLib/res/values-sr/strings.xml b/packages/SettingsLib/res/values-sr/strings.xml
index 0edc985..3157dee 100644
--- a/packages/SettingsLib/res/values-sr/strings.xml
+++ b/packages/SettingsLib/res/values-sr/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Таблет ће се ускоро искључити (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Уређај ће се ускоро искључити (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> до потпуног пуњења"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> до потпуног пуњења"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Напуниће се за <xliff:g id="TIME">%1$s</xliff:g>"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – напуниће се за <xliff:g id="TIME">%2$s</xliff:g>"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Непознато"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Пуни се"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"пуни се"</string>
diff --git a/packages/SettingsLib/res/values-sv/strings.xml b/packages/SettingsLib/res/values-sv/strings.xml
index 862fc6c..31517b8 100644
--- a/packages/SettingsLib/res/values-sv/strings.xml
+++ b/packages/SettingsLib/res/values-sv/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Surfplattan kan stängas av snart (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Enheten kan stängas av snart (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Batteriet är fulladdat om <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> tills det är fulladdat"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> kvar till full laddning"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> till full laddning"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Okänd"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Laddar"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"laddas"</string>
diff --git a/packages/SettingsLib/res/values-sw/strings.xml b/packages/SettingsLib/res/values-sw/strings.xml
index 12922ca..d73084f 100644
--- a/packages/SettingsLib/res/values-sw/strings.xml
+++ b/packages/SettingsLib/res/values-sw/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Kompyuta kibao inakaribia kuzimika (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Kifaa kinakaribia kuzimika (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Imebaki <xliff:g id="TIME">%1$s</xliff:g> chaji ijae"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> hadi ijae chaji"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Zimesalia <xliff:g id="TIME">%1$s</xliff:g> hadi ijae chaji"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> hadi ijae chaji"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Haijulikani"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Inachaji"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"inachaji"</string>
diff --git a/packages/SettingsLib/res/values-ta/strings.xml b/packages/SettingsLib/res/values-ta/strings.xml
index 0073003..de70d08 100644
--- a/packages/SettingsLib/res/values-ta/strings.xml
+++ b/packages/SettingsLib/res/values-ta/strings.xml
@@ -138,8 +138,8 @@
     <string name="accessibility_wifi_security_type_none" msgid="1223747559986205423">"கடவுச்சொல் தேவைப்படாத திறந்த நெட்வொர்க்"</string>
     <string name="accessibility_wifi_security_type_secured" msgid="862921720418885331">"கடவுச்சொல் தேவைப்படும் பாதுகாப்பான நெட்வொர்க்"</string>
     <string name="process_kernel_label" msgid="3916858646836739323">"Android OS"</string>
-    <string name="data_usage_uninstalled_apps" msgid="614263770923231598">"அகற்றப்பட்ட பயன்பாடுகள்"</string>
-    <string name="data_usage_uninstalled_apps_users" msgid="7986294489899813194">"அகற்றப்பட்ட பயன்பாடுகள் மற்றும் பயனர்கள்"</string>
+    <string name="data_usage_uninstalled_apps" msgid="614263770923231598">"அகற்றப்பட்ட ஆப்ஸ்"</string>
+    <string name="data_usage_uninstalled_apps_users" msgid="7986294489899813194">"அகற்றப்பட்ட ஆப்ஸ் மற்றும் பயனர்கள்"</string>
     <string name="data_usage_ota" msgid="5377889154805560860">"சிஸ்டம் புதுப்பிப்புகள்"</string>
     <string name="tether_settings_title_usb" msgid="6688416425801386511">"USB டெதெரிங்"</string>
     <string name="tether_settings_title_wifi" msgid="3277144155960302049">"போர்ட்டபிள் ஹாட்ஸ்பாட்"</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"டேப்லெட் விரைவில் ஆஃப் ஆகக்கூடும் (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"சாதனம் விரைவில் ஆஃப் ஆகக்கூடும் (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"முழு சார்ஜாக <xliff:g id="TIME">%1$s</xliff:g> ஆகும்"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - முழு சார்ஜாக <xliff:g id="TIME">%2$s</xliff:g> ஆகும்"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"முழு சார்ஜாக <xliff:g id="TIME">%1$s</xliff:g> ஆகும்"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - முழு சார்ஜாக <xliff:g id="TIME">%2$s</xliff:g> ஆகும்"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"அறியப்படாத"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"சார்ஜ் ஆகிறது"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"சார்ஜ் ஆகிறது"</string>
@@ -437,7 +437,7 @@
     <string name="use_system_language_to_select_input_method_subtypes" msgid="5747329075020379587">"சாதன மொழிகளைப் பயன்படுத்து"</string>
     <string name="failed_to_open_app_settings_toast" msgid="1251067459298072462">"<xliff:g id="SPELL_APPLICATION_NAME">%1$s</xliff:g> க்கான அமைப்புகளைத் திறப்பதில் தோல்வி"</string>
     <string name="ime_security_warning" msgid="4135828934735934248">"இந்த உள்ளீட்டு முறையானது, கடவுச்சொற்கள் மற்றும் கிரெடிட் கார்டு எண்கள் போன்ற தனிப்பட்ட தகவல் உள்பட நீங்கள் உள்ளிடும் எல்லா உரையையும் சேகரிக்கக்கூடும். இது <xliff:g id="IME_APPLICATION_NAME">%1$s</xliff:g> பயன்பாட்டிலிருந்து வந்துள்ளது. இந்த உள்ளீட்டு முறையைப் பயன்படுத்தவா?"</string>
-    <string name="direct_boot_unaware_dialog_message" msgid="7870273558547549125">"குறிப்பு: மறுதொடக்கம் செய்த பிறகு, மொபைலைத் திறக்கும் வரை இந்தப் பயன்பாட்டால் தொடங்க முடியாது"</string>
+    <string name="direct_boot_unaware_dialog_message" msgid="7870273558547549125">"குறிப்பு: மறுதொடக்கம் செய்த பிறகு, மொபைலைத் திறக்கும் வரை இந்த ஆப்ஸால் தொடங்க முடியாது"</string>
     <string name="ims_reg_title" msgid="7609782759207241443">"IMS பதிவின் நிலை"</string>
     <string name="ims_reg_status_registered" msgid="933003316932739188">"பதிவு செய்யப்பட்டது"</string>
     <string name="ims_reg_status_not_registered" msgid="6529783773485229486">"பதிவு செய்யப்படவில்லை"</string>
diff --git a/packages/SettingsLib/res/values-te/strings.xml b/packages/SettingsLib/res/values-te/strings.xml
index e591121..3591670 100644
--- a/packages/SettingsLib/res/values-te/strings.xml
+++ b/packages/SettingsLib/res/values-te/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"టాబ్లెట్ షట్‌డౌన్ కావచ్చు (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"పరికరం త్వరలో షట్‌డౌన్ కావచ్చు (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"పూర్తిగా ఛార్జ్ కావడానికి <xliff:g id="TIME">%1$s</xliff:g> పడుతుంది"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g>లో పూర్తిగా ఛార్జ్ అవుతుంది"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"ఛార్జ్ అవ్వడానికి <xliff:g id="TIME">%1$s</xliff:g> సమయం మిగిలి ఉంది"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - ఛార్జ్ అవ్వడానికి <xliff:g id="TIME">%2$s</xliff:g> పడుతుంది"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"తెలియదు"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"ఛార్జ్ అవుతోంది"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"ఛార్జ్ అవుతోంది"</string>
diff --git a/packages/SettingsLib/res/values-th/strings.xml b/packages/SettingsLib/res/values-th/strings.xml
index 0b184d2..1cfe45e 100644
--- a/packages/SettingsLib/res/values-th/strings.xml
+++ b/packages/SettingsLib/res/values-th/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"แท็บเล็ตอาจปิดเครื่องในไม่ช้า (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"อุปกรณ์อาจปิดเครื่องในไม่ช้า (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"อีก <xliff:g id="TIME">%1$s</xliff:g> จึงจะชาร์จเต็ม"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> จนกว่าจะชาร์จเต็ม"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"เหลือ <xliff:g id="TIME">%1$s</xliff:g> จนกว่าจะชาร์จ"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> จนกว่าจะชาร์จ"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"ไม่ทราบ"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"กำลังชาร์จ"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"กำลังชาร์จ"</string>
diff --git a/packages/SettingsLib/res/values-tl/strings.xml b/packages/SettingsLib/res/values-tl/strings.xml
index 85b6438..8b3118b 100644
--- a/packages/SettingsLib/res/values-tl/strings.xml
+++ b/packages/SettingsLib/res/values-tl/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Malapit nang mag-shutdown ang tablet (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Malapit nang mag-shut down ang device (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> ang natitira bago makumpleto ang charge"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> hanggang sa makumpleto ang charge"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> ang natitira bago matapos mag-charge"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> hanggang matapos mag-charge"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Hindi Kilala"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Nagcha-charge"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"nagcha-charge"</string>
diff --git a/packages/SettingsLib/res/values-tr/strings.xml b/packages/SettingsLib/res/values-tr/strings.xml
index 6031eca..5891c79 100644
--- a/packages/SettingsLib/res/values-tr/strings.xml
+++ b/packages/SettingsLib/res/values-tr/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Tablet kısa süre içinde kapanabilir (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Cihaz kısa süre içinde kapanabilir (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Tam olarak şarj olmasına <xliff:g id="TIME">%1$s</xliff:g> kaldı"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - Tam şarj olmasına <xliff:g id="TIME">%2$s</xliff:g> kaldı"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Şarj olmaya <xliff:g id="TIME">%1$s</xliff:g> kaldı"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - şarj olmaya <xliff:g id="TIME">%2$s</xliff:g> kaldı"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Bilinmiyor"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Şarj oluyor"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"şarj oluyor"</string>
diff --git a/packages/SettingsLib/res/values-uk/strings.xml b/packages/SettingsLib/res/values-uk/strings.xml
index 5f3c6a6..0bca307 100644
--- a/packages/SettingsLib/res/values-uk/strings.xml
+++ b/packages/SettingsLib/res/values-uk/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Планшет може невдовзі вимкнутися (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Пристрій може невдовзі вимкнутися (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"До повного зарядження залишилося <xliff:g id="TIME">%1$s</xliff:g>"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> до повного заряду"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> до повного заряду"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> до повного заряду"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Невідомо"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Заряджається"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"заряджається"</string>
diff --git a/packages/SettingsLib/res/values-ur/strings.xml b/packages/SettingsLib/res/values-ur/strings.xml
index 82d9b3f..1e27b48 100644
--- a/packages/SettingsLib/res/values-ur/strings.xml
+++ b/packages/SettingsLib/res/values-ur/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"ٹیبلیٹ جلد ہی بند ہو سکتا ہے (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"آلہ جلد ہی بند ہو سکتا ہے (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"‎<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>‎"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"پوری طرح چارج ہونے میں <xliff:g id="TIME">%1$s</xliff:g> باقی ہے"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> پوری طرح چارج ہونے تک"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"چارج ہونے میں <xliff:g id="TIME">%1$s</xliff:g> باقی"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> چارج ہونے تک"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"نامعلوم"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"چارج ہو رہا ہے"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"چارج ہو رہا ہے"</string>
diff --git a/packages/SettingsLib/res/values-uz/arrays.xml b/packages/SettingsLib/res/values-uz/arrays.xml
index 164aa93..4bc995f 100644
--- a/packages/SettingsLib/res/values-uz/arrays.xml
+++ b/packages/SettingsLib/res/values-uz/arrays.xml
@@ -241,7 +241,7 @@
     <item msgid="2355151170975410323">"“<xliff:g id="AS_TYPED_COMMAND">adb shell dumpsys gfxinfo</xliff:g>” buyrug‘ida"</item>
   </string-array>
   <string-array name="debug_hw_overdraw_entries">
-    <item msgid="8190572633763871652">"YOQILMAGAN"</item>
+    <item msgid="8190572633763871652">"Yoqilmagan"</item>
     <item msgid="7688197031296835369">"Ortiqcha chizilgan joylarni ko‘rsatish"</item>
     <item msgid="2290859360633824369">"Muayyan rangdagi hududlarni ajratib belgilash"</item>
   </string-array>
diff --git a/packages/SettingsLib/res/values-uz/strings.xml b/packages/SettingsLib/res/values-uz/strings.xml
index 0d3e8de..487100c 100644
--- a/packages/SettingsLib/res/values-uz/strings.xml
+++ b/packages/SettingsLib/res/values-uz/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Planshet tez orada o‘chib qolishi mumkin (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Qurilma tez orada o‘chib qolishi mumkin (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"To‘lishiga <xliff:g id="TIME">%1$s</xliff:g> qoldi"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> ichida to‘ladi"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> ichida toʻliq quvvat oladi"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> ichida toʻliq quvvat oladi"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Noma’lum"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Quvvat olmoqda"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"quvvat olmoqda"</string>
diff --git a/packages/SettingsLib/res/values-vi/strings.xml b/packages/SettingsLib/res/values-vi/strings.xml
index 5c06c80..c247617 100644
--- a/packages/SettingsLib/res/values-vi/strings.xml
+++ b/packages/SettingsLib/res/values-vi/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Máy tính bảng có thể sắp tắt (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Thiết bị có thể sắp tắt (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"Còn <xliff:g id="TIME">%1$s</xliff:g> cho tới khi được sạc đầy"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> cho tới khi được sạc đầy"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"Còn <xliff:g id="TIME">%1$s</xliff:g> nữa là sạc xong"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> – <xliff:g id="TIME">%2$s</xliff:g> nữa là sạc xong"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Không xác định"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Đang sạc"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"đang sạc"</string>
diff --git a/packages/SettingsLib/res/values-zh-rCN/strings.xml b/packages/SettingsLib/res/values-zh-rCN/strings.xml
index 460142c..dddc107 100644
--- a/packages/SettingsLib/res/values-zh-rCN/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rCN/strings.xml
@@ -60,7 +60,7 @@
     <string name="speed_label_medium" msgid="3175763313268941953">"适中"</string>
     <string name="speed_label_fast" msgid="7715732164050975057">"快"</string>
     <string name="speed_label_very_fast" msgid="2265363430784523409">"很快"</string>
-    <string name="preference_summary_default_combination" msgid="8532964268242666060">"<xliff:g id="STATE">%1$s</xliff:g>/<xliff:g id="DESCRIPTION">%2$s</xliff:g>"</string>
+    <string name="preference_summary_default_combination" msgid="8532964268242666060">"<xliff:g id="STATE">%1$s</xliff:g> / <xliff:g id="DESCRIPTION">%2$s</xliff:g>"</string>
     <string name="bluetooth_disconnected" msgid="6557104142667339895">"已断开连接"</string>
     <string name="bluetooth_disconnecting" msgid="8913264760027764974">"正在断开连接..."</string>
     <string name="bluetooth_connecting" msgid="8555009514614320497">"正在连接..."</string>
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"平板电脑可能即将关机 (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"设备可能即将关机 (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"还需 <xliff:g id="TIME">%1$s</xliff:g>充满电"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - 还需 <xliff:g id="TIME">%2$s</xliff:g>充满"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"还剩 <xliff:g id="TIME">%1$s</xliff:g>充满电"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g>后充满电"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"未知"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"正在充电"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"正在充电"</string>
diff --git a/packages/SettingsLib/res/values-zh-rHK/strings.xml b/packages/SettingsLib/res/values-zh-rHK/strings.xml
index 286765d..8560e22 100644
--- a/packages/SettingsLib/res/values-zh-rHK/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rHK/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"平板電腦可能即將關機 (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"裝置可能即將關機 (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g>後就能充滿電"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - 還需 <xliff:g id="TIME">%2$s</xliff:g>才能充滿電"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"還需 <xliff:g id="TIME">%1$s</xliff:g>才能充滿電"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - 還需 <xliff:g id="TIME">%2$s</xliff:g>才能充滿電"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"未知"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"充電中"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"正在充電"</string>
diff --git a/packages/SettingsLib/res/values-zh-rTW/strings.xml b/packages/SettingsLib/res/values-zh-rTW/strings.xml
index c641302..404aa19 100644
--- a/packages/SettingsLib/res/values-zh-rTW/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rTW/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"平板電腦可能即將關機 (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"裝置可能即將關機 (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"再過 <xliff:g id="TIME">%1$s</xliff:g>就能完成充電"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g>後充飽"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g>後充飽電"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g>後充飽電"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"不明"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"充電中"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"充電中"</string>
diff --git a/packages/SettingsLib/res/values-zu/strings.xml b/packages/SettingsLib/res/values-zu/strings.xml
index 1bfbf07..542332f 100644
--- a/packages/SettingsLib/res/values-zu/strings.xml
+++ b/packages/SettingsLib/res/values-zu/strings.xml
@@ -402,8 +402,8 @@
     <string name="power_remaining_duration_shutdown_imminent" product="tablet" msgid="7466484148515796216">"Ithebhulethi ingacisha maduze (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_remaining_duration_shutdown_imminent" product="device" msgid="603933521600231649">"Idivayisi ingacisha maduze (<xliff:g id="LEVEL">%1$s</xliff:g>)"</string>
     <string name="power_charging" msgid="1779532561355864267">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="STATE">%2$s</xliff:g>"</string>
-    <string name="power_remaining_charging_duration_only" msgid="1421102457410268886">"<xliff:g id="TIME">%1$s</xliff:g> kushiywe ishaja"</string>
-    <string name="power_charging_duration" msgid="4676999980973411875">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> kuze ligcwale ngokuphelele"</string>
+    <string name="power_remaining_charging_duration_only" msgid="6672239353042034265">"<xliff:g id="TIME">%1$s</xliff:g> esele ize ishaje"</string>
+    <string name="power_charging_duration" msgid="5850751284103249125">"<xliff:g id="LEVEL">%1$s</xliff:g> - <xliff:g id="TIME">%2$s</xliff:g> ize igcwale"</string>
     <string name="battery_info_status_unknown" msgid="196130600938058547">"Akwaziwa"</string>
     <string name="battery_info_status_charging" msgid="1705179948350365604">"Iyashaja"</string>
     <string name="battery_info_status_charging_lower" msgid="8689770213898117994">"iyashaja"</string>
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index 8f47470..1f923af 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -1004,9 +1004,9 @@
     <!-- [CHAR_LIMIT=40] Label for battery level chart when charging -->
     <string name="power_charging"><xliff:g id="level">%1$s</xliff:g> - <xliff:g id="state">%2$s</xliff:g></string>
     <!-- [CHAR_LIMIT=40] Label for estimated remaining duration of battery charging -->
-    <string name="power_remaining_charging_duration_only"><xliff:g id="time">%1$s</xliff:g> left until fully charged</string>
+    <string name="power_remaining_charging_duration_only"><xliff:g id="time">%1$s</xliff:g> left until charged</string>
     <!-- [CHAR_LIMIT=40] Label for battery level chart when charging with duration -->
-    <string name="power_charging_duration"><xliff:g id="level">%1$s</xliff:g> - <xliff:g id="time">%2$s</xliff:g> until fully charged</string>
+    <string name="power_charging_duration"><xliff:g id="level">%1$s</xliff:g> - <xliff:g id="time">%2$s</xliff:g> until charged</string>
 
     <!-- Battery Info screen. Value for a status item.  Used for diagnostic info screens, precise translation isn't needed -->
     <string name="battery_info_status_unknown">Unknown</string>
diff --git a/packages/SettingsLib/search/Android.bp b/packages/SettingsLib/search/Android.bp
index 15c8367..d398aa5 100644
--- a/packages/SettingsLib/search/Android.bp
+++ b/packages/SettingsLib/search/Android.bp
@@ -1,7 +1,9 @@
-java_library {
+android_library {
     name: "SettingsLib-search",
-    host_supported: true,
     srcs: ["src/**/*.java"],
+
+    sdk_version: "system_current",
+    min_sdk_version: "21",
 }
 
 java_plugin {
@@ -9,9 +11,11 @@
     processor_class: "com.android.settingslib.search.IndexableProcessor",
     static_libs: [
         "javapoet-prebuilt-jar",
-        "SettingsLib-search",
     ],
-    srcs: ["processor-src/**/*.java"],
+    srcs: [
+        "processor-src/**/*.java",
+        "src/com/android/settingslib/search/SearchIndexable.java"
+    ],
     java_resource_dirs: ["resources"],
 }
 
diff --git a/packages/SettingsLib/search/AndroidManifest.xml b/packages/SettingsLib/search/AndroidManifest.xml
new file mode 100644
index 0000000..9707283
--- /dev/null
+++ b/packages/SettingsLib/search/AndroidManifest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.settingslib.search">
+
+</manifest>
\ No newline at end of file
diff --git a/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java b/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java
index 10fc685..5dc9061 100644
--- a/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java
+++ b/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java
@@ -143,7 +143,7 @@
 
         final TypeSpec baseClass = TypeSpec.classBuilder(CLASS_BASE)
                 .addModifiers(Modifier.PUBLIC)
-                .addSuperinterface(ClassName.get(SearchIndexableResources.class))
+                .addSuperinterface(ClassName.get(PACKAGE, "SearchIndexableResources"))
                 .addField(providers)
                 .addMethod(baseConstructorBuilder.build())
                 .addMethod(addIndex)
@@ -210,4 +210,4 @@
         mFiler = processingEnvironment.getFiler();
         mMessager = processingEnvironment.getMessager();
     }
-}
+}
\ No newline at end of file
diff --git a/packages/SettingsLib/search/src/com/android/settingslib/search/Indexable.java b/packages/SettingsLib/search/src/com/android/settingslib/search/Indexable.java
new file mode 100644
index 0000000..e68b0d1
--- /dev/null
+++ b/packages/SettingsLib/search/src/com/android/settingslib/search/Indexable.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2019 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.settingslib.search;
+
+import android.content.Context;
+import android.provider.SearchIndexableResource;
+
+import java.util.List;
+
+/**
+ * Interface for classes whose instances can provide data for indexing.
+ *
+ * See {@link android.provider.SearchIndexableResource} and {@link SearchIndexableRaw}.
+ */
+public interface Indexable {
+
+    /**
+     * Interface for classes whose instances can provide data for indexing.
+     */
+    interface SearchIndexProvider {
+        /**
+         * Return a list of references for indexing.
+         *
+         * See {@link android.provider.SearchIndexableResource}
+         *
+         * @param context the context.
+         * @param enabled hint telling if the data needs to be considered into the search results
+         *                or not.
+         * @return a list of {@link android.provider.SearchIndexableResource} references.
+         * Can be null.
+         */
+        List<SearchIndexableResource> getXmlResourcesToIndex(Context context, boolean enabled);
+
+        /**
+         * Return a list of raw data for indexing. See {@link SearchIndexableRaw}
+         *
+         * @param context the context.
+         * @param enabled hint telling if the data needs to be considered into the search results
+         *                or not.
+         * @return a list of {@link SearchIndexableRaw} references. Can be null.
+         */
+        List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled);
+
+        /**
+         * Return a list of data keys that cannot be indexed. See {@link SearchIndexableRaw}
+         *
+         * @param context the context.
+         * @return a list of {@link SearchIndexableRaw} references. Can be null.
+         */
+        List<String> getNonIndexableKeys(Context context);
+    }
+}
diff --git a/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableRaw.java b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableRaw.java
new file mode 100644
index 0000000..021ca33
--- /dev/null
+++ b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableRaw.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2019 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.settingslib.search;
+
+import android.content.Context;
+import android.provider.SearchIndexableData;
+
+/**
+ * Indexable raw data for Search.
+ *
+ * This is the raw data used by the Indexer and should match its data model.
+ *
+ * See {@link Indexable} and {@link android.provider.SearchIndexableResource}.
+ */
+public class SearchIndexableRaw extends SearchIndexableData {
+
+    /**
+     * Title's raw data.
+     */
+    public String title;
+
+    /**
+     * Summary's raw data when the data is "ON".
+     */
+    public String summaryOn;
+
+    /**
+     * Summary's raw data when the data is "OFF".
+     */
+    public String summaryOff;
+
+    /**
+     * Entries associated with the raw data (when the data can have several values).
+     */
+    public String entries;
+
+    /**
+     * Keywords' raw data.
+     */
+    public String keywords;
+
+    /**
+     * Fragment's or Activity's title associated with the raw data.
+     */
+    public String screenTitle;
+
+    public SearchIndexableRaw(Context context) {
+        super(context);
+    }
+}
diff --git a/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java
index 300d360..976647b 100644
--- a/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java
+++ b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java
@@ -32,4 +32,4 @@
      * as a device binary.
      */
     void addIndex(Class indexClass);
-}
+}
\ No newline at end of file
diff --git a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
index 6a90671..19c6664 100644
--- a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
+++ b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
@@ -865,6 +865,10 @@
         void handleRebuildList() {
             AppFilter filter;
             Comparator<AppEntry> comparator;
+
+            if (!mResumed) {
+                return;
+            }
             synchronized (mRebuildSync) {
                 if (!mRebuildRequested) {
                     return;
@@ -1069,8 +1073,8 @@
                 }
             }
             if (rebuildingSessions != null) {
-                for (int i = 0; i < rebuildingSessions.size(); i++) {
-                    rebuildingSessions.get(i).handleRebuildList();
+                for (Session session : rebuildingSessions) {
+                    session.handleRebuildList();
                 }
             }
 
diff --git a/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationAccesses.java b/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationAccesses.java
index ea39317..81ca9ea 100644
--- a/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationAccesses.java
+++ b/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationAccesses.java
@@ -111,8 +111,9 @@
             for (int op : LOCATION_OPS) {
                 final String permission = AppOpsManager.opToPermission(op);
                 final int permissionFlags = pm.getPermissionFlags(permission, packageName, user);
-                if (PermissionChecker.checkPermission(mContext, permission, -1, uid, packageName)
-                        == PermissionChecker.PERMISSION_GRANTED) {
+                if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
+                        PermissionChecker.PID_UNKNOWN, uid, packageName)
+                                == PermissionChecker.PERMISSION_GRANTED) {
                     if ((permissionFlags
                             & PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED) == 0) {
                         showApp = false;
diff --git a/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java b/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java
index 60c9984..104cc8f 100644
--- a/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java
+++ b/packages/SettingsLib/src/com/android/settingslib/location/RecentLocationApps.java
@@ -110,9 +110,9 @@
                     final String permission = AppOpsManager.opToPermission(op);
                     final int permissionFlags = pm.getPermissionFlags(permission, packageName,
                             user);
-                    if (PermissionChecker.checkPermission(mContext, permission, -1, uid,
-                            packageName)
-                            == PermissionChecker.PERMISSION_GRANTED) {
+                    if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
+                            PermissionChecker.PID_UNKNOWN, uid, packageName)
+                                    == PermissionChecker.PERMISSION_GRANTED) {
                         if ((permissionFlags
                                 & PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED)
                                 == 0) {
diff --git a/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java b/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java
index 5c9a06f..4e052f1 100644
--- a/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java
@@ -26,7 +26,7 @@
 
     private static volatile Thread sMainThread;
     private static volatile Handler sMainThreadHandler;
-    private static volatile ExecutorService sSingleThreadExecutor;
+    private static volatile ExecutorService sThreadExecutor;
 
     /**
      * Returns true if the current thread is the UI thread.
@@ -64,10 +64,11 @@
      * @Return A future of the task that can be monitored for updates or cancelled.
      */
     public static Future postOnBackgroundThread(Runnable runnable) {
-        if (sSingleThreadExecutor == null) {
-            sSingleThreadExecutor = Executors.newSingleThreadExecutor();
+        if (sThreadExecutor == null) {
+            sThreadExecutor = Executors.newFixedThreadPool(
+                    Runtime.getRuntime().availableProcessors());
         }
-        return sSingleThreadExecutor.submit(runnable);
+        return sThreadExecutor.submit(runnable);
     }
 
     /**
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/ApplicationsStateRoboTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/ApplicationsStateRoboTest.java
index f8697a1..95a4f69b 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/ApplicationsStateRoboTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/applications/ApplicationsStateRoboTest.java
@@ -269,7 +269,7 @@
     }
 
     @Test
-    public void testDefaultSessionLoadsAll() {
+    public void testDefaultSession_isResumed_LoadsAll() {
         mSession.onResume();
 
         addApp(HOME_PACKAGE_NAME, 1);
@@ -296,6 +296,19 @@
     }
 
     @Test
+    public void testDefaultSession_isPaused_NotLoadsAll() {
+        mSession.onResume();
+
+        addApp(HOME_PACKAGE_NAME, 1);
+        addApp(LAUNCHABLE_PACKAGE_NAME, 2);
+        mSession.mResumed = false;
+        mSession.rebuild(ApplicationsState.FILTER_EVERYTHING, ApplicationsState.SIZE_COMPARATOR);
+        processAllMessages();
+
+        verify(mCallbacks, never()).onRebuildComplete(mAppEntriesCaptor.capture());
+    }
+
+    @Test
     public void testCustomSessionLoadsIconsOnly() {
         mSession.setSessionFlags(ApplicationsState.FLAG_SESSION_REQUEST_ICONS);
         mSession.onResume();
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileTest.java
index 5da6205..2664ecd 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/drawer/TileTest.java
@@ -23,7 +23,6 @@
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.shadow.api.Shadow;
 import org.robolectric.shadows.ShadowPackageManager;
-import org.robolectric.util.ReflectionHelpers;
 
 @RunWith(RobolectricTestRunner.class)
 public class TileTest {
@@ -41,7 +40,7 @@
         mActivityInfo.name = "abc";
         mActivityInfo.icon = com.android.internal.R.drawable.ic_plus;
         mActivityInfo.metaData = new Bundle();
-        mTile = new Tile(mActivityInfo, "category");
+        mTile = new ActivityTile(mActivityInfo, "category");
     }
 
     @Test
@@ -70,7 +69,7 @@
     @Test
     public void getIcon_noContextOrMetadata_returnNull() {
         mActivityInfo.metaData = null;
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
         assertThat(tile.getIcon(null)).isNull();
         assertThat(tile.getIcon(RuntimeEnvironment.application)).isNull();
     }
@@ -100,7 +99,7 @@
 
     @Test
     public void isIconTintable_hasMetadata_shouldReturnIconTintableMetadata() {
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
 
         mActivityInfo.metaData.putBoolean(TileUtils.META_DATA_PREFERENCE_ICON_TINTABLE, false);
         assertThat(tile.isIconTintable(RuntimeEnvironment.application)).isFalse();
@@ -111,14 +110,14 @@
 
     @Test
     public void isIconTintable_noIcon_shouldReturnFalse() {
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
 
         assertThat(tile.isIconTintable(RuntimeEnvironment.application)).isFalse();
     }
 
     @Test
     public void isIconTintable_noTintableMetadata_shouldReturnFalse() {
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
         mActivityInfo.metaData.putInt(META_DATA_PREFERENCE_ICON, android.R.drawable.ic_info);
 
         assertThat(tile.isIconTintable(RuntimeEnvironment.application)).isFalse();
@@ -126,7 +125,7 @@
 
     @Test
     public void getPriority_noMetadata_return0() {
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
 
         assertThat(tile.getOrder()).isEqualTo(0);
     }
@@ -135,7 +134,7 @@
     public void getPriority_badMetadata_return0() {
         mActivityInfo.metaData.putString(META_DATA_KEY_ORDER, "1");
 
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
 
         assertThat(tile.getOrder()).isEqualTo(0);
     }
@@ -144,7 +143,7 @@
     public void getPriority_validMetadata_returnMetadataValue() {
         mActivityInfo.metaData.putInt(META_DATA_KEY_ORDER, 1);
 
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
 
         assertThat(tile.getOrder()).isEqualTo(1);
     }
@@ -157,7 +156,7 @@
         spm.addResolveInfoForIntent(
                 new Intent().setClassName(mActivityInfo.packageName, mActivityInfo.name), info);
 
-        final Tile tile = new Tile(mActivityInfo, "category");
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
         final long staleTimeStamp = -10000;
         tile.mLastUpdateTime = staleTimeStamp;
 
@@ -173,8 +172,8 @@
         final ShadowPackageManager spm = Shadow.extract(mContext.getPackageManager());
         spm.removePackage(mActivityInfo.packageName);
 
-        final Tile tile = new Tile(mActivityInfo, "category");
-        ReflectionHelpers.setField(tile, "mActivityInfo", null);
+        final Tile tile = new ActivityTile(mActivityInfo, "category");
+        tile.mComponentInfo = null;
 
         assertThat(tile.getTitle(RuntimeEnvironment.application)).isNull();
     }
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/utils/ThreadUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/utils/ThreadUtilsTest.java
index 26db124..5114b00 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/utils/ThreadUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/utils/ThreadUtilsTest.java
@@ -50,7 +50,7 @@
     }
 
     @Test
-    public void testPostOnMainThread_shouldRunOnMainTread() {
+    public void testPostOnMainThread_shouldRunOnMainThread() {
         TestRunnable cr = new TestRunnable();
         ShadowLooper.pauseMainLooper();
         ThreadUtils.postOnMainThread(cr);
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AdaptiveIconTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AdaptiveIconTest.java
index ed6b9b0..6cbae05 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AdaptiveIconTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/AdaptiveIconTest.java
@@ -37,6 +37,7 @@
 import android.os.Bundle;
 
 import com.android.settingslib.R;
+import com.android.settingslib.drawer.ActivityTile;
 import com.android.settingslib.drawer.CategoryKey;
 import com.android.settingslib.drawer.Tile;
 
@@ -84,7 +85,7 @@
 
     @Test
     public void setBackgroundColor_externalTileWithBackgroundColorRawValue_shouldUpdateIcon() {
-        final Tile tile = spy(new Tile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE));
+        final Tile tile = spy(new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE));
         mActivityInfo.metaData.putInt(META_DATA_PREFERENCE_ICON_BACKGROUND_ARGB, 0xff0000);
         doReturn(Icon.createWithResource(mContext, R.drawable.ic_system_update))
                 .when(tile).getIcon(mContext);
@@ -97,7 +98,7 @@
 
     @Test
     public void setBackgroundColor_tileWithoutBackgroundColor_shouldSetDefaultBackgroundColor() {
-        final Tile tile = spy(new Tile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE));
+        final Tile tile = spy(new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE));
         doReturn(Icon.createWithResource(mContext, R.drawable.ic_system_update))
             .when(tile).getIcon(mContext);
         final AdaptiveIcon icon = new AdaptiveIcon(mContext, new ColorDrawable(Color.BLACK));
@@ -110,7 +111,7 @@
 
     @Test
     public void onBindTile_externalTileWithBackgroundColorHint_shouldUpdateIcon() {
-        final Tile tile = spy(new Tile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE));
+        final Tile tile = spy(new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_HOMEPAGE));
         mActivityInfo.metaData.putInt(META_DATA_PREFERENCE_ICON_BACKGROUND_HINT,
                 R.color.bt_outline_color);
         doReturn(Icon.createWithResource(mContext, R.drawable.ic_system_update))
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
index 8c2e431..67062b7 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
@@ -100,8 +100,6 @@
         Settings.Secure.DOZE_PICK_UP_GESTURE,
         Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
         Settings.Secure.DOZE_TAP_SCREEN_GESTURE,
-        Settings.Secure.DOZE_WAKE_LOCK_SCREEN_GESTURE,
-        Settings.Secure.DOZE_WAKE_DISPLAY_GESTURE,
         Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
         Settings.Secure.AUTOMATIC_STORAGE_MANAGER_DAYS_TO_RETAIN,
         Settings.Secure.FACE_UNLOCK_KEYGUARD_ENABLED,
@@ -114,7 +112,6 @@
         Settings.Secure.ASSIST_GESTURE_WAKE_ENABLED,
         Settings.Secure.VR_DISPLAY_MODE,
         Settings.Secure.NOTIFICATION_BADGING,
-        Settings.Secure.NOTIFICATION_BUBBLES,
         Settings.Secure.NOTIFICATION_DISMISS_RTL,
         Settings.Secure.QS_AUTO_ADDED_TILES,
         Settings.Secure.SCREENSAVER_ENABLED,
@@ -145,12 +142,9 @@
         Settings.Secure.TRUST_AGENTS_EXTEND_UNLOCK,
         Settings.Secure.UI_NIGHT_MODE,
         Settings.Secure.LOCK_SCREEN_WHEN_TRUST_LOST,
-        Settings.Secure.SKIP_GESTURE,
         Settings.Secure.SKIP_DIRECTION,
-        Settings.Secure.SILENCE_GESTURE,
         Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES,
         Settings.Secure.NAVIGATION_MODE,
-        Settings.Secure.AWARE_ENABLED,
         Settings.Secure.SKIP_GESTURE_COUNT,
         Settings.Secure.SKIP_TOUCH_COUNT,
         Settings.Secure.SILENCE_ALARMS_GESTURE_COUNT,
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
index f160edc6..976f336 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
@@ -157,7 +157,6 @@
         VALIDATORS.put(Secure.ASSIST_GESTURE_WAKE_ENABLED, BOOLEAN_VALIDATOR);
         VALIDATORS.put(Secure.VR_DISPLAY_MODE, new DiscreteValueValidator(new String[] {"0", "1"}));
         VALIDATORS.put(Secure.NOTIFICATION_BADGING, BOOLEAN_VALIDATOR);
-        VALIDATORS.put(Secure.NOTIFICATION_BUBBLES, BOOLEAN_VALIDATOR);
         VALIDATORS.put(Secure.NOTIFICATION_DISMISS_RTL, BOOLEAN_VALIDATOR);
         VALIDATORS.put(Secure.QS_AUTO_ADDED_TILES, TILE_LIST_VALIDATOR);
         VALIDATORS.put(Secure.SCREENSAVER_ENABLED, BOOLEAN_VALIDATOR);
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 365923e..2ce4e97 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -76,7 +76,7 @@
                 ConfigSettingsProto.RUNTIME_NATIVE_SETTINGS);
         namespaceToFieldMap.put(DeviceConfig.NAMESPACE_RUNTIME_NATIVE_BOOT,
                 ConfigSettingsProto.RUNTIME_NATIVE_BOOT_SETTINGS);
-        namespaceToFieldMap.put(DeviceConfig.NAMESPACE_STORAGE,
+        namespaceToFieldMap.put(DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
                 ConfigSettingsProto.STORAGE_SETTINGS);
         namespaceToFieldMap.put(DeviceConfig.NAMESPACE_SYSTEMUI,
                 ConfigSettingsProto.SYSTEMUI_SETTINGS);
@@ -2242,9 +2242,6 @@
         dumpSetting(s, p,
                 Settings.Secure.PACKAGE_VERIFIER_USER_CONSENT,
                 SecureSettingsProto.PackageVerifier.USER_CONSENT);
-        dumpSetting(s, p,
-                Settings.Secure.PACKAGE_VERIFIER_STATE,
-                SecureSettingsProto.PackageVerifier.STATE);
         p.end(packageVerifierToken);
 
         final long parentalControlToken = p.start(SecureSettingsProto.PARENTAL_CONTROL);
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 720266a..16c96e6 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -4385,8 +4385,7 @@
 
                 if (currentVersion == 182) {
                     // Remove secure bubble settings.
-                    getSecureSettingsLocked(userId).deleteSettingLocked(
-                            Secure.NOTIFICATION_BUBBLES);
+                    getSecureSettingsLocked(userId).deleteSettingLocked("notification_bubbles");
 
                     // Add global bubble settings.
                     getGlobalSettingsLocked().insertSettingLocked(Global.NOTIFICATION_BUBBLES,
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
index c05c4cd..de6a3a8 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
@@ -24,7 +24,6 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
-import android.content.pm.PackageManagerInternal;
 import android.content.pm.Signature;
 import android.os.Binder;
 import android.os.Build;
@@ -49,7 +48,6 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.ArrayUtils;
-import com.android.server.LocalServices;
 
 import libcore.io.IoUtils;
 
@@ -1175,9 +1173,8 @@
                 }
 
                 // If SetupWizard, done.
-                PackageManagerInternal packageManagerInternal = LocalServices.getService(
-                        PackageManagerInternal.class);
-                if (packageName.equals(packageManagerInternal.getSetupWizardPackageName())) {
+                String setupWizPackage = context.getPackageManager().getSetupWizardPackageName();
+                if (packageName.equals(setupWizPackage)) {
                     sSystemUids.put(uid, uid);
                     return true;
                 }
diff --git a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
index 6ea3db3..ebb9e86 100644
--- a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
+++ b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java
@@ -17,8 +17,7 @@
 package android.provider;
 
 import static com.google.android.collect.Sets.newHashSet;
-
-import static junit.framework.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import static java.lang.reflect.Modifier.isFinal;
 import static java.lang.reflect.Modifier.isPublic;
@@ -655,7 +654,6 @@
                  Settings.Secure.NIGHT_DISPLAY_LAST_ACTIVATED_TIME,
                  Settings.Secure.NUM_ROTATION_SUGGESTIONS_ACCEPTED,
                  Settings.Secure.ODI_CAPTIONS_ENABLED,
-                 Settings.Secure.PACKAGE_VERIFIER_STATE,
                  Settings.Secure.PACKAGE_VERIFIER_USER_CONSENT,
                  Settings.Secure.PARENTAL_CONTROL_LAST_UPDATE,
                  Settings.Secure.PAYMENT_SERVICE_SEARCH_URI,
@@ -721,7 +719,13 @@
                  Settings.Secure.BIOMETRIC_DEBUG_ENABLED,
                  Settings.Secure.FACE_UNLOCK_ATTENTION_REQUIRED,
                  Settings.Secure.FACE_UNLOCK_DIVERSITY_REQUIRED,
-                 Settings.Secure.MANAGED_PROVISIONING_DPC_DOWNLOADED);
+                 Settings.Secure.MANAGED_PROVISIONING_DPC_DOWNLOADED,
+                 Settings.Secure.AWARE_ENABLED,
+                 Settings.Secure.SKIP_GESTURE,
+                 Settings.Secure.SILENCE_GESTURE,
+                 Settings.Secure.DOZE_WAKE_LOCK_SCREEN_GESTURE,
+                 Settings.Secure.DOZE_WAKE_DISPLAY_GESTURE,
+                 Settings.Secure.FACE_UNLOCK_RE_ENROLL);
 
     @Test
     public void systemSettingsBackedUpOrBlacklisted() {
@@ -754,12 +758,11 @@
             Set<String> settings, Set<String> settingsToBackup, Set<String> blacklist) {
         Set<String> settingsNotBackedUp = difference(settings, settingsToBackup);
         Set<String> settingsNotBackedUpOrBlacklisted = difference(settingsNotBackedUp, blacklist);
-        assertTrue(
-                "Settings not backed up or blacklisted",
-                settingsNotBackedUpOrBlacklisted.isEmpty());
+        assertWithMessage("Settings not backed up or blacklisted")
+                .that(settingsNotBackedUpOrBlacklisted).isEmpty();
 
-        assertTrue(
-                "blacklisted settings backed up", intersect(settingsToBackup, blacklist).isEmpty());
+        assertWithMessage("blacklisted settings backed up")
+                .that(intersect(settingsToBackup, blacklist)).isEmpty();
     }
 
     private static Set<String> getCandidateSettings(
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index b2ff4b3..e11c063 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -29,6 +29,7 @@
     <uses-permission android:name="android.permission.CALL_PHONE" />
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.READ_PRECISE_PHONE_STATE" />
+    <uses-permission android:name="android.permission.READ_ACTIVE_EMERGENCY_SESSION" />
     <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
     <uses-permission android:name="android.permission.READ_CONTACTS" />
     <uses-permission android:name="android.permission.WRITE_CONTACTS" />
@@ -172,6 +173,8 @@
     <!-- Permissions needed to test system only camera devices -->
     <uses-permission android:name="android.permission.CAMERA" />
     <uses-permission android:name="android.permission.SYSTEM_CAMERA" />
+    <!-- Permissions needed for CTS camera test: RecordingTest.java when assuming shell id -->
+    <uses-permission android:name="android.permission.RECORD_AUDIO" />
     <!-- Permission needed to enable/disable Bluetooth/Wifi -->
     <uses-permission android:name="android.permission.MANAGE_BLUETOOTH_WHEN_WIRELESS_CONSENT_REQUIRED" />
     <uses-permission android:name="android.permission.MANAGE_WIFI_WHEN_WIRELESS_CONSENT_REQUIRED" />
@@ -238,7 +241,7 @@
 
         <activity
             android:name=".BugreportWarningActivity"
-            android:theme="@android:style/Theme.DeviceDefault.Dialog.Alert"
+            android:theme="@*android:style/Theme.DeviceDefault.Dialog.Alert.DayNight"
             android:finishOnCloseSystemDialogs="true"
             android:excludeFromRecents="true"
             android:exported="false" />
diff --git a/packages/Shell/src/com/android/shell/BugreportProgressService.java b/packages/Shell/src/com/android/shell/BugreportProgressService.java
index 602fe3e..a097249 100644
--- a/packages/Shell/src/com/android/shell/BugreportProgressService.java
+++ b/packages/Shell/src/com/android/shell/BugreportProgressService.java
@@ -37,6 +37,7 @@
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
+import android.app.admin.DevicePolicyManager;
 import android.content.ClipData;
 import android.content.Context;
 import android.content.DialogInterface;
@@ -107,6 +108,8 @@
 import java.io.InputStream;
 import java.io.PrintWriter;
 import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
 import java.text.NumberFormat;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
@@ -157,6 +160,8 @@
     private static final String TAG = "BugreportProgressService";
     private static final boolean DEBUG = false;
 
+    private Intent startSelfIntent;
+
     private static final String AUTHORITY = "com.android.shell";
 
     // External intents sent by dumpstate.
@@ -235,6 +240,24 @@
 
     private static final String NOTIFICATION_CHANNEL_ID = "bugreports";
 
+    /**
+     * Always keep the newest 8 bugreport files.
+     */
+    private static final int MIN_KEEP_COUNT = 8;
+
+    /**
+     * Always keep bugreports taken in the last week.
+     */
+    private static final long MIN_KEEP_AGE = DateUtils.WEEK_IN_MILLIS;
+
+    private static final String BUGREPORT_MIMETYPE = "application/vnd.android.bugreport";
+
+    /** Always keep just the last 3 remote bugreport's files around. */
+    private static final int REMOTE_BUGREPORT_FILES_AMOUNT = 3;
+
+    /** Always keep remote bugreport files created in the last day. */
+    private static final long REMOTE_MIN_KEEP_AGE = DateUtils.DAY_IN_MILLIS;
+
     private final Object mLock = new Object();
 
     /** Managed bugreport info (keyed by id) */
@@ -281,6 +304,7 @@
         mMainThreadHandler = new Handler(Looper.getMainLooper());
         mServiceHandler = new ServiceHandler("BugreportProgressServiceMainThread");
         mScreenshotHandler = new ScreenshotHandler("BugreportProgressServiceScreenshotThread");
+        startSelfIntent = new Intent(this, this.getClass());
 
         mScreenshotsDir = new File(getFilesDir(), SCREENSHOT_DIR);
         if (!mScreenshotsDir.exists()) {
@@ -307,6 +331,9 @@
     public int onStartCommand(Intent intent, int flags, int startId) {
         Log.v(TAG, "onStartCommand(): " + dumpIntent(intent));
         if (intent != null) {
+            if (!intent.hasExtra(EXTRA_ORIGINAL_INTENT) && !intent.hasExtra(EXTRA_ID)) {
+                return START_NOT_STICKY;
+            }
             // Handle it in a separate thread.
             final Message msg = mServiceHandler.obtainMessage();
             msg.what = MSG_SERVICE_COMMAND;
@@ -348,22 +375,27 @@
         }
     }
 
+    private static String getFileName(BugreportInfo info, String suffix) {
+        return String.format("%s-%s%s", info.baseName, info.name, suffix);
+    }
+
     private final class BugreportCallbackImpl extends BugreportCallback {
 
+        @GuardedBy("mLock")
         private final BugreportInfo mInfo;
 
-        BugreportCallbackImpl(String name, @Nullable String title, @Nullable String description) {
-            // pid not used in this workflow, so setting default = 0
-            mInfo = new BugreportInfo(mContext, 0 /* pid */, name,
-                    100 /* max progress*/, title, description);
+        BugreportCallbackImpl(BugreportInfo info) {
+            mInfo = info;
         }
 
         @Override
         public void onProgress(float progress) {
-            if (progress == 0) {
-                trackInfoWithId();
+            synchronized (mLock) {
+                if (progress == 0) {
+                    trackInfoWithIdLocked();
+                }
+                checkProgressUpdatedLocked(mInfo, (int) progress);
             }
-            checkProgressUpdated(mInfo, (int) progress);
         }
 
         /**
@@ -372,18 +404,21 @@
          */
         @Override
         public void onError(@BugreportErrorCode int errorCode) {
-            trackInfoWithId();
-            stopProgress(mInfo.id);
+            synchronized (mLock) {
+                trackInfoWithIdLocked();
+                stopProgressLocked(mInfo.id);
+            }
             Log.e(TAG, "Bugreport API callback onError() errorCode = " + errorCode);
             return;
         }
 
         @Override
         public void onFinished() {
-            trackInfoWithId();
-            // Stop running on foreground, otherwise share notification cannot be dismissed.
-            onBugreportFinished(mInfo.id);
-            stopSelfWhenDone();
+            mInfo.renameBugreportFile();
+            mInfo.renameScreenshots(mScreenshotsDir);
+            synchronized (mLock) {
+                sendBugreportFinishedBroadcastLocked();
+            }
         }
 
         /**
@@ -392,7 +427,8 @@
          * when dumpstate calls one of the callback functions (onProgress, onFinished, onError)
          * after the id has been incremented.
          */
-        private void trackInfoWithId() {
+        @GuardedBy("mLock")
+        private void trackInfoWithIdLocked() {
             final int id = SystemProperties.getInt(PROPERTY_LAST_ID, 1);
             if (mBugreportInfos.get(id) == null) {
                 mInfo.id = id;
@@ -400,6 +436,90 @@
             }
             return;
         }
+
+        @GuardedBy("mLock")
+        private void sendBugreportFinishedBroadcastLocked() {
+            final String bugreportFilePath = mInfo.bugreportFile.getAbsolutePath();
+            if (mInfo.bugreportFile.length() == 0) {
+                Log.e(TAG, "Bugreport file empty. File path = " + bugreportFilePath);
+                return;
+            }
+            if (mInfo.type == BugreportParams.BUGREPORT_MODE_REMOTE) {
+                sendRemoteBugreportFinishedBroadcast(mContext, bugreportFilePath,
+                        mInfo.bugreportFile);
+            } else {
+                trackInfoWithIdLocked();
+                cleanupOldFiles(MIN_KEEP_COUNT, MIN_KEEP_AGE);
+                final Intent intent = new Intent(INTENT_BUGREPORT_FINISHED);
+                intent.putExtra(EXTRA_BUGREPORT, bugreportFilePath);
+                addScreenshotToIntent(intent, mInfo);
+                mContext.sendBroadcast(intent, android.Manifest.permission.DUMP);
+                onBugreportFinished(mInfo.id);
+            }
+        }
+    }
+
+    private static void sendRemoteBugreportFinishedBroadcast(Context context,
+            String bugreportFileName, File bugreportFile) {
+        cleanupOldFiles(REMOTE_BUGREPORT_FILES_AMOUNT, REMOTE_MIN_KEEP_AGE);
+        final Intent intent = new Intent(DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH);
+        final Uri bugreportUri = getUri(context, bugreportFile);
+        final String bugreportHash = generateFileHash(bugreportFileName);
+        if (bugreportHash == null) {
+            Log.e(TAG, "Error generating file hash for remote bugreport");
+        }
+        intent.setDataAndType(bugreportUri, BUGREPORT_MIMETYPE);
+        intent.putExtra(DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH, bugreportHash);
+        intent.putExtra(EXTRA_BUGREPORT, bugreportFileName);
+        context.sendBroadcastAsUser(intent, UserHandle.SYSTEM,
+                android.Manifest.permission.DUMP);
+    }
+
+    private static void addScreenshotToIntent(Intent intent, BugreportInfo info) {
+        final String screenshotFileName = info.name + ".png";
+        final File screenshotFile = new File(BUGREPORT_DIR, screenshotFileName);
+        final String screenshotFilePath = screenshotFile.getAbsolutePath();
+        if (screenshotFile.length() > 0) {
+            intent.putExtra(EXTRA_SCREENSHOT, screenshotFilePath);
+        }
+        return;
+    }
+
+    private static String generateFileHash(String fileName) {
+        String fileHash = null;
+        try {
+            MessageDigest md = MessageDigest.getInstance("SHA-256");
+            FileInputStream input = new FileInputStream(new File(fileName));
+            byte[] buffer = new byte[65536];
+            int size;
+            while ((size = input.read(buffer)) > 0) {
+                md.update(buffer, 0, size);
+            }
+            input.close();
+            byte[] hashBytes = md.digest();
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < hashBytes.length; i++) {
+                sb.append(String.format("%02x", hashBytes[i]));
+            }
+            fileHash = sb.toString();
+        } catch (IOException | NoSuchAlgorithmException e) {
+            Log.e(TAG, "generating file hash for bugreport file failed " + fileName, e);
+        }
+        return fileHash;
+    }
+
+    static void cleanupOldFiles(final int minCount, final long minAge) {
+        new AsyncTask<Void, Void, Void>() {
+            @Override
+            protected Void doInBackground(Void... params) {
+                try {
+                    FileUtils.deleteOlderFiles(new File(BUGREPORT_DIR), minCount, minAge);
+                } catch (RuntimeException e) {
+                    Log.e(TAG, "RuntimeException deleting old files", e);
+                }
+                return null;
+            }
+        }.execute();
     }
 
     /**
@@ -559,34 +679,44 @@
         }
     }
 
-    private String getBugreportName() {
+    private String getBugreportBaseName(@BugreportParams.BugreportMode int type) {
         String buildId = SystemProperties.get("ro.build.id", "UNKNOWN_BUILD");
         String deviceName = SystemProperties.get("ro.product.name", "UNKNOWN_DEVICE");
-        String currentTimestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
-        return String.format("bugreport-%s-%s-%s", deviceName, buildId, currentTimestamp);
+        String typeSuffix = null;
+        if (type == BugreportParams.BUGREPORT_MODE_WIFI) {
+            typeSuffix = "wifi";
+        } else if (type == BugreportParams.BUGREPORT_MODE_TELEPHONY) {
+            typeSuffix = "telephony";
+        } else {
+            return String.format("bugreport-%s-%s", deviceName, buildId);
+        }
+        return String.format("bugreport-%s-%s-%s", deviceName, buildId, typeSuffix);
     }
 
     private void startBugreportAPI(Intent intent) {
         mUsingBugreportApi = true;
-        String bugreportName = getBugreportName();
+        String shareTitle = intent.getStringExtra(EXTRA_TITLE);
+        String shareDescription = intent.getStringExtra(EXTRA_DESCRIPTION);
+        int bugreportType = intent.getIntExtra(EXTRA_BUGREPORT_TYPE,
+                BugreportParams.BUGREPORT_MODE_INTERACTIVE);
+        String baseName = getBugreportBaseName(bugreportType);
+        String name = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
 
-        ParcelFileDescriptor bugreportFd = createReadWriteFile(BUGREPORT_DIR,
-                bugreportName + ".zip");
+        // pid not used in this workflow, so setting default = 0
+        BugreportInfo info = new BugreportInfo(mContext, 0 /* pid */, baseName, name,
+                100 /* max progress*/, shareTitle, shareDescription, bugreportType,
+                mUsingBugreportApi);
+
+        ParcelFileDescriptor bugreportFd = info.createBugreportFd();
         if (bugreportFd == null) {
             Log.e(TAG, "Bugreport parcel file descriptor is null.");
             return;
         }
-        int bugreportType = intent.getIntExtra(EXTRA_BUGREPORT_TYPE,
-                BugreportParams.BUGREPORT_MODE_INTERACTIVE);
-        String shareTitle = intent.getStringExtra(EXTRA_TITLE);
-        String shareDescription = intent.getStringExtra(EXTRA_DESCRIPTION);
-
-        ParcelFileDescriptor screenshotFd = createReadWriteFile(BUGREPORT_DIR,
-                bugreportName + ".png");
+        ParcelFileDescriptor screenshotFd = info.createScreenshotFd();
         if (screenshotFd == null) {
             Log.e(TAG, "Screenshot parcel file descriptor is null. Deleting bugreport file");
             FileUtils.closeQuietly(bugreportFd);
-            new File(BUGREPORT_DIR, String.format("%s.zip", bugreportName)).delete();
+            info.bugreportFile.delete();
             return;
         }
         mBugreportManager = (BugreportManager) mContext.getSystemService(
@@ -597,8 +727,7 @@
                 + " bugreport file fd: " + bugreportFd
                 + " screenshot file fd: " + screenshotFd);
 
-        BugreportCallbackImpl bugreportCallback = new BugreportCallbackImpl(bugreportName,
-                shareTitle, shareDescription);
+        BugreportCallbackImpl bugreportCallback = new BugreportCallbackImpl(info);
         try {
             mBugreportManager.startBugreport(bugreportFd, screenshotFd,
                     new BugreportParams(bugreportType), executor, bugreportCallback);
@@ -611,14 +740,13 @@
         }
     }
 
-    private ParcelFileDescriptor createReadWriteFile(String dirName, String fileName) {
+    private static ParcelFileDescriptor createReadWriteFile(File file) {
         try {
-            File f = new File(dirName, fileName);
-            f.createNewFile();
-            f.setReadable(true, true);
-            f.setWritable(true, true);
+            file.createNewFile();
+            file.setReadable(true, true);
+            file.setWritable(true, true);
 
-            ParcelFileDescriptor fd = ParcelFileDescriptor.open(f,
+            ParcelFileDescriptor fd = ParcelFileDescriptor.open(file,
                     ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_APPEND);
             return fd;
         } catch (IOException e) {
@@ -711,6 +839,9 @@
         } else {
             mForegroundId = id;
             Log.d(TAG, "Start running as foreground service on id " + mForegroundId);
+            // Explicitly starting the service so that stopForeground() does not crash
+            // Workaround for b/140997620
+            startForegroundService(startSelfIntent);
             startForeground(mForegroundId, notification);
         }
     }
@@ -729,7 +860,8 @@
     /**
      * Finalizes the progress on a given bugreport and cancel its notification.
      */
-    private void stopProgress(int id) {
+    @GuardedBy("mLock")
+    private void stopProgressLocked(int id) {
         if (mBugreportInfos.indexOfKey(id) < 0) {
             Log.w(TAG, "ID not watched: " + id);
         } else {
@@ -760,7 +892,9 @@
             }
             deleteScreenshots(info);
         }
-        stopProgress(id);
+        synchronized (mLock) {
+            stopProgressLocked(id);
+        }
     }
 
     /**
@@ -974,15 +1108,19 @@
      */
     private void onBugreportFinished(int id) {
         BugreportInfo info = getInfo(id);
-        final File bugreportFile = new File(BUGREPORT_DIR, info.name + ".zip");
+        final File bugreportFile = info.bugreportFile;
         final int max = -1; // this is to log metrics for dumpstate duration.
-        File screenshotFile = new File(BUGREPORT_DIR, info.name + ".png");
+        File screenshotFile = info.screenshotFiles.isEmpty()
+                ? null : info.screenshotFiles.get(0);
         // If the screenshot file did not get populated implies this type of bugreport does not
         // need the screenshot file; setting the file to null so that empty file doesnt get shared
-        if (screenshotFile.length() == 0) {
+        if (screenshotFile != null && screenshotFile.length() == 0) {
             if (screenshotFile.delete()) {
                 Log.d(TAG, "screenshot file deleted successfully.");
             }
+            info.screenshotFiles.remove(0);
+            // TODO(b/136066578): Will soon stop using the below variable as it is a no-op in
+            // API flow and the screenshotFile value is read from info.screenshotFiles
             screenshotFile = null;
         }
         // TODO: Since we are passing id to the function, it should be able to find the info linked
@@ -1006,10 +1144,18 @@
             DumpstateListener dumpstateListener = new DumpstateListener(info);
             mBugreportInfos.put(id, info);
         }
-        info.renameScreenshots(mScreenshotsDir);
-        info.bugreportFile = bugreportFile;
-        if (screenshotFile != null) {
-            info.addScreenshot(screenshotFile);
+        if (!mUsingBugreportApi) {
+            // Rename in API flow happens before sending the broadcast for remote bugreport (to
+            // handle renaming before sending broadcasts)
+            info.renameScreenshots(mScreenshotsDir);
+            // API workflow already has the bugreport file. This was required in legacy flow, when
+            // FINISHED broadcast would send the final bugreport files.
+            // TODO(b/136066578): Change function definition to not include bugreport/screenshot
+            // file in params
+            info.bugreportFile = bugreportFile;
+            if (screenshotFile != null) {
+                info.addScreenshot(screenshotFile);
+            }
         }
 
         if (max != -1) {
@@ -1043,7 +1189,9 @@
         if (!info.bugreportFile.exists() || !info.bugreportFile.canRead()) {
             Log.e(TAG, "Could not read bugreport file " + info.bugreportFile);
             Toast.makeText(context, R.string.bugreport_unreadable_text, Toast.LENGTH_LONG).show();
-            stopProgress(info.id);
+            synchronized (mLock) {
+                stopProgressLocked(info.id);
+            }
             return;
         }
 
@@ -1155,7 +1303,9 @@
         final Intent sendIntent = buildSendIntent(mContext, info);
         if (sendIntent == null) {
             Log.w(TAG, "Stopping progres on ID " + id + " because share intent could not be built");
-            stopProgress(id);
+            synchronized (mLock) {
+                stopProgressLocked(id);
+            }
             return;
         }
 
@@ -1178,9 +1328,10 @@
         } else {
             mContext.startActivity(notifIntent);
         }
-
-        // ... and stop watching this process.
-        stopProgress(id);
+        synchronized (mLock) {
+            // ... and stop watching this process.
+            stopProgressLocked(id);
+        }
     }
 
     static void sendShareIntent(Context context, Intent intent) {
@@ -1670,7 +1821,7 @@
                         if (hasFocus) {
                             return;
                         }
-                        sanitizeName();
+                        sanitizeName(info);
                     }
                 });
 
@@ -1689,9 +1840,13 @@
                                         MetricsLogger.action(context,
                                                 MetricsEvent.ACTION_BUGREPORT_DETAILS_CANCELED);
                                         if (!mTempName.equals(mSavedName)) {
-                                            // Must restore dumpstate's name since it was changed
+                                            // Must restore bugreport's name since it was changed
                                             // before user clicked OK.
-                                            setBugreportNameProperty(mPid, mSavedName);
+                                            if (mUsingBugreportApi) {
+                                                info.name = mSavedName;
+                                            } else {
+                                                setBugreportNameProperty(mPid, mSavedName);
+                                            }
                                         }
                                     }
                                 })
@@ -1740,7 +1895,7 @@
                     @Override
                     public void onClick(View view) {
                         MetricsLogger.action(context, MetricsEvent.ACTION_BUGREPORT_DETAILS_SAVED);
-                        sanitizeName();
+                        sanitizeName(info);
                         final String name = mInfoName.getText().toString();
                         final String title = mInfoTitle.getText().toString();
                         final String description = mInfoDescription.getText().toString();
@@ -1756,7 +1911,7 @@
          * Sanitizes the user-provided value for the {@code name} field, automatically replacing
          * invalid characters if necessary.
          */
-        private void sanitizeName() {
+        private void sanitizeName(BugreportInfo info) {
             String name = mInfoName.getText().toString();
             if (name.equals(mTempName)) {
                 if (DEBUG) Log.v(TAG, "name didn't change, no need to sanitize: " + name);
@@ -1778,23 +1933,15 @@
                 name = safeName.toString();
                 mInfoName.setText(name);
             }
-            if (mUsingBugreportApi) {
-                File prevFile = new File(BUGREPORT_DIR, mTempName + ".zip");
-                File newFile = new File(BUGREPORT_DIR, name + ".zip");
-                if (!prevFile.renameTo(newFile)) {
-                    Log.e(TAG, "File rename from : " + mTempName
-                            + " to : " + name + " from the UI failed.");
-                } else {
-                    Log.d(TAG, "File rename from : " + mTempName
-                            + " to : " + name + " from the UI succeeded.");
-                }
-            }
             mTempName = name;
-
-            // Must update system property for the cases where dumpstate finishes
-            // while the user is still entering other fields (like title or
-            // description)
-            setBugreportNameProperty(mPid, name);
+            if (mUsingBugreportApi) {
+                info.name = name;
+            } else {
+                // Must update system property for the cases where dumpstate finishes
+                // while the user is still entering other fields (like title or
+                // description)
+                setBugreportNameProperty(mPid, name);
+            }
         }
 
        /**
@@ -1830,14 +1977,23 @@
 
         /**
          * {@code pid} of the {@code dumpstate} process generating the bugreport.
+         * pid is unused in the API flow
+         * TODO(b/136066578): Remove pid
          */
         final int pid;
 
         /**
-         * Name of the bugreport, will be used to rename the final files.
-         * <p>
-         * Initial value is the bugreport filename reported by {@code dumpstate}, but user can
-         * change it later to a more meaningful name.
+         * Prefix name of the bugreport, this is uneditable.
+         * The baseName consists of the string "bugreport" + deviceName + buildID
+         * This will end with the string "wifi"/"telephony" for wifi/telephony bugreports.
+         * Bugreport zip file name  = "<baseName>-<name>.zip"
+         * Bugreport png file name = "<baseName>-<name>.png"
+         */
+        String baseName;
+
+        /**
+         * Suffix name of the bugreport/screenshot, is set to timestamp initially. User can make
+         * modifications to this using interface.
          */
         String name;
 
@@ -1907,6 +2063,12 @@
         boolean finished;
 
         /**
+         * Whether this bugreport is using API workflow.
+         * TODO(b/136066578): Remove when legacy bugreport methods are removed
+         */
+        boolean usingApi;
+
+        /**
          * Whether the details entries have been added to the bugreport yet.
          */
         boolean addingDetailsToZip;
@@ -1925,24 +2087,38 @@
         String shareDescription;
 
         /**
+         * Type of the bugreport
+         */
+        int type;
+
+        /**
          * Constructor for tracked bugreports - typically called upon receiving BUGREPORT_STARTED.
          */
         BugreportInfo(Context context, int id, int pid, String name, int max) {
-            this(context, pid, name, max, null, null);
+            // bugreports triggered by STARTED broadcast do not use callback functions,
+            // onFinished() callback method is the only function where type is used.
+            // Set type to -1 as it is unused in this workflow.
+            // This constructor will soon be removed.
+            this(context, pid, "" /* dumpstate handles basename */, name, max, null, null, -1,
+                    false);
             this.id = id;
         }
 
         /**
          * Constructor for tracked bugreports - typically called upon receiving BUGREPORT_REQUESTED.
          */
-        BugreportInfo(Context context, int pid, String name, int max, @Nullable String shareTitle,
-                @Nullable String shareDescription) {
+        BugreportInfo(Context context, int pid, String baseName, String name, int max,
+                @Nullable String shareTitle, @Nullable String shareDescription,
+                @BugreportParams.BugreportMode int type, boolean usingApi) {
             this.context = context;
             this.pid = pid;
             this.name = name;
             this.max = this.realMax = max;
             this.shareTitle = shareTitle == null ? "" : shareTitle;
             this.shareDescription = shareDescription == null ? "" : shareDescription;
+            this.type = type;
+            this.baseName = baseName;
+            this.usingApi = usingApi;
         }
 
         /**
@@ -1954,6 +2130,17 @@
             this.finished = true;
         }
 
+        ParcelFileDescriptor createBugreportFd() {
+            bugreportFile = new File(BUGREPORT_DIR, getFileName(this, ".zip"));
+            return createReadWriteFile(bugreportFile);
+        }
+
+        ParcelFileDescriptor createScreenshotFd() {
+            File screenshotFile = new File(BUGREPORT_DIR, getFileName(this, ".png"));
+            addScreenshot(screenshotFile);
+            return createReadWriteFile(screenshotFile);
+        }
+
         /**
          * Gets the name for next screenshot file.
          */
@@ -1979,7 +2166,12 @@
             final List<File> renamedFiles = new ArrayList<>(screenshotFiles.size());
             for (File oldFile : screenshotFiles) {
                 final String oldName = oldFile.getName();
-                final String newName = oldName.replaceFirst(Integer.toString(pid), name);
+                final String newName;
+                if (usingApi) {
+                    newName = getFileName(this, ".png");
+                } else {
+                    newName = oldName.replaceFirst(Integer.toString(pid), name);
+                }
                 final File newFile;
                 if (!newName.equals(oldName)) {
                     final File renamedFile = new File(screenshotDir, newName);
@@ -1994,6 +2186,18 @@
             screenshotFiles = renamedFiles;
         }
 
+        /**
+         * Rename bugreport file to include the name given by user via UI
+         */
+        void renameBugreportFile() {
+            File newBugreportFile = new File(BUGREPORT_DIR, getFileName(this, ".zip"));
+            if (!newBugreportFile.getPath().equals(bugreportFile.getPath())) {
+                if (bugreportFile.renameTo(newBugreportFile)) {
+                    bugreportFile = newBugreportFile;
+                }
+            }
+        }
+
         String getFormattedLastUpdate() {
             if (context == null) {
                 // Restored from Parcel
@@ -2012,8 +2216,10 @@
             final StringBuilder builder = new StringBuilder()
                     .append("\tid: ").append(id)
                     .append(", pid: ").append(pid)
+                    .append(", baseName: ").append(baseName)
                     .append(", name: ").append(name)
                     .append(", finished: ").append(finished)
+                    .append(", usingApi: ").append(usingApi)
                     .append("\n\ttitle: ").append(title)
                     .append("\n\tdescription: ");
             if (description == null) {
@@ -2045,6 +2251,7 @@
             context = null;
             id = in.readInt();
             pid = in.readInt();
+            baseName = in.readString();
             name = in.readString();
             title = in.readString();
             description = in.readString();
@@ -2062,6 +2269,7 @@
             }
 
             finished = in.readInt() == 1;
+            usingApi = in.readInt() == 1;
             screenshotCounter = in.readInt();
             shareDescription = in.readString();
             shareTitle = in.readString();
@@ -2071,6 +2279,7 @@
         public void writeToParcel(Parcel dest, int flags) {
             dest.writeInt(id);
             dest.writeInt(pid);
+            dest.writeString(baseName);
             dest.writeString(name);
             dest.writeString(title);
             dest.writeString(description);
@@ -2088,6 +2297,7 @@
             }
 
             dest.writeInt(finished ? 1 : 0);
+            dest.writeInt(usingApi ? 1 : 0);
             dest.writeInt(screenshotCounter);
             dest.writeString(shareDescription);
             dest.writeString(shareTitle);
@@ -2167,14 +2377,18 @@
                 // The right, long-term solution is to provide an onFinished() callback
                 // on IDumpstateListener and call it instead of using a broadcast.
                 Log.w(TAG, "Dumpstate process died:\n" + info);
-                stopProgress(info.id);
+                synchronized (mLock) {
+                    stopProgressLocked(info.id);
+                }
             }
             token.asBinder().unlinkToDeath(this, 0);
         }
 
         @Override
         public void onProgress(int progress) throws RemoteException {
-            checkProgressUpdated(info, progress);
+            synchronized (mLock) {
+                checkProgressUpdatedLocked(info, progress);
+            }
         }
 
         @Override
@@ -2193,7 +2407,8 @@
 
     }
 
-    private void checkProgressUpdated(BugreportInfo info, int progress) {
+    @GuardedBy("mLock")
+    private void checkProgressUpdatedLocked(BugreportInfo info, int progress) {
         if (progress > CAPPED_PROGRESS) {
             progress = CAPPED_PROGRESS;
         }
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index 37fefc2..0c582c4 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -170,39 +170,3 @@
     required: ["privapp_whitelist_com.android.systemui"],
 
 }
-
-// Only used for products that are shipping legacy Recents
-android_app {
-    name: "SystemUIWithLegacyRecents",
-    overrides: [
-        "SystemUI",
-    ],
-
-    platform_apis: true,
-    certificate: "platform",
-    privileged: true,
-
-    dxflags: ["--multi-dex"],
-    optimize: {
-        proguard_flags_files: ["proguard.flags", "legacy/recents/proguard.flags"],
-    },
-
-    static_libs: [
-        "SystemUI-core",
-    ],
-    libs: [
-        "telephony-common",
-    ],
-
-    kotlincflags: ["-Xjvm-default=enable"],
-
-    srcs: [
-        "legacy/recents/src/**/*.java",
-        "legacy/recents/src/**/I*.aidl",
-    ],
-    resource_dirs: [
-        "legacy/recents/res",
-    ],
-
-    manifest: "legacy/recents/AndroidManifest.xml",
-}
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 403e894..b288eb7 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -243,6 +243,9 @@
     <!-- Permission to change the display color -->
     <uses-permission android:name="android.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS" />
 
+    <!-- Query all packages on device on R+ -->
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
+
     <protected-broadcast android:name="com.android.settingslib.action.REGISTER_SLICE_RECEIVER" />
     <protected-broadcast android:name="com.android.settingslib.action.UNREGISTER_SLICE_RECEIVER" />
     <protected-broadcast android:name="com.android.settings.flashlight.action.FLASHLIGHT_CHANGED" />
diff --git a/packages/SystemUI/README.md b/packages/SystemUI/README.md
index a8ce196..a3d420e 100644
--- a/packages/SystemUI/README.md
+++ b/packages/SystemUI/README.md
@@ -104,12 +104,6 @@
 Shows the drag handle for the divider between two apps when in split screen
 mode.
 
-### [com.android.systemui.SystemBars](/packages/SystemUI/src/com/android/systemui/SystemBars.java)
-
-This is a proxy to the actual SystemUI for the status bar. This loads from
-config_statusBarComponent which defaults to StatusBar. (maybe this should be
-removed and copy how config_systemUiVendorServiceComponent works)
-
 ### [com.android.systemui.status.phone.StatusBar](/packages/SystemUI/src/com/android/systemui/status/phone/StatusBar.java)
 
 This shows the UI for the status bar and the notification shade it contains.
diff --git a/packages/SystemUI/legacy/recents/AndroidManifest.xml b/packages/SystemUI/legacy/recents/AndroidManifest.xml
deleted file mode 100644
index 0d8b3cd..0000000
--- a/packages/SystemUI/legacy/recents/AndroidManifest.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
- * Copyright (c) 2018 Google Inc.
- *
- * 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.
- */
--->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
-          xmlns:tools="http://schemas.android.com/tools"
-          package="com.android.systemui"
-          android:sharedUserId="android.uid.systemui"
-          coreApp="true">
-
-    <application
-        android:name="com.android.systemui.SystemUIApplication">
-
-        <!-- Service used by secondary users to register themselves with the system user. -->
-        <service android:name=".recents.RecentsSystemUserService"
-            android:exported="false"
-            android:permission="com.android.systemui.permission.SELF" />
-
-        <!-- Alternate Recents -->
-        <activity android:name=".recents.RecentsActivity"
-                  android:label="@string/accessibility_desc_recent_apps"
-                  android:exported="false"
-                  android:launchMode="singleInstance"
-                  android:excludeFromRecents="true"
-                  android:stateNotNeeded="true"
-                  android:resumeWhilePausing="true"
-                  android:resizeableActivity="true"
-                  android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden"
-                  android:theme="@style/RecentsTheme.Wallpaper">
-            <intent-filter>
-                <action android:name="com.android.systemui.recents.TOGGLE_RECENTS" />
-            </intent-filter>
-        </activity>
-
-    </application>
-</manifest>
diff --git a/packages/SystemUI/legacy/recents/proguard.flags b/packages/SystemUI/legacy/recents/proguard.flags
deleted file mode 100644
index c358949..0000000
--- a/packages/SystemUI/legacy/recents/proguard.flags
+++ /dev/null
@@ -1,14 +0,0 @@
--keepclassmembers class ** {
-    public void onBusEvent(**);
-    public void onInterprocessBusEvent(**);
-}
--keepclassmembers class ** extends **.EventBus$InterprocessEvent {
-    public <init>(android.os.Bundle);
-}
-
--keep class com.android.systemui.recents.views.TaskView {
-    public int getDim();
-    public void setDim(int);
-    public float getTaskProgress();
-    public void setTaskProgress(float);
-}
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_fast_toggle_app_home_exit.xml b/packages/SystemUI/legacy/recents/res/anim/recents_fast_toggle_app_home_exit.xml
deleted file mode 100644
index 69edcc7..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_fast_toggle_app_home_exit.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-<!-- Recents Activity -->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false"
-     android:zAdjustment="top">
-  <alpha android:fromAlpha="1.0" android:toAlpha="1.0"
-         android:fillEnabled="true"
-         android:fillBefore="true" android:fillAfter="true"
-         android:duration="250"/>
-</set>
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_from_launcher_enter.xml b/packages/SystemUI/legacy/recents/res/anim/recents_from_launcher_enter.xml
deleted file mode 100644
index 00b3dfd..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_from_launcher_enter.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false"
-     android:zAdjustment="normal">
-  <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
-         android:fillEnabled="true"
-         android:fillBefore="true" android:fillAfter="true"
-         android:interpolator="@android:interpolator/linear_out_slow_in"
-         android:duration="150"/>
-</set>
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_from_launcher_exit.xml b/packages/SystemUI/legacy/recents/res/anim/recents_from_launcher_exit.xml
deleted file mode 100644
index 33831b8..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_from_launcher_exit.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false"
-     android:zAdjustment="top">
-  <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
-         android:fillEnabled="true"
-         android:fillBefore="true" android:fillAfter="true"
-         android:interpolator="@interpolator/recents_from_launcher_exit_interpolator"
-         android:duration="133"/>
-</set>
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_from_unknown_enter.xml b/packages/SystemUI/legacy/recents/res/anim/recents_from_unknown_enter.xml
deleted file mode 100644
index da1dee0..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_from_unknown_enter.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false"
-     android:zAdjustment="top">
-  <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
-         android:fillEnabled="true"
-         android:fillBefore="true" android:fillAfter="true"
-         android:interpolator="@android:interpolator/linear"
-         android:duration="200"/>
-</set>
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_from_unknown_exit.xml b/packages/SystemUI/legacy/recents/res/anim/recents_from_unknown_exit.xml
deleted file mode 100644
index 31cf26a..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_from_unknown_exit.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false"
-     android:zAdjustment="normal">
-  <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
-         android:fillEnabled="true"
-         android:fillBefore="true" android:fillAfter="true"
-         android:interpolator="@android:interpolator/fast_out_slow_in"
-         android:duration="200"/>
-</set>
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_bounce.xml b/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_bounce.xml
deleted file mode 100644
index 74f2814..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_bounce.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:background="#ff000000" android:shareInterpolator="false" android:zAdjustment="normal">
-
-
-    <translate android:fromYDelta="0" android:toYDelta="2%"
-        android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-        android:interpolator="@android:interpolator/fast_out_slow_in"
-        android:duration="133"/>
-
-    <scale android:fromXScale="1.0" android:toXScale="0.98"
-        android:fromYScale="1.0" android:toYScale="0.98"
-        android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-        android:pivotX="50%p" android:pivotY="50%p"
-        android:interpolator="@android:interpolator/fast_out_slow_in"
-        android:duration="133" />
-
-    <translate android:fromYDelta="0" android:toYDelta="-2%"
-        android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-        android:interpolator="@interpolator/recents_launch_prev_affiliated_task_bounce_ydelta"
-        android:startOffset="133"
-        android:duration="217"/>
-
-    <scale android:fromXScale="1.0" android:toXScale="1.02040816326531"
-        android:fromYScale="1.0" android:toYScale="1.02040816326531"
-        android:fillEnabled="true" android:fillBefore="false" android:fillAfter="true"
-        android:pivotX="50%p" android:pivotY="50%p"
-        android:interpolator="@interpolator/recents_launch_next_affiliated_task_bounce_scale"
-        android:startOffset="133"
-        android:duration="217" />
-</set>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_source.xml b/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_source.xml
deleted file mode 100644
index f0fd684..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_source.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:background="#ff000000" android:shareInterpolator="false" android:zAdjustment="normal">
-
-    <alpha android:fromAlpha="1.0" android:toAlpha="0.6"
-        android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-        android:interpolator="@android:interpolator/accelerate_cubic"
-        android:duration="150"/>
-
-    <scale android:fromXScale="1.0" android:toXScale="0.9"
-        android:fromYScale="1.0" android:toYScale="0.9"
-        android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-        android:pivotX="50%p" android:pivotY="50%p"
-        android:interpolator="@android:interpolator/fast_out_slow_in"
-        android:duration="300" />
-</set>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_target.xml b/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_target.xml
deleted file mode 100644
index 170ac82..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_launch_next_affiliated_task_target.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:background="#ff000000" android:shareInterpolator="false" android:zAdjustment="top">
-
-    <translate android:fromYDelta="110%" android:toYDelta="0%"
-               android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-               android:interpolator="@android:interpolator/decelerate_quint"
-               android:startOffset="50"
-               android:duration="250" />
-</set>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_bounce.xml b/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_bounce.xml
deleted file mode 100644
index b19167d..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_bounce.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:background="#ff000000" android:shareInterpolator="false" android:zAdjustment="top">
-
-    <translate android:fromYDelta="0%" android:toYDelta="10%"
-               android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-               android:interpolator="@android:interpolator/fast_out_slow_in"
-               android:duration="133" />
-
-    <translate android:fromYDelta="0%" android:toYDelta="-10%"
-               android:fillEnabled="true" android:fillBefore="false" android:fillAfter="true"
-               android:interpolator="@interpolator/recents_launch_prev_affiliated_task_bounce_ydelta"
-               android:startOffset="133"
-               android:duration="217" />
-</set>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_source.xml b/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_source.xml
deleted file mode 100644
index ad5341b..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_source.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:background="#ff000000" android:shareInterpolator="false" android:zAdjustment="top">
-
-    <translate android:fromYDelta="0%" android:toYDelta="110%"
-               android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-               android:interpolator="@android:interpolator/accelerate_quint"
-               android:duration="300" />
-</set>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_target.xml b/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_target.xml
deleted file mode 100644
index 7687f02..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_launch_prev_affiliated_task_target.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:background="#ff000000" android:shareInterpolator="false" android:zAdjustment="normal">
-
-    <alpha android:fromAlpha="0.6" android:toAlpha="1.0"
-        android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-        android:interpolator="@android:interpolator/decelerate_cubic"
-        android:startOffset="75"
-        android:duration="150"/>
-
-    <scale android:fromXScale="0.9" android:toXScale="1.0"
-        android:fromYScale="0.9" android:toYScale="1.0"
-        android:fillEnabled="true" android:fillBefore="true" android:fillAfter="true"
-        android:interpolator="@android:interpolator/linear_out_slow_in"
-        android:pivotX="50%p" android:pivotY="50%p"
-        android:startOffset="75"
-        android:duration="225" />
-</set>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_to_launcher_enter.xml b/packages/SystemUI/legacy/recents/res/anim/recents_to_launcher_enter.xml
deleted file mode 100644
index 544ec88..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_to_launcher_enter.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false"
-     android:zAdjustment="normal">
-  <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
-         android:fillEnabled="true"
-         android:fillBefore="true" android:fillAfter="true"
-         android:interpolator="@interpolator/recents_to_launcher_enter_interpolator"
-         android:duration="133"/>
-</set>
diff --git a/packages/SystemUI/legacy/recents/res/anim/recents_to_launcher_exit.xml b/packages/SystemUI/legacy/recents/res/anim/recents_to_launcher_exit.xml
deleted file mode 100644
index 226edb8..0000000
--- a/packages/SystemUI/legacy/recents/res/anim/recents_to_launcher_exit.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2012, 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.
-*/
--->
-
-<set xmlns:android="http://schemas.android.com/apk/res/android"
-     android:shareInterpolator="false"
-     android:zAdjustment="top">
-  <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
-         android:fillEnabled="true"
-         android:fillBefore="true" android:fillAfter="true"
-         android:interpolator="@android:interpolator/linear_out_slow_in"
-         android:duration="1"/>
-</set>
diff --git a/packages/SystemUI/legacy/recents/res/drawable-hdpi/recents_lower_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-hdpi/recents_lower_gradient.9.png
deleted file mode 100644
index 17100f7..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-hdpi/recents_lower_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-hdpi/recents_status_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-hdpi/recents_status_gradient.9.png
deleted file mode 100644
index e969d4c2..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-hdpi/recents_status_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-mdpi/recents_lower_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-mdpi/recents_lower_gradient.9.png
deleted file mode 100644
index b53bd8f..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-mdpi/recents_lower_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-mdpi/recents_status_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-mdpi/recents_status_gradient.9.png
deleted file mode 100644
index 657f710..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-mdpi/recents_status_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-xhdpi/recents_lower_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-xhdpi/recents_lower_gradient.9.png
deleted file mode 100644
index 09606f6..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-xhdpi/recents_lower_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-xhdpi/recents_status_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-xhdpi/recents_status_gradient.9.png
deleted file mode 100644
index a444c55..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-xhdpi/recents_status_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_lower_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_lower_gradient.9.png
deleted file mode 100644
index 427cad9..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_lower_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_status_gradient.9.png b/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_status_gradient.9.png
deleted file mode 100644
index 29cf44b..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_status_gradient.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_task_shadow.9.png b/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_task_shadow.9.png
deleted file mode 100644
index 36e7e45..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable-xxhdpi/recents_task_shadow.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_dismiss_dark.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_dismiss_dark.xml
deleted file mode 100644
index b837ebe..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_dismiss_dark.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<!--
-Copyright (C) 2014 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-android:width="24dp"
-android:height="24dp"
-android:viewportWidth="24"
-android:viewportHeight="24">
-
-<path
-    android:fillColor="@color/recents_task_bar_dark_icon_color"
-    android:pathData="M18.3 5.71a.996 .996 0 0 0-1.41 0L12 10.59 7.11 5.7A.996 .996 0 1 0 5.7
-7.11L10.59 12 5.7 16.89a.996 .996 0 1 0 1.41 1.41L12 13.41l4.89 4.89a.996 .996 0
-1 0 1.41-1.41L13.41 12l4.89-4.89c.38-.38 .38 -1.02 0-1.4z" />
-<path
-    android:pathData="M0 0h24v24H0z" />
-</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_dismiss_light.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_dismiss_light.xml
deleted file mode 100644
index 2b20814..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_dismiss_light.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<!--
-Copyright (C) 2014 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-android:width="24dp"
-android:height="24dp"
-android:viewportWidth="24"
-android:viewportHeight="24">
-
-<path
-    android:fillColor="@color/recents_task_bar_light_icon_color"
-    android:pathData="M18.3 5.71a.996 .996 0 0 0-1.41 0L12 10.59 7.11 5.7A.996 .996 0 1 0 5.7
-7.11L10.59 12 5.7 16.89a.996 .996 0 1 0 1.41 1.41L12 13.41l4.89 4.89a.996 .996 0
-1 0 1.41-1.41L13.41 12l4.89-4.89c.38-.38 .38 -1.02 0-1.4z" />
-<path
-    android:pathData="M0 0h24v24H0z" />
-</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_empty.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_empty.xml
deleted file mode 100644
index 5506de1..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_empty.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-    android:width="100dp"
-    android:height="132dp"
-    android:viewportWidth="100"
-    android:viewportHeight="132">
-
-    <path
-        android:fillColor="#5AFFFFFF"
-        android:pathData="M86.91,68.67H13.09c-4.96,0-9,4.04-9,9V119c0,4.96,4.04,9,9,9h73.82c4.96,0,9-4.04,9-9V77.67
-C95.91,72.7,91.87,68.67,86.91,68.67z M27.59,77.27h26.72v3.94H27.59V77.27z
-M18.73,74.74c2.49,0,4.5,2.01,4.5,4.5
-c0,2.49-2.01,4.5-4.5,4.5s-4.5-2.01-4.5-4.5C14.23,76.75,16.24,74.74,18.73,74.74z
-M89.91,119c0,1.65-1.35,3-3,3H13.09 c-1.65,0-3-1.35-3-3V88.67h79.82V119z" />
-    <path
-        android:fillColor="#5AFFFFFF"
-        android:pathData="M86.91,36.3H13.09c-4.96,0-9,4.04-9,9v23c1.65-1.58,3.71-2.73,6-3.28v-9.08h79.82v9.08
-c2.29,0.55,4.35,1.69,6,3.28v-23C95.91,40.34,91.87,36.3,86.91,36.3z
-M18.73,51.38c-2.49,0-4.5-2.01-4.5-4.5s2.01-4.5,4.5-4.5
-s4.5,2.01,4.5,4.5S21.22,51.38,18.73,51.38z M54.31,48.84H27.59v-3.94h26.72V48.84z" />
-    <path
-        android:fillColor="#5AFFFFFF"
-        android:pathData="M86.91,4H13.09c-4.96,0-9,4.04-9,9v22.94c1.65-1.58,3.71-2.73,6-3.28V24h79.82v8.67
-c2.29,0.55,4.35,1.69,6,3.28V13C95.91,8.04,91.87,4,86.91,4z
-M18.73,18.5c-2.49,0-4.5-2.01-4.5-4.5s2.01-4.5,4.5-4.5
-s4.5,2.01,4.5,4.5S21.22,18.5,18.73,18.5z M54.31,15.97H27.59v-3.94h26.72V15.97z" />
-    <path
-        android:pathData="M 0 0 H 100 V 132 H 0 V 0 Z" />
-</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_grid_task_view_focus_frame_background.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_grid_task_view_focus_frame_background.xml
deleted file mode 100644
index 4987f9b..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_grid_task_view_focus_frame_background.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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.
--->
-<shape xmlns:android="http://schemas.android.com/apk/res/android">
-  <solid android:color="#61FFFFFF" />
-  <corners android:radius="@dimen/recents_grid_task_view_focused_frame_rounded_corners_radius"/>
-</shape>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_info_dark.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_info_dark.xml
deleted file mode 100644
index 555a69a..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_info_dark.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-Copyright (C) 2014 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-    <path
-        android:fillColor="@color/recents_task_bar_dark_icon_color"
-        android:pathData="M12.000000,2.000000C6.500000,2.000000 2.000000,6.500000 2.000000,12.000000s4.500000,10.000000 10.000000,10.000000c5.500000,0.000000 10.000000,-4.500000 10.000000,-10.000000S17.500000,2.000000 12.000000,2.000000zM13.000000,17.000000l-2.000000,0.000000l0.000000,-6.000000l2.000000,0.000000L13.000000,17.000000zM13.000000,9.000000l-2.000000,0.000000L11.000000,7.000000l2.000000,0.000000L13.000000,9.000000z"/>
-</vector>
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_info_light.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_info_light.xml
deleted file mode 100644
index 65e7bf5..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_info_light.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-Copyright (C) 2014 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-    <path
-        android:pathData="M12.000000,2.000000C6.500000,2.000000 2.000000,6.500000 2.000000,12.000000s4.500000,10.000000 10.000000,10.000000c5.500000,0.000000 10.000000,-4.500000 10.000000,-10.000000S17.500000,2.000000 12.000000,2.000000zM13.000000,17.000000l-2.000000,0.000000l0.000000,-6.000000l2.000000,0.000000L13.000000,17.000000zM13.000000,9.000000l-2.000000,0.000000L11.000000,7.000000l2.000000,0.000000L13.000000,9.000000z"
-        android:fillColor="#FFFFFF"/>
-</vector>
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_lock_to_app_pin.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_lock_to_app_pin.xml
deleted file mode 100644
index 317f858..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_lock_to_app_pin.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<!--
-Copyright (C) 2014 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="24.0"
-        android:viewportHeight="24.0">
-
-    <path
-        android:fillColor="#FFffffff"
-        android:pathData="M16.000000,12.000000L16.000000,4.000000l1.000000,0.000000L17.000000,2.000000L7.000000,2.000000l0.000000,2.000000l1.000000,0.000000l0.000000,8.000000l-2.000000,2.000000l0.000000,2.000000l5.200000,0.000000l0.000000,6.000000l1.600000,0.000000l0.000000,-6.000000L18.000000,16.000000l0.000000,-2.000000L16.000000,12.000000z"/>
-</vector>
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_lock_to_task_button_bg.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_lock_to_task_button_bg.xml
deleted file mode 100644
index 8a8164a..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_lock_to_task_button_bg.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-
-<ripple xmlns:android="http://schemas.android.com/apk/res/android"
-     android:color="#ff9cdfd9">
-     <item>
-          <shape android:shape="oval">
-               <solid android:color="#9cc8c4" />
-               <size android:width="@dimen/recents_lock_to_app_size"
-                     android:height="@dimen/recents_lock_to_app_size" />
-          </shape>
-     </item>
-</ripple>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_low_ram_stack_button_background.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_low_ram_stack_button_background.xml
deleted file mode 100644
index bff97f6..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_low_ram_stack_button_background.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<!--
-  ~ 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.
-  -->
-<shape xmlns:android="http://schemas.android.com/apk/res/android" >
-
-      <corners android:radius="@dimen/borderless_button_radius" />
-
-      <solid android:color="?attr/clearAllBackgroundColor" />
-
-</shape>
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_move_task_fullscreen_dark.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_move_task_fullscreen_dark.xml
deleted file mode 100644
index fd468c1..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_move_task_fullscreen_dark.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<!--
-Copyright (C) 2015 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-    android:width="24dp"
-    android:height="24dp"
-    android:viewportWidth="24"
-    android:viewportHeight="24">
-    <group
-            android:translateX="-252.000000"
-            android:translateY="-602.000000">
-        <group
-                android:translateX="109.000000"
-                android:translateY="514.000000">
-            <group
-                    android:translateX="144.000000"
-                    android:translateY="89.000000">
-                <path
-                    android:strokeColor="@color/recents_task_bar_dark_icon_color"
-                    android:strokeWidth="2"
-                    android:pathData="M17,17 L5,17 L5,5 L17,5 L17,17 Z" />
-            </group>
-        </group>
-    </group>
-</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_move_task_fullscreen_light.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_move_task_fullscreen_light.xml
deleted file mode 100644
index 53229063..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_move_task_fullscreen_light.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<!--
-Copyright (C) 2015 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-    android:width="24dp"
-    android:height="24dp"
-    android:viewportWidth="24"
-    android:viewportHeight="24">
-    <group
-            android:translateX="-252.000000"
-            android:translateY="-602.000000">
-        <group
-                android:translateX="109.000000"
-                android:translateY="514.000000">
-            <group
-                    android:translateX="144.000000"
-                    android:translateY="89.000000">
-                <path
-                    android:strokeColor="@color/recents_task_bar_light_icon_color"
-                    android:strokeWidth="2"
-                    android:pathData="M19,19 L3,19 L3,3 L19,3 L19,5 L19,18 L19,19 Z" />
-            </group>
-        </group>
-    </group>
-</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/drawable/recents_stack_action_background.xml b/packages/SystemUI/legacy/recents/res/drawable/recents_stack_action_background.xml
deleted file mode 100644
index 2a40dd0..0000000
--- a/packages/SystemUI/legacy/recents/res/drawable/recents_stack_action_background.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<!--
-Copyright (C) 2016 The Android Open Source Project
-
-   Licensed under the Apache License, Version 2 (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.
--->
-
-<ripple xmlns:android="http://schemas.android.com/apk/res/android"
-        android:color="?android:attr/colorControlHighlight">
-    <item android:id="@android:id/mask">
-        <shape>
-            <corners android:radius="@dimen/recents_task_view_rounded_corners_radius" />
-            <solid android:color="@android:color/white" />
-        </shape>
-    </item>
-</ripple>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/interpolator/recents_from_launcher_exit_interpolator.xml b/packages/SystemUI/legacy/recents/res/interpolator/recents_from_launcher_exit_interpolator.xml
deleted file mode 100644
index 4a7fff6..0000000
--- a/packages/SystemUI/legacy/recents/res/interpolator/recents_from_launcher_exit_interpolator.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-<pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
-    android:controlX1="0"
-    android:controlY1="0"
-    android:controlX2="0.8"
-    android:controlY2="1" />
diff --git a/packages/SystemUI/legacy/recents/res/interpolator/recents_launch_next_affiliated_task_bounce_scale.xml b/packages/SystemUI/legacy/recents/res/interpolator/recents_launch_next_affiliated_task_bounce_scale.xml
deleted file mode 100644
index c4e5d97..0000000
--- a/packages/SystemUI/legacy/recents/res/interpolator/recents_launch_next_affiliated_task_bounce_scale.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-<pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
-    android:pathData="M 0,0 c 0.8,0 0.2,1 1,1" />
diff --git a/packages/SystemUI/legacy/recents/res/interpolator/recents_launch_prev_affiliated_task_bounce_ydelta.xml b/packages/SystemUI/legacy/recents/res/interpolator/recents_launch_prev_affiliated_task_bounce_ydelta.xml
deleted file mode 100644
index 40a08b9..0000000
--- a/packages/SystemUI/legacy/recents/res/interpolator/recents_launch_prev_affiliated_task_bounce_ydelta.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-<pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
-    android:pathData="M 0,0 c 0.6,0 0.2,1 1,1" />
diff --git a/packages/SystemUI/legacy/recents/res/interpolator/recents_to_launcher_enter_interpolator.xml b/packages/SystemUI/legacy/recents/res/interpolator/recents_to_launcher_enter_interpolator.xml
deleted file mode 100644
index c61dfd8..0000000
--- a/packages/SystemUI/legacy/recents/res/interpolator/recents_to_launcher_enter_interpolator.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2014, 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.
-*/
--->
-<pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
-    android:controlX1="0.4"
-    android:controlY1="0"
-    android:controlX2="1"
-    android:controlY2="1" />
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents.xml b/packages/SystemUI/legacy/recents/res/layout/recents.xml
deleted file mode 100644
index ae89631..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-<FrameLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent">
-
-    <!-- Recents View -->
-    <com.android.systemui.recents.views.RecentsView
-        android:id="@+id/recents_view"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent">
-    </com.android.systemui.recents.views.RecentsView>
-
-    <!-- Incompatible task overlay -->
-    <ViewStub android:id="@+id/incompatible_app_overlay_stub"
-        android:inflatedId="@+id/incompatible_app_overlay"
-        android:layout="@layout/recents_incompatible_app_overlay"
-        android:layout_width="match_parent"
-        android:layout_height="128dp"
-        android:layout_gravity="center_horizontal|top" />
-
-    <!-- Nav Bar Scrim View -->
-    <ImageView
-        android:id="@+id/nav_bar_scrim"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_horizontal|bottom"
-        android:scaleType="fitXY"
-        android:src="@drawable/recents_lower_gradient" />
-</FrameLayout>
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_empty.xml b/packages/SystemUI/legacy/recents/res/layout/recents_empty.xml
deleted file mode 100644
index d7f058c..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_empty.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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="wrap_content"
-    android:layout_height="wrap_content"
-    android:layout_gravity="center"
-    android:gravity="center"
-    android:drawableTop="@drawable/recents_empty"
-    android:drawablePadding="25dp"
-    android:textSize="16sp"
-    android:drawableTint="?attr/wallpaperTextColor"
-    android:textColor="?attr/wallpaperTextColor"
-    android:text="@string/recents_empty_message"
-    android:fontFamily="sans-serif"
-    android:visibility="gone" />
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_grid_task_view.xml b/packages/SystemUI/legacy/recents/res/layout/recents_grid_task_view.xml
deleted file mode 100644
index 1c9b9ac..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_grid_task_view.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.recents.views.grid.GridTaskView
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:focusable="true">
-    <com.android.systemui.recents.views.grid.GridTaskViewThumbnail
-        android:id="@+id/task_view_thumbnail"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent" />
-
-    <include layout="@layout/recents_task_view_header" />
-
-    <!-- TODO: Move this into a view stub -->
-    <include layout="@layout/recents_task_view_lock_to_app"/>
-
-    <!-- The incompatible app toast -->
-    <include layout="@layout/recents_task_view_incompatible_app_toast"/>
-</com.android.systemui.recents.views.grid.GridTaskView>
-
-
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_incompatible_app_overlay.xml b/packages/SystemUI/legacy/recents/res/layout/recents_incompatible_app_overlay.xml
deleted file mode 100644
index a1c1e5b..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_incompatible_app_overlay.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-<FrameLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:alpha="0"
-    android:background="#88000000"
-    android:forceHasOverlappingRendering="false">
-    <TextView
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center"
-        android:drawableTop="@drawable/recents_info_light"
-        android:drawablePadding="8dp"
-        android:text="@string/dock_non_resizeble_failed_to_dock_text"
-        android:textColor="@android:color/white" />
-</FrameLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_low_ram_stack_action_button.xml b/packages/SystemUI/legacy/recents/res/layout/recents_low_ram_stack_action_button.xml
deleted file mode 100644
index dca8911..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_low_ram_stack_action_button.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ 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.
-  -->
-<TextView
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/button"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:paddingStart="26dp"
-    android:paddingEnd="26dp"
-    android:paddingTop="17dp"
-    android:paddingBottom="17dp"
-    android:text="@string/recents_stack_action_button_label"
-    android:textSize="14sp"
-    android:textColor="#FFFFFF"
-    android:textAllCaps="true"
-    android:fontFamily="sans-serif-medium"
-    android:background="@drawable/recents_low_ram_stack_button_background"
-    android:visibility="invisible"
-    android:forceHasOverlappingRendering="false"
-    style="?attr/clearAllStyle" />
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_search_bar.xml b/packages/SystemUI/legacy/recents/res/layout/recents_search_bar.xml
deleted file mode 100644
index 915283e..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_search_bar.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-<FrameLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:background="@drawable/search_bg_transparent">
-    <TextView
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center"
-        android:text="@string/recents_search_bar_label"
-        android:textColor="#99ffffff"
-        android:textSize="18sp"
-        android:textAllCaps="true" />
-</FrameLayout>
-
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_stack_action_button.xml b/packages/SystemUI/legacy/recents/res/layout/recents_stack_action_button.xml
deleted file mode 100644
index 4707a8c..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_stack_action_button.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 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:id="@+id/button"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:paddingStart="14dp"
-    android:paddingEnd="14dp"
-    android:paddingTop="12dp"
-    android:paddingBottom="12dp"
-    android:text="@string/recents_stack_action_button_label"
-    android:textSize="14sp"
-    android:textColor="?attr/wallpaperTextColor"
-    android:textAllCaps="true"
-    android:shadowColor="#99000000"
-    android:shadowDx="0"
-    android:shadowDy="2"
-    android:shadowRadius="5"
-    android:fontFamily="sans-serif-medium"
-    android:background="@drawable/recents_stack_action_background"
-    android:visibility="invisible"
-    android:forceHasOverlappingRendering="false"
-    style="?attr/clearAllStyle" />
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_task_view.xml b/packages/SystemUI/legacy/recents/res/layout/recents_task_view.xml
deleted file mode 100644
index 015e4a2..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_task_view.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.recents.views.TaskView
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:focusable="true">
-    <com.android.systemui.recents.views.TaskViewThumbnail
-        android:id="@+id/task_view_thumbnail"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent" />
-
-    <include layout="@layout/recents_task_view_header" />
-
-    <!-- TODO: Move this into a view stub -->
-    <include layout="@layout/recents_task_view_lock_to_app"/>
-
-    <!-- The incompatible app toast -->
-    <include layout="@layout/recents_task_view_incompatible_app_toast"/>
-</com.android.systemui.recents.views.TaskView>
-
-
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header.xml b/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header.xml
deleted file mode 100644
index 1734506..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header.xml
+++ /dev/null
@@ -1,75 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     Copyright (C) 2014 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.
--->
-<!-- The layouts params are calculated in TaskViewHeader.java -->
-<com.android.systemui.recents.views.TaskViewHeader
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/task_view_bar"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:layout_gravity="top|center_horizontal">
-    <com.android.systemui.recents.views.FixedSizeImageView
-        android:id="@+id/icon"
-        android:contentDescription="@string/recents_app_info_button_label"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical|start"
-        android:paddingTop="8dp"
-        android:paddingBottom="8dp"
-        android:paddingStart="16dp"
-        android:paddingEnd="12dp" />
-    <TextView
-        android:id="@+id/title"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical|start"
-        android:textSize="16sp"
-        android:textColor="#ffffffff"
-        android:text="@string/recents_empty_message"
-        android:fontFamily="sans-serif-medium"
-        android:singleLine="true"
-        android:maxLines="1"
-        android:ellipsize="marquee"
-        android:fadingEdge="horizontal"
-        android:forceHasOverlappingRendering="false" />
-    <com.android.systemui.recents.views.FixedSizeImageView
-        android:id="@+id/move_task"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical|end"
-        android:padding="@dimen/recents_task_view_header_button_padding"
-        android:src="@drawable/star"
-        android:background="?android:selectableItemBackground"
-        android:alpha="0"
-        android:visibility="gone" />
-    <com.android.systemui.recents.views.FixedSizeImageView
-        android:id="@+id/dismiss_task"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical|end"
-        android:padding="@dimen/recents_task_view_header_button_padding"
-        android:src="@drawable/recents_dismiss_light"
-        android:background="?android:selectableItemBackground"
-        android:alpha="0"
-        android:visibility="gone" />
-
-    <!-- The app overlay shows as the user long-presses on the app icon -->
-    <ViewStub android:id="@+id/app_overlay_stub"
-               android:inflatedId="@+id/app_overlay"
-               android:layout="@layout/recents_task_view_header_overlay"
-               android:layout_width="match_parent"
-               android:layout_height="match_parent" />
-</com.android.systemui.recents.views.TaskViewHeader>
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header_overlay.xml b/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header_overlay.xml
deleted file mode 100644
index cf09b1d..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header_overlay.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-<!-- The layouts params are calculated in TaskViewHeader.java -->
-<FrameLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent">
-    <com.android.systemui.recents.views.FixedSizeImageView
-        android:id="@+id/app_icon"
-        android:contentDescription="@string/recents_app_info_button_label"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical|start"
-        android:paddingTop="8dp"
-        android:paddingBottom="8dp"
-        android:paddingStart="16dp"
-        android:paddingEnd="12dp" />
-    <TextView
-        android:id="@+id/app_title"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical|start"
-        android:textSize="16sp"
-        android:textColor="#ffffffff"
-        android:text="@string/recents_empty_message"
-        android:fontFamily="sans-serif-medium"
-        android:singleLine="true"
-        android:maxLines="2"
-        android:ellipsize="marquee"
-        android:fadingEdge="horizontal" />
-    <com.android.systemui.recents.views.FixedSizeImageView
-        android:id="@+id/app_info"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical|end"
-        android:padding="@dimen/recents_task_view_header_button_padding"
-        android:background="?android:selectableItemBackground"
-        android:src="@drawable/recents_info_light" />
-</FrameLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header_progress_bar.xml b/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header_progress_bar.xml
deleted file mode 100644
index f352632..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_header_progress_bar.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-<ProgressBar
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    style="?android:attr/progressBarStyleHorizontal"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:indeterminateOnly="false"
-    android:visibility="invisible" />
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_incompatible_app_toast.xml b/packages/SystemUI/legacy/recents/res/layout/recents_task_view_incompatible_app_toast.xml
deleted file mode 100644
index d573d6b..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_incompatible_app_toast.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-<ViewStub
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/incompatible_app_toast_stub"
-    android:inflatedId="@+id/incompatible_app_toast"
-    android:layout="@*android:layout/transient_notification"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:layout_gravity="top|center_horizontal"
-    android:layout_marginTop="48dp"
-    android:layout_marginLeft="16dp"
-    android:layout_marginRight="16dp" />
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_lock_to_app.xml b/packages/SystemUI/legacy/recents/res/layout/recents_task_view_lock_to_app.xml
deleted file mode 100644
index 8cece11..0000000
--- a/packages/SystemUI/legacy/recents/res/layout/recents_task_view_lock_to_app.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.statusbar.AlphaOptimizedFrameLayout
-  xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/lock_to_app_fab"
-    android:layout_width="@dimen/recents_lock_to_app_size"
-    android:layout_height="@dimen/recents_lock_to_app_size"
-    android:layout_gravity="bottom|end"
-    android:layout_marginEnd="15dp"
-    android:layout_marginBottom="15dp"
-    android:translationZ="4dp"
-    android:contentDescription="@string/recents_lock_to_app_button_label"
-    android:background="@drawable/recents_lock_to_task_button_bg"
-    android:visibility="invisible"
-    android:alpha="0">
-    <ImageView
-        android:layout_width="@dimen/recents_lock_to_app_icon_size"
-        android:layout_height="@dimen/recents_lock_to_app_icon_size"
-        android:layout_gravity="center"
-        android:src="@drawable/recents_lock_to_app_pin" />
-</com.android.systemui.statusbar.AlphaOptimizedFrameLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/values-af/strings.xml b/packages/SystemUI/legacy/recents/res/values-af/strings.xml
deleted file mode 100644
index 736c810..0000000
--- a/packages/SystemUI/legacy/recents/res/values-af/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Oorsig."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Maak <xliff:g id="APP">%s</xliff:g> toe."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> is toegemaak."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Alle onlangse programme is toegemaak."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Maak <xliff:g id="APP">%s</xliff:g>-programinligting oop."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Begin tans <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Geen onlangse items nie"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Jy het alles toegemaak"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Programinligting"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"skermvaspen"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"soek"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Kon nie <xliff:g id="APP">%s</xliff:g> begin nie."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> is in veiligmodus gedeaktiveer."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Vee alles uit"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Sleep hierheen om verdeelde skerm te gebruik"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Verdeel horisontaal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Verdeel vertikaal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Verdeel gepasmaak"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Verdeel skerm na bo"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Verdeel skerm na links"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Verdeel skerm na regs"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-am/strings.xml b/packages/SystemUI/legacy/recents/res/values-am/strings.xml
deleted file mode 100644
index 2870be7..0000000
--- a/packages/SystemUI/legacy/recents/res/values-am/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"አጠቃላይ እይታ።"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> አስወግድ።"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ተሰናብቷል።"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"ሁሉም የቅርብ ጊዜ ማመልከቻዎች ተሰናብተዋል።"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"የ<xliff:g id="APP">%s</xliff:g> መተግበሪያ መረጃውን ይክፈቱ።"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> በመጀመር ላይ።"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ምንም የቅርብ ጊዜ ንጥሎች የሉም"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"ሁሉንም ነገር አጽድተዋል"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"የመተግበሪያ መረጃ"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ማያ ገጽ መሰካት"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ፈልግ"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>ን መጀመር አልተቻለም።"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> በጥንቃቄ ሁነታ ውስጥ ታግዷል።"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ሁሉንም አጽዳ"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"የተከፈለ ማያ ገጽን ለመጠቀም እዚህ ላይ ይጎትቱ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"አግድም ክፈል"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ቁልቁል ክፈል"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"በብጁ ክፈል"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"ማያ ገጽ ወደ ላይ ክፈል"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"ማያ ገጽ ወደ ግራ ክፈል"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"ማያ ገጽ ወደ ቀኝ ክፈል"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ar/strings.xml b/packages/SystemUI/legacy/recents/res/values-ar/strings.xml
deleted file mode 100644
index 004de41..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ar/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"النظرة عامة"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"إزالة <xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"تمَّت إزالة <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"تمَّت إزالة كل التطبيقات المستخدمة مؤخرًا."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"فتح معلومات تطبيق <xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"جارٍ بدء <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ليست هناك عناصر تم استخدامها مؤخرًا"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"لقد محوتَ كل شيء"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"معلومات التطبيق"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"تثبيت الشاشة"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"بحث"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"تعذَّر بدء <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"تم إيقاف <xliff:g id="APP">%s</xliff:g> في الوضع الآمن."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"محو الكل"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"اسحب هنا لاستخدام وضع تقسيم الشاشة"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"تقسيم أفقي"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"تقسيم رأسي"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"تقسيم مخصَّص"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"تقسيم الشاشة بمحاذاة الجزء العلوي"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"تقسيم الشاشة بمحاذاة اليسار"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"تقسيم الشاشة بمحاذاة اليمين"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-as/strings.xml b/packages/SystemUI/legacy/recents/res/values-as/strings.xml
deleted file mode 100644
index c742dab..0000000
--- a/packages/SystemUI/legacy/recents/res/values-as/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"অৱলোকন।"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"শেহতীয়া-ৰ তালিকাৰ পৰা <xliff:g id="APP">%s</xliff:g>ক আঁতৰাওক।"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"শেহতীয়া-ৰ তালিকাৰ পৰা <xliff:g id="APP">%s</xliff:g>ক আঁতৰোৱা হ’ল।"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"শেহতীয়া-ৰ তালিকাৰ পৰা সকলো এপ্লিকেশ্বন আঁতৰোৱা হ’ল।"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> এপ্লিকেশ্বনৰ তথ্য খোলক।"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g>ক আৰম্ভ কৰা হৈছে।"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"কোনো শেহতীয়া বস্তু নাই"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"আপুনি সকলো খালী কৰিলে"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"এপ্লিকেশ্বনৰ তথ্য"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"স্ক্ৰীণ পিনিং"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"সন্ধান কৰক"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>ক আৰম্ভ কৰিব পৰা নগ’ল।"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g>টো সুৰক্ষিত ম’ডত অক্ষম কৰা হ’ল।"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"সকলো মচক"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"বিভাজিত স্ক্ৰীণ ব্যৱহাৰ কৰিবলৈ ইয়ালৈ টানি আনি এৰক"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"আনুভূমিকভাৱে বিভাজন কৰক"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"উলম্বভাৱে বিভাজন কৰক"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"কাষ্টম বিভাজন কৰক"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"স্ক্ৰীণখনক ওপৰফাললৈ ভাগ কৰক"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"স্ক্ৰীণখনক বাওঁফাললৈ ভাগ কৰক"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"স্ক্ৰীণখনক সোঁফাললৈ ভাগ কৰক"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-az/strings.xml b/packages/SystemUI/legacy/recents/res/values-az/strings.xml
deleted file mode 100644
index 76ae02a..0000000
--- a/packages/SystemUI/legacy/recents/res/values-az/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"İcmal."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> tətbiqini silin."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> silindi."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Bütün son tətbiqlər silindi."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> tətbiq məlumatını açın."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> başladılır."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Ən son element yoxdur"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Hər şeyi sildiniz"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Tətbiq məlumatı"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ekran sancağı"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"axtarış"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> başladılmadı."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> təhlükəsiz rejimdə deaktiv edildi."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Hamısını silin"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Bölünmüş ekrandan istifadə etmək üçün bura sürüşdürün"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Horizontal Bölün"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Vertikal Bölün"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Fərdi Bölün"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Ekranı yuxarıya doğru bölün"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Ekranı sola doğru bölün"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Ekranı sağa doğru bölün"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-b+sr+Latn/strings.xml b/packages/SystemUI/legacy/recents/res/values-b+sr+Latn/strings.xml
deleted file mode 100644
index 3117eea..0000000
--- a/packages/SystemUI/legacy/recents/res/values-b+sr+Latn/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Pregled."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Odbacite aplikaciju <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Aplikacija <xliff:g id="APP">%s</xliff:g> je odbačena."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Sve nedavno korišćene aplikacije su odbačene."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Otvorite informacije o aplikaciji <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Pokreće se <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nema nedavnih stavki"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Obrisali ste sve"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informacije o aplikaciji"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"kačenje ekrana"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"pretraži"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Pokretanje aplikacije <xliff:g id="APP">%s</xliff:g> nije uspelo."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplikacija <xliff:g id="APP">%s</xliff:g> je onemogućena u bezbednom režimu."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Obriši sve"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Prevucite ovde da biste koristili razdeljeni ekran"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Podeli horizontalno"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Podeli vertikalno"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Podeli prilagođeno"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Podeli ekran nagore"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Podeli ekran nalevo"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Podeli ekran nadesno"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-be/strings.xml b/packages/SystemUI/legacy/recents/res/values-be/strings.xml
deleted file mode 100644
index 8121846..0000000
--- a/packages/SystemUI/legacy/recents/res/values-be/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Агляд."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Закрыць праграму \"<xliff:g id="APP">%s</xliff:g>\"."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Праграма \"<xliff:g id="APP">%s</xliff:g>\" закрыта."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Усе нядаўнія праграмы закрыты."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Адкрыць інфармацыю пра праграму \"<xliff:g id="APP">%s</xliff:g>\"."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Запускаецца праграма \"<xliff:g id="APP">%s</xliff:g>\"."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Няма нядаўніх элементаў"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Вы ўсё выдалілі"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Інфармацыя пра праграму"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"замацаванне экрана"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"пошук"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Не ўдалося запусціць праграму \"<xliff:g id="APP">%s</xliff:g>\"."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Праграма \"<xliff:g id="APP">%s</xliff:g>\" адключана ў бяспечным рэжыме."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Ачысціць усё"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Перацягніце сюды, каб перайсці ў рэжым падзеленага экрана"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Падзяліць гарызантальна"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Падзяліць вертыкальна"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Падзяліць іншым чынам"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Падзяліць экран зверху"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Падзяліць экран злева"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Падзяліць экран справа"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-bg/strings.xml b/packages/SystemUI/legacy/recents/res/values-bg/strings.xml
deleted file mode 100644
index 3dda34f..0000000
--- a/packages/SystemUI/legacy/recents/res/values-bg/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Общ преглед."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Отхвърляне на <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Приложението <xliff:g id="APP">%s</xliff:g> е отхвърлено."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Всички скорошни приложения са отхвърлени."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Отворете информацията за приложението <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> се стартира."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Няма скорошни елементи"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Изчистихте всичко"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Информация за приложението"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"фиксиране на екрана"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"търсене"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> не можа да стартира."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Приложението <xliff:g id="APP">%s</xliff:g> е деактивирано в безопасния режим."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Изчистване на всичко"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Преместете тук с плъзгане, за да използвате режим за разделен екран"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Хоризонтално разделяне"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Вертикално разделяне"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Персонализирано разделяне"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Разделяне на екрана нагоре"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Разделяне на екрана наляво"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Разделяне на екрана надясно"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-bn/strings.xml b/packages/SystemUI/legacy/recents/res/values-bn/strings.xml
deleted file mode 100644
index b22672e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-bn/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"এক নজরে।"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> খারিজ করুন।"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> খারিজ করা হয়েছে।"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"সব সাম্প্রতিক অ্যাপ্লিকেশন খারিজ করা হয়েছে।"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> অ্যাপ্লিকেশনের তথ্য খুলুন।"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> শুরু করা হচ্ছে।"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"কোনো সাম্প্রতিক আইটেম নেই"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"আপনি সবকিছু মুছে দিয়েছেন"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"অ্যাপ্লিকেশনের তথ্য"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"স্ক্রিন পিন করা"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"খুঁজুন"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> চালু করা যায়নি।"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"নিরাপদ মোডে <xliff:g id="APP">%s</xliff:g> বন্ধ করা আছে।"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"সবগুলি মুছে দিন"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"স্প্লিট স্ক্রিন ব্যবহার করতে এখানে টেনে আনুন"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"অনুভূমিক স্প্লিট করুন"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"উল্লম্ব স্প্লিট করুন"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"কাস্টম স্প্লিট করুন"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"স্ক্রিনটি উপরের দিকে স্প্লিট করুন"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"স্ক্রিনটি বাঁদিকে স্প্লিট করুন"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"স্ক্রিনটি ডানদিকে স্প্লিট করুন"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-bs/strings.xml b/packages/SystemUI/legacy/recents/res/values-bs/strings.xml
deleted file mode 100644
index 8e149ba8..0000000
--- a/packages/SystemUI/legacy/recents/res/values-bs/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Pregled."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Odbaci aplikaciju <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Aplikacija <xliff:g id="APP">%s</xliff:g> je odbačena."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Sve nedavno korištene aplikacije su odbačene."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Otvaranje informacija o aplikaciji <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Pokretanje aplikacije <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nema nedavnih stavki"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Sve ste obrisali"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informacije o aplikaciji"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"kačenje ekrana"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"pretraži"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Aplikacija <xliff:g id="APP">%s</xliff:g> nije pokrenuta."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplikacija <xliff:g id="APP">%s</xliff:g> je onemogućena u sigurnom načinu rada."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Obriši sve"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Povucite ovdje za korištenje podijeljenog ekrana"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Podjela po horizontali"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Podjela po vertikali"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Prilagođena podjela"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Dijeli ekran nagore"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Dijeli ekran nalijevo"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Dijeli ekran nadesno"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ca/strings.xml b/packages/SystemUI/legacy/recents/res/values-ca/strings.xml
deleted file mode 100644
index fff525c..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ca/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Aplicacions recents."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Ignora <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"S\'ha ignorat <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"S\'han ignorat totes les aplicacions recents."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Obre la informació sobre l\'aplicació <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"S\'està iniciant <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"No hi ha cap element recent"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Ho has esborrat tot"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informació de l\'aplicació"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"fixació de pantalla"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"cerca"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"No s\'ha pogut iniciar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"En mode segur, l\'aplicació <xliff:g id="APP">%s</xliff:g> està desactivada."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Esborra-ho tot"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arrossega-ho aquí per utilitzar la pantalla dividida"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Divisió horitzontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Divisió vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Divisió personalitzada"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Divideix la pantalla cap amunt"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Divideix la pantalla cap a l\'esquerra"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Divideix la pantalla cap a la dreta"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-cs/strings.xml b/packages/SystemUI/legacy/recents/res/values-cs/strings.xml
deleted file mode 100644
index 200f7a8..0000000
--- a/packages/SystemUI/legacy/recents/res/values-cs/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Přehled"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Zavřít aplikaci <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Aplikace <xliff:g id="APP">%s</xliff:g> byla odebrána."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Všechny naposledy použité aplikace byly odstraněny."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Otevře informace o aplikaci <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Spouštění aplikace <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Žádné nedávné položky"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Vše je vymazáno"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informace o aplikaci"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"připnutí obrazovky"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"hledat"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Aplikaci <xliff:g id="APP">%s</xliff:g> nelze spustit."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplikace <xliff:g id="APP">%s</xliff:g> je v nouzovém režimu zakázána."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Vymazat vše"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Přetáhnutím sem aktivujete rozdělenou obrazovku"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Vodorovné rozdělení"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Svislé rozdělení"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Vlastní rozdělení"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Rozdělit obrazovku nahoru"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Rozdělit obrazovku vlevo"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Rozdělit obrazovku vpravo"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-da/strings.xml b/packages/SystemUI/legacy/recents/res/values-da/strings.xml
deleted file mode 100644
index 0a1690e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-da/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Oversigt."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Fjern <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> er fjernet."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Alle de seneste apps er fjernet."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Åbn appoplysningerne for <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> åbnes."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Ingen nye elementer"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Du har ryddet alt"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Appoplysninger"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"skærmfastholdelse"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"søg"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> kunne ikke åbnes."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> er deaktiveret i sikker tilstand."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Ryd alle"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Træk hertil for at bruge opdelt skærm"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Opdel vandret"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Opdel lodret"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Opdel brugerdefineret"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Opdelt skærm øverst"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Opdelt skærm til venstre"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Opdelt skærm til højre"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-de/strings.xml b/packages/SystemUI/legacy/recents/res/values-de/strings.xml
deleted file mode 100644
index 4a089bf..0000000
--- a/packages/SystemUI/legacy/recents/res/values-de/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Übersicht."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> entfernen."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> wurde entfernt."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Alle kürzlich verwendeten Apps wurden entfernt."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Infos zur <xliff:g id="APP">%s</xliff:g> App öffnen."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> wird gestartet."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Keine kürzlich verwendeten Elemente"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Du hast alles gelöscht"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"App-Info"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"Bildschirm anpinnen"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"Suchen"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> konnte nicht gestartet werden."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ist im abgesicherten Modus deaktiviert."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Alle löschen"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Hierher ziehen, um den Bildschirm zu teilen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Geteilt – horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Geteilt – vertikal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Geteilt – benutzerdefiniert"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Geteilten Bildschirm oben anzeigen"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Geteilten Bildschirm links anzeigen"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Geteilten Bildschirm rechts anzeigen"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-el/strings.xml b/packages/SystemUI/legacy/recents/res/values-el/strings.xml
deleted file mode 100644
index 90baf52..0000000
--- a/packages/SystemUI/legacy/recents/res/values-el/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Επισκόπηση."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Παράβλεψη εφαρμογής <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Η εφαρμογή <xliff:g id="APP">%s</xliff:g> απορρίφθηκε."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Όλες οι πρόσφατες εφαρμογές παραβλέφθηκαν."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Άνοιγμα πληροφοριών εφαρμογής <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Έναρξη εφαρμογής <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Δεν υπάρχουν πρόσφατα στοιχεία"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Διαγράψατε όλα τα στοιχεία"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Πληροφορίες εφαρμογής"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"καρφίτσωμα οθόνης"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"αναζήτηση"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Δεν ήταν δυνατή η έναρξη της εφαρμογής <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Η εφαρμογή <xliff:g id="APP">%s</xliff:g> έχει απενεργοποιηθεί στην ασφαλή λειτουργία."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Διαγραφή όλων"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Σύρετε εδώ για να χρησιμοποιήσετε τον διαχωρισμό οθόνης"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Οριζόντιος διαχωρισμός"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Κάθετος διαχωρισμός"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Προσαρμοσμένος διαχωρισμός"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Διαχωρισμός οθόνης στην κορυφή"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Διαχωρισμός οθόνης στα αριστερά"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Διαχωρισμός οθόνης στα δεξιά"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-en-rAU/strings.xml b/packages/SystemUI/legacy/recents/res/values-en-rAU/strings.xml
deleted file mode 100644
index af1d055..0000000
--- a/packages/SystemUI/legacy/recents/res/values-en-rAU/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Overview."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Dismiss <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> dismissed."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"All recent applications dismissed."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Open <xliff:g id="APP">%s</xliff:g> application info."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Starting <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"No recent items"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"You\'ve cleared everything"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Application Info"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"screen pinning"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"search"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Could not start <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> is disabled in safe-mode."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Clear all"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Drag here to use split screen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Split Horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Split Vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Split Custom"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Split screen to the top"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Split screen to the left"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Split screen to the right"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-en-rCA/strings.xml b/packages/SystemUI/legacy/recents/res/values-en-rCA/strings.xml
deleted file mode 100644
index af1d055..0000000
--- a/packages/SystemUI/legacy/recents/res/values-en-rCA/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Overview."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Dismiss <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> dismissed."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"All recent applications dismissed."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Open <xliff:g id="APP">%s</xliff:g> application info."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Starting <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"No recent items"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"You\'ve cleared everything"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Application Info"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"screen pinning"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"search"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Could not start <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> is disabled in safe-mode."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Clear all"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Drag here to use split screen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Split Horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Split Vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Split Custom"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Split screen to the top"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Split screen to the left"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Split screen to the right"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-en-rGB/strings.xml b/packages/SystemUI/legacy/recents/res/values-en-rGB/strings.xml
deleted file mode 100644
index af1d055..0000000
--- a/packages/SystemUI/legacy/recents/res/values-en-rGB/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Overview."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Dismiss <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> dismissed."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"All recent applications dismissed."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Open <xliff:g id="APP">%s</xliff:g> application info."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Starting <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"No recent items"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"You\'ve cleared everything"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Application Info"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"screen pinning"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"search"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Could not start <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> is disabled in safe-mode."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Clear all"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Drag here to use split screen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Split Horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Split Vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Split Custom"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Split screen to the top"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Split screen to the left"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Split screen to the right"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-en-rIN/strings.xml b/packages/SystemUI/legacy/recents/res/values-en-rIN/strings.xml
deleted file mode 100644
index af1d055..0000000
--- a/packages/SystemUI/legacy/recents/res/values-en-rIN/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Overview."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Dismiss <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> dismissed."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"All recent applications dismissed."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Open <xliff:g id="APP">%s</xliff:g> application info."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Starting <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"No recent items"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"You\'ve cleared everything"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Application Info"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"screen pinning"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"search"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Could not start <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> is disabled in safe-mode."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Clear all"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Drag here to use split screen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Split Horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Split Vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Split Custom"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Split screen to the top"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Split screen to the left"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Split screen to the right"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-en-rXC/strings.xml b/packages/SystemUI/legacy/recents/res/values-en-rXC/strings.xml
deleted file mode 100644
index ceb6b13..0000000
--- a/packages/SystemUI/legacy/recents/res/values-en-rXC/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‎‏‏‎‏‎‏‏‏‏‎‎‏‎‏‏‏‎‏‏‏‏‎‎‏‏‏‎‎‏‎‏‎‎‎‎‎‎‎‏‎‏‏‎‏‏‏‏‎‏‎‎‎‏‏‏‎‏‎Overview.‎‏‎‎‏‎"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‎‎‏‎‏‏‎‎‎‏‏‏‎‎‎‏‏‎‏‎‏‎‎‏‏‎‎‎‏‎‎‎‏‎‎‏‎‎‎‏‏‏‏‏‎‎‎‏‎‎‎‏‏‎‏‏‏‎‎Dismiss ‎‏‎‎‏‏‎<xliff:g id="APP">%s</xliff:g>‎‏‎‎‏‏‏‎.‎‏‎‎‏‎"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‎‏‎‏‏‎‏‏‎‎‎‏‎‏‎‏‏‎‏‏‏‎‎‎‎‎‎‎‎‎‏‏‎‏‏‏‏‎‎‏‎‎‏‏‎‎‏‏‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‏‎<xliff:g id="APP">%s</xliff:g>‎‏‎‎‏‏‏‎ dismissed.‎‏‎‎‏‎"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‏‏‏‏‎‎‎‎‎‎‏‎‎‏‎‏‎‏‎‎‎‏‏‏‎‏‏‏‏‎‏‎‏‎‎‏‎‎‎‎‏‎‏‎‏‎‎‎‎‎‏‎‏‏‏‎‏‏‏‎‎All recent applications dismissed.‎‏‎‎‏‎"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‏‏‏‎‏‎‎‎‏‏‏‎‏‏‎‎‎‎‎‎‎‎‏‏‏‎‏‏‎‎‏‏‏‏‏‏‎‎‏‎‏‏‎‎‎‎‏‎‏‎‏‏‏‏‏‏‎‎‎‎Open ‎‏‎‎‏‏‎<xliff:g id="APP">%s</xliff:g>‎‏‎‎‏‏‏‎ application info.‎‏‎‎‏‎"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‏‎‏‎‏‏‏‎‎‏‏‏‏‏‏‎‎‏‏‎‎‏‏‎‏‏‏‏‎‎‏‏‏‏‎‏‏‎‏‏‎‎‎‎‏‎‎‏‎‏‏‏‎‏‏‏‏‏‎Starting ‎‏‎‎‏‏‎<xliff:g id="APP">%s</xliff:g>‎‏‎‎‏‏‏‎.‎‏‎‎‏‎"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‏‏‏‎‏‎‎‏‎‎‏‏‎‎‎‎‎‎‎‎‏‏‏‏‏‏‎‏‏‎‎‎‎‎‎‎‏‎‎‎‏‎‏‏‎‎‎‎‏‎‏‏‎‎‏‏‏‏‏‏‎No recent items‎‏‎‎‏‎"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‎‏‏‎‏‎‏‏‎‏‎‏‎‎‏‎‎‎‎‏‎‏‏‏‎‎‏‎‏‏‏‎‎‎‎‏‏‎‏‎‏‏‎‎‏‎‎‎‎‎‎‏‎‏‏‏‏‏‎You\'ve cleared everything‎‏‎‎‏‎"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‏‎‎‏‎‎‏‏‎‎‎‏‏‎‎‏‎‏‏‎‎‏‏‏‏‎‏‎‏‏‏‏‏‎‏‏‎‎‏‎‎‏‎‏‎‎‎‎‎‏‏‏‎‎‎‎‏‎‏‎‎Application Info‎‏‎‎‏‎"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‏‎‎‎‏‏‏‏‏‎‎‎‎‎‎‏‎‎‎‏‎‎‎‏‏‎‏‏‏‏‎‎‏‏‏‎‏‏‎‏‎‎‎‎‏‎‏‎‏‎‏‎‎‏‏‎‏‎‏‎screen pinning‎‏‎‎‏‎"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‎‎‏‏‎‏‏‎‏‏‎‎‎‏‏‎‎‏‏‎‏‏‎‏‏‎‏‏‏‏‏‏‎‏‎‎‏‏‎‏‎‏‏‎‎‏‎‎‏‎‎‏‎‏‎‏‎‏‎search‎‏‎‎‏‎"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‏‏‏‎‎‏‏‎‎‏‎‏‏‏‏‏‏‏‎‎‏‎‎‏‏‎‏‎‏‏‎‏‏‏‎‏‏‏‎‏‎‎‏‎‏‏‎‎‏‎‎‎‏‎‏‏‏‏‎‎‎Could not start ‎‏‎‎‏‏‎<xliff:g id="APP">%s</xliff:g>‎‏‎‎‏‏‏‎.‎‏‎‎‏‎"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‏‏‎‏‏‏‏‎‎‎‎‎‏‎‏‏‏‎‏‎‎‎‎‎‏‏‎‎‎‎‏‎‎‏‏‏‏‏‎‏‏‎‎‏‎‏‎‎‎‏‏‏‎‏‏‎‏‏‎‎‏‎‎‏‏‎<xliff:g id="APP">%s</xliff:g>‎‏‎‎‏‏‏‎ is disabled in safe-mode.‎‏‎‎‏‎"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‏‏‎‏‏‎‎‏‏‎‎‎‎‎‎‏‏‏‎‎‏‏‎‎‎‎‎‎‏‎‏‎‏‏‎‎‎‎‎‎‎‏‎‏‏‏‎‏‎‎‏‎‎‏‏‎‎‏‎Clear all‎‏‎‎‏‎"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‎‎‎‏‏‏‏‎‎‎‏‎‏‎‎‎‏‏‎‎‏‏‏‎‏‎‏‎‏‎‏‎‎‏‎‎‎‎‏‏‎‎‎‎‏‎‏‏‎‎‎‏‎‎‏‎‎‎‎Drag here to use split screen‎‏‎‎‏‎"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‎‏‏‏‏‎‏‏‎‎‏‎‎‏‎‎‏‏‏‎‏‏‏‏‎‎‏‎‏‏‎‎‎‎‏‏‏‏‏‎‏‏‏‏‏‎‏‏‏‎‏‎‏‎‎‏‏‎‏‎‏‏‎Split Horizontal‎‏‎‎‏‎"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‏‎‏‎‏‎‏‏‎‎‎‎‎‎‎‎‏‏‎‎‎‏‏‎‎‎‎‏‏‏‎‏‏‏‏‎‏‏‎‏‏‏‎‏‏‎‏‏‏‎‎‏‎‎‏‏‎‏‎Split Vertical‎‏‎‎‏‎"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‎‏‏‎‎‏‎‎‎‎‎‏‏‏‎‏‎‏‏‎‎‎‏‏‎‎‎‎‎‏‏‏‏‏‏‎‏‏‏‎‎‎‎‏‎‎‏‏‎‏‎‏‎‎‏‎‏‎‏‏‎Split Custom‎‏‎‎‏‎"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‏‎‎‏‏‏‎‎‎‎‎‏‏‏‎‎‎‎‎‎‏‎‎‏‏‎‎‎‎‎‎‎‏‏‏‎‏‏‏‎‎‎‏‎‎‏‏‏‏‎‏‏‎‎‎‏‏‏‎‎‎Split screen to the top‎‏‎‎‏‎"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‏‎‎‎‎‎‎‏‏‏‎‎‏‎‏‏‎‎‎‎‎‏‎‎‎‏‎‏‎‏‎‏‏‎‎‏‏‎‏‎‎‎‎‏‏‏‏‎‏‏‎‎‏‎‎‏‎‎‎Split screen to the left‎‏‎‎‏‎"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‏‎‎‏‏‎‏‎‎‏‏‏‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‎‎‎‎‏‎‏‏‎‏‏‏‎‏‎‎‏‎‏‎‎‎‎‎‏‎‏‎‎Split screen to the right‎‏‎‎‏‎"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-es-rUS/strings.xml b/packages/SystemUI/legacy/recents/res/values-es-rUS/strings.xml
deleted file mode 100644
index f212b02..0000000
--- a/packages/SystemUI/legacy/recents/res/values-es-rUS/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Recientes"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Permite descartar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Se descartó <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Se descartaron todas las aplicaciones recientes."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Permite abrir la información de la aplicación de <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Iniciando <xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"No hay elementos recientes"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Todo borrado"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Información de la aplicación"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"Fijar pantalla"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"Buscar"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"No se pudo iniciar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> está inhabilitada en modo seguro."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Borrar todo"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arrastra hasta aquí para usar la pantalla dividida"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"División horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"División vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"División personalizada"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Dividir pantalla en la parte superior"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Dividir pantalla a la izquierda"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Dividir pantalla a la derecha"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-es/strings.xml b/packages/SystemUI/legacy/recents/res/values-es/strings.xml
deleted file mode 100644
index 8bcfe84..0000000
--- a/packages/SystemUI/legacy/recents/res/values-es/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Aplicaciones recientes."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Cerrar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Se ha ignorado la aplicación <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Se han ignorado todas las aplicaciones recientes."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Abre la información de la aplicación <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Iniciando la aplicación <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"No hay elementos recientes"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Has borrado todo"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Información de la aplicación"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"fijar pantalla"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"buscar"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"No se ha podido iniciar la aplicación <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"La aplicación <xliff:g id="APP">%s</xliff:g> se ha inhabilitado en modo seguro."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Borrar todo"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arrastra el elemento hasta aquí para utilizar la pantalla dividida"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"División horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"División vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"División personalizada"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Dividir la pantalla en la parte superior"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Dividir la pantalla a la izquierda"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Dividir la pantalla a la derecha"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-et/strings.xml b/packages/SystemUI/legacy/recents/res/values-et/strings.xml
deleted file mode 100644
index c1903af..0000000
--- a/packages/SystemUI/legacy/recents/res/values-et/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Ülevaade."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Rakendusest <xliff:g id="APP">%s</xliff:g> loobumine."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Rakendusest <xliff:g id="APP">%s</xliff:g> on loobutud."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Kõikidest hiljutistest rakendustest on loobutud."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Rakenduse <xliff:g id="APP">%s</xliff:g> teabe avamine."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Rakenduse <xliff:g id="APP">%s</xliff:g> käivitamine."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Hiljutisi üksusi pole"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Olete kõik ära kustutanud"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Rakenduse teave"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ekraanikuva kinnitamine"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"otsi"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Rakendust <xliff:g id="APP">%s</xliff:g> ei saanud käivitada."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Rakendus <xliff:g id="APP">%s</xliff:g> on turvarežiimis keelatud."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Kustuta kõik"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Jagatud ekraani kasutamiseks lohistage siia"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Horisontaalne poolitamine"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Vertikaalne poolitamine"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Kohandatud poolitamine"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Poolita ekraan üles"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Poolita ekraan vasakule"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Poolita ekraan paremale"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-eu/strings.xml b/packages/SystemUI/legacy/recents/res/values-eu/strings.xml
deleted file mode 100644
index 91e250f..0000000
--- a/packages/SystemUI/legacy/recents/res/values-eu/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Ikuspegi orokorra."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Baztertu <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Baztertu da <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Baztertu dira azken aplikazio guztiak."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Ireki <xliff:g id="APP">%s</xliff:g> aplikazioari buruzko informazioa."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> abiarazten."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Ez dago azkenaldi honetako ezer"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Dena garbitu duzu"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Aplikazioaren informazioa"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"pantaila-ainguratzea"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"bilatu"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Ezin izan da abiarazi <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> desgaituta dago modu seguruan."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Garbitu guztiak"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arrastatu hona pantaila zatitzeko"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Zatitze horizontala"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Zatitze bertikala"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Zatitze pertsonalizatua"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Zatitu pantaila eta ezarri goian"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Zatitu pantaila eta ezarri ezkerrean"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Zatitu pantaila eta ezarri eskuinean"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-fa/strings.xml b/packages/SystemUI/legacy/recents/res/values-fa/strings.xml
deleted file mode 100644
index 61e87c1..0000000
--- a/packages/SystemUI/legacy/recents/res/values-fa/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"نمای کلی."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"رد کردن <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> نادیده گرفته شد."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"همه برنامه‌های اخیر رد شدند."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"باز کردن اطلاعات برنامه <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> درحال شروع به کار است."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"بدون موارد اخیر"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"همه‌چیز را پاک کرده‌اید"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"اطلاعات برنامه"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"پین کردن صفحه"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"جستجو"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> شروع نشد."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> در حالت ایمن غیرفعال است."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"پاک کردن همه"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"برای استفاده از تقسیم صفحه، به اینجا بکشید"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"تقسیم افقی"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"تقسیم عمودی"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"سفارشی کردن تقسیم"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"تقسیم کردن صفحه به بالا"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"تقسیم کردن صفحه به چپ"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"تقسیم کردن صفحه به راست"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-fi/strings.xml b/packages/SystemUI/legacy/recents/res/values-fi/strings.xml
deleted file mode 100644
index bf2e461..0000000
--- a/packages/SystemUI/legacy/recents/res/values-fi/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Viimeisimmät"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Hylkää <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> hylättiin."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Kaikki viimeisimmät sovellukset on hylätty."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Avaa sovelluksen <xliff:g id="APP">%s</xliff:g> tiedot."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Käynnistetään <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Ei viimeaikaisia kohteita"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Kaikki on hoidettu"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Sovellustiedot"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"näytön kiinnitys"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"haku"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ei käynnistynyt."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> on poistettu käytöstä vikasietotilassa."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Poista kaikki"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Jaa näyttö vetämällä tähän."</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Vaakasuuntainen jako"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Pystysuuntainen jako"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Oma jako"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Jaa näyttö ylös"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Jaa näyttö vasemmalle"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Jaa näyttö oikealle"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-fr-rCA/strings.xml b/packages/SystemUI/legacy/recents/res/values-fr-rCA/strings.xml
deleted file mode 100644
index e60727e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-fr-rCA/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Aperçu"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Supprimer <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> supprimée."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Toutes les applications récentes ont été supprimées."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Ouvre les détails de l\'application <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Lancement de <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Aucun élément récent"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Vous avez tout effacé"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Détails de l\'application"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"épinglage d\'écran"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"rechercher"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Impossible de lancer <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> est désactivée en mode sans échec."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Tout effacer"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Glissez l\'élément ici pour utiliser l\'écran partagé"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Séparation horizontale"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Séparation verticale"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Séparation personnalisée"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Écran partagé dans le haut"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Écran partagé à la gauche"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Écran partagé à la droite"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-fr/strings.xml b/packages/SystemUI/legacy/recents/res/values-fr/strings.xml
deleted file mode 100644
index 5b0d611..0000000
--- a/packages/SystemUI/legacy/recents/res/values-fr/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Aperçu"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Supprimer l\'application <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Application <xliff:g id="APP">%s</xliff:g> supprimée."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Toutes les applications récentes ont été supprimées."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Ouvre les informations sur l\'application <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Lancement de l\'application <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Aucun élément récent"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Vous avez tout effacé"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informations sur l\'application"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"épinglage d\'écran"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"rechercher"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Impossible de lancer l\'application <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"L\'application <xliff:g id="APP">%s</xliff:g> est désactivée en mode sécurisé."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Tout fermer"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Faire glisser ici pour utiliser l\'écran partagé"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Séparation horizontale"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Séparation verticale"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Séparation personnalisée"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Partager l\'écran en haut"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Partager l\'écran sur la gauche"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Partager l\'écran sur la droite"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-gl/strings.xml b/packages/SystemUI/legacy/recents/res/values-gl/strings.xml
deleted file mode 100644
index 008c776..0000000
--- a/packages/SystemUI/legacy/recents/res/values-gl/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Visión xeral."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Rexeita <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Rexeitouse <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Rexeitáronse todas as aplicacións recentes."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Abre a información da aplicación <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Iniciando <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Non hai elementos recentes"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Borraches todo"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Información da aplicación"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"fixación de pantalla"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"buscar"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Non se puido iniciar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"A aplicación <xliff:g id="APP">%s</xliff:g> está desactivada no modo seguro."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Borrar todo"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arrastra aquí para usar a pantalla dividida"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Dividir horizontalmente"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Dividir verticalmente"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Dividir de xeito personalizado"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Dividir pantalla arriba"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Dividir pantalla á esquerda"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Dividir pantalla á dereita"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-gu/strings.xml b/packages/SystemUI/legacy/recents/res/values-gu/strings.xml
deleted file mode 100644
index 33dc7e8..0000000
--- a/packages/SystemUI/legacy/recents/res/values-gu/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"ઝલક."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> કાઢી નાખો."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> કાઢી નાખી."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"તાજેતરની બધી ઍપ્લિકેશનો કાઢી નાખવામાં આવી."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g>ની ઍપ્લિકેશન માહિતી ખોલો."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g>ને શરૂ કરી રહ્યાં છીએ."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"તાજેતરની કોઈ આઇટમ નથી"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"તમે બધું સાફ કર્યું"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ઍપ્લિકેશનની માહિતી"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"સ્ક્રીન પિનિંગ"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"શોધો"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>ને શરૂ કરી શકાઈ નથી."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"સુરક્ષિત મોડમાં <xliff:g id="APP">%s</xliff:g>ને બંધ કરવામાં આવી છે."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"બધું સાફ કરો"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"વિભાજિત સ્ક્રીનનો ઉપયોગ કરવા માટે અહીં ખેંચો"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"સ્ક્રીનને આડી વિભાજિત કરો"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"સ્ક્રીનને ઊભી વિભાજિત કરો"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"સ્ક્રીનને કસ્ટમ વિભાજિત કરો"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"સ્ક્રીનને ઉપરની તરફ વિભાજિત કરો"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"સ્ક્રીનને ડાબી તરફ વિભાજિત કરો"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"સ્ક્રીનને જમણી તરફ વિભાજિત કરો"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-hi/strings.xml b/packages/SystemUI/legacy/recents/res/values-hi/strings.xml
deleted file mode 100644
index 3f19f33..0000000
--- a/packages/SystemUI/legacy/recents/res/values-hi/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"खास जानकारी."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> को खारिज करें."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> खारिज किया गया."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"हाल के सभी ऐप्लिकेशन खारिज कर दिए गए हैं."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ऐप्लिकेशन की जानकारी खोलें."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> शुरू किया जा रहा है."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"हाल का कोई आइटम नहीं है"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"आपने सब कुछ हटा दिया है"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ऐप्लिकेशन की जानकारी"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"स्क्रीन पिन करना"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"खोजें"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> शुरू नहीं किया जा सका."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> को सुरक्षित-मोड में बंद किया गया."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"सभी ऐप्लिकेशन बंद करें"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"स्क्रीन को दो हिस्सों में बाँटने (स्प्लिट स्क्रीन) के लिए यहां से खींचें और छोड़ें"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"क्षैतिज रूप से दो हिस्सों में बाँटें (स्प्लिट करें)"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"लम्बवत रूप से दो हिस्सों में बाँटें (स्प्लिट करें)"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"अपने मुताबिक दो हिस्सों में बाँटें (स्प्लिट स्क्रीन करें)"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"ऊपर की ओर दूसरी स्क्रीन बनाएं"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"बाईं ओर दूसरी स्क्रीन बनाएं"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"दाईं ओर दूसरी स्क्रीन बनाएं"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-hr/strings.xml b/packages/SystemUI/legacy/recents/res/values-hr/strings.xml
deleted file mode 100644
index 88926a4..0000000
--- a/packages/SystemUI/legacy/recents/res/values-hr/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Pregled."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Odbacivanje aplikacije <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Odbačena je aplikacija <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Odbačene su sve nedavne aplikacije."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Otvaranje informacija o aplikaciji <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Pokreće se aplikacija <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nema nedavnih stavki"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Izbrisali ste sve"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informacije o aplikaciji"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"prikačivanje zaslona"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"pretraživanje"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Aplikacija <xliff:g id="APP">%s</xliff:g> nije pokrenuta."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplikacija <xliff:g id="APP">%s</xliff:g> onemogućena je u sigurnom načinu."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Izbriši sve"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Povucite ovdje da biste upotrebljavali podijeljeni zaslon"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Podijeli vodoravno"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Podijeli okomito"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Podijeli prilagođeno"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Podijeli zaslon na vrhu"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Podijeli zaslon slijeva"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Podijeli zaslon zdesna"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-hu/strings.xml b/packages/SystemUI/legacy/recents/res/values-hu/strings.xml
deleted file mode 100644
index d0429e7..0000000
--- a/packages/SystemUI/legacy/recents/res/values-hu/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Áttekintés."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"A(z) <xliff:g id="APP">%s</xliff:g> elvetése."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> eltávolítva."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Az összes alkalmazás eltávolítva a nemrég használtak közül."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"A(z) <xliff:g id="APP">%s</xliff:g> alkalmazás adatainak megnyitása."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"A(z) <xliff:g id="APP">%s</xliff:g> indítása."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nincsenek mostanában használt elemek"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Mindent törölt"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Az alkalmazás adatai"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"képernyő rögzítése"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"keresés"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Nem lehet elindítani a következőt: <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"A(z) <xliff:g id="APP">%s</xliff:g> csökkentett módban le van tiltva."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Összes törlése"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Húzza ide az osztott képernyő használatához"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Osztott vízszintes"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Osztott függőleges"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Osztott egyéni"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Osztott képernyő felülre"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Osztott képernyő balra"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Osztott képernyő jobbra"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-hy/strings.xml b/packages/SystemUI/legacy/recents/res/values-hy/strings.xml
deleted file mode 100644
index c56b691..0000000
--- a/packages/SystemUI/legacy/recents/res/values-hy/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Համատեսք:"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Հեռացնել <xliff:g id="APP">%s</xliff:g> հավելվածը ցուցակից:"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> հավելվածը հեռացվել է ցուցակից:"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Բոլոր վերջին հավելվածները հեռացվել են ցուցակից:"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Բացել <xliff:g id="APP">%s</xliff:g> հավելվածի մասին տեղեկությունները"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> հավելվածը գործարկվում է:"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Այստեղ դեռ ոչինչ չկա"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Ցուցակը դատարկ է"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Հավելվածի մասին"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"էկրանի ամրացում"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"որոնում"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Չհաջողվեց գործարկել <xliff:g id="APP">%s</xliff:g> հավելվածը:"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> հավելվածը անվտանգ ռեժիմում անջատված է:"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Ջնջել բոլորը"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Քաշեք այստեղ՝ էկրանի տրոհումն օգտագործելու համար"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Հորիզոնական տրոհում"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Ուղղահայաց տրոհում"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Հատուկ տրոհում"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Տրոհել էկրանը վերևից"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Տրոհել էկրանը ձախից"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Տրոհել էկրանն աջից"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-in/strings.xml b/packages/SystemUI/legacy/recents/res/values-in/strings.xml
deleted file mode 100644
index aa9dcfe..0000000
--- a/packages/SystemUI/legacy/recents/res/values-in/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Ringkasan."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Hapus <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> dihapus."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Semua aplikasi yang baru dibuka telah dihapus."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Buka info aplikasi <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Memulai <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Tidak ada item yang baru dibuka"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Anda sudah menghapus semua"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Info Aplikasi"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"pin ke layar"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"telusuri"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Tidak dapat memulai <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> dinonaktifkan dalam mode aman."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Hapus semua"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Tarik ke sini untuk menggunakan layar terpisah"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Pisahkan Horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Pisahkan Vertikal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Pisahkan Khusus"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Pisahkan layar ke atas"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Pisahkan layar ke kiri"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Pisahkan layar ke kanan"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-is/strings.xml b/packages/SystemUI/legacy/recents/res/values-is/strings.xml
deleted file mode 100644
index e0a555e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-is/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Yfirlit."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Fjarlægja <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> fjarlægt."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Öll nýleg forrit fjarlægð."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Opna forritsupplýsingar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Ræsir <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Engin nýleg atriði"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Þú hefur hreinsað allt"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Forritsupplýsingar"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"skjáfesting"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"leita"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Ekki var hægt að ræsa <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Slökkt er á <xliff:g id="APP">%s</xliff:g> í öruggri stillingu."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Hreinsa allt"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Dragðu hingað til að skipta skjánum"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Lárétt skipting"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Lóðrétt skipting"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Sérsniðin skipting"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Skipta skjá að ofanverðu"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Skipta skjá til vinstri"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Skipta skjá til hægri"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-it/strings.xml b/packages/SystemUI/legacy/recents/res/values-it/strings.xml
deleted file mode 100644
index e04d560..0000000
--- a/packages/SystemUI/legacy/recents/res/values-it/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Panoramica."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Elimina <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> eliminata."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Tutte le applicazioni recenti sono state rimosse."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Mostra informazioni sull\'applicazione <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Avvio di <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nessun elemento recente"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Hai cancellato tutto"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informazioni sull\'applicazione"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"blocco su schermo"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"cerca"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Impossibile avviare <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"L\'app <xliff:g id="APP">%s</xliff:g> è stata disattivata in modalità provvisoria."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Cancella tutto"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Trascina qui per utilizzare la modalità Schermo diviso"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Divisione in orizzontale"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Divisione in verticale"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Divisione personalizzata"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Schermo diviso in alto"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Schermo diviso a sinistra"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Schermo diviso a destra"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-iw/strings.xml b/packages/SystemUI/legacy/recents/res/values-iw/strings.xml
deleted file mode 100644
index a96c709..0000000
--- a/packages/SystemUI/legacy/recents/res/values-iw/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"סקירה כללית."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"הסרה של <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> הוסרה."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"כל האפליקציות האחרונות הוסרו."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"פתיחת מידע על האפליקציה <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"מפעיל את <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"אין פריטים אחרונים"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"מחקת הכול"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"מידע על האפליקציה"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"הקפאת מסך"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"חיפוש"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"לא ניתן היה להפעיל את <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> מושבתת במצב בטוח."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ניקוי הכול"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"יש לגרור לכאן כדי להשתמש במסך מפוצל"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"פיצול אופקי"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"פיצול אנכי"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"פיצול מותאם אישית"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"פיצול מסך למעלה"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"פיצול מסך לשמאל"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"פיצול מסך לימין"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ja/strings.xml b/packages/SystemUI/legacy/recents/res/values-ja/strings.xml
deleted file mode 100644
index 4d7524c..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ja/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"最近"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g>を削除します。"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g>を削除しました。"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"最近のアプリをすべて削除しました。"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g>のアプリ情報を開きます。"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g>を開始しています。"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"最近のアイテムはありません"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"すべてのタスクを削除しました"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"アプリ情報"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"画面固定"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"検索"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>を開始できませんでした。"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g>はセーフモードでは無効になります。"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"すべて消去"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"分割画面を使用するにはここにドラッグします"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"横に分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"縦に分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"分割(カスタム)"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"画面を上に分割"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"画面を左に分割"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"画面を右に分割"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ka/strings.xml b/packages/SystemUI/legacy/recents/res/values-ka/strings.xml
deleted file mode 100644
index 088388b..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ka/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"მიმოხილვა"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g>-ის დახურვა."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> დაიხურა."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"ყველა ბოლოდროინდელი აპლიკაცია დაიხურა."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> აპლიკაციის ინფორმაციის გახსნა."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"მიმდინარეობს <xliff:g id="APP">%s</xliff:g>-ის გაშვება."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ბოლოდროინდელი ერთეულები არ არის"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"ყველაფერი გასუფთავდა"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"აპლიკაციის ინფორმაცია"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ეკრანზე ჩამაგრება"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ძიება"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>-ის გაშვება ვერ მოხერხდა."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> გათიშულია უსაფრთხო რეჟიმში."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ყველას გასუფთავება"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"ეკრანის გასაყოფად ჩავლებით გადმოიტანეთ აქ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"ჰორიზონტალური გაყოფა"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ვერტიკალური გაყოფა"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"მორგებული გაყოფა"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"ეკრანის გაყოფა ზემოთ"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"ეკრანის გაყოფა მარცხნივ"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"ეკრანის გაყოფა მარჯვნივ"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-kk/strings.xml b/packages/SystemUI/legacy/recents/res/values-kk/strings.xml
deleted file mode 100644
index 9d4e01c..0000000
--- a/packages/SystemUI/legacy/recents/res/values-kk/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Жалпы ақпарат."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> қолданбасын өшіру."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> өшірілді."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Барлық қолданбалар \"Соңғылар\" тізімінен өшірілді."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> қолданбасы туралы ақпаратты ашу."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> іске қосылды."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Ешқандай соңғы элементтер жоқ"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Барлығын өшірдіңіз"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Қолданба туралы ақпарат"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"экранды бекіту"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"іздеу"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> іске қосылмады."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> қауіпсіз режимде өшіріледі."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Барлығын өшіру"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Экранды бөлу үшін осы жерге сүйреңіз"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Көлденеңінен бөлу"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Тігінен бөлу"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Бөлу (арнаулы)"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Экранды жоғары жағынан бөлу"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Экранды сол жағынан бөлу"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Экранды оң жағынан бөлу"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-km/strings.xml b/packages/SystemUI/legacy/recents/res/values-km/strings.xml
deleted file mode 100644
index b7bfba6..0000000
--- a/packages/SystemUI/legacy/recents/res/values-km/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"ទិដ្ឋភាពរួម។"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"ច្រានចោល <xliff:g id="APP">%s</xliff:g> ។"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"បាន​ច្រានចោល <xliff:g id="APP">%s</xliff:g> ។"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"បាន​ច្រានចោល​កម្មវិធីថ្មីៗ​ទាំងអស់។"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"បើក​ព័ត៌មាន​កម្មវិធី <xliff:g id="APP">%s</xliff:g> ។"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"កំពុង​ចាប់ផ្ដើម <xliff:g id="APP">%s</xliff:g> ។"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"មិនមានធាតុថ្មីៗទេ"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"អ្នក​បានសម្អាត​អ្វីៗ​គ្រប់យ៉ាង"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ព័ត៌មាន​កម្មវិធី"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ការ​ភ្ជាប់​អេក្រង់"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ស្វែង​រក"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"មិន​អាច​ចាប់ផ្ដើម <xliff:g id="APP">%s</xliff:g> បានទេ។"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ត្រូវបាន​បិទ​ដំណើរការ​ក្នុងមុខងារ​សុវត្ថិភាព។"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"សម្អាត​ទាំងអស់"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"អូសនៅទីនេះដើម្បីប្រើអេក្រង់បំបែក"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"បំបែកផ្តេក"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"បំបែកបញ្ឈរ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"បំបែកផ្ទាល់ខ្លួន"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"បំបែក​អេក្រង់​ទៅ​ខាងលើ"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"បំបែក​អេក្រង់​ទៅ​ខាងឆ្វេង"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"បំបែក​អេក្រង់​ទៅ​ខាងស្តាំ"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-kn/strings.xml b/packages/SystemUI/legacy/recents/res/values-kn/strings.xml
deleted file mode 100644
index 84894c1..0000000
--- a/packages/SystemUI/legacy/recents/res/values-kn/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"ಸಮಗ್ರ ನೋಟ."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> ವಜಾಗೊಳಿಸಿ."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ವಜಾಗೊಳಿಸಲಾಗಿದೆ."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"ಇತ್ತೀಚಿನ ಎಲ್ಲಾ ಆ್ಯಪ್‌ಗಳನ್ನು ವಜಾಗೊಳಿಸಲಾಗಿದೆ."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ಆ್ಯಪ್ ಮಾಹಿತಿ ತೆರೆಯಿರಿ."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ಪ್ರಾರಂಭಿಸಲಾಗುತ್ತಿದೆ."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ಯಾವುದೇ ಇತ್ತೀಚಿನ ಐಟಂಗಳಿಲ್ಲ"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"ನೀವು ಎಲ್ಲವನ್ನೂ ತೆರವುಗೊಳಿಸಿರುವಿರಿ"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ಆ್ಯಪ್ ಮಾಹಿತಿ"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ಸ್ಕ್ರೀನ್ ಪಿನ್ನಿಂಗ್"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ಹುಡುಕಾಟ"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ಪ್ರಾರಂಭಿಸಲು ಸಾದ್ಯವಾಗಲಿಲ್ಲ."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ಅನ್ನು ಸುರಕ್ಷಿತ ಮೋಡ್‌ನಲ್ಲಿ ನಿಷ್ಕ್ರಿಯಗೊಳಿಸಲಾಗಿದೆ."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ಎಲ್ಲವನ್ನೂ ತೆರವುಗೊಳಿಸಿ"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"ವಿಭಜಿತ ಸ್ಕ್ರೀನ್ ಅನ್ನು ಬಳಸಲು ಇಲ್ಲಿ ಡ್ರ್ಯಾಗ್‌ ಮಾಡಿ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"ಅಡ್ಡಲಾಗಿ ವಿಭಜಿಸಿದ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ಲಂಬವಾಗಿ ವಿಭಜಿಸಿದ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"ಕಸ್ಟಮ್ ವಿಭಜಿಸಿದ"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"ಮೇಲ್ಭಾಗಕ್ಕೆ ಸ್ಕ್ರೀನ್ ಅನ್ನು ವಿಭಜಿಸಿ"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"ಎಡಕ್ಕೆ ಸ್ಕ್ರೀನ್ ಅನ್ನು ವಿಭಜಿಸಿ"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"ಬಲಕ್ಕೆ ಸ್ಕ್ರೀನ್ ಅನ್ನು ವಿಭಜಿಸಿ"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ko/strings.xml b/packages/SystemUI/legacy/recents/res/values-ko/strings.xml
deleted file mode 100644
index ee856bd..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ko/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"최근 사용"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g>을(를) 닫습니다."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> 애플리케이션을 닫았습니다."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"최근 사용한 애플리케이션을 모두 닫았습니다."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> 애플리케이션 정보를 엽니다."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g>을(를) 시작하는 중입니다."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"최근 항목이 없습니다."</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"모든 항목을 삭제했습니다."</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"애플리케이션 정보"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"화면 고정"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"검색"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>을(를) 시작할 수 없습니다."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g>은(는) 안전 모드에서 사용 중지됩니다."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"모두 삭제"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"여기를 드래그하여 분할 화면 사용하기"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"수평 분할"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"수직 분할"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"맞춤 분할"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"위쪽으로 화면 분할"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"왼쪽으로 화면 분할"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"오른쪽으로 화면 분할"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ky/strings.xml b/packages/SystemUI/legacy/recents/res/values-ky/strings.xml
deleted file mode 100644
index 879e492..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ky/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Сереп салуу."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> колдонмосун өчүрүү."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> колдонмосу өчүрүлдү."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Акыркы колдонмолордун баары өчүрүлдү."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> колдонмосу жөнүндө маалыматты ачыңыз."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ачылууда."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Акыркы колдонмолор жок"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Баарын тазаладыңыз"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Колдонмо жөнүндө маалымат"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"экран кадоо"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"издөө"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> колдонмосу ачылган жок"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> коопсуз режиминде өчүрүлдү."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Баарын тазалоо"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Экранды бөлүү үчүн бул жерге сүйрөңүз"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Туурасынан бөлүү"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Тигинен бөлүү"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Ыңгайлаштырылган бөлүү"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Экранды өйдө жакка бөлүү"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Экранды сол жакка бөлүү"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Экранды оң жакка бөлүү"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-lo/strings.xml b/packages/SystemUI/legacy/recents/res/values-lo/strings.xml
deleted file mode 100644
index 17f56b4..0000000
--- a/packages/SystemUI/legacy/recents/res/values-lo/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"ພາບຮວມ."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"ປິດ <xliff:g id="APP">%s</xliff:g> ໄວ້."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"ປິດ <xliff:g id="APP">%s</xliff:g> ແລ້ວ."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"ທຸກແອັບພລິເຄຊັນບໍ່ດົນມານີ້ຖືກປິດໄວ້ແລ້ວ."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"ເປີດຂໍ້ມູນແອັບພລິເຄຊັນ <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"ກຳລັງເປີດ <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ບໍ່ມີລາຍການຫຼ້າສຸດ"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"ທ່ານລຶບລ້າງທຸກຢ່າງແລ້ວ"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ຂໍ້ມູນແອັບພລິເຄຊັນ"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ການປັກໝຸດໜ້າຈໍ"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ຊອກຫາ"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"ບໍ່ສາມາດເລີ່ມ <xliff:g id="APP">%s</xliff:g> ໄດ້."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ຖືກປິດໃຊ້ໃນໂໝດຄວາມມປອດໄພ."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ລຶບລ້າງທັງໝົດ"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"ລາກມາບ່ອນນີ້ເພື່ອໃຊ້ການແບ່ງໜ້າຈໍ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"ການແຍກລວງຂວາງ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ການແຍກລວງຕັ້ງ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"ການແຍກກຳນົດເອງ"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"ແຍກໜ້າຈໍໄປທາງເທິງ"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"ແຍກໜ້າຈໍໄປທາງຊ້າຍ"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"ແຍກໜ້າຈໍໄປທາງຂວາ"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-lt/strings.xml b/packages/SystemUI/legacy/recents/res/values-lt/strings.xml
deleted file mode 100644
index 4a9eb83..0000000
--- a/packages/SystemUI/legacy/recents/res/values-lt/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Apžvalga."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Atsisakyti programos „<xliff:g id="APP">%s</xliff:g>“."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Atsisakyta programos „<xliff:g id="APP">%s</xliff:g>“."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Atsisakyta visų naujausių programų."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Atidaryti programos „<xliff:g id="APP">%s</xliff:g>“ informaciją."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Paleidžiama programa „<xliff:g id="APP">%s</xliff:g>“."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nėra jokių naujausių elementų"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Viską išvalėte"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Programos informacija"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ekrano prisegimas"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ieškoti"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Nepavyko paleisti programos „<xliff:g id="APP">%s</xliff:g>“."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Programa „<xliff:g id="APP">%s</xliff:g>“ išjungta saugos režimu."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Išvalyti viską"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Vilkite čia, kad naudotumėte skaidytą ekraną"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Horizontalus skaidymas"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Vertikalus skaidymas"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Tinkintas skaidymas"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Skaidyti ekraną į viršų"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Skaidyti ekraną į kairę"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Skaidyti ekraną į dešinę"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-lv/strings.xml b/packages/SystemUI/legacy/recents/res/values-lv/strings.xml
deleted file mode 100644
index 7d87e00..0000000
--- a/packages/SystemUI/legacy/recents/res/values-lv/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Pārskats."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Nerādīt lietotni <xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Vairs netiek rādīta lietotne <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Vairs netiek rādīta neviena nesen izmantotā lietojumprogramma."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Atveriet lietojumprogrammas <xliff:g id="APP">%s</xliff:g> informāciju."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Notiek lietotnes <xliff:g id="APP">%s</xliff:g> palaišana."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nav nesenu vienumu"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Visi uzdevumi ir notīrīti"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Lietojumprogrammas informācija"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"Piespraust ekrānu"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"Meklēt"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Nevarēja palaist lietotni <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Lietotne <xliff:g id="APP">%s</xliff:g> ir atspējota drošajā režīmā."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Notīrīt visu"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Velciet šeit, lai izmantotu ekrāna sadalīšanu"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Horizontāls dalījums"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Vertikāls dalījums"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Pielāgots dalījums"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Sadalīt ekrānu augšdaļā"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Sadalīt ekrānu kreisajā pusē"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Sadalīt ekrānu labajā pusē"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-mk/strings.xml b/packages/SystemUI/legacy/recents/res/values-mk/strings.xml
deleted file mode 100644
index d8ced0b..0000000
--- a/packages/SystemUI/legacy/recents/res/values-mk/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Преглед."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Отфрлете ја <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> е отфрлена."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Сите неодамнешни апликации се отфрлени."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Отворете информации за апликацијата <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Се стартува <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Нема неодамнешни ставки"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Избришавте сѐ"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Информации за апликацијата"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"прикачување екран"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"пребарувај"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> не можеше да се стартува."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> е оневозможена во безбеден режим."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Избриши сѐ"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Повлечете тука за да користите поделен екран"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Подели хоризонтално"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Подели вертикално"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Подели приспособено"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Подели го екранот во горниот дел"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Подели го екранот на левата страна"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Подели го екранот на десната страна"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ml/strings.xml b/packages/SystemUI/legacy/recents/res/values-ml/strings.xml
deleted file mode 100644
index 6dd797e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ml/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"അവലോകനം."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> ഡിസ്‌മിസ് ചെയ്യുക."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ഡിസ്‌മിസ് ചെയ്‌തു."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"അടുത്തിടെയുള്ള എല്ലാ ആപ്പുകളും ഡിസ്‌മിസ് ചെയ്‌തു."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ആപ്പ് വിവരങ്ങൾ തുറക്കുക."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ആരംഭിക്കുന്നു."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"സമീപകാല ഇനങ്ങൾ ഒന്നുമില്ല"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"നിങ്ങൾ എല്ലാം മായ്ച്ചിരിക്കുന്നു"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ആപ്പ് വിവരങ്ങൾ"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"സ്ക്രീൻ പിൻ ചെയ്യൽ"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"തിരയുക"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ആരംഭിക്കാനായില്ല"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"സുരക്ഷിത മോഡിൽ <xliff:g id="APP">%s</xliff:g> പ്രവർത്തനരഹിതമാക്കിയിരിക്കുന്നു."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"എല്ലാം മായ്‌ക്കുക"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"സ്പ്ലിറ്റ് സ്ക്രീൻ ഉപയോഗിക്കാൻ, ഇവിടെ വലിച്ചിടുക"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"തിരശ്ചീനമായി സ്‌പ്ലിറ്റ് ചെയ്യുക"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ലംബമായി സ്‌പ്ലിറ്റ് ചെയ്യുക"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"ഇഷ്‌ടാനുസൃതമായി സ്‌പ്ലിറ്റ് ചെയ്യുക"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"സ്ക്രീൻ മുകളിലോട്ട് സ്പ്ലിറ്റ് ചെയ്യുക"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"സ്ക്രീൻ ഇടത്തോട്ട് സ്പ്ലിറ്റ് ചെയ്യുക"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"സ്ക്രീൻ വലത്തോട്ട് സ്‌പ്ലിറ്റ് ചെയ്യുക"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-mn/strings.xml b/packages/SystemUI/legacy/recents/res/values-mn/strings.xml
deleted file mode 100644
index 205f56c..0000000
--- a/packages/SystemUI/legacy/recents/res/values-mn/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Тойм."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g>-г үл хэрэгсэнэ үү."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g>-г үл хэрэгссэн."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Саяхны бүх аппыг үл хэрэгссэн."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> аппын мэдээллийг нээнэ үү."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g>-г эхлүүлж байна."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Саяхны зүйлс алга"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Та бүгдийг нь устгасан"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Аппын мэдээлэл"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"дэлгэц тогтоох"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"хайх"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>-г эхлүүлж чадсангүй."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g>-г аюулгүй горимд идэвхгүй болгосон."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Бүгдийг устгах"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Хуваасан дэлгэцийг ашиглахын тулд энд чирэх"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Хэвтээ чиглэлд хуваах"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Босоо чиглэлд хуваах"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Хүссэн хэлбэрээр хуваах"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Дэлгэцийг дээд хэсэгт хуваах"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Дэлгэцийг зүүн хэсэгт хуваах"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Дэлгэцийг баруун хэсэгт хуваах"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-mr/strings.xml b/packages/SystemUI/legacy/recents/res/values-mr/strings.xml
deleted file mode 100644
index 51bce6d..0000000
--- a/packages/SystemUI/legacy/recents/res/values-mr/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"अवलोकन."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> डिसमिस करा."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> डिसमिस केले"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"अलीकडील सर्व अॅप्लिकेशन डिसमिस झाले."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> अॅप्लिकेशन माहिती उघडा."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> सुरू करत आहे."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"कोणतेही अलीकडील आयटम नाहीत"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"तुम्ही सर्वकाही साफ केले"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"अॅप्लिकेशन माहिती"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"स्‍क्रीन पिन करणे"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"शोधा"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> सुरू करता आले नाही."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> सुरक्षित मोडमध्ये बंद केले आहे."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"सर्व साफ करा"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"स्प्लिट स्क्रीन वापर करण्यासाठी येथे ड्रॅग करा"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"आडवे स्प्लिट करा"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"उभे स्प्लिट करा"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"कस्टम स्प्लिट करा"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"स्क्रीन वर स्प्लिट करा"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"स्क्रीन डावीकडे स्प्लिट करा"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"स्क्रीन उजवीकडे स्प्लिट करा"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ms/strings.xml b/packages/SystemUI/legacy/recents/res/values-ms/strings.xml
deleted file mode 100644
index ae4461d..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ms/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Ikhtisar."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Ketepikan <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> diketepikan."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Semua aplikasi terbaharu diketepikan."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Buka maklumat aplikasi <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Memulakan <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Tiada item terbaharu"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Anda telah mengetepikan semua item"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Maklumat Aplikasi"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"penyematan skrin"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"cari"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Tidak dapat memulakan <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> dilumpuhkan dalam mod selamat."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Kosongkan semua"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Seret ke sini untuk menggunakan skrin pisah"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Pisah Mendatar"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Pisah Menegak"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Pisah Tersuai"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Pisahkan skrin ke atas"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Pisahkan skrin ke kiri"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Pisahkan skrin ke kanan"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-my/strings.xml b/packages/SystemUI/legacy/recents/res/values-my/strings.xml
deleted file mode 100644
index 7b5870e1..0000000
--- a/packages/SystemUI/legacy/recents/res/values-my/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"အနှစ်ချုပ်။"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> ကို ပယ်မည်။"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ကို ဖယ်ထုတ်ထားသည်။"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"လတ်တလော အပလီကေးရှင်းအားလုံး ဖယ်ထုတ်ထားသည်။"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> အပလီကေးရှင်း အချက်အလက်ကို ဖွင့်မည်။"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ကို စတင်နေသည်။"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"လတ်တလော ဖွင့်ထားသည်များ မရှိပါ"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"အားလုံးကို ဖယ်ရှားပြီးပါပြီ"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"အပလီကေးရှင်း အချက်အလက်"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"မျက်နှာပြင် ပင်ထိုးမှု"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ရှာရန်"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ကို စတင်၍ မရပါ။"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"အန္တရာယ်ကင်းမှု စနစ်တွင် <xliff:g id="APP">%s</xliff:g> ကို ပိတ်ထားပါသည်။"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"အားလုံး ဖယ်ရှားရန်"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"မျက်နှာပြင် ခွဲ၍ပြသခြင်းကို အသုံးပြုရန် ဤနေရာသို့ ဖိဆွဲပါ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"အလျားလိုက် ခွဲရန်"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ဒေါင်လိုက် ခွဲရန်"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"စိတ်ကြိုက် ခွဲရန်"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"မျက်နှာပြင်ကို အပေါ်သို့ ခွဲရန်"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"မျက်နှာပြင်ကို ဘယ်ဘက်သို့ ခွဲရန်"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"မျက်နှာပြင်ကို ညာဘက်သို့ ခွဲရန်"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-nb/strings.xml b/packages/SystemUI/legacy/recents/res/values-nb/strings.xml
deleted file mode 100644
index 176986a..0000000
--- a/packages/SystemUI/legacy/recents/res/values-nb/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Oversikt."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Avvis <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> er avvist."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Alle nylig brukte apper er avvist."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Åpne appinformasjonen for <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Starter <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Ingen nylige elementer"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Du har fjernet alt"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Appinformasjon"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"én-appsmodus"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"søk"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Kunne ikke starte <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> er slått av i sikker modus."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Fjern alt"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Dra hit for å bruke delt skjerm"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Del horisontalt"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Del vertikalt"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Del tilpasset"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Delt skjerm øverst"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Delt skjerm til venstre"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Delt skjerm til høyre"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ne/strings.xml b/packages/SystemUI/legacy/recents/res/values-ne/strings.xml
deleted file mode 100644
index 0113833..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ne/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"परिदृश्य।"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> खारेज गर्नुहोस्।"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> खारेज गरिएको छ।"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"हालका सबै अनुप्रयोगहरू खारेज गरियो।"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> अनुप्रयोग सम्बन्धी जानकारी खोल्नुहोस्।"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> सुरु गर्दै।"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"हालसालैको कुनै पनि वस्तु छैन"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"तपाईंले सबै कुरा खाली गर्नुभएको छ"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"अनुप्रयोगको जानकारी"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"स्क्रिन पिनिसङ"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"खोज्नुहोस्"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> सुरु गर्न सकिएन।"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> लाई सुरक्षित मोडमा असक्षम पारिएको छ।"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"सबै हटाउनुहोस्"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"विभाजित स्क्रिनको प्रयोग गर्न यहाँ तान्नुहोस्"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"तेर्सो रूपमा विभाजन गर्नुहोस्"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ठाडो रूपमा विभाजन गर्नुहोस्"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"आफू अनुकूल विभाजन गर्नुहोस्"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"विभाजित स्क्रिन शीर्ष स्थानमा राख्नुहोस्‌"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"विभाजित स्क्रिन बायाँतर्फ राख्नुहोस्‌"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"विभाजित स्क्रिन दायाँतर्फ राख्नुहोस्‌"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-nl/strings.xml b/packages/SystemUI/legacy/recents/res/values-nl/strings.xml
deleted file mode 100644
index 9714022..0000000
--- a/packages/SystemUI/legacy/recents/res/values-nl/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Overzicht."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> sluiten."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> verwijderd."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Alle recente apps gesloten."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"App-gegevens voor <xliff:g id="APP">%s</xliff:g> openen."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> starten."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Geen recente items"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Je hebt alles gewist"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"App-informatie"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"scherm vastzetten"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"zoeken"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Kan <xliff:g id="APP">%s</xliff:g> niet starten."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> is uitgeschakeld in de veilige modus"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Alles wissen"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Sleep hier naartoe om het scherm te splitsen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Horizontaal splitsen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Verticaal splitsen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Aangepast splitsen"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Scherm bovenaan gesplitst"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Scherm links gesplitst"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Scherm rechts gesplitst"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-or/strings.xml b/packages/SystemUI/legacy/recents/res/values-or/strings.xml
deleted file mode 100644
index 7ffcc94..0000000
--- a/packages/SystemUI/legacy/recents/res/values-or/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"ସଂକ୍ଷିପ୍ତ ବିବରଣୀ"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> ଖାରଜ।"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ଖାରଜ କରିଦିଆଗଲା।"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"ସମସ୍ତ ସମ୍ପ୍ରତି ଆପ୍ଲିକେସନ୍‍ଗୁଡ଼ିକ ଖାରଜ କରାଯାଇଛି।"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ଆପ୍ଲିକେସନ୍‍ ସୂଚନା ଖୋଲନ୍ତୁ।"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ଆରମ୍ଭ ହେଉଛି।"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"କୌଣସି ସାମ୍ପ୍ରତିକ ଆଇଟମ୍ ନାହିଁ"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"ଆପଣ ସୁବୁକିଛି ଖାଲି କରିଦେଇଛନ୍ତି"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ଆପ୍ଲିକେସନ୍‍ ସୂଚନା"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ସ୍କ୍ରିନ୍‌ ଲକ୍‌"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ଖୋଜନ୍ତୁ"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> କୁ ଆରମ୍ଭ କରାଯାଇପାରିଲା ନାହିଁ।"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ସୁରକ୍ଷିତ-ମୋଡ୍‌ରେ ଅକ୍ଷମ ଅଟେ।"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ସବୁ ଖାଲି କରନ୍ତୁ"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"ସ୍ପ୍ଲିଟ୍‍ ସ୍କ୍ରିନ୍‍ ବ୍ୟବହାର କରିବା ପାଇଁ ଏଠାକୁ ଡ୍ରାଗ୍‌ କରନ୍ତୁ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"ଭୂସମାନ୍ତରଭାବରେ ଭାଗ କରନ୍ତୁ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ଭୂଲମ୍ବଭାବରେ ଭାଗ କରନ୍ତୁ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"କଷ୍ଟମ୍‍ କରି ଭାଗ କରନ୍ତୁ"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"ସ୍କ୍ରିନ୍‌କୁ ଉପର ଆଡ଼କୁ ଭାଗ କରନ୍ତୁ"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"ସ୍କ୍ରିନ୍‌କୁ ବାମ ଆଡ଼କୁ ଭାଗ କରନ୍ତୁ"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"ସ୍କ୍ରିନ୍‌କୁ ଡାହାଣ ଆଡ଼କୁ ଭାଗ କରନ୍ତୁ"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-pa/strings.xml b/packages/SystemUI/legacy/recents/res/values-pa/strings.xml
deleted file mode 100644
index 4608561..0000000
--- a/packages/SystemUI/legacy/recents/res/values-pa/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"ਰੂਪ-ਰੇਖਾ।"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> ਨੂੰ ਖਾਰਜ ਕਰੋ।"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ਖਾਰਜ ਕੀਤੀ ਗਈ।"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"ਸਾਰੀਆਂ ਹਾਲੀਆ ਐਪਲੀਕੇਸ਼ਨਾਂ ਖਾਰਜ ਕੀਤੀਆਂ ਗਈਆਂ।"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ਐਪਲੀਕੇਸ਼ਨਾਂ ਜਾਣਕਾਰੀ ਖੋਲ੍ਹੋ।"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ਚਾਲੂ ਕੀਤੀ ਜਾ ਰਹੀ ਹੈ।"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ਕੋਈ ਹਾਲੀਆ ਆਈਟਮਾਂ ਨਹੀਂ"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"ਤੁਸੀਂ ਸਭ ਕੁਝ ਸਾਫ਼ ਕਰ ਦਿੱਤਾ ਹੈ"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ਐਪਲੀਕੇਸ਼ਨ ਜਾਣਕਾਰੀ"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ਸਕ੍ਰੀਨ ਪਿਨਿੰਗ"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ਖੋਜ"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ਨੂੰ ਚਾਲੂ ਨਹੀਂ ਕਰ ਸਕੇ।"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ਨੂੰ ਸੁਰੱਖਿਅਤ-ਮੋਡ ਵਿੱਚ ਬੰਦ ਕੀਤਾ ਗਿਆ ਹੈ।"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ਸਭ ਕਲੀਅਰ ਕਰੋ"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"ਸਪਲਿਟ ਸਕ੍ਰੀਨ ਦੀ ਵਰਤੋਂ ਕਰਨ ਲਈ ਇੱਥੇ ਘਸੀਟੋ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"ਲੇਟਵੀਂ ਵੰਡ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"ਖੜ੍ਹਵੀਂ ਵੰਡ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"ਵਿਉਂਤੀ ਵੰਡ"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"ਸਕ੍ਰੀਨ ਨੂੰ ਉੱਪਰ ਵੱਲ ਵੰਡੋ"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"ਸਕ੍ਰੀਨ ਨੂੰ ਖੱਬੇ ਪਾਸੇ ਵੰਡੋ"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"ਸਕ੍ਰੀਨ ਨੂੰ ਸੱਜੇ ਪਾਸੇ ਵੰਡੋ"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-pl/strings.xml b/packages/SystemUI/legacy/recents/res/values-pl/strings.xml
deleted file mode 100644
index 50b4ad0..0000000
--- a/packages/SystemUI/legacy/recents/res/values-pl/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Przegląd."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Zamknij aplikację <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Aplikacja <xliff:g id="APP">%s</xliff:g> została zamknięta."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Wszystkie ostatnie aplikacje zostały zamknięte."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Otwórz informacje o aplikacji <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Uruchamiam aplikację <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Brak ostatnich elementów"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Wszystko zostało wyczyszczone"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informacje o aplikacji"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"przypinanie ekranu"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"szukaj"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Nie udało się uruchomić aplikacji <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplikacja <xliff:g id="APP">%s</xliff:g> została wyłączona w trybie bezpiecznym."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Wyczyść wszystko"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Przeciągnij tutaj, by podzielić ekran"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Podziel poziomo"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Podziel pionowo"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Podziel niestandardowo"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Podziel ekran u góry"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Podziel ekran z lewej"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Podziel ekran z prawej"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-pt-rBR/strings.xml b/packages/SystemUI/legacy/recents/res/values-pt-rBR/strings.xml
deleted file mode 100644
index b557ad2..0000000
--- a/packages/SystemUI/legacy/recents/res/values-pt-rBR/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Visão geral."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Dispensar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> dispensado."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Todos os aplicativos recentes foram dispensados."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Abre informações do aplicativo <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Iniciando <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nenhum item recente"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Você limpou tudo"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informações do aplicativo"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"Fixar tela"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"pesquisar"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Não foi possível iniciar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"O app <xliff:g id="APP">%s</xliff:g> fica desativado no modo de segurança."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Limpar tudo"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arraste aqui para usar a tela dividida"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Divisão horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Divisão vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Divisão personalizada"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Dividir a tela para a parte superior"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Dividir a tela para a esquerda"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Dividir a tela para a direita"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-pt-rPT/strings.xml b/packages/SystemUI/legacy/recents/res/values-pt-rPT/strings.xml
deleted file mode 100644
index e62e1c6..0000000
--- a/packages/SystemUI/legacy/recents/res/values-pt-rPT/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Vista geral."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Ignorar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Aplicação <xliff:g id="APP">%s</xliff:g> ignorada."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Todas as aplicações recentes foram ignoradas."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Abrir as informações da aplicação <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"A iniciar a aplicação <xliff:g id="APP">%s</xliff:g>…"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nenhum item recente"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Limpou tudo"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informações da aplicação"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"afixação no ecrã"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"pesquisar"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Não foi possível iniciar a aplicação <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"A aplicação <xliff:g id="APP">%s</xliff:g> está desativada no modo de segurança."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Limpar tudo"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arraste aqui para utilizar o ecrã dividido"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Divisão horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Divisão vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Divisão personalizada"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Ecrã dividido na parte superior"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Ecrã dividido à esquerda"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Ecrã dividido à direita"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-pt/strings.xml b/packages/SystemUI/legacy/recents/res/values-pt/strings.xml
deleted file mode 100644
index b557ad2..0000000
--- a/packages/SystemUI/legacy/recents/res/values-pt/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Visão geral."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Dispensar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> dispensado."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Todos os aplicativos recentes foram dispensados."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Abre informações do aplicativo <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Iniciando <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nenhum item recente"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Você limpou tudo"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informações do aplicativo"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"Fixar tela"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"pesquisar"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Não foi possível iniciar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"O app <xliff:g id="APP">%s</xliff:g> fica desativado no modo de segurança."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Limpar tudo"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Arraste aqui para usar a tela dividida"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Divisão horizontal"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Divisão vertical"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Divisão personalizada"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Dividir a tela para a parte superior"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Dividir a tela para a esquerda"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Dividir a tela para a direita"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ro/strings.xml b/packages/SystemUI/legacy/recents/res/values-ro/strings.xml
deleted file mode 100644
index 7f8f018..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ro/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Recente."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Închideți <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> a fost închisă."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Toate aplicațiile recente au fost închise."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Deschideți informațiile despre aplicația <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Se inițiază <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Niciun element recent"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Ați șters tot"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informații despre aplicație"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"fixare pe ecran"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"căutați"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> nu a putut porni."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplicația <xliff:g id="APP">%s</xliff:g> este dezactivată în modul sigur."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Ștergeți tot"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Trageți aici pentru a folosi ecranul împărțit"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Împărțiți pe orizontală"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Împărțiți pe verticală"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Împărțiți personalizat"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Împărțiți ecranul în partea de sus"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Împărțiți ecranul la stânga"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Împărțiți ecranul la dreapta"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ru/strings.xml b/packages/SystemUI/legacy/recents/res/values-ru/strings.xml
deleted file mode 100644
index 1e988bb..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ru/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Обзор."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Удалить приложение <xliff:g id="APP">%s</xliff:g> из списка."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Приложение <xliff:g id="APP">%s</xliff:g> удалено из списка."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Все недавние приложения удалены из списка."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Открыть информацию о приложении <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Запуск приложения <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Здесь пока ничего нет."</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Список пуст."</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Сведения о приложении"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"блокировка в приложении"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"поиск"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Не удалось запустить приложение \"<xliff:g id="APP">%s</xliff:g>\"."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Приложение \"<xliff:g id="APP">%s</xliff:g>\" отключено в безопасном режиме."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Удалить все"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Перетащите сюда, чтобы разделить экран"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Разделить по горизонтали"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Разделить по вертикали"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Разделить по-другому"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Разделить экран по верхнему краю"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Разделить экран по левому краю"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Разделить экран по правому краю"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-si/strings.xml b/packages/SystemUI/legacy/recents/res/values-si/strings.xml
deleted file mode 100644
index cae8357..0000000
--- a/packages/SystemUI/legacy/recents/res/values-si/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"දළ විශ්ලේෂණය."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> ඉවත ලන්න."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ඉවත දමා ඇත."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"සියලුම මෑත යෙඳුම් ඉවත ලන ලදී."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> යෙදුම් තොරතුරු විවෘත කරයි."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ආරම්භ කරමින්."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"මෑත අයිතම නැත"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"ඔබ සියලු දේ හිස් කර ඇත"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"යෙදුම් තොරතුරු"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"තිර ඇමිණීම"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"සෙවීම"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ආරම්භ කළ නොහැකි විය."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ආරක්ෂිත ප්‍රකාරය තුළ අබලයි."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"සියල්ල හිස් කරන්න"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"බෙදුම් තිරය භාවිත කිරීමට මෙතැනට අදින්න"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"තිරස්ව වෙන් කරන්න"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"සිරස්ව වෙන් කරන්න"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"අභිමත ලෙස වෙන් කරන්න"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"තිරය ඉහළට බෙදන්න"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"තිරය වමට බෙදන්න"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"තිරය දකුණට බෙදන්න"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-sk/strings.xml b/packages/SystemUI/legacy/recents/res/values-sk/strings.xml
deleted file mode 100644
index 9c3a857..0000000
--- a/packages/SystemUI/legacy/recents/res/values-sk/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Prehľad"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Zavrieť aplikáciu <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Aplikácia <xliff:g id="APP">%s</xliff:g> bola zrušená."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Všetky nedávne aplikácie boli zrušené."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Otvoriť informácie o aplikácii <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Spúšťa sa aplikácia <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Žiadne nedávne položky"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Vymazali ste všetko"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informácie o aplikácii"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"pripnutie obrazovky"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"hľadať"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Aplikáciu <xliff:g id="APP">%s</xliff:g> sa nepodarilo spustiť."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplikácia <xliff:g id="APP">%s</xliff:g> je v núdzovom režime zakázaná."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Vymazať všetko"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Presuňte okno sem a použite tak rozdelenú obrazovku"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Rozdeliť vodorovné"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Rozdeliť zvislé"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Rozdeliť vlastné"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Rozdelená obrazovka hore"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Rozdelená obrazovka naľavo"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Rozdelená obrazovka napravo"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-sl/strings.xml b/packages/SystemUI/legacy/recents/res/values-sl/strings.xml
deleted file mode 100644
index 56b2ddb..0000000
--- a/packages/SystemUI/legacy/recents/res/values-sl/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Pregled."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Opustitev aplikacije <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Aplikacija <xliff:g id="APP">%s</xliff:g> je bila odstranjena."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Vse nedavne aplikacije so bile opuščene."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Odpiranje podatkov o aplikaciji <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Zaganjanje aplikacije <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Ni nedavnih elementov"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Vse ste počistili"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Podatki o aplikaciji"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"pripenjanje zaslona"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"išči"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Aplikacije <xliff:g id="APP">%s</xliff:g> ni bilo mogoče zagnati."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Aplikacija <xliff:g id="APP">%s</xliff:g> je v varnem načinu onemogočena."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Počisti vse"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Povlecite sem za razdeljeni zaslon"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Razdeli vodoravno"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Razdeli navpično"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Razdeli po meri"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Razdeljen zaslon na vrhu"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Razdeljen zaslon na levi"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Razdeljen zaslon na desni"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-sq/strings.xml b/packages/SystemUI/legacy/recents/res/values-sq/strings.xml
deleted file mode 100644
index 48aab37..0000000
--- a/packages/SystemUI/legacy/recents/res/values-sq/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Përmbledhja."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Largo <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> është hequr."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Të gjitha aplikacionet e fundit u larguan."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Hap informacionin e aplikacionit <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Po nis <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Nuk ka asnjë artikull të fundit"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"I ke pastruar të gjitha"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Informacioni i aplikacionit"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"kyçja e ekranit"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"kërko"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> nuk mund të nisej."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> është i çaktivizuar në modalitetin e sigurt."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Pastroji të gjitha"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Zvarrit këtu për të përdorur ekranin e ndarë"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Horizontal i ndarë"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Vertikal i ndarë"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"I personalizuar i ndarë"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Ndaje ekranin lart"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Ndaje ekranin në të majtë"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Ndaje ekranin në të djathtë"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-sr/strings.xml b/packages/SystemUI/legacy/recents/res/values-sr/strings.xml
deleted file mode 100644
index 9d5f126..0000000
--- a/packages/SystemUI/legacy/recents/res/values-sr/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Преглед."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Одбаците апликацију <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Апликација <xliff:g id="APP">%s</xliff:g> је одбачена."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Све недавно коришћене апликације су одбачене."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Отворите информације о апликацији <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Покреће се <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Нема недавних ставки"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Обрисали сте све"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Информације о апликацији"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"качење екрана"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"претражи"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Покретање апликације <xliff:g id="APP">%s</xliff:g> није успело."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Апликација <xliff:g id="APP">%s</xliff:g> је онемогућена у безбедном режиму."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Обриши све"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Превуците овде да бисте користили раздељени екран"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Подели хоризонтално"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Подели вертикално"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Подели прилагођено"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Подели екран нагоре"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Подели екран налево"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Подели екран надесно"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-sv/strings.xml b/packages/SystemUI/legacy/recents/res/values-sv/strings.xml
deleted file mode 100644
index b2ee34f..0000000
--- a/packages/SystemUI/legacy/recents/res/values-sv/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Översikt."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Ta bort <xliff:g id="APP">%s</xliff:g> från listan."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> togs bort från listan."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Alla appar har tagits bort från listan Senaste."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Öppna appinformation för <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Startar <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Listan är tom"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Du har tömt listan"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Appinformation"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"fästa skärmen"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"sök"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Det gick inte att starta appen <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> är inaktiverad i säkert läge."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Rensa alla"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Dra hit för att dela upp skärmen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Dela vågrätt"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Dela lodrätt"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Dela anpassat"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Delad skärm till överkanten"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Delad skärm åt vänster"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Delad skärm åt höger"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-sw/strings.xml b/packages/SystemUI/legacy/recents/res/values-sw/strings.xml
deleted file mode 100644
index 49e7fb8..0000000
--- a/packages/SystemUI/legacy/recents/res/values-sw/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Muhtasari."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Ondoa <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> imeondolewa."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Programu za hivi majuzi zimeondolewa."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Fungua maelezo kuhusu programu ya <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Inaanzisha <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Hakuna vipengee vya hivi majuzi"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Umeondoa vipengee vyote"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Maelezo ya Programu"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"kubandika kwenye skirini"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"tafuta"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Imeshindwa kuanzisha <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> imezimwa katika hali salama."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Ondoa zote"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Buruta hapa ili utumie skrini iliyogawanywa"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Gawanya Mlalo"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Gawanya Wima"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Maalum Iliyogawanywa"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Gawa skrini kuelekea juu"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Gawa skrini upande wa kushoto"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Gawa skrini upande wa kulia"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-sw600dp/dimens.xml b/packages/SystemUI/legacy/recents/res/values-sw600dp/dimens.xml
deleted file mode 100644
index 20d6670..0000000
--- a/packages/SystemUI/legacy/recents/res/values-sw600dp/dimens.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (c) 2012, 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.
-*/
--->
-<resources>
-    <!-- The offsets the tasks animate from when recents is launched while docking -->
-    <dimen name="recents_task_stack_animation_launched_while_docking_offset">192dp</dimen>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ta/strings.xml b/packages/SystemUI/legacy/recents/res/values-ta/strings.xml
deleted file mode 100644
index 91643fd..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ta/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"மேலோட்டப் பார்வை."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> ஆப்ஸை அகற்றும்."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> அகற்றப்பட்டது."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"அனைத்துச் சமீபத்திய ஆப்ஸும் அகற்றப்பட்டன."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ஆப்ஸ் பற்றிய தகவலைத் திறக்கும்."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ஆப்ஸைத் தொடங்குகிறது."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"சமீபத்தியவை எதுவுமில்லை"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"அனைத்தையும் அழித்துவிட்டீர்கள்"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ஆப்ஸ் பற்றிய தகவல்"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"திரையைப் பின் செய்"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"தேடு"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ஆப்ஸைத் தொடங்க இயலவில்லை."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"பாதுகாப்புப் பயன்முறையில் <xliff:g id="APP">%s</xliff:g> முடக்கப்பட்டது."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"அனைத்தையும் அழி"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"\'திரைப் பிரிப்பைப்\' பயன்படுத்த இங்கே இழுக்கவும்"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"கிடைமட்டமாகப் பிரி"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"செங்குத்தாகப் பிரி"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"தனிப்பயன் விருப்பத்தில் பிரி"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"திரையை மேற்புறமாகப் பிரிக்கும்"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"திரையை இடப்புறமாகப் பிரிக்கும்"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"திரையை வலப்புறமாகப் பிரிக்கும்"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-te/strings.xml b/packages/SystemUI/legacy/recents/res/values-te/strings.xml
deleted file mode 100644
index ea4e638..0000000
--- a/packages/SystemUI/legacy/recents/res/values-te/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"అవలోకనం."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g>ని తీసివేయండి."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> తీసివేయబడింది."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"అన్ని ఇటీవలి యాప్‌లు తీసివేయబడ్డాయి."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> యాప్ సమాచారాన్ని తెరుస్తుంది."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g>ని ప్రారంభిస్తోంది."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ఇటీవలి అంశాలు ఏవీ లేవు"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"మీరు అన్నింటినీ తీసివేసారు"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"యాప్ సమాచారం"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"స్క్రీన్‌కు పిన్ చేయడం"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"వెతుకు"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g>ని ప్రారంభించడం సాధ్యపడలేదు."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> సురక్షిత-మోడ్‌లో నిలిపివేయబడింది."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"అన్నీ తీసివేయి"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"విభజన స్క్రీన్‌ను ఉపయోగించడానికి ఇక్కడ లాగండి"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"అడ్డంగా విభజించు"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"నిలువుగా విభజించు"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"అనుకూలంగా విభజించు"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"స్క్రీన్‌ని ఎగువకు విభజించు"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"స్క్రీన్‌ని ఎడమ వైపుకి విభజించు"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"స్క్రీన్‌ని కుడి వైపుకి విభజించు"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-th/strings.xml b/packages/SystemUI/legacy/recents/res/values-th/strings.xml
deleted file mode 100644
index b88d05e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-th/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"ภาพรวม"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"ยกเลิก <xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> ถูกนำออกไปแล้ว"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"ปิดแอปพลิเคชันล่าสุดทั้งหมดแล้ว"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"เปิดข้อมูลแอปพลิเคชัน <xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"กำลังเริ่มต้น <xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"ไม่มีรายการล่าสุด"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"คุณได้ล้างทุกอย่างแล้ว"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ข้อมูลแอปพลิเคชัน"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"การตรึงหน้าจอ"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ค้นหา"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"เริ่มใช้ <xliff:g id="APP">%s</xliff:g> ไม่ได้"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> ปิดใช้ในโหมดปลอดภัย"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"ล้างทั้งหมด"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"ลากมาที่นี่เพื่อใช้การแยกหน้าจอ"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"แยกในแนวนอน"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"แยกในแนวตั้ง"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"แยกแบบกำหนดเอง"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"แยกหน้าจอไปด้านบน"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"แยกหน้าจอไปทางซ้าย"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"แยกหน้าจอไปทางขวา"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-tl/strings.xml b/packages/SystemUI/legacy/recents/res/values-tl/strings.xml
deleted file mode 100644
index d940d4e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-tl/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Overview"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"I-dismiss ang <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Na-dismiss ang <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Na-dismiss ang lahat ng kamakailang application."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Buksan ang impormasyon ng <xliff:g id="APP">%s</xliff:g> application."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Sinisimulan ang <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Walang kamakailang item"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Na-clear mo ang lahat"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Impormasyon ng Application"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"pag-pin sa screen"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"hanapin"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Hindi masimulan ang <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Naka-disable ang <xliff:g id="APP">%s</xliff:g> sa safe-mode."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"I-clear lahat"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"I-drag dito para magamit ang split screen"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"I-split Pahalang"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"I-split Patayo"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Split Custom"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"I-split ang screen pataas"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"I-split ang screen pakaliwa"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"I-split ang screen pakanan"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-tr/strings.xml b/packages/SystemUI/legacy/recents/res/values-tr/strings.xml
deleted file mode 100644
index 982c57e..0000000
--- a/packages/SystemUI/legacy/recents/res/values-tr/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Genel Bakış."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> uygulamasını kapatır."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> kaldırıldı."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Tüm son uygulamalar kapatıldı."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> uygulama bilgilerini açar."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> başlatılıyor."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Yeni öğe yok"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Her şeyi sildiniz"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Uygulama Bilgileri"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ekran sabitleme"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"ara"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> başlatılamadı."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g>, güvenli modda devre dışıdır."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Tümünü temizle"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Ekranı bölünmüş olarak kullanmak için buraya sürükleyin"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Yatay Ayırma"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Dikey Ayırma"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Özel Ayırma"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Ekranı yukarıya doğru böl"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Ekranı sola doğru böl"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Ekranı sağa doğru böl"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-uk/strings.xml b/packages/SystemUI/legacy/recents/res/values-uk/strings.xml
deleted file mode 100644
index 0c0b709..0000000
--- a/packages/SystemUI/legacy/recents/res/values-uk/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Огляд."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Закрити додаток <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Додаток <xliff:g id="APP">%s</xliff:g> закрито."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Усі останні додатки закрито."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Відкрити інформацію про додаток <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Запуск додатка <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Немає останніх елементів"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Ви очистили все"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Інформація про додаток"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"закріпити екран"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"пошук"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Не вдалося запустити додаток <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Додаток <xliff:g id="APP">%s</xliff:g> вимкнено в безпечному режимі."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Очистити все"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Перетягніть сюди, щоб розділити екран"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Розділити горизонтально"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Розділити вертикально"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Розділити (власний варіант)"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Розділити екран угору"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Розділити екран уліво"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Розділити екран управо"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-ur/strings.xml b/packages/SystemUI/legacy/recents/res/values-ur/strings.xml
deleted file mode 100644
index 46033da..0000000
--- a/packages/SystemUI/legacy/recents/res/values-ur/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"عمومی جائزہ۔"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"<xliff:g id="APP">%s</xliff:g> کو مسترد کریں۔"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> کو مسترد کر دیا گیا۔"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"سبھی حالیہ ایپلیکیشنز کو مسترد کر دیا گیا۔"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ایپلیکیشن کی معلومات کھولیں۔"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> شروع ہو رہی ہے۔"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"کوئی حالیہ آئٹم نہیں"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"آپ نے سب کچھ صاف کر دیا ہے"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"ایپلیکیشن کی معلومات"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"اسکرین کو پن کرنا"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"تلاش کریں"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> کو شروع نہیں کیا جا سکا۔"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"محفوظ موڈ میں <xliff:g id="APP">%s</xliff:g> غیر فعال ہے۔"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"سبھی کو ہٹائیں"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"اسپلٹ اسکرین استعمال کرنے کے لیے یہاں گھسیٹیں"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"بلحاظ افقی تقسیم کریں"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"بلحاظ عمودی تقسیم کریں"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"بلحاظ حسب ضرورت تقسیم کریں"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"اسکرین کو اوپر کی جانب تقسیم کریں"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"اسکرین کو بائیں جانب تقسیم کریں"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"اسکرین کو دائیں جانب تقسیم کریں"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-uz/strings.xml b/packages/SystemUI/legacy/recents/res/values-uz/strings.xml
deleted file mode 100644
index 6f8b153..0000000
--- a/packages/SystemUI/legacy/recents/res/values-uz/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Umumiy nazar."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Olib tashlash: <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"<xliff:g id="APP">%s</xliff:g> olib tashlangan."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Yaqinda ishlatilgan barcha ilovalar olib tashlandi."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"<xliff:g id="APP">%s</xliff:g> ilovasi haqidagi axborotlarni ochadi."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"<xliff:g id="APP">%s</xliff:g> ishga tushirilmoqda."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Yaqinda ishlatilgan ilovalar yoʻq"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Hammasi tozalandi"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Ilova haqida axborot"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ekranni mahkamlash"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"qidiruv"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"<xliff:g id="APP">%s</xliff:g> ilovasi ishga tushmadi."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"Xavfsiz rejimda <xliff:g id="APP">%s</xliff:g> ilovasi yopildi."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Ha"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Ekranni boʻlish xususiyatidan foydalanish uchun bu yerga torting"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Gorizontal yoʻnalishda boʻlish"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Vertikal yoʻnalishda boʻlish"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Boshqa usulda boʻlish"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Ekranni tepaga qadash"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Ekranni chap tomonga qadash"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Ekranni oʻng tomonga qadash"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-vi/strings.xml b/packages/SystemUI/legacy/recents/res/values-vi/strings.xml
deleted file mode 100644
index f672a3d..0000000
--- a/packages/SystemUI/legacy/recents/res/values-vi/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Tổng quan."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Loại bỏ <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"Đã loại bỏ <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Đã loại bỏ tất cả các ứng dụng gần đây."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Mở thông tin ứng dụng <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Khởi động <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Không có mục gần đây nào"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Bạn đã xóa mọi nội dung"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Thông tin ứng dụng"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"khóa màn hình"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"tìm kiếm"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Không thể khởi động <xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g> bị tắt ở chế độ an toàn."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Xóa tất cả"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Kéo vào đây để sử dụng chế độ chia đôi màn hình"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Phân tách ngang"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Phân tách dọc"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Tùy chỉnh phân tách"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Chia đôi màn hình lên trên"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Chia đôi màn hình sang trái"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Chia đôi màn hình sang phải"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-zh-rCN/strings.xml b/packages/SystemUI/legacy/recents/res/values-zh-rCN/strings.xml
deleted file mode 100644
index 993bfae..0000000
--- a/packages/SystemUI/legacy/recents/res/values-zh-rCN/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"概览。"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"移除<xliff:g id="APP">%s</xliff:g>。"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"已移除<xliff:g id="APP">%s</xliff:g>"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"已关闭所有最近用过的应用。"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"打开<xliff:g id="APP">%s</xliff:g>应用信息。"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"正在启动<xliff:g id="APP">%s</xliff:g>。"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"近期没有任何内容"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"您已清除所有内容"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"应用信息"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"固定屏幕"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"搜索"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"无法启动<xliff:g id="APP">%s</xliff:g>。"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"<xliff:g id="APP">%s</xliff:g>已在安全模式下停用。"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"全部清除"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"拖动到此处即可使用分屏功能"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"水平分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"垂直分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"自定义分割"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"将屏幕分隔线移到上方"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"将屏幕分隔线移到左侧"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"将屏幕分隔线移到右侧"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-zh-rHK/strings.xml b/packages/SystemUI/legacy/recents/res/values-zh-rHK/strings.xml
deleted file mode 100644
index b93d246..0000000
--- a/packages/SystemUI/legacy/recents/res/values-zh-rHK/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"概覽。"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"關閉「<xliff:g id="APP">%s</xliff:g>」。"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"「<xliff:g id="APP">%s</xliff:g>」已關閉。"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"所有最近使用的應用程式均已關閉。"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"開啟「<xliff:g id="APP">%s</xliff:g>」應用程式的資料。"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"正在啟動「<xliff:g id="APP">%s</xliff:g>」。"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"最近沒有任何項目"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"您已清除所有工作"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"應用程式資料"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"螢幕固定"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"搜尋"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"無法啟動「<xliff:g id="APP">%s</xliff:g>」。"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"「<xliff:g id="APP">%s</xliff:g>」在安全模式下為停用狀態。"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"全部清除"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"拖曳這裡即可分割螢幕"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"水平分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"垂直分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"自訂分割"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"將分割畫面顯示喺頂部"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"將分割畫面顯示喺左邊"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"將分割畫面顯示喺右邊"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-zh-rTW/strings.xml b/packages/SystemUI/legacy/recents/res/values-zh-rTW/strings.xml
deleted file mode 100644
index 54d656d..0000000
--- a/packages/SystemUI/legacy/recents/res/values-zh-rTW/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"總覽。"</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"關閉「<xliff:g id="APP">%s</xliff:g>」。"</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"「<xliff:g id="APP">%s</xliff:g>」已關閉。"</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"最近使用的應用程式已全部關閉。"</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"開啟「<xliff:g id="APP">%s</xliff:g>」應用程式資訊。"</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"正在啟動「<xliff:g id="APP">%s</xliff:g>」。"</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"最近沒有任何項目"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"你已清除所有工作"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"應用程式資訊"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"螢幕固定"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"搜尋"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"無法啟動「<xliff:g id="APP">%s</xliff:g>」。"</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"「<xliff:g id="APP">%s</xliff:g>」在安全模式中為停用狀態。"</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"全部清除"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"拖曳到這裡即可使用分割畫面"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"水平分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"垂直分割"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"自訂分割"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"將分割畫面顯示在頂端"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"將分割畫面顯示在左邊"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"將分割畫面顯示在右邊"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values-zu/strings.xml b/packages/SystemUI/legacy/recents/res/values-zu/strings.xml
deleted file mode 100644
index 9cbc439..0000000
--- a/packages/SystemUI/legacy/recents/res/values-zu/strings.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- 
-/**
- * Copyright (c) 2009, 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.
- */
- -->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="accessibility_desc_recent_apps" msgid="2427210347871321373">"Buka konke."</string>
-    <string name="accessibility_recents_item_will_be_dismissed" msgid="2355882496933479534">"Cashisa i-<xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_dismissed" msgid="4816790842084268400">"I-<xliff:g id="APP">%s</xliff:g> icashisiwe."</string>
-    <string name="accessibility_recents_all_items_dismissed" msgid="5693205751863608046">"Zonke izinhlelo zokusebenza zakamuva zicashisiwe."</string>
-    <string name="accessibility_recents_item_open_app_info" msgid="3406797323476801016">"Vula ulwazi lohlelo lokusebenza le-<xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="accessibility_recents_item_launched" msgid="4519918148638221791">"Iqala i-<xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_empty_message" msgid="7967713254531861311">"Azikho izinto zakamuva"</string>
-    <string name="recents_empty_message_dismissed_all" msgid="1850214584987361375">"Usule yonke into"</string>
-    <string name="recents_app_info_button_label" msgid="8732926607391786762">"Ulwazi lohlelo lokusebenza"</string>
-    <string name="recents_lock_to_app_button_label" msgid="6087750201863853365">"ukuphina isikrini"</string>
-    <string name="recents_search_bar_label" msgid="638132045925945941">"sesha"</string>
-    <string name="recents_launch_error_message" msgid="9107963563503438012">"Ayikwazanga ukuqalisa i-<xliff:g id="APP">%s</xliff:g>."</string>
-    <string name="recents_launch_disabled_message" msgid="826461671965217243">"I-<xliff:g id="APP">%s</xliff:g> ikhutshaziwe kumodi yokuphepha."</string>
-    <string name="recents_stack_action_button_label" msgid="1974273390109881497">"Sula konke"</string>
-    <string name="recents_drag_hint_message" msgid="610417221848280136">"Hudulela lapha ukuze usebenzise ukuhlukanisa kwesikrini"</string>
-    <string name="recents_multistack_add_stack_dialog_split_horizontal" msgid="488987777874979435">"Hlukanisa ngokuvundlile"</string>
-    <string name="recents_multistack_add_stack_dialog_split_vertical" msgid="2498375296906391117">"Hlukanisa ngokumile"</string>
-    <string name="recents_multistack_add_stack_dialog_split_custom" msgid="7368405969130304811">"Hlukanisa ngokwezifiso"</string>
-    <string name="recents_accessibility_split_screen_top" msgid="8773505308411722524">"Hlukanisela isikrini phezulu"</string>
-    <string name="recents_accessibility_split_screen_left" msgid="722594718192007972">"Hlukanisela isikrini ngakwesokunxele"</string>
-    <string name="recents_accessibility_split_screen_right" msgid="2479764030969301514">"Hlukanisela isikrini ngakwesokudla"</string>
-</resources>
diff --git a/packages/SystemUI/legacy/recents/res/values/attrs.xml b/packages/SystemUI/legacy/recents/res/values/attrs.xml
deleted file mode 100644
index ef4cd5b..0000000
--- a/packages/SystemUI/legacy/recents/res/values/attrs.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2010 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.
--->
-
-<resources>
-
-    <declare-styleable name="RecentsPanelView">
-        <attr name="recentItemLayout" format="reference" />
-        <!-- Style for the "Clear all" button. -->
-        <attr name="clearAllStyle" format="reference" />
-        <attr name="clearAllBackgroundColor" format="reference" />
-    </declare-styleable>
-
-</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/values/colors.xml b/packages/SystemUI/legacy/recents/res/values/colors.xml
deleted file mode 100644
index 88b9b70..0000000
--- a/packages/SystemUI/legacy/recents/res/values/colors.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
- * Copyright 2010, 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.
- */
--->
-<resources>
-	<!-- The disabled recents task bar background color. -->
-    <color name="recents_task_bar_disabled_background_color">#ff676767</color>
-    <!-- The default recents task bar background color. -->
-    <color name="recents_task_bar_default_background_color">#ffe6e6e6</color>
-    <!-- The default recents task view background color. -->
-    <color name="recents_task_view_default_background_color">#fff3f3f3</color>
-    <!-- The recents task bar light text color to be drawn on top of dark backgrounds. -->
-    <color name="recents_task_bar_light_text_color">#ffeeeeee</color>
-    <!-- The recents task bar dark text color to be drawn on top of light backgrounds. -->
-    <color name="recents_task_bar_dark_text_color">#cc000000</color>
-    <!-- The recents task bar light dismiss icon color to be drawn on top of dark backgrounds. -->
-    <color name="recents_task_bar_light_icon_color">#ccffffff</color>
-    <!-- The recents task bar dark dismiss icon color to be drawn on top of light backgrounds. -->
-    <color name="recents_task_bar_dark_icon_color">#99000000</color>
-    <!-- The lock to task button background color. -->
-    <color name="recents_task_view_lock_to_app_button_background_color">#ffe6e6e6</color>
-    <!-- The lock to task button foreground color. -->
-    <color name="recents_task_view_lock_to_app_button_color">#ff666666</color>
-    <!-- The background color for the freeform workspace. -->
-    <color name="recents_freeform_workspace_bg_color">#33FFFFFF</color>
-
-    <!-- The background color for clear all button on light backgrounds if not transparent. -->
-    <color name="recents_clear_all_button_bg_light_color">#CCFFFFFF</color>
-    <!-- The background color for clear all button on dark backgrounds if not transparent. -->
-    <color name="recents_clear_all_button_bg_dark_color">#CC000000</color>
-
-    <!-- Shadow color for the first pixels around the fake shadow for recents. -->
-    <color name="fake_shadow_start_color">#44000000</color>
-
-    <!-- Shadow color for the furthest pixels around the fake shadow for recents. -->
-    <color name="fake_shadow_end_color">#03000000</color>
-</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/values/config.xml b/packages/SystemUI/legacy/recents/res/values/config.xml
deleted file mode 100644
index 2ff9abf..0000000
--- a/packages/SystemUI/legacy/recents/res/values/config.xml
+++ /dev/null
@@ -1,75 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2009, 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.
-*/
--->
-
-<!-- These resources are around just to allow their values to be customized
-     for different hardware and product builds. -->
-<resources>
-
-    <!-- Component to be used as the recents implementation.  Must implement the
-     RecentsImplementation interface.  This name is in the ComponentName flattened format
-     (package/class)  -->
-    <string name="config_recentsComponent" translatable="false">com.android.systemui.recents.LegacyRecentsImpl</string>
-
-    <!-- Whether recents should use hardware layers for its taskviews. This flag can be enabled
-    for devices where the java drawing of round rects may be slow -->
-    <bool name="config_recents_use_hardware_layers">false</bool>
-
-    <!-- The number of app thumbnails we keep in memory -->
-    <integer name="config_recents_max_thumbnail_count">10</integer>
-
-    <!-- The number of app icons we keep in memory -->
-    <integer name="config_recents_max_icon_count">20</integer>
-
-    <!-- Whether to use cheap, less good looking shadows for recents -->
-    <bool name="config_recents_fake_shadows">false</bool>
-
-    <!-- The duration in seconds to wait before the dismiss buttons are shown. -->
-    <integer name="recents_task_bar_dismiss_delay_seconds">1000</integer>
-
-    <!-- The duration for animating the task decorations in after transitioning from an app. -->
-    <integer name="recents_task_enter_from_app_duration">200</integer>
-
-    <!-- The duration for animating the task decorations in after transitioning from an app. -->
-    <integer name="recents_task_enter_from_affiliated_app_duration">125</integer>
-
-    <!-- The duration for animating the task decorations out before transitioning to an app. -->
-    <integer name="recents_task_exit_to_app_duration">125</integer>
-
-    <!-- The min animation duration for animating the nav bar scrim in. -->
-    <integer name="recents_nav_bar_scrim_enter_duration">400</integer>
-
-    <!-- The animation duration for scrolling the stack to a particular item. -->
-    <integer name="recents_animate_task_stack_scroll_duration">200</integer>
-
-    <!-- The delay to enforce between each alt-tab key press. -->
-    <integer name="recents_alt_tab_key_delay">200</integer>
-
-    <!-- Svelte specific logic, see RecentsConfiguration.SVELTE_* constants. -->
-    <integer name="recents_svelte_level">0</integer>
-
-    <!-- Recents: The relative range of visible tasks from the current scroll position
-         while the stack is focused. -->
-    <item name="recents_layout_focused_range_min" format="float" type="integer">-3</item>
-    <item name="recents_layout_focused_range_max" format="float" type="integer">2</item>
-
-    <!-- Recents: The relative range of visible tasks from the current scroll position
-         while the stack is not focused. -->
-    <item name="recents_layout_unfocused_range_min" format="float" type="integer">-2</item>
-    <item name="recents_layout_unfocused_range_max" format="float" type="integer">2.5</item>
-</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/values/dimens.xml b/packages/SystemUI/legacy/recents/res/values/dimens.xml
deleted file mode 100644
index 528610e4..0000000
--- a/packages/SystemUI/legacy/recents/res/values/dimens.xml
+++ /dev/null
@@ -1,110 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (c) 2006, 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.
-*/
--->
-<resources>
-<!-- Recents Layout -->
-
-    <!-- The amount to inset the stack, specifically at the top and the other sides.  We also
-         don't want this to change across configurations that Recents can be opened in, so we
-         define them statically for all display sizes. -->
-    <dimen name="recents_layout_min_margin">16dp</dimen>
-    <dimen name="recents_layout_top_margin_phone">16dp</dimen>
-    <dimen name="recents_layout_top_margin_tablet">32dp</dimen>
-    <dimen name="recents_layout_top_margin_tablet_xlarge">40dp</dimen>
-    <dimen name="recents_layout_bottom_margin">16dp</dimen>
-    <dimen name="recents_layout_side_margin_phone">16dp</dimen>
-    <dimen name="recents_layout_side_margin_tablet">48dp</dimen>
-    <dimen name="recents_layout_side_margin_tablet_docked">16dp</dimen>
-    <dimen name="recents_layout_side_margin_tablet_xlarge">64dp</dimen>
-    <dimen name="recents_layout_side_margin_tablet_xlarge_docked">16dp</dimen>
-
-    <!-- The height between the top margin and the top of the focused task. -->
-    <dimen name="recents_layout_top_peek_size">48dp</dimen>
-    <!-- The height between the bottom margin and the top of task in front of the focused task. -->
-    <dimen name="recents_layout_bottom_peek_size">56dp</dimen>
-
-    <!-- The offset from the top and bottom of the stack of the focused task.  The bottom offset
-         will be additionally offset by the bottom system insets since it goes under the nav bar
-         in certain orientations. -->
-    <dimen name="recents_layout_initial_top_offset_phone_port">128dp</dimen>
-    <dimen name="recents_layout_initial_bottom_offset_phone_port">80dp</dimen>
-    <dimen name="recents_layout_initial_top_offset_phone_land">72dp</dimen>
-    <dimen name="recents_layout_initial_bottom_offset_phone_land">72dp</dimen>
-    <dimen name="recents_layout_initial_top_offset_tablet">160dp</dimen>
-    <dimen name="recents_layout_initial_bottom_offset_tablet">112dp</dimen>
-
-    <!-- The min/max translationZ for the tasks in the stack. -->
-    <dimen name="recents_layout_z_min">3dp</dimen>
-    <dimen name="recents_layout_z_max">24dp</dimen>
-
-    <!-- The margin between the freeform and stack.  We also don't want this to change across
-         configurations that Recents can be opened in, so we define them statically for all
-         display sizes. -->
-    <dimen name="recents_freeform_layout_bottom_margin">16dp</dimen>
-
-    <!-- The padding between each freeform task. -->
-    <dimen name="recents_freeform_layout_task_padding">8dp</dimen>
-
-<!-- Recents Views -->
-
-    <!-- The height of a task view bar.  This has to be large enough to cover the action bar
-         height in either orientation at this smallest width. -->
-    <dimen name="recents_task_view_header_height">56dp</dimen>
-    <dimen name="recents_task_view_header_height_tablet_land">64dp</dimen>
-
-    <!-- The padding of a button in the recents task view header. -->
-    <dimen name="recents_task_view_header_button_padding">16dp</dimen>
-    <dimen name="recents_task_view_header_button_padding_tablet_land">20dp</dimen>
-
-    <!-- The radius of the rounded corners on a task view and its shadow (which can be larger
-         to create a softer corner effect. -->
-    <dimen name="recents_task_view_rounded_corners_radius">2dp</dimen>
-    <dimen name="recents_task_view_shadow_rounded_corners_radius">6dp</dimen>
-
-    <!-- The amount of highlight to make on each task view. -->
-    <dimen name="recents_task_view_highlight">1dp</dimen>
-
-    <!-- The size of the lock-to-app button and its icon. -->
-    <dimen name="recents_lock_to_app_size">56dp</dimen>
-    <dimen name="recents_lock_to_app_icon_size">28dp</dimen>
-
-    <!-- The amount of overscroll allowed when flinging to the end of the stack. -->
-    <dimen name="recents_fling_overscroll_distance">24dp</dimen>
-
-    <!-- The size of the drag hint text. -->
-    <dimen name="recents_drag_hint_text_size">14sp</dimen>
-
-    <!-- The min alpha to apply to a task affiliation group color. -->
-    <item name="recents_task_affiliation_color_min_alpha_percentage" format="float" type="dimen">0.6</item>
-
-    <!-- The amount to offset when animating into an affiliate group. -->
-    <dimen name="recents_task_stack_animation_affiliate_enter_offset">32dp</dimen>
-
-    <!-- The offsets the tasks animate from when recents is launched while docking -->
-    <dimen name="recents_task_stack_animation_launched_while_docking_offset">144dp</dimen>
-
-    <!-- The amount to translate when animating the removal of a task. -->
-    <dimen name="recents_task_view_remove_anim_translation_x">100dp</dimen>
-
-    <!-- The alpha to apply to the recents row when it doesn't have focus -->
-    <item name="recents_recents_row_dim_alpha" format="float" type="dimen">0.5</item>
-
-    <!-- The speed in dp/s at which the user needs to be scrolling in recents such that we start
-         loading full resolution screenshots. -->
-    <dimen name="recents_fast_fling_velocity">600dp</dimen>
-
-</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/values/dimens_grid.xml b/packages/SystemUI/legacy/recents/res/values/dimens_grid.xml
deleted file mode 100644
index febf65b8..0000000
--- a/packages/SystemUI/legacy/recents/res/values/dimens_grid.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (c) 2016, 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.
-*/
--->
-<resources>
-  <dimen name="recents_grid_padding_left_right">32dp</dimen>
-  <dimen name="recents_grid_padding_top_bottom">150dp</dimen>
-  <dimen name="recents_grid_padding_task_view">20dp</dimen>
-  <dimen name="recents_grid_task_view_header_height">44dp</dimen>
-  <dimen name="recents_grid_task_view_header_button_padding">8dp</dimen>
-  <dimen name="recents_grid_task_view_focused_frame_thickness">8dp</dimen>
-  <dimen name="recents_grid_task_view_rounded_corners_radius">4dp</dimen>
-  <dimen name="recents_grid_task_view_focused_frame_rounded_corners_radius">8dp</dimen>
-</resources>
-
diff --git a/packages/SystemUI/legacy/recents/res/values/strings.xml b/packages/SystemUI/legacy/recents/res/values/strings.xml
deleted file mode 100644
index 4b44ba9..0000000
--- a/packages/SystemUI/legacy/recents/res/values/strings.xml
+++ /dev/null
@@ -1,67 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/**
- * Copyright (c) 2009, 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.
- */
--->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-	
-    <!-- Content description for the recent apps panel (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_desc_recent_apps">Overview.</string>
-
-    <!-- Content description to tell the user that this button will remove an application from recents -->
-    <string name="accessibility_recents_item_will_be_dismissed">Dismiss <xliff:g id="app" example="Calendar">%s</xliff:g>.</string>
-    <!-- Content description to tell the user an application has been removed from recents -->
-    <string name="accessibility_recents_item_dismissed"><xliff:g id="app" example="Calendar">%s</xliff:g> dismissed.</string>
-    <!-- Content description to tell the user all applications has been removed from recents -->
-    <string name="accessibility_recents_all_items_dismissed">All recent applications dismissed.</string>
-    <!-- Content description to tell the user that this button will open application info for an application in recents -->
-    <string name="accessibility_recents_item_open_app_info">Open <xliff:g id="app" example="Calendar">%s</xliff:g> application info.</string>
-    <!-- Content description to tell the user an application has been launched from recents -->
-    <string name="accessibility_recents_item_launched">Starting <xliff:g id="app" example="Calendar">%s</xliff:g>.</string>
-
-    <!-- Recents: The empty recents string. [CHAR LIMIT=NONE] -->
-    <string name="recents_empty_message">No recent items</string>
-    <!-- Recents: The empty recents string after dismissing all tasks. [CHAR LIMIT=NONE] -->
-    <string name="recents_empty_message_dismissed_all">You\'ve cleared everything</string>
-    <!-- Recents: The info panel app info button string. [CHAR LIMIT=NONE] -->
-    <string name="recents_app_info_button_label">Application Info</string>
-    <!-- Recents: The screen pinning button. [CHAR LIMIT=NONE] -->
-    <string name="recents_lock_to_app_button_label">screen pinning</string>
-    <!-- Recents: Temporary string for the button in the recents search bar. [CHAR LIMIT=NONE] -->
-    <string name="recents_search_bar_label">search</string>
-    <!-- Recents: Launch error string. [CHAR LIMIT=NONE] -->
-    <string name="recents_launch_error_message">Could not start <xliff:g id="app" example="Calendar">%s</xliff:g>.</string>
-    <!-- Recents: Launch disabled string. [CHAR LIMIT=NONE] -->
-    <string name="recents_launch_disabled_message"><xliff:g id="app" example="Calendar">%s</xliff:g> is disabled in safe-mode.</string>
-    <!-- Recents: Stack action button string. [CHAR LIMIT=NONE] -->
-    <string name="recents_stack_action_button_label">Clear all</string>
-    <!-- Recents: Hint text that shows on the drop targets to start multiwindow. [CHAR LIMIT=NONE] -->
-    <string name="recents_drag_hint_message">Drag here to use split screen</string>
-
-    <!-- Recents: MultiStack add stack split horizontal radio button. [CHAR LIMIT=NONE] -->
-    <string name="recents_multistack_add_stack_dialog_split_horizontal">Split Horizontal</string>
-    <!-- Recents: MultiStack add stack split vertical radio button. [CHAR LIMIT=NONE] -->
-    <string name="recents_multistack_add_stack_dialog_split_vertical">Split Vertical</string>
-    <!-- Recents: MultiStack add stack split custom radio button. [CHAR LIMIT=NONE] -->
-    <string name="recents_multistack_add_stack_dialog_split_custom">Split Custom</string>
-    <!-- Recents: Accessibility split to the top -->
-    <string name="recents_accessibility_split_screen_top">Split screen to the top</string>
-    <!-- Recents: Accessibility split to the left -->
-    <string name="recents_accessibility_split_screen_left">Split screen to the left</string>
-    <!-- Recents: Accessibility split to the right -->
-    <string name="recents_accessibility_split_screen_right">Split screen to the right</string>
-
-</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/res/values/styles.xml b/packages/SystemUI/legacy/recents/res/values/styles.xml
deleted file mode 100644
index eb16be7..0000000
--- a/packages/SystemUI/legacy/recents/res/values/styles.xml
+++ /dev/null
@@ -1,55 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2006 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.
--->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android">
-
-    <style name="RecentsTheme" parent="@android:style/Theme.Material">
-        <!-- NoTitle -->
-        <item name="android:windowNoTitle">true</item>
-        <!-- Misc -->
-        <item name="android:statusBarColor">@android:color/transparent</item>
-        <item name="android:navigationBarColor">@android:color/transparent</item>
-        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
-        <item name="android:windowAnimationStyle">@null</item>
-        <item name="android:ambientShadowAlpha">0.35</item>
-    </style>
-
-    <!-- Recents theme -->
-    <style name="RecentsTheme.Wallpaper">
-        <item name="android:windowBackground">@*android:color/transparent</item>
-        <item name="android:colorBackgroundCacheHint">@null</item>
-        <item name="android:windowShowWallpaper">true</item>
-        <item name="android:windowDisablePreview">true</item>
-        <item name="clearAllStyle">@style/ClearAllButtonDefaultMargins</item>
-        <item name="clearAllBackgroundColor">@color/recents_clear_all_button_bg_dark_color</item>
-        <item name="wallpaperTextColor">@*android:color/primary_text_material_dark</item>
-        <item name="wallpaperTextColorSecondary">@*android:color/secondary_text_material_dark</item>
-    </style>
-
-    <style name="RecentsTheme.Wallpaper.Light">
-        <item name="clearAllBackgroundColor">@color/recents_clear_all_button_bg_light_color</item>
-        <item name="wallpaperTextColor">@*android:color/primary_text_material_light</item>
-        <item name="wallpaperTextColorSecondary">@*android:color/secondary_text_material_light</item>
-    </style>
-
-    <!-- Performance optimized Recents theme (no wallpaper) -->
-    <style name="RecentsTheme.NoWallpaper">
-        <item name="android:windowBackground">@android:color/black</item>
-        <item name="wallpaperTextColor">@android:color/white</item>
-        <item name="wallpaperTextColorSecondary">@android:color/white</item>
-    </style>
-
-  </resources>
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/Constants.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/Constants.java
deleted file mode 100644
index 003379f..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/Constants.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents;
-
-/**
- * Constants
- */
-public class Constants {
-
-    // TODO: Move into RecentsMetrics
-    public static class Metrics {
-        // DO NOT MODIFY THE ORDER OF THESE METRICS
-        public static final int DismissSourceKeyboard = 0;
-        public static final int DismissSourceSwipeGesture = 1;
-        public static final int DismissSourceHeaderButton = 2;
-        @Deprecated
-        public static final int DismissSourceHistorySwipeGesture = 3;
-    }
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/IRecentsNonSystemUserCallbacks.aidl b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/IRecentsNonSystemUserCallbacks.aidl
deleted file mode 100644
index 90c1099..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/IRecentsNonSystemUserCallbacks.aidl
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents;
-
-import android.graphics.Rect;
-
-/**
- * Due to the fact that RecentsActivity is per-user, we need to establish an
- * interface (this) for the system user to callback to the secondary users in
- * response to UI events coming in from the system user's SystemUI.
- */
-oneway interface IRecentsNonSystemUserCallbacks {
-    void preloadRecents();
-    void cancelPreloadingRecents();
-    void showRecents(boolean triggeredFromAltTab, boolean draggingInRecents, boolean animate,
-            int recentsGrowTarget);
-    void hideRecents(boolean triggeredFromAltTab, boolean triggeredFromHomeKey);
-    void toggleRecents(int recentsGrowTarget);
-    void onConfigurationChanged();
-    void splitPrimaryTask(int topTaskId, int stackCreateMode, in Rect initialBounds);
-    void onDraggingInRecents(float distanceFromTop);
-    void onDraggingInRecentsEnded(float velocity);
-    void showCurrentUserToast(int msgResId, int msgLength);
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/IRecentsSystemUserCallbacks.aidl b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/IRecentsSystemUserCallbacks.aidl
deleted file mode 100644
index e977144..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/IRecentsSystemUserCallbacks.aidl
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents;
-
-import android.graphics.Rect;
-
-/**
- * Due to the fact that RecentsActivity is per-user, we need to establish an
- * interface (this) for the non-system user to register itself for callbacks and to
- * callback to the system user to update internal state.
- */
-oneway interface IRecentsSystemUserCallbacks {
-    void registerNonSystemUserCallbacks(IBinder nonSystemUserCallbacks, int userId);
-
-    void updateRecentsVisibility(boolean visible);
-    void startScreenPinning(int taskId);
-    void sendRecentsDrawnEvent();
-    void sendDockingTopTaskEvent(in Rect initialRect);
-    void sendLaunchRecentsEvent();
-    void sendDockedFirstAnimationFrameEvent();
-    void setWaitingForTransitionStartEvent(boolean waitingForTransitionStart);
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/LegacyRecentsImpl.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/LegacyRecentsImpl.java
deleted file mode 100644
index a150de9..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/LegacyRecentsImpl.java
+++ /dev/null
@@ -1,750 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents;
-
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
-import static com.android.systemui.statusbar.phone.StatusBar.SYSTEM_DIALOG_REASON_RECENT_APPS;
-
-import android.app.ActivityManager;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.content.pm.ActivityInfo;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.hardware.display.DisplayManager;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.os.UserHandle;
-import android.util.EventLog;
-import android.util.Log;
-import android.view.Display;
-import android.widget.Toast;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.systemui.EventLogConstants;
-import com.android.systemui.EventLogTags;
-import com.android.systemui.R;
-import com.android.systemui.SysUiServiceProvider;
-import com.android.systemui.pip.PipUI;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.ConfigurationChangedEvent;
-import com.android.systemui.recents.events.activity.DockedFirstAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.DockedTopTaskEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskFailedEvent;
-import com.android.systemui.recents.events.activity.RecentsActivityStartingEvent;
-import com.android.systemui.recents.events.component.ExpandPipEvent;
-import com.android.systemui.recents.events.component.HidePipMenuEvent;
-import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent;
-import com.android.systemui.recents.events.component.ScreenPinningRequestEvent;
-import com.android.systemui.recents.events.component.SetWaitingForTransitionStartEvent;
-import com.android.systemui.recents.events.component.ShowUserToastEvent;
-import com.android.systemui.recents.events.ui.RecentsDrawnEvent;
-import com.android.systemui.recents.events.ui.RecentsGrowingEvent;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.model.RecentsTaskLoader;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-import com.android.systemui.stackdivider.Divider;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * An implementation of the SystemUI recents component, which supports both system and secondary
- * users.
- */
-public class LegacyRecentsImpl implements RecentsImplementation {
-
-    private final static String TAG = "Recents";
-
-    public final static int EVENT_BUS_PRIORITY = 1;
-    public final static int BIND_TO_SYSTEM_USER_RETRY_DELAY = 5000;
-
-    public final static Set<String> RECENTS_ACTIVITIES = new HashSet<>();
-    static {
-        RECENTS_ACTIVITIES.add(RecentsImpl.RECENTS_ACTIVITY);
-    }
-
-    private static final String COUNTER_WINDOW_SUPPORTED = "window_enter_supported";
-    private static final String COUNTER_WINDOW_UNSUPPORTED = "window_enter_unsupported";
-    private static final String COUNTER_WINDOW_INCOMPATIBLE = "window_enter_incompatible";
-
-    private static SystemServicesProxy sSystemServicesProxy;
-    private static RecentsDebugFlags sDebugFlags;
-    private static RecentsTaskLoader sTaskLoader;
-    private static RecentsConfiguration sConfiguration;
-
-    private Context mContext;
-    private SysUiServiceProvider mSysUiServiceProvider;
-    private Handler mHandler;
-    private RecentsImpl mImpl;
-
-    // Only For system user, this is the callbacks instance we return to each secondary user
-    private RecentsSystemUser mSystemToUserCallbacks;
-
-    // Only for secondary users, this is the callbacks instance provided by the system user to make
-    // calls back
-    private IRecentsSystemUserCallbacks mUserToSystemCallbacks;
-
-    // The set of runnables to run after binding to the system user's service.
-    private final ArrayList<Runnable> mOnConnectRunnables = new ArrayList<>();
-
-    // Only for secondary users, this is the death handler for the binder from the system user
-    private final IBinder.DeathRecipient mUserToSystemCallbacksDeathRcpt = new IBinder.DeathRecipient() {
-        @Override
-        public void binderDied() {
-            mUserToSystemCallbacks = null;
-            EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION,
-                    EventLogConstants.SYSUI_RECENTS_CONNECTION_USER_SYSTEM_UNBOUND,
-                    sSystemServicesProxy.getProcessUser());
-
-            // Retry after a fixed duration
-            mHandler.postDelayed(new Runnable() {
-                @Override
-                public void run() {
-                    registerWithSystemUser();
-                }
-            }, BIND_TO_SYSTEM_USER_RETRY_DELAY);
-        }
-    };
-
-    // Only for secondary users, this is the service connection we use to connect to the system user
-    private final ServiceConnection mUserToSystemServiceConnection = new ServiceConnection() {
-        @Override
-        public void onServiceConnected(ComponentName name, IBinder service) {
-            if (service != null) {
-                mUserToSystemCallbacks = IRecentsSystemUserCallbacks.Stub.asInterface(
-                        service);
-                EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION,
-                        EventLogConstants.SYSUI_RECENTS_CONNECTION_USER_SYSTEM_BOUND,
-                        sSystemServicesProxy.getProcessUser());
-
-                // Listen for system user's death, so that we can reconnect later
-                try {
-                    service.linkToDeath(mUserToSystemCallbacksDeathRcpt, 0);
-                } catch (RemoteException e) {
-                    Log.e(TAG, "Lost connection to (System) SystemUI", e);
-                }
-
-                // Run each of the queued runnables
-                runAndFlushOnConnectRunnables();
-            }
-
-            // Unbind ourselves now that we've registered our callbacks.  The
-            // binder to the system user are still valid at this point.
-            mContext.unbindService(this);
-        }
-
-        @Override
-        public void onServiceDisconnected(ComponentName name) {
-            // Do nothing
-        }
-    };
-
-    /**
-     * Returns the callbacks interface that non-system users can call.
-     */
-    public IBinder getSystemUserCallbacks() {
-        return mSystemToUserCallbacks;
-    }
-
-    public static RecentsTaskLoader getTaskLoader() {
-        return sTaskLoader;
-    }
-
-
-    public static SystemServicesProxy getSystemServices() {
-        return sSystemServicesProxy;
-    }
-
-    public static RecentsConfiguration getConfiguration() {
-        return sConfiguration;
-    }
-
-    public static RecentsDebugFlags getDebugFlags() {
-        return sDebugFlags;
-    }
-
-    @Override
-    public void onStart(Context context, SysUiServiceProvider sysUiServiceProvider) {
-        mContext = context;
-        mSysUiServiceProvider = sysUiServiceProvider;
-        final Resources res = mContext.getResources();
-        final int defaultTaskBarBackgroundColor =
-                mContext.getColor(R.color.recents_task_bar_default_background_color);
-        final int defaultTaskViewBackgroundColor =
-                mContext.getColor(R.color.recents_task_view_default_background_color);
-        sDebugFlags = new RecentsDebugFlags();
-        sSystemServicesProxy = SystemServicesProxy.getInstance(mContext);
-        sConfiguration = new RecentsConfiguration(mContext);
-        sTaskLoader = new RecentsTaskLoader(mContext,
-                // TODO: Once we start building the AAR, move these into the loader
-                res.getInteger(R.integer.config_recents_max_thumbnail_count),
-                res.getInteger(R.integer.config_recents_max_icon_count),
-                res.getInteger(R.integer.recents_svelte_level));
-        sTaskLoader.setDefaultColors(defaultTaskBarBackgroundColor, defaultTaskViewBackgroundColor);
-        mHandler = new Handler();
-        mImpl = new RecentsImpl(mContext);
-
-        // Register with the event bus
-        EventBus.getDefault().register(this, EVENT_BUS_PRIORITY);
-        EventBus.getDefault().register(sSystemServicesProxy, EVENT_BUS_PRIORITY);
-        EventBus.getDefault().register(sTaskLoader, EVENT_BUS_PRIORITY);
-
-        // Due to the fact that RecentsActivity is per-user, we need to establish and interface for
-        // the system user's Recents component to pass events (like show/hide/toggleRecents) to the
-        // secondary user, and vice versa (like visibility change, screen pinning).
-        final int processUser = sSystemServicesProxy.getProcessUser();
-        if (sSystemServicesProxy.isSystemUser(processUser)) {
-            // For the system user, initialize an instance of the interface that we can pass to the
-            // secondary user
-            mSystemToUserCallbacks = new RecentsSystemUser(mContext, mImpl);
-        } else {
-            // For the secondary user, bind to the primary user's service to get a persistent
-            // interface to register its implementation and to later update its state
-            registerWithSystemUser();
-        }
-    }
-
-    @Override
-    public void onBootCompleted() {
-        mImpl.onBootCompleted();
-    }
-
-
-    @Override
-    public void growRecents() {
-        EventBus.getDefault().send(new RecentsGrowingEvent());
-    }
-
-    /**
-     * Shows the Recents.
-     */
-    @Override
-    public void showRecentApps(boolean triggeredFromAltTab) {
-        ActivityManagerWrapper.getInstance().closeSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
-        int recentsGrowTarget = getComponent(Divider.class).getView().growsRecents();
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        if (sSystemServicesProxy.isSystemUser(currentUser)) {
-            mImpl.showRecents(triggeredFromAltTab, false /* draggingInRecents */,
-                    true /* animate */, recentsGrowTarget);
-        } else {
-            if (mSystemToUserCallbacks != null) {
-                IRecentsNonSystemUserCallbacks callbacks =
-                        mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                if (callbacks != null) {
-                    try {
-                        callbacks.showRecents(triggeredFromAltTab, false /* draggingInRecents */,
-                                true /* animate */, recentsGrowTarget);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                } else {
-                    Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                }
-            }
-        }
-    }
-
-    /**
-     * Hides the Recents.
-     */
-    @Override
-    public void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) {
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        if (sSystemServicesProxy.isSystemUser(currentUser)) {
-            mImpl.hideRecents(triggeredFromAltTab, triggeredFromHomeKey);
-        } else {
-            if (mSystemToUserCallbacks != null) {
-                IRecentsNonSystemUserCallbacks callbacks =
-                        mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                if (callbacks != null) {
-                    try {
-                        callbacks.hideRecents(triggeredFromAltTab, triggeredFromHomeKey);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                } else {
-                    Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                }
-            }
-        }
-    }
-
-    /**
-     * Toggles the Recents activity.
-     */
-    @Override
-    public void toggleRecentApps() {
-        int growTarget = getComponent(Divider.class).getView().growsRecents();
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        if (sSystemServicesProxy.isSystemUser(currentUser)) {
-            mImpl.toggleRecents(growTarget);
-        } else {
-            if (mSystemToUserCallbacks != null) {
-                IRecentsNonSystemUserCallbacks callbacks =
-                        mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                if (callbacks != null) {
-                    try {
-                        callbacks.toggleRecents(growTarget);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                } else {
-                    Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                }
-            }
-        }
-    }
-
-    /**
-     * Preloads info for the Recents activity.
-     */
-    @Override
-    public void preloadRecentApps() {
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        if (sSystemServicesProxy.isSystemUser(currentUser)) {
-            mImpl.preloadRecents();
-        } else {
-            if (mSystemToUserCallbacks != null) {
-                IRecentsNonSystemUserCallbacks callbacks =
-                        mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                if (callbacks != null) {
-                    try {
-                        callbacks.preloadRecents();
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                } else {
-                    Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                }
-            }
-        }
-    }
-
-    @Override
-    public void cancelPreloadRecentApps() {
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        if (sSystemServicesProxy.isSystemUser(currentUser)) {
-            mImpl.cancelPreloadingRecents();
-        } else {
-            if (mSystemToUserCallbacks != null) {
-                IRecentsNonSystemUserCallbacks callbacks =
-                        mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                if (callbacks != null) {
-                    try {
-                        callbacks.cancelPreloadingRecents();
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                } else {
-                    Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                }
-            }
-        }
-    }
-
-    @Override
-    public boolean splitPrimaryTask(int stackCreateMode, Rect initialBounds, int metricsDockAction) {
-        Point realSize = new Point();
-        if (initialBounds == null) {
-            mContext.getSystemService(DisplayManager.class).getDisplay(Display.DEFAULT_DISPLAY)
-                    .getRealSize(realSize);
-            initialBounds = new Rect(0, 0, realSize.x, realSize.y);
-        }
-
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        ActivityManager.RunningTaskInfo runningTask =
-                ActivityManagerWrapper.getInstance().getRunningTask();
-        final int activityType = runningTask != null
-                ? runningTask.configuration.windowConfiguration.getActivityType()
-                : ACTIVITY_TYPE_UNDEFINED;
-        boolean screenPinningActive = ActivityManagerWrapper.getInstance().isScreenPinningActive();
-        boolean isRunningTaskInHomeOrRecentsStack =
-                activityType == ACTIVITY_TYPE_HOME || activityType == ACTIVITY_TYPE_RECENTS;
-        if (runningTask != null && !isRunningTaskInHomeOrRecentsStack && !screenPinningActive) {
-            logDockAttempt(mContext, runningTask.topActivity, runningTask.resizeMode);
-            if (runningTask.supportsSplitScreenMultiWindow) {
-                if (metricsDockAction != -1) {
-                    MetricsLogger.action(mContext, metricsDockAction,
-                            runningTask.topActivity.flattenToShortString());
-                }
-                if (sSystemServicesProxy.isSystemUser(currentUser)) {
-                    mImpl.splitPrimaryTask(runningTask.id, stackCreateMode, initialBounds);
-                } else {
-                    if (mSystemToUserCallbacks != null) {
-                        IRecentsNonSystemUserCallbacks callbacks =
-                                mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                        if (callbacks != null) {
-                            try {
-                                callbacks.splitPrimaryTask(runningTask.id, stackCreateMode,
-                                        initialBounds);
-                            } catch (RemoteException e) {
-                                Log.e(TAG, "Callback failed", e);
-                            }
-                        } else {
-                            Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                        }
-                    }
-                }
-
-                return true;
-            } else {
-                EventBus.getDefault().send(new ShowUserToastEvent(
-                        R.string.dock_non_resizeble_failed_to_dock_text, Toast.LENGTH_SHORT));
-                return false;
-            }
-        } else {
-            return false;
-        }
-    }
-
-    public static void logDockAttempt(Context ctx, ComponentName activity, int resizeMode) {
-        if (resizeMode == ActivityInfo.RESIZE_MODE_UNRESIZEABLE) {
-            MetricsLogger.action(ctx, MetricsEvent.ACTION_WINDOW_DOCK_UNRESIZABLE,
-                    activity.flattenToShortString());
-        }
-        MetricsLogger.count(ctx, getMetricsCounterForResizeMode(resizeMode), 1);
-    }
-
-    private static String getMetricsCounterForResizeMode(int resizeMode) {
-        switch (resizeMode) {
-            case ActivityInfo.RESIZE_MODE_FORCE_RESIZEABLE:
-                return COUNTER_WINDOW_UNSUPPORTED;
-            case ActivityInfo.RESIZE_MODE_RESIZEABLE:
-            case ActivityInfo.RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION:
-                return COUNTER_WINDOW_SUPPORTED;
-            default:
-                return COUNTER_WINDOW_INCOMPATIBLE;
-        }
-    }
-
-    @Override
-    public void onAppTransitionFinished() {
-        if (!LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            // Fallback, reset the flag once an app transition ends
-            EventBus.getDefault().send(new SetWaitingForTransitionStartEvent(
-                    false /* waitingForTransitionStart */));
-        }
-    }
-
-    /**
-     * Updates on configuration change.
-     */
-    public void onConfigurationChanged(Configuration newConfig) {
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        if (sSystemServicesProxy.isSystemUser(currentUser)) {
-            mImpl.onConfigurationChanged();
-        } else {
-            if (mSystemToUserCallbacks != null) {
-                IRecentsNonSystemUserCallbacks callbacks =
-                        mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                if (callbacks != null) {
-                    try {
-                        callbacks.onConfigurationChanged();
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                } else {
-                    Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                }
-            }
-        }
-    }
-
-    /**
-     * Handle Recents activity visibility changed.
-     */
-    public final void onBusEvent(final RecentsVisibilityChangedEvent event) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        int processUser = ssp.getProcessUser();
-        if (ssp.isSystemUser(processUser)) {
-            mImpl.onVisibilityChanged(event.applicationContext, event.visible);
-        } else {
-            postToSystemUser(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        mUserToSystemCallbacks.updateRecentsVisibility(event.visible);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                }
-            });
-        }
-
-        // This will catch the cases when a user launches from recents to another app
-        // (and vice versa) that is not in the recents stack (such as home or bugreport) and it
-        // would not reset the wait for transition flag. This will catch it and make sure that the
-        // flag is reset.
-        if (!event.visible) {
-            mImpl.setWaitingForTransitionStart(false);
-        }
-    }
-
-    public final void onBusEvent(DockedFirstAnimationFrameEvent event) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        int processUser = ssp.getProcessUser();
-        if (ssp.isSystemUser(processUser)) {
-            final Divider divider = getComponent(Divider.class);
-            if (divider != null) {
-                divider.onDockedFirstAnimationFrame();
-            }
-        } else {
-            postToSystemUser(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        mUserToSystemCallbacks.sendDockedFirstAnimationFrameEvent();
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                }
-            });
-        }
-    }
-
-    /**
-     * Handle screen pinning request.
-     */
-    public final void onBusEvent(final ScreenPinningRequestEvent event) {
-        int processUser = sSystemServicesProxy.getProcessUser();
-        if (sSystemServicesProxy.isSystemUser(processUser)) {
-            mImpl.onStartScreenPinning(event.applicationContext, event.taskId);
-        } else {
-            postToSystemUser(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        mUserToSystemCallbacks.startScreenPinning(event.taskId);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                }
-            });
-        }
-    }
-
-    public final void onBusEvent(final RecentsDrawnEvent event) {
-        int processUser = sSystemServicesProxy.getProcessUser();
-        if (sSystemServicesProxy.isSystemUser(processUser)) {
-            final Divider divider = getComponent(Divider.class);
-            if (divider != null) {
-                divider.onRecentsDrawn();
-            }
-        } else {
-            postToSystemUser(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        mUserToSystemCallbacks.sendRecentsDrawnEvent();
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                }
-            });
-        }
-    }
-
-    public final void onBusEvent(final DockedTopTaskEvent event) {
-        int processUser = sSystemServicesProxy.getProcessUser();
-        if (sSystemServicesProxy.isSystemUser(processUser)) {
-            final Divider divider = getComponent(Divider.class);
-            if (divider != null) {
-                divider.onDockedTopTask();
-            }
-        } else {
-            postToSystemUser(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        mUserToSystemCallbacks.sendDockingTopTaskEvent(event.initialRect);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                }
-            });
-        }
-    }
-
-    public final void onBusEvent(final RecentsActivityStartingEvent event) {
-        int processUser = sSystemServicesProxy.getProcessUser();
-        if (sSystemServicesProxy.isSystemUser(processUser)) {
-            final Divider divider = getComponent(Divider.class);
-            if (divider != null) {
-                divider.onRecentsActivityStarting();
-            }
-        } else {
-            postToSystemUser(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        mUserToSystemCallbacks.sendLaunchRecentsEvent();
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                }
-            });
-        }
-    }
-
-    public final void onBusEvent(LaunchTaskFailedEvent event) {
-        // Reset the transition when tasks fail to launch
-        mImpl.setWaitingForTransitionStart(false);
-    }
-
-    public final void onBusEvent(ConfigurationChangedEvent event) {
-        // Update the configuration for the Recents component when the activity configuration
-        // changes as well
-        mImpl.onConfigurationChanged();
-    }
-
-    public final void onBusEvent(ShowUserToastEvent event) {
-        int currentUser = sSystemServicesProxy.getCurrentUser();
-        if (sSystemServicesProxy.isSystemUser(currentUser)) {
-            mImpl.onShowCurrentUserToast(event.msgResId, event.msgLength);
-        } else {
-            if (mSystemToUserCallbacks != null) {
-                IRecentsNonSystemUserCallbacks callbacks =
-                        mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser);
-                if (callbacks != null) {
-                    try {
-                        callbacks.showCurrentUserToast(event.msgResId, event.msgLength);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                } else {
-                    Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser);
-                }
-            }
-        }
-    }
-
-    public final void onBusEvent(SetWaitingForTransitionStartEvent event) {
-        int processUser = sSystemServicesProxy.getProcessUser();
-        if (sSystemServicesProxy.isSystemUser(processUser)) {
-            mImpl.setWaitingForTransitionStart(event.waitingForTransitionStart);
-        } else {
-            postToSystemUser(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        mUserToSystemCallbacks.setWaitingForTransitionStartEvent(
-                                event.waitingForTransitionStart);
-                    } catch (RemoteException e) {
-                        Log.e(TAG, "Callback failed", e);
-                    }
-                }
-            });
-        }
-    }
-
-    public final void onBusEvent(ExpandPipEvent event) {
-        PipUI pipUi = getComponent(PipUI.class);
-        if (pipUi == null) {
-            return;
-        }
-        pipUi.expandPip();
-    }
-
-    public final void onBusEvent(HidePipMenuEvent event) {
-        PipUI pipUi = getComponent(PipUI.class);
-        if (pipUi == null) {
-            return;
-        }
-        event.getAnimationTrigger().increment();
-        pipUi.hidePipMenu(() -> {
-                event.getAnimationTrigger().increment();
-            }, () -> {
-                event.getAnimationTrigger().decrement();
-            });
-        event.getAnimationTrigger().decrement();
-    }
-
-    /**
-     * Attempts to register with the system user.
-     */
-    private void registerWithSystemUser() {
-        final int processUser = sSystemServicesProxy.getProcessUser();
-        postToSystemUser(new Runnable() {
-            @Override
-            public void run() {
-                try {
-                    mUserToSystemCallbacks.registerNonSystemUserCallbacks(
-                            new RecentsImplProxy(mImpl), processUser);
-                } catch (RemoteException e) {
-                    Log.e(TAG, "Failed to register", e);
-                }
-            }
-        });
-    }
-
-    /**
-     * Runs the runnable in the system user's Recents context, connecting to the service if
-     * necessary.
-     */
-    private void postToSystemUser(final Runnable onConnectRunnable) {
-        mOnConnectRunnables.add(onConnectRunnable);
-        if (mUserToSystemCallbacks == null) {
-            Intent systemUserServiceIntent = new Intent();
-            systemUserServiceIntent.setClass(mContext, RecentsSystemUserService.class);
-            boolean bound = mContext.bindServiceAsUser(systemUserServiceIntent,
-                    mUserToSystemServiceConnection, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM);
-            EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION,
-                    EventLogConstants.SYSUI_RECENTS_CONNECTION_USER_BIND_SERVICE,
-                    sSystemServicesProxy.getProcessUser());
-            if (!bound) {
-                // Retry after a fixed duration
-                mHandler.postDelayed(new Runnable() {
-                    @Override
-                    public void run() {
-                        registerWithSystemUser();
-                    }
-                }, BIND_TO_SYSTEM_USER_RETRY_DELAY);
-            }
-        } else {
-            runAndFlushOnConnectRunnables();
-        }
-    }
-
-    /**
-     * Runs all the queued runnables after a service connection is made.
-     */
-    private void runAndFlushOnConnectRunnables() {
-        for (Runnable r : mOnConnectRunnables) {
-            r.run();
-        }
-        mOnConnectRunnables.clear();
-    }
-
-    private <T> T getComponent(Class<T> clazz) {
-        return mSysUiServiceProvider.getComponent(clazz);
-    }
-
-    @Override
-    public void dump(PrintWriter pw) {
-        pw.println("Recents");
-        pw.println("  currentUserId=" + SystemServicesProxy.getInstance(mContext).getCurrentUser());
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsActivity.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsActivity.java
deleted file mode 100644
index a7ccc3a..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsActivity.java
+++ /dev/null
@@ -1,858 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents;
-
-import static com.android.systemui.statusbar.phone.StatusBar.SYSTEM_DIALOG_REASON_HOME_KEY;
-
-import android.app.Activity;
-import android.app.ActivityOptions;
-import android.app.TaskStackBuilder;
-import android.app.WallpaperManager;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.res.Configuration;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.SystemClock;
-import android.os.UserHandle;
-import android.provider.Settings;
-import android.util.Log;
-import android.view.KeyEvent;
-import android.view.View;
-import android.view.ViewTreeObserver;
-import android.view.ViewTreeObserver.OnPreDrawListener;
-import android.view.WindowManager;
-import android.view.WindowManager.LayoutParams;
-
-import com.android.internal.colorextraction.ColorExtractor;
-import com.android.internal.content.PackageMonitor;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.internal.util.LatencyTracker;
-import com.android.systemui.DejankUtils;
-import com.android.systemui.Dependency;
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.colorextraction.SysuiColorExtractor;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.CancelEnterRecentsWindowAnimationEvent;
-import com.android.systemui.recents.events.activity.ConfigurationChangedEvent;
-import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
-import com.android.systemui.recents.events.activity.DockedFirstAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.DockedTopTaskEvent;
-import com.android.systemui.recents.events.activity.EnterRecentsWindowAnimationCompletedEvent;
-import com.android.systemui.recents.events.activity.EnterRecentsWindowLastAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.ExitRecentsWindowFirstAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.HideRecentsEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskFailedEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskSucceededEvent;
-import com.android.systemui.recents.events.activity.MultiWindowStateChangedEvent;
-import com.android.systemui.recents.events.activity.PackagesChangedEvent;
-import com.android.systemui.recents.events.activity.RecentsActivityStartingEvent;
-import com.android.systemui.recents.events.activity.ToggleRecentsEvent;
-import com.android.systemui.recents.events.component.ActivityUnpinnedEvent;
-import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent;
-import com.android.systemui.recents.events.component.ScreenPinningRequestEvent;
-import com.android.systemui.recents.events.component.SetWaitingForTransitionStartEvent;
-import com.android.systemui.recents.events.ui.AllTaskViewsDismissedEvent;
-import com.android.systemui.recents.events.ui.DeleteTaskDataEvent;
-import com.android.systemui.recents.events.ui.HideIncompatibleAppOverlayEvent;
-import com.android.systemui.recents.events.ui.RecentsDrawnEvent;
-import com.android.systemui.recents.events.ui.ShowApplicationInfoEvent;
-import com.android.systemui.recents.events.ui.ShowIncompatibleAppOverlayEvent;
-import com.android.systemui.recents.events.ui.StackViewScrolledEvent;
-import com.android.systemui.recents.events.ui.TaskViewDismissedEvent;
-import com.android.systemui.recents.events.ui.UserInteractionEvent;
-import com.android.systemui.recents.events.ui.focus.DismissFocusedTaskViewEvent;
-import com.android.systemui.recents.events.ui.focus.FocusNextTaskViewEvent;
-import com.android.systemui.recents.events.ui.focus.FocusPreviousTaskViewEvent;
-import com.android.systemui.recents.events.ui.focus.NavigateTaskViewEvent;
-import com.android.systemui.recents.events.ui.focus.NavigateTaskViewEvent.Direction;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.model.RecentsTaskLoadPlan;
-import com.android.systemui.recents.model.RecentsTaskLoader;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.recents.views.RecentsView;
-import com.android.systemui.recents.views.SystemBarScrimViews;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-
-/**
- * The main Recents activity that is started from RecentsComponent.
- */
-public class RecentsActivity extends Activity implements ViewTreeObserver.OnPreDrawListener,
-        ColorExtractor.OnColorsChangedListener {
-
-    private final static String TAG = "RecentsActivity";
-    private final static boolean DEBUG = false;
-
-    public final static int EVENT_BUS_PRIORITY = LegacyRecentsImpl.EVENT_BUS_PRIORITY + 1;
-    public final static int INCOMPATIBLE_APP_ALPHA_DURATION = 150;
-
-    private PackageMonitor mPackageMonitor = new PackageMonitor() {
-            @Override
-            public void onPackageRemoved(String packageName, int uid) {
-                RecentsActivity.this.onPackageChanged(packageName, getChangingUserId());
-            }
-
-            @Override
-            public boolean onPackageChanged(String packageName, int uid, String[] components) {
-                RecentsActivity.this.onPackageChanged(packageName, getChangingUserId());
-                return true;
-            }
-
-            @Override
-            public void onPackageModified(String packageName) {
-                RecentsActivity.this.onPackageChanged(packageName, getChangingUserId());
-            }
-        };
-    private Handler mHandler = new Handler();
-    private long mLastTabKeyEventTime;
-    private boolean mFinishedOnStartup;
-    private boolean mIgnoreAltTabRelease;
-    private boolean mIsVisible;
-    private boolean mRecentsStartRequested;
-    private Configuration mLastConfig;
-
-    // Top level views
-    private RecentsView mRecentsView;
-    private SystemBarScrimViews mScrimViews;
-    private View mIncompatibleAppOverlay;
-
-    // Runnables to finish the Recents activity
-    private Intent mHomeIntent;
-
-    // The trigger to automatically launch the current task
-    private int mFocusTimerDuration;
-    private final UserInteractionEvent mUserInteractionEvent = new UserInteractionEvent();
-
-    // Theme and colors
-    private SysuiColorExtractor mColorExtractor;
-    private boolean mUsingDarkText;
-
-    /**
-     * A common Runnable to finish Recents by launching Home with an animation depending on the
-     * last activity launch state. Generally we always launch home when we exit Recents rather than
-     * just finishing the activity since we don't know what is behind Recents in the task stack.
-     */
-    class LaunchHomeRunnable implements Runnable {
-
-        Intent mLaunchIntent;
-        ActivityOptions mOpts;
-
-        /**
-         * Creates a finish runnable that starts the specified intent.
-         */
-        public LaunchHomeRunnable(Intent launchIntent, ActivityOptions opts) {
-            mLaunchIntent = launchIntent;
-            mOpts = opts;
-        }
-
-        @Override
-        public void run() {
-            try {
-                mHandler.post(() -> {
-                    ActivityOptions opts = mOpts;
-                    if (opts == null) {
-                        opts = ActivityOptions.makeCustomAnimation(RecentsActivity.this,
-                                R.anim.recents_to_launcher_enter, R.anim.recents_to_launcher_exit);
-                    }
-                    startActivityAsUser(mLaunchIntent, opts.toBundle(), UserHandle.CURRENT);
-                });
-            } catch (Exception e) {
-                Log.e(TAG, getString(R.string.recents_launch_error_message, "Home"), e);
-            }
-        }
-    }
-
-    /**
-     * Broadcast receiver to handle messages from the system
-     */
-    final BroadcastReceiver mSystemBroadcastReceiver = new BroadcastReceiver() {
-        @Override
-        public void onReceive(Context ctx, Intent intent) {
-            String action = intent.getAction();
-            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
-                // When the screen turns off, dismiss Recents to Home
-                dismissRecentsToHomeIfVisible(false);
-            } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
-                // When switching users, dismiss Recents to Home similar to screen off
-                finish();
-            }
-        }
-    };
-
-    private final OnPreDrawListener mRecentsDrawnEventListener =
-            new ViewTreeObserver.OnPreDrawListener() {
-                @Override
-                public boolean onPreDraw() {
-                    mRecentsView.getViewTreeObserver().removeOnPreDrawListener(this);
-                    EventBus.getDefault().post(new RecentsDrawnEvent());
-                    if (LatencyTracker.isEnabled(getApplicationContext())) {
-                        DejankUtils.postAfterTraversal(() -> LatencyTracker.getInstance(
-                                getApplicationContext()).onActionEnd(
-                                LatencyTracker.ACTION_TOGGLE_RECENTS));
-                    }
-                    DejankUtils.postAfterTraversal(() -> {
-                        LegacyRecentsImpl.getTaskLoader().startLoader(RecentsActivity.this);
-                        LegacyRecentsImpl.getTaskLoader().getHighResThumbnailLoader().setVisible(true);
-                    });
-                    return true;
-                }
-            };
-
-    /**
-     * Dismisses recents if we are already visible and the intent is to toggle the recents view.
-     */
-    boolean dismissRecentsToFocusedTask(int logCategory) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        if (ssp.isRecentsActivityVisible()) {
-            // If we have a focused Task, launch that Task now
-            if (mRecentsView.launchFocusedTask(logCategory)) return true;
-        }
-        return false;
-    }
-
-    /**
-     * Dismisses recents back to the launch target task.
-     */
-    boolean dismissRecentsToLaunchTargetTaskOrHome() {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        if (ssp.isRecentsActivityVisible()) {
-            // If we have a focused Task, launch that Task now
-            if (mRecentsView.launchPreviousTask()) return true;
-            // If none of the other cases apply, then just go Home
-            dismissRecentsToHome(true /* animateTaskViews */);
-        }
-        return false;
-    }
-
-    /**
-     * Dismisses recents if we are already visible and the intent is to toggle the recents view.
-     */
-    boolean dismissRecentsToFocusedTaskOrHome() {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        if (ssp.isRecentsActivityVisible()) {
-            // If we have a focused Task, launch that Task now
-            if (mRecentsView.launchFocusedTask(0 /* logCategory */)) return true;
-            // If none of the other cases apply, then just go Home
-            dismissRecentsToHome(true /* animateTaskViews */);
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Dismisses Recents directly to Home without checking whether it is currently visible.
-     */
-    void dismissRecentsToHome(boolean animateTaskViews) {
-        dismissRecentsToHome(animateTaskViews, null);
-    }
-
-    /**
-     * Dismisses Recents directly to Home without checking whether it is currently visible.
-     *
-     * @param overrideAnimation If not null, will override the default animation that is based on
-     *                          how Recents was launched.
-     */
-    void dismissRecentsToHome(boolean animateTaskViews, ActivityOptions overrideAnimation) {
-        DismissRecentsToHomeAnimationStarted dismissEvent =
-                new DismissRecentsToHomeAnimationStarted(animateTaskViews);
-        dismissEvent.addPostAnimationCallback(new LaunchHomeRunnable(mHomeIntent,
-                overrideAnimation));
-        ActivityManagerWrapper.getInstance().closeSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
-        EventBus.getDefault().send(dismissEvent);
-    }
-
-    /** Dismisses Recents directly to Home if we currently aren't transitioning. */
-    boolean dismissRecentsToHomeIfVisible(boolean animated) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        if (ssp.isRecentsActivityVisible()) {
-            // Return to Home
-            dismissRecentsToHome(animated);
-            return true;
-        }
-        return false;
-    }
-
-    /** Called with the activity is first created. */
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        mFinishedOnStartup = false;
-
-        // In the case that the activity starts up before the Recents component has initialized
-        // (usually when debugging/pushing the SysUI apk), just finish this activity.
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        if (ssp == null) {
-            mFinishedOnStartup = true;
-            finish();
-            return;
-        }
-
-        // Register this activity with the event bus
-        EventBus.getDefault().register(this, EVENT_BUS_PRIORITY);
-
-        // Initialize the package monitor
-        mPackageMonitor.register(this, Looper.getMainLooper(), UserHandle.ALL,
-                true /* externalStorage */);
-
-        // Select theme based on wallpaper colors
-        mColorExtractor = Dependency.get(SysuiColorExtractor.class);
-        mColorExtractor.addOnColorsChangedListener(this);
-        mUsingDarkText = mColorExtractor.getColors(ColorExtractor.TYPE_DARK,
-                WallpaperManager.FLAG_SYSTEM).supportsDarkText();
-        setTheme(mUsingDarkText ? R.style.RecentsTheme_Wallpaper_Light
-                : R.style.RecentsTheme_Wallpaper);
-
-        // Set the Recents layout
-        setContentView(R.layout.recents);
-        takeKeyEvents(true);
-        mRecentsView = findViewById(R.id.recents_view);
-        mScrimViews = new SystemBarScrimViews(this);
-        getWindow().getAttributes().privateFlags |=
-                WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY;
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
-        }
-
-        mLastConfig = new Configuration(Utilities.getAppConfiguration(this));
-
-        // Set the window background
-        mRecentsView.updateBackgroundScrim(getWindow(), isInMultiWindowMode());
-
-        // Create the home intent runnable
-        mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
-        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
-        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
-                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
-
-        // Register the broadcast receiver to handle messages when the screen is turned off
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(Intent.ACTION_SCREEN_OFF);
-        filter.addAction(Intent.ACTION_USER_SWITCHED);
-        registerReceiver(mSystemBroadcastReceiver, filter);
-
-        getWindow().addPrivateFlags(LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION);
-    }
-
-    @Override
-    protected void onStart() {
-        super.onStart();
-
-        // Reload the stack view whenever we are made visible again
-        reloadStackView();
-
-        // Notify that recents is now visible
-        EventBus.getDefault().send(new RecentsVisibilityChangedEvent(this, true));
-        MetricsLogger.visible(this, MetricsEvent.OVERVIEW_ACTIVITY);
-
-        // Getting system scrim colors ignoring wallpaper visibility since it should never be grey.
-        ColorExtractor.GradientColors systemColors = mColorExtractor.getNeutralColors();
-        // We don't want to interpolate colors because we're defining the initial state.
-        // Gradient should be set/ready when you open "Recents".
-        mRecentsView.setScrimColors(systemColors, false);
-
-        // Notify of the next draw
-        mRecentsView.getViewTreeObserver().addOnPreDrawListener(mRecentsDrawnEventListener);
-
-        // If Recents was restarted, then it should complete the enter animation with partially
-        // reset launch state with dock, app and home set to false
-        Object isRelaunching = getLastNonConfigurationInstance();
-        if (isRelaunching != null && isRelaunching instanceof Boolean && (boolean) isRelaunching) {
-            RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-            launchState.launchedViaDockGesture = false;
-            launchState.launchedFromApp = false;
-            launchState.launchedFromHome = false;
-            onEnterAnimationComplete();
-        }
-        mRecentsStartRequested = false;
-    }
-
-    @Override
-    public void onColorsChanged(ColorExtractor colorExtractor, int which) {
-        if ((which & WallpaperManager.FLAG_SYSTEM) != 0) {
-            ColorExtractor.GradientColors colors = mColorExtractor.getNeutralColors();
-            boolean darkText = colors.supportsDarkText();
-            if (darkText != mUsingDarkText) {
-                mUsingDarkText = darkText;
-                setTheme(mUsingDarkText ? R.style.RecentsTheme_Wallpaper_Light
-                        : R.style.RecentsTheme_Wallpaper);
-                mRecentsView.reevaluateStyles();
-            }
-            mRecentsView.setScrimColors(colors, true /* animated */);
-        }
-    }
-
-    /**
-     * Reloads the stack views upon launching Recents.
-     */
-    private void reloadStackView() {
-        // If the Recents component has preloaded a load plan, then use that to prevent
-        // reconstructing the task stack
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        RecentsTaskLoadPlan loadPlan = RecentsImpl.consumeInstanceLoadPlan();
-        if (loadPlan == null) {
-            loadPlan = new RecentsTaskLoadPlan(this);
-        }
-
-        // Start loading tasks according to the load plan
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        RecentsActivityLaunchState launchState = config.getLaunchState();
-        if (!loadPlan.hasTasks()) {
-            loader.preloadTasks(loadPlan, launchState.launchedToTaskId);
-        }
-
-        RecentsTaskLoadPlan.Options loadOpts = new RecentsTaskLoadPlan.Options();
-        loadOpts.runningTaskId = launchState.launchedToTaskId;
-        loadOpts.numVisibleTasks = launchState.launchedNumVisibleTasks;
-        loadOpts.numVisibleTaskThumbnails = launchState.launchedNumVisibleThumbnails;
-        loader.loadTasks(loadPlan, loadOpts);
-        TaskStack stack = loadPlan.getTaskStack();
-        mRecentsView.onReload(stack, mIsVisible);
-
-        // Update the nav bar scrim, but defer the animation until the enter-window event
-        boolean animateNavBarScrim = !launchState.launchedViaDockGesture;
-        mScrimViews.updateNavBarScrim(animateNavBarScrim, stack.getTaskCount() > 0, null);
-
-        // If this is a new instance relaunched by AM, without going through the normal mechanisms,
-        // then we have to manually trigger the enter animation state
-        boolean wasLaunchedByAm = !launchState.launchedFromHome &&
-                !launchState.launchedFromApp;
-        if (wasLaunchedByAm) {
-            EventBus.getDefault().send(new EnterRecentsWindowAnimationCompletedEvent());
-        }
-
-        // Keep track of whether we launched from the nav bar button or via alt-tab
-        if (launchState.launchedWithAltTab) {
-            MetricsLogger.count(this, "overview_trigger_alttab", 1);
-        } else {
-            MetricsLogger.count(this, "overview_trigger_nav_btn", 1);
-        }
-
-        // Keep track of whether we launched from an app or from home
-        if (launchState.launchedFromApp) {
-            Task launchTarget = stack.getLaunchTarget();
-            int launchTaskIndexInStack = launchTarget != null
-                    ? stack.indexOfTask(launchTarget)
-                    : 0;
-            MetricsLogger.count(this, "overview_source_app", 1);
-            // If from an app, track the stack index of the app in the stack (for affiliated tasks)
-            MetricsLogger.histogram(this, "overview_source_app_index", launchTaskIndexInStack);
-        } else {
-            MetricsLogger.count(this, "overview_source_home", 1);
-        }
-
-        // Keep track of the total stack task count
-        int taskCount = mRecentsView.getStack().getTaskCount();
-        MetricsLogger.histogram(this, "overview_task_count", taskCount);
-
-        // After we have resumed, set the visible state until the next onStop() call
-        mIsVisible = true;
-    }
-
-    @Override
-    public void onEnterAnimationComplete() {
-        super.onEnterAnimationComplete();
-        EventBus.getDefault().send(new EnterRecentsWindowAnimationCompletedEvent());
-
-        // Workaround for b/64694148: The animation started callback is not made (see
-        // RecentsImpl.getThumbnailTransitionActivityOptions) so reset the transition-waiting state
-        // once the enter animation has completed.
-        EventBus.getDefault().send(new SetWaitingForTransitionStartEvent(false));
-    }
-
-    @Override
-    public Object onRetainNonConfigurationInstance() {
-        return true;
-    }
-
-    @Override
-    protected void onPause() {
-        super.onPause();
-
-        mIgnoreAltTabRelease = false;
-    }
-
-    @Override
-    public void onConfigurationChanged(Configuration newConfig) {
-        super.onConfigurationChanged(newConfig);
-
-        // Notify of the config change
-        Configuration newDeviceConfiguration = Utilities.getAppConfiguration(this);
-        int numStackTasks = mRecentsView.getStack().getTaskCount();
-        EventBus.getDefault().send(new ConfigurationChangedEvent(false /* fromMultiWindow */,
-                mLastConfig.orientation != newDeviceConfiguration.orientation,
-                mLastConfig.densityDpi != newDeviceConfiguration.densityDpi, numStackTasks > 0));
-
-        mLastConfig.updateFrom(newDeviceConfiguration);
-    }
-
-    @Override
-    public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
-        super.onMultiWindowModeChanged(isInMultiWindowMode);
-
-        // Set the window background
-        mRecentsView.updateBackgroundScrim(getWindow(), isInMultiWindowMode);
-
-        // Reload the task stack view if we are still visible to pick up the change in tasks that
-        // result from entering/exiting multi-window
-        if (mIsVisible) {
-            reloadTaskStack(isInMultiWindowMode, true /* sendConfigChangedEvent */);
-        }
-    }
-
-    @Override
-    protected void onStop() {
-        super.onStop();
-
-        // Notify that recents is now hidden
-        mIsVisible = false;
-        EventBus.getDefault().send(new RecentsVisibilityChangedEvent(this, false));
-        MetricsLogger.hidden(this, MetricsEvent.OVERVIEW_ACTIVITY);
-        LegacyRecentsImpl.getTaskLoader().getHighResThumbnailLoader().setVisible(false);
-
-        // When recents starts again before onStop, do not reset launch flags so entrance animation
-        // can run
-        if (!isChangingConfigurations() && !mRecentsStartRequested) {
-            // Workaround for b/22542869, if the RecentsActivity is started again, but without going
-            // through SystemUI, we need to reset the config launch flags to ensure that we do not
-            // wait on the system to send a signal that was never queued.
-            RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-            RecentsActivityLaunchState launchState = config.getLaunchState();
-            launchState.reset();
-        }
-
-        // Force a gc to attempt to clean up bitmap references more quickly (b/38258699)
-        LegacyRecentsImpl.getSystemServices().gc();
-    }
-
-    @Override
-    protected void onDestroy() {
-        super.onDestroy();
-
-        // In the case that the activity finished on startup, just skip the unregistration below
-        if (mFinishedOnStartup) {
-            return;
-        }
-
-        // Unregister the system broadcast receivers
-        unregisterReceiver(mSystemBroadcastReceiver);
-
-        // Unregister any broadcast receivers for the task loader
-        mPackageMonitor.unregister();
-
-        EventBus.getDefault().unregister(this);
-    }
-
-    @Override
-    public void onAttachedToWindow() {
-        super.onAttachedToWindow();
-        EventBus.getDefault().register(mScrimViews, EVENT_BUS_PRIORITY);
-    }
-
-    @Override
-    public void onDetachedFromWindow() {
-        super.onDetachedFromWindow();
-        EventBus.getDefault().unregister(mScrimViews);
-    }
-
-    @Override
-    public void onTrimMemory(int level) {
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        if (loader != null) {
-            loader.onTrimMemory(level);
-        }
-    }
-
-    @Override
-    public boolean onKeyDown(int keyCode, KeyEvent event) {
-        switch (keyCode) {
-            case KeyEvent.KEYCODE_TAB: {
-                int altTabKeyDelay = getResources().getInteger(R.integer.recents_alt_tab_key_delay);
-                boolean hasRepKeyTimeElapsed = (SystemClock.elapsedRealtime() -
-                        mLastTabKeyEventTime) > altTabKeyDelay;
-                if (event.getRepeatCount() <= 0 || hasRepKeyTimeElapsed) {
-                    // Focus the next task in the stack
-                    final boolean backward = event.isShiftPressed();
-                    if (backward) {
-                        EventBus.getDefault().send(new FocusPreviousTaskViewEvent());
-                    } else {
-                        EventBus.getDefault().send(new FocusNextTaskViewEvent());
-                    }
-                    mLastTabKeyEventTime = SystemClock.elapsedRealtime();
-
-                    // In the case of another ALT event, don't ignore the next release
-                    if (event.isAltPressed()) {
-                        mIgnoreAltTabRelease = false;
-                    }
-                }
-                return true;
-            }
-            case KeyEvent.KEYCODE_DPAD_UP:
-            case KeyEvent.KEYCODE_DPAD_DOWN:
-            case KeyEvent.KEYCODE_DPAD_LEFT:
-            case KeyEvent.KEYCODE_DPAD_RIGHT: {
-                final Direction direction = NavigateTaskViewEvent.getDirectionFromKeyCode(keyCode);
-                EventBus.getDefault().send(new NavigateTaskViewEvent(direction));
-                return true;
-            }
-            case KeyEvent.KEYCODE_DEL:
-            case KeyEvent.KEYCODE_FORWARD_DEL: {
-                if (event.getRepeatCount() <= 0) {
-                    EventBus.getDefault().send(new DismissFocusedTaskViewEvent());
-
-                    // Keep track of deletions by keyboard
-                    MetricsLogger.histogram(this, "overview_task_dismissed_source",
-                            Constants.Metrics.DismissSourceKeyboard);
-                    return true;
-                }
-            }
-            default:
-                break;
-        }
-        return super.onKeyDown(keyCode, event);
-    }
-
-    @Override
-    public void onUserInteraction() {
-        EventBus.getDefault().send(mUserInteractionEvent);
-    }
-
-    @Override
-    public void onBackPressed() {
-        // Back behaves like the recents button so just trigger a toggle event
-        EventBus.getDefault().send(new ToggleRecentsEvent());
-    }
-
-    /**** EventBus events ****/
-
-    public final void onBusEvent(ToggleRecentsEvent event) {
-        RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-        if (launchState.launchedFromHome) {
-            dismissRecentsToHome(true /* animateTaskViews */);
-        } else {
-            dismissRecentsToLaunchTargetTaskOrHome();
-        }
-    }
-
-    public final void onBusEvent(RecentsActivityStartingEvent event) {
-        mRecentsStartRequested = true;
-    }
-
-    public final void onBusEvent(HideRecentsEvent event) {
-        if (event.triggeredFromAltTab) {
-            // If we are hiding from releasing Alt-Tab, dismiss Recents to the focused app
-            if (!mIgnoreAltTabRelease) {
-                dismissRecentsToFocusedTaskOrHome();
-            }
-        } else if (event.triggeredFromHomeKey) {
-            dismissRecentsToHome(true /* animateTaskViews */);
-
-            // Cancel any pending dozes
-            EventBus.getDefault().send(mUserInteractionEvent);
-        } else {
-            // Do nothing
-        }
-    }
-
-    public final void onBusEvent(EnterRecentsWindowLastAnimationFrameEvent event) {
-        mRecentsView.getViewTreeObserver().addOnPreDrawListener(this);
-        mRecentsView.invalidate();
-    }
-
-    public final void onBusEvent(ExitRecentsWindowFirstAnimationFrameEvent event) {
-        mRecentsView.getViewTreeObserver().addOnPreDrawListener(this);
-        mRecentsView.invalidate();
-    }
-
-    public final void onBusEvent(DockedFirstAnimationFrameEvent event) {
-        mRecentsView.getViewTreeObserver().addOnPreDrawListener(this);
-        mRecentsView.invalidate();
-    }
-
-    public final void onBusEvent(CancelEnterRecentsWindowAnimationEvent event) {
-        RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-        int launchToTaskId = launchState.launchedToTaskId;
-        if (launchToTaskId != -1 &&
-                (event.launchTask == null || launchToTaskId != event.launchTask.key.id)) {
-            ActivityManagerWrapper am = ActivityManagerWrapper.getInstance();
-            am.cancelWindowTransition(launchState.launchedToTaskId);
-        }
-    }
-
-    public final void onBusEvent(ShowApplicationInfoEvent event) {
-        // Create a new task stack with the application info details activity
-        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
-                Uri.fromParts("package", event.task.key.getComponent().getPackageName(), null));
-        intent.setComponent(intent.resolveActivity(getPackageManager()));
-        TaskStackBuilder.create(this)
-                .addNextIntentWithParentStack(intent).startActivities(null,
-                        new UserHandle(event.task.key.userId));
-
-        // Keep track of app-info invocations
-        MetricsLogger.count(this, "overview_app_info", 1);
-    }
-
-    public final void onBusEvent(ShowIncompatibleAppOverlayEvent event) {
-        if (mIncompatibleAppOverlay == null) {
-            mIncompatibleAppOverlay = Utilities.findViewStubById(this,
-                    R.id.incompatible_app_overlay_stub).inflate();
-            mIncompatibleAppOverlay.setWillNotDraw(false);
-            mIncompatibleAppOverlay.setVisibility(View.VISIBLE);
-        }
-        mIncompatibleAppOverlay.animate()
-                .alpha(1f)
-                .setDuration(INCOMPATIBLE_APP_ALPHA_DURATION)
-                .setInterpolator(Interpolators.ALPHA_IN)
-                .start();
-    }
-
-    public final void onBusEvent(HideIncompatibleAppOverlayEvent event) {
-        if (mIncompatibleAppOverlay != null) {
-            mIncompatibleAppOverlay.animate()
-                    .alpha(0f)
-                    .setDuration(INCOMPATIBLE_APP_ALPHA_DURATION)
-                    .setInterpolator(Interpolators.ALPHA_OUT)
-                    .start();
-        }
-    }
-
-    public final void onBusEvent(DeleteTaskDataEvent event) {
-        // Remove any stored data from the loader
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        loader.deleteTaskData(event.task, false);
-
-        // Remove the task from activity manager
-        ActivityManagerWrapper.getInstance().removeTask(event.task.key.id);
-    }
-
-    public final void onBusEvent(TaskViewDismissedEvent event) {
-        mRecentsView.updateScrimOpacity();
-    }
-
-    public final void onBusEvent(AllTaskViewsDismissedEvent event) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        if (ssp.hasDockedTask()) {
-            mRecentsView.showEmptyView(event.msgResId);
-        } else {
-            // Just go straight home (no animation necessary because there are no more task views)
-            dismissRecentsToHome(false /* animateTaskViews */);
-        }
-
-        // Keep track of all-deletions
-        MetricsLogger.count(this, "overview_task_all_dismissed", 1);
-    }
-
-    public final void onBusEvent(LaunchTaskSucceededEvent event) {
-        MetricsLogger.histogram(this, "overview_task_launch_index", event.taskIndexFromStackFront);
-    }
-
-    public final void onBusEvent(LaunchTaskFailedEvent event) {
-        // Return to Home
-        dismissRecentsToHome(true /* animateTaskViews */);
-
-        MetricsLogger.count(this, "overview_task_launch_failed", 1);
-    }
-
-    public final void onBusEvent(ScreenPinningRequestEvent event) {
-        MetricsLogger.count(this, "overview_screen_pinned", 1);
-    }
-
-    public final void onBusEvent(StackViewScrolledEvent event) {
-        // Once the user has scrolled while holding alt-tab, then we should ignore the release of
-        // the key
-        mIgnoreAltTabRelease = true;
-    }
-
-    public final void onBusEvent(final DockedTopTaskEvent event) {
-        mRecentsView.getViewTreeObserver().addOnPreDrawListener(mRecentsDrawnEventListener);
-        mRecentsView.invalidate();
-    }
-
-    public final void onBusEvent(final ActivityUnpinnedEvent event) {
-        if (mIsVisible) {
-            // Skip the configuration change event as the PiP activity does not actually affect the
-            // config of recents
-            reloadTaskStack(isInMultiWindowMode(), false /* sendConfigChangedEvent */);
-        }
-    }
-
-    private void reloadTaskStack(boolean isInMultiWindowMode, boolean sendConfigChangedEvent) {
-        // Reload the task stack completely
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        RecentsActivityLaunchState launchState = config.getLaunchState();
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        RecentsTaskLoadPlan loadPlan = new RecentsTaskLoadPlan(this);
-        loader.preloadTasks(loadPlan, -1 /* runningTaskId */);
-
-        RecentsTaskLoadPlan.Options loadOpts = new RecentsTaskLoadPlan.Options();
-        loadOpts.numVisibleTasks = launchState.launchedNumVisibleTasks;
-        loadOpts.numVisibleTaskThumbnails = launchState.launchedNumVisibleThumbnails;
-        loader.loadTasks(loadPlan, loadOpts);
-
-        TaskStack stack = loadPlan.getTaskStack();
-        int numStackTasks = stack.getTaskCount();
-        boolean showDeferredAnimation = numStackTasks > 0;
-
-        if (sendConfigChangedEvent) {
-            EventBus.getDefault().send(new ConfigurationChangedEvent(true /* fromMultiWindow */,
-                    false /* fromDeviceOrientationChange */, false /* fromDisplayDensityChange */,
-                    numStackTasks > 0));
-        }
-        EventBus.getDefault().send(new MultiWindowStateChangedEvent(isInMultiWindowMode,
-                showDeferredAnimation, stack));
-    }
-
-    @Override
-    public boolean onPreDraw() {
-        mRecentsView.getViewTreeObserver().removeOnPreDrawListener(this);
-        return true;
-    }
-
-    public void onPackageChanged(String packageName, int userId) {
-        LegacyRecentsImpl.getTaskLoader().onPackageChanged(packageName);
-        EventBus.getDefault().send(new PackagesChangedEvent(packageName, userId));
-    }
-
-    @Override
-    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
-        super.dump(prefix, fd, writer, args);
-        EventBus.getDefault().dump(prefix, writer);
-        LegacyRecentsImpl.getTaskLoader().dump(prefix, writer);
-
-        String id = Integer.toHexString(System.identityHashCode(this));
-
-        writer.print(prefix); writer.print(TAG);
-        writer.print(" visible="); writer.print(mIsVisible ? "Y" : "N");
-        writer.print(" currentTime="); writer.print(System.currentTimeMillis());
-        writer.print(" [0x"); writer.print(id); writer.print("]");
-        writer.println();
-
-        if (mRecentsView != null) {
-            mRecentsView.dump(prefix, writer);
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsActivityLaunchState.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsActivityLaunchState.java
deleted file mode 100644
index 14fda95..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsActivityLaunchState.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents;
-
-/**
- * The launch state of the RecentsActivity.
- *
- * Current Constraints:
- *  - needed in onStart() before onNewIntent()
- *  - needs to be reset when Recents is hidden
- *  - needs to be computed in Recents component
- *  - needs to be accessible by views
- */
-public class RecentsActivityLaunchState {
-
-    public boolean launchedWithAltTab;
-    public boolean launchedFromApp;
-    // Set if the activity that we launched from entered PiP during the transition into Recents
-    public boolean launchedFromPipApp;
-    // Set if the next activity that quick-switch will launch is the PiP activity
-    public boolean launchedWithNextPipApp;
-    public boolean launchedFromHome;
-    public boolean launchedViaDragGesture;
-    public boolean launchedViaDockGesture;
-    public int launchedToTaskId;
-    public int launchedNumVisibleTasks;
-    public int launchedNumVisibleThumbnails;
-
-    public void reset() {
-        launchedFromHome = false;
-        launchedFromApp = false;
-        launchedFromPipApp = false;
-        launchedWithNextPipApp = false;
-        launchedToTaskId = -1;
-        launchedWithAltTab = false;
-        launchedViaDragGesture = false;
-        launchedViaDockGesture = false;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsConfiguration.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsConfiguration.java
deleted file mode 100644
index ee53734..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsConfiguration.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents;
-
-import android.app.ActivityManager;
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-
-import android.os.SystemProperties;
-
-import com.android.systemui.R;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.views.DockState;
-
-/**
- * Represents the dock regions for each orientation.
- */
-class DockRegion {
-    public static DockState[] PHONE_LANDSCAPE = {
-            // We only allow docking to the left in landscape for now on small devices
-            DockState.LEFT
-    };
-    public static DockState[] PHONE_PORTRAIT = {
-            // We only allow docking to the top for now on small devices
-            DockState.TOP
-    };
-    public static DockState[] TABLET_LANDSCAPE = {
-            DockState.LEFT,
-            DockState.RIGHT
-    };
-    public static DockState[] TABLET_PORTRAIT = PHONE_PORTRAIT;
-}
-
-/**
- * Application resources that can be retrieved from the application context and are not specifically
- * tied to the current activity.
- */
-public class RecentsConfiguration {
-
-    private static final int LARGE_SCREEN_MIN_DP = 600;
-    private static final int XLARGE_SCREEN_MIN_DP = 720;
-
-    // Launch states
-    public RecentsActivityLaunchState mLaunchState = new RecentsActivityLaunchState();
-
-    // Since the positions in Recents has to be calculated globally (before the RecentsActivity
-    // starts), we need to calculate some resource values ourselves, instead of relying on framework
-    // resources.
-    public final boolean isLargeScreen;
-    public final boolean isXLargeScreen;
-    public final int smallestWidth;
-
-    /** Misc **/
-    public boolean fakeShadows;
-    public int svelteLevel;
-
-    // Whether this product supports Grid-based Recents. If this is field is set to true, then
-    // Recents will layout task views in a grid mode when there's enough space in the screen.
-    public boolean isGridEnabled;
-
-    // Support for Android Recents for low ram devices. If this field is set to true, then Recents
-    // will use the alternative layout.
-    public boolean isLowRamDevice;
-
-    // Enable drag and drop split from Recents. Disabled for low ram devices.
-    public boolean dragToSplitEnabled;
-
-    private final Context mAppContext;
-
-    public RecentsConfiguration(Context context) {
-        // Load only resources that can not change after the first load either through developer
-        // settings or via multi window
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        mAppContext = context.getApplicationContext();
-        Resources res = mAppContext.getResources();
-        fakeShadows = res.getBoolean(R.bool.config_recents_fake_shadows);
-        svelteLevel = res.getInteger(R.integer.recents_svelte_level);
-        isGridEnabled = SystemProperties.getBoolean("ro.recents.grid", false);
-        isLowRamDevice = ActivityManager.isLowRamDeviceStatic();
-        dragToSplitEnabled = !isLowRamDevice;
-
-        float screenDensity = context.getResources().getDisplayMetrics().density;
-        smallestWidth = ssp.getDeviceSmallestWidth();
-        isLargeScreen = smallestWidth >= (int) (screenDensity * LARGE_SCREEN_MIN_DP);
-        isXLargeScreen = smallestWidth >= (int) (screenDensity * XLARGE_SCREEN_MIN_DP);
-    }
-
-    /**
-     * Returns the activity launch state.
-     * TODO: This will be refactored out of RecentsConfiguration.
-     */
-    public RecentsActivityLaunchState getLaunchState() {
-        return mLaunchState;
-    }
-
-    /**
-     * Returns the preferred dock states for the current orientation.
-     * @return a list of dock states for device and its orientation
-     */
-    public DockState[] getDockStatesForCurrentOrientation() {
-        boolean isLandscape = mAppContext.getResources().getConfiguration().orientation ==
-                Configuration.ORIENTATION_LANDSCAPE;
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        if (config.isLargeScreen) {
-            return isLandscape ? DockRegion.TABLET_LANDSCAPE : DockRegion.TABLET_PORTRAIT;
-        } else {
-            return isLandscape ? DockRegion.PHONE_LANDSCAPE : DockRegion.PHONE_PORTRAIT;
-        }
-    }
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsDebugFlags.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsDebugFlags.java
deleted file mode 100644
index 1918593..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsDebugFlags.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents;
-
-public class RecentsDebugFlags {
-
-    public static class Static {
-        // Enables debug drawing for the transition thumbnail
-        public static final boolean EnableTransitionThumbnailDebugMode = false;
-
-        // Disables enter and exit transitions for other tasks for low ram devices
-        public static final boolean DisableRecentsLowRamEnterExitAnimation = false;
-
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsImpl.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsImpl.java
deleted file mode 100644
index 3e5acab..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsImpl.java
+++ /dev/null
@@ -1,1118 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents;
-
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
-import static android.view.View.MeasureSpec;
-
-import static com.android.systemui.statusbar.phone.StatusBar.SYSTEM_DIALOG_REASON_RECENT_APPS;
-
-import android.app.ActivityManager;
-import android.app.ActivityOptions;
-import android.app.trust.TrustManager;
-import android.content.ActivityNotFoundException;
-import android.content.ComponentCallbacks2;
-import android.content.Context;
-import android.content.Intent;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.drawable.Drawable;
-import android.os.Handler;
-import android.os.SystemClock;
-import android.util.ArraySet;
-import android.util.Log;
-import android.util.MutableBoolean;
-import android.util.Pair;
-import android.view.LayoutInflater;
-import android.view.ViewConfiguration;
-import android.view.WindowManager;
-
-import android.widget.Toast;
-
-import com.android.systemui.Dependency;
-import com.android.systemui.SysUiServiceProvider;
-import com.android.systemui.pip.phone.ForegroundThread;
-import com.google.android.collect.Lists;
-
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.policy.DockedDividerUtils;
-import com.android.systemui.R;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.DockedTopTaskEvent;
-import com.android.systemui.recents.events.activity.EnterRecentsWindowLastAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.HideRecentsEvent;
-import com.android.systemui.recents.events.activity.LaunchMostRecentTaskRequestEvent;
-import com.android.systemui.recents.events.activity.LaunchNextTaskRequestEvent;
-import com.android.systemui.recents.events.activity.RecentsActivityStartingEvent;
-import com.android.systemui.recents.events.activity.ToggleRecentsEvent;
-import com.android.systemui.recents.events.component.ActivityPinnedEvent;
-import com.android.systemui.recents.events.component.ActivityUnpinnedEvent;
-import com.android.systemui.recents.events.component.HidePipMenuEvent;
-import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent;
-import com.android.systemui.recents.events.component.ScreenPinningRequestEvent;
-import com.android.systemui.recents.events.ui.DraggingInRecentsEndedEvent;
-import com.android.systemui.recents.events.ui.DraggingInRecentsEvent;
-import com.android.systemui.recents.events.ui.TaskSnapshotChangedEvent;
-import com.android.systemui.recents.misc.DozeTrigger;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.misc.SysUiTaskStackChangeListener;
-import com.android.systemui.recents.model.RecentsTaskLoadPlan;
-import com.android.systemui.recents.model.RecentsTaskLoader;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import com.android.systemui.recents.views.TaskStackLayoutAlgorithm;
-import com.android.systemui.recents.views.TaskStackLayoutAlgorithm.VisibilityReport;
-import com.android.systemui.recents.views.TaskStackView;
-import com.android.systemui.recents.views.TaskViewHeader;
-import com.android.systemui.recents.views.TaskViewTransform;
-import com.android.systemui.recents.views.grid.TaskGridLayoutAlgorithm;
-import com.android.systemui.shared.recents.view.AppTransitionAnimationSpecCompat;
-import com.android.systemui.shared.recents.view.AppTransitionAnimationSpecsFuture;
-import com.android.systemui.shared.recents.view.RecentsTransition;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-import com.android.systemui.stackdivider.DividerView;
-import com.android.systemui.statusbar.phone.StatusBar;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * An implementation of the Recents component for the current user.  For secondary users, this can
- * be called remotely from the system user.
- */
-public class RecentsImpl implements ActivityOptions.OnAnimationFinishedListener {
-
-    private final static String TAG = "RecentsImpl";
-
-    // The minimum amount of time between each recents button press that we will handle
-    private final static int MIN_TOGGLE_DELAY_MS = 350;
-
-    // The duration within which the user releasing the alt tab (from when they pressed alt tab)
-    // that the fast alt-tab animation will run.  If the user's alt-tab takes longer than this
-    // duration, then we will toggle recents after this duration.
-    private final static int FAST_ALT_TAB_DELAY_MS = 225;
-
-    private final static ArraySet<TaskKey> EMPTY_SET = new ArraySet<>();
-
-    public final static String RECENTS_PACKAGE = "com.android.systemui";
-    public final static String RECENTS_ACTIVITY = "com.android.systemui.recents.RecentsActivity";
-
-    /**
-     * An implementation of SysUiTaskStackChangeListener, that allows us to listen for changes to the system
-     * task stacks and update recents accordingly.
-     */
-    class TaskStackListenerImpl extends SysUiTaskStackChangeListener {
-
-        private OverviewProxyService mOverviewProxyService;
-
-        public TaskStackListenerImpl() {
-            mOverviewProxyService = Dependency.get(OverviewProxyService.class);
-        }
-
-        @Override
-        public void onTaskStackChangedBackground() {
-            // Skip background preloading recents in SystemUI if the overview services is bound
-            if (mOverviewProxyService.isEnabled()) {
-                return;
-            }
-
-            // Check this is for the right user
-            if (!checkCurrentUserId(mContext, false /* debug */)) {
-                return;
-            }
-
-            // Preloads the next task
-            RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-            if (config.svelteLevel == RecentsTaskLoader.SVELTE_NONE) {
-                Rect windowRect = getWindowRect(null /* windowRectOverride */);
-                if (windowRect.isEmpty()) {
-                    return;
-                }
-
-                // Load the next task only if we aren't svelte
-                ActivityManager.RunningTaskInfo runningTaskInfo =
-                        ActivityManagerWrapper.getInstance().getRunningTask();
-                RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-                RecentsTaskLoadPlan plan = new RecentsTaskLoadPlan(mContext);
-                loader.preloadTasks(plan, -1);
-                TaskStack stack = plan.getTaskStack();
-                RecentsActivityLaunchState launchState = new RecentsActivityLaunchState();
-                RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options();
-
-                synchronized (mBackgroundLayoutAlgorithm) {
-                    // This callback is made when a new activity is launched and the old one is
-                    // paused so ignore the current activity and try and preload the thumbnail for
-                    // the previous one.
-                    updateDummyStackViewLayout(mBackgroundLayoutAlgorithm, stack, windowRect);
-
-                    // Launched from app is always the worst case (in terms of how many
-                    // thumbnails/tasks visible)
-                    launchState.launchedFromApp = true;
-                    mBackgroundLayoutAlgorithm.update(plan.getTaskStack(), EMPTY_SET, launchState,
-                            -1 /* lastScrollPPresent */);
-                    VisibilityReport visibilityReport =
-                            mBackgroundLayoutAlgorithm.computeStackVisibilityReport(
-                                    stack.getTasks());
-
-                    launchOpts.runningTaskId = runningTaskInfo != null ? runningTaskInfo.id : -1;
-                    launchOpts.numVisibleTasks = visibilityReport.numVisibleTasks;
-                    launchOpts.numVisibleTaskThumbnails = visibilityReport.numVisibleThumbnails;
-                    launchOpts.onlyLoadForCache = true;
-                    launchOpts.onlyLoadPausedActivities = true;
-                    launchOpts.loadThumbnails = true;
-                }
-                loader.loadTasks(plan, launchOpts);
-            }
-        }
-
-        @Override
-        public void onActivityPinned(String packageName, int userId, int taskId, int stackId) {
-            // Check this is for the right user
-            if (!checkCurrentUserId(mContext, false /* debug */)) {
-                return;
-            }
-
-            // This time needs to be fetched the same way the last active time is fetched in
-            // {@link TaskRecord#touchActiveTime}
-            LegacyRecentsImpl.getConfiguration().getLaunchState().launchedFromPipApp = true;
-            LegacyRecentsImpl.getConfiguration().getLaunchState().launchedWithNextPipApp = false;
-            EventBus.getDefault().send(new ActivityPinnedEvent(taskId));
-            consumeInstanceLoadPlan();
-            sLastPipTime = System.currentTimeMillis();
-        }
-
-        @Override
-        public void onActivityUnpinned() {
-            // Check this is for the right user
-            if (!checkCurrentUserId(mContext, false /* debug */)) {
-                return;
-            }
-
-            EventBus.getDefault().send(new ActivityUnpinnedEvent());
-            sLastPipTime = -1;
-        }
-
-        @Override
-        public void onTaskSnapshotChanged(int taskId, ThumbnailData snapshot) {
-            // Check this is for the right user
-            if (!checkCurrentUserId(mContext, false /* debug */)) {
-                return;
-            }
-
-            EventBus.getDefault().send(new TaskSnapshotChangedEvent(taskId, snapshot));
-        }
-    }
-
-    protected static RecentsTaskLoadPlan sInstanceLoadPlan;
-    // Stores the last pinned task time
-    protected static long sLastPipTime = -1;
-    // Stores whether we are waiting for a transition to/from recents to start. During this time,
-    // we disallow the user from manually toggling recents until the transition has started.
-    private static boolean mWaitingForTransitionStart = false;
-    // Stores whether or not the user toggled while we were waiting for a transition to/from
-    // recents. In this case, we defer the toggle state until then and apply it immediately after.
-    private static boolean mToggleFollowingTransitionStart = true;
-
-    private Runnable mResetToggleFlagListener = new Runnable() {
-        @Override
-        public void run() {
-            setWaitingForTransitionStart(false);
-        }
-    };
-
-    private TrustManager mTrustManager;
-    protected Context mContext;
-    protected Handler mHandler;
-    TaskStackListenerImpl mTaskStackListener;
-    boolean mDraggingInRecents;
-    boolean mLaunchedWhileDocking;
-
-    // Task launching
-    Rect mTmpBounds = new Rect();
-    TaskViewTransform mTmpTransform = new TaskViewTransform();
-    int mTaskBarHeight;
-
-    // Header (for transition)
-    TaskViewHeader mHeaderBar;
-    final Object mHeaderBarLock = new Object();
-    private TaskStackView mDummyStackView;
-    private TaskStackLayoutAlgorithm mBackgroundLayoutAlgorithm;
-
-    // Variables to keep track of if we need to start recents after binding
-    protected boolean mTriggeredFromAltTab;
-    protected long mLastToggleTime;
-    DozeTrigger mFastAltTabTrigger = new DozeTrigger(FAST_ALT_TAB_DELAY_MS, new Runnable() {
-        @Override
-        public void run() {
-            // When this fires, then the user has not released alt-tab for at least
-            // FAST_ALT_TAB_DELAY_MS milliseconds
-            showRecents(mTriggeredFromAltTab, false /* draggingInRecents */, true /* animate */,
-                    DividerView.INVALID_RECENTS_GROW_TARGET);
-        }
-    });
-
-    private OverviewProxyService.OverviewProxyListener mOverviewProxyListener =
-            new OverviewProxyService.OverviewProxyListener() {
-        @Override
-        public void onConnectionChanged(boolean isConnected) {
-            if (!isConnected) {
-                // Clear everything when the connection to the overview service
-                LegacyRecentsImpl.getTaskLoader().onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_COMPLETE);
-            }
-        }
-    };
-
-    // Used to reset the dummy stack view
-    private final TaskStack mEmptyTaskStack = new TaskStack();
-
-    public RecentsImpl(Context context) {
-        mContext = context;
-        mHandler = new Handler();
-        mBackgroundLayoutAlgorithm = new TaskStackLayoutAlgorithm(context, null);
-
-        // Initialize the static foreground thread
-        ForegroundThread.get();
-
-        // Register the task stack listener
-        mTaskStackListener = new TaskStackListenerImpl();
-        ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener);
-
-        // Initialize the static configuration resources
-        mDummyStackView = new TaskStackView(mContext);
-        reloadResources();
-
-        mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
-    }
-
-    public void onBootCompleted() {
-        // Skip preloading tasks if we are already bound to the service
-        if (Dependency.get(OverviewProxyService.class).isEnabled()) {
-            return;
-        }
-
-        // When we start, preload the data associated with the previous recent tasks.
-        // We can use a new plan since the caches will be the same.
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        RecentsTaskLoadPlan plan = new RecentsTaskLoadPlan(mContext);
-        loader.preloadTasks(plan, -1);
-        RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options();
-        launchOpts.numVisibleTasks = loader.getIconCacheSize();
-        launchOpts.numVisibleTaskThumbnails = loader.getThumbnailCacheSize();
-        launchOpts.onlyLoadForCache = true;
-        loader.loadTasks(plan, launchOpts);
-    }
-
-    public void onConfigurationChanged() {
-        reloadResources();
-        mDummyStackView.reloadOnConfigurationChange();
-        synchronized (mBackgroundLayoutAlgorithm) {
-            mBackgroundLayoutAlgorithm.reloadOnConfigurationChange(mContext);
-        }
-    }
-
-    /**
-     * This is only called from the system user's Recents.  Secondary users will instead proxy their
-     * visibility change events through to the system user via
-     * {@link LegacyRecentsImpl#onBusEvent(RecentsVisibilityChangedEvent)}.
-     */
-    public void onVisibilityChanged(Context context, boolean visible) {
-        LegacyRecentsImpl.getSystemServices().setRecentsVisibility(visible);
-    }
-
-    /**
-     * This is only called from the system user's Recents.  Secondary users will instead proxy their
-     * visibility change events through to the system user via
-     * {@link LegacyRecentsImpl#onBusEvent(ScreenPinningRequestEvent)}.
-     */
-    public void onStartScreenPinning(Context context, int taskId) {
-        final StatusBar statusBar = getStatusBar();
-        if (statusBar != null) {
-            statusBar.showScreenPinningRequest(taskId, false);
-        }
-    }
-
-    public void showRecents(boolean triggeredFromAltTab, boolean draggingInRecents,
-            boolean animate, int growTarget) {
-        final SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        final MutableBoolean isHomeStackVisible = new MutableBoolean(true);
-        final boolean isRecentsVisible = LegacyRecentsImpl.getSystemServices().isRecentsActivityVisible(
-                isHomeStackVisible);
-        final boolean fromHome = isHomeStackVisible.value;
-        final boolean launchedWhileDockingTask =
-                LegacyRecentsImpl.getSystemServices().getSplitScreenPrimaryStack() != null;
-
-        mTriggeredFromAltTab = triggeredFromAltTab;
-        mDraggingInRecents = draggingInRecents;
-        mLaunchedWhileDocking = launchedWhileDockingTask;
-        if (mFastAltTabTrigger.isAsleep()) {
-            // Fast alt-tab duration has elapsed, fall through to showing Recents and reset
-            mFastAltTabTrigger.stopDozing();
-        } else if (mFastAltTabTrigger.isDozing()) {
-            // Fast alt-tab duration has not elapsed.  If this is triggered by a different
-            // showRecents() call, then ignore that call for now.
-            // TODO: We can not handle quick tabs that happen between the initial showRecents() call
-            //       that started the activity and the activity starting up.  The severity of this
-            //       is inversely proportional to the FAST_ALT_TAB_DELAY_MS duration though.
-            if (!triggeredFromAltTab) {
-                return;
-            }
-            mFastAltTabTrigger.stopDozing();
-        } else if (triggeredFromAltTab) {
-            // The fast alt-tab detector is not yet running, so start the trigger and wait for the
-            // hideRecents() call, or for the fast alt-tab duration to elapse
-            mFastAltTabTrigger.startDozing();
-            return;
-        }
-
-        try {
-            // Check if the top task is in the home stack, and start the recents activity
-            final boolean forceVisible = launchedWhileDockingTask || draggingInRecents;
-            if (forceVisible || !isRecentsVisible) {
-                ActivityManager.RunningTaskInfo runningTask =
-                        ActivityManagerWrapper.getInstance().getRunningTask();
-                startRecentsActivityAndDismissKeyguardIfNeeded(runningTask,
-                        isHomeStackVisible.value || fromHome, animate, growTarget);
-            }
-        } catch (ActivityNotFoundException e) {
-            Log.e(TAG, "Failed to launch RecentsActivity", e);
-        }
-    }
-
-    public void hideRecents(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) {
-        if (triggeredFromAltTab && mFastAltTabTrigger.isDozing()) {
-            // The user has released alt-tab before the trigger has run, so just show the next
-            // task immediately
-            showNextTask();
-
-            // Cancel the fast alt-tab trigger
-            mFastAltTabTrigger.stopDozing();
-            return;
-        }
-
-        // Defer to the activity to handle hiding recents, if it handles it, then it must still
-        // be visible
-        EventBus.getDefault().post(new HideRecentsEvent(triggeredFromAltTab,
-                triggeredFromHomeKey));
-    }
-
-    public void toggleRecents(int growTarget) {
-        if (ActivityManagerWrapper.getInstance().isScreenPinningActive()) {
-            return;
-        }
-
-        // Skip this toggle if we are already waiting to trigger recents via alt-tab
-        if (mFastAltTabTrigger.isDozing()) {
-            return;
-        }
-
-        if (mWaitingForTransitionStart) {
-            mToggleFollowingTransitionStart = true;
-            return;
-        }
-
-        mDraggingInRecents = false;
-        mLaunchedWhileDocking = false;
-        mTriggeredFromAltTab = false;
-
-        try {
-            MutableBoolean isHomeStackVisible = new MutableBoolean(true);
-            long elapsedTime = SystemClock.elapsedRealtime() - mLastToggleTime;
-
-            SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-            if (ssp.isRecentsActivityVisible(isHomeStackVisible)) {
-                RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-                RecentsActivityLaunchState launchState = config.getLaunchState();
-                if (!launchState.launchedWithAltTab) {
-                    if (LegacyRecentsImpl.getConfiguration().isGridEnabled) {
-                        // Has the user tapped quickly?
-                        boolean isQuickTap = elapsedTime < ViewConfiguration.getDoubleTapTimeout();
-                        if (isQuickTap) {
-                            EventBus.getDefault().post(new LaunchNextTaskRequestEvent());
-                        } else {
-                            EventBus.getDefault().post(new LaunchMostRecentTaskRequestEvent());
-                        }
-                    } else {
-                        // Launch the next focused task
-                        EventBus.getDefault().post(new LaunchNextTaskRequestEvent());
-                    }
-                } else {
-                    // If the user has toggled it too quickly, then just eat up the event here (it's
-                    // better than showing a janky screenshot).
-                    // NOTE: Ideally, the screenshot mechanism would take the window transform into
-                    // account
-                    if (elapsedTime < MIN_TOGGLE_DELAY_MS) {
-                        return;
-                    }
-
-                    EventBus.getDefault().post(new ToggleRecentsEvent());
-                    mLastToggleTime = SystemClock.elapsedRealtime();
-                }
-                return;
-            } else {
-                // If the user has toggled it too quickly, then just eat up the event here (it's
-                // better than showing a janky screenshot).
-                // NOTE: Ideally, the screenshot mechanism would take the window transform into
-                // account
-                if (elapsedTime < MIN_TOGGLE_DELAY_MS) {
-                    return;
-                }
-
-                // Otherwise, start the recents activity
-                ActivityManager.RunningTaskInfo runningTask =
-                        ActivityManagerWrapper.getInstance().getRunningTask();
-                startRecentsActivityAndDismissKeyguardIfNeeded(runningTask,
-                        isHomeStackVisible.value, true /* animate */, growTarget);
-
-                // Only close the other system windows if we are actually showing recents
-                ActivityManagerWrapper.getInstance().closeSystemWindows(
-                        SYSTEM_DIALOG_REASON_RECENT_APPS);
-                mLastToggleTime = SystemClock.elapsedRealtime();
-            }
-        } catch (ActivityNotFoundException e) {
-            Log.e(TAG, "Failed to launch RecentsActivity", e);
-        }
-    }
-
-    public void preloadRecents() {
-        if (ActivityManagerWrapper.getInstance().isScreenPinningActive()) {
-            return;
-        }
-
-        // Skip preloading recents when keyguard is showing
-        final StatusBar statusBar = getStatusBar();
-        if (statusBar != null && statusBar.isKeyguardShowing()) {
-            return;
-        }
-
-        // Preload only the raw task list into a new load plan (which will be consumed by the
-        // RecentsActivity) only if there is a task to animate to.  Post this to ensure that we
-        // don't block the touch feedback on the nav bar button which triggers this.
-        mHandler.post(() -> {
-            SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-            if (!ssp.isRecentsActivityVisible(null)) {
-                ActivityManager.RunningTaskInfo runningTask =
-                        ActivityManagerWrapper.getInstance().getRunningTask();
-                if (runningTask == null) {
-                    return;
-                }
-
-                RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-                sInstanceLoadPlan = new RecentsTaskLoadPlan(mContext);
-                loader.preloadTasks(sInstanceLoadPlan, runningTask.id);
-                TaskStack stack = sInstanceLoadPlan.getTaskStack();
-                if (stack.getTaskCount() > 0) {
-                    // Only preload the icon (but not the thumbnail since it may not have been taken
-                    // for the pausing activity)
-                    preloadIcon(runningTask.id);
-
-                    // At this point, we don't know anything about the stack state.  So only
-                    // calculate the dimensions of the thumbnail that we need for the transition
-                    // into Recents, but do not draw it until we construct the activity options when
-                    // we start Recents
-                    updateHeaderBarLayout(stack, null /* window rect override*/);
-                }
-            }
-        });
-    }
-
-    public void cancelPreloadingRecents() {
-        // Do nothing
-    }
-
-    public void onDraggingInRecents(float distanceFromTop) {
-        EventBus.getDefault().sendOntoMainThread(new DraggingInRecentsEvent(distanceFromTop));
-    }
-
-    public void onDraggingInRecentsEnded(float velocity) {
-        EventBus.getDefault().sendOntoMainThread(new DraggingInRecentsEndedEvent(velocity));
-    }
-
-    public void onShowCurrentUserToast(int msgResId, int msgLength) {
-        Toast.makeText(mContext, msgResId, msgLength).show();
-    }
-
-    /**
-     * Transitions to the next recent task in the stack.
-     */
-    public void showNextTask() {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        RecentsTaskLoadPlan plan = new RecentsTaskLoadPlan(mContext);
-        loader.preloadTasks(plan, -1);
-        TaskStack focusedStack = plan.getTaskStack();
-
-        // Return early if there are no tasks in the focused stack
-        if (focusedStack == null || focusedStack.getTaskCount() == 0) return;
-
-        // Return early if there is no running task
-        ActivityManager.RunningTaskInfo runningTask =
-                ActivityManagerWrapper.getInstance().getRunningTask();
-        if (runningTask == null) return;
-
-        // Find the task in the recents list
-        boolean isRunningTaskInHomeStack =
-                runningTask.configuration.windowConfiguration.getActivityType()
-                        == ACTIVITY_TYPE_HOME;
-        ArrayList<Task> tasks = focusedStack.getTasks();
-        Task toTask = null;
-        ActivityOptions launchOpts = null;
-        int taskCount = tasks.size();
-        for (int i = taskCount - 1; i >= 1; i--) {
-            Task task = tasks.get(i);
-            if (isRunningTaskInHomeStack) {
-                toTask = tasks.get(i - 1);
-                launchOpts = ActivityOptions.makeCustomAnimation(mContext,
-                        R.anim.recents_launch_next_affiliated_task_target,
-                        R.anim.recents_fast_toggle_app_home_exit);
-                break;
-            } else if (task.key.id == runningTask.id) {
-                toTask = tasks.get(i - 1);
-                launchOpts = ActivityOptions.makeCustomAnimation(mContext,
-                        R.anim.recents_launch_prev_affiliated_task_target,
-                        R.anim.recents_launch_prev_affiliated_task_source);
-                break;
-            }
-        }
-
-        // Return early if there is no next task
-        if (toTask == null) {
-            ssp.startInPlaceAnimationOnFrontMostApplication(
-                    ActivityOptions.makeCustomInPlaceAnimation(mContext,
-                            R.anim.recents_launch_prev_affiliated_task_bounce));
-            return;
-        }
-
-        // Launch the task
-        ActivityManagerWrapper.getInstance().startActivityFromRecentsAsync(toTask.key, launchOpts,
-                null /* resultCallback */, null /* resultCallbackHandler */);
-    }
-
-    /**
-     * Transitions to the next affiliated task.
-     */
-    public void showRelativeAffiliatedTask(boolean showNextTask) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        RecentsTaskLoadPlan plan = new RecentsTaskLoadPlan(mContext);
-        loader.preloadTasks(plan, -1);
-        TaskStack focusedStack = plan.getTaskStack();
-
-        // Return early if there are no tasks in the focused stack
-        if (focusedStack == null || focusedStack.getTaskCount() == 0) return;
-
-        // Return early if there is no running task (can't determine affiliated tasks in this case)
-        ActivityManager.RunningTaskInfo runningTask =
-                ActivityManagerWrapper.getInstance().getRunningTask();
-        final int activityType = runningTask.configuration.windowConfiguration.getActivityType();
-        if (runningTask == null) return;
-        // Return early if the running task is in the home/recents stack (optimization)
-        if (activityType == ACTIVITY_TYPE_HOME || activityType == ACTIVITY_TYPE_RECENTS) return;
-
-        // Find the task in the recents list
-        ArrayList<Task> tasks = focusedStack.getTasks();
-        Task toTask = null;
-        ActivityOptions launchOpts = null;
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task task = tasks.get(i);
-            if (task.key.id == runningTask.id) {
-                if (showNextTask) {
-                    if ((i + 1) < taskCount) {
-                        toTask = tasks.get(i + 1);
-                        launchOpts = ActivityOptions.makeCustomAnimation(mContext,
-                                R.anim.recents_launch_next_affiliated_task_target,
-                                R.anim.recents_launch_next_affiliated_task_source);
-                    }
-                } else {
-                    if ((i - 1) >= 0) {
-                        toTask = tasks.get(i - 1);
-                        launchOpts = ActivityOptions.makeCustomAnimation(mContext,
-                                R.anim.recents_launch_prev_affiliated_task_target,
-                                R.anim.recents_launch_prev_affiliated_task_source);
-                    }
-                }
-                break;
-            }
-        }
-
-        // Return early if there is no next task
-        if (toTask == null) {
-            if (showNextTask) {
-                ssp.startInPlaceAnimationOnFrontMostApplication(
-                        ActivityOptions.makeCustomInPlaceAnimation(mContext,
-                                R.anim.recents_launch_next_affiliated_task_bounce));
-            } else {
-                ssp.startInPlaceAnimationOnFrontMostApplication(
-                        ActivityOptions.makeCustomInPlaceAnimation(mContext,
-                                R.anim.recents_launch_prev_affiliated_task_bounce));
-            }
-            return;
-        }
-
-        // Keep track of actually launched affiliated tasks
-        MetricsLogger.count(mContext, "overview_affiliated_task_launch", 1);
-
-        // Launch the task
-        ActivityManagerWrapper.getInstance().startActivityFromRecentsAsync(toTask.key, launchOpts,
-                null /* resultListener */, null /* resultCallbackHandler */);
-    }
-
-    public void splitPrimaryTask(int taskId, int stackCreateMode, Rect initialBounds) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-
-        // Make sure we inform DividerView before we actually start the activity so we can change
-        // the resize mode already.
-        if (ssp.setTaskWindowingModeSplitScreenPrimary(taskId, stackCreateMode, initialBounds)) {
-            EventBus.getDefault().send(new DockedTopTaskEvent(initialBounds));
-        }
-    }
-
-    public void setWaitingForTransitionStart(boolean waitingForTransitionStart) {
-        if (mWaitingForTransitionStart == waitingForTransitionStart) {
-            return;
-        }
-
-        mWaitingForTransitionStart = waitingForTransitionStart;
-        if (!waitingForTransitionStart && mToggleFollowingTransitionStart) {
-            mHandler.post(() -> toggleRecents(DividerView.INVALID_RECENTS_GROW_TARGET));
-        }
-        mToggleFollowingTransitionStart = false;
-    }
-
-    /**
-     * Returns the preloaded load plan and invalidates it.
-     */
-    public static RecentsTaskLoadPlan consumeInstanceLoadPlan() {
-        RecentsTaskLoadPlan plan = sInstanceLoadPlan;
-        sInstanceLoadPlan = null;
-        return plan;
-    }
-
-    /**
-     * @return the time at which a task last entered picture-in-picture.
-     */
-    public static long getLastPipTime() {
-        return sLastPipTime;
-    }
-
-    /**
-     * Clears the time at which a task last entered picture-in-picture.
-     */
-    public static void clearLastPipTime() {
-        sLastPipTime = -1;
-    }
-
-    /**
-     * Reloads all the resources for the current configuration.
-     */
-    private void reloadResources() {
-        Resources res = mContext.getResources();
-
-        mTaskBarHeight = TaskStackLayoutAlgorithm.getDimensionForDevice(mContext,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height_tablet_land,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height_tablet_land,
-                R.dimen.recents_grid_task_view_header_height);
-
-        LayoutInflater inflater = LayoutInflater.from(mContext);
-        mHeaderBar = (TaskViewHeader) inflater.inflate(R.layout.recents_task_view_header,
-                null, false);
-        mHeaderBar.setLayoutDirection(res.getConfiguration().getLayoutDirection());
-    }
-
-    private void updateDummyStackViewLayout(TaskStackLayoutAlgorithm stackLayout,
-            TaskStack stack, Rect windowRect) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        Rect displayRect = ssp.getDisplayRect();
-        Rect systemInsets = new Rect();
-        ssp.getStableInsets(systemInsets);
-
-        // When docked, the nav bar insets are consumed and the activity is measured without insets.
-        // However, the window bounds include the insets, so we need to subtract them here to make
-        // them identical.
-        if (ssp.hasDockedTask()) {
-            if (systemInsets.bottom < windowRect.height()) {
-                // Only apply inset if it isn't going to cause the rect height to go negative.
-                windowRect.bottom -= systemInsets.bottom;
-            }
-            systemInsets.bottom = 0;
-        }
-        calculateWindowStableInsets(systemInsets, windowRect, displayRect);
-        windowRect.offsetTo(0, 0);
-
-        // Rebind the header bar and draw it for the transition
-        stackLayout.setSystemInsets(systemInsets);
-        if (stack != null) {
-            stackLayout.getTaskStackBounds(displayRect, windowRect, systemInsets.top,
-                    systemInsets.left, systemInsets.right, mTmpBounds);
-            stackLayout.reset();
-            stackLayout.initialize(displayRect, windowRect, mTmpBounds);
-        }
-    }
-
-    private Rect getWindowRect(Rect windowRectOverride) {
-       return windowRectOverride != null
-                ? new Rect(windowRectOverride)
-                : LegacyRecentsImpl.getSystemServices().getWindowRect();
-    }
-
-    /**
-     * Prepares the header bar layout for the next transition, if the task view bounds has changed
-     * since the last call, it will attempt to re-measure and layout the header bar to the new size.
-     *
-     * @param stack the stack to initialize the stack layout with
-     * @param windowRectOverride the rectangle to use when calculating the stack state which can
-     *                           be different from the current window rect if recents is resizing
-     *                           while being launched
-     */
-    private void updateHeaderBarLayout(TaskStack stack, Rect windowRectOverride) {
-        Rect windowRect = getWindowRect(windowRectOverride);
-        int taskViewWidth = 0;
-        boolean useGridLayout = mDummyStackView.useGridLayout();
-        updateDummyStackViewLayout(mDummyStackView.getStackAlgorithm(), stack, windowRect);
-        if (stack != null) {
-            TaskStackLayoutAlgorithm stackLayout = mDummyStackView.getStackAlgorithm();
-            mDummyStackView.getStack().removeAllTasks(false /* notifyStackChanges */);
-            mDummyStackView.setTasks(stack, false /* allowNotifyStackChanges */);
-            // Get the width of a task view so that we know how wide to draw the header bar.
-            if (useGridLayout) {
-                TaskGridLayoutAlgorithm gridLayout = mDummyStackView.getGridAlgorithm();
-                gridLayout.initialize(windowRect);
-                taskViewWidth = (int) gridLayout.getTransform(0 /* taskIndex */,
-                        stack.getTaskCount(), new TaskViewTransform(),
-                        stackLayout).rect.width();
-            } else {
-                Rect taskViewBounds = stackLayout.getUntransformedTaskViewBounds();
-                if (!taskViewBounds.isEmpty()) {
-                    taskViewWidth = taskViewBounds.width();
-                }
-            }
-        }
-
-        if (stack != null && taskViewWidth > 0) {
-            synchronized (mHeaderBarLock) {
-                if (mHeaderBar.getMeasuredWidth() != taskViewWidth ||
-                        mHeaderBar.getMeasuredHeight() != mTaskBarHeight) {
-                    if (useGridLayout) {
-                        mHeaderBar.setShouldDarkenBackgroundColor(true);
-                        mHeaderBar.setNoUserInteractionState();
-                    }
-                    mHeaderBar.forceLayout();
-                    mHeaderBar.measure(
-                            MeasureSpec.makeMeasureSpec(taskViewWidth, MeasureSpec.EXACTLY),
-                            MeasureSpec.makeMeasureSpec(mTaskBarHeight, MeasureSpec.EXACTLY));
-                }
-                mHeaderBar.layout(0, 0, taskViewWidth, mTaskBarHeight);
-            }
-        }
-    }
-
-    /**
-     * Given the stable insets and the rect for our window, calculates the insets that affect our
-     * window.
-     */
-    private void calculateWindowStableInsets(Rect inOutInsets, Rect windowRect, Rect displayRect) {
-
-        // Display rect without insets - available app space
-        Rect appRect = new Rect(displayRect);
-        appRect.inset(inOutInsets);
-
-        // Our window intersected with available app space
-        Rect windowRectWithInsets = new Rect(windowRect);
-        windowRectWithInsets.intersect(appRect);
-        inOutInsets.left = windowRectWithInsets.left - windowRect.left;
-        inOutInsets.top = windowRectWithInsets.top - windowRect.top;
-        inOutInsets.right = windowRect.right - windowRectWithInsets.right;
-        inOutInsets.bottom = windowRect.bottom - windowRectWithInsets.bottom;
-    }
-
-    /**
-     * Preloads the icon of a task.
-     */
-    private void preloadIcon(int runningTaskId) {
-        // Ensure that we load the running task's icon
-        RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options();
-        launchOpts.runningTaskId = runningTaskId;
-        launchOpts.loadThumbnails = false;
-        launchOpts.onlyLoadForCache = true;
-        LegacyRecentsImpl.getTaskLoader().loadTasks(sInstanceLoadPlan, launchOpts);
-    }
-
-    /**
-     * Creates the activity options for a unknown state->recents transition.
-     */
-    protected ActivityOptions getUnknownTransitionActivityOptions() {
-        return ActivityOptions.makeCustomAnimation(mContext,
-                R.anim.recents_from_unknown_enter,
-                R.anim.recents_from_unknown_exit,
-                mHandler, null);
-    }
-
-    /**
-     * Creates the activity options for a home->recents transition.
-     */
-    protected ActivityOptions getHomeTransitionActivityOptions() {
-        return ActivityOptions.makeCustomAnimation(mContext,
-                R.anim.recents_from_launcher_enter,
-                R.anim.recents_from_launcher_exit,
-                mHandler, null);
-    }
-
-    /**
-     * Creates the activity options for an app->recents transition.
-     */
-    private Pair<ActivityOptions, AppTransitionAnimationSpecsFuture>
-            getThumbnailTransitionActivityOptions(ActivityManager.RunningTaskInfo runningTask,
-                    Rect windowOverrideRect) {
-        final boolean isLowRamDevice = LegacyRecentsImpl.getConfiguration().isLowRamDevice;
-
-        // Update the destination rect
-        Task toTask = new Task();
-        TaskViewTransform toTransform = getThumbnailTransitionTransform(mDummyStackView, toTask,
-                windowOverrideRect);
-
-        RectF toTaskRect = toTransform.rect;
-        AppTransitionAnimationSpecsFuture future = new AppTransitionAnimationSpecsFuture(mHandler) {
-            @Override
-            public List<AppTransitionAnimationSpecCompat> composeSpecs() {
-                Rect rect = new Rect();
-                toTaskRect.round(rect);
-                Bitmap thumbnail = drawThumbnailTransitionBitmap(toTask, toTransform);
-                return Lists.newArrayList(new AppTransitionAnimationSpecCompat(toTask.key.id,
-                        thumbnail, rect));
-            }
-        };
-
-        // For low end ram devices, wait for transition flag is reset when Recents entrance
-        // animation is complete instead of when the transition animation starts
-        return new Pair<>(RecentsTransition.createAspectScaleAnimation(mContext, mHandler,
-                false /* scaleUp */, future, isLowRamDevice ? null : mResetToggleFlagListener),
-                future);
-    }
-
-    /**
-     * Returns the transition rect for the given task id.
-     */
-    private TaskViewTransform getThumbnailTransitionTransform(TaskStackView stackView,
-            Task runningTaskOut, Rect windowOverrideRect) {
-        // Find the running task in the TaskStack
-        TaskStack stack = stackView.getStack();
-        Task launchTask = stack.getLaunchTarget();
-        if (launchTask != null) {
-            runningTaskOut.copyFrom(launchTask);
-        } else {
-            // If no task is specified or we can not find the task just use the front most one
-            launchTask = stack.getFrontMostTask();
-            runningTaskOut.copyFrom(launchTask);
-        }
-
-        // Get the transform for the running task
-        stackView.updateLayoutAlgorithm(true /* boundScroll */);
-        stackView.updateToInitialState();
-        stackView.getStackAlgorithm().getStackTransformScreenCoordinates(launchTask,
-                stackView.getScroller().getStackScroll(), mTmpTransform, null, windowOverrideRect);
-        return mTmpTransform;
-    }
-
-    /**
-     * Draws the header of a task used for the window animation into a bitmap.
-     */
-    private Bitmap drawThumbnailTransitionBitmap(Task toTask,
-            TaskViewTransform toTransform) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        int width = (int) toTransform.rect.width();
-        int height = (int) toTransform.rect.height();
-        if (toTransform != null && toTask.key != null && width > 0 && height > 0) {
-            synchronized (mHeaderBarLock) {
-                boolean disabledInSafeMode = !toTask.isSystemApp && ssp.isInSafeMode();
-                mHeaderBar.onTaskViewSizeChanged(width, height);
-                if (RecentsDebugFlags.Static.EnableTransitionThumbnailDebugMode) {
-                    return RecentsTransition.drawViewIntoHardwareBitmap(width, mTaskBarHeight,
-                            null, 1f, 0xFFff0000);
-                } else {
-                    // Workaround for b/27815919, reset the callback so that we do not trigger an
-                    // invalidate on the header bar as a result of updating the icon
-                    Drawable icon = mHeaderBar.getIconView().getDrawable();
-                    if (icon != null) {
-                        icon.setCallback(null);
-                    }
-                    mHeaderBar.bindToTask(toTask, false /* touchExplorationEnabled */,
-                            disabledInSafeMode);
-                    mHeaderBar.onTaskDataLoaded();
-                    mHeaderBar.setDimAlpha(toTransform.dimAlpha);
-                    return RecentsTransition.drawViewIntoHardwareBitmap(width, mTaskBarHeight,
-                            mHeaderBar, 1f, 0);
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Shows the recents activity after dismissing the keyguard if visible
-     */
-    protected void startRecentsActivityAndDismissKeyguardIfNeeded(
-            final ActivityManager.RunningTaskInfo runningTask, final boolean isHomeStackVisible,
-            final boolean animate, final int growTarget) {
-        // Preload only if device for current user is unlocked
-        final StatusBar statusBar = getStatusBar();
-        if (statusBar != null && statusBar.isKeyguardShowing()) {
-            statusBar.executeRunnableDismissingKeyguard(() -> {
-                    // Flush trustmanager before checking device locked per user when preloading
-                    mTrustManager.reportKeyguardShowingChanged();
-                    mHandler.post(() -> startRecentsActivity(runningTask, isHomeStackVisible,
-                            animate, growTarget));
-                }, null,  true /* dismissShade */, false /* afterKeyguardGone */,
-                true /* deferred */);
-        } else {
-            startRecentsActivity(runningTask, isHomeStackVisible, animate, growTarget);
-        }
-    }
-
-    private void startRecentsActivity(ActivityManager.RunningTaskInfo runningTask,
-            boolean isHomeStackVisible, boolean animate, int growTarget) {
-        RecentsTaskLoader loader = LegacyRecentsImpl.getTaskLoader();
-        RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-
-        int runningTaskId = !mLaunchedWhileDocking && (runningTask != null)
-                ? runningTask.id
-                : -1;
-
-        // In the case where alt-tab is triggered, we never get a preloadRecents() call, so we
-        // should always preload the tasks now. If we are dragging in recents, reload them as
-        // the stacks might have changed.
-        if (mLaunchedWhileDocking || mTriggeredFromAltTab || sInstanceLoadPlan == null) {
-            // Create a new load plan if preloadRecents() was never triggered
-            sInstanceLoadPlan = new RecentsTaskLoadPlan(mContext);
-        }
-        if (mLaunchedWhileDocking || mTriggeredFromAltTab || !sInstanceLoadPlan.hasTasks()) {
-            loader.preloadTasks(sInstanceLoadPlan, runningTaskId);
-        }
-
-        TaskStack stack = sInstanceLoadPlan.getTaskStack();
-        boolean hasRecentTasks = stack.getTaskCount() > 0;
-        boolean useThumbnailTransition = (runningTask != null) && !isHomeStackVisible &&
-                hasRecentTasks;
-
-        // Update the launch state that we need in updateHeaderBarLayout()
-        launchState.launchedFromHome = !useThumbnailTransition && !mLaunchedWhileDocking;
-        launchState.launchedFromApp = useThumbnailTransition || mLaunchedWhileDocking;
-        launchState.launchedFromPipApp = false;
-        launchState.launchedWithNextPipApp =
-                stack.isNextLaunchTargetPip(RecentsImpl.getLastPipTime());
-        launchState.launchedViaDockGesture = mLaunchedWhileDocking;
-        launchState.launchedViaDragGesture = mDraggingInRecents;
-        launchState.launchedToTaskId = runningTaskId;
-        launchState.launchedWithAltTab = mTriggeredFromAltTab;
-
-        // Disable toggling of recents between starting the activity and it is visible and the app
-        // has started its transition into recents.
-        setWaitingForTransitionStart(useThumbnailTransition);
-
-        // Preload the icon (this will be a null-op if we have preloaded the icon already in
-        // preloadRecents())
-        preloadIcon(runningTaskId);
-
-        // Update the header bar if necessary
-        Rect windowOverrideRect = getWindowRectOverride(growTarget);
-        updateHeaderBarLayout(stack, windowOverrideRect);
-
-        // Prepare the dummy stack for the transition
-        TaskStackLayoutAlgorithm.VisibilityReport stackVr =
-                mDummyStackView.computeStackVisibilityReport();
-
-        // Update the remaining launch state
-        launchState.launchedNumVisibleTasks = stackVr.numVisibleTasks;
-        launchState.launchedNumVisibleThumbnails = stackVr.numVisibleThumbnails;
-
-        if (!animate) {
-            startRecentsActivity(ActivityOptions.makeCustomAnimation(mContext, -1, -1),
-                    null /* future */);
-            return;
-        }
-
-        Pair<ActivityOptions, AppTransitionAnimationSpecsFuture> pair;
-        if (useThumbnailTransition) {
-            // Try starting with a thumbnail transition
-            pair = getThumbnailTransitionActivityOptions(runningTask, windowOverrideRect);
-        } else {
-            // If there is no thumbnail transition, but is launching from home into recents, then
-            // use a quick home transition
-            pair = new Pair<>(hasRecentTasks
-                    ? getHomeTransitionActivityOptions()
-                    : getUnknownTransitionActivityOptions(), null);
-        }
-        startRecentsActivity(pair.first, pair.second);
-        mLastToggleTime = SystemClock.elapsedRealtime();
-    }
-
-    private Rect getWindowRectOverride(int growTarget) {
-        if (growTarget == DividerView.INVALID_RECENTS_GROW_TARGET) {
-            return SystemServicesProxy.getInstance(mContext).getWindowRect();
-        }
-        Rect result = new Rect();
-        Rect displayRect = LegacyRecentsImpl.getSystemServices().getDisplayRect();
-        DockedDividerUtils.calculateBoundsForPosition(growTarget, WindowManager.DOCKED_BOTTOM,
-                result, displayRect.width(), displayRect.height(),
-                LegacyRecentsImpl.getSystemServices().getDockedDividerSize(mContext));
-        return result;
-    }
-
-    private StatusBar getStatusBar() {
-        return SysUiServiceProvider.getComponent(mContext, StatusBar.class);
-    }
-
-    /**
-     * Starts the recents activity.
-     */
-    private void startRecentsActivity(ActivityOptions opts,
-            final AppTransitionAnimationSpecsFuture future) {
-        Intent intent = new Intent();
-        intent.setClassName(RECENTS_PACKAGE, RECENTS_ACTIVITY);
-        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
-                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
-                | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
-        HidePipMenuEvent hideMenuEvent = new HidePipMenuEvent();
-        hideMenuEvent.addPostAnimationCallback(() -> {
-            LegacyRecentsImpl.getSystemServices().startActivityAsUserAsync(intent, opts);
-            EventBus.getDefault().send(new RecentsActivityStartingEvent());
-            if (future != null) {
-                future.composeSpecsSynchronous();
-            }
-        });
-        EventBus.getDefault().send(hideMenuEvent);
-
-        // Once we have launched the activity, reset the dummy stack view tasks so we don't hold
-        // onto references to the same tasks consumed by the activity
-        mDummyStackView.setTasks(mEmptyTaskStack, false /* notifyStackChanges */);
-    }
-
-    /**** OnAnimationFinishedListener Implementation ****/
-
-    @Override
-    public void onAnimationFinished() {
-        EventBus.getDefault().post(new EnterRecentsWindowLastAnimationFrameEvent());
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsImplProxy.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsImplProxy.java
deleted file mode 100644
index a1da785..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsImplProxy.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents;
-
-import android.graphics.Rect;
-import android.os.Handler;
-import android.os.Message;
-import android.os.RemoteException;
-
-import com.android.internal.os.SomeArgs;
-
-/**
- * A proxy class which directs all methods from {@link IRecentsNonSystemUserCallbacks} to
- * {@link RecentsImpl} and makes sure they are called from the main thread.
- */
-public class RecentsImplProxy extends IRecentsNonSystemUserCallbacks.Stub {
-
-    private static final int MSG_PRELOAD_RECENTS = 1;
-    private static final int MSG_CANCEL_PRELOADING_RECENTS = 2;
-    private static final int MSG_SHOW_RECENTS = 3;
-    private static final int MSG_HIDE_RECENTS = 4;
-    private static final int MSG_TOGGLE_RECENTS = 5;
-    private static final int MSG_ON_CONFIGURATION_CHANGED = 6;
-    private static final int MSG_DOCK_TOP_TASK = 7;
-    private static final int MSG_ON_DRAGGING_IN_RECENTS = 8;
-    private static final int MSG_ON_DRAGGING_IN_RECENTS_ENDED = 9;
-    private static final int MSG_SHOW_USER_TOAST = 10;
-
-    private RecentsImpl mImpl;
-
-    public RecentsImplProxy(RecentsImpl recentsImpl) {
-        mImpl = recentsImpl;
-    }
-
-    @Override
-    public void preloadRecents() throws RemoteException {
-        mHandler.sendEmptyMessage(MSG_PRELOAD_RECENTS);
-    }
-
-    @Override
-    public void cancelPreloadingRecents() throws RemoteException {
-        mHandler.sendEmptyMessage(MSG_CANCEL_PRELOADING_RECENTS);
-    }
-
-    @Override
-    public void showRecents(boolean triggeredFromAltTab, boolean draggingInRecents, boolean animate,
-            int growTarget) throws RemoteException {
-        SomeArgs args = SomeArgs.obtain();
-        args.argi1 = triggeredFromAltTab ? 1 : 0;
-        args.argi2 = draggingInRecents ? 1 : 0;
-        args.argi3 = animate ? 1 : 0;
-        args.argi4 = growTarget;
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_RECENTS, args));
-    }
-
-    @Override
-    public void hideRecents(boolean triggeredFromAltTab, boolean triggeredFromHomeKey)
-            throws RemoteException {
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_HIDE_RECENTS, triggeredFromAltTab ? 1 :0,
-                triggeredFromHomeKey ? 1 : 0));
-    }
-
-    @Override
-    public void toggleRecents(int growTarget) throws RemoteException {
-        SomeArgs args = SomeArgs.obtain();
-        args.argi1 = growTarget;
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_TOGGLE_RECENTS, args));
-    }
-
-    @Override
-    public void onConfigurationChanged() throws RemoteException {
-        mHandler.sendEmptyMessage(MSG_ON_CONFIGURATION_CHANGED);
-    }
-
-    @Override
-    public void splitPrimaryTask(int topTaskId, int stackCreateMode, Rect initialBounds)
-            throws RemoteException {
-        SomeArgs args = SomeArgs.obtain();
-        args.argi1 = topTaskId;
-        args.argi2 = stackCreateMode;
-        args.arg1 = initialBounds;
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_DOCK_TOP_TASK, args));
-    }
-
-    @Override
-    public void onDraggingInRecents(float distanceFromTop) throws RemoteException {
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_ON_DRAGGING_IN_RECENTS, distanceFromTop));
-    }
-
-    @Override
-    public void onDraggingInRecentsEnded(float velocity) throws RemoteException {
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_ON_DRAGGING_IN_RECENTS_ENDED, velocity));
-    }
-
-    @Override
-    public void showCurrentUserToast(int msgResId, int msgLength) {
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_USER_TOAST, msgResId, msgLength));
-    }
-
-    private final Handler mHandler = new Handler() {
-
-        @Override
-        public void handleMessage(Message msg) {
-            SomeArgs args;
-            switch (msg.what) {
-                case MSG_PRELOAD_RECENTS:
-                    mImpl.preloadRecents();
-                    break;
-                case MSG_CANCEL_PRELOADING_RECENTS:
-                    mImpl.cancelPreloadingRecents();
-                    break;
-                case MSG_SHOW_RECENTS:
-                    args = (SomeArgs) msg.obj;
-                    mImpl.showRecents(args.argi1 != 0, args.argi2 != 0, args.argi3 != 0,
-                            args.argi4);
-                    break;
-                case MSG_HIDE_RECENTS:
-                    mImpl.hideRecents(msg.arg1 != 0, msg.arg2 != 0);
-                    break;
-                case MSG_TOGGLE_RECENTS:
-                    args = (SomeArgs) msg.obj;
-                    mImpl.toggleRecents(args.argi1);
-                    break;
-                case MSG_ON_CONFIGURATION_CHANGED:
-                    mImpl.onConfigurationChanged();
-                    break;
-                case MSG_DOCK_TOP_TASK:
-                    args = (SomeArgs) msg.obj;
-                    mImpl.splitPrimaryTask(args.argi1, args.argi2 = 0,
-                            (Rect) args.arg1);
-                    break;
-                case MSG_ON_DRAGGING_IN_RECENTS:
-                    mImpl.onDraggingInRecents((Float) msg.obj);
-                    break;
-                case MSG_ON_DRAGGING_IN_RECENTS_ENDED:
-                    mImpl.onDraggingInRecentsEnded((Float) msg.obj);
-                    break;
-                case MSG_SHOW_USER_TOAST:
-                    mImpl.onShowCurrentUserToast(msg.arg1, msg.arg2);
-                    break;
-                default:
-                    super.handleMessage(msg);
-            }
-            super.handleMessage(msg);
-        }
-    };
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsSystemUser.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsSystemUser.java
deleted file mode 100644
index c5e9f04..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsSystemUser.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents;
-
-import android.content.Context;
-import android.graphics.Rect;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.EventLog;
-import android.util.Log;
-import android.util.SparseArray;
-
-import com.android.systemui.EventLogConstants;
-import com.android.systemui.EventLogTags;
-import com.android.systemui.pip.phone.ForegroundThread;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.DockedFirstAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.DockedTopTaskEvent;
-import com.android.systemui.recents.events.activity.RecentsActivityStartingEvent;
-import com.android.systemui.recents.events.component.SetWaitingForTransitionStartEvent;
-import com.android.systemui.recents.events.ui.RecentsDrawnEvent;
-
-/**
- * An implementation of the system user's Recents interface to be called remotely by secondary
- * users.
- */
-public class RecentsSystemUser extends IRecentsSystemUserCallbacks.Stub {
-
-    private static final String TAG = "RecentsSystemUser";
-
-    private Context mContext;
-    private RecentsImpl mImpl;
-    private final SparseArray<IRecentsNonSystemUserCallbacks> mNonSystemUserRecents =
-            new SparseArray<>();
-
-    public RecentsSystemUser(Context context, RecentsImpl impl) {
-        mContext = context;
-        mImpl = impl;
-    }
-
-    @Override
-    public void registerNonSystemUserCallbacks(final IBinder nonSystemUserCallbacks,
-            final int userId) {
-        try {
-            final IRecentsNonSystemUserCallbacks callback =
-                    IRecentsNonSystemUserCallbacks.Stub.asInterface(nonSystemUserCallbacks);
-            nonSystemUserCallbacks.linkToDeath(new IBinder.DeathRecipient() {
-                @Override
-                public void binderDied() {
-                    mNonSystemUserRecents.removeAt(mNonSystemUserRecents.indexOfValue(callback));
-                    EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION,
-                            EventLogConstants.SYSUI_RECENTS_CONNECTION_SYSTEM_UNREGISTER_USER,
-                            userId);
-                }
-            }, 0);
-            mNonSystemUserRecents.put(userId, callback);
-            EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION,
-                    EventLogConstants.SYSUI_RECENTS_CONNECTION_SYSTEM_REGISTER_USER, userId);
-        } catch (RemoteException e) {
-            Log.e(TAG, "Failed to register NonSystemUserCallbacks", e);
-        }
-    }
-
-    public IRecentsNonSystemUserCallbacks getNonSystemUserRecentsForUser(int userId) {
-        return mNonSystemUserRecents.get(userId);
-    }
-
-    @Override
-    public void updateRecentsVisibility(boolean visible) {
-        ForegroundThread.getHandler().post(() -> {
-            mImpl.onVisibilityChanged(mContext, visible);
-        });
-    }
-
-    @Override
-    public void startScreenPinning(int taskId) {
-        ForegroundThread.getHandler().post(() -> {
-            mImpl.onStartScreenPinning(mContext, taskId);
-        });
-    }
-
-    @Override
-    public void sendRecentsDrawnEvent() {
-        EventBus.getDefault().post(new RecentsDrawnEvent());
-    }
-
-    @Override
-    public void sendDockingTopTaskEvent(Rect initialRect) throws RemoteException {
-        EventBus.getDefault().post(new DockedTopTaskEvent(initialRect));
-    }
-
-    @Override
-    public void sendLaunchRecentsEvent() throws RemoteException {
-        EventBus.getDefault().post(new RecentsActivityStartingEvent());
-    }
-
-    @Override
-    public void sendDockedFirstAnimationFrameEvent() throws RemoteException {
-        EventBus.getDefault().post(new DockedFirstAnimationFrameEvent());
-    }
-
-    @Override
-    public void setWaitingForTransitionStartEvent(boolean waitingForTransitionStart) {
-        EventBus.getDefault().post(new SetWaitingForTransitionStartEvent(
-                waitingForTransitionStart));
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsSystemUserService.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsSystemUserService.java
deleted file mode 100644
index b5a0181..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/RecentsSystemUserService.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2010 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.recents;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.IBinder;
-import android.util.Log;
-
-import com.android.systemui.SysUiServiceProvider;
-
-/**
- * A strictly system-user service that is started by the secondary user's Recents (with a limited
- * lifespan), to get the interface that the secondary user's Recents can call through to the system
- * user's Recents.
- */
-public class RecentsSystemUserService extends Service {
-
-    private static final String TAG = "RecentsSystemUserService";
-    private static final boolean DEBUG = false;
-
-    @Override
-    public void onCreate() {
-        super.onCreate();
-    }
-
-    @Override
-    public IBinder onBind(Intent intent) {
-        LegacyRecentsImpl recents = SysUiServiceProvider.getComponent(this, LegacyRecentsImpl.class);
-        if (DEBUG) {
-            Log.d(TAG, "onBind: " + recents);
-        }
-        if (recents != null) {
-            return recents.getSystemUserCallbacks();
-        }
-        return null;
-    }
-}
-
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/EventBus.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/EventBus.java
deleted file mode 100644
index 177362c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/EventBus.java
+++ /dev/null
@@ -1,763 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.events;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.os.SystemClock;
-import android.os.UserHandle;
-import android.util.Log;
-
-import com.android.systemui.recents.misc.ReferenceCountedTrigger;
-
-import java.io.PrintWriter;
-import java.lang.ref.WeakReference;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-
-/**
- * Represents a subscriber, which implements various event bus handler methods.
- */
-class Subscriber {
-    private WeakReference<Object> mSubscriber;
-
-    long registrationTime;
-
-    Subscriber(Object subscriber, long registrationTime) {
-        mSubscriber = new WeakReference<>(subscriber);
-        this.registrationTime = registrationTime;
-    }
-
-    public String toString(int priority) {
-        Object sub = mSubscriber.get();
-        String id = Integer.toHexString(System.identityHashCode(sub));
-        return sub.getClass().getSimpleName() + " [0x" + id + ", P" + priority + "]";
-    }
-
-    public Object getReference() {
-        return mSubscriber.get();
-    }
-}
-
-/**
- * Represents an event handler with a priority.
- */
-class EventHandler {
-    int priority;
-    Subscriber subscriber;
-    EventHandlerMethod method;
-
-    EventHandler(Subscriber subscriber, EventHandlerMethod method, int priority) {
-        this.subscriber = subscriber;
-        this.method = method;
-        this.priority = priority;
-    }
-
-    @Override
-    public String toString() {
-        return subscriber.toString(priority) + " " + method.toString();
-    }
-}
-
-/**
- * Represents the low level method handling a particular event.
- */
-class EventHandlerMethod {
-    private Method mMethod;
-    Class<? extends EventBus.Event> eventType;
-
-    EventHandlerMethod(Method method, Class<? extends EventBus.Event> eventType) {
-        mMethod = method;
-        mMethod.setAccessible(true);
-        this.eventType = eventType;
-    }
-
-    public void invoke(Object target, EventBus.Event event)
-            throws InvocationTargetException, IllegalAccessException {
-        mMethod.invoke(target, event);
-    }
-
-    @Override
-    public String toString() {
-        return mMethod.getName() + "(" + eventType.getSimpleName() + ")";
-    }
-}
-
-/**
- * A simple in-process event bus.  It is simple because we can make assumptions about the state of
- * SystemUI and Recent's lifecycle.
- *
- * <p>
- * Currently, there is a single EventBus that handles {@link EventBus.Event}s for each subscriber
- * on the main application thread.  Publishers can send() events to synchronously call subscribers
- * of that event, or post() events to be processed in the next run of the {@link Looper}.
- *
- * <p>
- * Subscribers must be registered with a particular EventBus before they will receive events, and
- * handler methods must match a specific signature.
- *
- * <p>
- * Event method signature:<ul>
- * <li>Methods must be public final
- * <li>Methods must return void
- * <li>Methods must be called "onBusEvent"
- * <li>Methods must take one parameter, of class type deriving from {@link EventBus.Event}
- * </ul>
- *
- * </p>
- * Each subscriber can be registered with a given priority (default 1), and events will be dispatch
- * in decreasing order of priority.  For subscribers with the same priority, events will be
- * dispatched by latest registration time to earliest.
- *
- * <p>
- * Caveats:<ul>
- * <li>The EventBus keeps a {@link WeakReference} to the publisher to prevent memory leaks, so
- * there must be another strong reference to the publisher for it to not get garbage-collected and
- * continue receiving events.
- * <li>Because the event handlers are called back using reflection, the EventBus is not intended
- * for use in tight, performance criticial loops.  For most user input/system callback events, this
- * is generally of low enough frequency to use the EventBus.
- * <li>Because the event handlers are called back using reflection, there will often be no
- * references to them from actual code.  The proguard configuration will be need to be updated to
- * keep these extra methods:
- *
- * -keepclassmembers class ** {
- * public void onBusEvent(**);
- * public void onInterprocessBusEvent(**);
- * }
- * -keepclassmembers class ** extends **.EventBus$InterprocessEvent {
- * public <init>(android.os.Bundle);
- * }
- *
- * <li>Subscriber registration can be expensive depending on the subscriber's {@link Class}.  This
- * is only done once per class type, but if possible, it is best to pre-register an instance of
- * that class beforehand or when idle.
- * <li>Each event should be sent once.  Events may hold internal information about the current
- * dispatch, or may be queued to be dispatched on another thread (if posted from a non-main thread),
- * so it may be unsafe to edit, change, or re-send the event again.
- * <li>Events should follow a pattern of public-final POD (plain old data) objects, where they are
- * initialized by the constructor and read by each subscriber of that event.  Subscribers should
- * never alter events as they are processed, and this enforces that pattern.
- * </ul>
- *
- * <p>
- * Future optimizations:
- * <li>throw exception/log when a subscriber loses the reference
- * <li>trace cost per registration & invocation
- * <li>trace cross-process invocation
- * <li>register(subscriber, Class&lt;?&gt;...) -- pass in exact class types you want registered
- * <li>setSubscriberEventHandlerPriority(subscriber, Class<Event>, priority)
- * <li>allow subscribers to implement interface, ie. EventBus.Subscriber, which lets then test a
- * message before invocation (ie. check if task id == this task id)
- * <li>add postOnce() which automatically debounces
- * <li>add postDelayed() which delays / postDelayedOnce() which delays and bounces
- * <li>consolidate register() and registerInterprocess()
- * <li>sendForResult&lt;ReturnType&gt;(Event) to send and get a result, but who will send the
- * result?
- * </p>
- */
-public class EventBus {
-
-    private static final String TAG = "EventBus";
-    private static final boolean DEBUG_TRACE_ALL = false;
-
-    /**
-     * An event super class that allows us to track internal event state across subscriber
-     * invocations.
-     *
-     * Events should not be edited by subscribers.
-     */
-    public static class Event implements Cloneable {
-        // Indicates that this event's dispatch should be traced and logged to logcat
-        boolean trace;
-        // Indicates that this event must be posted on the EventBus's looper thread before invocation
-        boolean requiresPost;
-        // Not currently exposed, allows a subscriber to cancel further dispatch of this event
-        boolean cancelled;
-
-        // Only accessible from derived events
-        protected Event() {}
-
-        /**
-         * Called by the EventBus prior to dispatching this event to any subscriber of this event.
-         */
-        void onPreDispatch() {
-            // Do nothing
-        }
-
-        /**
-         * Called by the EventBus after dispatching this event to every subscriber of this event.
-         */
-        void onPostDispatch() {
-            // Do nothing
-        }
-
-        @Override
-        protected Object clone() throws CloneNotSupportedException {
-            Event evt = (Event) super.clone();
-            // When cloning an event, reset the cancelled-dispatch state
-            evt.cancelled = false;
-            return evt;
-        }
-    }
-
-    /**
-     * An event that represents an animated state change, which allows subscribers to coordinate
-     * callbacks which happen after the animation has taken place.
-     *
-     * Internally, it is guaranteed that increment() and decrement() will be called before and the
-     * after the event is dispatched.
-     */
-    public static class AnimatedEvent extends Event {
-
-        private final ReferenceCountedTrigger mTrigger = new ReferenceCountedTrigger();
-
-        // Only accessible from derived events
-        protected AnimatedEvent() {}
-
-        /**
-         * Returns the reference counted trigger that coordinates the animations for this event.
-         */
-        public ReferenceCountedTrigger getAnimationTrigger() {
-            return mTrigger;
-        }
-
-        /**
-         * Adds a callback that is guaranteed to be called after the state has changed regardless of
-         * whether an actual animation took place.
-         */
-        public void addPostAnimationCallback(Runnable r) {
-            mTrigger.addLastDecrementRunnable(r);
-        }
-
-        @Override
-        void onPreDispatch() {
-            mTrigger.increment();
-        }
-
-        @Override
-        void onPostDispatch() {
-            mTrigger.decrement();
-        }
-
-        @Override
-        protected Object clone() throws CloneNotSupportedException {
-            throw new CloneNotSupportedException();
-        }
-    }
-
-    /**
-     * An event that can be reusable, only used for situations where we want to reduce memory
-     * allocations when events are sent frequently (ie. on scroll).
-     */
-    public static class ReusableEvent extends Event {
-
-        private int mDispatchCount;
-
-        protected ReusableEvent() {}
-
-        @Override
-        void onPostDispatch() {
-            super.onPostDispatch();
-            mDispatchCount++;
-        }
-
-        @Override
-        protected Object clone() throws CloneNotSupportedException {
-            throw new CloneNotSupportedException();
-        }
-    }
-
-    /**
-     * Proguard must also know, and keep, all methods matching this signature.
-     *
-     * -keepclassmembers class ** {
-     *     public void onBusEvent(**);
-     *     public void onInterprocessBusEvent(**);
-     * }
-     */
-    private static final String METHOD_PREFIX = "onBusEvent";
-
-    // The default priority of all subscribers
-    private static final int DEFAULT_SUBSCRIBER_PRIORITY = 1;
-
-    // Orders the handlers by priority and registration time
-    private static final Comparator<EventHandler> EVENT_HANDLER_COMPARATOR = new Comparator<EventHandler>() {
-        @Override
-        public int compare(EventHandler h1, EventHandler h2) {
-            // Rank the handlers by priority descending, followed by registration time descending.
-            // aka. the later registered
-            if (h1.priority != h2.priority) {
-                return h2.priority - h1.priority;
-            } else {
-                return Long.compare(h2.subscriber.registrationTime, h1.subscriber.registrationTime);
-            }
-        }
-    };
-
-    // Used for initializing the default bus
-    private static final Object sLock = new Object();
-    private static volatile EventBus sDefaultBus;
-
-    // The handler to post all events
-    private Handler mHandler;
-
-    /**
-     * Map from event class -> event handler list.  Keeps track of the actual mapping from event
-     * to subscriber method.
-     */
-    private HashMap<Class<? extends Event>, ArrayList<EventHandler>> mEventTypeMap = new HashMap<>();
-
-    /**
-     * Map from subscriber class -> event handler method lists.  Used to determine upon registration
-     * of a new subscriber whether we need to read all the subscriber's methods again using
-     * reflection or whether we can just add the subscriber to the event type map.
-     */
-    private HashMap<Class<? extends Object>, ArrayList<EventHandlerMethod>> mSubscriberTypeMap = new HashMap<>();
-
-    /**
-     * Set of all currently registered subscribers
-     */
-    private ArrayList<Subscriber> mSubscribers = new ArrayList<>();
-
-    // For tracing
-    private int mCallCount;
-    private long mCallDurationMicros;
-
-    /**
-     * Private constructor to create an event bus for a given looper.
-     */
-    private EventBus(Looper looper) {
-        mHandler = new Handler(looper);
-    }
-
-    /**
-     * @return the default event bus for the application's main thread.
-     */
-    public static EventBus getDefault() {
-        if (sDefaultBus == null)
-        synchronized (sLock) {
-            if (sDefaultBus == null) {
-                if (DEBUG_TRACE_ALL) {
-                    logWithPid("New EventBus");
-                }
-                sDefaultBus = new EventBus(Looper.getMainLooper());
-            }
-        }
-        return sDefaultBus;
-    }
-
-    /**
-     * Registers a subscriber to receive events with the default priority.
-     *
-     * @param subscriber the subscriber to handle events.  If this is the first instance of the
-     *                   subscriber's class type that has been registered, the class's methods will
-     *                   be scanned for appropriate event handler methods.
-     */
-    public void register(Object subscriber) {
-        registerSubscriber(subscriber, DEFAULT_SUBSCRIBER_PRIORITY);
-    }
-
-    /**
-     * Registers a subscriber to receive events with the given priority.
-     *
-     * @param subscriber the subscriber to handle events.  If this is the first instance of the
-     *                   subscriber's class type that has been registered, the class's methods will
-     *                   be scanned for appropriate event handler methods.
-     * @param priority the priority that this subscriber will receive events relative to other
-     *                 subscribers
-     */
-    public void register(Object subscriber, int priority) {
-        registerSubscriber(subscriber, priority);
-    }
-
-    /**
-     * Remove all EventHandlers pointing to the specified subscriber.  This does not remove the
-     * mapping of subscriber type to event handler method, in case new instances of this subscriber
-     * are registered.
-     */
-    public void unregister(Object subscriber) {
-        if (DEBUG_TRACE_ALL) {
-            logWithPid("unregister()");
-        }
-
-        // Fail immediately if we are being called from the non-main thread
-        long callingThreadId = Thread.currentThread().getId();
-        if (callingThreadId != mHandler.getLooper().getThread().getId()) {
-            throw new RuntimeException("Can not unregister() a subscriber from a non-main thread.");
-        }
-
-        // Return early if this is not a registered subscriber
-        if (!findRegisteredSubscriber(subscriber, true /* removeFoundSubscriber */)) {
-            return;
-        }
-
-        Class<?> subscriberType = subscriber.getClass();
-        ArrayList<EventHandlerMethod> subscriberMethods = mSubscriberTypeMap.get(subscriberType);
-        if (subscriberMethods != null) {
-            // For each of the event handlers the subscriber handles, remove all references of that
-            // handler
-            for (EventHandlerMethod method : subscriberMethods) {
-                ArrayList<EventHandler> eventHandlers = mEventTypeMap.get(method.eventType);
-                for (int i = eventHandlers.size() - 1; i >= 0; i--) {
-                    if (eventHandlers.get(i).subscriber.getReference() == subscriber) {
-                        eventHandlers.remove(i);
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * Sends an event to the subscribers of the given event type immediately.  This can only be
-     * called from the same thread as the EventBus's looper thread (for the default EventBus, this
-     * is the main application thread).
-     */
-    public void send(Event event) {
-        // Fail immediately if we are being called from the non-main thread
-        long callingThreadId = Thread.currentThread().getId();
-        if (callingThreadId != mHandler.getLooper().getThread().getId()) {
-            throw new RuntimeException("Can not send() a message from a non-main thread.");
-        }
-
-        if (DEBUG_TRACE_ALL) {
-            logWithPid("send(" + event.getClass().getSimpleName() + ")");
-        }
-
-        // Reset the event's cancelled state
-        event.requiresPost = false;
-        event.cancelled = false;
-        queueEvent(event);
-    }
-
-    /**
-     * Post a message to the subscribers of the given event type.  The messages will be posted on
-     * the EventBus's looper thread (for the default EventBus, this is the main application thread).
-     */
-    public void post(Event event) {
-        if (DEBUG_TRACE_ALL) {
-            logWithPid("post(" + event.getClass().getSimpleName() + ")");
-        }
-
-        // Reset the event's cancelled state
-        event.requiresPost = true;
-        event.cancelled = false;
-        queueEvent(event);
-    }
-
-    /**
-     * If this method is called from the main thread, it will be handled directly. If this method
-     * is not called from the main thread, it will be posted onto the main thread.
-     */
-    public void sendOntoMainThread(Event event) {
-        long callingThreadId = Thread.currentThread().getId();
-        if (callingThreadId != mHandler.getLooper().getThread().getId()) {
-            post(event);
-        } else {
-            send(event);
-        }
-    }
-
-    /**
-     * @return a dump of the current state of the EventBus
-     */
-    public void dump(String prefix, PrintWriter writer) {
-        writer.println(dumpInternal(prefix));
-    }
-
-    public String dumpInternal(String prefix) {
-        String innerPrefix = prefix + "  ";
-        String innerInnerPrefix = innerPrefix + "  ";
-        StringBuilder output = new StringBuilder();
-        output.append(prefix);
-        output.append("Registered class types:");
-        output.append("\n");
-        ArrayList<Class<?>> subsciberTypes = new ArrayList<>(mSubscriberTypeMap.keySet());
-        Collections.sort(subsciberTypes, new Comparator<Class<?>>() {
-            @Override
-            public int compare(Class<?> o1, Class<?> o2) {
-                return o1.getSimpleName().compareTo(o2.getSimpleName());
-            }
-        });
-        for (int i = 0; i < subsciberTypes.size(); i++) {
-            Class<?> clz = subsciberTypes.get(i);
-            output.append(innerPrefix);
-            output.append(clz.getSimpleName());
-            output.append("\n");
-        }
-        output.append(prefix);
-        output.append("Event map:");
-        output.append("\n");
-        ArrayList<Class<?>> classes = new ArrayList<>(mEventTypeMap.keySet());
-        Collections.sort(classes, new Comparator<Class<?>>() {
-            @Override
-            public int compare(Class<?> o1, Class<?> o2) {
-                return o1.getSimpleName().compareTo(o2.getSimpleName());
-            }
-        });
-        for (int i = 0; i < classes.size(); i++) {
-            Class<?> clz = classes.get(i);
-            output.append(innerPrefix);
-            output.append(clz.getSimpleName());
-            output.append(" -> ");
-            output.append("\n");
-            ArrayList<EventHandler> handlers = mEventTypeMap.get(clz);
-            for (EventHandler handler : handlers) {
-                Object subscriber = handler.subscriber.getReference();
-                if (subscriber != null) {
-                    String id = Integer.toHexString(System.identityHashCode(subscriber));
-                    output.append(innerInnerPrefix);
-                    output.append(subscriber.getClass().getSimpleName());
-                    output.append(" [0x" + id + ", #" + handler.priority + "]");
-                    output.append("\n");
-                }
-            }
-        }
-        return output.toString();
-    }
-
-    /**
-     * Registers a new subscriber.
-     */
-    private void registerSubscriber(Object subscriber, int priority) {
-        // Fail immediately if we are being called from the non-main thread
-        long callingThreadId = Thread.currentThread().getId();
-        if (callingThreadId != mHandler.getLooper().getThread().getId()) {
-            throw new RuntimeException("Can not register() a subscriber from a non-main thread.");
-        }
-
-        // Return immediately if this exact subscriber is already registered
-        if (findRegisteredSubscriber(subscriber, false /* removeFoundSubscriber */)) {
-            return;
-        }
-
-        long t1 = 0;
-        if (DEBUG_TRACE_ALL) {
-            t1 = SystemClock.currentTimeMicro();
-            logWithPid("registerSubscriber(" + subscriber.getClass().getSimpleName() + ")");
-        }
-        Subscriber sub = new Subscriber(subscriber, SystemClock.uptimeMillis());
-        Class<?> subscriberType = subscriber.getClass();
-        ArrayList<EventHandlerMethod> subscriberMethods = mSubscriberTypeMap.get(subscriberType);
-        if (subscriberMethods != null) {
-            if (DEBUG_TRACE_ALL) {
-                logWithPid("Subscriber class type already registered");
-            }
-
-            // If we've parsed this subscriber type before, just add to the set for all the known
-            // events
-            for (EventHandlerMethod method : subscriberMethods) {
-                ArrayList<EventHandler> eventTypeHandlers = mEventTypeMap.get(method.eventType);
-                eventTypeHandlers.add(new EventHandler(sub, method, priority));
-                sortEventHandlersByPriority(eventTypeHandlers);
-            }
-            mSubscribers.add(sub);
-            return;
-        } else {
-            if (DEBUG_TRACE_ALL) {
-                logWithPid("Subscriber class type requires registration");
-            }
-
-            // If we are parsing this type from scratch, ensure we add it to the subscriber type
-            // map, and pull out he handler methods below
-            subscriberMethods = new ArrayList<>();
-            mSubscriberTypeMap.put(subscriberType, subscriberMethods);
-            mSubscribers.add(sub);
-        }
-
-        // Find all the valid event bus handler methods of the subscriber
-        Method[] methods = subscriberType.getDeclaredMethods();
-        for (Method m : methods) {
-            Class<?>[] parameterTypes = m.getParameterTypes();
-            if (isValidEventBusHandlerMethod(m, parameterTypes)) {
-                Class<? extends Event> eventType = (Class<? extends Event>) parameterTypes[0];
-                ArrayList<EventHandler> eventTypeHandlers = mEventTypeMap.get(eventType);
-                if (eventTypeHandlers == null) {
-                    eventTypeHandlers = new ArrayList<>();
-                    mEventTypeMap.put(eventType, eventTypeHandlers);
-                }
-                EventHandlerMethod method = new EventHandlerMethod(m, eventType);
-                EventHandler handler = new EventHandler(sub, method, priority);
-                eventTypeHandlers.add(handler);
-                subscriberMethods.add(method);
-                sortEventHandlersByPriority(eventTypeHandlers);
-
-                if (DEBUG_TRACE_ALL) {
-                    logWithPid("  * Method: " + m.getName() +
-                            " event: " + parameterTypes[0].getSimpleName());
-                }
-            }
-        }
-        if (DEBUG_TRACE_ALL) {
-            logWithPid("Registered " + subscriber.getClass().getSimpleName() + " in " +
-                    (SystemClock.currentTimeMicro() - t1) + " microseconds");
-        }
-    }
-
-    /**
-     * Adds a new message.
-     */
-    private void queueEvent(final Event event) {
-        ArrayList<EventHandler> eventHandlers = mEventTypeMap.get(event.getClass());
-        if (eventHandlers == null) {
-            // This is just an optimization to return early if there are no handlers. However, we
-            // should still ensure that we call pre/post dispatch callbacks so that AnimatedEvents
-            // are still cleaned up correctly if a listener has not been registered to handle them
-            event.onPreDispatch();
-            event.onPostDispatch();
-            return;
-        }
-
-        // Prepare this event
-        boolean hasPostedEvent = false;
-        event.onPreDispatch();
-
-        // We need to clone the list in case a subscriber unregisters itself during traversal
-        // TODO: Investigate whether we can skip the object creation here
-        eventHandlers = (ArrayList<EventHandler>) eventHandlers.clone();
-        int eventHandlerCount = eventHandlers.size();
-        for (int i = 0; i < eventHandlerCount; i++) {
-            final EventHandler eventHandler = eventHandlers.get(i);
-            if (eventHandler.subscriber.getReference() != null) {
-                if (event.requiresPost) {
-                    mHandler.post(() -> processEvent(eventHandler, event));
-                    hasPostedEvent = true;
-                } else {
-                    processEvent(eventHandler, event);
-                }
-            }
-        }
-
-        // Clean up after this event, deferring until all subscribers have been called
-        if (hasPostedEvent) {
-            mHandler.post(event::onPostDispatch);
-        } else {
-            event.onPostDispatch();
-        }
-    }
-
-    /**
-     * Processes and dispatches the given event to the given event handler, on the thread of whoever
-     * calls this method.
-     */
-    private void processEvent(final EventHandler eventHandler, final Event event) {
-        // Skip if the event was already cancelled
-        if (event.cancelled) {
-            if (event.trace || DEBUG_TRACE_ALL) {
-                logWithPid("Event dispatch cancelled");
-            }
-            return;
-        }
-
-        try {
-            if (event.trace || DEBUG_TRACE_ALL) {
-                logWithPid(" -> " + eventHandler.toString());
-            }
-            Object sub = eventHandler.subscriber.getReference();
-            if (sub != null) {
-                long t1 = 0;
-                if (DEBUG_TRACE_ALL) {
-                    t1 = SystemClock.currentTimeMicro();
-                }
-                eventHandler.method.invoke(sub, event);
-                if (DEBUG_TRACE_ALL) {
-                    long duration = (SystemClock.currentTimeMicro() - t1);
-                    mCallDurationMicros += duration;
-                    mCallCount++;
-                    logWithPid(eventHandler.method.toString() + " duration: " + duration +
-                            " microseconds, avg: " + (mCallDurationMicros / mCallCount));
-                }
-            } else {
-                Log.e(TAG, "Failed to deliver event to null subscriber");
-            }
-        } catch (IllegalAccessException e) {
-            Log.e(TAG, "Failed to invoke method", e.getCause());
-        } catch (InvocationTargetException e) {
-            throw new RuntimeException(e.getCause());
-        }
-    }
-
-    /**
-     * Returns whether this subscriber is currently registered.  If {@param removeFoundSubscriber}
-     * is true, then remove the subscriber before returning.
-     */
-    private boolean findRegisteredSubscriber(Object subscriber, boolean removeFoundSubscriber) {
-        for (int i = mSubscribers.size() - 1; i >= 0; i--) {
-            Subscriber sub = mSubscribers.get(i);
-            if (sub.getReference() == subscriber) {
-                if (removeFoundSubscriber) {
-                    mSubscribers.remove(i);
-                }
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * @return whether {@param method} is a valid (normal or interprocess) event bus handler method
-     */
-    private boolean isValidEventBusHandlerMethod(Method method, Class<?>[] parameterTypes) {
-        int modifiers = method.getModifiers();
-        if (Modifier.isPublic(modifiers) &&
-                Modifier.isFinal(modifiers) &&
-                method.getReturnType().equals(Void.TYPE) &&
-                parameterTypes.length == 1) {
-            if (EventBus.Event.class.isAssignableFrom(parameterTypes[0]) &&
-                            method.getName().startsWith(METHOD_PREFIX)) {
-                return true;
-            } else {
-                if (DEBUG_TRACE_ALL) {
-                    if (!EventBus.Event.class.isAssignableFrom(parameterTypes[0])) {
-                        logWithPid("  Expected method take an Event-based parameter: " + method.getName());
-                    }
-                }
-            }
-        } else {
-            if (DEBUG_TRACE_ALL) {
-                if (!Modifier.isPublic(modifiers)) {
-                    logWithPid("  Expected method to be public: " + method.getName());
-                } else if (!Modifier.isFinal(modifiers)) {
-                    logWithPid("  Expected method to be final: " + method.getName());
-                } else if (!method.getReturnType().equals(Void.TYPE)) {
-                    logWithPid("  Expected method to return null: " + method.getName());
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Sorts the event handlers by priority and registration time.
-     */
-    private void sortEventHandlersByPriority(List<EventHandler> eventHandlers) {
-        Collections.sort(eventHandlers, EVENT_HANDLER_COMPARATOR);
-    }
-
-    /**
-     * Helper method to log the given {@param text} with the current process and user id.
-     */
-    private static void logWithPid(String text) {
-        Log.d(TAG, "[" + android.os.Process.myPid() + ", u" + UserHandle.myUserId() + "] " + text);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/AppTransitionFinishedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/AppTransitionFinishedEvent.java
deleted file mode 100644
index 4738eed..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/AppTransitionFinishedEvent.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Sent when an app transition has finished playing.
- */
-public class AppTransitionFinishedEvent extends EventBus.Event {
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/CancelEnterRecentsWindowAnimationEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/CancelEnterRecentsWindowAnimationEvent.java
deleted file mode 100644
index fec34e3..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/CancelEnterRecentsWindowAnimationEvent.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-
-/**
- * This is sent when we want to cancel the enter-recents window animation for the launch task.
- */
-public class CancelEnterRecentsWindowAnimationEvent extends EventBus.Event {
-
-    // This is set for the task that is launching, which allows us to ensure that we are not
-    // cancelling the same task animation (it will just be overwritten instead)
-    public final Task launchTask;
-
-    public CancelEnterRecentsWindowAnimationEvent(Task launchTask) {
-        this.launchTask = launchTask;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ConfigurationChangedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ConfigurationChangedEvent.java
deleted file mode 100644
index 294c1e7..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ConfigurationChangedEvent.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the Recents activity configuration has changed.
- */
-public class ConfigurationChangedEvent extends EventBus.AnimatedEvent {
-
-    public final boolean fromMultiWindow;
-    public final boolean fromDeviceOrientationChange;
-    public final boolean fromDisplayDensityChange;
-    public final boolean hasStackTasks;
-
-    public ConfigurationChangedEvent(boolean fromMultiWindow, boolean fromDeviceOrientationChange,
-            boolean fromDisplayDensityChange, boolean hasStackTasks) {
-        this.fromMultiWindow = fromMultiWindow;
-        this.fromDeviceOrientationChange = fromDeviceOrientationChange;
-        this.fromDisplayDensityChange = fromDisplayDensityChange;
-        this.hasStackTasks = hasStackTasks;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DismissRecentsToHomeAnimationStarted.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DismissRecentsToHomeAnimationStarted.java
deleted file mode 100644
index e7be858..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DismissRecentsToHomeAnimationStarted.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the task animation when dismissing Recents starts.
- */
-public class DismissRecentsToHomeAnimationStarted extends EventBus.AnimatedEvent {
-
-    public final boolean animated;
-
-    public DismissRecentsToHomeAnimationStarted(boolean animated) {
-        this.animated = animated;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DockedFirstAnimationFrameEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DockedFirstAnimationFrameEvent.java
deleted file mode 100644
index 32d9a70..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DockedFirstAnimationFrameEvent.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus.Event;
-
-/**
- * Sent when the window animation has started when docking a task
- */
-public class DockedFirstAnimationFrameEvent extends Event {
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DockedTopTaskEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DockedTopTaskEvent.java
deleted file mode 100644
index 9e3ced3..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/DockedTopTaskEvent.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.activity;
-
-import android.graphics.Rect;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Fires when the user invoked the gesture to dock the top/left task after we called into window
- * manager and before we start recents.
- */
-public class DockedTopTaskEvent extends EventBus.Event {
-
-    public Rect initialRect;
-
-    public DockedTopTaskEvent(Rect initialRect) {
-        this.initialRect = initialRect;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/EnterRecentsWindowAnimationCompletedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/EnterRecentsWindowAnimationCompletedEvent.java
deleted file mode 100644
index b31f320..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/EnterRecentsWindowAnimationCompletedEvent.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the window animation into Recents completes.  We use this signal to know when
- * we can start in-app animations so that they don't conflict with the window transition into
- * Recents.
- */
-public class EnterRecentsWindowAnimationCompletedEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/EnterRecentsWindowLastAnimationFrameEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/EnterRecentsWindowLastAnimationFrameEvent.java
deleted file mode 100644
index fd023d8..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/EnterRecentsWindowLastAnimationFrameEvent.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-public class EnterRecentsWindowLastAnimationFrameEvent extends EventBus.Event {
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ExitRecentsWindowFirstAnimationFrameEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ExitRecentsWindowFirstAnimationFrameEvent.java
deleted file mode 100644
index fa806eb..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ExitRecentsWindowFirstAnimationFrameEvent.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Event sent when the exit animation is started.
- *
- * This is sent so parts of UI can synchronize on this event and adjust their appearance. An example
- * of that is hiding the tasks when the launched application window becomes visible.
- */
-public class ExitRecentsWindowFirstAnimationFrameEvent extends EventBus.Event {
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/HideRecentsEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/HideRecentsEvent.java
deleted file mode 100644
index bf9b421..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/HideRecentsEvent.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the user taps on the Home button or finishes alt-tabbing to hide the Recents
- * activity.
- */
-public class HideRecentsEvent extends EventBus.Event {
-
-    public final boolean triggeredFromAltTab;
-    public final boolean triggeredFromHomeKey;
-
-    public HideRecentsEvent(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) {
-        this.triggeredFromAltTab = triggeredFromAltTab;
-        this.triggeredFromHomeKey = triggeredFromHomeKey;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/HideStackActionButtonEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/HideStackActionButtonEvent.java
deleted file mode 100644
index e4a4f59..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/HideStackActionButtonEvent.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.systemui.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the stack action button should be hidden.
- */
-public class HideStackActionButtonEvent extends EventBus.Event {
-
-    // Whether or not to translate the stack action button when hiding it
-    public final boolean translate;
-
-    public HideStackActionButtonEvent() {
-        this(true);
-    }
-
-    public HideStackActionButtonEvent(boolean translate) {
-        this.translate = translate;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchMostRecentTaskRequestEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchMostRecentTaskRequestEvent.java
deleted file mode 100644
index 24913a4..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchMostRecentTaskRequestEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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.systemui.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This event is sent to request that the most recent task is launched.
- */
-public class LaunchMostRecentTaskRequestEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchNextTaskRequestEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchNextTaskRequestEvent.java
deleted file mode 100644
index 11604b5..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchNextTaskRequestEvent.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This event is sent to request that the next task is launched after a double-tap on the Recents
- * button.
- */
-public class LaunchNextTaskRequestEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskEvent.java
deleted file mode 100644
index 2409f39..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskEvent.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
-import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
-
-import android.graphics.Rect;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent to request that a particular task is launched.
- */
-public class LaunchTaskEvent extends EventBus.Event {
-
-    public final TaskView taskView;
-    public final Task task;
-    public final Rect targetTaskBounds;
-    public final int targetWindowingMode;
-    public final int targetActivityType;
-    public final boolean screenPinningRequested;
-
-    public LaunchTaskEvent(TaskView taskView, Task task, Rect targetTaskBounds,
-            boolean screenPinningRequested) {
-        this(taskView, task, targetTaskBounds, screenPinningRequested,
-                WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_UNDEFINED);
-    }
-
-    public LaunchTaskEvent(TaskView taskView, Task task, Rect targetTaskBounds,
-            boolean screenPinningRequested, int windowingMode, int activityType) {
-        this.taskView = taskView;
-        this.task = task;
-        this.targetTaskBounds = targetTaskBounds;
-        this.targetWindowingMode = windowingMode;
-        this.targetActivityType = activityType;
-        this.screenPinningRequested = screenPinningRequested;
-    }
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskFailedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskFailedEvent.java
deleted file mode 100644
index 3a2d58c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskFailedEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when we fail to launch a task.
- */
-public class LaunchTaskFailedEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskStartedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskStartedEvent.java
deleted file mode 100644
index 3925ab1..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskStartedEvent.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent following {@link LaunchTaskEvent} after the call to the system is made to
- * start the task.
- */
-public class LaunchTaskStartedEvent extends EventBus.AnimatedEvent {
-
-    public final TaskView taskView;
-    public final boolean screenPinningRequested;
-
-    public LaunchTaskStartedEvent(TaskView taskView, boolean screenPinningRequested) {
-        this.taskView = taskView;
-        this.screenPinningRequested = screenPinningRequested;
-    }
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskSucceededEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskSucceededEvent.java
deleted file mode 100644
index ec5089f..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/LaunchTaskSucceededEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when we successfully launch a task.
- */
-public class LaunchTaskSucceededEvent extends EventBus.Event {
-
-    public final int taskIndexFromStackFront;
-
-    public LaunchTaskSucceededEvent(int taskIndexFromStackFront) {
-        this.taskIndexFromStackFront = taskIndexFromStackFront;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/MultiWindowStateChangedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/MultiWindowStateChangedEvent.java
deleted file mode 100644
index 64eeafa..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/MultiWindowStateChangedEvent.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.model.TaskStack;
-
-/**
- * This is sent by the activity whenever the multi-window state has changed.
- */
-public class MultiWindowStateChangedEvent extends EventBus.AnimatedEvent {
-
-    public final boolean inMultiWindow;
-    // This flag is only used when undocking a task
-    public final boolean showDeferredAnimation;
-    public final TaskStack stack;
-
-    public MultiWindowStateChangedEvent(boolean inMultiWindow, boolean showDeferredAnimation,
-            TaskStack stack) {
-        this.inMultiWindow = inMultiWindow;
-        this.showDeferredAnimation = showDeferredAnimation;
-        this.stack = stack;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/PackagesChangedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/PackagesChangedEvent.java
deleted file mode 100644
index 47670e0..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/PackagesChangedEvent.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.views.TaskStackView;
-import com.android.systemui.recents.RecentsActivity;
-
-/**
- * This event is sent by {@link RecentsActivity} when a package on the the system changes.
- * {@link TaskStackView}s listen for this event, and remove the tasks associated with the removed
- * packages.
- */
-public class PackagesChangedEvent extends EventBus.Event {
-
-    public final String packageName;
-    public final int userId;
-
-    public PackagesChangedEvent(String packageName, int userId) {
-        this.packageName = packageName;
-        this.userId = userId;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/RecentsActivityStartingEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/RecentsActivityStartingEvent.java
deleted file mode 100644
index a2ecfe2..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/RecentsActivityStartingEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Called after recents activity is being started, i.e. startActivity has just been called.
- */
-public class RecentsActivityStartingEvent extends EventBus.Event{
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ShowEmptyViewEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ShowEmptyViewEvent.java
deleted file mode 100644
index 75bfd7b..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ShowEmptyViewEvent.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.systemui.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Sent when the stack should be hidden and the empty view shown.
- */
-public class ShowEmptyViewEvent extends EventBus.Event {
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ShowStackActionButtonEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ShowStackActionButtonEvent.java
deleted file mode 100644
index d81f89c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ShowStackActionButtonEvent.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the stack action view button should be shown.
- */
-public class ShowStackActionButtonEvent extends EventBus.Event {
-
-    // Whether or not to translate the stack action button when showing it
-    public final boolean translate;
-
-    public ShowStackActionButtonEvent(boolean translate) {
-        this.translate = translate;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/TaskStackUpdatedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/TaskStackUpdatedEvent.java
deleted file mode 100644
index 0d614e8c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/TaskStackUpdatedEvent.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.model.TaskStack;
-
-/**
- * This is sent by the activity whenever the task stach has changed.
- */
-public class TaskStackUpdatedEvent extends EventBus.AnimatedEvent {
-
-    /**
-     * A new TaskStack instance representing the latest stack state.
-     */
-    public final TaskStack stack;
-    public final boolean inMultiWindow;
-
-    public TaskStackUpdatedEvent(TaskStack stack, boolean inMultiWindow) {
-        this.stack = stack;
-        this.inMultiWindow = inMultiWindow;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ToggleRecentsEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ToggleRecentsEvent.java
deleted file mode 100644
index 49655b4..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/ToggleRecentsEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the user taps on the Overview button to toggle the Recents activity.
- */
-public class ToggleRecentsEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/UndockingTaskEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/UndockingTaskEvent.java
deleted file mode 100644
index d5083a8..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/activity/UndockingTaskEvent.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.activity;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Fires when the user invoked the gesture to undock the task in the docked stack.
- */
-public class UndockingTaskEvent extends EventBus.Event {
-
-    public UndockingTaskEvent() {
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ActivityPinnedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ActivityPinnedEvent.java
deleted file mode 100644
index f4d2fcf..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ActivityPinnedEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.systemui.recents.events.component;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when an activity is pinned.
- */
-public class ActivityPinnedEvent extends EventBus.Event {
-
-    public final int taskId;
-
-    public ActivityPinnedEvent(int taskId) {
-        this.taskId = taskId;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ActivityUnpinnedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ActivityUnpinnedEvent.java
deleted file mode 100644
index 48c5f0b..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ActivityUnpinnedEvent.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.systemui.recents.events.component;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when an activity is unpinned.
- */
-public class ActivityUnpinnedEvent extends EventBus.Event {
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ExpandPipEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ExpandPipEvent.java
deleted file mode 100644
index 37266f6..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ExpandPipEvent.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.systemui.recents.events.component;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the PiP should be expanded due to being relaunched.
- */
-public class ExpandPipEvent extends EventBus.Event {
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/HidePipMenuEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/HidePipMenuEvent.java
deleted file mode 100644
index ce4f207..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/HidePipMenuEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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.systemui.recents.events.component;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the PiP menu should be hidden.
- */
-public class HidePipMenuEvent extends EventBus.AnimatedEvent {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/RecentsVisibilityChangedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/RecentsVisibilityChangedEvent.java
deleted file mode 100644
index 8843eb4..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/RecentsVisibilityChangedEvent.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.component;
-
-import android.content.Context;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when the visibility of the RecentsActivity for the current user changes.  Handlers
- * of this event should not alter the UI, as the activity may still be visible.
- */
-public class RecentsVisibilityChangedEvent extends EventBus.Event {
-
-    public final Context applicationContext;
-    public final boolean visible;
-
-    public RecentsVisibilityChangedEvent(Context context, boolean visible) {
-        this.applicationContext = context.getApplicationContext();
-        this.visible = visible;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ScreenPinningRequestEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ScreenPinningRequestEvent.java
deleted file mode 100644
index d460917..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ScreenPinningRequestEvent.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.component;
-
-import android.content.Context;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when we want to start screen pinning.
- */
-public class ScreenPinningRequestEvent extends EventBus.Event {
-
-    public final Context applicationContext;
-    public final int taskId;
-
-    public ScreenPinningRequestEvent(Context context, int taskId) {
-        this.applicationContext = context.getApplicationContext();
-        this.taskId = taskId;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/SetWaitingForTransitionStartEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/SetWaitingForTransitionStartEvent.java
deleted file mode 100644
index d9cf5fb..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/SetWaitingForTransitionStartEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.systemui.recents.events.component;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when we are setting/resetting the flag to wait for the transition to start.
- */
-public class SetWaitingForTransitionStartEvent extends EventBus.Event {
-
-    public final boolean waitingForTransitionStart;
-
-    public SetWaitingForTransitionStartEvent(boolean waitingForTransitionStart) {
-        this.waitingForTransitionStart = waitingForTransitionStart;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ShowUserToastEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ShowUserToastEvent.java
deleted file mode 100644
index e2b39c3..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/component/ShowUserToastEvent.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.component;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when we want to show a toast for the current user.
- */
-public class ShowUserToastEvent extends EventBus.Event {
-
-    public final int msgResId;
-    public final int msgLength;
-
-    public ShowUserToastEvent(int msgResId, int msgLength) {
-        this.msgResId = msgResId;
-        this.msgLength = msgLength;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/AllTaskViewsDismissedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/AllTaskViewsDismissedEvent.java
deleted file mode 100644
index 0352161..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/AllTaskViewsDismissedEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent whenever all the task views in a stack have been dismissed.
- */
-public class AllTaskViewsDismissedEvent extends EventBus.Event {
-
-    public final int msgResId;
-
-    public AllTaskViewsDismissedEvent(int msgResId) {
-        this.msgResId = msgResId;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DeleteTaskDataEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DeleteTaskDataEvent.java
deleted file mode 100644
index b52e83b..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DeleteTaskDataEvent.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-
-/**
- * This is sent when the data associated with a given {@link Task} should be deleted from the
- * system.
- */
-public class DeleteTaskDataEvent extends EventBus.Event {
-
-    public final Task task;
-
-    public DeleteTaskDataEvent(Task task) {
-        this.task = task;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DismissAllTaskViewsEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DismissAllTaskViewsEvent.java
deleted file mode 100644
index f8b59c7..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DismissAllTaskViewsEvent.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent to request that all the {@link TaskView}s are dismissed.
- */
-public class DismissAllTaskViewsEvent extends EventBus.AnimatedEvent {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DismissTaskViewEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DismissTaskViewEvent.java
deleted file mode 100644
index 1f8c644..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DismissTaskViewEvent.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent to request that the given {@link TaskView} is dismissed.
- */
-public class DismissTaskViewEvent extends EventBus.AnimatedEvent {
-
-    public final TaskView taskView;
-
-    public DismissTaskViewEvent(TaskView taskView) {
-        this.taskView = taskView;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DraggingInRecentsEndedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DraggingInRecentsEndedEvent.java
deleted file mode 100644
index 9be8eb1..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DraggingInRecentsEndedEvent.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.android.systemui.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus.Event;
-
-/**
- * This event is sent when the user finished dragging in recents.
- */
-public class DraggingInRecentsEndedEvent extends Event {
-
-    public final float velocity;
-
-    public DraggingInRecentsEndedEvent(float velocity) {
-        this.velocity = velocity;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DraggingInRecentsEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DraggingInRecentsEvent.java
deleted file mode 100644
index 5e8bfd4..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/DraggingInRecentsEvent.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.android.systemui.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus.Event;
-
-/**
- * This event is sent when the user changed how far they are dragging in recents.
- */
-public class DraggingInRecentsEvent extends Event {
-
-    public final float distanceFromTop;
-
-    public DraggingInRecentsEvent(float distanceFromTop) {
-        this.distanceFromTop = distanceFromTop;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/HideIncompatibleAppOverlayEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/HideIncompatibleAppOverlayEvent.java
deleted file mode 100644
index d6ef636..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/HideIncompatibleAppOverlayEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when a user stops draggin an incompatible app task.
- */
-public class HideIncompatibleAppOverlayEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/RecentsDrawnEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/RecentsDrawnEvent.java
deleted file mode 100644
index 5483166..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/RecentsDrawnEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Fired when recents was launched and has drawn its first frame.
- */
-public class RecentsDrawnEvent extends EventBus.Event {
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/RecentsGrowingEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/RecentsGrowingEvent.java
deleted file mode 100644
index d9b0027..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/RecentsGrowingEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Sent when recents is about to grow in multi-window mode when entering recents.
- */
-public class RecentsGrowingEvent extends EventBus.Event {
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/ShowApplicationInfoEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/ShowApplicationInfoEvent.java
deleted file mode 100644
index da19384..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/ShowApplicationInfoEvent.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-
-/**
- * This is sent when a user wants to show the application info for a {@link Task}.
- */
-public class ShowApplicationInfoEvent extends EventBus.Event {
-
-    public final Task task;
-
-    public ShowApplicationInfoEvent(Task task) {
-        this.task = task;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/ShowIncompatibleAppOverlayEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/ShowIncompatibleAppOverlayEvent.java
deleted file mode 100644
index 3a4350e..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/ShowIncompatibleAppOverlayEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent when a user starts dragging an incompatible app task.
- */
-public class ShowIncompatibleAppOverlayEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/StackViewScrolledEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/StackViewScrolledEvent.java
deleted file mode 100644
index c4b47c0..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/StackViewScrolledEvent.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui;
-
-import android.util.MutableInt;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent whenever a new scroll gesture happens on a stack view.
- */
-public class StackViewScrolledEvent extends EventBus.ReusableEvent {
-
-    public final MutableInt yMovement;
-
-    public StackViewScrolledEvent() {
-        yMovement = new MutableInt(0);
-    }
-
-    public void updateY(int y) {
-        yMovement.value = y;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/TaskSnapshotChangedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/TaskSnapshotChangedEvent.java
deleted file mode 100644
index f082928..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/TaskSnapshotChangedEvent.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.systemui.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-
-/**
- * Sent when a task snapshot has changed.
- */
-public class TaskSnapshotChangedEvent extends EventBus.Event {
-
-    public final int taskId;
-    public final ThumbnailData thumbnailData;
-
-    public TaskSnapshotChangedEvent(int taskId, ThumbnailData thumbnailData) {
-        this.taskId = taskId;
-        this.thumbnailData = thumbnailData;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/TaskViewDismissedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/TaskViewDismissedEvent.java
deleted file mode 100644
index 9738124..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/TaskViewDismissedEvent.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.utilities.AnimationProps;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent when a {@link TaskView} has been dismissed and is no longer visible.
- */
-public class TaskViewDismissedEvent extends EventBus.Event {
-
-    public final Task task;
-    public final TaskView taskView;
-    public final AnimationProps animation;
-
-    public TaskViewDismissedEvent(Task task, TaskView taskView, AnimationProps animation) {
-        this.task = task;
-        this.taskView = taskView;
-        this.animation = animation;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/UserInteractionEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/UserInteractionEvent.java
deleted file mode 100644
index 39e4c1d..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/UserInteractionEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent whenever the user interacts with the activity.
- */
-public class UserInteractionEvent extends EventBus.ReusableEvent {
-    // Simple Event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragDropTargetChangedEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragDropTargetChangedEvent.java
deleted file mode 100644
index cf61b1e..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragDropTargetChangedEvent.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui.dragndrop;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.views.DropTarget;
-
-/**
- * This event is sent when a user drags in/out of a drop target.
- */
-public class DragDropTargetChangedEvent extends EventBus.AnimatedEvent {
-
-    // The task that is currently being dragged
-    public final Task task;
-    public final DropTarget dropTarget;
-
-    public DragDropTargetChangedEvent(Task task, DropTarget dropTarget) {
-        this.task = task;
-        this.dropTarget = dropTarget;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragEndCancelledEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragEndCancelledEvent.java
deleted file mode 100644
index c11936e..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragEndCancelledEvent.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.events.ui.dragndrop;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent whenever a drag end is cancelled because of an error.
- */
-public class DragEndCancelledEvent extends EventBus.AnimatedEvent {
-
-    public final TaskStack stack;
-    public final Task task;
-    public final TaskView taskView;
-
-    public DragEndCancelledEvent(TaskStack stack, Task task, TaskView taskView) {
-        this.stack = stack;
-        this.task = task;
-        this.taskView = taskView;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragEndEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragEndEvent.java
deleted file mode 100644
index 73cbde9..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragEndEvent.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui.dragndrop;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.views.DropTarget;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent whenever a drag ends.
- */
-public class DragEndEvent extends EventBus.AnimatedEvent {
-
-    public final Task task;
-    public final TaskView taskView;
-    public final DropTarget dropTarget;
-
-    public DragEndEvent(Task task, TaskView taskView, DropTarget dropTarget) {
-        this.task = task;
-        this.taskView = taskView;
-        this.dropTarget = dropTarget;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragStartEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragStartEvent.java
deleted file mode 100644
index 021be77..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragStartEvent.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui.dragndrop;
-
-import android.graphics.Point;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent whenever a drag starts.
- */
-public class DragStartEvent extends EventBus.Event {
-
-    public final Task task;
-    public final TaskView taskView;
-    public final Point tlOffset;
-    public final boolean isUserTouchInitiated;
-
-    public DragStartEvent(Task task, TaskView taskView, Point tlOffset) {
-        this(task, taskView, tlOffset, true);
-    }
-
-    public DragStartEvent(Task task, TaskView taskView, Point tlOffset,
-            boolean isUserTouchInitiated) {
-        this.task = task;
-        this.taskView = taskView;
-        this.tlOffset = tlOffset;
-        this.isUserTouchInitiated = isUserTouchInitiated;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragStartInitializeDropTargetsEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragStartInitializeDropTargetsEvent.java
deleted file mode 100644
index 64ba574..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/dragndrop/DragStartInitializeDropTargetsEvent.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui.dragndrop;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.views.RecentsViewTouchHandler;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent by the drag manager when it requires drop targets to register themselves for
- * the current drag gesture.
- */
-public class DragStartInitializeDropTargetsEvent extends EventBus.Event {
-
-    public final Task task;
-    public final TaskView taskView;
-    public final RecentsViewTouchHandler handler;
-
-    public DragStartInitializeDropTargetsEvent(Task task, TaskView taskView,
-            RecentsViewTouchHandler handler) {
-        this.task = task;
-        this.taskView = taskView;
-        this.handler = handler;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/DismissFocusedTaskViewEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/DismissFocusedTaskViewEvent.java
deleted file mode 100644
index df74018..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/DismissFocusedTaskViewEvent.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui.focus;
-
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.views.TaskView;
-
-/**
- * This event is sent to request that the currently focused {@link TaskView} is dismissed.
- */
-public class DismissFocusedTaskViewEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/FocusNextTaskViewEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/FocusNextTaskViewEvent.java
deleted file mode 100644
index 171ab5e..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/FocusNextTaskViewEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui.focus;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Focuses the next task view in the stack.
- */
-public class FocusNextTaskViewEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/FocusPreviousTaskViewEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/FocusPreviousTaskViewEvent.java
deleted file mode 100644
index 22469e7..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/FocusPreviousTaskViewEvent.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.events.ui.focus;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Focuses the previous task view in the stack.
- */
-public class FocusPreviousTaskViewEvent extends EventBus.Event {
-    // Simple event
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/NavigateTaskViewEvent.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/NavigateTaskViewEvent.java
deleted file mode 100644
index 5508d26..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/events/ui/focus/NavigateTaskViewEvent.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.systemui.recents.events.ui.focus;
-
-import android.view.KeyEvent;
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * Navigates the task view by arrow keys.
- */
-public class NavigateTaskViewEvent extends EventBus.Event {
-    public enum Direction {
-        UNDEFINED, UP, DOWN, LEFT, RIGHT;
-    }
-
-    public Direction direction;
-    public NavigateTaskViewEvent(Direction direction) {
-        this.direction = direction;
-    }
-
-    public static Direction getDirectionFromKeyCode(int keyCode) {
-        switch (keyCode) {
-            case KeyEvent.KEYCODE_DPAD_UP:
-                return Direction.UP;
-            case KeyEvent.KEYCODE_DPAD_DOWN:
-                return Direction.DOWN;
-            case KeyEvent.KEYCODE_DPAD_LEFT:
-                return Direction.LEFT;
-            case KeyEvent.KEYCODE_DPAD_RIGHT:
-                return Direction.RIGHT;
-            default:
-                return Direction.UNDEFINED;
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/DozeTrigger.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/DozeTrigger.java
deleted file mode 100644
index 574ea03..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/DozeTrigger.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.misc;
-
-import android.os.Handler;
-import android.view.ViewDebug;
-
-/**
- * A dozer is a class that fires a trigger after it falls asleep.
- * You can occasionally poke the trigger to wake it up, but it will fall asleep if left untouched.
- */
-public class DozeTrigger {
-
-    Handler mHandler;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    boolean mIsDozing;
-    @ViewDebug.ExportedProperty(category="recents")
-    boolean mIsAsleep;
-    @ViewDebug.ExportedProperty(category="recents")
-    int mDozeDurationMilliseconds;
-    Runnable mOnSleepRunnable;
-
-    // Sleep-runnable
-    Runnable mDozeRunnable = new Runnable() {
-        @Override
-        public void run() {
-            mIsDozing = false;
-            mIsAsleep = true;
-            mOnSleepRunnable.run();
-        }
-    };
-
-    public DozeTrigger(int dozeDurationMilliseconds, Runnable onSleepRunnable) {
-        mHandler = new Handler();
-        mDozeDurationMilliseconds = dozeDurationMilliseconds;
-        mOnSleepRunnable = onSleepRunnable;
-    }
-
-    /**
-     * Starts dozing and queues the onSleepRunnable to be called. This also resets the trigger flag.
-     */
-    public void startDozing() {
-        forcePoke();
-        mIsAsleep = false;
-    }
-
-    /**
-     * Stops dozing and prevents the onSleepRunnable from being called.
-     */
-    public void stopDozing() {
-        mHandler.removeCallbacks(mDozeRunnable);
-        mIsDozing = false;
-        mIsAsleep = false;
-    }
-
-    /**
-     * Updates the duration that we have to wait until dozing triggers.
-     */
-    public void setDozeDuration(int duration) {
-        mDozeDurationMilliseconds = duration;
-    }
-
-    /**
-     * Poke this dozer to wake it up if it is dozing, delaying the onSleepRunnable from being
-     * called for a for the doze duration.
-     */
-    public void poke() {
-        if (mIsDozing) {
-            forcePoke();
-        }
-    }
-
-    /**
-     * Poke this dozer to wake it up even if it is not currently dozing.
-     */
-    void forcePoke() {
-        mHandler.removeCallbacks(mDozeRunnable);
-        mHandler.postDelayed(mDozeRunnable, mDozeDurationMilliseconds);
-        mIsDozing = true;
-    }
-
-    /** Returns whether we are dozing or not. */
-    public boolean isDozing() {
-        return mIsDozing;
-    }
-
-    /** Returns whether the trigger has fired at least once. */
-    public boolean isAsleep() {
-        return mIsAsleep;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/FreePathInterpolator.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/FreePathInterpolator.java
deleted file mode 100644
index 720c952..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/FreePathInterpolator.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.misc;
-
-import android.graphics.Path;
-import android.view.animation.BaseInterpolator;
-import android.view.animation.Interpolator;
-
-/**
- * An interpolator that can traverse a Path. The x coordinate along the <code>Path</code>
- * is the input value and the output is the y coordinate of the line at that point.
- * This means that the Path must conform to a function <code>y = f(x)</code>.
- *
- * <p>The <code>Path</code> must not have gaps in the x direction and must not
- * loop back on itself such that there can be two points sharing the same x coordinate.
- * It is alright to have a disjoint line in the vertical direction:</p>
- * <p><blockquote><pre>
- *     Path path = new Path();
- *     path.lineTo(0.25f, 0.25f);
- *     path.moveTo(0.25f, 0.5f);
- *     path.lineTo(1f, 1f);
- * </pre></blockquote></p>
- */
-public class FreePathInterpolator extends BaseInterpolator {
-
-    // This governs how accurate the approximation of the Path is.
-    private static final float PRECISION = 0.002f;
-
-    private float[] mX;
-    private float[] mY;
-    private float mArcLength;
-
-    /**
-     * Create an interpolator for an arbitrary <code>Path</code>.
-     *
-     * @param path The <code>Path</code> to use to make the line representing the interpolator.
-     */
-    public FreePathInterpolator(Path path) {
-        initPath(path);
-    }
-
-    private void initPath(Path path) {
-        float[] pointComponents = path.approximate(PRECISION);
-
-        int numPoints = pointComponents.length / 3;
-
-        mX = new float[numPoints];
-        mY = new float[numPoints];
-        mArcLength = 0;
-        float prevX = 0;
-        float prevY = 0;
-        float prevFraction = 0;
-        int componentIndex = 0;
-        for (int i = 0; i < numPoints; i++) {
-            float fraction = pointComponents[componentIndex++];
-            float x = pointComponents[componentIndex++];
-            float y = pointComponents[componentIndex++];
-            if (fraction == prevFraction && x != prevX) {
-                throw new IllegalArgumentException(
-                        "The Path cannot have discontinuity in the X axis.");
-            }
-            if (x < prevX) {
-                throw new IllegalArgumentException("The Path cannot loop back on itself.");
-            }
-            mX[i] = x;
-            mY[i] = y;
-            mArcLength += Math.hypot(x - prevX, y - prevY);
-            prevX = x;
-            prevY = y;
-            prevFraction = fraction;
-        }
-    }
-
-    /**
-     * Using the line in the Path in this interpolator that can be described as
-     * <code>y = f(x)</code>, finds the y coordinate of the line given <code>t</code>
-     * as the x coordinate.
-     *
-     * @param t Treated as the x coordinate along the line.
-     * @return The y coordinate of the Path along the line where x = <code>t</code>.
-     * @see Interpolator#getInterpolation(float)
-     */
-    @Override
-    public float getInterpolation(float t) {
-        int startIndex = 0;
-        int endIndex = mX.length - 1;
-
-        // Return early if out of bounds
-        if (t <= 0) {
-            return mY[startIndex];
-        } else if (t >= 1) {
-            return mY[endIndex];
-        }
-
-        // Do a binary search for the correct x to interpolate between.
-        while (endIndex - startIndex > 1) {
-            int midIndex = (startIndex + endIndex) / 2;
-            if (t < mX[midIndex]) {
-                endIndex = midIndex;
-            } else {
-                startIndex = midIndex;
-            }
-        }
-
-        float xRange = mX[endIndex] - mX[startIndex];
-        if (xRange == 0) {
-            return mY[startIndex];
-        }
-
-        float tInRange = t - mX[startIndex];
-        float fraction = tInRange / xRange;
-
-        float startY = mY[startIndex];
-        float endY = mY[endIndex];
-        return startY + (fraction * (endY - startY));
-    }
-
-    /**
-     * Finds the x that provides the given <code>y = f(x)</code>.
-     *
-     * @param y a value from (0,1) that is in this path.
-     */
-    public float getX(float y) {
-        int startIndex = 0;
-        int endIndex = mY.length - 1;
-
-        // Return early if out of bounds
-        if (y <= 0) {
-            return mX[endIndex];
-        } else if (y >= 1) {
-            return mX[startIndex];
-        }
-
-        // Do a binary search for index that bounds the y
-        while (endIndex - startIndex > 1) {
-            int midIndex = (startIndex + endIndex) / 2;
-            if (y < mY[midIndex]) {
-                startIndex = midIndex;
-            } else {
-                endIndex = midIndex;
-            }
-        }
-
-        float yRange = mY[endIndex] - mY[startIndex];
-        if (yRange == 0) {
-            return mX[startIndex];
-        }
-
-        float tInRange = y - mY[startIndex];
-        float fraction = tInRange / yRange;
-
-        float startX = mX[startIndex];
-        float endX = mX[endIndex];
-        return startX + (fraction * (endX - startX));
-    }
-
-    /**
-     * Returns the arclength of the path we are interpolating.
-     */
-    public float getArcLength() {
-        return mArcLength;
-    }
-}
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/ReferenceCountedTrigger.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/ReferenceCountedTrigger.java
deleted file mode 100644
index 2637d88..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/ReferenceCountedTrigger.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.misc;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-
-import java.util.ArrayList;
-
-/**
- * A ref counted trigger that does some logic when the count is first incremented, or last
- * decremented.  Not thread safe as it's not currently needed.
- */
-public class ReferenceCountedTrigger {
-
-    int mCount;
-    ArrayList<Runnable> mFirstIncRunnables = new ArrayList<>();
-    ArrayList<Runnable> mLastDecRunnables = new ArrayList<>();
-    Runnable mErrorRunnable;
-
-    // Convenience runnables
-    Runnable mIncrementRunnable = new Runnable() {
-        @Override
-        public void run() {
-            increment();
-        }
-    };
-    Runnable mDecrementRunnable = new Runnable() {
-        @Override
-        public void run() {
-            decrement();
-        }
-    };
-
-    public ReferenceCountedTrigger() {
-        this(null, null, null);
-    }
-
-    public ReferenceCountedTrigger(Runnable firstIncRunnable, Runnable lastDecRunnable,
-            Runnable errorRunanable) {
-        if (firstIncRunnable != null) mFirstIncRunnables.add(firstIncRunnable);
-        if (lastDecRunnable != null) mLastDecRunnables.add(lastDecRunnable);
-        mErrorRunnable = errorRunanable;
-    }
-
-    /** Increments the ref count */
-    public void increment() {
-        if (mCount == 0 && !mFirstIncRunnables.isEmpty()) {
-            int numRunnables = mFirstIncRunnables.size();
-            for (int i = 0; i < numRunnables; i++) {
-                mFirstIncRunnables.get(i).run();
-            }
-        }
-        mCount++;
-    }
-
-    /** Convenience method to increment this trigger as a runnable */
-    public Runnable incrementAsRunnable() {
-        return mIncrementRunnable;
-    }
-
-    /** Adds a runnable to the last-decrement runnables list. */
-    public void addLastDecrementRunnable(Runnable r) {
-        mLastDecRunnables.add(r);
-    }
-
-    /** Decrements the ref count */
-    public void decrement() {
-        mCount--;
-        if (mCount == 0) {
-            flushLastDecrementRunnables();
-        } else if (mCount < 0) {
-            if (mErrorRunnable != null) {
-                mErrorRunnable.run();
-            } else {
-                throw new RuntimeException("Invalid ref count");
-            }
-        }
-    }
-
-    /**
-     * Runs and clears all the last-decrement runnables now.
-     */
-    public void flushLastDecrementRunnables() {
-        if (!mLastDecRunnables.isEmpty()) {
-            int numRunnables = mLastDecRunnables.size();
-            for (int i = 0; i < numRunnables; i++) {
-                mLastDecRunnables.get(i).run();
-            }
-        }
-        mLastDecRunnables.clear();
-    }
-
-    /**
-     * Convenience method to decrement this trigger as a animator listener.  This listener is
-     * guarded to prevent being called back multiple times, and will trigger a decrement once and
-     * only once.
-     */
-    public Animator.AnimatorListener decrementOnAnimationEnd() {
-        return new AnimatorListenerAdapter() {
-            private boolean hasEnded;
-
-            @Override
-            public void onAnimationEnd(Animator animation) {
-                if (hasEnded) return;
-                decrement();
-                hasEnded = true;
-            }
-        };
-    }
-
-    /** Returns the current ref count */
-    public int getCount() {
-        return mCount;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/SysUiTaskStackChangeListener.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/SysUiTaskStackChangeListener.java
deleted file mode 100644
index 5d7f1ba..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/SysUiTaskStackChangeListener.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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.systemui.recents.misc;
-
-import android.content.Context;
-
-import com.android.systemui.shared.system.TaskStackChangeListener;
-
-/**
- * An implementation of {@link TaskStackChangeListener}.
- */
-public abstract class SysUiTaskStackChangeListener extends TaskStackChangeListener {
-
-    /**
-     * Checks that the current user matches the user's SystemUI process.
-     */
-    protected final boolean checkCurrentUserId(Context context, boolean debug) {
-        int currentUserId = SystemServicesProxy.getInstance(context).getCurrentUser();
-        return checkCurrentUserId(currentUserId, debug);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/SystemServicesProxy.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/SystemServicesProxy.java
deleted file mode 100644
index 44354bc1..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/misc/SystemServicesProxy.java
+++ /dev/null
@@ -1,535 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.misc;
-
-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_FULLSCREEN;
-import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
-import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
-import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
-
-import android.app.ActivityManager;
-import android.app.ActivityManager.StackInfo;
-import android.app.ActivityOptions;
-import android.app.ActivityTaskManager;
-import android.app.AppGlobals;
-import android.app.IActivityManager;
-import android.app.IActivityTaskManager;
-import android.app.WindowConfiguration;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.IPackageManager;
-import android.content.pm.PackageManager;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.graphics.Point;
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuffXfermode;
-import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.service.dreams.DreamService;
-import android.service.dreams.IDreamManager;
-import android.util.Log;
-import android.util.MutableBoolean;
-import android.view.Display;
-import android.view.IDockedStackListener;
-import android.view.IWindowManager;
-import android.view.WindowManager;
-import android.view.WindowManager.KeyboardShortcutsReceiver;
-import android.view.WindowManagerGlobal;
-import android.view.accessibility.AccessibilityManager;
-
-import com.android.internal.app.AssistUtils;
-import com.android.internal.os.BackgroundThread;
-import com.android.systemui.Dependency;
-import com.android.systemui.UiOffloadThread;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsImpl;
-import com.android.systemui.statusbar.policy.UserInfoController;
-
-import java.util.List;
-
-/**
- * Acts as a shim around the real system services that we need to access data from, and provides
- * a point of injection when testing UI.
- */
-public class SystemServicesProxy {
-    final static String TAG = "SystemServicesProxy";
-
-    final static BitmapFactory.Options sBitmapOptions;
-    static {
-        sBitmapOptions = new BitmapFactory.Options();
-        sBitmapOptions.inMutable = true;
-        sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
-    }
-
-    private static SystemServicesProxy sSystemServicesProxy;
-
-    AccessibilityManager mAccm;
-    ActivityManager mAm;
-    IActivityManager mIam;
-    IActivityTaskManager mIatm;
-    PackageManager mPm;
-    IPackageManager mIpm;
-    private final IDreamManager mDreamManager;
-    private final Context mContext;
-    AssistUtils mAssistUtils;
-    WindowManager mWm;
-    IWindowManager mIwm;
-    UserManager mUm;
-    Display mDisplay;
-    String mRecentsPackage;
-    private int mCurrentUserId;
-
-    boolean mIsSafeMode;
-
-    int mDummyThumbnailWidth;
-    int mDummyThumbnailHeight;
-    Paint mBgProtectionPaint;
-    Canvas mBgProtectionCanvas;
-
-    private final Runnable mGcRunnable = new Runnable() {
-        @Override
-        public void run() {
-            System.gc();
-            System.runFinalization();
-        }
-    };
-
-    private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class);
-
-    private final UserInfoController.OnUserInfoChangedListener mOnUserInfoChangedListener =
-            (String name, Drawable picture, String userAccount) ->
-                    mCurrentUserId = mAm.getCurrentUser();
-
-    /** Private constructor */
-    private SystemServicesProxy(Context context) {
-        mContext = context.getApplicationContext();
-        mAccm = AccessibilityManager.getInstance(context);
-        mAm = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
-        mIam = ActivityManager.getService();
-        mIatm = ActivityTaskManager.getService();
-        mPm = context.getPackageManager();
-        mIpm = AppGlobals.getPackageManager();
-        mAssistUtils = new AssistUtils(context);
-        mWm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
-        mIwm = WindowManagerGlobal.getWindowManagerService();
-        mUm = UserManager.get(context);
-        mDreamManager = IDreamManager.Stub.asInterface(
-                ServiceManager.checkService(DreamService.DREAM_SERVICE));
-        mDisplay = mWm.getDefaultDisplay();
-        mRecentsPackage = context.getPackageName();
-        mIsSafeMode = mPm.isSafeMode();
-        mCurrentUserId = mAm.getCurrentUser();
-
-        // Get the dummy thumbnail width/heights
-        Resources res = context.getResources();
-        int wId = com.android.internal.R.dimen.thumbnail_width;
-        int hId = com.android.internal.R.dimen.thumbnail_height;
-        mDummyThumbnailWidth = res.getDimensionPixelSize(wId);
-        mDummyThumbnailHeight = res.getDimensionPixelSize(hId);
-
-        // Create the protection paints
-        mBgProtectionPaint = new Paint();
-        mBgProtectionPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));
-        mBgProtectionPaint.setColor(0xFFffffff);
-        mBgProtectionCanvas = new Canvas();
-
-        // Since SystemServicesProxy can be accessed from a per-SysUI process component, create a
-        // per-process listener to keep track of the current user id to reduce the number of binder
-        // calls to fetch it.
-        UserInfoController userInfoController = Dependency.get(UserInfoController.class);
-        userInfoController.addCallback(mOnUserInfoChangedListener);
-    }
-
-    /**
-     * Returns the single instance of the {@link SystemServicesProxy}.
-     * This should only be called on the main thread.
-     */
-    public static synchronized SystemServicesProxy getInstance(Context context) {
-        if (sSystemServicesProxy == null) {
-            sSystemServicesProxy = new SystemServicesProxy(context);
-        }
-        return sSystemServicesProxy;
-    }
-
-    /**
-     * Requests a gc() from the background thread.
-     */
-    public void gc() {
-        BackgroundThread.getHandler().post(mGcRunnable);
-    }
-
-    /**
-     * Returns whether the recents activity is currently visible.
-     */
-    public boolean isRecentsActivityVisible() {
-        return isRecentsActivityVisible(null);
-    }
-
-    /**
-     * Returns whether the recents activity is currently visible.
-     *
-     * @param isHomeStackVisible if provided, will return whether the home stack is visible
-     *                           regardless of the recents visibility
-     *
-     * TODO(winsonc): Refactor this check to just use the recents activity lifecycle
-     */
-    public boolean isRecentsActivityVisible(MutableBoolean isHomeStackVisible) {
-        if (mIam == null) return false;
-
-        try {
-            List<StackInfo> stackInfos = mIatm.getAllStackInfos();
-            ActivityManager.StackInfo homeStackInfo = null;
-            ActivityManager.StackInfo fullscreenStackInfo = null;
-            ActivityManager.StackInfo recentsStackInfo = null;
-            for (int i = 0; i < stackInfos.size(); i++) {
-                final StackInfo stackInfo = stackInfos.get(i);
-                final WindowConfiguration winConfig = stackInfo.configuration.windowConfiguration;
-                final int activityType = winConfig.getActivityType();
-                final int windowingMode = winConfig.getWindowingMode();
-                if (homeStackInfo == null && activityType == ACTIVITY_TYPE_HOME) {
-                    homeStackInfo = stackInfo;
-                } else if (fullscreenStackInfo == null && activityType == ACTIVITY_TYPE_STANDARD
-                        && (windowingMode == WINDOWING_MODE_FULLSCREEN
-                            || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY)) {
-                    fullscreenStackInfo = stackInfo;
-                } else if (recentsStackInfo == null && activityType == ACTIVITY_TYPE_RECENTS) {
-                    recentsStackInfo = stackInfo;
-                }
-            }
-            boolean homeStackVisibleNotOccluded = isStackNotOccluded(homeStackInfo,
-                    fullscreenStackInfo);
-            boolean recentsStackVisibleNotOccluded = isStackNotOccluded(recentsStackInfo,
-                    fullscreenStackInfo);
-            if (isHomeStackVisible != null) {
-                isHomeStackVisible.value = homeStackVisibleNotOccluded;
-            }
-            ComponentName topActivity = recentsStackInfo != null ?
-                    recentsStackInfo.topActivity : null;
-            return (recentsStackVisibleNotOccluded && topActivity != null
-                    && topActivity.getPackageName().equals(RecentsImpl.RECENTS_PACKAGE)
-                    && LegacyRecentsImpl.RECENTS_ACTIVITIES.contains(topActivity.getClassName()));
-        } catch (RemoteException e) {
-            e.printStackTrace();
-        }
-        return false;
-    }
-
-    private boolean isStackNotOccluded(ActivityManager.StackInfo stackInfo,
-            ActivityManager.StackInfo fullscreenStackInfo) {
-        boolean stackVisibleNotOccluded = stackInfo == null || stackInfo.visible;
-        if (fullscreenStackInfo != null && stackInfo != null) {
-            boolean isFullscreenStackOccludingg = fullscreenStackInfo.visible &&
-                    fullscreenStackInfo.position > stackInfo.position;
-            stackVisibleNotOccluded &= !isFullscreenStackOccludingg;
-        }
-        return stackVisibleNotOccluded;
-    }
-
-    /**
-     * Returns whether this device is in the safe mode.
-     */
-    public boolean isInSafeMode() {
-        return mIsSafeMode;
-    }
-
-    /** Moves an already resumed task to the side of the screen to initiate split screen. */
-    public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
-            Rect initialBounds) {
-        if (mIatm == null) {
-            return false;
-        }
-
-        try {
-            return mIatm.setTaskWindowingModeSplitScreenPrimary(taskId, createMode,
-                    true /* onTop */, false /* animate */, initialBounds, true /* showRecents */);
-        } catch (RemoteException e) {
-            e.printStackTrace();
-        }
-        return false;
-    }
-
-    public ActivityManager.StackInfo getSplitScreenPrimaryStack() {
-        try {
-            return mIatm.getStackInfo(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_UNDEFINED);
-        } catch (RemoteException e) {
-            return null;
-        }
-    }
-
-    /**
-     * @return whether there are any docked tasks for the current user.
-     */
-    public boolean hasDockedTask() {
-        if (mIam == null) return false;
-
-        ActivityManager.StackInfo stackInfo = getSplitScreenPrimaryStack();
-        if (stackInfo != null) {
-            int userId = getCurrentUser();
-            boolean hasUserTask = false;
-            for (int i = stackInfo.taskUserIds.length - 1; i >= 0 && !hasUserTask; i--) {
-                hasUserTask = (stackInfo.taskUserIds[i] == userId);
-            }
-            return hasUserTask;
-        }
-        return false;
-    }
-
-    /**
-     * Returns whether there is a soft nav bar on specified display.
-     *
-     * @param displayId the id of display to check if there is a software navigation bar.
-     */
-    public boolean hasSoftNavigationBar(int displayId) {
-        try {
-            return mIwm.hasNavigationBar(displayId);
-        } catch (RemoteException e) {
-            e.printStackTrace();
-        }
-        return false;
-    }
-
-    /**
-     * Returns whether the device has a transposed nav bar (on the right of the screen) in the
-     * current display orientation.
-     */
-    public boolean hasTransposedNavigationBar() {
-        Rect insets = new Rect();
-        getStableInsets(insets);
-        return insets.right > 0;
-    }
-
-    /** Set the task's windowing mode. */
-    public void setTaskWindowingMode(int taskId, int windowingMode) {
-        if (mIatm == null) return;
-
-        try {
-            mIatm.setTaskWindowingMode(taskId, windowingMode, false /* onTop */);
-        } catch (RemoteException | IllegalArgumentException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Returns whether the provided {@param userId} represents the system user.
-     */
-    public boolean isSystemUser(int userId) {
-        return userId == UserHandle.USER_SYSTEM;
-    }
-
-    /**
-     * Returns the current user id.  Used instead of KeyguardUpdateMonitor in SystemUI components
-     * that run in the non-primary SystemUI process.
-     */
-    public int getCurrentUser() {
-        return mCurrentUserId;
-    }
-
-    /**
-     * Returns the processes user id.
-     */
-    public int getProcessUser() {
-        if (mUm == null) return 0;
-        return mUm.getUserHandle();
-    }
-
-    /**
-     * Returns whether touch exploration is currently enabled.
-     */
-    public boolean isTouchExplorationEnabled() {
-        if (mAccm == null) return false;
-
-        return mAccm.isEnabled() && mAccm.isTouchExplorationEnabled();
-    }
-
-    /**
-     * Returns whether the current task is in screen-pinning mode.
-     */
-    public boolean isScreenPinningActive() {
-        if (mIam == null) return false;
-
-        try {
-            return mIatm.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_PINNED;
-        } catch (RemoteException e) {
-            return false;
-        }
-    }
-
-    /**
-     * Returns the smallest width/height.
-     */
-    public int getDeviceSmallestWidth() {
-        if (mDisplay == null) return 0;
-
-        Point smallestSizeRange = new Point();
-        Point largestSizeRange = new Point();
-        mDisplay.getCurrentSizeRange(smallestSizeRange, largestSizeRange);
-        return smallestSizeRange.x;
-    }
-
-    /**
-     * Returns the current display rect in the current display orientation.
-     */
-    public Rect getDisplayRect() {
-        Rect displayRect = new Rect();
-        if (mDisplay == null) return displayRect;
-
-        Point p = new Point();
-        mDisplay.getRealSize(p);
-        displayRect.set(0, 0, p.x, p.y);
-        return displayRect;
-    }
-
-    /**
-     * Returns the window rect for the RecentsActivity, based on the dimensions of the recents stack
-     */
-    public Rect getWindowRect() {
-        Rect windowRect = new Rect();
-        if (mIam == null) return windowRect;
-
-        try {
-            // Use the recents stack bounds, fallback to fullscreen stack if it is null
-            ActivityManager.StackInfo stackInfo =
-                    mIatm.getStackInfo(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_RECENTS);
-            if (stackInfo == null) {
-                stackInfo = mIatm.getStackInfo(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-            }
-            if (stackInfo != null) {
-                windowRect.set(stackInfo.bounds);
-            }
-        } catch (RemoteException e) {
-            e.printStackTrace();
-        } finally {
-            return windowRect;
-        }
-    }
-
-    public void startActivityAsUserAsync(Intent intent, ActivityOptions opts) {
-        mUiOffloadThread.submit(() -> mContext.startActivityAsUser(intent,
-                opts != null ? opts.toBundle() : null, UserHandle.CURRENT));
-    }
-
-    /** Starts an in-place animation on the front most application windows. */
-    public void startInPlaceAnimationOnFrontMostApplication(ActivityOptions opts) {
-        if (mIam == null) return;
-
-        try {
-            mIatm.startInPlaceAnimationOnFrontMostApplication(
-                    opts == null ? null : opts.toBundle());
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void registerDockedStackListener(IDockedStackListener listener) {
-        if (mWm == null) return;
-
-        try {
-            mIwm.registerDockedStackListener(listener);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Calculates the size of the dock divider in the current orientation.
-     */
-    public int getDockedDividerSize(Context context) {
-        Resources res = context.getResources();
-        int dividerWindowWidth = res.getDimensionPixelSize(
-                com.android.internal.R.dimen.docked_stack_divider_thickness);
-        int dividerInsets = res.getDimensionPixelSize(
-                com.android.internal.R.dimen.docked_stack_divider_insets);
-        return dividerWindowWidth - 2 * dividerInsets;
-    }
-
-    public void requestKeyboardShortcuts(
-            Context context, KeyboardShortcutsReceiver receiver, int deviceId) {
-        mWm.requestAppKeyboardShortcuts(receiver, deviceId);
-    }
-
-    public void getStableInsets(Rect outStableInsets) {
-        if (mWm == null) return;
-
-        try {
-            mIwm.getStableInsets(Display.DEFAULT_DISPLAY, outStableInsets);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Updates the visibility of recents.
-     */
-    public void setRecentsVisibility(final boolean visible) {
-        mUiOffloadThread.submit(() -> {
-            try {
-                mIwm.setRecentsVisibility(visible);
-            } catch (RemoteException e) {
-                Log.e(TAG, "Unable to reach window manager", e);
-            }
-        });
-    }
-
-    /**
-     * Updates the visibility of the picture-in-picture.
-     */
-    public void setPipVisibility(final boolean visible) {
-        mUiOffloadThread.submit(() -> {
-            try {
-                mIwm.setPipVisibility(visible);
-            } catch (RemoteException e) {
-                Log.e(TAG, "Unable to reach window manager", e);
-            }
-        });
-    }
-
-    public boolean isDreaming() {
-        try {
-            return mDreamManager.isDreaming();
-        } catch (RemoteException e) {
-            Log.e(TAG, "Failed to query dream manager.", e);
-        }
-        return false;
-    }
-
-    public void awakenDreamsAsync() {
-        mUiOffloadThread.submit(() -> {
-            try {
-                mDreamManager.awaken();
-            } catch (RemoteException e) {
-                e.printStackTrace();
-            }
-        });
-    }
-
-    public interface StartActivityFromRecentsResultListener {
-        void onStartActivityResult(boolean succeeded);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/BackgroundTaskLoader.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/BackgroundTaskLoader.java
deleted file mode 100644
index e85a7fb..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/BackgroundTaskLoader.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * 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.systemui.recents.model;
-
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.util.Log;
-
-import com.android.systemui.shared.recents.model.IconLoader;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-
-/**
- * Background task resource loader
- */
-class BackgroundTaskLoader implements Runnable {
-    static String TAG = "BackgroundTaskLoader";
-    static boolean DEBUG = false;
-
-    private Context mContext;
-    private final HandlerThread mLoadThread;
-    private final Handler mLoadThreadHandler;
-    private final Handler mMainThreadHandler;
-
-    private final TaskResourceLoadQueue mLoadQueue;
-    private final IconLoader mIconLoader;
-
-    private boolean mStarted;
-    private boolean mCancelled;
-    private boolean mWaitingOnLoadQueue;
-
-    private final OnIdleChangedListener mOnIdleChangedListener;
-
-    /** Constructor, creates a new loading thread that loads task resources in the background */
-    public BackgroundTaskLoader(TaskResourceLoadQueue loadQueue,
-            IconLoader iconLoader, OnIdleChangedListener onIdleChangedListener) {
-        mLoadQueue = loadQueue;
-        mIconLoader = iconLoader;
-        mMainThreadHandler = new Handler();
-        mOnIdleChangedListener = onIdleChangedListener;
-        mLoadThread = new HandlerThread("Recents-TaskResourceLoader",
-                android.os.Process.THREAD_PRIORITY_BACKGROUND);
-        mLoadThread.start();
-        mLoadThreadHandler = new Handler(mLoadThread.getLooper());
-    }
-
-    /** Restarts the loader thread */
-    void start(Context context) {
-        mContext = context;
-        mCancelled = false;
-        if (!mStarted) {
-            // Start loading on the load thread
-            mStarted = true;
-            mLoadThreadHandler.post(this);
-        } else {
-            // Notify the load thread to start loading again
-            synchronized (mLoadThread) {
-                mLoadThread.notifyAll();
-            }
-        }
-    }
-
-    /** Requests the loader thread to stop after the current iteration */
-    void stop() {
-        // Mark as cancelled for the thread to pick up
-        mCancelled = true;
-        // If we are waiting for the load queue for more tasks, then we can just reset the
-        // Context now, since nothing is using it
-        if (mWaitingOnLoadQueue) {
-            mContext = null;
-        }
-    }
-
-    @Override
-    public void run() {
-        while (true) {
-            if (mCancelled) {
-                // We have to unset the context here, since the background thread may be using it
-                // when we call stop()
-                mContext = null;
-                // If we are cancelled, then wait until we are started again
-                synchronized(mLoadThread) {
-                    try {
-                        mLoadThread.wait();
-                    } catch (InterruptedException ie) {
-                        ie.printStackTrace();
-                    }
-                }
-            } else {
-                // If we've stopped the loader, then fall through to the above logic to wait on
-                // the load thread
-                processLoadQueueItem();
-
-                // If there are no other items in the list, then just wait until something is added
-                if (!mCancelled && mLoadQueue.isEmpty()) {
-                    synchronized(mLoadQueue) {
-                        try {
-                            mWaitingOnLoadQueue = true;
-                            mMainThreadHandler.post(new Runnable() {
-                                @Override
-                                public void run() {
-                                    mOnIdleChangedListener.onIdleChanged(true);
-                                }
-                            });
-                            mLoadQueue.wait();
-                            mMainThreadHandler.post(new Runnable() {
-                                @Override
-                                public void run() {
-                                    mOnIdleChangedListener.onIdleChanged(false);
-                                }
-                            });
-                            mWaitingOnLoadQueue = false;
-                        } catch (InterruptedException ie) {
-                            ie.printStackTrace();
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * This needs to be in a separate method to work around an surprising interpreter behavior:
-     * The register will keep the local reference to cachedThumbnailData even if it falls out of
-     * scope. Putting it into a method fixes this issue.
-     */
-    private void processLoadQueueItem() {
-        // Load the next item from the queue
-        final Task t = mLoadQueue.nextTask();
-        if (t != null) {
-            final Drawable icon = mIconLoader.getIcon(t);
-            if (DEBUG) Log.d(TAG, "Loading thumbnail: " + t.key);
-            final ThumbnailData thumbnailData =
-                    ActivityManagerWrapper.getInstance().getTaskThumbnail(t.key.id,
-                            true /* reducedResolution */);
-
-            if (!mCancelled) {
-                // Notify that the task data has changed
-                mMainThreadHandler.post(new Runnable() {
-                    @Override
-                    public void run() {
-                        t.notifyTaskDataLoaded(thumbnailData, icon);
-                    }
-                });
-            }
-        }
-    }
-
-    interface OnIdleChangedListener {
-        void onIdleChanged(boolean idle);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/FilteredTaskList.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/FilteredTaskList.java
deleted file mode 100644
index 005be75..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/FilteredTaskList.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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.systemui.recents.model;
-
-import android.util.ArrayMap;
-import android.util.SparseArray;
-
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A list of filtered tasks.
- */
-class FilteredTaskList {
-
-    private final ArrayList<Task> mTasks = new ArrayList<>();
-    private final ArrayList<Task> mFilteredTasks = new ArrayList<>();
-    private final ArrayMap<TaskKey, Integer> mFilteredTaskIndices = new ArrayMap<>();
-    private TaskFilter mFilter;
-
-    /** Sets the task filter, and returns whether the set of filtered tasks have changed. */
-    boolean setFilter(TaskFilter filter) {
-        ArrayList<Task> prevFilteredTasks = new ArrayList<>(mFilteredTasks);
-        mFilter = filter;
-        updateFilteredTasks();
-        return !prevFilteredTasks.equals(mFilteredTasks);
-    }
-
-    /** Adds a new task to the task list */
-    void add(Task t) {
-        mTasks.add(t);
-        updateFilteredTasks();
-    }
-
-    /** Sets the list of tasks */
-    void set(List<Task> tasks) {
-        mTasks.clear();
-        mTasks.addAll(tasks);
-        updateFilteredTasks();
-    }
-
-    /** Removes a task from the base list only if it is in the filtered list */
-    boolean remove(Task t) {
-        if (mFilteredTasks.contains(t)) {
-            boolean removed = mTasks.remove(t);
-            updateFilteredTasks();
-            return removed;
-        }
-        return false;
-    }
-
-    /** Returns the index of this task in the list of filtered tasks */
-    int indexOf(Task t) {
-        if (t != null && mFilteredTaskIndices.containsKey(t.key)) {
-            return mFilteredTaskIndices.get(t.key);
-        }
-        return -1;
-    }
-
-    /** Returns the size of the list of filtered tasks */
-    int size() {
-        return mFilteredTasks.size();
-    }
-
-    /** Returns whether the filtered list contains this task */
-    boolean contains(Task t) {
-        return mFilteredTaskIndices.containsKey(t.key);
-    }
-
-    /** Updates the list of filtered tasks whenever the base task list changes */
-    private void updateFilteredTasks() {
-        mFilteredTasks.clear();
-        if (mFilter != null) {
-            // Create a sparse array from task id to Task
-            SparseArray<Task> taskIdMap = new SparseArray<>();
-            int taskCount = mTasks.size();
-            for (int i = 0; i < taskCount; i++) {
-                Task t = mTasks.get(i);
-                taskIdMap.put(t.key.id, t);
-            }
-
-            for (int i = 0; i < taskCount; i++) {
-                Task t = mTasks.get(i);
-                if (mFilter.acceptTask(taskIdMap, t, i)) {
-                    mFilteredTasks.add(t);
-                }
-            }
-        } else {
-            mFilteredTasks.addAll(mTasks);
-        }
-        updateFilteredTaskIndices();
-    }
-
-    /** Updates the mapping of tasks to indices. */
-    private void updateFilteredTaskIndices() {
-        int taskCount = mFilteredTasks.size();
-        mFilteredTaskIndices.clear();
-        for (int i = 0; i < taskCount; i++) {
-            Task t = mFilteredTasks.get(i);
-            mFilteredTaskIndices.put(t.key, i);
-        }
-    }
-
-    /** Returns the list of filtered tasks */
-    ArrayList<Task> getTasks() {
-        return mFilteredTasks;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/HighResThumbnailLoader.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/HighResThumbnailLoader.java
deleted file mode 100644
index 34bc334..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/HighResThumbnailLoader.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * 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.systemui.recents.model;
-
-import static android.os.Process.setThreadPriority;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.os.SystemClock;
-import android.util.ArraySet;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskCallbacks;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-
-/**
- * Loader class that loads full-resolution thumbnails when appropriate.
- */
-public class HighResThumbnailLoader implements
-        TaskCallbacks, BackgroundTaskLoader.OnIdleChangedListener {
-
-    private final ActivityManagerWrapper mActivityManager;
-
-    @GuardedBy("mLoadQueue")
-    private final ArrayDeque<Task> mLoadQueue = new ArrayDeque<>();
-    @GuardedBy("mLoadQueue")
-    private final ArraySet<Task> mLoadingTasks = new ArraySet<>();
-    @GuardedBy("mLoadQueue")
-    private boolean mLoaderIdling;
-
-    private final ArrayList<Task> mVisibleTasks = new ArrayList<>();
-
-    private final Thread mLoadThread;
-    private final Handler mMainThreadHandler;
-    private final boolean mIsLowRamDevice;
-    private boolean mLoading;
-    private boolean mVisible;
-    private boolean mFlingingFast;
-    private boolean mTaskLoadQueueIdle;
-
-    public HighResThumbnailLoader(ActivityManagerWrapper activityManager, Looper looper,
-            boolean isLowRamDevice) {
-        mActivityManager = activityManager;
-        mMainThreadHandler = new Handler(looper);
-        mLoadThread = new Thread(mLoader, "Recents-HighResThumbnailLoader");
-        mLoadThread.start();
-        mIsLowRamDevice = isLowRamDevice;
-    }
-
-    public void setVisible(boolean visible) {
-        if (mIsLowRamDevice) {
-            return;
-        }
-        mVisible = visible;
-        updateLoading();
-    }
-
-    public void setFlingingFast(boolean flingingFast) {
-        if (mFlingingFast == flingingFast || mIsLowRamDevice) {
-            return;
-        }
-        mFlingingFast = flingingFast;
-        updateLoading();
-    }
-
-    @Override
-    public void onIdleChanged(boolean idle) {
-        setTaskLoadQueueIdle(idle);
-    }
-
-    /**
-     * Sets whether the other task load queue is idling. Avoid double-loading bitmaps by not
-     * starting this queue until the other queue is idling.
-     */
-    public void setTaskLoadQueueIdle(boolean idle) {
-        if (mIsLowRamDevice) {
-            return;
-        }
-        mTaskLoadQueueIdle = idle;
-        updateLoading();
-    }
-
-    @VisibleForTesting
-    boolean isLoading() {
-        return mLoading;
-    }
-
-    private void updateLoading() {
-        setLoading(mVisible && !mFlingingFast && mTaskLoadQueueIdle);
-    }
-
-    private void setLoading(boolean loading) {
-        if (loading == mLoading) {
-            return;
-        }
-        synchronized (mLoadQueue) {
-            mLoading = loading;
-            if (!loading) {
-                stopLoading();
-            } else {
-                startLoading();
-            }
-        }
-    }
-
-    @GuardedBy("mLoadQueue")
-    private void startLoading() {
-        for (int i = mVisibleTasks.size() - 1; i >= 0; i--) {
-            Task t = mVisibleTasks.get(i);
-            if ((t.thumbnail == null || t.thumbnail.reducedResolution)
-                    && !mLoadQueue.contains(t) && !mLoadingTasks.contains(t)) {
-                mLoadQueue.add(t);
-            }
-        }
-        mLoadQueue.notifyAll();
-    }
-
-    @GuardedBy("mLoadQueue")
-    private void stopLoading() {
-        mLoadQueue.clear();
-        mLoadQueue.notifyAll();
-    }
-
-    /**
-     * Needs to be called when a task becomes visible. Note that this is different from
-     * {@link TaskCallbacks#onTaskDataLoaded} as this method should only be called once when it
-     * becomes visible, whereas onTaskDataLoaded can be called multiple times whenever some data
-     * has been updated.
-     */
-    public void onTaskVisible(Task t) {
-        t.addCallback(this);
-        mVisibleTasks.add(t);
-        if ((t.thumbnail == null || t.thumbnail.reducedResolution) && mLoading) {
-            synchronized (mLoadQueue) {
-                mLoadQueue.add(t);
-                mLoadQueue.notifyAll();
-            }
-        }
-    }
-
-    /**
-     * Needs to be called when a task becomes visible. See {@link #onTaskVisible} why this is
-     * different from {@link TaskCallbacks#onTaskDataUnloaded()}
-     */
-    public void onTaskInvisible(Task t) {
-        t.removeCallback(this);
-        mVisibleTasks.remove(t);
-        synchronized (mLoadQueue) {
-            mLoadQueue.remove(t);
-        }
-    }
-
-    @VisibleForTesting
-    void waitForLoaderIdle() {
-        while (true) {
-            synchronized (mLoadQueue) {
-                if (mLoadQueue.isEmpty() && mLoaderIdling) {
-                    return;
-                }
-            }
-            SystemClock.sleep(100);
-        }
-    }
-
-    @Override
-    public void onTaskDataLoaded(Task task, ThumbnailData thumbnailData) {
-        if (thumbnailData != null && !thumbnailData.reducedResolution) {
-            synchronized (mLoadQueue) {
-                mLoadQueue.remove(task);
-            }
-        }
-    }
-
-    @Override
-    public void onTaskDataUnloaded() {
-    }
-
-    @Override
-    public void onTaskWindowingModeChanged() {
-    }
-
-    private final Runnable mLoader = new Runnable() {
-
-        @Override
-        public void run() {
-            setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND + 1);
-            while (true) {
-                Task next = null;
-                synchronized (mLoadQueue) {
-                    if (!mLoading || mLoadQueue.isEmpty()) {
-                        try {
-                            mLoaderIdling = true;
-                            mLoadQueue.wait();
-                            mLoaderIdling = false;
-                        } catch (InterruptedException e) {
-                            // Don't care.
-                        }
-                    } else {
-                        next = mLoadQueue.poll();
-                        if (next != null) {
-                            mLoadingTasks.add(next);
-                        }
-                    }
-                }
-                if (next != null) {
-                    loadTask(next);
-                }
-            }
-        }
-
-        private void loadTask(final Task t) {
-            final ThumbnailData thumbnail = mActivityManager.getTaskThumbnail(t.key.id,
-                    false /* reducedResolution */);
-            mMainThreadHandler.post(new Runnable() {
-                @Override
-                public void run() {
-                    synchronized (mLoadQueue) {
-                        mLoadingTasks.remove(t);
-                    }
-                    if (mVisibleTasks.contains(t)) {
-                        t.notifyTaskDataLoaded(thumbnail, t.icon);
-                    }
-                }
-            });
-        }
-    };
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/RecentsTaskLoadPlan.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/RecentsTaskLoadPlan.java
deleted file mode 100644
index 2df79d8..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/RecentsTaskLoadPlan.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.model;
-
-import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
-
-import android.app.ActivityManager;
-import android.app.ActivityTaskManager;
-import android.app.KeyguardManager;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.pm.ActivityInfo;
-import android.content.pm.ApplicationInfo;
-import android.content.res.Resources;
-import android.graphics.drawable.Drawable;
-import android.util.SparseBooleanArray;
-
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-
-/**
- * This class stores the loading state as it goes through multiple stages of loading:
- *   1) preloadRawTasks() will load the raw set of recents tasks from the system
- *   2) preloadPlan() will construct a new task stack with all metadata and only icons and
- *      thumbnails that are currently in the cache
- *   3) executePlan() will actually load and fill in the icons and thumbnails according to the load
- *      options specified, such that we can transition into the Recents activity seamlessly
- */
-public class RecentsTaskLoadPlan {
-
-    /** The set of conditions to preload tasks. */
-    public static class PreloadOptions {
-        public boolean loadTitles = true;
-    }
-
-    /** The set of conditions to load tasks. */
-    public static class Options {
-        public int runningTaskId = -1;
-        public boolean loadIcons = true;
-        public boolean loadThumbnails = false;
-        public boolean onlyLoadForCache = false;
-        public boolean onlyLoadPausedActivities = false;
-        public int numVisibleTasks = 0;
-        public int numVisibleTaskThumbnails = 0;
-    }
-
-    private final Context mContext;
-    private final KeyguardManager mKeyguardManager;
-
-    private List<ActivityManager.RecentTaskInfo> mRawTasks;
-    private TaskStack mStack;
-
-    private final SparseBooleanArray mTmpLockedUsers = new SparseBooleanArray();
-
-    public RecentsTaskLoadPlan(Context context) {
-        mContext = context;
-        mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
-    }
-
-    /**
-     * Preloads the list of recent tasks from the system. After this call, the TaskStack will
-     * have a list of all the recent tasks with their metadata, not including icons or
-     * thumbnails which were not cached and have to be loaded.
-     *
-     * The tasks will be ordered by:
-     * - least-recent to most-recent stack tasks
-     *
-     * Note: Do not lock, since this can be calling back to the loader, which separately also drives
-     * this call (callers should synchronize on the loader before making this call).
-     */
-    public void preloadPlan(PreloadOptions opts, RecentsTaskLoader loader, int runningTaskId,
-            int currentUserId) {
-        Resources res = mContext.getResources();
-        ArrayList<Task> allTasks = new ArrayList<>();
-        if (mRawTasks == null) {
-            mRawTasks = ActivityManagerWrapper.getInstance().getRecentTasks(
-                    ActivityTaskManager.getMaxRecentTasksStatic(), currentUserId);
-
-            // Since the raw tasks are given in most-recent to least-recent order, we need to reverse it
-            Collections.reverse(mRawTasks);
-        }
-
-        int taskCount = mRawTasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            ActivityManager.RecentTaskInfo t = mRawTasks.get(i);
-
-            // Compose the task key
-            final ComponentName sourceComponent = t.origActivity != null
-                    // Activity alias if there is one
-                    ? t.origActivity
-                    // The real activity if there is no alias (or the target if there is one)
-                    : t.realActivity;
-            final int windowingMode = t.configuration.windowConfiguration.getWindowingMode();
-            TaskKey taskKey = new TaskKey(t.persistentId, windowingMode, t.baseIntent,
-                    sourceComponent, t.userId, t.lastActiveTime, t.displayId);
-
-            boolean isFreeformTask = windowingMode == WINDOWING_MODE_FREEFORM;
-            boolean isStackTask = !isFreeformTask;
-            boolean isLaunchTarget = taskKey.id == runningTaskId;
-
-            ActivityInfo info = loader.getAndUpdateActivityInfo(taskKey);
-            if (info == null) {
-                continue;
-            }
-
-            // Load the title, icon, and color
-            String title = opts.loadTitles
-                    ? loader.getAndUpdateActivityTitle(taskKey, t.taskDescription)
-                    : "";
-            String titleDescription = opts.loadTitles
-                    ? loader.getAndUpdateContentDescription(taskKey, t.taskDescription)
-                    : "";
-            Drawable icon = isStackTask
-                    ? loader.getAndUpdateActivityIcon(taskKey, t.taskDescription, false)
-                    : null;
-            ThumbnailData thumbnail = loader.getAndUpdateThumbnail(taskKey,
-                    false /* loadIfNotCached */, false /* storeInCache */);
-            int activityColor = loader.getActivityPrimaryColor(t.taskDescription);
-            int backgroundColor = loader.getActivityBackgroundColor(t.taskDescription);
-            boolean isSystemApp = (info != null) &&
-                    ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
-
-            // TODO: Refactor to not do this every preload
-            if (mTmpLockedUsers.indexOfKey(t.userId) < 0) {
-                mTmpLockedUsers.put(t.userId, mKeyguardManager.isDeviceLocked(t.userId));
-            }
-            boolean isLocked = mTmpLockedUsers.get(t.userId);
-
-            // Add the task to the stack
-            Task task = new Task(taskKey, icon,
-                    thumbnail, title, titleDescription, activityColor, backgroundColor,
-                    isLaunchTarget, isStackTask, isSystemApp, t.supportsSplitScreenMultiWindow,
-                    t.taskDescription, t.resizeMode, t.topActivity, isLocked);
-
-            allTasks.add(task);
-        }
-
-        // Initialize the stacks
-        mStack = new TaskStack();
-        mStack.setTasks(allTasks, false /* notifyStackChanges */);
-    }
-
-    /**
-     * Called to apply the actual loading based on the specified conditions.
-     *
-     * Note: Do not lock, since this can be calling back to the loader, which separately also drives
-     * this call (callers should synchronize on the loader before making this call).
-     */
-    public void executePlan(Options opts, RecentsTaskLoader loader) {
-        Resources res = mContext.getResources();
-
-        // Iterate through each of the tasks and load them according to the load conditions.
-        ArrayList<Task> tasks = mStack.getTasks();
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task task = tasks.get(i);
-            TaskKey taskKey = task.key;
-
-            boolean isRunningTask = (task.key.id == opts.runningTaskId);
-            boolean isVisibleTask = i >= (taskCount - opts.numVisibleTasks);
-            boolean isVisibleThumbnail = i >= (taskCount - opts.numVisibleTaskThumbnails);
-
-            // If requested, skip the running task
-            if (opts.onlyLoadPausedActivities && isRunningTask) {
-                continue;
-            }
-
-            if (opts.loadIcons && (isRunningTask || isVisibleTask)) {
-                if (task.icon == null) {
-                    task.icon = loader.getAndUpdateActivityIcon(taskKey, task.taskDescription,
-                            true);
-                }
-            }
-            if (opts.loadThumbnails && isVisibleThumbnail) {
-                task.thumbnail = loader.getAndUpdateThumbnail(taskKey,
-                        true /* loadIfNotCached */, true /* storeInCache */);
-            }
-        }
-    }
-
-    /**
-     * Returns the TaskStack from the preloaded list of recent tasks.
-     */
-    public TaskStack getTaskStack() {
-        return mStack;
-    }
-
-    /** Returns whether there are any tasks in any stacks. */
-    public boolean hasTasks() {
-        if (mStack != null) {
-            return mStack.getTaskCount() > 0;
-        }
-        return false;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/RecentsTaskLoader.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/RecentsTaskLoader.java
deleted file mode 100644
index 012913a..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/RecentsTaskLoader.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.model;
-
-import android.app.ActivityManager;
-import android.app.ActivityTaskManager;
-import android.content.ComponentCallbacks2;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.pm.ActivityInfo;
-import android.graphics.drawable.Drawable;
-import android.os.Looper;
-import android.os.Trace;
-import android.util.Log;
-import android.util.LruCache;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.systemui.recents.model.RecentsTaskLoadPlan.Options;
-import com.android.systemui.recents.model.RecentsTaskLoadPlan.PreloadOptions;
-import com.android.systemui.shared.recents.model.IconLoader;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-import com.android.systemui.shared.recents.model.TaskKeyLruCache;
-import com.android.systemui.shared.recents.model.TaskKeyLruCache.EvictionCallback;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-
-import java.io.PrintWriter;
-import java.util.Map;
-
-
-/**
- * Recents task loader
- */
-public class RecentsTaskLoader {
-    private static final String TAG = "RecentsTaskLoader";
-    private static final boolean DEBUG = false;
-
-    /** Levels of svelte in increasing severity/austerity. */
-    // No svelting.
-    public static final int SVELTE_NONE = 0;
-    // Limit thumbnail cache to number of visible thumbnails when Recents was loaded, disable
-    // caching thumbnails as you scroll.
-    public static final int SVELTE_LIMIT_CACHE = 1;
-    // Disable the thumbnail cache, load thumbnails asynchronously when the activity loads and
-    // evict all thumbnails when hidden.
-    public static final int SVELTE_DISABLE_CACHE = 2;
-    // Disable all thumbnail loading.
-    public static final int SVELTE_DISABLE_LOADING = 3;
-
-    // This activity info LruCache is useful because it can be expensive to retrieve ActivityInfos
-    // for many tasks, which we use to get the activity labels and icons.  Unlike the other caches
-    // below, this is per-package so we can't invalidate the items in the cache based on the last
-    // active time.  Instead, we rely on the PackageMonitor to keep us informed whenever a
-    // package in the cache has been updated, so that we may remove it.
-    private final LruCache<ComponentName, ActivityInfo> mActivityInfoCache;
-    private final TaskKeyLruCache<Drawable> mIconCache;
-    private final TaskKeyLruCache<String> mActivityLabelCache;
-    private final TaskKeyLruCache<String> mContentDescriptionCache;
-    private final TaskResourceLoadQueue mLoadQueue;
-    private final IconLoader mIconLoader;
-    private final BackgroundTaskLoader mLoader;
-    private final HighResThumbnailLoader mHighResThumbnailLoader;
-    @GuardedBy("this")
-    private final TaskKeyStrongCache<ThumbnailData> mThumbnailCache = new TaskKeyStrongCache<>();
-    @GuardedBy("this")
-    private final TaskKeyStrongCache<ThumbnailData> mTempCache = new TaskKeyStrongCache<>();
-    private final int mMaxThumbnailCacheSize;
-    private final int mMaxIconCacheSize;
-    private int mNumVisibleTasksLoaded;
-    private int mSvelteLevel;
-
-    private int mDefaultTaskBarBackgroundColor;
-    private int mDefaultTaskViewBackgroundColor;
-
-    private EvictionCallback mClearActivityInfoOnEviction = new EvictionCallback() {
-        @Override
-        public void onEntryEvicted(TaskKey key) {
-            if (key != null) {
-                mActivityInfoCache.remove(key.getComponent());
-            }
-        }
-    };
-
-    public RecentsTaskLoader(Context context, int maxThumbnailCacheSize, int maxIconCacheSize,
-            int svelteLevel) {
-        mMaxThumbnailCacheSize = maxThumbnailCacheSize;
-        mMaxIconCacheSize = maxIconCacheSize;
-        mSvelteLevel = svelteLevel;
-
-        // Initialize the proxy, cache and loaders
-        int numRecentTasks = ActivityTaskManager.getMaxRecentTasksStatic();
-        mHighResThumbnailLoader = new HighResThumbnailLoader(ActivityManagerWrapper.getInstance(),
-                Looper.getMainLooper(), ActivityManager.isLowRamDeviceStatic());
-        mLoadQueue = new TaskResourceLoadQueue();
-        mIconCache = new TaskKeyLruCache<>(mMaxIconCacheSize, mClearActivityInfoOnEviction);
-        mActivityLabelCache = new TaskKeyLruCache<>(numRecentTasks, mClearActivityInfoOnEviction);
-        mContentDescriptionCache = new TaskKeyLruCache<>(numRecentTasks,
-                mClearActivityInfoOnEviction);
-        mActivityInfoCache = new LruCache<>(numRecentTasks);
-
-        mIconLoader = createNewIconLoader(context, mIconCache, mActivityInfoCache);
-        mLoader = new BackgroundTaskLoader(mLoadQueue, mIconLoader, mHighResThumbnailLoader);
-    }
-
-    protected IconLoader createNewIconLoader(Context context,TaskKeyLruCache<Drawable> iconCache,
-            LruCache<ComponentName, ActivityInfo> activityInfoCache) {
-        return new IconLoader.DefaultIconLoader(context, iconCache, activityInfoCache);
-    }
-
-    /**
-     * Sets the default task bar/view colors if none are provided by the app.
-     */
-    public void setDefaultColors(int defaultTaskBarBackgroundColor,
-            int defaultTaskViewBackgroundColor) {
-        mDefaultTaskBarBackgroundColor = defaultTaskBarBackgroundColor;
-        mDefaultTaskViewBackgroundColor = defaultTaskViewBackgroundColor;
-    }
-
-    /** Returns the size of the app icon cache. */
-    public int getIconCacheSize() {
-        return mMaxIconCacheSize;
-    }
-
-    /** Returns the size of the thumbnail cache. */
-    public int getThumbnailCacheSize() {
-        return mMaxThumbnailCacheSize;
-    }
-
-    public HighResThumbnailLoader getHighResThumbnailLoader() {
-        return mHighResThumbnailLoader;
-    }
-
-    /** Preloads recents tasks using the specified plan to store the output. */
-    public synchronized void preloadTasks(RecentsTaskLoadPlan plan, int runningTaskId) {
-        preloadTasks(plan, runningTaskId, ActivityManagerWrapper.getInstance().getCurrentUserId());
-    }
-
-    /** Preloads recents tasks using the specified plan to store the output. */
-    public synchronized void preloadTasks(RecentsTaskLoadPlan plan, int runningTaskId,
-            int currentUserId) {
-        try {
-            Trace.beginSection("preloadPlan");
-            plan.preloadPlan(new PreloadOptions(), this, runningTaskId, currentUserId);
-        } finally {
-            Trace.endSection();
-        }
-    }
-
-    /** Begins loading the heavy task data according to the specified options. */
-    public synchronized void loadTasks(RecentsTaskLoadPlan plan, Options opts) {
-        if (opts == null) {
-            throw new RuntimeException("Requires load options");
-        }
-        if (opts.onlyLoadForCache && opts.loadThumbnails) {
-            // If we are loading for the cache, we'd like to have the real cache only include the
-            // visible thumbnails. However, we also don't want to reload already cached thumbnails.
-            // Thus, we copy over the current entries into a second cache, and clear the real cache,
-            // such that the real cache only contains visible thumbnails.
-            mTempCache.copyEntries(mThumbnailCache);
-            mThumbnailCache.evictAll();
-        }
-        plan.executePlan(opts, this);
-        mTempCache.evictAll();
-        if (!opts.onlyLoadForCache) {
-            mNumVisibleTasksLoaded = opts.numVisibleTasks;
-        }
-    }
-
-    /**
-     * Acquires the task resource data directly from the cache, loading if necessary.
-     */
-    public void loadTaskData(Task t) {
-        Drawable icon = mIconCache.getAndInvalidateIfModified(t.key);
-        icon = icon != null ? icon : mIconLoader.getDefaultIcon(t.key.userId);
-        mLoadQueue.addTask(t);
-        t.notifyTaskDataLoaded(t.thumbnail, icon);
-    }
-
-    /** Releases the task resource data back into the pool. */
-    public void unloadTaskData(Task t) {
-        mLoadQueue.removeTask(t);
-        t.notifyTaskDataUnloaded(mIconLoader.getDefaultIcon(t.key.userId));
-    }
-
-    /** Completely removes the resource data from the pool. */
-    public void deleteTaskData(Task t, boolean notifyTaskDataUnloaded) {
-        mLoadQueue.removeTask(t);
-        mIconCache.remove(t.key);
-        mActivityLabelCache.remove(t.key);
-        mContentDescriptionCache.remove(t.key);
-        if (notifyTaskDataUnloaded) {
-            t.notifyTaskDataUnloaded(mIconLoader.getDefaultIcon(t.key.userId));
-        }
-    }
-
-    /**
-     * Handles signals from the system, trimming memory when requested to prevent us from running
-     * out of memory.
-     */
-    public synchronized void onTrimMemory(int level) {
-        switch (level) {
-            case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN:
-                // Stop the loader immediately when the UI is no longer visible
-                stopLoader();
-                mIconCache.trimToSize(Math.max(mNumVisibleTasksLoaded,
-                        mMaxIconCacheSize / 2));
-                break;
-            case ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE:
-            case ComponentCallbacks2.TRIM_MEMORY_BACKGROUND:
-                // We are leaving recents, so trim the data a bit
-                mIconCache.trimToSize(Math.max(1, mMaxIconCacheSize / 2));
-                mActivityInfoCache.trimToSize(Math.max(1,
-                        ActivityTaskManager.getMaxRecentTasksStatic() / 2));
-                break;
-            case ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW:
-            case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
-                // We are going to be low on memory
-                mIconCache.trimToSize(Math.max(1, mMaxIconCacheSize / 4));
-                mActivityInfoCache.trimToSize(Math.max(1,
-                        ActivityTaskManager.getMaxRecentTasksStatic() / 4));
-                break;
-            case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL:
-            case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
-                // We are low on memory, so release everything
-                mIconCache.evictAll();
-                mActivityInfoCache.evictAll();
-                // The cache is small, only clear the label cache when we are critical
-                mActivityLabelCache.evictAll();
-                mContentDescriptionCache.evictAll();
-                mThumbnailCache.evictAll();
-                break;
-            default:
-                break;
-        }
-    }
-
-    public void onPackageChanged(String packageName) {
-        // Remove all the cached activity infos for this package.  The other caches do not need to
-        // be pruned at this time, as the TaskKey expiration checks will flush them next time their
-        // cached contents are requested
-        Map<ComponentName, ActivityInfo> activityInfoCache = mActivityInfoCache.snapshot();
-        for (ComponentName cn : activityInfoCache.keySet()) {
-            if (cn.getPackageName().equals(packageName)) {
-                if (DEBUG) {
-                    Log.d(TAG, "Removing activity info from cache: " + cn);
-                }
-                mActivityInfoCache.remove(cn);
-            }
-        }
-    }
-
-    /**
-     * Returns the cached task label if the task key is not expired, updating the cache if it is.
-     */
-    String getAndUpdateActivityTitle(TaskKey taskKey, ActivityManager.TaskDescription td) {
-        // Return the task description label if it exists
-        if (td != null && td.getLabel() != null) {
-            return td.getLabel();
-        }
-        // Return the cached activity label if it exists
-        String label = mActivityLabelCache.getAndInvalidateIfModified(taskKey);
-        if (label != null) {
-            return label;
-        }
-        // All short paths failed, load the label from the activity info and cache it
-        ActivityInfo activityInfo = getAndUpdateActivityInfo(taskKey);
-        if (activityInfo != null) {
-            label = ActivityManagerWrapper.getInstance().getBadgedActivityLabel(activityInfo,
-                    taskKey.userId);
-            mActivityLabelCache.put(taskKey, label);
-            return label;
-        }
-        // If the activity info does not exist or fails to load, return an empty label for now,
-        // but do not cache it
-        return "";
-    }
-
-    /**
-     * Returns the cached task content description if the task key is not expired, updating the
-     * cache if it is.
-     */
-    String getAndUpdateContentDescription(TaskKey taskKey, ActivityManager.TaskDescription td) {
-        // Return the cached content description if it exists
-        String label = mContentDescriptionCache.getAndInvalidateIfModified(taskKey);
-        if (label != null) {
-            return label;
-        }
-
-        // All short paths failed, load the label from the activity info and cache it
-        ActivityInfo activityInfo = getAndUpdateActivityInfo(taskKey);
-        if (activityInfo != null) {
-            label = ActivityManagerWrapper.getInstance().getBadgedContentDescription(
-                    activityInfo, taskKey.userId, td);
-            if (td == null) {
-                // Only add to the cache if the task description is null, otherwise, it is possible
-                // for the task description to change between calls without the last active time
-                // changing (ie. between preloading and Overview starting) which would lead to stale
-                // content descriptions
-                // TODO: Investigate improving this
-                mContentDescriptionCache.put(taskKey, label);
-            }
-            return label;
-        }
-        // If the content description does not exist, return an empty label for now, but do not
-        // cache it
-        return "";
-    }
-
-    /**
-     * Returns the cached task icon if the task key is not expired, updating the cache if it is.
-     */
-    Drawable getAndUpdateActivityIcon(TaskKey taskKey, ActivityManager.TaskDescription td,
-            boolean loadIfNotCached) {
-        return mIconLoader.getAndInvalidateIfModified(taskKey, td, loadIfNotCached);
-    }
-
-    /**
-     * Returns the cached thumbnail if the task key is not expired, updating the cache if it is.
-     */
-    synchronized ThumbnailData getAndUpdateThumbnail(TaskKey taskKey, boolean loadIfNotCached,
-            boolean storeInCache) {
-        ThumbnailData cached = mThumbnailCache.getAndInvalidateIfModified(taskKey);
-        if (cached != null) {
-            return cached;
-        }
-
-        cached = mTempCache.getAndInvalidateIfModified(taskKey);
-        if (cached != null) {
-            mThumbnailCache.put(taskKey, cached);
-            return cached;
-        }
-
-        if (loadIfNotCached) {
-            if (mSvelteLevel < SVELTE_DISABLE_LOADING) {
-                // Load the thumbnail from the system
-                ThumbnailData thumbnailData = ActivityManagerWrapper.getInstance().getTaskThumbnail(
-                        taskKey.id, true /* reducedResolution */);
-                if (thumbnailData.thumbnail != null) {
-                    if (storeInCache) {
-                        mThumbnailCache.put(taskKey, thumbnailData);
-                    }
-                    return thumbnailData;
-                }
-            }
-        }
-
-        // We couldn't load any thumbnail
-        return null;
-    }
-
-    /**
-     * Returns the task's primary color if possible, defaulting to the default color if there is
-     * no specified primary color.
-     */
-    int getActivityPrimaryColor(ActivityManager.TaskDescription td) {
-        if (td != null && td.getPrimaryColor() != 0) {
-            return td.getPrimaryColor();
-        }
-        return mDefaultTaskBarBackgroundColor;
-    }
-
-    /**
-     * Returns the task's background color if possible.
-     */
-    int getActivityBackgroundColor(ActivityManager.TaskDescription td) {
-        if (td != null && td.getBackgroundColor() != 0) {
-            return td.getBackgroundColor();
-        }
-        return mDefaultTaskViewBackgroundColor;
-    }
-
-    /**
-     * Returns the activity info for the given task key, retrieving one from the system if the
-     * task key is expired.
-     */
-    ActivityInfo getAndUpdateActivityInfo(TaskKey taskKey) {
-        return mIconLoader.getAndUpdateActivityInfo(taskKey);
-    }
-
-    /**
-     * Starts loading tasks.
-     */
-    public void startLoader(Context ctx) {
-        mLoader.start(ctx);
-    }
-
-    /**
-     * Stops the task loader and clears all queued, pending task loads.
-     */
-    private void stopLoader() {
-        mLoader.stop();
-        mLoadQueue.clearTasks();
-    }
-
-    public synchronized void dump(String prefix, PrintWriter writer) {
-        String innerPrefix = prefix + "  ";
-
-        writer.print(prefix); writer.println(TAG);
-        writer.print(prefix); writer.println("Icon Cache");
-        mIconCache.dump(innerPrefix, writer);
-        writer.print(prefix); writer.println("Thumbnail Cache");
-        mThumbnailCache.dump(innerPrefix, writer);
-        writer.print(prefix); writer.println("Temp Thumbnail Cache");
-        mTempCache.dump(innerPrefix, writer);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskFilter.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskFilter.java
deleted file mode 100644
index 9b734ec..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskFilter.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.systemui.recents.model;
-
-import android.util.SparseArray;
-import com.android.systemui.shared.recents.model.Task;
-
-/**
- * An interface for a task filter to query whether a particular task should show in a stack.
- */
-public interface TaskFilter {
-    /** Returns whether the filter accepts the specified task */
-    boolean acceptTask(SparseArray<Task> taskIdMap, Task t, int index);
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskKeyStrongCache.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskKeyStrongCache.java
deleted file mode 100644
index 27f2098..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskKeyStrongCache.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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.systemui.recents.model;
-
-import android.util.ArrayMap;
-
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-
-import com.android.systemui.shared.recents.model.TaskKeyCache;
-import com.android.systemui.shared.recents.model.TaskKeyLruCache;
-import java.io.PrintWriter;
-
-/**
- * Like {@link TaskKeyLruCache}, but without LRU functionality.
- */
-public class TaskKeyStrongCache<V> extends TaskKeyCache<V> {
-
-    private static final String TAG = "TaskKeyCache";
-
-    private final ArrayMap<Integer, V> mCache = new ArrayMap<>();
-
-    public final void copyEntries(TaskKeyStrongCache<V> other) {
-        for (int i = other.mKeys.size() - 1; i >= 0; i--) {
-            TaskKey key = other.mKeys.valueAt(i);
-            put(key, other.mCache.get(key.id));
-        }
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        String innerPrefix = prefix + "  ";
-        writer.print(prefix); writer.print(TAG);
-        writer.print(" numEntries="); writer.print(mKeys.size());
-        writer.println();
-        int keyCount = mKeys.size();
-        for (int i = 0; i < keyCount; i++) {
-            writer.print(innerPrefix); writer.println(mKeys.get(mKeys.keyAt(i)));
-        }
-    }
-
-    @Override
-    protected V getCacheEntry(int id) {
-        return mCache.get(id);
-    }
-
-    @Override
-    protected void putCacheEntry(int id, V value) {
-        mCache.put(id, value);
-    }
-
-    @Override
-    protected void removeCacheEntry(int id) {
-        mCache.remove(id);
-    }
-
-    @Override
-    protected void evictAllCache() {
-        mCache.clear();
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskResourceLoadQueue.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskResourceLoadQueue.java
deleted file mode 100644
index fe89ad5..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskResourceLoadQueue.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.systemui.recents.model;
-
-import com.android.systemui.shared.recents.model.Task;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-/**
- * A Task load queue
- */
-class TaskResourceLoadQueue {
-
-    private final ConcurrentLinkedQueue<Task> mQueue = new ConcurrentLinkedQueue<>();
-
-    /** Adds a new task to the load queue */
-    void addTask(Task t) {
-        if (!mQueue.contains(t)) {
-            mQueue.add(t);
-        }
-        synchronized(this) {
-            notifyAll();
-        }
-    }
-
-    /**
-     * Retrieves the next task from the load queue, as well as whether we want that task to be
-     * force reloaded.
-     */
-    Task nextTask() {
-        return mQueue.poll();
-    }
-
-    /** Removes a task from the load queue */
-    void removeTask(Task t) {
-        mQueue.remove(t);
-    }
-
-    /** Clears all the tasks from the load queue */
-    void clearTasks() {
-        mQueue.clear();
-    }
-
-    /** Returns whether the load queue is empty */
-    boolean isEmpty() {
-        return mQueue.isEmpty();
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskStack.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskStack.java
deleted file mode 100644
index 01e6ba3..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/model/TaskStack.java
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.model;
-
-import android.content.ComponentName;
-import android.util.ArrayMap;
-import android.util.ArraySet;
-import android.util.SparseArray;
-
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-import com.android.systemui.recents.utilities.AnimationProps;
-import com.android.systemui.shared.system.PackageManagerWrapper;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- * The task stack contains a list of multiple tasks.
- */
-public class TaskStack {
-
-    private static final String TAG = "TaskStack";
-
-    /** Task stack callbacks */
-    public interface TaskStackCallbacks {
-        /**
-         * Notifies when a new task has been added to the stack.
-         */
-        void onStackTaskAdded(TaskStack stack, Task newTask);
-
-        /**
-         * Notifies when a task has been removed from the stack.
-         */
-        void onStackTaskRemoved(TaskStack stack, Task removedTask, Task newFrontMostTask,
-                AnimationProps animation, boolean fromDockGesture,
-                boolean dismissRecentsIfAllRemoved);
-
-        /**
-         * Notifies when all tasks have been removed from the stack.
-         */
-        void onStackTasksRemoved(TaskStack stack);
-
-        /**
-         * Notifies when tasks in the stack have been updated.
-         */
-        void onStackTasksUpdated(TaskStack stack);
-    }
-
-    private final ArrayList<Task> mRawTaskList = new ArrayList<>();
-    private final FilteredTaskList mStackTaskList = new FilteredTaskList();
-    private TaskStackCallbacks mCb;
-
-    public TaskStack() {
-        // Ensure that we only show stack tasks
-        mStackTaskList.setFilter(new TaskFilter() {
-            @Override
-            public boolean acceptTask(SparseArray<Task> taskIdMap, Task t, int index) {
-                return  t.isStackTask;
-            }
-        });
-    }
-
-    /** Sets the callbacks for this task stack. */
-    public void setCallbacks(TaskStackCallbacks cb) {
-        mCb = cb;
-    }
-
-    /**
-     * Removes a task from the stack, with an additional {@param animation} hint to the callbacks on
-     * how they should update themselves.
-     */
-    public void removeTask(Task t, AnimationProps animation, boolean fromDockGesture) {
-        removeTask(t, animation, fromDockGesture, true /* dismissRecentsIfAllRemoved */);
-    }
-
-    /**
-     * Removes a task from the stack, with an additional {@param animation} hint to the callbacks on
-     * how they should update themselves.
-     */
-    public void removeTask(Task t, AnimationProps animation, boolean fromDockGesture,
-            boolean dismissRecentsIfAllRemoved) {
-        if (mStackTaskList.contains(t)) {
-            mStackTaskList.remove(t);
-            Task newFrontMostTask = getFrontMostTask();
-            if (mCb != null) {
-                // Notify that a task has been removed
-                mCb.onStackTaskRemoved(this, t, newFrontMostTask, animation,
-                        fromDockGesture, dismissRecentsIfAllRemoved);
-            }
-        }
-        mRawTaskList.remove(t);
-    }
-
-    /**
-     * Removes all tasks from the stack.
-     */
-    public void removeAllTasks(boolean notifyStackChanges) {
-        ArrayList<Task> tasks = mStackTaskList.getTasks();
-        for (int i = tasks.size() - 1; i >= 0; i--) {
-            Task t = tasks.get(i);
-            mStackTaskList.remove(t);
-            mRawTaskList.remove(t);
-        }
-        if (mCb != null && notifyStackChanges) {
-            // Notify that all tasks have been removed
-            mCb.onStackTasksRemoved(this);
-        }
-    }
-
-
-    /**
-     * @see #setTasks(List, boolean)
-     */
-    public void setTasks(TaskStack stack, boolean notifyStackChanges) {
-        setTasks(stack.mRawTaskList, notifyStackChanges);
-    }
-
-    /**
-     * Sets a few tasks in one go, without calling any callbacks.
-     *
-     * @param tasks the new set of tasks to replace the current set.
-     * @param notifyStackChanges whether or not to callback on specific changes to the list of tasks.
-     */
-    public void setTasks(List<Task> tasks, boolean notifyStackChanges) {
-        // Compute a has set for each of the tasks
-        ArrayMap<TaskKey, Task> currentTasksMap = createTaskKeyMapFromList(mRawTaskList);
-        ArrayMap<TaskKey, Task> newTasksMap = createTaskKeyMapFromList(tasks);
-        ArrayList<Task> addedTasks = new ArrayList<>();
-        ArrayList<Task> removedTasks = new ArrayList<>();
-        ArrayList<Task> allTasks = new ArrayList<>();
-
-        // Disable notifications if there are no callbacks
-        if (mCb == null) {
-            notifyStackChanges = false;
-        }
-
-        // Remove any tasks that no longer exist
-        int taskCount = mRawTaskList.size();
-        for (int i = taskCount - 1; i >= 0; i--) {
-            Task task = mRawTaskList.get(i);
-            if (!newTasksMap.containsKey(task.key)) {
-                if (notifyStackChanges) {
-                    removedTasks.add(task);
-                }
-            }
-        }
-
-        // Add any new tasks
-        taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task newTask = tasks.get(i);
-            Task currentTask = currentTasksMap.get(newTask.key);
-            if (currentTask == null && notifyStackChanges) {
-                addedTasks.add(newTask);
-            } else if (currentTask != null) {
-                // The current task has bound callbacks, so just copy the data from the new task
-                // state and add it back into the list
-                currentTask.copyFrom(newTask);
-                newTask = currentTask;
-            }
-            allTasks.add(newTask);
-        }
-
-        // Sort all the tasks to ensure they are ordered correctly
-        for (int i = allTasks.size() - 1; i >= 0; i--) {
-            allTasks.get(i).temporarySortIndexInStack = i;
-        }
-
-        mStackTaskList.set(allTasks);
-        mRawTaskList.clear();
-        mRawTaskList.addAll(allTasks);
-
-        // Only callback for the removed tasks after the stack has updated
-        int removedTaskCount = removedTasks.size();
-        Task newFrontMostTask = getFrontMostTask();
-        for (int i = 0; i < removedTaskCount; i++) {
-            mCb.onStackTaskRemoved(this, removedTasks.get(i), newFrontMostTask,
-                    AnimationProps.IMMEDIATE, false /* fromDockGesture */,
-                    true /* dismissRecentsIfAllRemoved */);
-        }
-
-        // Only callback for the newly added tasks after this stack has been updated
-        int addedTaskCount = addedTasks.size();
-        for (int i = 0; i < addedTaskCount; i++) {
-            mCb.onStackTaskAdded(this, addedTasks.get(i));
-        }
-
-        // Notify that the task stack has been updated
-        if (notifyStackChanges) {
-            mCb.onStackTasksUpdated(this);
-        }
-    }
-
-    /**
-     * Gets the front-most task in the stack.
-     */
-    public Task getFrontMostTask() {
-        ArrayList<Task> stackTasks = mStackTaskList.getTasks();
-        if (stackTasks.isEmpty()) {
-            return null;
-        }
-        return stackTasks.get(stackTasks.size() - 1);
-    }
-
-    /** Gets the task keys */
-    public ArrayList<TaskKey> getTaskKeys() {
-        ArrayList<TaskKey> taskKeys = new ArrayList<>();
-        ArrayList<Task> tasks = computeAllTasksList();
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task task = tasks.get(i);
-            taskKeys.add(task.key);
-        }
-        return taskKeys;
-    }
-
-    /**
-     * Returns the set of "active" (non-historical) tasks in the stack that have been used recently.
-     */
-    public ArrayList<Task> getTasks() {
-        return mStackTaskList.getTasks();
-    }
-
-    /**
-     * Computes a set of all the active and historical tasks.
-     */
-    public ArrayList<Task> computeAllTasksList() {
-        ArrayList<Task> tasks = new ArrayList<>();
-        tasks.addAll(mStackTaskList.getTasks());
-        return tasks;
-    }
-
-    /**
-     * Returns the number of stack tasks.
-     */
-    public int getTaskCount() {
-        return mStackTaskList.size();
-    }
-
-    /**
-     * Returns the task in stack tasks which is the launch target.
-     */
-    public Task getLaunchTarget() {
-        ArrayList<Task> tasks = mStackTaskList.getTasks();
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task task = tasks.get(i);
-            if (task.isLaunchTarget) {
-                return task;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Returns whether the next launch target should actually be the PiP task.
-     */
-    public boolean isNextLaunchTargetPip(long lastPipTime) {
-        Task launchTarget = getLaunchTarget();
-        Task nextLaunchTarget = getNextLaunchTargetRaw();
-        if (nextLaunchTarget != null && lastPipTime > 0) {
-            // If the PiP time is more recent than the next launch target, then launch the PiP task
-            return lastPipTime > nextLaunchTarget.key.lastActiveTime;
-        } else if (launchTarget != null && lastPipTime > 0 && getTaskCount() == 1) {
-            // Otherwise, if there is no next launch target, but there is a PiP, then launch
-            // the PiP task
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Returns the task in stack tasks which should be launched next if Recents are toggled
-     * again, or null if there is no task to be launched. Callers should check
-     * {@link #isNextLaunchTargetPip(long)} before fetching the next raw launch target from the
-     * stack.
-     */
-    public Task getNextLaunchTarget() {
-        Task nextLaunchTarget = getNextLaunchTargetRaw();
-        if (nextLaunchTarget != null) {
-            return nextLaunchTarget;
-        }
-        return getTasks().get(getTaskCount() - 1);
-    }
-
-    private Task getNextLaunchTargetRaw() {
-        int taskCount = getTaskCount();
-        if (taskCount == 0) {
-            return null;
-        }
-        int launchTaskIndex = indexOfTask(getLaunchTarget());
-        if (launchTaskIndex != -1 && launchTaskIndex > 0) {
-            return getTasks().get(launchTaskIndex - 1);
-        }
-        return null;
-    }
-
-    /** Returns the index of this task in this current task stack */
-    public int indexOfTask(Task t) {
-        return mStackTaskList.indexOf(t);
-    }
-
-    /** Finds the task with the specified task id. */
-    public Task findTaskWithId(int taskId) {
-        ArrayList<Task> tasks = computeAllTasksList();
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task task = tasks.get(i);
-            if (task.key.id == taskId) {
-                return task;
-            }
-        }
-        return null;
-    }
-    
-    /**
-     * Computes the components of tasks in this stack that have been removed as a result of a change
-     * in the specified package.
-     */
-    public ArraySet<ComponentName> computeComponentsRemoved(String packageName, int userId) {
-        // Identify all the tasks that should be removed as a result of the package being removed.
-        // Using a set to ensure that we callback once per unique component.
-        ArraySet<ComponentName> existingComponents = new ArraySet<>();
-        ArraySet<ComponentName> removedComponents = new ArraySet<>();
-        ArrayList<TaskKey> taskKeys = getTaskKeys();
-        int taskKeyCount = taskKeys.size();
-        for (int i = 0; i < taskKeyCount; i++) {
-            TaskKey t = taskKeys.get(i);
-
-            // Skip if this doesn't apply to the current user
-            if (t.userId != userId) continue;
-
-            ComponentName cn = t.getComponent();
-            if (cn.getPackageName().equals(packageName)) {
-                if (existingComponents.contains(cn)) {
-                    // If we know that the component still exists in the package, then skip
-                    continue;
-                }
-                if (PackageManagerWrapper.getInstance().getActivityInfo(cn, userId) != null) {
-                    existingComponents.add(cn);
-                } else {
-                    removedComponents.add(cn);
-                }
-            }
-        }
-        return removedComponents;
-    }
-
-    @Override
-    public String toString() {
-        String str = "Stack Tasks (" + mStackTaskList.size() + "):\n";
-        ArrayList<Task> tasks = mStackTaskList.getTasks();
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            str += "    " + tasks.get(i).toString() + "\n";
-        }
-        return str;
-    }
-
-    /**
-     * Given a list of tasks, returns a map of each task's key to the task.
-     */
-    private ArrayMap<TaskKey, Task> createTaskKeyMapFromList(List<Task> tasks) {
-        ArrayMap<TaskKey, Task> map = new ArrayMap<>(tasks.size());
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task task = tasks.get(i);
-            map.put(task.key, task);
-        }
-        return map;
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        String innerPrefix = prefix + "  ";
-
-        writer.print(prefix); writer.print(TAG);
-        writer.print(" numStackTasks="); writer.print(mStackTaskList.size());
-        writer.println();
-        ArrayList<Task> tasks = mStackTaskList.getTasks();
-        int taskCount = tasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            tasks.get(i).dump(innerPrefix, writer);
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/utilities/AnimationProps.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/utilities/AnimationProps.java
deleted file mode 100644
index 5463998..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/utilities/AnimationProps.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.utilities;
-
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.ValueAnimator;
-import android.annotation.IntDef;
-import android.util.SparseArray;
-import android.util.SparseLongArray;
-import android.view.View;
-import android.view.animation.Interpolator;
-import android.view.animation.LinearInterpolator;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.List;
-
-/**
- * The generic set of animation properties to animate a {@link View}. The animation can have
- * different interpolators, start delays and durations for each of the different properties.
- */
-public class AnimationProps {
-
-    private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator();
-    public static final AnimationProps IMMEDIATE = new AnimationProps(0, LINEAR_INTERPOLATOR);
-
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef({ALL, TRANSLATION_X, TRANSLATION_Y, TRANSLATION_Z, ALPHA, SCALE, BOUNDS})
-    public @interface PropType {}
-
-    public static final int ALL = 0;
-    public static final int TRANSLATION_X = 1;
-    public static final int TRANSLATION_Y = 2;
-    public static final int TRANSLATION_Z = 3;
-    public static final int ALPHA = 4;
-    public static final int SCALE = 5;
-    public static final int BOUNDS = 6;
-    public static final int DIM_ALPHA = 7;
-
-    private SparseLongArray mPropStartDelay;
-    private SparseLongArray mPropDuration;
-    private SparseArray<Interpolator> mPropInterpolators;
-    private Animator.AnimatorListener mListener;
-
-    /**
-     * The builder constructor.
-     */
-    public AnimationProps() {}
-
-    /**
-     * Creates an animation with a default {@param duration} and {@param interpolator} for all
-     * properties in this animation.
-     */
-    public AnimationProps(int duration, Interpolator interpolator) {
-        this(0, duration, interpolator, null);
-    }
-
-    /**
-     * Creates an animation with a default {@param duration} and {@param interpolator} for all
-     * properties in this animation.
-     */
-    public AnimationProps(int duration, Interpolator interpolator,
-            Animator.AnimatorListener listener) {
-        this(0, duration, interpolator, listener);
-    }
-
-    /**
-     * Creates an animation with a default {@param startDelay}, {@param duration} and
-     * {@param interpolator} for all properties in this animation.
-     */
-    public AnimationProps(int startDelay, int duration, Interpolator interpolator) {
-        this(startDelay, duration, interpolator, null);
-    }
-
-    /**
-     * Creates an animation with a default {@param startDelay}, {@param duration} and
-     * {@param interpolator} for all properties in this animation.
-     */
-    public AnimationProps(int startDelay, int duration, Interpolator interpolator,
-            Animator.AnimatorListener listener) {
-        setStartDelay(ALL, startDelay);
-        setDuration(ALL, duration);
-        setInterpolator(ALL, interpolator);
-        setListener(listener);
-    }
-
-    /**
-     * Creates a new {@link AnimatorSet} that will animate the given animators.  Callers need to
-     * manually apply the individual animation properties for each of the animators respectively.
-     */
-    public AnimatorSet createAnimator(List<Animator> animators) {
-        AnimatorSet anim = new AnimatorSet();
-        if (mListener != null) {
-            anim.addListener(mListener);
-        }
-        anim.playTogether(animators);
-        return anim;
-    }
-
-    /**
-     * Applies the specific start delay, duration and interpolator to the given {@param animator}
-     * for the specified {@param propertyType}.
-     */
-    public <T extends ValueAnimator> T apply(@PropType int propertyType, T animator) {
-        animator.setStartDelay(getStartDelay(propertyType));
-        animator.setDuration(getDuration(propertyType));
-        animator.setInterpolator(getInterpolator(propertyType));
-        return animator;
-    }
-
-    /**
-     * Sets a start delay for a specific property.
-     */
-    public AnimationProps setStartDelay(@PropType int propertyType, int startDelay) {
-        if (mPropStartDelay == null) {
-            mPropStartDelay = new SparseLongArray();
-        }
-        mPropStartDelay.append(propertyType, startDelay);
-        return this;
-    }
-
-    /**
-     * Returns the start delay for a specific property.
-     */
-    public long getStartDelay(@PropType int propertyType) {
-        if (mPropStartDelay != null) {
-            long startDelay = mPropStartDelay.get(propertyType, -1);
-            if (startDelay != -1) {
-                return startDelay;
-            }
-            return mPropStartDelay.get(ALL, 0);
-        }
-        return 0;
-    }
-
-    /**
-     * Sets a duration for a specific property.
-     */
-    public AnimationProps setDuration(@PropType int propertyType, int duration) {
-        if (mPropDuration == null) {
-            mPropDuration = new SparseLongArray();
-        }
-        mPropDuration.append(propertyType, duration);
-        return this;
-    }
-
-    /**
-     * Returns the duration for a specific property.
-     */
-    public long getDuration(@PropType int propertyType) {
-        if (mPropDuration != null) {
-            long duration = mPropDuration.get(propertyType, -1);
-            if (duration != -1) {
-                return duration;
-            }
-            return mPropDuration.get(ALL, 0);
-        }
-        return 0;
-    }
-
-    /**
-     * Sets an interpolator for a specific property.
-     */
-    public AnimationProps setInterpolator(@PropType int propertyType, Interpolator interpolator) {
-        if (mPropInterpolators == null) {
-            mPropInterpolators = new SparseArray<>();
-        }
-        mPropInterpolators.append(propertyType, interpolator);
-        return this;
-    }
-
-    /**
-     * Returns the interpolator for a specific property, falling back to the general interpolator
-     * if there is no specific property interpolator.
-     */
-    public Interpolator getInterpolator(@PropType int propertyType) {
-        if (mPropInterpolators != null) {
-            Interpolator interp = mPropInterpolators.get(propertyType);
-            if (interp != null) {
-                return interp;
-            }
-            return mPropInterpolators.get(ALL, LINEAR_INTERPOLATOR);
-        }
-        return LINEAR_INTERPOLATOR;
-    }
-
-    /**
-     * Sets an animator listener for this animation.
-     */
-    public AnimationProps setListener(Animator.AnimatorListener listener) {
-        mListener = listener;
-        return this;
-    }
-
-    /**
-     * Returns the animator listener for this animation.
-     */
-    public Animator.AnimatorListener getListener() {
-        return mListener;
-    }
-
-    /**
-     * Returns whether this animation has any duration.
-     */
-    public boolean isImmediate() {
-        int count = mPropDuration.size();
-        for (int i = 0; i < count; i++) {
-            if (mPropDuration.valueAt(i) > 0) {
-                return false;
-            }
-        }
-        return true;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/utilities/Utilities.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/utilities/Utilities.java
deleted file mode 100644
index ff58eba..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/utilities/Utilities.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.utilities;
-
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.RectEvaluator;
-import android.annotation.FloatRange;
-import android.annotation.Nullable;
-import android.app.Activity;
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.graphics.Color;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.drawable.Drawable;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Trace;
-import android.util.ArraySet;
-import android.util.IntProperty;
-import android.util.Property;
-import android.util.TypedValue;
-import android.view.Surface;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewParent;
-import android.view.ViewRootImpl;
-import android.view.ViewStub;
-
-import com.android.systemui.shared.recents.utilities.RectFEvaluator;
-import java.util.ArrayList;
-import java.util.Collections;
-
-/* Common code */
-public class Utilities {
-
-    public static final Property<Drawable, Integer> DRAWABLE_ALPHA =
-            new IntProperty<Drawable>("drawableAlpha") {
-                @Override
-                public void setValue(Drawable object, int alpha) {
-                    object.setAlpha(alpha);
-                }
-
-                @Override
-                public Integer get(Drawable object) {
-                    return object.getAlpha();
-                }
-            };
-
-    public static final Property<Drawable, Rect> DRAWABLE_RECT =
-            new Property<Drawable, Rect>(Rect.class, "drawableBounds") {
-                @Override
-                public void set(Drawable object, Rect bounds) {
-                    object.setBounds(bounds);
-                }
-
-                @Override
-                public Rect get(Drawable object) {
-                    return object.getBounds();
-                }
-            };
-
-    public static final RectFEvaluator RECTF_EVALUATOR = new RectFEvaluator();
-    public static final RectEvaluator RECT_EVALUATOR = new RectEvaluator(new Rect());
-
-    /**
-     * @return the first parent walking up the view hierarchy that has the given class type.
-     *
-     * @param parentClass must be a class derived from {@link View}
-     */
-    public static <T extends View> T findParent(View v, Class<T> parentClass) {
-        ViewParent parent = v.getParent();
-        while (parent != null) {
-            if (parentClass.isAssignableFrom(parent.getClass())) {
-                return (T) parent;
-            }
-            parent = parent.getParent();
-        }
-        return null;
-    }
-
-    /**
-     * Initializes the {@param setOut} with the given object.
-     */
-    public static <T> ArraySet<T> objectToSet(T obj, ArraySet<T> setOut) {
-        setOut.clear();
-        if (obj != null) {
-            setOut.add(obj);
-        }
-        return setOut;
-    }
-
-    /**
-     * Replaces the contents of {@param setOut} with the contents of the {@param array}.
-     */
-    public static <T> ArraySet<T> arrayToSet(T[] array, ArraySet<T> setOut) {
-        setOut.clear();
-        if (array != null) {
-            Collections.addAll(setOut, array);
-        }
-        return setOut;
-    }
-
-    /**
-     * @return the clamped {@param value} between the provided {@param min} and {@param max}.
-     */
-    public static int clamp(int value, int min, int max) {
-        return Math.max(min, Math.min(max, value));
-    }
-
-    /**
-     * @return the clamped {@param value} between 0 and 1.
-     */
-    public static float clamp01(float value) {
-        return Math.max(0f, Math.min(1f, value));
-    }
-
-    /**
-     * Scales the {@param value} to be proportionally between the {@param min} and
-     * {@param max} values.
-     *
-     * @param value must be between 0 and 1
-     */
-    public static float mapRange(@FloatRange(from=0.0,to=1.0) float value, float min, float max) {
-        return min + (value * (max - min));
-    }
-
-    /**
-     * Scales the {@param value} proportionally from {@param min} and {@param max} to 0 and 1.
-     *
-     * @param value must be between {@param min} and {@param max}
-     */
-    public static float unmapRange(float value, float min, float max) {
-        return (value - min) / (max - min);
-    }
-
-    /** Scales a rect about its centroid */
-    public static void scaleRectAboutCenter(RectF r, float scale) {
-        if (scale != 1.0f) {
-            float cx = r.centerX();
-            float cy = r.centerY();
-            r.offset(-cx, -cy);
-            r.left *= scale;
-            r.top *= scale;
-            r.right *= scale;
-            r.bottom *= scale;
-            r.offset(cx, cy);
-        }
-    }
-
-    /** Returns the base color overlaid with another overlay color with a specified alpha. */
-    public static int getColorWithOverlay(int baseColor, int overlayColor, float overlayAlpha) {
-        return Color.rgb(
-            (int) (overlayAlpha * Color.red(baseColor) +
-                    (1f - overlayAlpha) * Color.red(overlayColor)),
-            (int) (overlayAlpha * Color.green(baseColor) +
-                    (1f - overlayAlpha) * Color.green(overlayColor)),
-            (int) (overlayAlpha * Color.blue(baseColor) +
-                    (1f - overlayAlpha) * Color.blue(overlayColor)));
-    }
-
-    /**
-     * Cancels an animation ensuring that if it has listeners, onCancel and onEnd
-     * are not called.
-     */
-    public static void cancelAnimationWithoutCallbacks(Animator animator) {
-        if (animator != null && animator.isStarted()) {
-            removeAnimationListenersRecursive(animator);
-            animator.cancel();
-        }
-    }
-
-    /**
-     * Recursively removes all the listeners of all children of this animator
-     */
-    public static void removeAnimationListenersRecursive(Animator animator) {
-        if (animator instanceof AnimatorSet) {
-            ArrayList<Animator> animators = ((AnimatorSet) animator).getChildAnimations();
-            for (int i = animators.size() - 1; i >= 0; i--) {
-                removeAnimationListenersRecursive(animators.get(i));
-            }
-        }
-        animator.removeAllListeners();
-    }
-
-    /**
-     * Sets the given {@link View}'s frame from its current translation.
-     */
-    public static void setViewFrameFromTranslation(View v) {
-        RectF taskViewRect = new RectF(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
-        taskViewRect.offset(v.getTranslationX(), v.getTranslationY());
-        v.setTranslationX(0);
-        v.setTranslationY(0);
-        v.setLeftTopRightBottom((int) taskViewRect.left, (int) taskViewRect.top,
-                (int) taskViewRect.right, (int) taskViewRect.bottom);
-    }
-
-    /**
-     * Returns a view stub for the given view id.
-     */
-    public static ViewStub findViewStubById(View v, int stubId) {
-        return (ViewStub) v.findViewById(stubId);
-    }
-
-    /**
-     * Returns a view stub for the given view id.
-     */
-    public static ViewStub findViewStubById(Activity a, int stubId) {
-        return (ViewStub) a.findViewById(stubId);
-    }
-
-    /**
-     * Used for debugging, converts DP to PX.
-     */
-    public static float dpToPx(Resources res, float dp) {
-        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics());
-    }
-
-    /**
-     * Adds a trace event for debugging.
-     */
-    public static void addTraceEvent(String event) {
-        Trace.traceBegin(Trace.TRACE_TAG_VIEW, event);
-        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
-    }
-
-    /**
-     * Returns whether this view, or one of its descendants have accessibility focus.
-     */
-    public static boolean isDescendentAccessibilityFocused(View v) {
-        if (v.isAccessibilityFocused()) {
-            return true;
-        }
-
-        if (v instanceof ViewGroup) {
-            ViewGroup vg = (ViewGroup) v;
-            int childCount = vg.getChildCount();
-            for (int i = 0; i < childCount; i++) {
-                if (isDescendentAccessibilityFocused(vg.getChildAt(i))) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Returns the application configuration, which is independent of the activity's current
-     * configuration in multiwindow.
-     */
-    public static Configuration getAppConfiguration(Context context) {
-        return context.getApplicationContext().getResources().getConfiguration();
-    }
-
-    /**
-     * @return The next frame name for the specified surface or -1 if the surface is no longer
-     *         valid.
-     */
-    public static long getNextFrameNumber(Surface s) {
-        return s != null && s.isValid()
-                ? s.getNextFrameNumber()
-                : -1;
-
-    }
-
-    /**
-     * @return The surface for the specified view.
-     */
-    public static @Nullable Surface getSurface(View v) {
-        ViewRootImpl viewRoot = v.getViewRootImpl();
-        if (viewRoot == null) {
-            return null;
-        }
-        return viewRoot.mSurface;
-    }
-
-    /**
-     * Returns a lightweight dump of a rect.
-     */
-    public static String dumpRect(Rect r) {
-        if (r == null) {
-            return "N:0,0-0,0";
-        }
-        return r.left + "," + r.top + "-" + r.right + "," + r.bottom;
-    }
-
-    /**
-     * Posts a runnable on a handler at the front of the queue ignoring any sync barriers.
-     */
-    public static void postAtFrontOfQueueAsynchronously(Handler h, Runnable r) {
-        Message msg = h.obtainMessage().setCallback(r);
-        h.sendMessageAtFrontOfQueue(msg);
-    }
-
-    /** Calculates the constrast between two colors, using the algorithm provided by the WCAG v2. */
-    public static float computeContrastBetweenColors(int bg, int fg) {
-        float bgR = Color.red(bg) / 255f;
-        float bgG = Color.green(bg) / 255f;
-        float bgB = Color.blue(bg) / 255f;
-        bgR = (bgR < 0.03928f) ? bgR / 12.92f : (float) Math.pow((bgR + 0.055f) / 1.055f, 2.4f);
-        bgG = (bgG < 0.03928f) ? bgG / 12.92f : (float) Math.pow((bgG + 0.055f) / 1.055f, 2.4f);
-        bgB = (bgB < 0.03928f) ? bgB / 12.92f : (float) Math.pow((bgB + 0.055f) / 1.055f, 2.4f);
-        float bgL = 0.2126f * bgR + 0.7152f * bgG + 0.0722f * bgB;
-
-        float fgR = Color.red(fg) / 255f;
-        float fgG = Color.green(fg) / 255f;
-        float fgB = Color.blue(fg) / 255f;
-        fgR = (fgR < 0.03928f) ? fgR / 12.92f : (float) Math.pow((fgR + 0.055f) / 1.055f, 2.4f);
-        fgG = (fgG < 0.03928f) ? fgG / 12.92f : (float) Math.pow((fgG + 0.055f) / 1.055f, 2.4f);
-        fgB = (fgB < 0.03928f) ? fgB / 12.92f : (float) Math.pow((fgB + 0.055f) / 1.055f, 2.4f);
-        float fgL = 0.2126f * fgR + 0.7152f * fgG + 0.0722f * fgB;
-
-        return Math.abs((fgL + 0.05f) / (bgL + 0.05f));
-    }
-
-    /**
-     * @return the clamped {@param value} between the provided {@param min} and {@param max}.
-     */
-    public static float clamp(float value, float min, float max) {
-        return Math.max(min, Math.min(max, value));
-    }
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/AnimateableViewBounds.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/AnimateableViewBounds.java
deleted file mode 100644
index e188506..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/AnimateableViewBounds.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.graphics.Outline;
-import android.graphics.Rect;
-import android.view.View;
-import android.view.ViewOutlineProvider;
-
-import com.android.systemui.recents.utilities.Utilities;
-
-/**
- * An outline provider that has a clip and outline that can be animated.
- */
-public class AnimateableViewBounds extends ViewOutlineProvider {
-
-    private static final float MIN_ALPHA = 0.1f;
-    private static final float MAX_ALPHA = 0.8f;
-
-    protected View mSourceView;
-    protected Rect mClipRect = new Rect();
-    protected Rect mClipBounds = new Rect();
-    protected Rect mLastClipBounds = new Rect();
-    protected int mCornerRadius;
-    protected float mAlpha = 1f;
-
-    public AnimateableViewBounds(View source, int cornerRadius) {
-        mSourceView = source;
-        mCornerRadius = cornerRadius;
-    }
-
-    /**
-     * Resets the right and bottom clip for this view.
-     */
-    public void reset() {
-        mClipRect.set(0, 0, 0, 0);
-        updateClipBounds();
-    }
-
-    @Override
-    public void getOutline(View view, Outline outline) {
-        outline.setAlpha(Utilities.mapRange(mAlpha, MIN_ALPHA, MAX_ALPHA));
-        if (mCornerRadius > 0) {
-            outline.setRoundRect(mClipRect.left, mClipRect.top,
-                    mSourceView.getWidth() - mClipRect.right,
-                    mSourceView.getHeight() - mClipRect.bottom,
-                    mCornerRadius);
-        } else {
-            outline.setRect(mClipRect.left, mClipRect.top,
-                    mSourceView.getWidth() - mClipRect.right,
-                    mSourceView.getHeight() - mClipRect.bottom);
-        }
-    }
-
-    /**
-     * Sets the view outline alpha.
-     */
-    public void setAlpha(float alpha) {
-        if (Float.compare(alpha, mAlpha) != 0) {
-            mAlpha = alpha;
-            // TODO, If both clip and alpha change in the same frame, only invalidate once
-            mSourceView.invalidateOutline();
-        }
-    }
-
-    /**
-     * @return the outline alpha.
-     */
-    public float getAlpha() {
-        return mAlpha;
-    }
-
-    /**
-     * Sets the top clip.
-     */
-    public void setClipTop(int top) {
-        mClipRect.top = top;
-        updateClipBounds();
-    }
-
-    /**
-     * @return the top clip.
-     */
-    public int getClipTop() {
-        return mClipRect.top;
-    }
-
-    /**
-     * Sets the bottom clip.
-     */
-    public void setClipBottom(int bottom) {
-        mClipRect.bottom = bottom;
-        updateClipBounds();
-    }
-
-    /**
-     * @return the bottom clip.
-     */
-    public int getClipBottom() {
-        return mClipRect.bottom;
-    }
-
-    /**
-     * @return the clip bounds.
-     */
-    public Rect getClipBounds() {
-        return mClipBounds;
-    }
-
-    protected void updateClipBounds() {
-        mClipBounds.set(Math.max(0, mClipRect.left), Math.max(0, mClipRect.top),
-                mSourceView.getWidth() - Math.max(0, mClipRect.right),
-                mSourceView.getHeight() - Math.max(0, mClipRect.bottom));
-        if (!mLastClipBounds.equals(mClipBounds)) {
-            mSourceView.setClipBounds(mClipBounds);
-            // TODO, If both clip and alpha change in the same frame, only invalidate once
-            mSourceView.invalidateOutline();
-            mLastClipBounds.set(mClipBounds);
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/DockState.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/DockState.java
deleted file mode 100644
index d9c921c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/DockState.java
+++ /dev/null
@@ -1,351 +0,0 @@
-/*
- * 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.systemui.recents.views;
-
-import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT;
-import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
-import static android.view.WindowManager.DOCKED_BOTTOM;
-import static android.view.WindowManager.DOCKED_INVALID;
-import static android.view.WindowManager.DOCKED_LEFT;
-import static android.view.WindowManager.DOCKED_RIGHT;
-import static android.view.WindowManager.DOCKED_TOP;
-
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
-import android.animation.PropertyValuesHolder;
-import android.annotation.IntDef;
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.drawable.ColorDrawable;
-import android.util.IntProperty;
-import android.view.animation.Interpolator;
-
-import com.android.internal.policy.DockedDividerUtils;
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.utilities.Utilities;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-
-/**
- * The various possible dock states when dragging and dropping a task.
- */
-public class DockState implements DropTarget {
-
-    public static final int DOCK_AREA_BG_COLOR = 0xFFffffff;
-    public static final int DOCK_AREA_GRID_BG_COLOR = 0xFF000000;
-
-    // The rotation to apply to the hint text
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef({HORIZONTAL, VERTICAL})
-    public @interface TextOrientation {}
-    private static final int HORIZONTAL = 0;
-    private static final int VERTICAL = 1;
-
-    private static final int DOCK_AREA_ALPHA = 80;
-    public static final DockState NONE = new DockState(DOCKED_INVALID, -1, 80, 255, HORIZONTAL,
-            null, null, null);
-    public static final DockState LEFT = new DockState(DOCKED_LEFT,
-            SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, DOCK_AREA_ALPHA, 0, VERTICAL,
-            new RectF(0, 0, 0.125f, 1), new RectF(0, 0, 0.125f, 1),
-            new RectF(0, 0, 0.5f, 1));
-    public static final DockState TOP = new DockState(DOCKED_TOP,
-            SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, DOCK_AREA_ALPHA, 0, HORIZONTAL,
-            new RectF(0, 0, 1, 0.125f), new RectF(0, 0, 1, 0.125f),
-            new RectF(0, 0, 1, 0.5f));
-    public static final DockState RIGHT = new DockState(DOCKED_RIGHT,
-            SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT, DOCK_AREA_ALPHA, 0, VERTICAL,
-            new RectF(0.875f, 0, 1, 1), new RectF(0.875f, 0, 1, 1),
-            new RectF(0.5f, 0, 1, 1));
-    public static final DockState BOTTOM = new DockState(DOCKED_BOTTOM,
-            SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT, DOCK_AREA_ALPHA, 0, HORIZONTAL,
-            new RectF(0, 0.875f, 1, 1), new RectF(0, 0.875f, 1, 1),
-            new RectF(0, 0.5f, 1, 1));
-
-    @Override
-    public boolean acceptsDrop(int x, int y, int width, int height, Rect insets,
-            boolean isCurrentTarget) {
-        if (isCurrentTarget) {
-            getMappedRect(expandedTouchDockArea, width, height, mTmpRect);
-            return mTmpRect.contains(x, y);
-        } else {
-            getMappedRect(touchArea, width, height, mTmpRect);
-            updateBoundsWithSystemInsets(mTmpRect, insets);
-            return mTmpRect.contains(x, y);
-        }
-    }
-
-    // Represents the view state of this dock state
-    public static class ViewState {
-        private static final IntProperty<ViewState> HINT_ALPHA =
-                new IntProperty<ViewState>("drawableAlpha") {
-                    @Override
-                    public void setValue(ViewState object, int alpha) {
-                        object.mHintTextAlpha = alpha;
-                        object.dockAreaOverlay.invalidateSelf();
-                    }
-
-                    @Override
-                    public Integer get(ViewState object) {
-                        return object.mHintTextAlpha;
-                    }
-                };
-
-        public final int dockAreaAlpha;
-        public final ColorDrawable dockAreaOverlay;
-        public final int hintTextAlpha;
-        public final int hintTextOrientation;
-
-        private final int mHintTextResId;
-        private String mHintText;
-        private Paint mHintTextPaint;
-        private Point mHintTextBounds = new Point();
-        private int mHintTextAlpha = 255;
-        private AnimatorSet mDockAreaOverlayAnimator;
-        private Rect mTmpRect = new Rect();
-
-        private ViewState(int areaAlpha, int hintAlpha, @TextOrientation int hintOrientation,
-                int hintTextResId) {
-            dockAreaAlpha = areaAlpha;
-            dockAreaOverlay = new ColorDrawable(LegacyRecentsImpl.getConfiguration().isGridEnabled
-                    ? DOCK_AREA_GRID_BG_COLOR : DOCK_AREA_BG_COLOR);
-            dockAreaOverlay.setAlpha(0);
-            hintTextAlpha = hintAlpha;
-            hintTextOrientation = hintOrientation;
-            mHintTextResId = hintTextResId;
-            mHintTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
-            mHintTextPaint.setColor(Color.WHITE);
-        }
-
-        /**
-         * Updates the view state with the given context.
-         */
-        public void update(Context context) {
-            Resources res = context.getResources();
-            mHintText = context.getString(mHintTextResId);
-            mHintTextPaint.setTextSize(res.getDimensionPixelSize(
-                    R.dimen.recents_drag_hint_text_size));
-            mHintTextPaint.getTextBounds(mHintText, 0, mHintText.length(), mTmpRect);
-            mHintTextBounds.set((int) mHintTextPaint.measureText(mHintText), mTmpRect.height());
-        }
-
-        /**
-         * Draws the current view state.
-         */
-        public void draw(Canvas canvas) {
-            // Draw the overlay background
-            if (dockAreaOverlay.getAlpha() > 0) {
-                dockAreaOverlay.draw(canvas);
-            }
-
-            // Draw the hint text
-            if (mHintTextAlpha > 0) {
-                Rect bounds = dockAreaOverlay.getBounds();
-                int x = bounds.left + (bounds.width() - mHintTextBounds.x) / 2;
-                int y = bounds.top + (bounds.height() + mHintTextBounds.y) / 2;
-                mHintTextPaint.setAlpha(mHintTextAlpha);
-                if (hintTextOrientation == VERTICAL) {
-                    canvas.save();
-                    canvas.rotate(-90f, bounds.centerX(), bounds.centerY());
-                }
-                canvas.drawText(mHintText, x, y, mHintTextPaint);
-                if (hintTextOrientation == VERTICAL) {
-                    canvas.restore();
-                }
-            }
-        }
-
-        /**
-         * Creates a new bounds and alpha animation.
-         */
-        public void startAnimation(Rect bounds, int areaAlpha, int hintAlpha, int duration,
-                Interpolator interpolator, boolean animateAlpha, boolean animateBounds) {
-            if (mDockAreaOverlayAnimator != null) {
-                mDockAreaOverlayAnimator.cancel();
-            }
-
-            ObjectAnimator anim;
-            ArrayList<Animator> animators = new ArrayList<>();
-            if (dockAreaOverlay.getAlpha() != areaAlpha) {
-                if (animateAlpha) {
-                    anim = ObjectAnimator.ofInt(dockAreaOverlay,
-                            Utilities.DRAWABLE_ALPHA, dockAreaOverlay.getAlpha(), areaAlpha);
-                    anim.setDuration(duration);
-                    anim.setInterpolator(interpolator);
-                    animators.add(anim);
-                } else {
-                    dockAreaOverlay.setAlpha(areaAlpha);
-                }
-            }
-            if (mHintTextAlpha != hintAlpha) {
-                if (animateAlpha) {
-                    anim = ObjectAnimator.ofInt(this, HINT_ALPHA, mHintTextAlpha,
-                            hintAlpha);
-                    anim.setDuration(150);
-                    anim.setInterpolator(hintAlpha > mHintTextAlpha
-                            ? Interpolators.ALPHA_IN
-                            : Interpolators.ALPHA_OUT);
-                    animators.add(anim);
-                } else {
-                    mHintTextAlpha = hintAlpha;
-                    dockAreaOverlay.invalidateSelf();
-                }
-            }
-            if (bounds != null && !dockAreaOverlay.getBounds().equals(bounds)) {
-                if (animateBounds) {
-                    PropertyValuesHolder prop = PropertyValuesHolder.ofObject(
-                            Utilities.DRAWABLE_RECT, Utilities.RECT_EVALUATOR,
-                            new Rect(dockAreaOverlay.getBounds()), bounds);
-                    anim = ObjectAnimator.ofPropertyValuesHolder(dockAreaOverlay, prop);
-                    anim.setDuration(duration);
-                    anim.setInterpolator(interpolator);
-                    animators.add(anim);
-                } else {
-                    dockAreaOverlay.setBounds(bounds);
-                }
-            }
-            if (!animators.isEmpty()) {
-                mDockAreaOverlayAnimator = new AnimatorSet();
-                mDockAreaOverlayAnimator.playTogether(animators);
-                mDockAreaOverlayAnimator.start();
-            }
-        }
-    }
-
-    public final int dockSide;
-    public final int createMode;
-    public final ViewState viewState;
-    private final RectF touchArea;
-    private final RectF dockArea;
-    private final RectF expandedTouchDockArea;
-    private static final Rect mTmpRect = new Rect();
-
-    /**
-     * @param createMode used to pass to ActivityManager to dock the task
-     * @param touchArea the area in which touch will initiate this dock state
-     * @param dockArea the visible dock area
-     * @param expandedTouchDockArea the area in which touch will continue to dock after entering
-     *                              the initial touch area.  This is also the new dock area to
-     *                              draw.
-     */
-    DockState(int dockSide, int createMode, int dockAreaAlpha, int hintTextAlpha,
-            @TextOrientation int hintTextOrientation, RectF touchArea, RectF dockArea,
-            RectF expandedTouchDockArea) {
-        this.dockSide = dockSide;
-        this.createMode = createMode;
-        this.viewState = new ViewState(dockAreaAlpha, hintTextAlpha, hintTextOrientation,
-                R.string.recents_drag_hint_message);
-        this.dockArea = dockArea;
-        this.touchArea = touchArea;
-        this.expandedTouchDockArea = expandedTouchDockArea;
-    }
-
-    /**
-     * Updates the dock state with the given context.
-     */
-    public void update(Context context) {
-        viewState.update(context);
-    }
-
-    /**
-     * Returns the docked task bounds with the given {@param width} and {@param height}.
-     */
-    public Rect getPreDockedBounds(int width, int height, Rect insets) {
-        getMappedRect(dockArea, width, height, mTmpRect);
-        return updateBoundsWithSystemInsets(mTmpRect, insets);
-    }
-
-    /**
-     * Returns the expanded docked task bounds with the given {@param width} and
-     * {@param height}.
-     */
-    public Rect getDockedBounds(int width, int height, int dividerSize, Rect insets,
-            Resources res) {
-        // Calculate the docked task bounds
-        boolean isHorizontalDivision =
-                res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
-        int position = DockedDividerUtils.calculateMiddlePosition(isHorizontalDivision,
-                insets, width, height, dividerSize);
-        Rect newWindowBounds = new Rect();
-        DockedDividerUtils.calculateBoundsForPosition(position, dockSide, newWindowBounds,
-                width, height, dividerSize);
-        return newWindowBounds;
-    }
-
-    /**
-     * Returns the task stack bounds with the given {@param width} and
-     * {@param height}.
-     */
-    public Rect getDockedTaskStackBounds(Rect displayRect, int width, int height,
-            int dividerSize, Rect insets, TaskStackLayoutAlgorithm layoutAlgorithm,
-            Resources res, Rect windowRectOut) {
-        // Calculate the inverse docked task bounds
-        boolean isHorizontalDivision =
-                res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
-        int position = DockedDividerUtils.calculateMiddlePosition(isHorizontalDivision,
-                insets, width, height, dividerSize);
-        DockedDividerUtils.calculateBoundsForPosition(position,
-                DockedDividerUtils.invertDockSide(dockSide), windowRectOut, width, height,
-                dividerSize);
-
-        // Calculate the task stack bounds from the new window bounds
-        Rect taskStackBounds = new Rect();
-        // If the task stack bounds is specifically under the dock area, then ignore the top
-        // inset
-        int top = dockArea.bottom < 1f
-                ? 0
-                : insets.top;
-        // For now, ignore the left insets since we always dock on the left and show Recents
-        // on the right
-        layoutAlgorithm.getTaskStackBounds(displayRect, windowRectOut, top, 0, insets.right,
-                taskStackBounds);
-        return taskStackBounds;
-    }
-
-    /**
-     * Returns the expanded bounds in certain dock sides such that the bounds account for the
-     * system insets (namely the vertical nav bar).  This call modifies and returns the given
-     * {@param bounds}.
-     */
-    private Rect updateBoundsWithSystemInsets(Rect bounds, Rect insets) {
-        if (dockSide == DOCKED_LEFT) {
-            bounds.right += insets.left;
-        } else if (dockSide == DOCKED_RIGHT) {
-            bounds.left -= insets.right;
-        }
-        return bounds;
-    }
-
-    /**
-     * Returns the mapped rect to the given dimensions.
-     */
-    private void getMappedRect(RectF bounds, int width, int height, Rect out) {
-        out.set((int) (bounds.left * width), (int) (bounds.top * height),
-                (int) (bounds.right * width), (int) (bounds.bottom * height));
-    }
-}
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/DropTarget.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/DropTarget.java
deleted file mode 100644
index f2a6310..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/DropTarget.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.graphics.Rect;
-
-/**
- * Represents a drop target for a drag gesture.
- */
-public interface DropTarget {
-
-    /**
-     * Returns whether this target can accept this drop.  The x,y are relative to the top level
-     * RecentsView, and the width/height are of the RecentsView.
-     */
-    boolean acceptsDrop(int x, int y, int width, int height, Rect insets, boolean isCurrentTarget);
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FakeShadowDrawable.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FakeShadowDrawable.java
deleted file mode 100644
index 86b4297..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FakeShadowDrawable.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.content.res.Resources;
-import android.graphics.Canvas;
-import android.graphics.ColorFilter;
-import android.graphics.LinearGradient;
-import android.graphics.Paint;
-import android.graphics.Path;
-import android.graphics.PixelFormat;
-import android.graphics.RadialGradient;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.Shader;
-import android.graphics.drawable.Drawable;
-import android.util.Log;
-
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsConfiguration;
-
-/**
- * A rounded rectangle drawable which also includes a shadow around. This is mostly copied from
- * frameworks/support/v7/cardview/eclair-mr1/android/support/v7/widget/
- * RoundRectDrawableWithShadow.java revision c42ba8c000d1e6ce85e152dfc17089a0a69e739f with a few
- * modifications to suit our needs in SystemUI.
- */
-class FakeShadowDrawable extends Drawable {
-    // used to calculate content padding
-    final static double COS_45 = Math.cos(Math.toRadians(45));
-
-    final static float SHADOW_MULTIPLIER = 1.5f;
-
-    final float mInsetShadow; // extra shadow to avoid gaps between card and shadow
-
-    Paint mCornerShadowPaint;
-
-    Paint mEdgeShadowPaint;
-
-    final RectF mCardBounds;
-
-    float mCornerRadius;
-
-    Path mCornerShadowPath;
-
-    // updated value with inset
-    float mMaxShadowSize;
-
-    // actual value set by developer
-    float mRawMaxShadowSize;
-
-    // multiplied value to account for shadow offset
-    float mShadowSize;
-
-    // actual value set by developer
-    float mRawShadowSize;
-
-    private boolean mDirty = true;
-
-    private final int mShadowStartColor;
-
-    private final int mShadowEndColor;
-
-    private boolean mAddPaddingForCorners = true;
-
-    /**
-     * If shadow size is set to a value above max shadow, we print a warning
-     */
-    private boolean mPrintedShadowClipWarning = false;
-
-    public FakeShadowDrawable(Resources resources, RecentsConfiguration config) {
-        mShadowStartColor = resources.getColor(R.color.fake_shadow_start_color);
-        mShadowEndColor = resources.getColor(R.color.fake_shadow_end_color);
-        mInsetShadow = resources.getDimension(R.dimen.fake_shadow_inset);
-        setShadowSize(resources.getDimensionPixelSize(R.dimen.fake_shadow_size),
-                resources.getDimensionPixelSize(R.dimen.fake_shadow_size));
-        mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
-        mCornerShadowPaint.setStyle(Paint.Style.FILL);
-        mCornerShadowPaint.setDither(true);
-        mCornerRadius = LegacyRecentsImpl.getConfiguration().isGridEnabled ?
-                resources.getDimensionPixelSize(
-                    R.dimen.recents_grid_task_view_rounded_corners_radius) :
-                resources.getDimensionPixelSize(R.dimen.recents_task_view_rounded_corners_radius);
-        mCardBounds = new RectF();
-        mEdgeShadowPaint = new Paint(mCornerShadowPaint);
-    }
-
-    @Override
-    public void setAlpha(int alpha) {
-        mCornerShadowPaint.setAlpha(alpha);
-        mEdgeShadowPaint.setAlpha(alpha);
-    }
-
-    @Override
-    protected void onBoundsChange(Rect bounds) {
-        super.onBoundsChange(bounds);
-        mDirty = true;
-    }
-
-    void setShadowSize(float shadowSize, float maxShadowSize) {
-        if (shadowSize < 0 || maxShadowSize < 0) {
-            throw new IllegalArgumentException("invalid shadow size");
-        }
-        if (shadowSize > maxShadowSize) {
-            shadowSize = maxShadowSize;
-            if (!mPrintedShadowClipWarning) {
-                Log.w("CardView", "Shadow size is being clipped by the max shadow size. See "
-                        + "{CardView#setMaxCardElevation}.");
-                mPrintedShadowClipWarning = true;
-            }
-        }
-        if (mRawShadowSize == shadowSize && mRawMaxShadowSize == maxShadowSize) {
-            return;
-        }
-        mRawShadowSize = shadowSize;
-        mRawMaxShadowSize = maxShadowSize;
-        mShadowSize = shadowSize * SHADOW_MULTIPLIER + mInsetShadow;
-        mMaxShadowSize = maxShadowSize + mInsetShadow;
-        mDirty = true;
-        invalidateSelf();
-    }
-
-    @Override
-    public boolean getPadding(Rect padding) {
-        int vOffset = (int) Math.ceil(calculateVerticalPadding(mRawMaxShadowSize, mCornerRadius,
-                mAddPaddingForCorners));
-        int hOffset = (int) Math.ceil(calculateHorizontalPadding(mRawMaxShadowSize, mCornerRadius,
-                mAddPaddingForCorners));
-        padding.set(hOffset, vOffset, hOffset, vOffset);
-        return true;
-    }
-
-    static float calculateVerticalPadding(float maxShadowSize, float cornerRadius,
-            boolean addPaddingForCorners) {
-        if (addPaddingForCorners) {
-            return (float) (maxShadowSize * SHADOW_MULTIPLIER + (1 - COS_45) * cornerRadius);
-        } else {
-            return maxShadowSize * SHADOW_MULTIPLIER;
-        }
-    }
-
-    static float calculateHorizontalPadding(float maxShadowSize, float cornerRadius,
-            boolean addPaddingForCorners) {
-        if (addPaddingForCorners) {
-            return (float) (maxShadowSize + (1 - COS_45) * cornerRadius);
-        } else {
-            return maxShadowSize;
-        }
-    }
-
-    @Override
-    public void setColorFilter(ColorFilter colorFilter) {
-        mCornerShadowPaint.setColorFilter(colorFilter);
-        mEdgeShadowPaint.setColorFilter(colorFilter);
-    }
-
-    @Override
-    public int getOpacity() {
-        return PixelFormat.OPAQUE;
-    }
-
-    @Override
-    public void draw(Canvas canvas) {
-        if (mDirty) {
-            buildComponents(getBounds());
-            mDirty = false;
-        }
-        canvas.translate(0, mRawShadowSize / 4);
-        drawShadow(canvas);
-        canvas.translate(0, -mRawShadowSize / 4);
-    }
-
-    private void drawShadow(Canvas canvas) {
-        final float edgeShadowTop = -mCornerRadius - mShadowSize;
-        final float inset = mCornerRadius + mInsetShadow + mRawShadowSize / 2;
-        final boolean drawHorizontalEdges = mCardBounds.width() - 2 * inset > 0;
-        final boolean drawVerticalEdges = mCardBounds.height() - 2 * inset > 0;
-        // LT
-        int saved = canvas.save();
-        canvas.translate(mCardBounds.left + inset, mCardBounds.top + inset);
-        canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
-        if (drawHorizontalEdges) {
-            canvas.drawRect(0, edgeShadowTop,
-                    mCardBounds.width() - 2 * inset, -mCornerRadius,
-                    mEdgeShadowPaint);
-        }
-        canvas.restoreToCount(saved);
-        // RB
-        saved = canvas.save();
-        canvas.translate(mCardBounds.right - inset, mCardBounds.bottom - inset);
-        canvas.rotate(180f);
-        canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
-        if (drawHorizontalEdges) {
-            canvas.drawRect(0, edgeShadowTop,
-                    mCardBounds.width() - 2 * inset, -mCornerRadius + mShadowSize,
-                    mEdgeShadowPaint);
-        }
-        canvas.restoreToCount(saved);
-        // LB
-        saved = canvas.save();
-        canvas.translate(mCardBounds.left + inset, mCardBounds.bottom - inset);
-        canvas.rotate(270f);
-        canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
-        if (drawVerticalEdges) {
-            canvas.drawRect(0, edgeShadowTop,
-                    mCardBounds.height() - 2 * inset, -mCornerRadius, mEdgeShadowPaint);
-        }
-        canvas.restoreToCount(saved);
-        // RT
-        saved = canvas.save();
-        canvas.translate(mCardBounds.right - inset, mCardBounds.top + inset);
-        canvas.rotate(90f);
-        canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
-        if (drawVerticalEdges) {
-            canvas.drawRect(0, edgeShadowTop,
-                    mCardBounds.height() - 2 * inset, -mCornerRadius, mEdgeShadowPaint);
-        }
-        canvas.restoreToCount(saved);
-    }
-
-    private void buildShadowCorners() {
-        RectF innerBounds = new RectF(-mCornerRadius, -mCornerRadius, mCornerRadius, mCornerRadius);
-        RectF outerBounds = new RectF(innerBounds);
-        outerBounds.inset(-mShadowSize, -mShadowSize);
-
-        if (mCornerShadowPath == null) {
-            mCornerShadowPath = new Path();
-        } else {
-            mCornerShadowPath.reset();
-        }
-        mCornerShadowPath.setFillType(Path.FillType.EVEN_ODD);
-        mCornerShadowPath.moveTo(-mCornerRadius, 0);
-        mCornerShadowPath.rLineTo(-mShadowSize, 0);
-        // outer arc
-        mCornerShadowPath.arcTo(outerBounds, 180f, 90f, false);
-        // inner arc
-        mCornerShadowPath.arcTo(innerBounds, 270f, -90f, false);
-        mCornerShadowPath.close();
-
-        float startRatio = mCornerRadius / (mCornerRadius + mShadowSize);
-        mCornerShadowPaint.setShader(new RadialGradient(0, 0, mCornerRadius + mShadowSize,
-                new int[]{mShadowStartColor, mShadowStartColor, mShadowEndColor},
-                new float[]{0f, startRatio, 1f}
-                , Shader.TileMode.CLAMP));
-
-        // we offset the content shadowSize/2 pixels up to make it more realistic.
-        // this is why edge shadow shader has some extra space
-        // When drawing bottom edge shadow, we use that extra space.
-        mEdgeShadowPaint.setShader(new LinearGradient(0, -mCornerRadius + mShadowSize, 0,
-                -mCornerRadius - mShadowSize,
-                new int[]{mShadowStartColor, mShadowStartColor, mShadowEndColor},
-                new float[]{0f, .5f, 1f}, Shader.TileMode.CLAMP));
-    }
-
-    private void buildComponents(Rect bounds) {
-        // Card is offset SHADOW_MULTIPLIER * maxShadowSize to account for the shadow shift.
-        // We could have different top-bottom offsets to avoid extra gap above but in that case
-        // center aligning Views inside the CardView would be problematic.
-        final float verticalOffset = mMaxShadowSize * SHADOW_MULTIPLIER;
-        mCardBounds.set(bounds.left + mMaxShadowSize, bounds.top + verticalOffset,
-                bounds.right - mMaxShadowSize, bounds.bottom - verticalOffset);
-        buildShadowCorners();
-    }
-
-    float getMinWidth() {
-        final float content = 2 *
-                Math.max(mRawMaxShadowSize, mCornerRadius + mInsetShadow + mRawMaxShadowSize / 2);
-        return content + (mRawMaxShadowSize + mInsetShadow) * 2;
-    }
-
-    float getMinHeight() {
-        final float content = 2 * Math.max(mRawMaxShadowSize, mCornerRadius + mInsetShadow
-                        + mRawMaxShadowSize * SHADOW_MULTIPLIER / 2);
-        return content + (mRawMaxShadowSize * SHADOW_MULTIPLIER + mInsetShadow) * 2;
-    }
-}
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FixedSizeFrameLayout.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FixedSizeFrameLayout.java
deleted file mode 100644
index 471df6a..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FixedSizeFrameLayout.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.views;
-
-import android.content.Context;
-import android.graphics.Rect;
-import android.util.AttributeSet;
-import android.widget.FrameLayout;
-
-/**
- * This is an optimized FrameLayout whose layout is completely directed by its parent, and as a
- * result, does not propagate <code>requestLayout()</code> up the view hierarchy. Instead, it will
- * relayout its children with the last known layout bounds when a layout is requested from a child
- * view.
- */
-public class FixedSizeFrameLayout extends FrameLayout {
-
-    private final Rect mLayoutBounds = new Rect();
-
-    public FixedSizeFrameLayout(Context context) {
-        super(context);
-    }
-
-    public FixedSizeFrameLayout(Context context, AttributeSet attrs) {
-        super(context, attrs);
-    }
-
-    public FixedSizeFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
-        super(context, attrs, defStyleAttr);
-    }
-
-    public FixedSizeFrameLayout(Context context, AttributeSet attrs, int defStyleAttr,
-            int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-    }
-
-    @Override
-    protected final void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-        measureContents(MeasureSpec.getSize(widthMeasureSpec),
-                MeasureSpec.getSize(heightMeasureSpec));
-    }
-
-    @Override
-    protected final void onLayout(boolean changed, int left, int top, int right, int bottom) {
-        mLayoutBounds.set(left, top, right, bottom);
-        layoutContents(mLayoutBounds, changed);
-    }
-
-    @Override
-    public final void requestLayout() {
-        // The base ViewGroup constructor attempts to call requestLayout() before this class's
-        // members are initialized so we should just propagate in that case
-        if (mLayoutBounds == null || mLayoutBounds.isEmpty()) {
-            super.requestLayout();
-        } else {
-            // If we are already laid out, then just reuse the same bounds to layout the children
-            // (but not itself)
-            // TODO: Investigate whether we should coalesce these to the next frame if needed
-            measureContents(getMeasuredWidth(), getMeasuredHeight());
-            layoutContents(mLayoutBounds, false);
-        }
-    }
-
-    /**
-     * Measures the contents of this fixed layout.
-     */
-    protected void measureContents(int width, int height) {
-        super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
-                MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
-    }
-
-    /**
-     * Lays out the contents of this fixed layout.
-     */
-    protected void layoutContents(Rect bounds, boolean changed) {
-        super.onLayout(changed, bounds.left, bounds.top, bounds.right, bounds.bottom);
-
-        int width = getMeasuredWidth();
-        int height = getMeasuredHeight();
-        onSizeChanged(width, height, width, height);
-    }
-
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FixedSizeImageView.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FixedSizeImageView.java
deleted file mode 100644
index d3b5e47..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/FixedSizeImageView.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.content.Context;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.util.AttributeSet;
-
-import com.android.systemui.statusbar.AlphaOptimizedImageView;
-
-/**
- * This is an optimized ImageView that does not trigger a <code>requestLayout()</code> or
- * <code>invalidate()</code> when setting the image to <code>null</code>.
- */
-public class FixedSizeImageView extends AlphaOptimizedImageView {
-
-    private boolean mAllowRelayout = true;
-    private boolean mAllowInvalidate = true;
-
-    public FixedSizeImageView(Context context) {
-        this(context, null);
-    }
-
-    public FixedSizeImageView(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public FixedSizeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public FixedSizeImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-    }
-
-    @Override
-    public void requestLayout() {
-        if (mAllowRelayout) {
-            super.requestLayout();
-        }
-    }
-
-    @Override
-    public void invalidate() {
-        if (mAllowInvalidate) {
-            super.invalidate();
-        }
-    }
-
-    @Override
-    public void setImageDrawable(Drawable drawable) {
-        boolean isNullBitmapDrawable = (drawable instanceof BitmapDrawable) &&
-                (((BitmapDrawable) drawable).getBitmap() == null);
-        if (drawable == null || isNullBitmapDrawable) {
-            mAllowRelayout = false;
-            mAllowInvalidate = false;
-        }
-        super.setImageDrawable(drawable);
-        mAllowRelayout = true;
-        mAllowInvalidate = true;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsEntrancePathInterpolator.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsEntrancePathInterpolator.java
deleted file mode 100644
index e32da2d..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsEntrancePathInterpolator.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.systemui.recents.views;
-
-import android.view.animation.PathInterpolator;
-
-/**
- * A helper interpolator to stagger the entrance animation in recents by offsetting the start time
- */
-public class RecentsEntrancePathInterpolator extends PathInterpolator {
-    final float mStartOffsetFraction;
-
-    /**
-     * Create an interpolator for a cubic Bezier curve with an offset play time. The end points
-     * <code>(0, 0)</code> and <code>(1, 1)</code> are assumed.
-     *
-     * @param controlX1 The x coordinate of the first control point of the cubic Bezier.
-     * @param controlY1 The y coordinate of the first control point of the cubic Bezier.
-     * @param controlX2 The x coordinate of the second control point of the cubic Bezier.
-     * @param controlY2 The y coordinate of the second control point of the cubic Bezier.
-     * @param startOffsetFraction The fraction from 0 to 1 to start the animation from
-     */
-    public RecentsEntrancePathInterpolator(float controlX1, float controlY1, float controlX2,
-            float controlY2, float startOffsetFraction) {
-        super(controlX1, controlY1, controlX2, controlY2);
-        mStartOffsetFraction = startOffsetFraction;
-    }
-
-    @Override
-    public float getInterpolation(float t) {
-        return super.getInterpolation(t + mStartOffsetFraction);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsTransitionComposer.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsTransitionComposer.java
deleted file mode 100644
index ce66318..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsTransitionComposer.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
-import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
-import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
-import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
-import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.Rect;
-import android.util.Log;
-
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsDebugFlags;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.view.AppTransitionAnimationSpecCompat;
-import com.android.systemui.shared.recents.view.RecentsTransition;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A helper class to create the transition app animation specs to/from Recents
- */
-public class RecentsTransitionComposer {
-
-    private static final String TAG = "RecentsTransitionComposer";
-
-    private Context mContext;
-    private TaskViewTransform mTmpTransform = new TaskViewTransform();
-
-    public RecentsTransitionComposer(Context context) {
-        mContext = context;
-    }
-
-    /**
-     * Composes a single animation spec for the given {@link TaskView}
-     */
-    private static AppTransitionAnimationSpecCompat composeAnimationSpec(TaskStackView stackView,
-            TaskView taskView, TaskViewTransform transform, boolean addHeaderBitmap) {
-        Bitmap b = null;
-        if (addHeaderBitmap) {
-            b = composeHeaderBitmap(taskView, transform);
-            if (b == null) {
-                return null;
-            }
-        }
-
-        Rect taskRect = new Rect();
-        transform.rect.round(taskRect);
-        // Disable in for low ram devices because each task does in Recents does not have fullscreen
-        // height (stackView height) and when transitioning to fullscreen app, the code below would
-        // force the task thumbnail to full stackView height immediately causing the transition
-        // jarring.
-        if (!LegacyRecentsImpl.getConfiguration().isLowRamDevice && taskView.getTask() !=
-                stackView.getStack().getFrontMostTask()) {
-            taskRect.bottom = taskRect.top + stackView.getMeasuredHeight();
-        }
-        return new AppTransitionAnimationSpecCompat(taskView.getTask().key.id, b, taskRect);
-    }
-
-    /**
-     * Composes the transition spec when docking a task, which includes a full task bitmap.
-     */
-    public List<AppTransitionAnimationSpecCompat> composeDockAnimationSpec(TaskView taskView,
-            Rect bounds) {
-        mTmpTransform.fillIn(taskView);
-        Task task = taskView.getTask();
-        Bitmap buffer = RecentsTransitionComposer.composeTaskBitmap(taskView, mTmpTransform);
-        return Collections.singletonList(new AppTransitionAnimationSpecCompat(task.key.id, buffer,
-                bounds));
-    }
-
-    /**
-     * Composes the animation specs for all the tasks in the target stack.
-     */
-    public List<AppTransitionAnimationSpecCompat> composeAnimationSpecs(final Task task,
-            final TaskStackView stackView, int windowingMode, int activityType, Rect windowRect) {
-        // Calculate the offscreen task rect (for tasks that are not backed by views)
-        TaskView taskView = stackView.getChildViewForTask(task);
-        TaskStackLayoutAlgorithm stackLayout = stackView.getStackAlgorithm();
-        Rect offscreenTaskRect = new Rect();
-        stackLayout.getFrontOfStackTransform().rect.round(offscreenTaskRect);
-
-        // If this is a full screen stack, the transition will be towards the single, full screen
-        // task. We only need the transition spec for this task.
-
-        // TODO: Sometimes targetStackId is not initialized after reboot, so we also have to
-        // check for INVALID_STACK_ID (now WINDOWING_MODE_UNDEFINED)
-        if (windowingMode == WINDOWING_MODE_FULLSCREEN
-                || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
-                || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
-                || activityType == ACTIVITY_TYPE_ASSISTANT
-                || windowingMode == WINDOWING_MODE_UNDEFINED) {
-            List<AppTransitionAnimationSpecCompat> specs = new ArrayList<>();
-            if (taskView == null) {
-                specs.add(composeOffscreenAnimationSpec(task, offscreenTaskRect));
-            } else {
-                mTmpTransform.fillIn(taskView);
-                stackLayout.transformToScreenCoordinates(mTmpTransform, windowRect);
-                AppTransitionAnimationSpecCompat spec = composeAnimationSpec(stackView, taskView,
-                        mTmpTransform, true /* addHeaderBitmap */);
-                if (spec != null) {
-                    specs.add(spec);
-                }
-            }
-            return specs;
-        }
-        return Collections.emptyList();
-    }
-
-    /**
-     * Composes a single animation spec for the given {@link Task}
-     */
-    private static AppTransitionAnimationSpecCompat composeOffscreenAnimationSpec(Task task,
-            Rect taskRect) {
-        return new AppTransitionAnimationSpecCompat(task.key.id, null, taskRect);
-    }
-
-    public static Bitmap composeTaskBitmap(TaskView taskView, TaskViewTransform transform) {
-        float scale = transform.scale;
-        int fromWidth = (int) (transform.rect.width() * scale);
-        int fromHeight = (int) (transform.rect.height() * scale);
-        if (fromWidth == 0 || fromHeight == 0) {
-            Log.e(TAG, "Could not compose thumbnail for task: " + taskView.getTask() +
-                    " at transform: " + transform);
-
-            return RecentsTransition.drawViewIntoHardwareBitmap(1, 1, null, 1f, 0x00ffffff);
-        } else {
-            if (RecentsDebugFlags.Static.EnableTransitionThumbnailDebugMode) {
-                return RecentsTransition.drawViewIntoHardwareBitmap(fromWidth, fromHeight, null, 1f,
-                        0xFFff0000);
-            } else {
-                return RecentsTransition.drawViewIntoHardwareBitmap(fromWidth, fromHeight, taskView,
-                        scale, 0);
-            }
-        }
-    }
-
-    private static Bitmap composeHeaderBitmap(TaskView taskView,
-            TaskViewTransform transform) {
-        float scale = transform.scale;
-        int headerWidth = (int) (transform.rect.width());
-        int headerHeight = (int) (taskView.mHeaderView.getMeasuredHeight() * scale);
-        if (headerWidth == 0 || headerHeight == 0) {
-            return null;
-        }
-
-        if (RecentsDebugFlags.Static.EnableTransitionThumbnailDebugMode) {
-            return RecentsTransition.drawViewIntoHardwareBitmap(headerWidth, headerHeight, null, 1f,
-                    0xFFff0000);
-        } else {
-            return RecentsTransition.drawViewIntoHardwareBitmap(headerWidth, headerHeight,
-                    taskView.mHeaderView, scale, 0);
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsView.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsView.java
deleted file mode 100644
index e60ffba..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsView.java
+++ /dev/null
@@ -1,1077 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
-
-import static com.android.systemui.statusbar.phone.StatusBar.SYSTEM_DIALOG_REASON_RECENT_APPS;
-
-import android.animation.ValueAnimator;
-import android.animation.ValueAnimator.AnimatorUpdateListener;
-import android.annotation.Nullable;
-import android.app.ActivityOptions;
-import android.content.Context;
-import android.content.res.ColorStateList;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Point;
-import android.graphics.PointF;
-import android.graphics.Rect;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.Drawable;
-import android.os.Handler;
-import android.util.ArraySet;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.util.MathUtils;
-import android.view.LayoutInflater;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.ViewDebug;
-import android.view.ViewPropertyAnimator;
-import android.view.Window;
-import android.view.WindowInsets;
-import android.widget.FrameLayout;
-import android.widget.TextView;
-
-import com.android.internal.colorextraction.ColorExtractor;
-import com.android.internal.colorextraction.drawable.ScrimDrawable;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settingslib.Utils;
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsActivity;
-import com.android.systemui.recents.RecentsActivityLaunchState;
-import com.android.systemui.recents.RecentsConfiguration;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.CancelEnterRecentsWindowAnimationEvent;
-import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
-import com.android.systemui.recents.events.activity.DockedFirstAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.EnterRecentsWindowAnimationCompletedEvent;
-import com.android.systemui.recents.events.activity.ExitRecentsWindowFirstAnimationFrameEvent;
-import com.android.systemui.recents.events.activity.HideStackActionButtonEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskFailedEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskStartedEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskSucceededEvent;
-import com.android.systemui.recents.events.activity.MultiWindowStateChangedEvent;
-import com.android.systemui.recents.events.activity.ShowEmptyViewEvent;
-import com.android.systemui.recents.events.activity.ShowStackActionButtonEvent;
-import com.android.systemui.recents.events.component.ExpandPipEvent;
-import com.android.systemui.recents.events.component.ScreenPinningRequestEvent;
-import com.android.systemui.recents.events.component.SetWaitingForTransitionStartEvent;
-import com.android.systemui.recents.events.ui.AllTaskViewsDismissedEvent;
-import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
-import com.android.systemui.recents.events.ui.DraggingInRecentsEndedEvent;
-import com.android.systemui.recents.events.ui.DraggingInRecentsEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragDropTargetChangedEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndCancelledEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
-import com.android.systemui.recents.misc.ReferenceCountedTrigger;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.view.AppTransitionAnimationSpecCompat;
-import com.android.systemui.shared.recents.view.AppTransitionAnimationSpecsFuture;
-import com.android.systemui.shared.recents.view.RecentsTransition;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-import com.android.systemui.shared.system.ActivityOptionsCompat;
-import com.android.systemui.shared.system.WindowManagerWrapper;
-import com.android.systemui.stackdivider.WindowManagerProxy;
-import com.android.systemui.statusbar.FlingAnimationUtils;
-import com.android.systemui.statusbar.phone.ScrimController;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This view is the the top level layout that contains TaskStacks (which are laid out according
- * to their SpaceNode bounds.
- */
-public class RecentsView extends FrameLayout {
-
-    private static final String TAG = "RecentsView";
-
-    private static final int DEFAULT_UPDATE_SCRIM_DURATION = 200;
-
-    private static final int SHOW_STACK_ACTION_BUTTON_DURATION = 134;
-    private static final int HIDE_STACK_ACTION_BUTTON_DURATION = 100;
-
-    private static final int BUSY_RECENTS_TASK_COUNT = 3;
-
-    private Handler mHandler;
-    private TaskStackView mTaskStackView;
-    private TextView mStackActionButton;
-    private TextView mEmptyView;
-    private final float mStackButtonShadowRadius;
-    private final PointF mStackButtonShadowDistance;
-    private final int mStackButtonShadowColor;
-
-    private boolean mAwaitingFirstLayout = true;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    Rect mSystemInsets = new Rect();
-    private int mDividerSize;
-
-    private float mBusynessFactor;
-    private ScrimDrawable mBackgroundScrim;
-    private ColorDrawable mMultiWindowBackgroundScrim;
-    private ValueAnimator mBackgroundScrimAnimator;
-    private Point mTmpDisplaySize = new Point();
-
-    private final AnimatorUpdateListener mUpdateBackgroundScrimAlpha = (animation) -> {
-        int alpha = (Integer) animation.getAnimatedValue();
-        mBackgroundScrim.setAlpha(alpha);
-        mMultiWindowBackgroundScrim.setAlpha(alpha);
-    };
-
-    private RecentsTransitionComposer mTransitionHelper;
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="touch_")
-    private RecentsViewTouchHandler mTouchHandler;
-    private final FlingAnimationUtils mFlingAnimationUtils;
-
-    public RecentsView(Context context) {
-        this(context, null);
-    }
-
-    public RecentsView(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public RecentsView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-        setWillNotDraw(false);
-
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        mHandler = new Handler();
-        mTransitionHelper = new RecentsTransitionComposer(getContext());
-        mDividerSize = ssp.getDockedDividerSize(context);
-        mTouchHandler = new RecentsViewTouchHandler(this);
-        mFlingAnimationUtils = new FlingAnimationUtils(context, 0.3f);
-        mBackgroundScrim = new ScrimDrawable();
-        mMultiWindowBackgroundScrim = new ColorDrawable();
-
-        LayoutInflater inflater = LayoutInflater.from(context);
-        mEmptyView = (TextView) inflater.inflate(R.layout.recents_empty, this, false);
-        addView(mEmptyView);
-
-        if (mStackActionButton != null) {
-            removeView(mStackActionButton);
-        }
-        mStackActionButton = (TextView) inflater.inflate(LegacyRecentsImpl.getConfiguration()
-                        .isLowRamDevice
-                    ? R.layout.recents_low_ram_stack_action_button
-                    : R.layout.recents_stack_action_button,
-                this, false);
-
-        mStackButtonShadowRadius = mStackActionButton.getShadowRadius();
-        mStackButtonShadowDistance = new PointF(mStackActionButton.getShadowDx(),
-                mStackActionButton.getShadowDy());
-        mStackButtonShadowColor = mStackActionButton.getShadowColor();
-        addView(mStackActionButton);
-
-        reevaluateStyles();
-    }
-
-    public void reevaluateStyles() {
-        int textColor = Utils.getColorAttrDefaultColor(mContext, R.attr.wallpaperTextColor);
-        boolean usingDarkText = Color.luminance(textColor) < 0.5f;
-
-        mEmptyView.setTextColor(textColor);
-        mEmptyView.setCompoundDrawableTintList(new ColorStateList(new int[][]{
-                {android.R.attr.state_enabled}}, new int[]{textColor}));
-
-        if (mStackActionButton != null) {
-            mStackActionButton.setTextColor(textColor);
-            // Enable/disable shadow if text color is already dark.
-            if (usingDarkText) {
-                mStackActionButton.setShadowLayer(0, 0, 0, 0);
-            } else {
-                mStackActionButton.setShadowLayer(mStackButtonShadowRadius,
-                        mStackButtonShadowDistance.x, mStackButtonShadowDistance.y,
-                        mStackButtonShadowColor);
-            }
-        }
-
-        // Let's also require dark status and nav bars if the text is dark
-        int systemBarsStyle = usingDarkText ? View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR |
-                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : 0;
-
-        setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
-                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
-                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
-                systemBarsStyle);
-    }
-
-    /**
-     * Called from RecentsActivity when it is relaunched.
-     */
-    public void onReload(TaskStack stack, boolean isResumingFromVisible) {
-        final RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        final RecentsActivityLaunchState launchState = config.getLaunchState();
-        final boolean isTaskStackEmpty = stack.getTaskCount() == 0;
-
-        if (mTaskStackView == null) {
-            isResumingFromVisible = false;
-            mTaskStackView = new TaskStackView(getContext());
-            mTaskStackView.setSystemInsets(mSystemInsets);
-            addView(mTaskStackView);
-        }
-
-        // Reset the state
-        mAwaitingFirstLayout = !isResumingFromVisible;
-
-        // Update the stack
-        mTaskStackView.onReload(isResumingFromVisible);
-        updateStack(stack, true /* setStackViewTasks */);
-        updateBusyness();
-
-        if (isResumingFromVisible) {
-            // If we are already visible, then restore the background scrim
-            animateBackgroundScrim(getOpaqueScrimAlpha(), DEFAULT_UPDATE_SCRIM_DURATION);
-        } else {
-            // If we are already occluded by the app, then set the final background scrim alpha now.
-            // Otherwise, defer until the enter animation completes to animate the scrim alpha with
-            // the tasks for the home animation.
-            if (launchState.launchedViaDockGesture || launchState.launchedFromApp
-                    || isTaskStackEmpty) {
-                mBackgroundScrim.setAlpha((int) (getOpaqueScrimAlpha() * 255));
-            } else {
-                mBackgroundScrim.setAlpha(0);
-            }
-            mMultiWindowBackgroundScrim.setAlpha(mBackgroundScrim.getAlpha());
-        }
-    }
-
-    /**
-     * Called from RecentsActivity when the task stack is updated.
-     */
-    public void updateStack(TaskStack stack, boolean setStackViewTasks) {
-        if (setStackViewTasks) {
-            mTaskStackView.setTasks(stack, true /* allowNotifyStackChanges */);
-        }
-
-        // Update the top level view's visibilities
-        if (stack.getTaskCount() > 0) {
-            hideEmptyView();
-        } else {
-            showEmptyView(R.string.recents_empty_message);
-        }
-    }
-
-    /**
-     * Animates the scrim opacity based on how many tasks are visible.
-     * Called from {@link RecentsActivity} when tasks are dismissed.
-     */
-    public void updateScrimOpacity() {
-        if (updateBusyness()) {
-            animateBackgroundScrim(getOpaqueScrimAlpha(), DEFAULT_UPDATE_SCRIM_DURATION);
-        }
-    }
-
-    /**
-     * Updates the busyness factor.
-     *
-     * @return True if it changed.
-     */
-    private boolean updateBusyness() {
-        final int taskCount = mTaskStackView.getStack().getTaskCount();
-        final float busyness = Math.min(taskCount, BUSY_RECENTS_TASK_COUNT)
-                / (float) BUSY_RECENTS_TASK_COUNT;
-        if (mBusynessFactor == busyness) {
-            return false;
-        } else {
-            mBusynessFactor = busyness;
-            return true;
-        }
-    }
-
-    /**
-     * Returns the current TaskStack.
-     */
-    public TaskStack getStack() {
-        return mTaskStackView.getStack();
-    }
-
-    /**
-     * Returns the window background scrim.
-     */
-    public void updateBackgroundScrim(Window window, boolean isInMultiWindow) {
-        if (isInMultiWindow) {
-            mBackgroundScrim.setCallback(null);
-            window.setBackgroundDrawable(mMultiWindowBackgroundScrim);
-        } else {
-            mMultiWindowBackgroundScrim.setCallback(null);
-            window.setBackgroundDrawable(mBackgroundScrim);
-        }
-    }
-
-    /** Launches the focused task from the first stack if possible */
-    public boolean launchFocusedTask(int logEvent) {
-        if (mTaskStackView != null) {
-            Task task = mTaskStackView.getFocusedTask();
-            if (task != null) {
-                TaskView taskView = mTaskStackView.getChildViewForTask(task);
-                EventBus.getDefault().send(new LaunchTaskEvent(taskView, task, null, false));
-
-                if (logEvent != 0) {
-                    MetricsLogger.action(getContext(), logEvent,
-                            task.key.getComponent().toString());
-                }
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /** Launches the task that recents was launched from if possible */
-    public boolean launchPreviousTask() {
-        if (LegacyRecentsImpl.getConfiguration().getLaunchState().launchedFromPipApp) {
-            // If the app auto-entered PiP on the way to Recents, then just re-expand it
-            EventBus.getDefault().send(new ExpandPipEvent());
-            return true;
-        }
-
-        if (mTaskStackView != null) {
-            Task task = getStack().getLaunchTarget();
-            if (task != null) {
-                TaskView taskView = mTaskStackView.getChildViewForTask(task);
-                EventBus.getDefault().send(new LaunchTaskEvent(taskView, task, null, false));
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Hides the task stack and shows the empty view.
-     */
-    public void showEmptyView(int msgResId) {
-        mTaskStackView.setVisibility(View.INVISIBLE);
-        mEmptyView.setText(msgResId);
-        mEmptyView.setVisibility(View.VISIBLE);
-        mEmptyView.bringToFront();
-        mStackActionButton.bringToFront();
-    }
-
-    /**
-     * Shows the task stack and hides the empty view.
-     */
-    public void hideEmptyView() {
-        mEmptyView.setVisibility(View.INVISIBLE);
-        mTaskStackView.setVisibility(View.VISIBLE);
-        mTaskStackView.bringToFront();
-        mStackActionButton.bringToFront();
-    }
-
-    /**
-     * Set the color of the scrim.
-     *
-     * @param scrimColors Colors to use.
-     * @param animated Interpolate colors if true.
-     */
-    public void setScrimColors(ColorExtractor.GradientColors scrimColors, boolean animated) {
-        mBackgroundScrim.setColor(scrimColors.getMainColor(), animated);
-        int alpha = mMultiWindowBackgroundScrim.getAlpha();
-        mMultiWindowBackgroundScrim.setColor(scrimColors.getMainColor());
-        mMultiWindowBackgroundScrim.setAlpha(alpha);
-    }
-
-    @Override
-    protected void onAttachedToWindow() {
-        EventBus.getDefault().register(this, RecentsActivity.EVENT_BUS_PRIORITY + 1);
-        EventBus.getDefault().register(mTouchHandler, RecentsActivity.EVENT_BUS_PRIORITY + 2);
-        super.onAttachedToWindow();
-    }
-
-    @Override
-    protected void onDetachedFromWindow() {
-        super.onDetachedFromWindow();
-        EventBus.getDefault().unregister(this);
-        EventBus.getDefault().unregister(mTouchHandler);
-    }
-
-    /**
-     * This is called with the full size of the window since we are handling our own insets.
-     */
-    @Override
-    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-        int width = MeasureSpec.getSize(widthMeasureSpec);
-        int height = MeasureSpec.getSize(heightMeasureSpec);
-
-        if (mTaskStackView.getVisibility() != GONE) {
-            mTaskStackView.measure(widthMeasureSpec, heightMeasureSpec);
-        }
-
-        // Measure the empty view to the full size of the screen
-        if (mEmptyView.getVisibility() != GONE) {
-            measureChild(mEmptyView, MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
-                    MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
-        }
-
-        // Measure the stack action button within the constraints of the space above the stack
-        Rect buttonBounds = mTaskStackView.mLayoutAlgorithm.getStackActionButtonRect();
-        measureChild(mStackActionButton,
-                MeasureSpec.makeMeasureSpec(buttonBounds.width(), MeasureSpec.AT_MOST),
-                MeasureSpec.makeMeasureSpec(buttonBounds.height(), MeasureSpec.AT_MOST));
-
-        setMeasuredDimension(width, height);
-    }
-
-    /**
-     * This is called with the full size of the window since we are handling our own insets.
-     */
-    @Override
-    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
-        if (mTaskStackView.getVisibility() != GONE) {
-            mTaskStackView.layout(left, top, left + getMeasuredWidth(), top + getMeasuredHeight());
-        }
-
-        // Layout the empty view
-        if (mEmptyView.getVisibility() != GONE) {
-            int leftRightInsets = mSystemInsets.left + mSystemInsets.right;
-            int topBottomInsets = mSystemInsets.top + mSystemInsets.bottom;
-            int childWidth = mEmptyView.getMeasuredWidth();
-            int childHeight = mEmptyView.getMeasuredHeight();
-            int childLeft = left + mSystemInsets.left +
-                    Math.max(0, (right - left - leftRightInsets - childWidth)) / 2;
-            int childTop = top + mSystemInsets.top +
-                    Math.max(0, (bottom - top - topBottomInsets - childHeight)) / 2;
-            mEmptyView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
-        }
-
-        // Needs to know the screen size since the gradient never scales up or down
-        // even when bounds change.
-        mContext.getDisplay().getRealSize(mTmpDisplaySize);
-        mBackgroundScrim.setBounds(left, top, right, bottom);
-        mMultiWindowBackgroundScrim.setBounds(0, 0, mTmpDisplaySize.x, mTmpDisplaySize.y);
-
-        // Layout the stack action button such that its drawable is start-aligned with the
-        // stack, vertically centered in the available space above the stack
-        Rect buttonBounds = getStackActionButtonBoundsFromStackLayout();
-        mStackActionButton.layout(buttonBounds.left, buttonBounds.top, buttonBounds.right,
-                buttonBounds.bottom);
-
-        if (mAwaitingFirstLayout) {
-            mAwaitingFirstLayout = false;
-            // If launched via dragging from the nav bar, then we should translate the whole view
-            // down offscreen
-            RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-            if (launchState.launchedViaDragGesture) {
-                setTranslationY(getMeasuredHeight());
-            } else {
-                setTranslationY(0f);
-            }
-
-            if (LegacyRecentsImpl.getConfiguration().isLowRamDevice
-                    && mEmptyView.getVisibility() == View.VISIBLE) {
-                animateEmptyView(true /* show */, null /* postAnimationTrigger */);
-            }
-        }
-    }
-
-    @Override
-    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
-        mSystemInsets.set(insets.getSystemWindowInsetsAsRect());
-        mTaskStackView.setSystemInsets(mSystemInsets);
-        requestLayout();
-        return insets;
-    }
-
-    @Override
-    public boolean onInterceptTouchEvent(MotionEvent ev) {
-        return mTouchHandler.onInterceptTouchEvent(ev);
-    }
-
-    @Override
-    public boolean onTouchEvent(MotionEvent ev) {
-        return mTouchHandler.onTouchEvent(ev);
-    }
-
-    @Override
-    public void onDrawForeground(Canvas canvas) {
-        super.onDrawForeground(canvas);
-
-        ArrayList<DockState> visDockStates = mTouchHandler.getVisibleDockStates();
-        for (int i = visDockStates.size() - 1; i >= 0; i--) {
-            visDockStates.get(i).viewState.draw(canvas);
-        }
-    }
-
-    @Override
-    protected boolean verifyDrawable(Drawable who) {
-        ArrayList<DockState> visDockStates = mTouchHandler.getVisibleDockStates();
-        for (int i = visDockStates.size() - 1; i >= 0; i--) {
-            Drawable d = visDockStates.get(i).viewState.dockAreaOverlay;
-            if (d == who) {
-                return true;
-            }
-        }
-        return super.verifyDrawable(who);
-    }
-
-    /**** EventBus Events ****/
-
-    public final void onBusEvent(LaunchTaskEvent event) {
-        launchTaskFromRecents(getStack(), event.task, mTaskStackView, event.taskView,
-                event.screenPinningRequested, event.targetWindowingMode, event.targetActivityType);
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            EventBus.getDefault().send(new HideStackActionButtonEvent(false /* translate */));
-        }
-    }
-
-    public final void onBusEvent(DismissRecentsToHomeAnimationStarted event) {
-        int taskViewExitToHomeDuration = TaskStackAnimationHelper.EXIT_TO_HOME_TRANSLATION_DURATION;
-        // Hide the stack action button
-        EventBus.getDefault().send(new HideStackActionButtonEvent());
-        animateBackgroundScrim(0f, taskViewExitToHomeDuration);
-
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            animateEmptyView(false /* show */, event.getAnimationTrigger());
-        }
-    }
-
-    public final void onBusEvent(DragStartEvent event) {
-        updateVisibleDockRegions(LegacyRecentsImpl.getConfiguration().getDockStatesForCurrentOrientation(),
-                true /* isDefaultDockState */, DockState.NONE.viewState.dockAreaAlpha,
-                DockState.NONE.viewState.hintTextAlpha,
-                true /* animateAlpha */, false /* animateBounds */);
-
-        // Temporarily hide the stack action button without changing visibility
-        if (mStackActionButton != null) {
-            mStackActionButton.animate()
-                    .alpha(0f)
-                    .setDuration(HIDE_STACK_ACTION_BUTTON_DURATION)
-                    .setInterpolator(Interpolators.ALPHA_OUT)
-                    .start();
-        }
-    }
-
-    public final void onBusEvent(DragDropTargetChangedEvent event) {
-        if (event.dropTarget == null || !(event.dropTarget instanceof DockState)) {
-            updateVisibleDockRegions(
-                    LegacyRecentsImpl.getConfiguration().getDockStatesForCurrentOrientation(),
-                    true /* isDefaultDockState */, DockState.NONE.viewState.dockAreaAlpha,
-                    DockState.NONE.viewState.hintTextAlpha,
-                    true /* animateAlpha */, true /* animateBounds */);
-        } else {
-            final DockState dockState = (DockState) event.dropTarget;
-            updateVisibleDockRegions(new DockState[] {dockState},
-                    false /* isDefaultDockState */, -1, -1, true /* animateAlpha */,
-                    true /* animateBounds */);
-        }
-        if (mStackActionButton != null) {
-            event.addPostAnimationCallback(new Runnable() {
-                @Override
-                public void run() {
-                    // Move the clear all button to its new position
-                    Rect buttonBounds = getStackActionButtonBoundsFromStackLayout();
-                    mStackActionButton.setLeftTopRightBottom(buttonBounds.left, buttonBounds.top,
-                            buttonBounds.right, buttonBounds.bottom);
-                }
-            });
-        }
-    }
-
-    public final void onBusEvent(final DragEndEvent event) {
-        // Handle the case where we drop onto a dock region
-        if (event.dropTarget instanceof DockState) {
-            final DockState dockState = (DockState) event.dropTarget;
-
-            // Hide the dock region
-            updateVisibleDockRegions(null, false /* isDefaultDockState */, -1, -1,
-                    false /* animateAlpha */, false /* animateBounds */);
-
-            // We translated the view but we need to animate it back from the current layout-space
-            // rect to its final layout-space rect
-            Utilities.setViewFrameFromTranslation(event.taskView);
-
-            final ActivityOptions options = ActivityOptionsCompat.makeSplitScreenOptions(
-                    dockState.createMode == SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT);
-            if (ActivityManagerWrapper.getInstance().startActivityFromRecents(event.task.key.id,
-                    options)) {
-                final Runnable animStartedListener = () -> {
-                    EventBus.getDefault().send(new DockedFirstAnimationFrameEvent());
-                    // Remove the task and don't bother relaying out, as all the tasks
-                    // will be relaid out when the stack changes on the multiwindow
-                    // change event
-                    getStack().removeTask(event.task, null, true /* fromDockGesture */);
-                };
-                final Rect taskRect = getTaskRect(event.taskView);
-                AppTransitionAnimationSpecsFuture future = new AppTransitionAnimationSpecsFuture(
-                        getHandler()) {
-                    @Override
-                    public List<AppTransitionAnimationSpecCompat> composeSpecs() {
-                        return mTransitionHelper.composeDockAnimationSpec(event.taskView, taskRect);
-                    }
-                };
-                WindowManagerWrapper.getInstance().overridePendingAppTransitionMultiThumbFuture(
-                        future, animStartedListener, getHandler(), true /* scaleUp */,
-                        getContext().getDisplayId());
-                MetricsLogger.action(mContext, MetricsEvent.ACTION_WINDOW_DOCK_DRAG_DROP,
-                        event.task.getTopComponent().flattenToShortString());
-            } else {
-                EventBus.getDefault().send(new DragEndCancelledEvent(getStack(), event.task,
-                        event.taskView));
-            }
-        } else {
-            // Animate the overlay alpha back to 0
-            updateVisibleDockRegions(null, true /* isDefaultDockState */, -1, -1,
-                    true /* animateAlpha */, false /* animateBounds */);
-        }
-
-        // Show the stack action button again without changing visibility
-        if (mStackActionButton != null) {
-            mStackActionButton.animate()
-                    .alpha(1f)
-                    .setDuration(SHOW_STACK_ACTION_BUTTON_DURATION)
-                    .setInterpolator(Interpolators.ALPHA_IN)
-                    .start();
-        }
-    }
-
-    public final void onBusEvent(final DragEndCancelledEvent event) {
-        // Animate the overlay alpha back to 0
-        updateVisibleDockRegions(null, true /* isDefaultDockState */, -1, -1,
-                true /* animateAlpha */, false /* animateBounds */);
-    }
-
-    private Rect getTaskRect(TaskView taskView) {
-        int[] location = taskView.getLocationOnScreen();
-        int viewX = location[0];
-        int viewY = location[1];
-        return new Rect(viewX, viewY,
-                (int) (viewX + taskView.getWidth() * taskView.getScaleX()),
-                (int) (viewY + taskView.getHeight() * taskView.getScaleY()));
-    }
-
-    public final void onBusEvent(DraggingInRecentsEvent event) {
-        if (mTaskStackView.getTaskViews().size() > 0) {
-            setTranslationY(event.distanceFromTop - mTaskStackView.getTaskViews().get(0).getY());
-        }
-    }
-
-    public final void onBusEvent(DraggingInRecentsEndedEvent event) {
-        ViewPropertyAnimator animator = animate();
-        if (event.velocity > mFlingAnimationUtils.getMinVelocityPxPerSecond()) {
-            animator.translationY(getHeight());
-            animator.withEndAction(new Runnable() {
-                @Override
-                public void run() {
-                    WindowManagerProxy.getInstance().maximizeDockedStack();
-                }
-            });
-            mFlingAnimationUtils.apply(animator, getTranslationY(), getHeight(), event.velocity);
-        } else {
-            animator.translationY(0f);
-            animator.setListener(null);
-            mFlingAnimationUtils.apply(animator, getTranslationY(), 0, event.velocity);
-        }
-        animator.start();
-    }
-
-    public final void onBusEvent(EnterRecentsWindowAnimationCompletedEvent event) {
-        RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-        if (!launchState.launchedViaDockGesture && !launchState.launchedFromApp
-                && getStack().getTaskCount() > 0) {
-            animateBackgroundScrim(getOpaqueScrimAlpha(),
-                    TaskStackAnimationHelper.ENTER_FROM_HOME_TRANSLATION_DURATION);
-        }
-    }
-
-    public final void onBusEvent(AllTaskViewsDismissedEvent event) {
-        EventBus.getDefault().send(new HideStackActionButtonEvent());
-    }
-
-    public final void onBusEvent(DismissAllTaskViewsEvent event) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        if (!ssp.hasDockedTask()) {
-            // Animate the background away only if we are dismissing Recents to home
-            animateBackgroundScrim(0f, DEFAULT_UPDATE_SCRIM_DURATION);
-        }
-    }
-
-    public final void onBusEvent(ShowStackActionButtonEvent event) {
-        showStackActionButton(SHOW_STACK_ACTION_BUTTON_DURATION, event.translate);
-    }
-
-    public final void onBusEvent(HideStackActionButtonEvent event) {
-        hideStackActionButton(HIDE_STACK_ACTION_BUTTON_DURATION, true /* translate */);
-    }
-
-    public final void onBusEvent(MultiWindowStateChangedEvent event) {
-        updateStack(event.stack, false /* setStackViewTasks */);
-    }
-
-    public final void onBusEvent(ShowEmptyViewEvent event) {
-        showEmptyView(R.string.recents_empty_message);
-    }
-
-    /**
-     * Shows the stack action button.
-     */
-    private void showStackActionButton(final int duration, final boolean translate) {
-        final ReferenceCountedTrigger postAnimationTrigger = new ReferenceCountedTrigger();
-        if (mStackActionButton.getVisibility() == View.INVISIBLE) {
-            mStackActionButton.setVisibility(View.VISIBLE);
-            mStackActionButton.setAlpha(0f);
-            if (translate) {
-                mStackActionButton.setTranslationY(mStackActionButton.getMeasuredHeight() *
-                        (LegacyRecentsImpl.getConfiguration().isLowRamDevice ? 1 : -0.25f));
-            } else {
-                mStackActionButton.setTranslationY(0f);
-            }
-            postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
-                @Override
-                public void run() {
-                    if (translate) {
-                        mStackActionButton.animate()
-                            .translationY(0f);
-                    }
-                    mStackActionButton.animate()
-                            .alpha(1f)
-                            .setDuration(duration)
-                            .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
-                            .start();
-                }
-            });
-        }
-        postAnimationTrigger.flushLastDecrementRunnables();
-    }
-
-    /**
-     * Hides the stack action button.
-     */
-    private void hideStackActionButton(int duration, boolean translate) {
-        final ReferenceCountedTrigger postAnimationTrigger = new ReferenceCountedTrigger();
-        hideStackActionButton(duration, translate, postAnimationTrigger);
-        postAnimationTrigger.flushLastDecrementRunnables();
-    }
-
-    /**
-     * Hides the stack action button.
-     */
-    private void hideStackActionButton(int duration, boolean translate,
-                                       final ReferenceCountedTrigger postAnimationTrigger) {
-        if (mStackActionButton.getVisibility() == View.VISIBLE) {
-            if (translate) {
-                mStackActionButton.animate().translationY(mStackActionButton.getMeasuredHeight()
-                        * (LegacyRecentsImpl.getConfiguration().isLowRamDevice ? 1 : -0.25f));
-            }
-            mStackActionButton.animate()
-                    .alpha(0f)
-                    .setDuration(duration)
-                    .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
-                    .withEndAction(new Runnable() {
-                        @Override
-                        public void run() {
-                            mStackActionButton.setVisibility(View.INVISIBLE);
-                            postAnimationTrigger.decrement();
-                        }
-                    })
-                    .start();
-            postAnimationTrigger.increment();
-        }
-    }
-
-    /**
-     * Animates a translation in the Y direction and fades in/out for empty view to show or hide it.
-     * @param show whether to translate up and fade in the empty view to the center of the screen
-     * @param postAnimationTrigger to keep track of the animation
-     */
-    private void animateEmptyView(boolean show, ReferenceCountedTrigger postAnimationTrigger) {
-        float start = mTaskStackView.getStackAlgorithm().getTaskRect().height() / 4;
-        mEmptyView.setTranslationY(show ? start : 0);
-        mEmptyView.setAlpha(show ? 0f : 1f);
-        ViewPropertyAnimator animator = mEmptyView.animate()
-                .setDuration(150)
-                .setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
-                .translationY(show ? 0 : start)
-                .alpha(show ? 1f : 0f);
-
-        if (postAnimationTrigger != null) {
-            animator.setListener(postAnimationTrigger.decrementOnAnimationEnd());
-            postAnimationTrigger.increment();
-        }
-        animator.start();
-    }
-
-    /**
-     * Updates the dock region to match the specified dock state.
-     */
-    private void updateVisibleDockRegions(DockState[] newDockStates,
-            boolean isDefaultDockState, int overrideAreaAlpha, int overrideHintAlpha,
-            boolean animateAlpha, boolean animateBounds) {
-        ArraySet<DockState> newDockStatesSet = Utilities.arrayToSet(newDockStates,
-                new ArraySet<DockState>());
-        ArrayList<DockState> visDockStates = mTouchHandler.getVisibleDockStates();
-        for (int i = visDockStates.size() - 1; i >= 0; i--) {
-            DockState dockState = visDockStates.get(i);
-            DockState.ViewState viewState = dockState.viewState;
-            if (newDockStates == null || !newDockStatesSet.contains(dockState)) {
-                // This is no longer visible, so hide it
-                viewState.startAnimation(null, 0, 0, TaskStackView.SLOW_SYNC_STACK_DURATION,
-                        Interpolators.FAST_OUT_SLOW_IN, animateAlpha, animateBounds);
-            } else {
-                // This state is now visible, update the bounds and show it
-                int areaAlpha = overrideAreaAlpha != -1
-                        ? overrideAreaAlpha
-                        : viewState.dockAreaAlpha;
-                int hintAlpha = overrideHintAlpha != -1
-                        ? overrideHintAlpha
-                        : viewState.hintTextAlpha;
-                Rect bounds = isDefaultDockState
-                        ? dockState.getPreDockedBounds(getMeasuredWidth(), getMeasuredHeight(),
-                                mSystemInsets)
-                        : dockState.getDockedBounds(getMeasuredWidth(), getMeasuredHeight(),
-                                mDividerSize, mSystemInsets, getResources());
-                if (viewState.dockAreaOverlay.getCallback() != this) {
-                    viewState.dockAreaOverlay.setCallback(this);
-                    viewState.dockAreaOverlay.setBounds(bounds);
-                }
-                viewState.startAnimation(bounds, areaAlpha, hintAlpha,
-                        TaskStackView.SLOW_SYNC_STACK_DURATION, Interpolators.FAST_OUT_SLOW_IN,
-                        animateAlpha, animateBounds);
-            }
-        }
-    }
-
-    /**
-     * Scrim alpha based on how busy recents is:
-     * Scrim will be {@link ScrimController#GRADIENT_SCRIM_ALPHA} when the stack is empty,
-     * and {@link ScrimController#GRADIENT_SCRIM_ALPHA_BUSY} when it's full.
-     *
-     * @return Alpha from 0 to 1.
-     */
-    private float getOpaqueScrimAlpha() {
-        return MathUtils.map(0, 1, ScrimController.GRADIENT_SCRIM_ALPHA,
-                ScrimController.GRADIENT_SCRIM_ALPHA_BUSY, mBusynessFactor);
-    }
-
-    /**
-     * Animates the background scrim to the given {@param alpha}.
-     */
-    private void animateBackgroundScrim(float alpha, int duration) {
-        Utilities.cancelAnimationWithoutCallbacks(mBackgroundScrimAnimator);
-        // Calculate the absolute alpha to animate from
-        final int fromAlpha = mBackgroundScrim.getAlpha();
-        final int toAlpha = (int) (alpha * 255);
-        mBackgroundScrimAnimator = ValueAnimator.ofInt(fromAlpha, toAlpha);
-        mBackgroundScrimAnimator.setDuration(duration);
-        mBackgroundScrimAnimator.setInterpolator(toAlpha > fromAlpha
-                ? Interpolators.ALPHA_IN
-                : Interpolators.ALPHA_OUT);
-        mBackgroundScrimAnimator.addUpdateListener(mUpdateBackgroundScrimAlpha);
-        mBackgroundScrimAnimator.start();
-    }
-
-    /**
-     * @return the bounds of the stack action button.
-     */
-    Rect getStackActionButtonBoundsFromStackLayout() {
-        Rect actionButtonRect = new Rect(
-                mTaskStackView.mLayoutAlgorithm.getStackActionButtonRect());
-        int left, top;
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            Rect windowRect = LegacyRecentsImpl.getSystemServices().getWindowRect();
-            int spaceLeft = windowRect.width() - mSystemInsets.left - mSystemInsets.right;
-            left = (spaceLeft - mStackActionButton.getMeasuredWidth()) / 2 + mSystemInsets.left;
-            top = windowRect.height() - (mStackActionButton.getMeasuredHeight()
-                    + mSystemInsets.bottom + mStackActionButton.getPaddingBottom() / 2);
-        } else {
-            left = isLayoutRtl()
-                ? actionButtonRect.left - mStackActionButton.getPaddingLeft()
-                : actionButtonRect.right + mStackActionButton.getPaddingRight()
-                        - mStackActionButton.getMeasuredWidth();
-            top = actionButtonRect.top +
-                (actionButtonRect.height() - mStackActionButton.getMeasuredHeight()) / 2;
-        }
-        actionButtonRect.set(left, top, left + mStackActionButton.getMeasuredWidth(),
-                top + mStackActionButton.getMeasuredHeight());
-        return actionButtonRect;
-    }
-
-    View getStackActionButton() {
-        return mStackActionButton;
-    }
-
-    /**
-     * Launches the specified {@link Task}.
-     */
-    public void launchTaskFromRecents(final TaskStack stack, @Nullable final Task task,
-            final TaskStackView stackView, final TaskView taskView,
-            final boolean screenPinningRequested, final int windowingMode, final int activityType) {
-
-        final Runnable animStartedListener;
-        final AppTransitionAnimationSpecsFuture transitionFuture;
-        if (taskView != null) {
-
-            // Fetch window rect here already in order not to be blocked on lock contention in WM
-            // when the future calls it.
-            final Rect windowRect = LegacyRecentsImpl.getSystemServices().getWindowRect();
-            transitionFuture = new AppTransitionAnimationSpecsFuture(stackView.getHandler()) {
-                @Override
-                public List<AppTransitionAnimationSpecCompat> composeSpecs() {
-                    return mTransitionHelper.composeAnimationSpecs(task, stackView, windowingMode,
-                            activityType, windowRect);
-                }
-            };
-            animStartedListener = new Runnable() {
-                private boolean mHandled;
-
-                @Override
-                public void run() {
-                    if (mHandled) {
-                        return;
-                    }
-                    mHandled = true;
-
-                    // If we are launching into another task, cancel the previous task's
-                    // window transition
-                    EventBus.getDefault().send(new CancelEnterRecentsWindowAnimationEvent(task));
-                    EventBus.getDefault().send(new ExitRecentsWindowFirstAnimationFrameEvent());
-                    stackView.cancelAllTaskViewAnimations();
-
-                    if (screenPinningRequested) {
-                        // Request screen pinning after the animation runs
-                        mHandler.postDelayed(() -> {
-                            EventBus.getDefault().send(new ScreenPinningRequestEvent(mContext,
-                                    task.key.id));
-                        }, 350);
-                    }
-
-                    if (!LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                        // Reset the state where we are waiting for the transition to start
-                        EventBus.getDefault().send(new SetWaitingForTransitionStartEvent(false));
-                    }
-                }
-            };
-        } else {
-            // This is only the case if the task is not on screen (scrolled offscreen for example)
-            transitionFuture = null;
-            animStartedListener = new Runnable() {
-                private boolean mHandled;
-
-                @Override
-                public void run() {
-                    if (mHandled) {
-                        return;
-                    }
-                    mHandled = true;
-
-                    // If we are launching into another task, cancel the previous task's
-                    // window transition
-                    EventBus.getDefault().send(new CancelEnterRecentsWindowAnimationEvent(task));
-                    EventBus.getDefault().send(new ExitRecentsWindowFirstAnimationFrameEvent());
-                    stackView.cancelAllTaskViewAnimations();
-
-                    if (!LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                        // Reset the state where we are waiting for the transition to start
-                        EventBus.getDefault().send(new SetWaitingForTransitionStartEvent(false));
-                    }
-                }
-            };
-        }
-
-        EventBus.getDefault().send(new SetWaitingForTransitionStartEvent(true));
-        final ActivityOptions opts = RecentsTransition.createAspectScaleAnimation(mContext,
-                mHandler, true /* scaleUp */, transitionFuture != null ? transitionFuture : null,
-                animStartedListener);
-        if (taskView == null) {
-            // If there is no task view, then we do not need to worry about animating out occluding
-            // task views, and we can launch immediately
-            startTaskActivity(stack, task, taskView, opts, transitionFuture,
-                    windowingMode, activityType);
-        } else {
-            LaunchTaskStartedEvent launchStartedEvent = new LaunchTaskStartedEvent(taskView,
-                    screenPinningRequested);
-            EventBus.getDefault().send(launchStartedEvent);
-            startTaskActivity(stack, task, taskView, opts, transitionFuture, windowingMode,
-                    activityType);
-        }
-        ActivityManagerWrapper.getInstance().closeSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
-    }
-
-    /**
-     * Starts the activity for the launch task.
-     *
-     * @param taskView this is the {@link TaskView} that we are launching from. This can be null if
-     *                 we are toggling recents and the launch-to task is now offscreen.
-     */
-    private void startTaskActivity(TaskStack stack, Task task, @Nullable TaskView taskView,
-            ActivityOptions opts, AppTransitionAnimationSpecsFuture transitionFuture,
-            int windowingMode, int activityType) {
-        ActivityManagerWrapper.getInstance().startActivityFromRecentsAsync(task.key, opts,
-                windowingMode, activityType, succeeded -> {
-            if (succeeded) {
-                // Keep track of the index of the task launch
-                int taskIndexFromFront = 0;
-                int taskIndex = stack.indexOfTask(task);
-                if (taskIndex > -1) {
-                    taskIndexFromFront = stack.getTaskCount() - taskIndex - 1;
-                }
-                EventBus.getDefault().send(new LaunchTaskSucceededEvent(taskIndexFromFront));
-            } else {
-                Log.e(TAG, mContext.getString(R.string.recents_launch_error_message, task.title));
-
-                // Dismiss the task if we fail to launch it
-                if (taskView != null) {
-                    taskView.dismissTask();
-                }
-
-                // Keep track of failed launches
-                EventBus.getDefault().send(new LaunchTaskFailedEvent());
-            }
-        }, getHandler());
-        if (transitionFuture != null) {
-            mHandler.post(transitionFuture::composeSpecsSynchronous);
-        }
-    }
-
-    @Override
-    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
-        super.requestDisallowInterceptTouchEvent(disallowIntercept);
-        mTouchHandler.cancelStackActionButtonClick();
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        String innerPrefix = prefix + "  ";
-        String id = Integer.toHexString(System.identityHashCode(this));
-
-        writer.print(prefix); writer.print(TAG);
-        writer.print(" awaitingFirstLayout="); writer.print(mAwaitingFirstLayout ? "Y" : "N");
-        writer.print(" insets="); writer.print(Utilities.dumpRect(mSystemInsets));
-        writer.print(" [0x"); writer.print(id); writer.print("]");
-        writer.println();
-
-        if (getStack() != null) {
-            getStack().dump(innerPrefix, writer);
-        }
-        if (mTaskStackView != null) {
-            mTaskStackView.dump(innerPrefix, writer);
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsViewTouchHandler.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsViewTouchHandler.java
deleted file mode 100644
index 1a827d5..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/RecentsViewTouchHandler.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.app.ActivityTaskManager;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.view.InputDevice;
-import android.view.MotionEvent;
-import android.view.PointerIcon;
-import android.view.View;
-import android.view.ViewConfiguration;
-import android.view.ViewDebug;
-
-import com.android.internal.policy.DividerSnapAlgorithm;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.ConfigurationChangedEvent;
-import com.android.systemui.recents.events.activity.HideRecentsEvent;
-import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
-import com.android.systemui.recents.events.ui.HideIncompatibleAppOverlayEvent;
-import com.android.systemui.recents.events.ui.ShowIncompatibleAppOverlayEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragDropTargetChangedEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragStartInitializeDropTargetsEvent;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.shared.recents.model.Task;
-
-import java.util.ArrayList;
-
-/**
- * Handles touch events for a RecentsView.
- */
-public class RecentsViewTouchHandler {
-
-    private RecentsView mRv;
-
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="drag_task")
-    private Task mDragTask;
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="drag_task_view_")
-    private TaskView mTaskView;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    private Point mTaskViewOffset = new Point();
-    @ViewDebug.ExportedProperty(category="recents")
-    private Point mDownPos = new Point();
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mDragRequested;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mIsDragging;
-    private float mDragSlop;
-    private int mDeviceId = -1;
-
-    private DropTarget mLastDropTarget;
-    private DividerSnapAlgorithm mDividerSnapAlgorithm;
-    private ArrayList<DropTarget> mDropTargets = new ArrayList<>();
-    private ArrayList<DockState> mVisibleDockStates = new ArrayList<>();
-
-    public RecentsViewTouchHandler(RecentsView rv) {
-        mRv = rv;
-        mDragSlop = ViewConfiguration.get(rv.getContext()).getScaledTouchSlop();
-        updateSnapAlgorithm();
-    }
-
-    private void updateSnapAlgorithm() {
-        Rect insets = new Rect();
-        SystemServicesProxy.getInstance(mRv.getContext()).getStableInsets(insets);
-        mDividerSnapAlgorithm = DividerSnapAlgorithm.create(mRv.getContext(), insets);
-    }
-
-    /**
-     * Registers a new drop target for the current drag only.
-     */
-    public void registerDropTargetForCurrentDrag(DropTarget target) {
-        mDropTargets.add(target);
-    }
-
-    /**
-     * Returns the set of visible dock states for this current drag.
-     */
-    public ArrayList<DockState> getVisibleDockStates() {
-        return mVisibleDockStates;
-    }
-
-    /** Touch preprocessing for handling below */
-    public boolean onInterceptTouchEvent(MotionEvent ev) {
-        return handleTouchEvent(ev) || mDragRequested;
-    }
-
-    /** Handles touch events once we have intercepted them */
-    public boolean onTouchEvent(MotionEvent ev) {
-        handleTouchEvent(ev);
-        if (ev.getAction() == MotionEvent.ACTION_UP && mRv.getStack().getTaskCount() == 0) {
-            EventBus.getDefault().send(new HideRecentsEvent(false, true));
-        }
-        return true;
-    }
-
-    /**** Events ****/
-
-    public final void onBusEvent(DragStartEvent event) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        mRv.getParent().requestDisallowInterceptTouchEvent(true);
-        mDragRequested = true;
-        // We defer starting the actual drag handling until the user moves past the drag slop
-        mIsDragging = false;
-        mDragTask = event.task;
-        mTaskView = event.taskView;
-        mDropTargets.clear();
-
-        int[] recentsViewLocation = new int[2];
-        mRv.getLocationInWindow(recentsViewLocation);
-        mTaskViewOffset.set(mTaskView.getLeft() - recentsViewLocation[0] + event.tlOffset.x,
-                mTaskView.getTop() - recentsViewLocation[1] + event.tlOffset.y);
-
-        // Change space coordinates relative to the view to RecentsView when user initiates a touch
-        if (event.isUserTouchInitiated) {
-            float x = mDownPos.x - mTaskViewOffset.x;
-            float y = mDownPos.y - mTaskViewOffset.y;
-            mTaskView.setTranslationX(x);
-            mTaskView.setTranslationY(y);
-        }
-
-        mVisibleDockStates.clear();
-        if (ActivityTaskManager.supportsMultiWindow(mRv.getContext()) && !ssp.hasDockedTask()
-                && mDividerSnapAlgorithm.isSplitScreenFeasible()) {
-            LegacyRecentsImpl.logDockAttempt(mRv.getContext(), event.task.getTopComponent(),
-                    event.task.resizeMode);
-            if (!event.task.isDockable) {
-                EventBus.getDefault().send(new ShowIncompatibleAppOverlayEvent());
-            } else {
-                // Add the dock state drop targets (these take priority)
-                DockState[] dockStates = LegacyRecentsImpl.getConfiguration()
-                        .getDockStatesForCurrentOrientation();
-                for (DockState dockState : dockStates) {
-                    registerDropTargetForCurrentDrag(dockState);
-                    dockState.update(mRv.getContext());
-                    mVisibleDockStates.add(dockState);
-                }
-            }
-        }
-
-        // Request other drop targets to register themselves
-        EventBus.getDefault().send(new DragStartInitializeDropTargetsEvent(event.task,
-                event.taskView, this));
-        if (mDeviceId != -1) {
-            InputDevice device = InputDevice.getDevice(mDeviceId);
-            if (device != null) {
-                device.setPointerType(PointerIcon.TYPE_GRABBING);
-            }
-        }
-    }
-
-    public final void onBusEvent(DragEndEvent event) {
-        if (!mDragTask.isDockable) {
-            EventBus.getDefault().send(new HideIncompatibleAppOverlayEvent());
-        }
-        mDragRequested = false;
-        mDragTask = null;
-        mTaskView = null;
-        mLastDropTarget = null;
-    }
-
-    public final void onBusEvent(ConfigurationChangedEvent event) {
-        if (event.fromDisplayDensityChange || event.fromDeviceOrientationChange) {
-            updateSnapAlgorithm();
-        }
-    }
-
-    void cancelStackActionButtonClick() {
-        mRv.getStackActionButton().setPressed(false);
-    }
-
-    private boolean isWithinStackActionButton(float x, float y) {
-        Rect rect = mRv.getStackActionButtonBoundsFromStackLayout();
-        return mRv.getStackActionButton().getVisibility() == View.VISIBLE &&
-                mRv.getStackActionButton().pointInView(x - rect.left, y - rect.top, 0 /* slop */);
-    }
-
-    private void changeStackActionButtonDrawableHotspot(float x, float y) {
-        Rect rect = mRv.getStackActionButtonBoundsFromStackLayout();
-        mRv.getStackActionButton().drawableHotspotChanged(x - rect.left, y - rect.top);
-    }
-
-    /**
-     * Handles dragging touch events
-     */
-    private boolean handleTouchEvent(MotionEvent ev) {
-        int action = ev.getActionMasked();
-        boolean consumed = false;
-        float evX = ev.getX();
-        float evY = ev.getY();
-        switch (action) {
-            case MotionEvent.ACTION_DOWN:
-                mDownPos.set((int) evX, (int) evY);
-                mDeviceId = ev.getDeviceId();
-
-                if (isWithinStackActionButton(evX, evY)) {
-                    changeStackActionButtonDrawableHotspot(evX, evY);
-                    mRv.getStackActionButton().setPressed(true);
-                }
-                break;
-            case MotionEvent.ACTION_MOVE: {
-                float x = evX - mTaskViewOffset.x;
-                float y = evY - mTaskViewOffset.y;
-
-                if (mRv.getStackActionButton().isPressed() && isWithinStackActionButton(evX, evY)) {
-                    changeStackActionButtonDrawableHotspot(evX, evY);
-                }
-
-                if (mDragRequested) {
-                    if (!mIsDragging) {
-                        mIsDragging = Math.hypot(evX - mDownPos.x, evY - mDownPos.y) > mDragSlop;
-                    }
-                    if (mIsDragging) {
-                        int width = mRv.getMeasuredWidth();
-                        int height = mRv.getMeasuredHeight();
-
-                        DropTarget currentDropTarget = null;
-
-                        // Give priority to the current drop target to retain the touch handling
-                        if (mLastDropTarget != null) {
-                            if (mLastDropTarget.acceptsDrop((int) evX, (int) evY, width, height,
-                                    mRv.mSystemInsets, true /* isCurrentTarget */)) {
-                                currentDropTarget = mLastDropTarget;
-                            }
-                        }
-
-                        // Otherwise, find the next target to handle this event
-                        if (currentDropTarget == null) {
-                            for (DropTarget target : mDropTargets) {
-                                if (target.acceptsDrop((int) evX, (int) evY, width, height,
-                                        mRv.mSystemInsets, false /* isCurrentTarget */)) {
-                                    currentDropTarget = target;
-                                    break;
-                                }
-                            }
-                        }
-                        if (mLastDropTarget != currentDropTarget) {
-                            mLastDropTarget = currentDropTarget;
-                            EventBus.getDefault().send(new DragDropTargetChangedEvent(mDragTask,
-                                    currentDropTarget));
-                        }
-                    }
-                    mTaskView.setTranslationX(x);
-                    mTaskView.setTranslationY(y);
-                }
-                break;
-            }
-            case MotionEvent.ACTION_UP:
-            case MotionEvent.ACTION_CANCEL: {
-                if (mRv.getStackActionButton().isPressed() && isWithinStackActionButton(evX, evY)) {
-                    EventBus.getDefault().send(new DismissAllTaskViewsEvent());
-                    consumed = true;
-                }
-                cancelStackActionButtonClick();
-                if (mDragRequested) {
-                    boolean cancelled = action == MotionEvent.ACTION_CANCEL;
-                    if (cancelled) {
-                        EventBus.getDefault().send(new DragDropTargetChangedEvent(mDragTask, null));
-                    }
-                    EventBus.getDefault().send(new DragEndEvent(mDragTask, mTaskView,
-                            !cancelled ? mLastDropTarget : null));
-                    break;
-                }
-                mDeviceId = -1;
-            }
-        }
-        return consumed;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/SystemBarScrimViews.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/SystemBarScrimViews.java
deleted file mode 100644
index 22c12b4..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/SystemBarScrimViews.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.content.Context;
-import android.view.View;
-
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsActivity;
-import com.android.systemui.recents.events.activity.ConfigurationChangedEvent;
-import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
-import com.android.systemui.recents.events.activity.EnterRecentsWindowAnimationCompletedEvent;
-import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
-import com.android.systemui.recents.events.activity.MultiWindowStateChangedEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndCancelledEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
-import com.android.systemui.recents.utilities.AnimationProps;
-
-/** Manages the scrims for the various system bars. */
-public class SystemBarScrimViews {
-
-    private static final int DEFAULT_ANIMATION_DURATION = 150;
-
-    private Context mContext;
-
-    private View mNavBarScrimView;
-
-    private boolean mHasNavBarScrim;
-    private boolean mShouldAnimateNavBarScrim;
-    private boolean mHasTransposedNavBar;
-    private boolean mHasDockedTasks;
-    private int mNavBarScrimEnterDuration;
-
-    public SystemBarScrimViews(RecentsActivity activity) {
-        mContext = activity;
-        mNavBarScrimView = activity.findViewById(R.id.nav_bar_scrim);
-        mNavBarScrimView.forceHasOverlappingRendering(false);
-        mNavBarScrimEnterDuration = activity.getResources().getInteger(
-                R.integer.recents_nav_bar_scrim_enter_duration);
-        mHasNavBarScrim = LegacyRecentsImpl.getSystemServices().hasTransposedNavigationBar();
-        mHasDockedTasks = LegacyRecentsImpl.getSystemServices().hasDockedTask();
-    }
-
-    /**
-     * Updates the nav bar scrim.
-     */
-    public void updateNavBarScrim(boolean animateNavBarScrim, boolean hasStackTasks,
-            AnimationProps animation) {
-        prepareEnterRecentsAnimation(isNavBarScrimRequired(hasStackTasks), animateNavBarScrim);
-        if (animateNavBarScrim && animation != null) {
-            animateNavBarScrimVisibility(true, animation);
-        }
-    }
-
-    /**
-     * Prepares the scrim views for animating when entering Recents. This will be called before
-     * the first draw, unless we are updating the scrim on configuration change.
-     */
-    private void prepareEnterRecentsAnimation(boolean hasNavBarScrim, boolean animateNavBarScrim) {
-        mHasNavBarScrim = hasNavBarScrim;
-        mShouldAnimateNavBarScrim = animateNavBarScrim;
-
-        mNavBarScrimView.setVisibility(mHasNavBarScrim && !mShouldAnimateNavBarScrim ?
-                View.VISIBLE : View.INVISIBLE);
-    }
-
-    /**
-     * Animates the nav bar scrim visibility.
-     */
-    private void animateNavBarScrimVisibility(boolean visible, AnimationProps animation) {
-        int toY = 0;
-        if (visible) {
-            mNavBarScrimView.setVisibility(View.VISIBLE);
-            mNavBarScrimView.setTranslationY(mNavBarScrimView.getMeasuredHeight());
-        } else {
-            toY = mNavBarScrimView.getMeasuredHeight();
-        }
-        if (animation != AnimationProps.IMMEDIATE) {
-            mNavBarScrimView.animate()
-                    .translationY(toY)
-                    .setDuration(animation.getDuration(AnimationProps.BOUNDS))
-                    .setInterpolator(animation.getInterpolator(AnimationProps.BOUNDS))
-                    .start();
-        } else {
-            mNavBarScrimView.setTranslationY(toY);
-        }
-    }
-
-    /**
-     * @return Whether to show the nav bar scrim.
-     */
-    private boolean isNavBarScrimRequired(boolean hasStackTasks) {
-        return hasStackTasks && !mHasTransposedNavBar && !mHasDockedTasks;
-    }
-
-    /**** EventBus events ****/
-
-    /**
-     * Starts animating the scrim views when entering Recents.
-     */
-    public final void onBusEvent(EnterRecentsWindowAnimationCompletedEvent event) {
-        if (mHasNavBarScrim) {
-            AnimationProps animation = mShouldAnimateNavBarScrim
-                    ? new AnimationProps()
-                            .setDuration(AnimationProps.BOUNDS, mNavBarScrimEnterDuration)
-                            .setInterpolator(AnimationProps.BOUNDS, Interpolators.DECELERATE_QUINT)
-                    : AnimationProps.IMMEDIATE;
-            animateNavBarScrimVisibility(true, animation);
-        }
-    }
-
-    /**
-     * Starts animating the scrim views when leaving Recents (either via launching a task, or
-     * going home).
-     */
-    public final void onBusEvent(DismissRecentsToHomeAnimationStarted event) {
-        if (mHasNavBarScrim) {
-            AnimationProps animation = createBoundsAnimation(
-                    TaskStackAnimationHelper.EXIT_TO_HOME_TRANSLATION_DURATION);
-            animateNavBarScrimVisibility(false, animation);
-        }
-    }
-
-    public final void onBusEvent(DismissAllTaskViewsEvent event) {
-        if (mHasNavBarScrim) {
-            AnimationProps animation = createBoundsAnimation(
-                    TaskStackAnimationHelper.EXIT_TO_HOME_TRANSLATION_DURATION);
-            animateNavBarScrimVisibility(false, animation);
-        }
-    }
-
-    public final void onBusEvent(ConfigurationChangedEvent event) {
-        if (event.fromDeviceOrientationChange) {
-            mHasNavBarScrim = LegacyRecentsImpl.getSystemServices().hasTransposedNavigationBar();
-        }
-        animateScrimToCurrentNavBarState(event.hasStackTasks);
-    }
-
-    public final void onBusEvent(MultiWindowStateChangedEvent event) {
-        mHasDockedTasks = event.inMultiWindow;
-        animateScrimToCurrentNavBarState(event.stack.getTaskCount() > 0);
-    }
-
-    public final void onBusEvent(final DragEndEvent event) {
-        // Hide the nav bar scrims once we drop to a dock region
-        if (event.dropTarget instanceof DockState) {
-            animateScrimToCurrentNavBarState(false /* hasStackTasks */);
-        }
-    }
-
-    public final void onBusEvent(final DragEndCancelledEvent event) {
-        // Restore the scrims to the normal state
-        animateScrimToCurrentNavBarState(event.stack.getTaskCount() > 0);
-    }
-
-    /**
-     * Animates the scrim to match the state of the current nav bar.
-     */
-    private void animateScrimToCurrentNavBarState(boolean hasStackTasks) {
-        boolean hasNavBarScrim = isNavBarScrimRequired(hasStackTasks);
-        if (mHasNavBarScrim != hasNavBarScrim) {
-            AnimationProps animation = hasNavBarScrim
-                    ? createBoundsAnimation(DEFAULT_ANIMATION_DURATION)
-                    : AnimationProps.IMMEDIATE;
-            animateNavBarScrimVisibility(hasNavBarScrim, animation);
-        }
-        mHasNavBarScrim = hasNavBarScrim;
-    }
-
-    /**
-     * @return a default animation to aniamte the bounds of the scrim.
-     */
-    private AnimationProps createBoundsAnimation(int duration) {
-        return new AnimationProps()
-                .setDuration(AnimationProps.BOUNDS, duration)
-                .setInterpolator(AnimationProps.BOUNDS, Interpolators.FAST_OUT_SLOW_IN);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
deleted file mode 100644
index 5574934..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
+++ /dev/null
@@ -1,705 +0,0 @@
-/*
- * Copyright (C) 2015 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.recents.views;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.ValueAnimator;
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.util.Log;
-import android.view.animation.Interpolator;
-import android.view.animation.PathInterpolator;
-
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsActivityLaunchState;
-import com.android.systemui.recents.RecentsConfiguration;
-import com.android.systemui.recents.RecentsDebugFlags;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.component.SetWaitingForTransitionStartEvent;
-import com.android.systemui.recents.misc.ReferenceCountedTrigger;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.recents.views.lowram.TaskStackLowRamLayoutAlgorithm;
-import com.android.systemui.recents.utilities.AnimationProps;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A helper class to create task view animations for {@link TaskView}s in a {@link TaskStackView},
- * but not the contents of the {@link TaskView}s.
- */
-public class TaskStackAnimationHelper {
-
-    /**
-     * Callbacks from the helper to coordinate view-content animations with view animations.
-     */
-    public interface Callbacks {
-        /**
-         * Callback to prepare for the start animation for the launch target {@link TaskView}.
-         */
-        void onPrepareLaunchTargetForEnterAnimation();
-
-        /**
-         * Callback to start the animation for the launch target {@link TaskView}.
-         */
-        void onStartLaunchTargetEnterAnimation(TaskViewTransform transform, int duration,
-                boolean screenPinningEnabled, ReferenceCountedTrigger postAnimationTrigger);
-
-        /**
-         * Callback to start the animation for the launch target {@link TaskView} when it is
-         * launched from Recents.
-         */
-        void onStartLaunchTargetLaunchAnimation(int duration, boolean screenPinningRequested,
-                ReferenceCountedTrigger postAnimationTrigger);
-
-        /**
-         * Callback to start the animation for the front {@link TaskView} if there is no launch
-         * target.
-         */
-        void onStartFrontTaskEnterAnimation(boolean screenPinningEnabled);
-    }
-
-    private static final int DOUBLE_FRAME_OFFSET_MS = 33;
-    private static final int FRAME_OFFSET_MS = 16;
-
-    private static final int ENTER_EXIT_NUM_ANIMATING_TASKS = 5;
-
-    private static final int ENTER_FROM_HOME_ALPHA_DURATION = 100;
-    public static final int ENTER_FROM_HOME_TRANSLATION_DURATION = 300;
-    private static final Interpolator ENTER_FROM_HOME_ALPHA_INTERPOLATOR = Interpolators.LINEAR;
-
-    public static final int EXIT_TO_HOME_TRANSLATION_DURATION = 200;
-    private static final Interpolator EXIT_TO_HOME_TRANSLATION_INTERPOLATOR =
-            new PathInterpolator(0.4f, 0, 0.6f, 1f);
-
-    private static final int DISMISS_TASK_DURATION = 175;
-    private static final int DISMISS_ALL_TASKS_DURATION = 200;
-    private static final Interpolator DISMISS_ALL_TRANSLATION_INTERPOLATOR =
-            new PathInterpolator(0.4f, 0, 1f, 1f);
-
-    private static final Interpolator FOCUS_NEXT_TASK_INTERPOLATOR =
-            new PathInterpolator(0.4f, 0, 0, 1f);
-    private static final Interpolator FOCUS_IN_FRONT_NEXT_TASK_INTERPOLATOR =
-            new PathInterpolator(0, 0, 0, 1f);
-    private static final Interpolator FOCUS_BEHIND_NEXT_TASK_INTERPOLATOR =
-            Interpolators.LINEAR_OUT_SLOW_IN;
-
-    private static final Interpolator ENTER_WHILE_DOCKING_INTERPOLATOR =
-            Interpolators.LINEAR_OUT_SLOW_IN;
-
-    private final int mEnterAndExitFromHomeTranslationOffset;
-    private TaskStackView mStackView;
-
-    private TaskViewTransform mTmpTransform = new TaskViewTransform();
-    private ArrayList<TaskViewTransform> mTmpCurrentTaskTransforms = new ArrayList<>();
-    private ArrayList<TaskViewTransform> mTmpFinalTaskTransforms = new ArrayList<>();
-
-    public TaskStackAnimationHelper(Context context, TaskStackView stackView) {
-        mStackView = stackView;
-        mEnterAndExitFromHomeTranslationOffset = LegacyRecentsImpl.getConfiguration().isGridEnabled
-                ? 0 : DOUBLE_FRAME_OFFSET_MS;
-    }
-
-    /**
-     * Prepares the stack views and puts them in their initial animation state while visible, before
-     * the in-app enter animations start (after the window-transition completes).
-     */
-    public void prepareForEnterAnimation() {
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        RecentsActivityLaunchState launchState = config.getLaunchState();
-        Resources res = mStackView.getResources();
-        Resources appResources = mStackView.getContext().getApplicationContext().getResources();
-
-        TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
-        TaskStackViewScroller stackScroller = mStackView.getScroller();
-        TaskStack stack = mStackView.getStack();
-        Task launchTargetTask = stack.getLaunchTarget();
-
-        // Break early if there are no tasks
-        if (stack.getTaskCount() == 0) {
-            return;
-        }
-
-        int offscreenYOffset = stackLayout.mStackRect.height();
-        int taskViewAffiliateGroupEnterOffset = res.getDimensionPixelSize(
-                R.dimen.recents_task_stack_animation_affiliate_enter_offset);
-        int launchedWhileDockingOffset = res.getDimensionPixelSize(
-                R.dimen.recents_task_stack_animation_launched_while_docking_offset);
-        boolean isLandscape = appResources.getConfiguration().orientation
-                == Configuration.ORIENTATION_LANDSCAPE;
-
-        float top = 0;
-        final boolean isLowRamDevice = LegacyRecentsImpl.getConfiguration().isLowRamDevice;
-        if (isLowRamDevice && launchState.launchedFromApp && !launchState.launchedViaDockGesture) {
-            stackLayout.getStackTransform(launchTargetTask, stackScroller.getStackScroll(),
-                    mTmpTransform, null /* frontTransform */);
-            top = mTmpTransform.rect.top;
-        }
-
-        // Prepare each of the task views for their enter animation from front to back
-        List<TaskView> taskViews = mStackView.getTaskViews();
-        for (int i = taskViews.size() - 1; i >= 0; i--) {
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            // Get the current transform for the task, which will be used to position it offscreen
-            stackLayout.getStackTransform(task, stackScroller.getStackScroll(), mTmpTransform,
-                    null);
-
-            if (launchState.launchedFromApp && !launchState.launchedViaDockGesture) {
-                if (task.isLaunchTarget) {
-                    tv.onPrepareLaunchTargetForEnterAnimation();
-                } else if (isLowRamDevice && i >= taskViews.size() -
-                            (TaskStackLowRamLayoutAlgorithm.MAX_LAYOUT_TASK_COUNT + 1)
-                        && !RecentsDebugFlags.Static.DisableRecentsLowRamEnterExitAnimation) {
-                    // Move the last 2nd and 3rd last tasks in-app animation to match the motion of
-                    // the last task's app transition
-                    stackLayout.getStackTransform(task, stackScroller.getStackScroll(),
-                            mTmpTransform, null);
-                    mTmpTransform.rect.offset(0, -top);
-                    mTmpTransform.alpha = 0f;
-                    mStackView.updateTaskViewToTransform(tv, mTmpTransform,
-                            AnimationProps.IMMEDIATE);
-                    stackLayout.getStackTransform(task, stackScroller.getStackScroll(),
-                            mTmpTransform, null);
-                    mTmpTransform.alpha = 1f;
-                    // Duration see {@link
-                    // com.android.server.wm.AppTransition#DEFAULT_APP_TRANSITION_DURATION}
-                    mStackView.updateTaskViewToTransform(tv, mTmpTransform,
-                            new AnimationProps(336, Interpolators.FAST_OUT_SLOW_IN));
-                }
-            } else if (launchState.launchedFromHome) {
-                if (isLowRamDevice) {
-                    mTmpTransform.rect.offset(0, stackLayout.getTaskRect().height() / 4);
-                } else {
-                    // Move the task view off screen (below) so we can animate it in
-                    mTmpTransform.rect.offset(0, offscreenYOffset);
-                }
-                mTmpTransform.alpha = 0f;
-                mStackView.updateTaskViewToTransform(tv, mTmpTransform, AnimationProps.IMMEDIATE);
-            } else if (launchState.launchedViaDockGesture) {
-                int offset = isLandscape
-                        ? launchedWhileDockingOffset
-                        : (int) (offscreenYOffset * 0.9f);
-                mTmpTransform.rect.offset(0, offset);
-                mTmpTransform.alpha = 0f;
-                mStackView.updateTaskViewToTransform(tv, mTmpTransform, AnimationProps.IMMEDIATE);
-            }
-        }
-    }
-
-    /**
-     * Starts the in-app enter animation, which animates the {@link TaskView}s to their final places
-     * depending on how Recents was triggered.
-     */
-    public void startEnterAnimation(final ReferenceCountedTrigger postAnimationTrigger) {
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        RecentsActivityLaunchState launchState = config.getLaunchState();
-        Resources res = mStackView.getResources();
-        Resources appRes = mStackView.getContext().getApplicationContext().getResources();
-
-        TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
-        TaskStackViewScroller stackScroller = mStackView.getScroller();
-        TaskStack stack = mStackView.getStack();
-        Task launchTargetTask = stack.getLaunchTarget();
-
-        // Break early if there are no tasks
-        if (stack.getTaskCount() == 0) {
-            return;
-        }
-
-        final boolean isLowRamDevice = LegacyRecentsImpl.getConfiguration().isLowRamDevice;
-        int taskViewEnterFromAppDuration = res.getInteger(
-                R.integer.recents_task_enter_from_app_duration);
-        int taskViewEnterFromAffiliatedAppDuration = res.getInteger(
-                R.integer.recents_task_enter_from_affiliated_app_duration);
-        int dockGestureAnimDuration = appRes.getInteger(
-                R.integer.long_press_dock_anim_duration);
-
-        // Since low ram devices have an animation when entering app -> recents, do not allow
-        // toggle until the animation is complete
-        if (launchState.launchedFromApp && !launchState.launchedViaDockGesture && isLowRamDevice) {
-            postAnimationTrigger.addLastDecrementRunnable(() -> EventBus.getDefault()
-                .send(new SetWaitingForTransitionStartEvent(false)));
-        }
-
-        // Create enter animations for each of the views from front to back
-        List<TaskView> taskViews = mStackView.getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = taskViewCount - 1; i >= 0; i--) {
-            int taskIndexFromFront = taskViewCount - i - 1;
-            int taskIndexFromBack = i;
-            final TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            // Get the current transform for the task, which will be updated to the final transform
-            // to animate to depending on how recents was invoked
-            stackLayout.getStackTransform(task, stackScroller.getStackScroll(), mTmpTransform,
-                    null);
-
-            if (launchState.launchedFromApp && !launchState.launchedViaDockGesture) {
-                if (task.isLaunchTarget) {
-                    tv.onStartLaunchTargetEnterAnimation(mTmpTransform,
-                            taskViewEnterFromAppDuration, mStackView.mScreenPinningEnabled,
-                            postAnimationTrigger);
-                }
-
-            } else if (launchState.launchedFromHome) {
-                // Animate the tasks up, but offset the animations to be relative to the front-most
-                // task animation
-                final float startOffsetFraction = (float) (Math.min(ENTER_EXIT_NUM_ANIMATING_TASKS,
-                        taskIndexFromFront) * mEnterAndExitFromHomeTranslationOffset) /
-                        ENTER_FROM_HOME_TRANSLATION_DURATION;
-                AnimationProps taskAnimation = new AnimationProps()
-                        .setInterpolator(AnimationProps.ALPHA, ENTER_FROM_HOME_ALPHA_INTERPOLATOR)
-                        .setListener(postAnimationTrigger.decrementOnAnimationEnd());
-                if (isLowRamDevice) {
-                    taskAnimation.setInterpolator(AnimationProps.BOUNDS,
-                            Interpolators.FAST_OUT_SLOW_IN)
-                            .setDuration(AnimationProps.BOUNDS, 150)
-                            .setDuration(AnimationProps.ALPHA, 150);
-                } else {
-                    taskAnimation.setStartDelay(AnimationProps.ALPHA,
-                                Math.min(ENTER_EXIT_NUM_ANIMATING_TASKS, taskIndexFromFront) *
-                                        FRAME_OFFSET_MS)
-                            .setInterpolator(AnimationProps.BOUNDS,
-                                new RecentsEntrancePathInterpolator(0f, 0f, 0.2f, 1f,
-                                        startOffsetFraction))
-                            .setDuration(AnimationProps.BOUNDS, ENTER_FROM_HOME_TRANSLATION_DURATION)
-                            .setDuration(AnimationProps.ALPHA, ENTER_FROM_HOME_ALPHA_DURATION);
-                }
-                postAnimationTrigger.increment();
-                mStackView.updateTaskViewToTransform(tv, mTmpTransform, taskAnimation);
-                if (i == taskViewCount - 1) {
-                    tv.onStartFrontTaskEnterAnimation(mStackView.mScreenPinningEnabled);
-                }
-            } else if (launchState.launchedViaDockGesture) {
-                // Animate the tasks up - add some delay to match the divider animation
-                AnimationProps taskAnimation = new AnimationProps()
-                        .setDuration(AnimationProps.BOUNDS, dockGestureAnimDuration +
-                                (taskIndexFromBack * DOUBLE_FRAME_OFFSET_MS))
-                        .setInterpolator(AnimationProps.BOUNDS,
-                                ENTER_WHILE_DOCKING_INTERPOLATOR)
-                        .setStartDelay(AnimationProps.BOUNDS, 48)
-                        .setListener(postAnimationTrigger.decrementOnAnimationEnd());
-                postAnimationTrigger.increment();
-                mStackView.updateTaskViewToTransform(tv, mTmpTransform, taskAnimation);
-            }
-        }
-    }
-
-    /**
-     * Starts an in-app animation to hide all the task views so that we can transition back home.
-     */
-    public void startExitToHomeAnimation(boolean animated,
-            ReferenceCountedTrigger postAnimationTrigger) {
-        TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
-        TaskStack stack = mStackView.getStack();
-
-        // Break early if there are no tasks
-        if (stack.getTaskCount() == 0) {
-            return;
-        }
-
-        int offscreenYOffset = stackLayout.mStackRect.height();
-
-        // Create the animations for each of the tasks
-        List<TaskView> taskViews = mStackView.getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            int taskIndexFromFront = taskViewCount - i - 1;
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            if (mStackView.isIgnoredTask(task)) {
-                continue;
-            }
-
-            // Animate the tasks down
-            AnimationProps taskAnimation;
-            if (animated) {
-                int delay = Math.min(ENTER_EXIT_NUM_ANIMATING_TASKS , taskIndexFromFront) *
-                        mEnterAndExitFromHomeTranslationOffset;
-                taskAnimation = new AnimationProps()
-                        .setDuration(AnimationProps.BOUNDS, EXIT_TO_HOME_TRANSLATION_DURATION)
-                        .setListener(postAnimationTrigger.decrementOnAnimationEnd());
-                if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                    taskAnimation.setInterpolator(AnimationProps.BOUNDS,
-                            Interpolators.FAST_OUT_SLOW_IN);
-                } else {
-                    taskAnimation.setStartDelay(AnimationProps.BOUNDS, delay)
-                            .setInterpolator(AnimationProps.BOUNDS,
-                                    EXIT_TO_HOME_TRANSLATION_INTERPOLATOR);
-                }
-                postAnimationTrigger.increment();
-            } else {
-                taskAnimation = AnimationProps.IMMEDIATE;
-            }
-
-            mTmpTransform.fillIn(tv);
-            if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                taskAnimation.setInterpolator(AnimationProps.ALPHA,
-                                EXIT_TO_HOME_TRANSLATION_INTERPOLATOR)
-                        .setDuration(AnimationProps.ALPHA, EXIT_TO_HOME_TRANSLATION_DURATION);
-                mTmpTransform.rect.offset(0, stackLayout.mTaskStackLowRamLayoutAlgorithm
-                        .getTaskRect().height() / 4);
-                mTmpTransform.alpha = 0f;
-            } else {
-                mTmpTransform.rect.offset(0, offscreenYOffset);
-            }
-            mStackView.updateTaskViewToTransform(tv, mTmpTransform, taskAnimation);
-        }
-    }
-
-    /**
-     * Starts the animation for the launching task view, hiding any tasks that might occlude the
-     * window transition for the launching task.
-     */
-    public void startLaunchTaskAnimation(TaskView launchingTaskView, boolean screenPinningRequested,
-            final ReferenceCountedTrigger postAnimationTrigger) {
-        Resources res = mStackView.getResources();
-
-        int taskViewExitToAppDuration = res.getInteger(
-                R.integer.recents_task_exit_to_app_duration);
-        int taskViewAffiliateGroupEnterOffset = res.getDimensionPixelSize(
-                R.dimen.recents_task_stack_animation_affiliate_enter_offset);
-
-        Task launchingTask = launchingTaskView.getTask();
-        List<TaskView> taskViews = mStackView.getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            if (tv == launchingTaskView) {
-                tv.setClipViewInStack(false);
-                postAnimationTrigger.addLastDecrementRunnable(new Runnable() {
-                    @Override
-                    public void run() {
-                        tv.setClipViewInStack(true);
-                    }
-                });
-                tv.onStartLaunchTargetLaunchAnimation(taskViewExitToAppDuration,
-                        screenPinningRequested, postAnimationTrigger);
-            }
-        }
-    }
-
-    /**
-     * Starts the delete animation for the specified {@link TaskView}.
-     */
-    public void startDeleteTaskAnimation(final TaskView deleteTaskView, boolean gridLayout,
-            final ReferenceCountedTrigger postAnimationTrigger) {
-        if (gridLayout) {
-            startTaskGridDeleteTaskAnimation(deleteTaskView, postAnimationTrigger);
-        } else {
-            startTaskStackDeleteTaskAnimation(deleteTaskView, postAnimationTrigger);
-        }
-    }
-
-    /**
-     * Starts the delete animation for all the {@link TaskView}s.
-     */
-    public void startDeleteAllTasksAnimation(final List<TaskView> taskViews, boolean gridLayout,
-            final ReferenceCountedTrigger postAnimationTrigger) {
-        if (gridLayout) {
-            for (int i = 0; i < taskViews.size(); i++) {
-                startTaskGridDeleteTaskAnimation(taskViews.get(i), postAnimationTrigger);
-            }
-        } else {
-            startTaskStackDeleteAllTasksAnimation(taskViews, postAnimationTrigger);
-        }
-    }
-
-    /**
-     * Starts the animation to focus the next {@link TaskView} when paging through recents.
-     *
-     * @return whether or not this will trigger a scroll in the stack
-     */
-    public boolean startScrollToFocusedTaskAnimation(Task newFocusedTask,
-            boolean requestViewFocus) {
-        TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
-        TaskStackViewScroller stackScroller = mStackView.getScroller();
-        TaskStack stack = mStackView.getStack();
-
-        final float curScroll = stackScroller.getStackScroll();
-        final float newScroll = stackScroller.getBoundedStackScroll(
-                stackLayout.getStackScrollForTask(newFocusedTask));
-        boolean willScrollToFront = newScroll > curScroll;
-        boolean willScroll = Float.compare(newScroll, curScroll) != 0;
-
-        // Get the current set of task transforms
-        int taskViewCount = mStackView.getTaskViews().size();
-        ArrayList<Task> stackTasks = stack.getTasks();
-        mStackView.getCurrentTaskTransforms(stackTasks, mTmpCurrentTaskTransforms);
-
-        // Pick up the newly visible views after the scroll
-        mStackView.bindVisibleTaskViews(newScroll);
-
-        // Update the internal state
-        stackLayout.setFocusState(TaskStackLayoutAlgorithm.STATE_FOCUSED);
-        stackScroller.setStackScroll(newScroll, null /* animation */);
-        mStackView.cancelDeferredTaskViewLayoutAnimation();
-
-        // Get the final set of task transforms
-        mStackView.getLayoutTaskTransforms(newScroll, stackLayout.getFocusState(), stackTasks,
-                true /* ignoreTaskOverrides */, mTmpFinalTaskTransforms);
-
-        // Focus the task view
-        TaskView newFocusedTaskView = mStackView.getChildViewForTask(newFocusedTask);
-        if (newFocusedTaskView == null) {
-            // Log the error if we have no task view, and skip the animation
-            Log.e("TaskStackAnimationHelper", "b/27389156 null-task-view prebind:" + taskViewCount +
-                    " postbind:" + mStackView.getTaskViews().size() + " prescroll:" + curScroll +
-                    " postscroll: " + newScroll);
-            return false;
-        }
-        newFocusedTaskView.setFocusedState(true, requestViewFocus);
-
-        // Setup the end listener to return all the hidden views to the view pool after the
-        // focus animation
-        ReferenceCountedTrigger postAnimTrigger = new ReferenceCountedTrigger();
-        postAnimTrigger.addLastDecrementRunnable(new Runnable() {
-            @Override
-            public void run() {
-                mStackView.bindVisibleTaskViews(newScroll);
-            }
-        });
-
-        List<TaskView> taskViews = mStackView.getTaskViews();
-        taskViewCount = taskViews.size();
-        int newFocusTaskViewIndex = taskViews.indexOf(newFocusedTaskView);
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            if (mStackView.isIgnoredTask(task)) {
-                continue;
-            }
-
-            int taskIndex = stackTasks.indexOf(task);
-            TaskViewTransform fromTransform = mTmpCurrentTaskTransforms.get(taskIndex);
-            TaskViewTransform toTransform = mTmpFinalTaskTransforms.get(taskIndex);
-
-            // Update the task to the initial state (for the newly picked up tasks)
-            mStackView.updateTaskViewToTransform(tv, fromTransform, AnimationProps.IMMEDIATE);
-
-            int duration;
-            Interpolator interpolator;
-            if (willScrollToFront) {
-                duration = calculateStaggeredAnimDuration(i);
-                interpolator = FOCUS_BEHIND_NEXT_TASK_INTERPOLATOR;
-            } else {
-                if (i < newFocusTaskViewIndex) {
-                    duration = 150 + ((newFocusTaskViewIndex - i - 1) * 50);
-                    interpolator = FOCUS_BEHIND_NEXT_TASK_INTERPOLATOR;
-                } else if (i > newFocusTaskViewIndex) {
-                    duration = Math.max(100, 150 - ((i - newFocusTaskViewIndex - 1) * 50));
-                    interpolator = FOCUS_IN_FRONT_NEXT_TASK_INTERPOLATOR;
-                } else {
-                    duration = 200;
-                    interpolator = FOCUS_NEXT_TASK_INTERPOLATOR;
-                }
-            }
-
-            AnimationProps anim = new AnimationProps()
-                    .setDuration(AnimationProps.BOUNDS, duration)
-                    .setInterpolator(AnimationProps.BOUNDS, interpolator)
-                    .setListener(postAnimTrigger.decrementOnAnimationEnd());
-            postAnimTrigger.increment();
-            mStackView.updateTaskViewToTransform(tv, toTransform, anim);
-        }
-        return willScroll;
-    }
-
-    /**
-     * Starts the animation to go to the initial stack layout with a task focused.  In addition, the
-     * previous task will be animated in after the scroll completes.
-     */
-    public void startNewStackScrollAnimation(TaskStack newStack,
-            ReferenceCountedTrigger animationTrigger) {
-        TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
-        TaskStackViewScroller stackScroller = mStackView.getScroller();
-
-        // Get the current set of task transforms
-        ArrayList<Task> stackTasks = newStack.getTasks();
-        mStackView.getCurrentTaskTransforms(stackTasks, mTmpCurrentTaskTransforms);
-
-        // Update the stack
-        mStackView.setTasks(newStack, false /* allowNotifyStackChanges */);
-        mStackView.updateLayoutAlgorithm(false /* boundScroll */);
-
-        // Pick up the newly visible views after the scroll
-        final float newScroll = stackLayout.mInitialScrollP;
-        mStackView.bindVisibleTaskViews(newScroll);
-
-        // Update the internal state
-        stackLayout.setFocusState(TaskStackLayoutAlgorithm.STATE_UNFOCUSED);
-        stackLayout.setTaskOverridesForInitialState(newStack, true /* ignoreScrollToFront */);
-        stackScroller.setStackScroll(newScroll);
-        mStackView.cancelDeferredTaskViewLayoutAnimation();
-
-        // Get the final set of task transforms
-        mStackView.getLayoutTaskTransforms(newScroll, stackLayout.getFocusState(), stackTasks,
-                false /* ignoreTaskOverrides */, mTmpFinalTaskTransforms);
-
-        // Hide the front most task view until the scroll is complete
-        Task frontMostTask = newStack.getFrontMostTask();
-        final TaskView frontMostTaskView = mStackView.getChildViewForTask(frontMostTask);
-        final TaskViewTransform frontMostTransform = mTmpFinalTaskTransforms.get(
-                stackTasks.indexOf(frontMostTask));
-        if (frontMostTaskView != null) {
-            mStackView.updateTaskViewToTransform(frontMostTaskView,
-                    stackLayout.getFrontOfStackTransform(), AnimationProps.IMMEDIATE);
-        }
-
-        // Setup the end listener to return all the hidden views to the view pool after the
-        // focus animation
-        animationTrigger.addLastDecrementRunnable(new Runnable() {
-            @Override
-            public void run() {
-                mStackView.bindVisibleTaskViews(newScroll);
-
-                // Now, animate in the front-most task
-                if (frontMostTaskView != null) {
-                    mStackView.updateTaskViewToTransform(frontMostTaskView, frontMostTransform,
-                            new AnimationProps(75, 250, FOCUS_BEHIND_NEXT_TASK_INTERPOLATOR));
-                }
-            }
-        });
-
-        List<TaskView> taskViews = mStackView.getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            if (mStackView.isIgnoredTask(task)) {
-                continue;
-            }
-            if (task == frontMostTask && frontMostTaskView != null) {
-                continue;
-            }
-
-            int taskIndex = stackTasks.indexOf(task);
-            TaskViewTransform fromTransform = mTmpCurrentTaskTransforms.get(taskIndex);
-            TaskViewTransform toTransform = mTmpFinalTaskTransforms.get(taskIndex);
-
-            // Update the task to the initial state (for the newly picked up tasks)
-            mStackView.updateTaskViewToTransform(tv, fromTransform, AnimationProps.IMMEDIATE);
-
-            int duration = calculateStaggeredAnimDuration(i);
-            Interpolator interpolator = FOCUS_BEHIND_NEXT_TASK_INTERPOLATOR;
-
-            AnimationProps anim = new AnimationProps()
-                    .setDuration(AnimationProps.BOUNDS, duration)
-                    .setInterpolator(AnimationProps.BOUNDS, interpolator)
-                    .setListener(animationTrigger.decrementOnAnimationEnd());
-            animationTrigger.increment();
-            mStackView.updateTaskViewToTransform(tv, toTransform, anim);
-        }
-    }
-
-    /**
-     * Caclulates a staggered duration for {@link #startScrollToFocusedTaskAnimation} and
-     * {@link #startNewStackScrollAnimation}.
-     */
-    private int calculateStaggeredAnimDuration(int i) {
-        return Math.max(100, 100 + ((i - 1) * 50));
-    }
-
-    private void startTaskGridDeleteTaskAnimation(final TaskView deleteTaskView,
-            final ReferenceCountedTrigger postAnimationTrigger) {
-        postAnimationTrigger.increment();
-        postAnimationTrigger.addLastDecrementRunnable(() -> {
-            mStackView.getTouchHandler().onChildDismissed(deleteTaskView);
-        });
-        deleteTaskView.animate().setDuration(300).scaleX(0.9f).scaleY(0.9f).alpha(0).setListener(
-                new AnimatorListenerAdapter() {
-                    @Override
-                    public void onAnimationEnd(Animator animation) {
-                        postAnimationTrigger.decrement();
-                    }}).start();
-    }
-
-    private void startTaskStackDeleteTaskAnimation(final TaskView deleteTaskView,
-            final ReferenceCountedTrigger postAnimationTrigger) {
-        TaskStackViewTouchHandler touchHandler = mStackView.getTouchHandler();
-        touchHandler.onBeginManualDrag(deleteTaskView);
-
-        postAnimationTrigger.increment();
-        postAnimationTrigger.addLastDecrementRunnable(() -> {
-            touchHandler.onChildDismissed(deleteTaskView);
-        });
-
-        final float dismissSize = touchHandler.getScaledDismissSize();
-        ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
-        animator.setDuration(400);
-        animator.addUpdateListener((animation) -> {
-            float progress = (Float) animation.getAnimatedValue();
-            deleteTaskView.setTranslationX(progress * dismissSize);
-            touchHandler.updateSwipeProgress(deleteTaskView, true, progress);
-        });
-        animator.addListener(new AnimatorListenerAdapter() {
-            @Override
-            public void onAnimationEnd(Animator animation) {
-                postAnimationTrigger.decrement();
-            }
-        });
-        animator.start();
-    }
-
-    private void startTaskStackDeleteAllTasksAnimation(final List<TaskView> taskViews,
-            final ReferenceCountedTrigger postAnimationTrigger) {
-        TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
-
-        int offscreenXOffset = mStackView.getMeasuredWidth() - stackLayout.getTaskRect().left;
-
-        int taskViewCount = taskViews.size();
-        for (int i = taskViewCount - 1; i >= 0; i--) {
-            TaskView tv = taskViews.get(i);
-            int taskIndexFromFront = taskViewCount - i - 1;
-            int startDelay = taskIndexFromFront * DOUBLE_FRAME_OFFSET_MS;
-
-            // Disabling clipping with the stack while the view is animating away
-            tv.setClipViewInStack(false);
-
-            // Compose the new animation and transform and star the animation
-            AnimationProps taskAnimation = new AnimationProps(startDelay,
-                    DISMISS_ALL_TASKS_DURATION, DISMISS_ALL_TRANSLATION_INTERPOLATOR,
-                    new AnimatorListenerAdapter() {
-                        @Override
-                        public void onAnimationEnd(Animator animation) {
-                            postAnimationTrigger.decrement();
-
-                            // Re-enable clipping with the stack (we will reuse this view)
-                            tv.setClipViewInStack(true);
-                        }
-                    });
-            postAnimationTrigger.increment();
-
-            mTmpTransform.fillIn(tv);
-            mTmpTransform.rect.offset(offscreenXOffset, 0);
-            mStackView.updateTaskViewToTransform(tv, mTmpTransform, taskAnimation);
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
deleted file mode 100644
index 58a3f12..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
+++ /dev/null
@@ -1,1283 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.annotation.IntDef;
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.graphics.Path;
-import android.graphics.Rect;
-import android.util.ArraySet;
-import android.util.Log;
-import android.util.SparseArray;
-import android.util.SparseIntArray;
-import android.view.ViewDebug;
-
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsActivityLaunchState;
-import com.android.systemui.recents.RecentsConfiguration;
-import com.android.systemui.recents.RecentsDebugFlags;
-import com.android.systemui.recents.misc.FreePathInterpolator;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.recents.views.lowram.TaskStackLowRamLayoutAlgorithm;
-import com.android.systemui.recents.views.grid.TaskGridLayoutAlgorithm;
-
-import java.io.PrintWriter;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Used to describe a visible range that can be normalized to [0, 1].
- */
-class Range {
-    final float relativeMin;
-    final float relativeMax;
-    float origin;
-    float min;
-    float max;
-
-    public Range(float relMin, float relMax) {
-        min = relativeMin = relMin;
-        max = relativeMax = relMax;
-    }
-
-    /**
-     * Offsets this range to a given absolute position.
-     */
-    public void offset(float x) {
-        this.origin = x;
-        min = x + relativeMin;
-        max = x + relativeMax;
-    }
-
-    /**
-     * Returns x normalized to the range 0 to 1 such that 0 = min, 0.5 = origin and 1 = max
-     *
-     * @param x is an absolute value in the same domain as origin
-     */
-    public float getNormalizedX(float x) {
-        if (x < origin) {
-            return 0.5f + 0.5f * (x - origin) / -relativeMin;
-        } else {
-            return 0.5f + 0.5f * (x - origin) / relativeMax;
-        }
-    }
-
-    /**
-     * Given a normalized {@param x} value in this range, projected onto the full range to get an
-     * absolute value about the given {@param origin}.
-     */
-    public float getAbsoluteX(float normX) {
-        if (normX < 0.5f) {
-            return (normX - 0.5f) / 0.5f * -relativeMin;
-        } else {
-            return (normX - 0.5f) / 0.5f * relativeMax;
-        }
-    }
-
-    /**
-     * Returns whether a value at an absolute x would be within range.
-     */
-    public boolean isInRange(float absX) {
-        return (absX >= Math.floor(min)) && (absX <= Math.ceil(max));
-    }
-}
-
-/**
- * The layout logic for a TaskStackView.  This layout needs to be able to calculate the stack layout
- * without an activity-specific context only with the information passed in.  This layout can have
- * two states focused and unfocused, and in the focused state, there is a task that is displayed
- * more prominently in the stack.
- */
-public class TaskStackLayoutAlgorithm {
-
-    private static final String TAG = "TaskStackLayoutAlgorithm";
-
-    // The distribution of view bounds alpha
-    // XXX: This is a hack because you can currently set the max alpha to be > 1f
-    public static final float OUTLINE_ALPHA_MIN_VALUE = 0f;
-    public static final float OUTLINE_ALPHA_MAX_VALUE = 2f;
-
-    // The medium/maximum dim on the tasks
-    private static final float MED_DIM = 0.15f;
-    private static final float MAX_DIM = 0.25f;
-
-    // The various focus states
-    public static final int STATE_FOCUSED = 1;
-    public static final int STATE_UNFOCUSED = 0;
-
-    // The side that an offset is anchored
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef({FROM_TOP, FROM_BOTTOM})
-    public @interface AnchorSide {}
-    private static final int FROM_TOP = 0;
-    private static final int FROM_BOTTOM = 1;
-
-    // The extent that we care about when calculating fractions
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef({WIDTH, HEIGHT})
-    public @interface Extent {}
-    private static final int WIDTH = 0;
-    private static final int HEIGHT = 1;
-
-    public interface TaskStackLayoutAlgorithmCallbacks {
-        void onFocusStateChanged(int prevFocusState, int curFocusState);
-    }
-
-    /**
-     * @return True if we should use the grid layout.
-     */
-    boolean useGridLayout() {
-        return LegacyRecentsImpl.getConfiguration().isGridEnabled;
-    }
-
-    // A report of the visibility state of the stack
-    public static class VisibilityReport {
-        public int numVisibleTasks;
-        public int numVisibleThumbnails;
-
-        public VisibilityReport(int tasks, int thumbnails) {
-            numVisibleTasks = tasks;
-            numVisibleThumbnails = thumbnails;
-        }
-    }
-
-    Context mContext;
-    private TaskStackLayoutAlgorithmCallbacks mCb;
-
-    // The task bounds (untransformed) for layout.  This rect is anchored at mTaskRoot.
-    @ViewDebug.ExportedProperty(category="recents")
-    public Rect mTaskRect = new Rect();
-    // The stack bounds, inset from the top system insets, and runs to the bottom of the screen
-    @ViewDebug.ExportedProperty(category="recents")
-    public Rect mStackRect = new Rect();
-    // This is the current system insets
-    @ViewDebug.ExportedProperty(category="recents")
-    public Rect mSystemInsets = new Rect();
-
-    // The visible ranges when the stack is focused and unfocused
-    private Range mUnfocusedRange;
-    private Range mFocusedRange;
-
-    // This is the bounds of the stack action above the stack rect
-    @ViewDebug.ExportedProperty(category="recents")
-    private Rect mStackActionButtonRect = new Rect();
-    // The base top margin for the stack from the system insets
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mBaseTopMargin;
-    // The base side margin for the stack from the system insets
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mBaseSideMargin;
-    // The base bottom margin for the stack from the system insets
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mBaseBottomMargin;
-    private int mMinMargin;
-
-    // The initial offset that the focused task is from the top
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mInitialTopOffset;
-    private int mBaseInitialTopOffset;
-    // The initial offset that the launch-from task is from the bottom
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mInitialBottomOffset;
-    private int mBaseInitialBottomOffset;
-
-    // The height between the top margin and the top of the focused task
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mFocusedTopPeekHeight;
-    // The height between the bottom margin and the top of task in front of the focused task
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mFocusedBottomPeekHeight;
-
-    // The offset from the bottom of the stack to the bottom of the bounds when the stack is
-    // scrolled to the front
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mStackBottomOffset;
-
-    /** The height, in pixels, of each task view's title bar. */
-    private int mTitleBarHeight;
-
-    // The paths defining the motion of the tasks when the stack is focused and unfocused
-    private Path mUnfocusedCurve;
-    private Path mFocusedCurve;
-    private FreePathInterpolator mUnfocusedCurveInterpolator;
-    private FreePathInterpolator mFocusedCurveInterpolator;
-
-    // The paths defining the distribution of the dim to apply to tasks in the stack when focused
-    // and unfocused
-    private Path mUnfocusedDimCurve;
-    private Path mFocusedDimCurve;
-    private FreePathInterpolator mUnfocusedDimCurveInterpolator;
-    private FreePathInterpolator mFocusedDimCurveInterpolator;
-
-    // The state of the stack focus (0..1), which controls the transition of the stack from the
-    // focused to non-focused state
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mFocusState;
-
-    // The smallest scroll progress, at this value, the back most task will be visible
-    @ViewDebug.ExportedProperty(category="recents")
-    float mMinScrollP;
-    // The largest scroll progress, at this value, the front most task will be visible above the
-    // navigation bar
-    @ViewDebug.ExportedProperty(category="recents")
-    float mMaxScrollP;
-    // The initial progress that the scroller is set when you first enter recents
-    @ViewDebug.ExportedProperty(category="recents")
-    float mInitialScrollP;
-    // The task progress for the front-most task in the stack
-    @ViewDebug.ExportedProperty(category="recents")
-    float mFrontMostTaskP;
-
-    // The last computed task counts
-    @ViewDebug.ExportedProperty(category="recents")
-    int mNumStackTasks;
-
-    // The min/max z translations
-    @ViewDebug.ExportedProperty(category="recents")
-    int mMinTranslationZ;
-    @ViewDebug.ExportedProperty(category="recents")
-    public int mMaxTranslationZ;
-
-    // Optimization, allows for quick lookup of task -> index
-    private SparseIntArray mTaskIndexMap = new SparseIntArray();
-    private SparseArray<Float> mTaskIndexOverrideMap = new SparseArray<>();
-
-    TaskGridLayoutAlgorithm mTaskGridLayoutAlgorithm;
-    TaskStackLowRamLayoutAlgorithm mTaskStackLowRamLayoutAlgorithm;
-
-    // The transform to place TaskViews at the front and back of the stack respectively
-    TaskViewTransform mBackOfStackTransform = new TaskViewTransform();
-    TaskViewTransform mFrontOfStackTransform = new TaskViewTransform();
-
-    public TaskStackLayoutAlgorithm(Context context, TaskStackLayoutAlgorithmCallbacks cb) {
-        mContext = context;
-        mCb = cb;
-        mTaskGridLayoutAlgorithm = new TaskGridLayoutAlgorithm(context);
-        mTaskStackLowRamLayoutAlgorithm = new TaskStackLowRamLayoutAlgorithm(context);
-        reloadOnConfigurationChange(context);
-    }
-
-    /**
-     * Reloads the layout for the current configuration.
-     */
-    public void reloadOnConfigurationChange(Context context) {
-        Resources res = context.getResources();
-        mFocusedRange = new Range(res.getFloat(R.integer.recents_layout_focused_range_min),
-                res.getFloat(R.integer.recents_layout_focused_range_max));
-        mUnfocusedRange = new Range(res.getFloat(R.integer.recents_layout_unfocused_range_min),
-                res.getFloat(R.integer.recents_layout_unfocused_range_max));
-        mFocusState = getInitialFocusState();
-        mFocusedTopPeekHeight = res.getDimensionPixelSize(R.dimen.recents_layout_top_peek_size);
-        mFocusedBottomPeekHeight =
-                res.getDimensionPixelSize(R.dimen.recents_layout_bottom_peek_size);
-        mMinTranslationZ = res.getDimensionPixelSize(R.dimen.recents_layout_z_min);
-        mMaxTranslationZ = res.getDimensionPixelSize(R.dimen.recents_layout_z_max);
-        mBaseInitialTopOffset = getDimensionForDevice(context,
-                R.dimen.recents_layout_initial_top_offset_phone_port,
-                R.dimen.recents_layout_initial_top_offset_phone_land,
-                R.dimen.recents_layout_initial_top_offset_tablet,
-                R.dimen.recents_layout_initial_top_offset_tablet,
-                R.dimen.recents_layout_initial_top_offset_tablet,
-                R.dimen.recents_layout_initial_top_offset_tablet,
-                R.dimen.recents_layout_initial_top_offset_tablet);
-        mBaseInitialBottomOffset = getDimensionForDevice(context,
-                R.dimen.recents_layout_initial_bottom_offset_phone_port,
-                R.dimen.recents_layout_initial_bottom_offset_phone_land,
-                R.dimen.recents_layout_initial_bottom_offset_tablet,
-                R.dimen.recents_layout_initial_bottom_offset_tablet,
-                R.dimen.recents_layout_initial_bottom_offset_tablet,
-                R.dimen.recents_layout_initial_bottom_offset_tablet,
-                R.dimen.recents_layout_initial_bottom_offset_tablet);
-        mTaskGridLayoutAlgorithm.reloadOnConfigurationChange(context);
-        mTaskStackLowRamLayoutAlgorithm.reloadOnConfigurationChange(context);
-        mMinMargin = res.getDimensionPixelSize(R.dimen.recents_layout_min_margin);
-        mBaseTopMargin = getDimensionForDevice(context,
-                R.dimen.recents_layout_top_margin_phone,
-                R.dimen.recents_layout_top_margin_tablet,
-                R.dimen.recents_layout_top_margin_tablet_xlarge,
-                R.dimen.recents_layout_top_margin_tablet);
-        mBaseSideMargin = getDimensionForDevice(context,
-                R.dimen.recents_layout_side_margin_phone,
-                R.dimen.recents_layout_side_margin_tablet,
-                R.dimen.recents_layout_side_margin_tablet_xlarge,
-                R.dimen.recents_layout_side_margin_tablet);
-        mBaseBottomMargin = res.getDimensionPixelSize(R.dimen.recents_layout_bottom_margin);
-        mTitleBarHeight = getDimensionForDevice(mContext,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height_tablet_land,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height_tablet_land,
-                R.dimen.recents_grid_task_view_header_height);
-    }
-
-    /**
-     * Resets this layout when the stack view is reset.
-     */
-    public void reset() {
-        mTaskIndexOverrideMap.clear();
-        setFocusState(getInitialFocusState());
-    }
-
-    /**
-     * Sets the system insets.
-     */
-    public boolean setSystemInsets(Rect systemInsets) {
-        boolean changed = !mSystemInsets.equals(systemInsets);
-        mSystemInsets.set(systemInsets);
-        mTaskGridLayoutAlgorithm.setSystemInsets(systemInsets);
-        mTaskStackLowRamLayoutAlgorithm.setSystemInsets(systemInsets);
-        return changed;
-    }
-
-    /**
-     * Sets the focused state.
-     */
-    public void setFocusState(int focusState) {
-        int prevFocusState = mFocusState;
-        mFocusState = focusState;
-        updateFrontBackTransforms();
-        if (mCb != null) {
-            mCb.onFocusStateChanged(prevFocusState, focusState);
-        }
-    }
-
-    /**
-     * Gets the focused state.
-     */
-    public int getFocusState() {
-        return mFocusState;
-    }
-
-    /**
-     * Computes the stack and task rects.  The given task stack bounds already has the top/right
-     * insets and left/right padding already applied.
-     */
-    public void initialize(Rect displayRect, Rect windowRect, Rect taskStackBounds) {
-        Rect lastStackRect = new Rect(mStackRect);
-
-        int topMargin = getScaleForExtent(windowRect, displayRect, mBaseTopMargin, mMinMargin, HEIGHT);
-        int bottomMargin = getScaleForExtent(windowRect, displayRect, mBaseBottomMargin, mMinMargin,
-                HEIGHT);
-        mInitialTopOffset = getScaleForExtent(windowRect, displayRect, mBaseInitialTopOffset,
-                mMinMargin, HEIGHT);
-        mInitialBottomOffset = mBaseInitialBottomOffset;
-
-        // Compute the stack bounds
-        mStackBottomOffset = mSystemInsets.bottom + bottomMargin;
-        mStackRect.set(taskStackBounds);
-        mStackRect.top += topMargin;
-
-        // The stack action button will take the full un-padded header space above the stack
-        mStackActionButtonRect.set(mStackRect.left, mStackRect.top - topMargin,
-                mStackRect.right, mStackRect.top + mFocusedTopPeekHeight);
-
-        // Anchor the task rect top aligned to the stack rect
-        int height = mStackRect.height() - mInitialTopOffset - mStackBottomOffset;
-        mTaskRect.set(mStackRect.left, mStackRect.top, mStackRect.right, mStackRect.top + height);
-
-        if (mTaskRect.width() <= 0 || mTaskRect.height() <= 0) {
-            // Logging for b/36654830
-            Log.e(TAG, "Invalid task rect: taskRect=" + mTaskRect + " stackRect=" + mStackRect
-                    + " displayRect=" + displayRect + " windowRect=" + windowRect
-                    + " taskStackBounds=" + taskStackBounds);
-        }
-
-        // Short circuit here if the stack rects haven't changed so we don't do all the work below
-        if (!lastStackRect.equals(mStackRect)) {
-            // Reinitialize the focused and unfocused curves
-            mUnfocusedCurve = constructUnfocusedCurve();
-            mUnfocusedCurveInterpolator = new FreePathInterpolator(mUnfocusedCurve);
-            mFocusedCurve = constructFocusedCurve();
-            mFocusedCurveInterpolator = new FreePathInterpolator(mFocusedCurve);
-            mUnfocusedDimCurve = constructUnfocusedDimCurve();
-            mUnfocusedDimCurveInterpolator = new FreePathInterpolator(mUnfocusedDimCurve);
-            mFocusedDimCurve = constructFocusedDimCurve();
-            mFocusedDimCurveInterpolator = new FreePathInterpolator(mFocusedDimCurve);
-
-            updateFrontBackTransforms();
-        }
-
-        // Initialize the grid layout
-        mTaskGridLayoutAlgorithm.initialize(windowRect);
-        mTaskStackLowRamLayoutAlgorithm.initialize(windowRect);
-    }
-
-    /**
-     * Computes the minimum and maximum scroll progress values and the progress values for each task
-     * in the stack.
-     */
-    public void update(TaskStack stack, ArraySet<Task.TaskKey> ignoreTasksSet,
-            RecentsActivityLaunchState launchState, float lastScrollPPercent) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-
-        // Clear the progress map
-        mTaskIndexMap.clear();
-
-        // Return early if we have no tasks
-        ArrayList<Task> tasks = stack.getTasks();
-        if (tasks.isEmpty()) {
-            mFrontMostTaskP = 0;
-            mMinScrollP = mMaxScrollP = mInitialScrollP = 0;
-            mNumStackTasks = 0;
-            return;
-        }
-
-        // Filter the set of stack tasks
-        ArrayList<Task> stackTasks = new ArrayList<>();
-        for (int i = 0; i < tasks.size(); i++) {
-            Task task = tasks.get(i);
-            if (ignoreTasksSet.contains(task.key)) {
-                continue;
-            }
-            stackTasks.add(task);
-        }
-        mNumStackTasks = stackTasks.size();
-
-        // Put each of the tasks in the progress map at a fixed index (does not need to actually
-        // map to a scroll position, just by index)
-        int taskCount = stackTasks.size();
-        for (int i = 0; i < taskCount; i++) {
-            Task task = stackTasks.get(i);
-            mTaskIndexMap.put(task.key.id, i);
-        }
-
-        // Calculate the min/max/initial scroll
-        Task launchTask = stack.getLaunchTarget();
-        int launchTaskIndex = launchTask != null
-                ? stack.indexOfTask(launchTask)
-                : mNumStackTasks - 1;
-        if (getInitialFocusState() == STATE_FOCUSED) {
-            int maxBottomOffset = mStackBottomOffset + mTaskRect.height();
-            float maxBottomNormX = getNormalizedXFromFocusedY(maxBottomOffset, FROM_BOTTOM);
-            mFocusedRange.offset(0f);
-            mMinScrollP = 0;
-            mMaxScrollP = Math.max(mMinScrollP, (mNumStackTasks - 1) -
-                    Math.max(0, mFocusedRange.getAbsoluteX(maxBottomNormX)));
-            if (launchState.launchedFromHome || launchState.launchedFromPipApp
-                    || launchState.launchedWithNextPipApp) {
-                mInitialScrollP = Utilities.clamp(launchTaskIndex, mMinScrollP, mMaxScrollP);
-            } else {
-                mInitialScrollP = Utilities.clamp(launchTaskIndex - 1, mMinScrollP, mMaxScrollP);
-            }
-        } else if (mNumStackTasks == 1) {
-            // If there is one stack task, ignore the min/max/initial scroll positions
-            mMinScrollP = 0;
-            mMaxScrollP = 0;
-            mInitialScrollP = 0;
-        } else {
-            // Set the max scroll to be the point where the front most task is visible with the
-            // stack bottom offset
-            int maxBottomOffset = mStackBottomOffset + mTaskRect.height();
-            float maxBottomNormX = getNormalizedXFromUnfocusedY(maxBottomOffset, FROM_BOTTOM);
-            mUnfocusedRange.offset(0f);
-            mMinScrollP = LegacyRecentsImpl.getConfiguration().isLowRamDevice
-                    ? mTaskStackLowRamLayoutAlgorithm.getMinScrollP()
-                    : 0;
-            mMaxScrollP = LegacyRecentsImpl.getConfiguration().isLowRamDevice
-                    ? mTaskStackLowRamLayoutAlgorithm.getMaxScrollP(taskCount)
-                    : Math.max(mMinScrollP, (mNumStackTasks - 1) -
-                    Math.max(0, mUnfocusedRange.getAbsoluteX(maxBottomNormX)));
-            boolean scrollToFront = launchState.launchedFromHome || launchState.launchedFromPipApp
-                    || launchState.launchedWithNextPipApp || launchState.launchedViaDockGesture;
-
-            if (launchState.launchedWithAltTab) {
-                mInitialScrollP = Utilities.clamp(launchTaskIndex, mMinScrollP, mMaxScrollP);
-            } else if (0 <= lastScrollPPercent && lastScrollPPercent <= 1) {
-                mInitialScrollP = Utilities.mapRange(lastScrollPPercent, mMinScrollP, mMaxScrollP);
-            } else if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                mInitialScrollP = mTaskStackLowRamLayoutAlgorithm.getInitialScrollP(mNumStackTasks,
-                        scrollToFront);
-            } else if (scrollToFront) {
-                mInitialScrollP = Utilities.clamp(launchTaskIndex, mMinScrollP, mMaxScrollP);
-            } else {
-                // We are overriding the initial two task positions, so set the initial scroll
-                // position to match the second task (aka focused task) position
-                float initialTopNormX = getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP);
-                mInitialScrollP = Math.max(mMinScrollP, Math.min(mMaxScrollP, (mNumStackTasks - 2))
-                        - Math.max(0, mUnfocusedRange.getAbsoluteX(initialTopNormX)));
-            }
-        }
-    }
-
-    /**
-     * Creates task overrides to ensure the initial stack layout if necessary.
-     */
-    public void setTaskOverridesForInitialState(TaskStack stack, boolean ignoreScrollToFront) {
-        RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-
-        mTaskIndexOverrideMap.clear();
-
-        boolean scrollToFront = launchState.launchedFromHome ||
-                launchState.launchedFromPipApp ||
-                launchState.launchedWithNextPipApp ||
-                launchState.launchedViaDockGesture;
-        if (getInitialFocusState() == STATE_UNFOCUSED && mNumStackTasks > 1) {
-            if (ignoreScrollToFront || (!launchState.launchedWithAltTab && !scrollToFront)) {
-                // Set the initial scroll to the predefined state (which differs from the stack)
-                float [] initialNormX = null;
-                float minBottomTaskNormX = getNormalizedXFromUnfocusedY(mSystemInsets.bottom +
-                        mInitialBottomOffset, FROM_BOTTOM);
-                float maxBottomTaskNormX = getNormalizedXFromUnfocusedY(mFocusedTopPeekHeight +
-                        mTaskRect.height() - mMinMargin, FROM_TOP);
-                if (mNumStackTasks <= 2) {
-                    // For small stacks, position the tasks so that they are top aligned to under
-                    // the action button, but ensure that it is at least a certain offset from the
-                    // bottom of the stack
-                    initialNormX = new float[] {
-                            Math.min(maxBottomTaskNormX, minBottomTaskNormX),
-                            getNormalizedXFromUnfocusedY(mFocusedTopPeekHeight, FROM_TOP)
-                    };
-                } else {
-                    initialNormX = new float[] {
-                            minBottomTaskNormX,
-                            getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP)
-                    };
-                }
-
-                mUnfocusedRange.offset(0f);
-                List<Task> tasks = stack.getTasks();
-                int taskCount = tasks.size();
-                for (int i = taskCount - 1; i >= 0; i--) {
-                    int indexFromFront = taskCount - i - 1;
-                    if (indexFromFront >= initialNormX.length) {
-                        break;
-                    }
-                    float newTaskProgress = mInitialScrollP +
-                            mUnfocusedRange.getAbsoluteX(initialNormX[indexFromFront]);
-                    mTaskIndexOverrideMap.put(tasks.get(i).key.id, newTaskProgress);
-                }
-            }
-        }
-    }
-
-    /**
-     * Adds and override task progress for the given task when transitioning from focused to
-     * unfocused state.
-     */
-    public void addUnfocusedTaskOverride(Task task, float stackScroll) {
-        if (mFocusState != STATE_UNFOCUSED) {
-            mFocusedRange.offset(stackScroll);
-            mUnfocusedRange.offset(stackScroll);
-            float focusedRangeX = mFocusedRange.getNormalizedX(mTaskIndexMap.get(task.key.id));
-            float focusedY = mFocusedCurveInterpolator.getInterpolation(focusedRangeX);
-            float unfocusedRangeX = mUnfocusedCurveInterpolator.getX(focusedY);
-            float unfocusedTaskProgress = stackScroll + mUnfocusedRange.getAbsoluteX(unfocusedRangeX);
-            if (Float.compare(focusedRangeX, unfocusedRangeX) != 0) {
-                mTaskIndexOverrideMap.put(task.key.id, unfocusedTaskProgress);
-            }
-        }
-    }
-
-    /**
-     * Adds and override task progress for the given task when transitioning from focused to
-     * unfocused state.
-     */
-    public void addUnfocusedTaskOverride(TaskView taskView, float stackScroll) {
-        mFocusedRange.offset(stackScroll);
-        mUnfocusedRange.offset(stackScroll);
-
-        Task task = taskView.getTask();
-        int top = taskView.getTop() - mTaskRect.top;
-        float focusedRangeX = getNormalizedXFromFocusedY(top, FROM_TOP);
-        float unfocusedRangeX = getNormalizedXFromUnfocusedY(top, FROM_TOP);
-        float unfocusedTaskProgress = stackScroll + mUnfocusedRange.getAbsoluteX(unfocusedRangeX);
-        if (Float.compare(focusedRangeX, unfocusedRangeX) != 0) {
-            mTaskIndexOverrideMap.put(task.key.id, unfocusedTaskProgress);
-        }
-    }
-
-    public void clearUnfocusedTaskOverrides() {
-        mTaskIndexOverrideMap.clear();
-    }
-
-    /**
-     * Updates this stack when a scroll happens.
-     *
-     */
-    public float updateFocusStateOnScroll(float lastTargetStackScroll, float targetStackScroll,
-            float lastStackScroll) {
-        if (targetStackScroll == lastStackScroll || LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            return targetStackScroll;
-        }
-
-        float deltaScroll = targetStackScroll - lastStackScroll;
-        float deltaTargetScroll = targetStackScroll - lastTargetStackScroll;
-        float newScroll = targetStackScroll;
-        mUnfocusedRange.offset(targetStackScroll);
-        for (int i = mTaskIndexOverrideMap.size() - 1; i >= 0; i--) {
-            int taskId = mTaskIndexOverrideMap.keyAt(i);
-            float x = mTaskIndexMap.get(taskId);
-            float overrideX = mTaskIndexOverrideMap.get(taskId, 0f);
-            float newOverrideX = overrideX + deltaScroll;
-            if (isInvalidOverrideX(x, overrideX, newOverrideX)) {
-                // Remove the override once we reach the original task index
-                mTaskIndexOverrideMap.removeAt(i);
-            } else if ((overrideX >= x && deltaScroll <= 0f) ||
-                    (overrideX <= x && deltaScroll >= 0f)) {
-                // Scrolling from override x towards x, then lock the task in place
-                mTaskIndexOverrideMap.put(taskId, newOverrideX);
-            } else {
-                // Scrolling override x away from x, we should still move the scroll towards x
-                newScroll = lastStackScroll;
-                newOverrideX = overrideX - deltaTargetScroll;
-                if (isInvalidOverrideX(x, overrideX, newOverrideX)) {
-                    mTaskIndexOverrideMap.removeAt(i);
-                } else{
-                    mTaskIndexOverrideMap.put(taskId, newOverrideX);
-                }
-            }
-        }
-        return newScroll;
-    }
-
-    private boolean isInvalidOverrideX(float x, float overrideX, float newOverrideX) {
-        boolean outOfBounds = mUnfocusedRange.getNormalizedX(newOverrideX) < 0f ||
-                mUnfocusedRange.getNormalizedX(newOverrideX) > 1f;
-        return outOfBounds || (overrideX >= x && x >= newOverrideX) ||
-                (overrideX <= x && x <= newOverrideX);
-    }
-
-    /**
-     * Returns the default focus state.
-     */
-    public int getInitialFocusState() {
-        RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-        RecentsDebugFlags debugFlags = LegacyRecentsImpl.getDebugFlags();
-        if (launchState.launchedWithAltTab) {
-            return STATE_FOCUSED;
-        } else {
-            return STATE_UNFOCUSED;
-        }
-    }
-
-    public Rect getStackActionButtonRect() {
-        return useGridLayout()
-                ? mTaskGridLayoutAlgorithm.getStackActionButtonRect() : mStackActionButtonRect;
-    }
-
-    /**
-     * Returns the TaskViewTransform that would put the task just off the back of the stack.
-     */
-    public TaskViewTransform getBackOfStackTransform() {
-        return mBackOfStackTransform;
-    }
-
-    /**
-     * Returns the TaskViewTransform that would put the task just off the front of the stack.
-     */
-    public TaskViewTransform getFrontOfStackTransform() {
-        return mFrontOfStackTransform;
-    }
-
-    /**
-     * Returns whether this stack layout has been initialized.
-     */
-    public boolean isInitialized() {
-        return !mStackRect.isEmpty();
-    }
-
-    /**
-     * Computes the maximum number of visible tasks and thumbnails when the scroll is at the initial
-     * stack scroll.  Requires that update() is called first.
-     */
-    public VisibilityReport computeStackVisibilityReport(ArrayList<Task> tasks) {
-        if (useGridLayout()) {
-            return mTaskGridLayoutAlgorithm.computeStackVisibilityReport(tasks);
-        }
-
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            return mTaskStackLowRamLayoutAlgorithm.computeStackVisibilityReport(tasks);
-        }
-
-        // Ensure minimum visibility count
-        if (tasks.size() <= 1) {
-            return new VisibilityReport(1, 1);
-        }
-
-        // Otherwise, walk backwards in the stack and count the number of tasks and visible
-        // thumbnails and add that to the total task count
-        TaskViewTransform tmpTransform = new TaskViewTransform();
-        Range currentRange = getInitialFocusState() > 0f ? mFocusedRange : mUnfocusedRange;
-        currentRange.offset(mInitialScrollP);
-        int taskBarHeight = mContext.getResources().getDimensionPixelSize(
-                R.dimen.recents_task_view_header_height);
-        int numVisibleTasks = 0;
-        int numVisibleThumbnails = 0;
-        float prevScreenY = Integer.MAX_VALUE;
-        for (int i = tasks.size() - 1; i >= 0; i--) {
-            Task task = tasks.get(i);
-
-            // Skip invisible
-            float taskProgress = getStackScrollForTask(task);
-            if (!currentRange.isInRange(taskProgress)) {
-                continue;
-            }
-
-            getStackTransform(taskProgress, taskProgress, mInitialScrollP, mFocusState,
-                    tmpTransform, null, false /* ignoreSingleTaskCase */, false /* forceUpdate */);
-            float screenY = tmpTransform.rect.top;
-            boolean hasVisibleThumbnail = (prevScreenY - screenY) > taskBarHeight;
-            if (hasVisibleThumbnail) {
-                numVisibleThumbnails++;
-                numVisibleTasks++;
-                prevScreenY = screenY;
-            } else {
-                // Once we hit the next front most task that does not have a visible thumbnail,
-                // walk through remaining visible set
-                for (int j = i; j >= 0; j--) {
-                    taskProgress = getStackScrollForTask(tasks.get(j));
-                    if (!currentRange.isInRange(taskProgress)) {
-                        break;
-                    }
-                    numVisibleTasks++;
-                }
-                break;
-            }
-        }
-        return new VisibilityReport(numVisibleTasks, numVisibleThumbnails);
-    }
-
-    /**
-     * Returns the transform for the given task.  This transform is relative to the mTaskRect, which
-     * is what the view is measured and laid out with.
-     */
-    public TaskViewTransform getStackTransform(Task task, float stackScroll,
-            TaskViewTransform transformOut, TaskViewTransform frontTransform) {
-        return getStackTransform(task, stackScroll, mFocusState, transformOut, frontTransform,
-                false /* forceUpdate */, false /* ignoreTaskOverrides */);
-    }
-
-    public TaskViewTransform getStackTransform(Task task, float stackScroll,
-            TaskViewTransform transformOut, TaskViewTransform frontTransform,
-            boolean ignoreTaskOverrides) {
-        return getStackTransform(task, stackScroll, mFocusState, transformOut, frontTransform,
-                false /* forceUpdate */, ignoreTaskOverrides);
-    }
-
-    public TaskViewTransform getStackTransform(Task task, float stackScroll, int focusState,
-            TaskViewTransform transformOut, TaskViewTransform frontTransform, boolean forceUpdate,
-            boolean ignoreTaskOverrides) {
-        if (useGridLayout()) {
-            int taskIndex = mTaskIndexMap.get(task.key.id);
-            int taskCount = mTaskIndexMap.size();
-            mTaskGridLayoutAlgorithm.getTransform(taskIndex, taskCount, transformOut, this);
-            return transformOut;
-        } else if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            if (task == null) {
-                transformOut.reset();
-                return transformOut;
-            }
-            int taskIndex = mTaskIndexMap.get(task.key.id);
-            mTaskStackLowRamLayoutAlgorithm.getTransform(taskIndex, stackScroll, transformOut,
-                    mNumStackTasks, this);
-            return transformOut;
-        } else {
-            // Return early if we have an invalid index
-            int nonOverrideTaskProgress = mTaskIndexMap.get(task.key.id, -1);
-            if (task == null || nonOverrideTaskProgress == -1) {
-                transformOut.reset();
-                return transformOut;
-            }
-            float taskProgress = ignoreTaskOverrides
-                    ? nonOverrideTaskProgress
-                    : getStackScrollForTask(task);
-
-            getStackTransform(taskProgress, nonOverrideTaskProgress, stackScroll, focusState,
-                    transformOut, frontTransform, false /* ignoreSingleTaskCase */, forceUpdate);
-            return transformOut;
-        }
-    }
-
-    /**
-     * Like {@link #getStackTransform}, but in screen coordinates
-     */
-    public TaskViewTransform getStackTransformScreenCoordinates(Task task, float stackScroll,
-            TaskViewTransform transformOut, TaskViewTransform frontTransform,
-            Rect windowOverrideRect) {
-        TaskViewTransform transform = getStackTransform(task, stackScroll, mFocusState,
-                transformOut, frontTransform, true /* forceUpdate */,
-                false /* ignoreTaskOverrides */);
-        return transformToScreenCoordinates(transform, windowOverrideRect);
-    }
-
-    /**
-     * Transforms the given {@param transformOut} to the screen coordinates, overriding the current
-     * window rectangle with {@param windowOverrideRect} if non-null.
-     */
-    TaskViewTransform transformToScreenCoordinates(TaskViewTransform transformOut,
-            Rect windowOverrideRect) {
-        Rect windowRect = windowOverrideRect != null
-                ? windowOverrideRect
-                : LegacyRecentsImpl.getSystemServices().getWindowRect();
-        transformOut.rect.offset(windowRect.left, windowRect.top);
-        if (useGridLayout()) {
-            // Draw the thumbnail a little lower to perfectly coincide with the view we are
-            // transitioning to, where the header bar has already been drawn.
-            transformOut.rect.offset(0, mTitleBarHeight);
-        }
-        return transformOut;
-    }
-
-    /**
-     * Update/get the transform.
-     *
-     * @param ignoreSingleTaskCase When set, will ensure that the transform computed does not take
-     *                             into account the special single-task case.  This is only used
-     *                             internally to ensure that we can calculate the transform for any
-     *                             position in the stack.
-     */
-    public void getStackTransform(float taskProgress, float nonOverrideTaskProgress,
-            float stackScroll, int focusState, TaskViewTransform transformOut,
-            TaskViewTransform frontTransform, boolean ignoreSingleTaskCase, boolean forceUpdate) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-
-        // Ensure that the task is in range
-        mUnfocusedRange.offset(stackScroll);
-        mFocusedRange.offset(stackScroll);
-        boolean unfocusedVisible = mUnfocusedRange.isInRange(taskProgress);
-        boolean focusedVisible = mFocusedRange.isInRange(taskProgress);
-
-        // Skip if the task is not visible
-        if (!forceUpdate && !unfocusedVisible && !focusedVisible) {
-            transformOut.reset();
-            return;
-        }
-
-        // Map the absolute task progress to the normalized x at the stack scroll.  We use this to
-        // calculate positions along the curve.
-        mUnfocusedRange.offset(stackScroll);
-        mFocusedRange.offset(stackScroll);
-        float unfocusedRangeX = mUnfocusedRange.getNormalizedX(taskProgress);
-        float focusedRangeX = mFocusedRange.getNormalizedX(taskProgress);
-
-        // Map the absolute task progress to the normalized x at the bounded stack scroll.  We use
-        // this to calculate bounded properties, like translationZ and outline alpha.
-        float boundedStackScroll = Utilities.clamp(stackScroll, mMinScrollP, mMaxScrollP);
-        mUnfocusedRange.offset(boundedStackScroll);
-        mFocusedRange.offset(boundedStackScroll);
-        float boundedScrollUnfocusedRangeX = mUnfocusedRange.getNormalizedX(taskProgress);
-        float boundedScrollUnfocusedNonOverrideRangeX =
-                mUnfocusedRange.getNormalizedX(nonOverrideTaskProgress);
-
-        // Map the absolute task progress to the normalized x at the upper bounded stack scroll.
-        // We use this to calculate the dim, which is bounded only on one end.
-        float lowerBoundedStackScroll = Utilities.clamp(stackScroll, -Float.MAX_VALUE, mMaxScrollP);
-        mUnfocusedRange.offset(lowerBoundedStackScroll);
-        mFocusedRange.offset(lowerBoundedStackScroll);
-        float lowerBoundedUnfocusedRangeX = mUnfocusedRange.getNormalizedX(taskProgress);
-        float lowerBoundedFocusedRangeX = mFocusedRange.getNormalizedX(taskProgress);
-
-        int x = (mStackRect.width() - mTaskRect.width()) / 2;
-        int y;
-        float z;
-        float dimAlpha;
-        float viewOutlineAlpha;
-        if (mNumStackTasks == 1 && !ignoreSingleTaskCase) {
-            // When there is exactly one task, then decouple the task from the stack and just move
-            // in screen space
-            float tmpP = (mMinScrollP - stackScroll) / mNumStackTasks;
-            int centerYOffset = (mStackRect.top - mTaskRect.top) +
-                    (mStackRect.height() - mSystemInsets.bottom - mTaskRect.height()) / 2;
-            y = centerYOffset + getYForDeltaP(tmpP, 0);
-            z = mMaxTranslationZ;
-            dimAlpha = 0f;
-            viewOutlineAlpha = OUTLINE_ALPHA_MIN_VALUE +
-                    (OUTLINE_ALPHA_MAX_VALUE - OUTLINE_ALPHA_MIN_VALUE) / 2f;
-
-        } else {
-            // Otherwise, update the task to the stack layout
-            int unfocusedY = (int) ((1f - mUnfocusedCurveInterpolator.getInterpolation(
-                    unfocusedRangeX)) * mStackRect.height());
-            int focusedY = (int) ((1f - mFocusedCurveInterpolator.getInterpolation(
-                    focusedRangeX)) * mStackRect.height());
-            float unfocusedDim = mUnfocusedDimCurveInterpolator.getInterpolation(
-                    lowerBoundedUnfocusedRangeX);
-            float focusedDim = mFocusedDimCurveInterpolator.getInterpolation(
-                    lowerBoundedFocusedRangeX);
-
-            // Special case, because we override the initial task positions differently for small
-            // stacks, we clamp the dim to 0 in the initial position, and then only modulate the
-            // dim when the task is scrolled back towards the top of the screen
-            if (mNumStackTasks <= 2 && nonOverrideTaskProgress == 0f) {
-                if (boundedScrollUnfocusedRangeX >= 0.5f) {
-                    unfocusedDim = 0f;
-                } else {
-                    float offset = mUnfocusedDimCurveInterpolator.getInterpolation(0.5f);
-                    unfocusedDim -= offset;
-                    unfocusedDim *= MAX_DIM / (MAX_DIM - offset);
-                }
-            }
-            y = (mStackRect.top - mTaskRect.top) +
-                    (int) com.android.systemui.recents.utilities.Utilities
-                            .mapRange(focusState, unfocusedY, focusedY);
-            z = Utilities.mapRange(Utilities.clamp01(boundedScrollUnfocusedNonOverrideRangeX),
-                    mMinTranslationZ, mMaxTranslationZ);
-            dimAlpha = com.android.systemui.recents.utilities.Utilities
-                    .mapRange(focusState, unfocusedDim, focusedDim);
-            viewOutlineAlpha = Utilities.mapRange(Utilities.clamp01(boundedScrollUnfocusedRangeX),
-                    OUTLINE_ALPHA_MIN_VALUE, OUTLINE_ALPHA_MAX_VALUE);
-        }
-
-        // Fill out the transform
-        transformOut.scale = 1f;
-        transformOut.alpha = 1f;
-        transformOut.translationZ = z;
-        transformOut.dimAlpha = dimAlpha;
-        transformOut.viewOutlineAlpha = viewOutlineAlpha;
-        transformOut.rect.set(mTaskRect);
-        transformOut.rect.offset(x, y);
-        Utilities.scaleRectAboutCenter(transformOut.rect, transformOut.scale);
-        transformOut.visible = (transformOut.rect.top < mStackRect.bottom) &&
-                (frontTransform == null || transformOut.rect.top != frontTransform.rect.top);
-    }
-
-    /**
-     * Returns the untransformed task view bounds.
-     */
-    public Rect getUntransformedTaskViewBounds() {
-        return new Rect(mTaskRect);
-    }
-
-    /**
-     * Returns the scroll progress to scroll to such that the top of the task is at the top of the
-     * stack.
-     */
-    float getStackScrollForTask(Task t) {
-        Float overrideP = mTaskIndexOverrideMap.get(t.key.id, null);
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice || overrideP == null) {
-            return (float) mTaskIndexMap.get(t.key.id, 0);
-        }
-        return overrideP;
-    }
-
-    /**
-     * Returns the original scroll progress to scroll to such that the top of the task is at the top
-     * of the stack.
-     */
-    float getStackScrollForTaskIgnoreOverrides(Task t) {
-        return (float) mTaskIndexMap.get(t.key.id, 0);
-    }
-
-    /**
-     * Returns the scroll progress to scroll to such that the top of the task at the initial top
-     * offset (which is at the task's brightest point).
-     */
-    float getStackScrollForTaskAtInitialOffset(Task t) {
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-            return mTaskStackLowRamLayoutAlgorithm.getInitialScrollP(mNumStackTasks,
-                    launchState.launchedFromHome || launchState.launchedFromPipApp
-                            || launchState.launchedWithNextPipApp);
-        }
-        float normX = getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP);
-        mUnfocusedRange.offset(0f);
-        return Utilities.clamp((float) mTaskIndexMap.get(t.key.id, 0) - Math.max(0,
-                mUnfocusedRange.getAbsoluteX(normX)), mMinScrollP, mMaxScrollP);
-    }
-
-    /**
-     * Maps a movement in screen y, relative to {@param downY}, to a movement in along the arc
-     * length of the curve.  We know the curve is mostly flat, so we just map the length of the
-     * screen along the arc-length proportionally (1/arclength).
-     */
-    public float getDeltaPForY(int downY, int y) {
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            return mTaskStackLowRamLayoutAlgorithm.scrollToPercentage(downY - y);
-        }
-        float deltaP = (float) (y - downY) / mStackRect.height() *
-                mUnfocusedCurveInterpolator.getArcLength();
-        return -deltaP;
-    }
-
-    /**
-     * This is the inverse of {@link #getDeltaPForY}.  Given a movement along the arc length
-     * of the curve, map back to the screen y.
-     */
-    public int getYForDeltaP(float downScrollP, float p) {
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            return mTaskStackLowRamLayoutAlgorithm.percentageToScroll(downScrollP - p);
-        }
-        int y = (int) ((p - downScrollP) * mStackRect.height() *
-                (1f / mUnfocusedCurveInterpolator.getArcLength()));
-        return -y;
-    }
-
-    /**
-     * Returns the task stack bounds in the current orientation.  This rect takes into account the
-     * top and right system insets (but not the bottom inset) and left/right paddings, but _not_
-     * the top/bottom padding or insets.
-     */
-    public void getTaskStackBounds(Rect displayRect, Rect windowRect, int topInset, int leftInset,
-            int rightInset, Rect taskStackBounds) {
-        taskStackBounds.set(windowRect.left + leftInset, windowRect.top + topInset,
-                windowRect.right - rightInset, windowRect.bottom);
-
-        // Ensure that the new width is at most the smaller display edge size
-        int sideMargin = getScaleForExtent(windowRect, displayRect, mBaseSideMargin, mMinMargin,
-                WIDTH);
-        int targetStackWidth = taskStackBounds.width() - 2 * sideMargin;
-        if (Utilities.getAppConfiguration(mContext).orientation
-                == Configuration.ORIENTATION_LANDSCAPE) {
-            // If we are in landscape, calculate the width of the stack in portrait and ensure that
-            // we are not larger than that size
-            Rect portraitDisplayRect = new Rect(0, 0,
-                    Math.min(displayRect.width(), displayRect.height()),
-                    Math.max(displayRect.width(), displayRect.height()));
-            int portraitSideMargin = getScaleForExtent(portraitDisplayRect, portraitDisplayRect,
-                    mBaseSideMargin, mMinMargin, WIDTH);
-            targetStackWidth = Math.min(targetStackWidth,
-                    portraitDisplayRect.width() - 2 * portraitSideMargin);
-        }
-        taskStackBounds.inset((taskStackBounds.width() - targetStackWidth) / 2, 0);
-    }
-
-    /**
-     * Retrieves resources that are constant regardless of the current configuration of the device.
-     */
-    public static int getDimensionForDevice(Context ctx, int phoneResId,
-            int tabletResId, int xlargeTabletResId, int gridLayoutResId) {
-        return getDimensionForDevice(ctx, phoneResId, phoneResId, tabletResId, tabletResId,
-                xlargeTabletResId, xlargeTabletResId, gridLayoutResId);
-    }
-
-    /**
-     * Retrieves resources that are constant regardless of the current configuration of the device.
-     */
-    public static int getDimensionForDevice(Context ctx, int phonePortResId, int phoneLandResId,
-            int tabletPortResId, int tabletLandResId, int xlargeTabletPortResId,
-            int xlargeTabletLandResId, int gridLayoutResId) {
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        Resources res = ctx.getResources();
-        boolean isLandscape = Utilities.getAppConfiguration(ctx).orientation ==
-                Configuration.ORIENTATION_LANDSCAPE;
-        if (config.isGridEnabled) {
-            return res.getDimensionPixelSize(gridLayoutResId);
-        } else if (config.isXLargeScreen) {
-            return res.getDimensionPixelSize(isLandscape
-                    ? xlargeTabletLandResId
-                    : xlargeTabletPortResId);
-        } else if (config.isLargeScreen) {
-            return res.getDimensionPixelSize(isLandscape
-                    ? tabletLandResId
-                    : tabletPortResId);
-        } else {
-            return res.getDimensionPixelSize(isLandscape
-                    ? phoneLandResId
-                    : phonePortResId);
-        }
-    }
-
-    /**
-     * Returns the normalized x on the unfocused curve given an absolute Y position (relative to the
-     * stack height).
-     */
-    private float getNormalizedXFromUnfocusedY(float y, @AnchorSide int fromSide) {
-        float offset = (fromSide == FROM_TOP)
-                ? mStackRect.height() - y
-                : y;
-        float offsetPct = offset / mStackRect.height();
-        return mUnfocusedCurveInterpolator.getX(offsetPct);
-    }
-
-    /**
-     * Returns the normalized x on the focused curve given an absolute Y position (relative to the
-     * stack height).
-     */
-    private float getNormalizedXFromFocusedY(float y, @AnchorSide int fromSide) {
-        float offset = (fromSide == FROM_TOP)
-                ? mStackRect.height() - y
-                : y;
-        float offsetPct = offset / mStackRect.height();
-        return mFocusedCurveInterpolator.getX(offsetPct);
-    }
-
-    /**
-     * Creates a new path for the focused curve.
-     */
-    private Path constructFocusedCurve() {
-        // Initialize the focused curve. This curve is a piecewise curve composed of several
-        // linear pieces that goes from (0,1) through (0.5, peek height offset),
-        // (0.5, bottom task offsets), and (1,0).
-        float topPeekHeightPct = (float) mFocusedTopPeekHeight / mStackRect.height();
-        float bottomPeekHeightPct = (float) (mStackBottomOffset + mFocusedBottomPeekHeight) /
-                mStackRect.height();
-        float minBottomPeekHeightPct = (float) (mFocusedTopPeekHeight + mTaskRect.height() -
-                mMinMargin) / mStackRect.height();
-        Path p = new Path();
-        p.moveTo(0f, 1f);
-        p.lineTo(0.5f, 1f - topPeekHeightPct);
-        p.lineTo(1f - (0.5f / mFocusedRange.relativeMax), Math.max(1f - minBottomPeekHeightPct,
-                bottomPeekHeightPct));
-        p.lineTo(1f, 0f);
-        return p;
-    }
-
-    /**
-     * Creates a new path for the unfocused curve.
-     */
-    private Path constructUnfocusedCurve() {
-        // Initialize the unfocused curve. This curve is a piecewise curve composed of two quadradic
-        // beziers that goes from (0,1) through (0.5, peek height offset) and ends at (1,0).  This
-        // ensures that we match the range, at which 0.5 represents the stack scroll at the current
-        // task progress.  Because the height offset can change depending on a resource, we compute
-        // the control point of the second bezier such that between it and a first known point,
-        // there is a tangent at (0.5, peek height offset).
-        float cpoint1X = 0.4f;
-        float cpoint1Y = 0.975f;
-        float topPeekHeightPct = (float) mFocusedTopPeekHeight / mStackRect.height();
-        float slope = ((1f - topPeekHeightPct) - cpoint1Y) / (0.5f - cpoint1X);
-        float b = 1f - slope * cpoint1X;
-        float cpoint2X = 0.65f;
-        float cpoint2Y = slope * cpoint2X + b;
-        Path p = new Path();
-        p.moveTo(0f, 1f);
-        p.cubicTo(0f, 1f, cpoint1X, cpoint1Y, 0.5f, 1f - topPeekHeightPct);
-        p.cubicTo(0.5f, 1f - topPeekHeightPct, cpoint2X, cpoint2Y, 1f, 0f);
-        return p;
-    }
-
-    /**
-     * Creates a new path for the focused dim curve.
-     */
-    private Path constructFocusedDimCurve() {
-        Path p = new Path();
-        // The focused dim interpolator starts at max dim, reduces to zero at 0.5 (the focused
-        // task), then goes back to max dim at the next task
-        p.moveTo(0f, MAX_DIM);
-        p.lineTo(0.5f, 0f);
-        p.lineTo(0.5f + (0.5f / mFocusedRange.relativeMax), MAX_DIM);
-        p.lineTo(1f, MAX_DIM);
-        return p;
-    }
-
-    /**
-     * Creates a new path for the unfocused dim curve.
-     */
-    private Path constructUnfocusedDimCurve() {
-        float focusX = getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP);
-        float cpoint2X = focusX + (1f - focusX) / 2;
-        Path p = new Path();
-        // The unfocused dim interpolator starts at max dim, reduces to zero at 0.5 (the focused
-        // task), then goes back to max dim towards the front of the stack
-        p.moveTo(0f, MAX_DIM);
-        p.cubicTo(focusX * 0.5f, MAX_DIM, focusX * 0.75f, MAX_DIM * 0.75f, focusX, 0f);
-        p.cubicTo(cpoint2X, 0f, cpoint2X, MED_DIM, 1f, MED_DIM);
-        return p;
-    }
-
-    /**
-     * Scales the given {@param value} to the scale of the {@param instance} rect relative to the
-     * {@param other} rect in the {@param extent} side.
-     */
-    private int getScaleForExtent(Rect instance, Rect other, int value, int minValue,
-                                  @Extent int extent) {
-        if (extent == WIDTH) {
-            float scale = Utilities.clamp01((float) instance.width() / other.width());
-            return Math.max(minValue, (int) (scale * value));
-        } else if (extent == HEIGHT) {
-            float scale = Utilities.clamp01((float) instance.height() / other.height());
-            return Math.max(minValue, (int) (scale * value));
-        }
-        return value;
-    }
-
-    /**
-     * Updates the current transforms that would put a TaskView at the front and back of the stack.
-     */
-    private void updateFrontBackTransforms() {
-        // Return early if we have not yet initialized
-        if (mStackRect.isEmpty()) {
-            return;
-        }
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            mTaskStackLowRamLayoutAlgorithm.getBackOfStackTransform(mBackOfStackTransform, this);
-            mTaskStackLowRamLayoutAlgorithm.getFrontOfStackTransform(mFrontOfStackTransform, this);
-            return;
-        }
-
-        float min = Utilities.mapRange(mFocusState, mUnfocusedRange.relativeMin,
-                mFocusedRange.relativeMin);
-        float max = Utilities.mapRange(mFocusState, mUnfocusedRange.relativeMax,
-                mFocusedRange.relativeMax);
-        getStackTransform(min, min, 0f, mFocusState, mBackOfStackTransform, null,
-                true /* ignoreSingleTaskCase */, true /* forceUpdate */);
-        getStackTransform(max, max, 0f, mFocusState, mFrontOfStackTransform, null,
-                true /* ignoreSingleTaskCase */, true /* forceUpdate */);
-        mBackOfStackTransform.visible = true;
-        mFrontOfStackTransform.visible = true;
-    }
-
-    /**
-     * Returns the proper task rectangle according to the current grid state.
-     */
-    public Rect getTaskRect() {
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            return mTaskStackLowRamLayoutAlgorithm.getTaskRect();
-        }
-        return useGridLayout() ? mTaskGridLayoutAlgorithm.getTaskGridRect() : mTaskRect;
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        String innerPrefix = prefix + "  ";
-
-        writer.print(prefix); writer.print(TAG);
-        writer.write(" numStackTasks="); writer.print(mNumStackTasks);
-        writer.println();
-
-        writer.print(innerPrefix);
-        writer.print("insets="); writer.print(Utilities.dumpRect(mSystemInsets));
-        writer.print(" stack="); writer.print(Utilities.dumpRect(mStackRect));
-        writer.print(" task="); writer.print(Utilities.dumpRect(mTaskRect));
-        writer.print(" actionButton="); writer.print(
-                Utilities.dumpRect(mStackActionButtonRect));
-        writer.println();
-
-        writer.print(innerPrefix);
-        writer.print("minScroll="); writer.print(mMinScrollP);
-        writer.print(" maxScroll="); writer.print(mMaxScrollP);
-        writer.print(" initialScroll="); writer.print(mInitialScrollP);
-        writer.println();
-
-        writer.print(innerPrefix);
-        writer.print("focusState="); writer.print(mFocusState);
-        writer.println();
-
-        if (mTaskIndexOverrideMap.size() > 0) {
-            for (int i = mTaskIndexOverrideMap.size() - 1; i >= 0; i--) {
-                int taskId = mTaskIndexOverrideMap.keyAt(i);
-                float x = mTaskIndexMap.get(taskId);
-                float overrideX = mTaskIndexOverrideMap.get(taskId, 0f);
-
-                writer.print(innerPrefix);
-                writer.print("taskId= "); writer.print(taskId);
-                writer.print(" x= "); writer.print(x);
-                writer.print(" overrideX= "); writer.print(overrideX);
-                writer.println();
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackView.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackView.java
deleted file mode 100644
index b89218c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackView.java
+++ /dev/null
@@ -1,2291 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.ValueAnimator;
-import android.annotation.IntDef;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.graphics.Rect;
-import android.os.Bundle;
-import android.util.ArrayMap;
-import android.util.ArraySet;
-import android.util.MutableBoolean;
-import android.view.LayoutInflater;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.ViewDebug;
-import android.view.ViewGroup;
-import android.view.accessibility.AccessibilityEvent;
-import android.view.accessibility.AccessibilityNodeInfo;
-import android.widget.FrameLayout;
-import android.widget.ScrollView;
-
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.systemui.Dependency;
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.plugins.FalsingManager;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsActivity;
-import com.android.systemui.recents.RecentsActivityLaunchState;
-import com.android.systemui.recents.RecentsConfiguration;
-import com.android.systemui.recents.RecentsDebugFlags;
-import com.android.systemui.recents.RecentsImpl;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.CancelEnterRecentsWindowAnimationEvent;
-import com.android.systemui.recents.events.activity.ConfigurationChangedEvent;
-import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
-import com.android.systemui.recents.events.activity.EnterRecentsWindowAnimationCompletedEvent;
-import com.android.systemui.recents.events.activity.HideRecentsEvent;
-import com.android.systemui.recents.events.activity.HideStackActionButtonEvent;
-import com.android.systemui.recents.events.activity.LaunchMostRecentTaskRequestEvent;
-import com.android.systemui.recents.events.activity.LaunchNextTaskRequestEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskEvent;
-import com.android.systemui.recents.events.activity.LaunchTaskStartedEvent;
-import com.android.systemui.recents.events.activity.MultiWindowStateChangedEvent;
-import com.android.systemui.recents.events.activity.PackagesChangedEvent;
-import com.android.systemui.recents.events.activity.ShowEmptyViewEvent;
-import com.android.systemui.recents.events.activity.ShowStackActionButtonEvent;
-import com.android.systemui.recents.events.component.ActivityPinnedEvent;
-import com.android.systemui.recents.events.component.ExpandPipEvent;
-import com.android.systemui.recents.events.component.HidePipMenuEvent;
-import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent;
-import com.android.systemui.recents.events.ui.AllTaskViewsDismissedEvent;
-import com.android.systemui.recents.events.ui.DeleteTaskDataEvent;
-import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
-import com.android.systemui.recents.events.ui.DismissTaskViewEvent;
-import com.android.systemui.recents.events.ui.RecentsGrowingEvent;
-import com.android.systemui.recents.events.ui.TaskViewDismissedEvent;
-import com.android.systemui.recents.events.ui.UserInteractionEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragDropTargetChangedEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndCancelledEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
-import com.android.systemui.recents.events.ui.focus.DismissFocusedTaskViewEvent;
-import com.android.systemui.recents.events.ui.focus.FocusNextTaskViewEvent;
-import com.android.systemui.recents.events.ui.focus.FocusPreviousTaskViewEvent;
-import com.android.systemui.recents.events.ui.focus.NavigateTaskViewEvent;
-import com.android.systemui.recents.misc.DozeTrigger;
-import com.android.systemui.recents.misc.ReferenceCountedTrigger;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.recents.utilities.AnimationProps;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.recents.views.grid.GridTaskView;
-import com.android.systemui.recents.views.grid.TaskGridLayoutAlgorithm;
-import com.android.systemui.recents.views.grid.TaskViewFocusFrame;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-
-import java.io.PrintWriter;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-import java.util.List;
-
-
-/* The visual representation of a task stack view */
-public class TaskStackView extends FrameLayout implements TaskStack.TaskStackCallbacks,
-        TaskView.TaskViewCallbacks, TaskStackViewScroller.TaskStackViewScrollerCallbacks,
-        TaskStackLayoutAlgorithm.TaskStackLayoutAlgorithmCallbacks,
-        ViewPool.ViewPoolConsumer<TaskView, Task> {
-
-    private static final String TAG = "TaskStackView";
-
-    // The thresholds at which to show/hide the stack action button.
-    private static final float SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD = 0.3f;
-    private static final float HIDE_STACK_ACTION_BUTTON_SCROLL_THRESHOLD = 0.3f;
-
-    public static final int DEFAULT_SYNC_STACK_DURATION = 200;
-    public static final int SLOW_SYNC_STACK_DURATION = 250;
-    private static final int DRAG_SCALE_DURATION = 175;
-    static final float DRAG_SCALE_FACTOR = 1.05f;
-
-    private static final int LAUNCH_NEXT_SCROLL_BASE_DURATION = 216;
-    private static final int LAUNCH_NEXT_SCROLL_INCR_DURATION = 32;
-
-    // The actions to perform when resetting to initial state,
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef({INITIAL_STATE_UPDATE_NONE, INITIAL_STATE_UPDATE_ALL, INITIAL_STATE_UPDATE_LAYOUT_ONLY})
-    public @interface InitialStateAction {}
-    /** Do not update the stack and layout to the initial state. */
-    private static final int INITIAL_STATE_UPDATE_NONE = 0;
-    /** Update both the stack and layout to the initial state. */
-    private static final int INITIAL_STATE_UPDATE_ALL = 1;
-    /** Update only the layout to the initial state. */
-    private static final int INITIAL_STATE_UPDATE_LAYOUT_ONLY = 2;
-
-    private LayoutInflater mInflater;
-    private TaskStack mStack = new TaskStack();
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="layout_")
-    TaskStackLayoutAlgorithm mLayoutAlgorithm;
-    // The stable layout algorithm is only used to calculate the task rect with the stable bounds
-    private TaskStackLayoutAlgorithm mStableLayoutAlgorithm;
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="scroller_")
-    private TaskStackViewScroller mStackScroller;
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="touch_")
-    private TaskStackViewTouchHandler mTouchHandler;
-    private TaskStackAnimationHelper mAnimationHelper;
-    private ViewPool<TaskView, Task> mViewPool;
-
-    private ArrayList<TaskView> mTaskViews = new ArrayList<>();
-    private ArrayList<TaskViewTransform> mCurrentTaskTransforms = new ArrayList<>();
-    private ArraySet<Task.TaskKey> mIgnoreTasks = new ArraySet<>();
-    private AnimationProps mDeferredTaskViewLayoutAnimation = null;
-
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="doze_")
-    private DozeTrigger mUIDozeTrigger;
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="focused_task_")
-    private Task mFocusedTask;
-
-    private int mTaskCornerRadiusPx;
-    private int mDividerSize;
-    private int mStartTimerIndicatorDuration;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mTaskViewsClipDirty = true;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mEnterAnimationComplete = false;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mStackReloaded = false;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mFinishedLayoutAfterStackReload = false;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mLaunchNextAfterFirstMeasure = false;
-    @ViewDebug.ExportedProperty(category="recents")
-    @InitialStateAction
-    private int mInitialState = INITIAL_STATE_UPDATE_ALL;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mInMeasureLayout = false;
-    @ViewDebug.ExportedProperty(category="recents")
-    boolean mTouchExplorationEnabled;
-    @ViewDebug.ExportedProperty(category="recents")
-    boolean mScreenPinningEnabled;
-
-    // The stable stack bounds are the full bounds that we were measured with from RecentsView
-    @ViewDebug.ExportedProperty(category="recents")
-    private Rect mStableStackBounds = new Rect();
-    // The current stack bounds are dynamic and may change as the user drags and drops
-    @ViewDebug.ExportedProperty(category="recents")
-    private Rect mStackBounds = new Rect();
-    // The current window bounds at the point we were measured
-    @ViewDebug.ExportedProperty(category="recents")
-    private Rect mStableWindowRect = new Rect();
-    // The current window bounds are dynamic and may change as the user drags and drops
-    @ViewDebug.ExportedProperty(category="recents")
-    private Rect mWindowRect = new Rect();
-    // The current display bounds
-    @ViewDebug.ExportedProperty(category="recents")
-    private Rect mDisplayRect = new Rect();
-    // The current display orientation
-    @ViewDebug.ExportedProperty(category="recents")
-    private int mDisplayOrientation = Configuration.ORIENTATION_UNDEFINED;
-
-    private Rect mTmpRect = new Rect();
-    private ArrayMap<Task.TaskKey, TaskView> mTmpTaskViewMap = new ArrayMap<>();
-    private List<TaskView> mTmpTaskViews = new ArrayList<>();
-    private TaskViewTransform mTmpTransform = new TaskViewTransform();
-    private int[] mTmpIntPair = new int[2];
-    private boolean mResetToInitialStateWhenResized;
-    private int mLastWidth;
-    private int mLastHeight;
-    private boolean mStackActionButtonVisible;
-
-    // Percentage of last ScrollP from the min to max scrollP that lives after configuration changes
-    private float mLastScrollPPercent = -1;
-
-    // We keep track of the task view focused by user interaction and draw a frame around it in the
-    // grid layout.
-    private TaskViewFocusFrame mTaskViewFocusFrame;
-
-    private Task mPrefetchingTask;
-    private final float mFastFlingVelocity;
-
-    // A convenience update listener to request updating clipping of tasks
-    private ValueAnimator.AnimatorUpdateListener mRequestUpdateClippingListener =
-            new ValueAnimator.AnimatorUpdateListener() {
-                @Override
-                public void onAnimationUpdate(ValueAnimator animation) {
-                    if (!mTaskViewsClipDirty) {
-                        mTaskViewsClipDirty = true;
-                        invalidate();
-                    }
-                }
-            };
-
-    private DropTarget mStackDropTarget = new DropTarget() {
-        @Override
-        public boolean acceptsDrop(int x, int y, int width, int height, Rect insets,
-                boolean isCurrentTarget) {
-            // This drop target has a fixed bounds and should be checked last, so just fall through
-            // if it is the current target
-            if (!isCurrentTarget) {
-                return mLayoutAlgorithm.mStackRect.contains(x, y);
-            }
-            return false;
-        }
-    };
-
-    public TaskStackView(Context context) {
-        super(context);
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        Resources res = context.getResources();
-
-        // Set the stack first
-        mStack.setCallbacks(this);
-        mViewPool = new ViewPool<>(context, this);
-        mInflater = LayoutInflater.from(context);
-        mLayoutAlgorithm = new TaskStackLayoutAlgorithm(context, this);
-        mStableLayoutAlgorithm = new TaskStackLayoutAlgorithm(context, null);
-        mStackScroller = new TaskStackViewScroller(context, this, mLayoutAlgorithm);
-        mTouchHandler = new TaskStackViewTouchHandler(
-                context, this, mStackScroller, Dependency.get(FalsingManager.class));
-        mAnimationHelper = new TaskStackAnimationHelper(context, this);
-        mTaskCornerRadiusPx = LegacyRecentsImpl.getConfiguration().isGridEnabled ?
-                res.getDimensionPixelSize(R.dimen.recents_grid_task_view_rounded_corners_radius) :
-                res.getDimensionPixelSize(R.dimen.recents_task_view_rounded_corners_radius);
-        mFastFlingVelocity = res.getDimensionPixelSize(R.dimen.recents_fast_fling_velocity);
-        mDividerSize = ssp.getDockedDividerSize(context);
-        mDisplayOrientation = Utilities.getAppConfiguration(mContext).orientation;
-        mDisplayRect = ssp.getDisplayRect();
-        mStackActionButtonVisible = false;
-
-        // Create a frame to draw around the focused task view
-        if (LegacyRecentsImpl.getConfiguration().isGridEnabled) {
-            mTaskViewFocusFrame = new TaskViewFocusFrame(mContext, this,
-                mLayoutAlgorithm.mTaskGridLayoutAlgorithm);
-            addView(mTaskViewFocusFrame);
-            getViewTreeObserver().addOnGlobalFocusChangeListener(mTaskViewFocusFrame);
-        }
-
-        int taskBarDismissDozeDelaySeconds = getResources().getInteger(
-                R.integer.recents_task_bar_dismiss_delay_seconds);
-        mUIDozeTrigger = new DozeTrigger(taskBarDismissDozeDelaySeconds, new Runnable() {
-            @Override
-            public void run() {
-                // Show the task bar dismiss buttons
-                List<TaskView> taskViews = getTaskViews();
-                int taskViewCount = taskViews.size();
-                for (int i = 0; i < taskViewCount; i++) {
-                    TaskView tv = taskViews.get(i);
-                    tv.startNoUserInteractionAnimation();
-                }
-            }
-        });
-        setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
-    }
-
-    @Override
-    protected void onAttachedToWindow() {
-        EventBus.getDefault().register(this, RecentsActivity.EVENT_BUS_PRIORITY + 1);
-        super.onAttachedToWindow();
-        readSystemFlags();
-    }
-
-    @Override
-    protected void onDetachedFromWindow() {
-        super.onDetachedFromWindow();
-        EventBus.getDefault().unregister(this);
-    }
-
-    /**
-     * Called from RecentsActivity when it is relaunched.
-     */
-    void onReload(boolean isResumingFromVisible) {
-        if (!isResumingFromVisible) {
-            // Reset the focused task
-            resetFocusedTask(getFocusedTask());
-        }
-
-        // Reset the state of each of the task views
-        List<TaskView> taskViews = new ArrayList<>();
-        taskViews.addAll(getTaskViews());
-        taskViews.addAll(mViewPool.getViews());
-        for (int i = taskViews.size() - 1; i >= 0; i--) {
-            taskViews.get(i).onReload(isResumingFromVisible);
-        }
-
-        // Reset the stack state
-        readSystemFlags();
-        mTaskViewsClipDirty = true;
-        mUIDozeTrigger.stopDozing();
-        if (!isResumingFromVisible) {
-            mStackScroller.reset();
-            mStableLayoutAlgorithm.reset();
-            mLayoutAlgorithm.reset();
-            mLastScrollPPercent = -1;
-        }
-
-        // Since we always animate to the same place in (the initial state), always reset the stack
-        // to the initial state when resuming
-        mStackReloaded = true;
-        mFinishedLayoutAfterStackReload = false;
-        mLaunchNextAfterFirstMeasure = false;
-        mInitialState = INITIAL_STATE_UPDATE_ALL;
-        requestLayout();
-    }
-
-    /**
-     * Sets the stack tasks of this TaskStackView from the given TaskStack.
-     */
-    public void setTasks(TaskStack stack, boolean allowNotifyStackChanges) {
-        boolean isInitialized = mLayoutAlgorithm.isInitialized();
-
-        // Only notify if we are already initialized, otherwise, everything will pick up all the
-        // new and old tasks when we next layout
-        mStack.setTasks(stack, allowNotifyStackChanges && isInitialized);
-    }
-
-    /** Returns the task stack. */
-    public TaskStack getStack() {
-        return mStack;
-    }
-
-    /**
-     * Updates this TaskStackView to the initial state.
-     */
-    public void updateToInitialState() {
-        mStackScroller.setStackScrollToInitialState();
-        mLayoutAlgorithm.setTaskOverridesForInitialState(mStack, false /* ignoreScrollToFront */);
-    }
-
-    /** Updates the list of task views */
-    void updateTaskViewsList() {
-        mTaskViews.clear();
-        int childCount = getChildCount();
-        for (int i = 0; i < childCount; i++) {
-            View v = getChildAt(i);
-            if (v instanceof TaskView) {
-                mTaskViews.add((TaskView) v);
-            }
-        }
-    }
-
-    /** Gets the list of task views */
-    List<TaskView> getTaskViews() {
-        return mTaskViews;
-    }
-
-    /**
-     * Returns the front most task view.
-     */
-    private TaskView getFrontMostTaskView() {
-        List<TaskView> taskViews = getTaskViews();
-        if (taskViews.isEmpty()) {
-            return null;
-        }
-        return taskViews.get(taskViews.size() - 1);
-    }
-
-    /**
-     * Finds the child view given a specific {@param task}.
-     */
-    public TaskView getChildViewForTask(Task t) {
-        List<TaskView> taskViews = getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            if (tv.getTask() == t) {
-                return tv;
-            }
-        }
-        return null;
-    }
-
-    /** Returns the stack algorithm for this task stack. */
-    public TaskStackLayoutAlgorithm getStackAlgorithm() {
-        return mLayoutAlgorithm;
-    }
-
-    /** Returns the grid algorithm for this task stack. */
-    public TaskGridLayoutAlgorithm getGridAlgorithm() {
-        return mLayoutAlgorithm.mTaskGridLayoutAlgorithm;
-    }
-
-    /**
-     * Returns the touch handler for this task stack.
-     */
-    public TaskStackViewTouchHandler getTouchHandler() {
-        return mTouchHandler;
-    }
-
-    /**
-     * Adds a task to the ignored set.
-     */
-    void addIgnoreTask(Task task) {
-        mIgnoreTasks.add(task.key);
-    }
-
-    /**
-     * Removes a task from the ignored set.
-     */
-    void removeIgnoreTask(Task task) {
-        mIgnoreTasks.remove(task.key);
-    }
-
-    /**
-     * Returns whether the specified {@param task} is ignored.
-     */
-    boolean isIgnoredTask(Task task) {
-        return mIgnoreTasks.contains(task.key);
-    }
-
-    /**
-     * Computes the task transforms at the current stack scroll for all visible tasks. If a valid
-     * target stack scroll is provided (ie. is different than {@param curStackScroll}), then the
-     * visible range includes all tasks at the target stack scroll. This is useful for ensure that
-     * all views necessary for a transition or animation will be visible at the start.
-     *
-     * @param taskTransforms The set of task view transforms to reuse, this list will be sized to
-     *                       match the size of {@param tasks}
-     * @param tasks The set of tasks for which to generate transforms
-     * @param curStackScroll The current stack scroll
-     * @param targetStackScroll The stack scroll that we anticipate we are going to be scrolling to.
-     *                          The range of the union of the visible views at the current and
-     *                          target stack scrolls will be returned.
-     * @param ignoreTasksSet The set of tasks to skip for purposes of calculaing the visible range.
-     *                       Transforms will still be calculated for the ignore tasks.
-     * @return the front and back most visible task indices (there may be non visible tasks in
-     *         between this range)
-     */
-    int[] computeVisibleTaskTransforms(ArrayList<TaskViewTransform> taskTransforms,
-            ArrayList<Task> tasks, float curStackScroll, float targetStackScroll,
-            ArraySet<Task.TaskKey> ignoreTasksSet, boolean ignoreTaskOverrides) {
-        int taskCount = tasks.size();
-        int[] visibleTaskRange = mTmpIntPair;
-        visibleTaskRange[0] = -1;
-        visibleTaskRange[1] = -1;
-        boolean useTargetStackScroll = Float.compare(curStackScroll, targetStackScroll) != 0;
-
-        // We can reuse the task transforms where possible to reduce object allocation
-        matchTaskListSize(tasks, taskTransforms);
-
-        // Update the stack transforms
-        TaskViewTransform frontTransform = null;
-        TaskViewTransform frontTransformAtTarget = null;
-        TaskViewTransform transform = null;
-        TaskViewTransform transformAtTarget = null;
-        for (int i = taskCount - 1; i >= 0; i--) {
-            Task task = tasks.get(i);
-
-            // Calculate the current and (if necessary) the target transform for the task
-            transform = mLayoutAlgorithm.getStackTransform(task, curStackScroll,
-                    taskTransforms.get(i), frontTransform, ignoreTaskOverrides);
-            if (useTargetStackScroll && !transform.visible) {
-                // If we have a target stack scroll and the task is not currently visible, then we
-                // just update the transform at the new scroll
-                // TODO: Optimize this
-                transformAtTarget = mLayoutAlgorithm.getStackTransform(task, targetStackScroll,
-                    new TaskViewTransform(), frontTransformAtTarget);
-                if (transformAtTarget.visible) {
-                    transform.copyFrom(transformAtTarget);
-                }
-            }
-
-            // For ignore tasks, only calculate the stack transform and skip the calculation of the
-            // visible stack indices
-            if (ignoreTasksSet.contains(task.key)) {
-                continue;
-            }
-
-            frontTransform = transform;
-            frontTransformAtTarget = transformAtTarget;
-            if (transform.visible) {
-                if (visibleTaskRange[0] < 0) {
-                    visibleTaskRange[0] = i;
-                }
-                visibleTaskRange[1] = i;
-            }
-        }
-        return visibleTaskRange;
-    }
-
-    /**
-     * Binds the visible {@link TaskView}s at the given target scroll.
-     */
-    void bindVisibleTaskViews(float targetStackScroll) {
-        bindVisibleTaskViews(targetStackScroll, false /* ignoreTaskOverrides */);
-    }
-
-    /**
-     * Synchronizes the set of children {@link TaskView}s to match the visible set of tasks in the
-     * current {@link TaskStack}. This call does not continue on to update their position to the
-     * computed {@link TaskViewTransform}s of the visible range, but only ensures that they will
-     * be added/removed from the view hierarchy and placed in the correct Z order and initial
-     * position (if not currently on screen).
-     *
-     * @param targetStackScroll If provided, will ensure that the set of visible {@link TaskView}s
-     *                          includes those visible at the current stack scroll, and all at the
-     *                          target stack scroll.
-     * @param ignoreTaskOverrides If set, the visible task computation will get the transforms for
-     *                            tasks at their non-overridden task progress
-     */
-    void bindVisibleTaskViews(float targetStackScroll, boolean ignoreTaskOverrides) {
-        // Get all the task transforms
-        ArrayList<Task> tasks = mStack.getTasks();
-        int[] visibleTaskRange = computeVisibleTaskTransforms(mCurrentTaskTransforms, tasks,
-                mStackScroller.getStackScroll(), targetStackScroll, mIgnoreTasks,
-                ignoreTaskOverrides);
-
-        // Return all the invisible children to the pool
-        mTmpTaskViewMap.clear();
-        List<TaskView> taskViews = getTaskViews();
-        int lastFocusedTaskIndex = -1;
-        int taskViewCount = taskViews.size();
-        for (int i = taskViewCount - 1; i >= 0; i--) {
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            // Skip ignored tasks
-            if (mIgnoreTasks.contains(task.key)) {
-                continue;
-            }
-
-            // It is possible for the set of lingering TaskViews to differ from the stack if the
-            // stack was updated before the relayout.  If the task view is no longer in the stack,
-            // then just return it back to the view pool.
-            int taskIndex = mStack.indexOfTask(task);
-            TaskViewTransform transform = null;
-            if (taskIndex != -1) {
-                transform = mCurrentTaskTransforms.get(taskIndex);
-            }
-
-            if (transform != null && transform.visible) {
-                mTmpTaskViewMap.put(task.key, tv);
-            } else {
-                if (mTouchExplorationEnabled && Utilities.isDescendentAccessibilityFocused(tv)) {
-                    lastFocusedTaskIndex = taskIndex;
-                    resetFocusedTask(task);
-                }
-                mViewPool.returnViewToPool(tv);
-            }
-        }
-
-        // Pick up all the newly visible children
-        for (int i = tasks.size() - 1; i >= 0; i--) {
-            Task task = tasks.get(i);
-            TaskViewTransform transform = mCurrentTaskTransforms.get(i);
-
-            // Skip ignored tasks
-            if (mIgnoreTasks.contains(task.key)) {
-                continue;
-            }
-
-            // Skip the invisible stack tasks
-            if (!transform.visible) {
-                continue;
-            }
-
-            TaskView tv = mTmpTaskViewMap.get(task.key);
-            if (tv == null) {
-                tv = mViewPool.pickUpViewFromPool(task, task);
-                if (transform.rect.top <= mLayoutAlgorithm.mStackRect.top) {
-                    updateTaskViewToTransform(tv, mLayoutAlgorithm.getBackOfStackTransform(),
-                            AnimationProps.IMMEDIATE);
-                } else {
-                    updateTaskViewToTransform(tv, mLayoutAlgorithm.getFrontOfStackTransform(),
-                            AnimationProps.IMMEDIATE);
-                }
-            } else {
-                // Reattach it in the right z order
-                final int taskIndex = mStack.indexOfTask(task);
-                final int insertIndex = findTaskViewInsertIndex(task, taskIndex);
-                if (insertIndex != getTaskViews().indexOf(tv)){
-                    detachViewFromParent(tv);
-                    attachViewToParent(tv, insertIndex, tv.getLayoutParams());
-                    updateTaskViewsList();
-                }
-            }
-        }
-
-        updatePrefetchingTask(tasks, visibleTaskRange[0], visibleTaskRange[1]);
-
-        // Update the focus if the previous focused task was returned to the view pool
-        if (lastFocusedTaskIndex != -1) {
-            int newFocusedTaskIndex = (lastFocusedTaskIndex < visibleTaskRange[1])
-                    ? visibleTaskRange[1]
-                    : visibleTaskRange[0];
-            setFocusedTask(newFocusedTaskIndex, false /* scrollToTask */,
-                    true /* requestViewFocus */);
-            TaskView focusedTaskView = getChildViewForTask(mFocusedTask);
-            if (focusedTaskView != null) {
-                focusedTaskView.requestAccessibilityFocus();
-            }
-        }
-    }
-
-    /**
-     * @see #relayoutTaskViews(AnimationProps, ArrayMap<Task, AnimationProps>, boolean)
-     */
-    public void relayoutTaskViews(AnimationProps animation) {
-        relayoutTaskViews(animation, null /* animationOverrides */,
-                false /* ignoreTaskOverrides */);
-    }
-
-    /**
-     * Relayout the the visible {@link TaskView}s to their current transforms as specified by the
-     * {@link TaskStackLayoutAlgorithm} with the given {@param animation}. This call cancels any
-     * animations that are current running on those task views, and will ensure that the children
-     * {@link TaskView}s will match the set of visible tasks in the stack.  If a {@link Task} has
-     * an animation provided in {@param animationOverrides}, that will be used instead.
-     */
-    private void relayoutTaskViews(AnimationProps animation,
-            ArrayMap<Task, AnimationProps> animationOverrides, boolean ignoreTaskOverrides) {
-        // If we had a deferred animation, cancel that
-        cancelDeferredTaskViewLayoutAnimation();
-
-        // Synchronize the current set of TaskViews
-        bindVisibleTaskViews(mStackScroller.getStackScroll(), ignoreTaskOverrides);
-
-        // Animate them to their final transforms with the given animation
-        List<TaskView> taskViews = getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            if (mIgnoreTasks.contains(task.key)) {
-                continue;
-            }
-
-            int taskIndex = mStack.indexOfTask(task);
-            TaskViewTransform transform = mCurrentTaskTransforms.get(taskIndex);
-            if (animationOverrides != null && animationOverrides.containsKey(task)) {
-                animation = animationOverrides.get(task);
-            }
-
-            updateTaskViewToTransform(tv, transform, animation);
-        }
-    }
-
-    /**
-     * Posts an update to synchronize the {@link TaskView}s with the stack on the next frame.
-     */
-    void relayoutTaskViewsOnNextFrame(AnimationProps animation) {
-        mDeferredTaskViewLayoutAnimation = animation;
-        invalidate();
-    }
-
-    /**
-     * Called to update a specific {@link TaskView} to a given {@link TaskViewTransform} with a
-     * given set of {@link AnimationProps} properties.
-     */
-    public void updateTaskViewToTransform(TaskView taskView, TaskViewTransform transform,
-            AnimationProps animation) {
-        if (taskView.isAnimatingTo(transform)) {
-            return;
-        }
-        taskView.cancelTransformAnimation();
-        taskView.updateViewPropertiesToTaskTransform(transform, animation,
-                mRequestUpdateClippingListener);
-    }
-
-    /**
-     * Returns the current task transforms of all tasks, falling back to the stack layout if there
-     * is no {@link TaskView} for the task.
-     */
-    public void getCurrentTaskTransforms(ArrayList<Task> tasks,
-            ArrayList<TaskViewTransform> transformsOut) {
-        matchTaskListSize(tasks, transformsOut);
-        int focusState = mLayoutAlgorithm.getFocusState();
-        for (int i = tasks.size() - 1; i >= 0; i--) {
-            Task task = tasks.get(i);
-            TaskViewTransform transform = transformsOut.get(i);
-            TaskView tv = getChildViewForTask(task);
-            if (tv != null) {
-                transform.fillIn(tv);
-            } else {
-                mLayoutAlgorithm.getStackTransform(task, mStackScroller.getStackScroll(),
-                        focusState, transform, null, true /* forceUpdate */,
-                        false /* ignoreTaskOverrides */);
-            }
-            transform.visible = true;
-        }
-    }
-
-    /**
-     * Returns the task transforms for all the tasks in the stack if the stack was at the given
-     * {@param stackScroll} and {@param focusState}.
-     */
-    public void getLayoutTaskTransforms(float stackScroll, int focusState, ArrayList<Task> tasks,
-            boolean ignoreTaskOverrides, ArrayList<TaskViewTransform> transformsOut) {
-        matchTaskListSize(tasks, transformsOut);
-        for (int i = tasks.size() - 1; i >= 0; i--) {
-            Task task = tasks.get(i);
-            TaskViewTransform transform = transformsOut.get(i);
-            mLayoutAlgorithm.getStackTransform(task, stackScroll, focusState, transform, null,
-                    true /* forceUpdate */, ignoreTaskOverrides);
-            transform.visible = true;
-        }
-    }
-
-    /**
-     * Cancels the next deferred task view layout.
-     */
-    void cancelDeferredTaskViewLayoutAnimation() {
-        mDeferredTaskViewLayoutAnimation = null;
-    }
-
-    /**
-     * Cancels all {@link TaskView} animations.
-     */
-    void cancelAllTaskViewAnimations() {
-        List<TaskView> taskViews = getTaskViews();
-        for (int i = taskViews.size() - 1; i >= 0; i--) {
-            final TaskView tv = taskViews.get(i);
-            if (!mIgnoreTasks.contains(tv.getTask().key)) {
-                tv.cancelTransformAnimation();
-            }
-        }
-    }
-
-    /**
-     * Updates the clip for each of the task views from back to front.
-     */
-    private void clipTaskViews() {
-        // We never clip task views in grid layout
-        if (LegacyRecentsImpl.getConfiguration().isGridEnabled) {
-            return;
-        }
-
-        // Update the clip on each task child
-        List<TaskView> taskViews = getTaskViews();
-        TaskView tmpTv = null;
-        TaskView prevVisibleTv = null;
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            TaskView frontTv = null;
-            int clipBottom = 0;
-
-            if (isIgnoredTask(tv.getTask())) {
-                // For each of the ignore tasks, update the translationZ of its TaskView to be
-                // between the translationZ of the tasks immediately underneath it
-                if (prevVisibleTv != null) {
-                    tv.setTranslationZ(Math.max(tv.getTranslationZ(),
-                            prevVisibleTv.getTranslationZ() + 0.1f));
-                }
-            }
-
-            if (i < (taskViewCount - 1) && tv.shouldClipViewInStack()) {
-                // Find the next view to clip against
-                for (int j = i + 1; j < taskViewCount; j++) {
-                    tmpTv = taskViews.get(j);
-
-                    if (tmpTv.shouldClipViewInStack()) {
-                        frontTv = tmpTv;
-                        break;
-                    }
-                }
-
-                // Clip against the next view, this is just an approximation since we are
-                // stacked and we can make assumptions about the visibility of the this
-                // task relative to the ones in front of it.
-                if (frontTv != null) {
-                    float taskBottom = tv.getBottom();
-                    float frontTaskTop = frontTv.getTop();
-                    if (frontTaskTop < taskBottom) {
-                        // Map the stack view space coordinate (the rects) to view space
-                        clipBottom = (int) (taskBottom - frontTaskTop) - mTaskCornerRadiusPx;
-                    }
-                }
-            }
-            tv.getViewBounds().setClipBottom(clipBottom);
-            tv.mThumbnailView.updateThumbnailVisibility(clipBottom - tv.getPaddingBottom());
-            prevVisibleTv = tv;
-        }
-        mTaskViewsClipDirty = false;
-    }
-
-    public void updateLayoutAlgorithm(boolean boundScrollToNewMinMax) {
-        updateLayoutAlgorithm(boundScrollToNewMinMax, LegacyRecentsImpl.getConfiguration().getLaunchState());
-    }
-
-    /**
-     * Updates the layout algorithm min and max virtual scroll bounds.
-     */
-   public void updateLayoutAlgorithm(boolean boundScrollToNewMinMax,
-           RecentsActivityLaunchState launchState) {
-        // Compute the min and max scroll values
-        mLayoutAlgorithm.update(mStack, mIgnoreTasks, launchState, mLastScrollPPercent);
-
-        if (boundScrollToNewMinMax) {
-            mStackScroller.boundScroll();
-        }
-    }
-
-    /**
-     * Updates the stack layout to its stable places.
-     */
-    private void updateLayoutToStableBounds() {
-        mWindowRect.set(mStableWindowRect);
-        mStackBounds.set(mStableStackBounds);
-        mLayoutAlgorithm.setSystemInsets(mStableLayoutAlgorithm.mSystemInsets);
-        mLayoutAlgorithm.initialize(mDisplayRect, mWindowRect, mStackBounds);
-        updateLayoutAlgorithm(true /* boundScroll */);
-    }
-
-    /** Returns the scroller. */
-    public TaskStackViewScroller getScroller() {
-        return mStackScroller;
-    }
-
-    /**
-     * Sets the focused task to the provided (bounded taskIndex).
-     *
-     * @return whether or not the stack will scroll as a part of this focus change
-     */
-    public boolean setFocusedTask(int taskIndex, boolean scrollToTask,
-            final boolean requestViewFocus) {
-        return setFocusedTask(taskIndex, scrollToTask, requestViewFocus, 0);
-    }
-
-    /**
-     * Sets the focused task to the provided (bounded focusTaskIndex).
-     *
-     * @return whether or not the stack will scroll as a part of this focus change
-     */
-    public boolean setFocusedTask(int focusTaskIndex, boolean scrollToTask,
-            boolean requestViewFocus, int timerIndicatorDuration) {
-        // Find the next task to focus
-        int newFocusedTaskIndex = mStack.getTaskCount() > 0 ?
-                Utilities.clamp(focusTaskIndex, 0, mStack.getTaskCount() - 1) : -1;
-        final Task newFocusedTask = (newFocusedTaskIndex != -1) ?
-                mStack.getTasks().get(newFocusedTaskIndex) : null;
-
-        // Reset the last focused task state if changed
-        if (mFocusedTask != null) {
-            // Cancel the timer indicator, if applicable
-            if (timerIndicatorDuration > 0) {
-                final TaskView tv = getChildViewForTask(mFocusedTask);
-                if (tv != null) {
-                    tv.getHeaderView().cancelFocusTimerIndicator();
-                }
-            }
-
-            resetFocusedTask(mFocusedTask);
-        }
-
-        boolean willScroll = false;
-        mFocusedTask = newFocusedTask;
-
-        if (newFocusedTask != null) {
-            // Start the timer indicator, if applicable
-            if (timerIndicatorDuration > 0) {
-                final TaskView tv = getChildViewForTask(mFocusedTask);
-                if (tv != null) {
-                    tv.getHeaderView().startFocusTimerIndicator(timerIndicatorDuration);
-                } else {
-                    // The view is null; set a flag for later
-                    mStartTimerIndicatorDuration = timerIndicatorDuration;
-                }
-            }
-
-            if (scrollToTask) {
-                // Cancel any running enter animations at this point when we scroll or change focus
-                if (!mEnterAnimationComplete) {
-                    cancelAllTaskViewAnimations();
-                }
-
-                mLayoutAlgorithm.clearUnfocusedTaskOverrides();
-                willScroll = mAnimationHelper.startScrollToFocusedTaskAnimation(newFocusedTask,
-                        requestViewFocus);
-                if (willScroll) {
-                    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
-                }
-            } else {
-                // Focus the task view
-                TaskView newFocusedTaskView = getChildViewForTask(newFocusedTask);
-                if (newFocusedTaskView != null) {
-                    newFocusedTaskView.setFocusedState(true, requestViewFocus);
-                }
-            }
-            // Any time a task view gets the focus, we move the focus frame around it.
-            if (mTaskViewFocusFrame != null) {
-                mTaskViewFocusFrame.moveGridTaskViewFocus(getChildViewForTask(newFocusedTask));
-            }
-        }
-        return willScroll;
-    }
-
-    /**
-     * Sets the focused task relative to the currently focused task.
-     *
-     * @param forward whether to go to the next task in the stack (along the curve) or the previous
-     * @param stackTasksOnly if set, will ensure that the traversal only goes along stack tasks, and
-     *                       if the currently focused task is not a stack task, will set the focus
-     *                       to the first visible stack task
-     * @param animated determines whether to actually draw the highlight along with the change in
-     *                            focus.
-     */
-    public void setRelativeFocusedTask(boolean forward, boolean stackTasksOnly, boolean animated) {
-        setRelativeFocusedTask(forward, stackTasksOnly, animated, false, 0);
-    }
-
-    /**
-     * Sets the focused task relative to the currently focused task.
-     *
-     * @param forward whether to go to the next task in the stack (along the curve) or the previous
-     * @param stackTasksOnly if set, will ensure that the traversal only goes along stack tasks, and
-     *                       if the currently focused task is not a stack task, will set the focus
-     *                       to the first visible stack task
-     * @param animated determines whether to actually draw the highlight along with the change in
-     *                            focus.
-     * @param cancelWindowAnimations if set, will attempt to cancel window animations if a scroll
-     *                               happens.
-     * @param timerIndicatorDuration the duration to initialize the auto-advance timer indicator
-     */
-    public void setRelativeFocusedTask(boolean forward, boolean stackTasksOnly, boolean animated,
-                                       boolean cancelWindowAnimations, int timerIndicatorDuration) {
-        Task focusedTask = getFocusedTask();
-        int newIndex = mStack.indexOfTask(focusedTask);
-        if (focusedTask != null) {
-            if (stackTasksOnly) {
-                List<Task> tasks =  mStack.getTasks();
-                // Try the next task if it is a stack task
-                int tmpNewIndex = newIndex + (forward ? -1 : 1);
-                if (0 <= tmpNewIndex && tmpNewIndex < tasks.size()) {
-                    newIndex = tmpNewIndex;
-                }
-            } else {
-                // No restrictions, lets just move to the new task (looping forward/backwards if
-                // necessary)
-                int taskCount = mStack.getTaskCount();
-                newIndex = (newIndex + (forward ? -1 : 1) + taskCount) % taskCount;
-            }
-        } else {
-            // We don't have a focused task
-            float stackScroll = mStackScroller.getStackScroll();
-            ArrayList<Task> tasks = mStack.getTasks();
-            int taskCount = tasks.size();
-            if (useGridLayout()) {
-                // For the grid layout, we directly set focus to the most recently used task
-                // no matter we're moving forwards or backwards.
-                newIndex = taskCount - 1;
-            } else {
-                // For the grid layout we pick a proper task to focus, according to the current
-                // stack scroll.
-                if (forward) {
-                    // Walk backwards and focus the next task smaller than the current stack scroll
-                    for (newIndex = taskCount - 1; newIndex >= 0; newIndex--) {
-                        float taskP = mLayoutAlgorithm.getStackScrollForTask(tasks.get(newIndex));
-                        if (Float.compare(taskP, stackScroll) <= 0) {
-                            break;
-                        }
-                    }
-                } else {
-                    // Walk forwards and focus the next task larger than the current stack scroll
-                    for (newIndex = 0; newIndex < taskCount; newIndex++) {
-                        float taskP = mLayoutAlgorithm.getStackScrollForTask(tasks.get(newIndex));
-                        if (Float.compare(taskP, stackScroll) >= 0) {
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-        if (newIndex != -1) {
-            boolean willScroll = setFocusedTask(newIndex, true /* scrollToTask */,
-                    true /* requestViewFocus */, timerIndicatorDuration);
-            if (willScroll && cancelWindowAnimations) {
-                // As we iterate to the next/previous task, cancel any current/lagging window
-                // transition animations
-                EventBus.getDefault().send(new CancelEnterRecentsWindowAnimationEvent(null));
-            }
-        }
-    }
-
-    /**
-     * Resets the focused task.
-     */
-    public void resetFocusedTask(Task task) {
-        if (task != null) {
-            TaskView tv = getChildViewForTask(task);
-            if (tv != null) {
-                tv.setFocusedState(false, false /* requestViewFocus */);
-            }
-        }
-        if (mTaskViewFocusFrame != null) {
-            mTaskViewFocusFrame.moveGridTaskViewFocus(null);
-        }
-        mFocusedTask = null;
-    }
-
-    /**
-     * Returns the focused task.
-     */
-    public Task getFocusedTask() {
-        return mFocusedTask;
-    }
-
-    /**
-     * Returns the accessibility focused task.
-     */
-    Task getAccessibilityFocusedTask() {
-        List<TaskView> taskViews = getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            if (Utilities.isDescendentAccessibilityFocused(tv)) {
-                return tv.getTask();
-            }
-        }
-        TaskView frontTv = getFrontMostTaskView();
-        if (frontTv != null) {
-            return frontTv.getTask();
-        }
-        return null;
-    }
-
-    @Override
-    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
-        super.onInitializeAccessibilityEvent(event);
-        List<TaskView> taskViews = getTaskViews();
-        int taskViewCount = taskViews.size();
-        if (taskViewCount > 0) {
-            TaskView backMostTask = taskViews.get(0);
-            TaskView frontMostTask = taskViews.get(taskViewCount - 1);
-            event.setFromIndex(mStack.indexOfTask(backMostTask.getTask()));
-            event.setToIndex(mStack.indexOfTask(frontMostTask.getTask()));
-            event.setContentDescription(frontMostTask.getTask().title);
-        }
-        event.setItemCount(mStack.getTaskCount());
-
-        int stackHeight = mLayoutAlgorithm.mStackRect.height();
-        event.setScrollY((int) (mStackScroller.getStackScroll() * stackHeight));
-        event.setMaxScrollY((int) (mLayoutAlgorithm.mMaxScrollP * stackHeight));
-    }
-
-    @Override
-    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
-        super.onInitializeAccessibilityNodeInfo(info);
-        List<TaskView> taskViews = getTaskViews();
-        int taskViewCount = taskViews.size();
-        if (taskViewCount > 1) {
-            // Find the accessibility focused task
-            Task focusedTask = getAccessibilityFocusedTask();
-            info.setScrollable(true);
-            int focusedTaskIndex = mStack.indexOfTask(focusedTask);
-            if (focusedTaskIndex > 0 || !mStackActionButtonVisible) {
-                info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
-            }
-            if (0 <= focusedTaskIndex && focusedTaskIndex < mStack.getTaskCount() - 1) {
-                info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
-            }
-        }
-    }
-
-    @Override
-    public CharSequence getAccessibilityClassName() {
-        return ScrollView.class.getName();
-    }
-
-    @Override
-    public boolean performAccessibilityAction(int action, Bundle arguments) {
-        if (super.performAccessibilityAction(action, arguments)) {
-            return true;
-        }
-        Task focusedTask = getAccessibilityFocusedTask();
-        int taskIndex = mStack.indexOfTask(focusedTask);
-        if (0 <= taskIndex && taskIndex < mStack.getTaskCount()) {
-            switch (action) {
-                case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
-                    setFocusedTask(taskIndex + 1, true /* scrollToTask */, true /* requestViewFocus */,
-                            0);
-                    return true;
-                }
-                case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
-                    setFocusedTask(taskIndex - 1, true /* scrollToTask */, true /* requestViewFocus */,
-                            0);
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    @Override
-    public boolean onInterceptTouchEvent(MotionEvent ev) {
-        return mTouchHandler.onInterceptTouchEvent(ev);
-    }
-
-    @Override
-    public boolean onTouchEvent(MotionEvent ev) {
-        return mTouchHandler.onTouchEvent(ev);
-    }
-
-    @Override
-    public boolean onGenericMotionEvent(MotionEvent ev) {
-        return mTouchHandler.onGenericMotionEvent(ev);
-    }
-
-    @Override
-    public void computeScroll() {
-        if (mStackScroller.computeScroll()) {
-            // Notify accessibility
-            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
-            LegacyRecentsImpl.getTaskLoader().getHighResThumbnailLoader().setFlingingFast(
-                    mStackScroller.getScrollVelocity() > mFastFlingVelocity);
-        }
-        if (mDeferredTaskViewLayoutAnimation != null) {
-            relayoutTaskViews(mDeferredTaskViewLayoutAnimation);
-            mTaskViewsClipDirty = true;
-            mDeferredTaskViewLayoutAnimation = null;
-        }
-        if (mTaskViewsClipDirty) {
-            clipTaskViews();
-        }
-        mLastScrollPPercent = Utilities.clamp(Utilities.unmapRange(mStackScroller.getStackScroll(),
-            mLayoutAlgorithm.mMinScrollP, mLayoutAlgorithm.mMaxScrollP), 0, 1);
-    }
-
-    /**
-     * Computes the maximum number of visible tasks and thumbnails. Requires that
-     * updateLayoutForStack() is called first.
-     */
-    public TaskStackLayoutAlgorithm.VisibilityReport computeStackVisibilityReport() {
-        return mLayoutAlgorithm.computeStackVisibilityReport(mStack.getTasks());
-    }
-
-    /**
-     * Updates the system insets.
-     */
-    public void setSystemInsets(Rect systemInsets) {
-        boolean changed = false;
-        changed |= mStableLayoutAlgorithm.setSystemInsets(systemInsets);
-        changed |= mLayoutAlgorithm.setSystemInsets(systemInsets);
-        if (changed) {
-            requestLayout();
-        }
-    }
-
-    /**
-     * This is called with the full window width and height to allow stack view children to
-     * perform the full screen transition down.
-     */
-    @Override
-    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-        mInMeasureLayout = true;
-        int width = MeasureSpec.getSize(widthMeasureSpec);
-        int height = MeasureSpec.getSize(heightMeasureSpec);
-
-        // Update the stable stack bounds, but only update the current stack bounds if the stable
-        // bounds have changed.  This is because we may get spurious measures while dragging where
-        // our current stack bounds reflect the target drop region.
-        mLayoutAlgorithm.getTaskStackBounds(mDisplayRect, new Rect(0, 0, width, height),
-                mLayoutAlgorithm.mSystemInsets.top, mLayoutAlgorithm.mSystemInsets.left,
-                mLayoutAlgorithm.mSystemInsets.right, mTmpRect);
-        if (!mTmpRect.equals(mStableStackBounds)) {
-            mStableStackBounds.set(mTmpRect);
-            mStackBounds.set(mTmpRect);
-            mStableWindowRect.set(0, 0, width, height);
-            mWindowRect.set(0, 0, width, height);
-        }
-
-        // Compute the rects in the stack algorithm
-        mStableLayoutAlgorithm.initialize(mDisplayRect, mStableWindowRect, mStableStackBounds);
-        mLayoutAlgorithm.initialize(mDisplayRect, mWindowRect, mStackBounds);
-        updateLayoutAlgorithm(false /* boundScroll */);
-
-        // If this is the first layout, then scroll to the front of the stack, then update the
-        // TaskViews with the stack so that we can lay them out
-        boolean resetToInitialState = (width != mLastWidth || height != mLastHeight)
-                && mResetToInitialStateWhenResized;
-        if (!mFinishedLayoutAfterStackReload || mInitialState != INITIAL_STATE_UPDATE_NONE
-                || resetToInitialState) {
-            if (mInitialState != INITIAL_STATE_UPDATE_LAYOUT_ONLY || resetToInitialState) {
-                updateToInitialState();
-                mResetToInitialStateWhenResized = false;
-            }
-            if (mFinishedLayoutAfterStackReload) {
-                mInitialState = INITIAL_STATE_UPDATE_NONE;
-            }
-        }
-        // If we got the launch-next event before the first layout pass, then re-send it after the
-        // initial state has been updated
-        if (mLaunchNextAfterFirstMeasure) {
-            mLaunchNextAfterFirstMeasure = false;
-            EventBus.getDefault().post(new LaunchNextTaskRequestEvent());
-        }
-
-        // Rebind all the views, including the ignore ones
-        bindVisibleTaskViews(mStackScroller.getStackScroll(), false /* ignoreTaskOverrides */);
-
-        // Measure each of the TaskViews
-        mTmpTaskViews.clear();
-        mTmpTaskViews.addAll(getTaskViews());
-        mTmpTaskViews.addAll(mViewPool.getViews());
-        int taskViewCount = mTmpTaskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            measureTaskView(mTmpTaskViews.get(i));
-        }
-        if (mTaskViewFocusFrame != null) {
-            mTaskViewFocusFrame.measure();
-        }
-
-        setMeasuredDimension(width, height);
-        mLastWidth = width;
-        mLastHeight = height;
-        mInMeasureLayout = false;
-    }
-
-    /**
-     * Measures a TaskView.
-     */
-    private void measureTaskView(TaskView tv) {
-        Rect padding = new Rect();
-        if (tv.getBackground() != null) {
-            tv.getBackground().getPadding(padding);
-        }
-        mTmpRect.set(mStableLayoutAlgorithm.getTaskRect());
-        mTmpRect.union(mLayoutAlgorithm.getTaskRect());
-        tv.measure(
-                MeasureSpec.makeMeasureSpec(mTmpRect.width() + padding.left + padding.right,
-                        MeasureSpec.EXACTLY),
-                MeasureSpec.makeMeasureSpec(mTmpRect.height() + padding.top + padding.bottom,
-                        MeasureSpec.EXACTLY));
-    }
-
-    @Override
-    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
-        // Layout each of the TaskViews
-        mTmpTaskViews.clear();
-        mTmpTaskViews.addAll(getTaskViews());
-        mTmpTaskViews.addAll(mViewPool.getViews());
-        int taskViewCount = mTmpTaskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            layoutTaskView(changed, mTmpTaskViews.get(i));
-        }
-        if (mTaskViewFocusFrame != null) {
-            mTaskViewFocusFrame.layout();
-        }
-
-        if (changed) {
-            if (mStackScroller.isScrollOutOfBounds()) {
-                mStackScroller.boundScroll();
-            }
-        }
-
-        // Relayout all of the task views including the ignored ones
-        relayoutTaskViews(AnimationProps.IMMEDIATE);
-        clipTaskViews();
-
-        if (!mFinishedLayoutAfterStackReload) {
-            // Prepare the task enter animations (this can be called numerous times)
-            mInitialState = INITIAL_STATE_UPDATE_NONE;
-            onFirstLayout();
-
-            if (mStackReloaded) {
-                mFinishedLayoutAfterStackReload = true;
-                tryStartEnterAnimation();
-            }
-        }
-    }
-
-    /**
-     * Lays out a TaskView.
-     */
-    private void layoutTaskView(boolean changed, TaskView tv) {
-        if (changed) {
-            Rect padding = new Rect();
-            if (tv.getBackground() != null) {
-                tv.getBackground().getPadding(padding);
-            }
-            mTmpRect.set(mStableLayoutAlgorithm.getTaskRect());
-            mTmpRect.union(mLayoutAlgorithm.getTaskRect());
-            tv.cancelTransformAnimation();
-            tv.layout(mTmpRect.left - padding.left, mTmpRect.top - padding.top,
-                    mTmpRect.right + padding.right, mTmpRect.bottom + padding.bottom);
-        } else {
-            // If the layout has not changed, then just lay it out again in-place
-            tv.layout(tv.getLeft(), tv.getTop(), tv.getRight(), tv.getBottom());
-        }
-    }
-
-    /** Handler for the first layout. */
-    void onFirstLayout() {
-        // Setup the view for the enter animation
-        mAnimationHelper.prepareForEnterAnimation();
-
-        // Set the task focused state without requesting view focus, and leave the focus animations
-        // until after the enter-animation
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        RecentsActivityLaunchState launchState = config.getLaunchState();
-
-        // We set the initial focused task view iff the following conditions are satisfied:
-        // 1. Recents is showing task views in stack layout.
-        // 2. Recents is launched with ALT + TAB.
-        boolean setFocusOnFirstLayout = !useGridLayout() || launchState.launchedWithAltTab;
-        if (setFocusOnFirstLayout) {
-            int focusedTaskIndex = getInitialFocusTaskIndex(launchState, mStack.getTaskCount(),
-                useGridLayout());
-            if (focusedTaskIndex != -1) {
-                setFocusedTask(focusedTaskIndex, false /* scrollToTask */,
-                        false /* requestViewFocus */);
-            }
-        }
-        updateStackActionButtonVisibility();
-    }
-
-    public boolean isTouchPointInView(float x, float y, TaskView tv) {
-        mTmpRect.set(tv.getLeft(), tv.getTop(), tv.getRight(), tv.getBottom());
-        mTmpRect.offset((int) tv.getTranslationX(), (int) tv.getTranslationY());
-        return mTmpRect.contains((int) x, (int) y);
-    }
-
-    /**
-     * Returns a non-ignored task in the {@param tasks} list that can be used as an achor when
-     * calculating the scroll position before and after a layout change.
-     */
-    public Task findAnchorTask(List<Task> tasks, MutableBoolean isFrontMostTask) {
-        for (int i = tasks.size() - 1; i >= 0; i--) {
-            Task task = tasks.get(i);
-
-            // Ignore deleting tasks
-            if (isIgnoredTask(task)) {
-                if (i == tasks.size() - 1) {
-                    isFrontMostTask.value = true;
-                }
-                continue;
-            }
-            return task;
-        }
-        return null;
-    }
-
-    /**** TaskStackCallbacks Implementation ****/
-
-    @Override
-    public void onStackTaskAdded(TaskStack stack, Task newTask) {
-        // Update the min/max scroll and animate other task views into their new positions
-        updateLayoutAlgorithm(true /* boundScroll */);
-
-        // Animate all the tasks into place
-        relayoutTaskViews(!mFinishedLayoutAfterStackReload
-                ? AnimationProps.IMMEDIATE
-                : new AnimationProps(DEFAULT_SYNC_STACK_DURATION, Interpolators.FAST_OUT_SLOW_IN));
-    }
-
-    /**
-     * We expect that the {@link TaskView} associated with the removed task is already hidden.
-     */
-    @Override
-    public void onStackTaskRemoved(TaskStack stack, Task removedTask, Task newFrontMostTask,
-            AnimationProps animation, boolean fromDockGesture, boolean dismissRecentsIfAllRemoved) {
-        if (mFocusedTask == removedTask) {
-            resetFocusedTask(removedTask);
-        }
-
-        // Remove the view associated with this task, we can't rely on updateTransforms
-        // to work here because the task is no longer in the list
-        TaskView tv = getChildViewForTask(removedTask);
-        if (tv != null) {
-            mViewPool.returnViewToPool(tv);
-        }
-
-        // Remove the task from the ignored set
-        removeIgnoreTask(removedTask);
-
-        // If requested, relayout with the given animation
-        if (animation != null) {
-            updateLayoutAlgorithm(true /* boundScroll */);
-            relayoutTaskViews(animation);
-        }
-
-        // Update the new front most task's action button
-        if (mScreenPinningEnabled && newFrontMostTask != null) {
-            TaskView frontTv = getChildViewForTask(newFrontMostTask);
-            if (frontTv != null) {
-                frontTv.showActionButton(true /* fadeIn */, DEFAULT_SYNC_STACK_DURATION);
-            }
-        }
-
-        // If there are no remaining tasks, then just close recents
-        if (mStack.getTaskCount() == 0) {
-            if (dismissRecentsIfAllRemoved) {
-                EventBus.getDefault().send(new AllTaskViewsDismissedEvent(fromDockGesture
-                        ? R.string.recents_empty_message
-                        : R.string.recents_empty_message_dismissed_all));
-            } else {
-                EventBus.getDefault().send(new ShowEmptyViewEvent());
-            }
-        }
-    }
-
-    @Override
-    public void onStackTasksRemoved(TaskStack stack) {
-        // Reset the focused task
-        resetFocusedTask(getFocusedTask());
-
-        // Return all the views to the pool
-        List<TaskView> taskViews = new ArrayList<>();
-        taskViews.addAll(getTaskViews());
-        for (int i = taskViews.size() - 1; i >= 0; i--) {
-            mViewPool.returnViewToPool(taskViews.get(i));
-        }
-
-        // Remove all the ignore tasks
-        mIgnoreTasks.clear();
-
-        // If there are no remaining tasks, then just close recents
-        EventBus.getDefault().send(new AllTaskViewsDismissedEvent(
-                R.string.recents_empty_message_dismissed_all));
-    }
-
-    @Override
-    public void onStackTasksUpdated(TaskStack stack) {
-        if (!mFinishedLayoutAfterStackReload) {
-            return;
-        }
-
-        // Update the layout and immediately layout
-        updateLayoutAlgorithm(false /* boundScroll */);
-        relayoutTaskViews(AnimationProps.IMMEDIATE);
-
-        // Rebind all the task views.  This will not trigger new resources to be loaded
-        // unless they have actually changed
-        List<TaskView> taskViews = getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            bindTaskView(tv, tv.getTask());
-        }
-    }
-
-    /**** ViewPoolConsumer Implementation ****/
-
-    @Override
-    public TaskView createView(Context context) {
-        if (LegacyRecentsImpl.getConfiguration().isGridEnabled) {
-            return (GridTaskView) mInflater.inflate(R.layout.recents_grid_task_view, this, false);
-        } else {
-            return (TaskView) mInflater.inflate(R.layout.recents_task_view, this, false);
-        }
-    }
-
-    @Override
-    public void onReturnViewToPool(TaskView tv) {
-        final Task task = tv.getTask();
-
-        // Unbind the task from the task view
-        unbindTaskView(tv, task);
-
-        // Reset the view properties and view state
-        tv.clearAccessibilityFocus();
-        tv.resetViewProperties();
-        tv.setFocusedState(false, false /* requestViewFocus */);
-        tv.setClipViewInStack(false);
-        if (mScreenPinningEnabled) {
-            tv.hideActionButton(false /* fadeOut */, 0 /* duration */, false /* scaleDown */, null);
-        }
-
-        // Detach the view from the hierarchy
-        detachViewFromParent(tv);
-        // Update the task views list after removing the task view
-        updateTaskViewsList();
-    }
-
-    @Override
-    public void onPickUpViewFromPool(TaskView tv, Task task, boolean isNewView) {
-        // Find the index where this task should be placed in the stack
-        int taskIndex = mStack.indexOfTask(task);
-        int insertIndex = findTaskViewInsertIndex(task, taskIndex);
-
-        // Add/attach the view to the hierarchy
-        if (isNewView) {
-            if (mInMeasureLayout) {
-                // If we are measuring the layout, then just add the view normally as it will be
-                // laid out during the layout pass
-                addView(tv, insertIndex);
-            } else {
-                // Otherwise, this is from a bindVisibleTaskViews() call outside the measure/layout
-                // pass, and we should layout the new child ourselves
-                ViewGroup.LayoutParams params = tv.getLayoutParams();
-                if (params == null) {
-                    params = generateDefaultLayoutParams();
-                }
-                addViewInLayout(tv, insertIndex, params, true /* preventRequestLayout */);
-                measureTaskView(tv);
-                layoutTaskView(true /* changed */, tv);
-            }
-        } else {
-            attachViewToParent(tv, insertIndex, tv.getLayoutParams());
-        }
-        // Update the task views list after adding the new task view
-        updateTaskViewsList();
-
-        // Bind the task view to the new task
-        bindTaskView(tv, task);
-
-        // Set the new state for this view, including the callbacks and view clipping
-        tv.setCallbacks(this);
-        tv.setTouchEnabled(true);
-        tv.setClipViewInStack(true);
-        if (mFocusedTask == task) {
-            tv.setFocusedState(true, false /* requestViewFocus */);
-            if (mStartTimerIndicatorDuration > 0) {
-                // The timer indicator couldn't be started before, so start it now
-                tv.getHeaderView().startFocusTimerIndicator(mStartTimerIndicatorDuration);
-                mStartTimerIndicatorDuration = 0;
-            }
-        }
-
-        // Restore the action button visibility if it is the front most task view
-        if (mScreenPinningEnabled && tv.getTask() == mStack.getFrontMostTask()) {
-            tv.showActionButton(false /* fadeIn */, 0 /* fadeInDuration */);
-        }
-    }
-
-    @Override
-    public boolean hasPreferredData(TaskView tv, Task preferredData) {
-        return (tv.getTask() == preferredData);
-    }
-
-    private void bindTaskView(TaskView tv, Task task) {
-        // Rebind the task and request that this task's data be filled into the TaskView
-        tv.onTaskBound(task, mTouchExplorationEnabled, mDisplayOrientation, mDisplayRect);
-
-        // If the doze trigger has already fired, then update the state for this task view
-        if (mUIDozeTrigger.isAsleep() ||
-                useGridLayout() || LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            tv.setNoUserInteractionState();
-        }
-
-        if (task == mPrefetchingTask) {
-            task.notifyTaskDataLoaded(task.thumbnail, task.icon);
-        } else {
-            // Load the task data
-            LegacyRecentsImpl.getTaskLoader().loadTaskData(task);
-        }
-        LegacyRecentsImpl.getTaskLoader().getHighResThumbnailLoader().onTaskVisible(task);
-    }
-
-    private void unbindTaskView(TaskView tv, Task task) {
-        if (task != mPrefetchingTask) {
-            // Report that this task's data is no longer being used
-            LegacyRecentsImpl.getTaskLoader().unloadTaskData(task);
-        }
-        LegacyRecentsImpl.getTaskLoader().getHighResThumbnailLoader().onTaskInvisible(task);
-    }
-
-    private void updatePrefetchingTask(ArrayList<Task> tasks, int frontIndex, int backIndex) {
-        Task t = null;
-        boolean somethingVisible = frontIndex != -1 && backIndex != -1;
-        if (somethingVisible && frontIndex < tasks.size() - 1) {
-            t = tasks.get(frontIndex + 1);
-        }
-        if (mPrefetchingTask != t) {
-            if (mPrefetchingTask != null) {
-                int index = tasks.indexOf(mPrefetchingTask);
-                if (index < backIndex || index > frontIndex) {
-                    LegacyRecentsImpl.getTaskLoader().unloadTaskData(mPrefetchingTask);
-                }
-            }
-            mPrefetchingTask = t;
-            if (t != null) {
-                LegacyRecentsImpl.getTaskLoader().loadTaskData(t);
-            }
-        }
-    }
-
-    private void clearPrefetchingTask() {
-        if (mPrefetchingTask != null) {
-            LegacyRecentsImpl.getTaskLoader().unloadTaskData(mPrefetchingTask);
-        }
-        mPrefetchingTask = null;
-    }
-
-    /**** TaskViewCallbacks Implementation ****/
-
-    @Override
-    public void onTaskViewClipStateChanged(TaskView tv) {
-        if (!mTaskViewsClipDirty) {
-            mTaskViewsClipDirty = true;
-            invalidate();
-        }
-    }
-
-    /**** TaskStackLayoutAlgorithm.TaskStackLayoutAlgorithmCallbacks ****/
-
-    @Override
-    public void onFocusStateChanged(int prevFocusState, int curFocusState) {
-        if (mDeferredTaskViewLayoutAnimation == null) {
-            mUIDozeTrigger.poke();
-            relayoutTaskViewsOnNextFrame(AnimationProps.IMMEDIATE);
-        }
-    }
-
-    /**** TaskStackViewScroller.TaskStackViewScrollerCallbacks ****/
-
-    @Override
-    public void onStackScrollChanged(float prevScroll, float curScroll, AnimationProps animation) {
-        mUIDozeTrigger.poke();
-        if (animation != null) {
-            relayoutTaskViewsOnNextFrame(animation);
-        }
-
-        // In grid layout, the stack action button always remains visible.
-        if (mEnterAnimationComplete && !useGridLayout()) {
-            if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                // Show stack button when user drags down to show older tasks on low ram devices
-                if (mStack.getTaskCount() > 0 && !mStackActionButtonVisible
-                        && mTouchHandler.mIsScrolling && curScroll - prevScroll < 0) {
-                    // Going up
-                    EventBus.getDefault().send(
-                            new ShowStackActionButtonEvent(true /* translate */));
-                }
-                return;
-            }
-            if (prevScroll > SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
-                    curScroll <= SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
-                    mStack.getTaskCount() > 0) {
-                EventBus.getDefault().send(new ShowStackActionButtonEvent(true /* translate */));
-            } else if (prevScroll < HIDE_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
-                    curScroll >= HIDE_STACK_ACTION_BUTTON_SCROLL_THRESHOLD) {
-                EventBus.getDefault().send(new HideStackActionButtonEvent());
-            }
-        }
-    }
-
-    /**** EventBus Events ****/
-
-    public final void onBusEvent(PackagesChangedEvent event) {
-        // Compute which components need to be removed
-        ArraySet<ComponentName> removedComponents = mStack.computeComponentsRemoved(
-                event.packageName, event.userId);
-
-        // For other tasks, just remove them directly if they no longer exist
-        ArrayList<Task> tasks = mStack.getTasks();
-        for (int i = tasks.size() - 1; i >= 0; i--) {
-            final Task t = tasks.get(i);
-            if (removedComponents.contains(t.key.getComponent())) {
-                final TaskView tv = getChildViewForTask(t);
-                if (tv != null) {
-                    // For visible children, defer removing the task until after the animation
-                    tv.dismissTask();
-                } else {
-                    // Otherwise, remove the task from the stack immediately
-                    mStack.removeTask(t, AnimationProps.IMMEDIATE, false /* fromDockGesture */);
-                }
-            }
-        }
-    }
-
-    public final void onBusEvent(LaunchTaskEvent event) {
-        // Cancel any doze triggers once a task is launched
-        mUIDozeTrigger.stopDozing();
-    }
-
-    public final void onBusEvent(LaunchMostRecentTaskRequestEvent event) {
-        if (mStack.getTaskCount() > 0) {
-            Task mostRecentTask = mStack.getFrontMostTask();
-            launchTask(mostRecentTask);
-        }
-    }
-
-    public final void onBusEvent(ShowStackActionButtonEvent event) {
-        mStackActionButtonVisible = true;
-    }
-
-    public final void onBusEvent(HideStackActionButtonEvent event) {
-        mStackActionButtonVisible = false;
-    }
-
-    public final void onBusEvent(LaunchNextTaskRequestEvent event) {
-        if (!mFinishedLayoutAfterStackReload) {
-            mLaunchNextAfterFirstMeasure = true;
-            return;
-        }
-
-        if (mStack.getTaskCount() == 0) {
-            if (RecentsImpl.getLastPipTime() != -1) {
-                EventBus.getDefault().send(new ExpandPipEvent());
-                MetricsLogger.action(getContext(), MetricsEvent.OVERVIEW_LAUNCH_PREVIOUS_TASK,
-                        "pip");
-            } else {
-                // If there are no tasks, then just hide recents back to home.
-                EventBus.getDefault().send(new HideRecentsEvent(false, true));
-            }
-            return;
-        }
-
-        if (!LegacyRecentsImpl.getConfiguration().getLaunchState().launchedFromPipApp
-                && mStack.isNextLaunchTargetPip(RecentsImpl.getLastPipTime())) {
-            // If the launch task is in the pinned stack, then expand the PiP now
-            EventBus.getDefault().send(new ExpandPipEvent());
-            MetricsLogger.action(getContext(), MetricsEvent.OVERVIEW_LAUNCH_PREVIOUS_TASK, "pip");
-        } else {
-            final Task launchTask = mStack.getNextLaunchTarget();
-            if (launchTask != null) {
-                // Defer launching the task until the PiP menu has been dismissed (if it is
-                // showing at all)
-                HidePipMenuEvent hideMenuEvent = new HidePipMenuEvent();
-                hideMenuEvent.addPostAnimationCallback(() -> {
-                    launchTask(launchTask);
-                });
-                EventBus.getDefault().send(hideMenuEvent);
-                MetricsLogger.action(getContext(), MetricsEvent.OVERVIEW_LAUNCH_PREVIOUS_TASK,
-                        launchTask.key.getComponent().toString());
-            }
-        }
-    }
-
-    public final void onBusEvent(LaunchTaskStartedEvent event) {
-        mAnimationHelper.startLaunchTaskAnimation(event.taskView, event.screenPinningRequested,
-                event.getAnimationTrigger());
-    }
-
-    public final void onBusEvent(DismissRecentsToHomeAnimationStarted event) {
-        // Stop any scrolling
-        mTouchHandler.cancelNonDismissTaskAnimations();
-        mStackScroller.stopScroller();
-        mStackScroller.stopBoundScrollAnimation();
-        cancelDeferredTaskViewLayoutAnimation();
-
-        // Start the task animations
-        mAnimationHelper.startExitToHomeAnimation(event.animated, event.getAnimationTrigger());
-
-        // Dismiss the grid task view focus frame
-        if (mTaskViewFocusFrame != null) {
-            mTaskViewFocusFrame.moveGridTaskViewFocus(null);
-        }
-    }
-
-    public final void onBusEvent(DismissFocusedTaskViewEvent event) {
-        if (mFocusedTask != null) {
-            if (mTaskViewFocusFrame != null) {
-                mTaskViewFocusFrame.moveGridTaskViewFocus(null);
-            }
-            TaskView tv = getChildViewForTask(mFocusedTask);
-            if (tv != null) {
-                tv.dismissTask();
-            }
-            resetFocusedTask(mFocusedTask);
-        }
-    }
-
-    public final void onBusEvent(DismissTaskViewEvent event) {
-        // For visible children, defer removing the task until after the animation
-        mAnimationHelper.startDeleteTaskAnimation(
-                event.taskView, useGridLayout(), event.getAnimationTrigger());
-    }
-
-    public final void onBusEvent(final DismissAllTaskViewsEvent event) {
-        // Keep track of the tasks which will have their data removed
-        ArrayList<Task> tasks = new ArrayList<>(mStack.getTasks());
-        mAnimationHelper.startDeleteAllTasksAnimation(
-                getTaskViews(), useGridLayout(), event.getAnimationTrigger());
-        event.addPostAnimationCallback(new Runnable() {
-            @Override
-            public void run() {
-                // Announce for accessibility
-                announceForAccessibility(getContext().getString(
-                        R.string.accessibility_recents_all_items_dismissed));
-
-                // Remove all tasks and delete the task data for all tasks
-                mStack.removeAllTasks(true /* notifyStackChanges */);
-                for (int i = tasks.size() - 1; i >= 0; i--) {
-                    EventBus.getDefault().send(new DeleteTaskDataEvent(tasks.get(i)));
-                }
-
-                MetricsLogger.action(getContext(), MetricsEvent.OVERVIEW_DISMISS_ALL);
-            }
-        });
-
-    }
-
-    public final void onBusEvent(TaskViewDismissedEvent event) {
-        // Announce for accessibility
-        announceForAccessibility(getContext().getString(
-                R.string.accessibility_recents_item_dismissed, event.task.title));
-
-        if (useGridLayout() && event.animation != null) {
-            event.animation.setListener(new AnimatorListenerAdapter() {
-                public void onAnimationEnd(Animator animator) {
-                    if (mTaskViewFocusFrame != null) {
-                        // Resize the grid layout task view focus frame
-                        mTaskViewFocusFrame.resize();
-                    }
-                }
-            });
-        }
-
-        // Remove the task from the stack
-        mStack.removeTask(event.task, event.animation, false /* fromDockGesture */);
-        EventBus.getDefault().send(new DeleteTaskDataEvent(event.task));
-        if (mStack.getTaskCount() > 0 && LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            EventBus.getDefault().send(new ShowStackActionButtonEvent(false /* translate */));
-        }
-
-        MetricsLogger.action(getContext(), MetricsEvent.OVERVIEW_DISMISS,
-                event.task.key.getComponent().toString());
-    }
-
-    public final void onBusEvent(FocusNextTaskViewEvent event) {
-        // Stop any scrolling
-        mStackScroller.stopScroller();
-        mStackScroller.stopBoundScrollAnimation();
-
-        setRelativeFocusedTask(true, false /* stackTasksOnly */, true /* animated */, false, 0);
-    }
-
-    public final void onBusEvent(FocusPreviousTaskViewEvent event) {
-        // Stop any scrolling
-        mStackScroller.stopScroller();
-        mStackScroller.stopBoundScrollAnimation();
-
-        setRelativeFocusedTask(false, false /* stackTasksOnly */, true /* animated */);
-    }
-
-    public final void onBusEvent(NavigateTaskViewEvent event) {
-        if (useGridLayout()) {
-            final int taskCount = mStack.getTaskCount();
-            final int currentIndex = mStack.indexOfTask(getFocusedTask());
-            final int nextIndex = mLayoutAlgorithm.mTaskGridLayoutAlgorithm.navigateFocus(taskCount,
-                    currentIndex, event.direction);
-            setFocusedTask(nextIndex, false, true);
-        } else {
-            switch (event.direction) {
-                case UP:
-                    EventBus.getDefault().send(new FocusPreviousTaskViewEvent());
-                    break;
-                case DOWN:
-                    EventBus.getDefault().send(new FocusNextTaskViewEvent());
-                    break;
-            }
-        }
-    }
-
-    public final void onBusEvent(UserInteractionEvent event) {
-        // Poke the doze trigger on user interaction
-        mUIDozeTrigger.poke();
-
-        RecentsDebugFlags debugFlags = LegacyRecentsImpl.getDebugFlags();
-        if (mFocusedTask != null) {
-            TaskView tv = getChildViewForTask(mFocusedTask);
-            if (tv != null) {
-                tv.getHeaderView().cancelFocusTimerIndicator();
-            }
-        }
-    }
-
-    public final void onBusEvent(DragStartEvent event) {
-        // Ensure that the drag task is not animated
-        addIgnoreTask(event.task);
-
-        // Enlarge the dragged view slightly
-        float finalScale = event.taskView.getScaleX() * DRAG_SCALE_FACTOR;
-        mLayoutAlgorithm.getStackTransform(event.task, getScroller().getStackScroll(),
-                mTmpTransform, null);
-        mTmpTransform.scale = finalScale;
-        mTmpTransform.translationZ = mLayoutAlgorithm.mMaxTranslationZ + 1;
-        mTmpTransform.dimAlpha = 0f;
-        updateTaskViewToTransform(event.taskView, mTmpTransform,
-                new AnimationProps(DRAG_SCALE_DURATION, Interpolators.FAST_OUT_SLOW_IN));
-    }
-
-    public final void onBusEvent(DragDropTargetChangedEvent event) {
-        AnimationProps animation = new AnimationProps(SLOW_SYNC_STACK_DURATION,
-                Interpolators.FAST_OUT_SLOW_IN);
-        boolean ignoreTaskOverrides = false;
-        if (event.dropTarget instanceof DockState) {
-            // Calculate the new task stack bounds that matches the window size that Recents will
-            // have after the drop
-            final DockState dockState = (DockState) event.dropTarget;
-            Rect systemInsets = new Rect(mStableLayoutAlgorithm.mSystemInsets);
-            // When docked, the nav bar insets are consumed and the activity is measured without
-            // insets.  However, the window bounds include the insets, so we need to subtract them
-            // here to make them identical.
-            int height = getMeasuredHeight();
-            height -= systemInsets.bottom;
-            systemInsets.bottom = 0;
-            mStackBounds.set(dockState.getDockedTaskStackBounds(mDisplayRect, getMeasuredWidth(),
-                    height, mDividerSize, systemInsets,
-                    mLayoutAlgorithm, getResources(), mWindowRect));
-            mLayoutAlgorithm.setSystemInsets(systemInsets);
-            mLayoutAlgorithm.initialize(mDisplayRect, mWindowRect, mStackBounds);
-            updateLayoutAlgorithm(true /* boundScroll */);
-            ignoreTaskOverrides = true;
-        } else {
-            // Restore the pre-drag task stack bounds, but ensure that we don't layout the dragging
-            // task view, so add it back to the ignore set after updating the layout
-            removeIgnoreTask(event.task);
-            updateLayoutToStableBounds();
-            addIgnoreTask(event.task);
-        }
-        relayoutTaskViews(animation, null /* animationOverrides */, ignoreTaskOverrides);
-    }
-
-    public final void onBusEvent(final DragEndEvent event) {
-        // We don't handle drops on the dock regions
-        if (event.dropTarget instanceof DockState) {
-            // However, we do need to reset the overrides, since the last state of this task stack
-            // view layout was ignoring task overrides (see DragDropTargetChangedEvent handler)
-            mLayoutAlgorithm.clearUnfocusedTaskOverrides();
-            return;
-        }
-
-        // Restore the task, so that relayout will apply to it below
-        removeIgnoreTask(event.task);
-
-        // Convert the dragging task view back to its final layout-space rect
-        Utilities.setViewFrameFromTranslation(event.taskView);
-
-        // Animate all the tasks into place
-        ArrayMap<Task, AnimationProps> animationOverrides = new ArrayMap<>();
-        animationOverrides.put(event.task, new AnimationProps(SLOW_SYNC_STACK_DURATION,
-                Interpolators.FAST_OUT_SLOW_IN,
-                event.getAnimationTrigger().decrementOnAnimationEnd()));
-        relayoutTaskViews(new AnimationProps(SLOW_SYNC_STACK_DURATION,
-                Interpolators.FAST_OUT_SLOW_IN));
-        event.getAnimationTrigger().increment();
-    }
-
-    public final void onBusEvent(final DragEndCancelledEvent event) {
-        // Restore the pre-drag task stack bounds, including the dragging task view
-        removeIgnoreTask(event.task);
-        updateLayoutToStableBounds();
-
-        // Convert the dragging task view back to its final layout-space rect
-        Utilities.setViewFrameFromTranslation(event.taskView);
-
-        // Animate all the tasks into place
-        ArrayMap<Task, AnimationProps> animationOverrides = new ArrayMap<>();
-        animationOverrides.put(event.task, new AnimationProps(SLOW_SYNC_STACK_DURATION,
-                Interpolators.FAST_OUT_SLOW_IN,
-                event.getAnimationTrigger().decrementOnAnimationEnd()));
-        relayoutTaskViews(new AnimationProps(SLOW_SYNC_STACK_DURATION,
-                Interpolators.FAST_OUT_SLOW_IN));
-        event.getAnimationTrigger().increment();
-    }
-
-    public final void onBusEvent(EnterRecentsWindowAnimationCompletedEvent event) {
-        mEnterAnimationComplete = true;
-        tryStartEnterAnimation();
-    }
-
-    private void tryStartEnterAnimation() {
-        if (!mStackReloaded || !mFinishedLayoutAfterStackReload || !mEnterAnimationComplete) {
-            return;
-        }
-
-        if (mStack.getTaskCount() > 0) {
-            // Start the task enter animations
-            ReferenceCountedTrigger trigger = new ReferenceCountedTrigger();
-            mAnimationHelper.startEnterAnimation(trigger);
-
-            // Add a runnable to the post animation ref counter to clear all the views
-            trigger.addLastDecrementRunnable(() -> {
-                // Start the dozer to trigger to trigger any UI that shows after a timeout
-                mUIDozeTrigger.startDozing();
-
-                // Update the focused state here -- since we only set the focused task without
-                // requesting view focus in onFirstLayout(), actually request view focus and
-                // animate the focused state if we are alt-tabbing now, after the window enter
-                // animation is completed
-                if (mFocusedTask != null) {
-                    RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-                    RecentsActivityLaunchState launchState = config.getLaunchState();
-                    setFocusedTask(mStack.indexOfTask(mFocusedTask),
-                            false /* scrollToTask */, launchState.launchedWithAltTab);
-                    TaskView focusedTaskView = getChildViewForTask(mFocusedTask);
-                    if (mTouchExplorationEnabled && focusedTaskView != null) {
-                        focusedTaskView.requestAccessibilityFocus();
-                    }
-                }
-            });
-        }
-
-        // This flag is only used to choreograph the enter animation, so we can reset it here
-        mStackReloaded = false;
-    }
-
-    public final void onBusEvent(final MultiWindowStateChangedEvent event) {
-        if (event.inMultiWindow || !event.showDeferredAnimation) {
-            setTasks(event.stack, true /* allowNotifyStackChanges */);
-        } else {
-            // Reset the launch state before handling the multiwindow change
-            RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-            launchState.reset();
-
-            // Defer until the next frame to ensure that we have received all the system insets, and
-            // initial layout updates
-            event.getAnimationTrigger().increment();
-            post(new Runnable() {
-                @Override
-                public void run() {
-                    // Scroll the stack to the front to see the undocked task
-                    mAnimationHelper.startNewStackScrollAnimation(event.stack,
-                            event.getAnimationTrigger());
-                    event.getAnimationTrigger().decrement();
-                }
-            });
-        }
-    }
-
-    public final void onBusEvent(ConfigurationChangedEvent event) {
-        if (event.fromDeviceOrientationChange) {
-            mDisplayOrientation = Utilities.getAppConfiguration(mContext).orientation;
-            mDisplayRect = LegacyRecentsImpl.getSystemServices().getDisplayRect();
-
-            // Always stop the scroller, otherwise, we may continue setting the stack scroll to the
-            // wrong bounds in the new layout
-            mStackScroller.stopScroller();
-        }
-        reloadOnConfigurationChange();
-
-        // Notify the task views of the configuration change so they can reload their resources
-        if (!event.fromMultiWindow) {
-            mTmpTaskViews.clear();
-            mTmpTaskViews.addAll(getTaskViews());
-            mTmpTaskViews.addAll(mViewPool.getViews());
-            int taskViewCount = mTmpTaskViews.size();
-            for (int i = 0; i < taskViewCount; i++) {
-                mTmpTaskViews.get(i).onConfigurationChanged();
-            }
-        }
-
-        // Update the Clear All button in case we're switching in or out of grid layout.
-        updateStackActionButtonVisibility();
-
-        // Trigger a new layout and update to the initial state if necessary. When entering split
-        // screen, the multi-window configuration change event can happen after the stack is already
-        // reloaded (but pending measure/layout), in this case, do not override the intiial state
-        // and just wait for the upcoming measure/layout pass.
-        if (event.fromMultiWindow && mInitialState == INITIAL_STATE_UPDATE_NONE) {
-            mInitialState = INITIAL_STATE_UPDATE_LAYOUT_ONLY;
-            requestLayout();
-        } else if (event.fromDeviceOrientationChange) {
-            mInitialState = INITIAL_STATE_UPDATE_ALL;
-            requestLayout();
-        }
-    }
-
-    public final void onBusEvent(RecentsGrowingEvent event) {
-        mResetToInitialStateWhenResized = true;
-    }
-
-    public final void onBusEvent(RecentsVisibilityChangedEvent event) {
-        if (!event.visible) {
-            if (mTaskViewFocusFrame != null) {
-                mTaskViewFocusFrame.moveGridTaskViewFocus(null);
-            }
-
-            List<TaskView> taskViews = new ArrayList<>(getTaskViews());
-            for (int i = 0; i < taskViews.size(); i++) {
-                mViewPool.returnViewToPool(taskViews.get(i));
-            }
-            clearPrefetchingTask();
-
-            // We can not reset mEnterAnimationComplete in onReload() because when docking the top
-            // task, we can receive the enter animation callback before onReload(), so reset it
-            // here onces Recents is not visible
-            mEnterAnimationComplete = false;
-        }
-    }
-
-    public final void onBusEvent(ActivityPinnedEvent event) {
-        // If an activity enters PiP while Recents is open, remove the stack task associated with
-        // the new PiP task
-        Task removeTask = mStack.findTaskWithId(event.taskId);
-        if (removeTask != null) {
-            // In this case, we remove the task, but if the last task is removed, don't dismiss
-            // Recents to home
-            mStack.removeTask(removeTask, AnimationProps.IMMEDIATE, false /* fromDockGesture */,
-                    false /* dismissRecentsIfAllRemoved */);
-        }
-        updateLayoutAlgorithm(false /* boundScroll */);
-        updateToInitialState();
-    }
-
-    public void reloadOnConfigurationChange() {
-        mStableLayoutAlgorithm.reloadOnConfigurationChange(getContext());
-        mLayoutAlgorithm.reloadOnConfigurationChange(getContext());
-    }
-
-    /**
-     * Returns the insert index for the task in the current set of task views. If the given task
-     * is already in the task view list, then this method returns the insert index assuming it
-     * is first removed at the previous index.
-     *
-     * @param task the task we are finding the index for
-     * @param taskIndex the index of the task in the stack
-     */
-    private int findTaskViewInsertIndex(Task task, int taskIndex) {
-        if (taskIndex != -1) {
-            List<TaskView> taskViews = getTaskViews();
-            boolean foundTaskView = false;
-            int taskViewCount = taskViews.size();
-            for (int i = 0; i < taskViewCount; i++) {
-                Task tvTask = taskViews.get(i).getTask();
-                if (tvTask == task) {
-                    foundTaskView = true;
-                } else if (taskIndex < mStack.indexOfTask(tvTask)) {
-                    if (foundTaskView) {
-                        return i - 1;
-                    } else {
-                        return i;
-                    }
-                }
-            }
-        }
-        return -1;
-    }
-
-    private void launchTask(Task task) {
-        // Stop all animations
-        cancelAllTaskViewAnimations();
-
-        float curScroll = mStackScroller.getStackScroll();
-        float targetScroll = mLayoutAlgorithm.getStackScrollForTaskAtInitialOffset(task);
-        float absScrollDiff = Math.abs(targetScroll - curScroll);
-        if (getChildViewForTask(task) == null || absScrollDiff > 0.35f) {
-            int duration = (int) (LAUNCH_NEXT_SCROLL_BASE_DURATION +
-                    absScrollDiff * LAUNCH_NEXT_SCROLL_INCR_DURATION);
-            mStackScroller.animateScroll(targetScroll,
-                    duration, new Runnable() {
-                        @Override
-                        public void run() {
-                            EventBus.getDefault().send(new LaunchTaskEvent(
-                                    getChildViewForTask(task), task, null,
-                                    false /* screenPinningRequested */));
-                        }
-                    });
-        } else {
-            EventBus.getDefault().send(new LaunchTaskEvent(getChildViewForTask(task), task, null,
-                    false /* screenPinningRequested */));
-        }
-    }
-
-    /**
-     * Check whether we should use the grid layout.
-     */
-    public boolean useGridLayout() {
-        return mLayoutAlgorithm.useGridLayout();
-    }
-
-    /**
-     * Reads current system flags related to accessibility and screen pinning.
-     */
-    private void readSystemFlags() {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        mTouchExplorationEnabled = ssp.isTouchExplorationEnabled();
-        mScreenPinningEnabled = ActivityManagerWrapper.getInstance().isScreenPinningEnabled()
-                && !ActivityManagerWrapper.getInstance().isLockToAppActive();
-    }
-
-    private void updateStackActionButtonVisibility() {
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            return;
-        }
-
-        // Always show the button in grid layout.
-        if (useGridLayout() ||
-                (mStackScroller.getStackScroll() < SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
-                        mStack.getTaskCount() > 0)) {
-            EventBus.getDefault().send(new ShowStackActionButtonEvent(false /* translate */));
-        } else {
-            EventBus.getDefault().send(new HideStackActionButtonEvent());
-        }
-    }
-
-    /**
-     * Returns the task to focus given the current launch state.
-     */
-    private int getInitialFocusTaskIndex(RecentsActivityLaunchState launchState, int numTasks,
-            boolean useGridLayout) {
-        if (launchState.launchedFromApp) {
-            if (useGridLayout) {
-                // If coming from another app to the grid layout, focus the front most task
-                return numTasks - 1;
-            }
-
-            // If coming from another app, focus the next task
-            return Math.max(0, numTasks - 2);
-        } else {
-            // If coming from home, focus the front most task
-            return numTasks - 1;
-        }
-    }
-
-    /**
-     * Updates {@param transforms} to be the same size as {@param tasks}.
-     */
-    private void matchTaskListSize(List<Task> tasks, List<TaskViewTransform> transforms) {
-        // We can reuse the task transforms where possible to reduce object allocation
-        int taskTransformCount = transforms.size();
-        int taskCount = tasks.size();
-        if (taskTransformCount < taskCount) {
-            // If there are less transforms than tasks, then add as many transforms as necessary
-            for (int i = taskTransformCount; i < taskCount; i++) {
-                transforms.add(new TaskViewTransform());
-            }
-        } else if (taskTransformCount > taskCount) {
-            // If there are more transforms than tasks, then just subset the transform list
-            transforms.subList(taskCount, taskTransformCount).clear();
-        }
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        String innerPrefix = prefix + "  ";
-        String id = Integer.toHexString(System.identityHashCode(this));
-
-        writer.print(prefix); writer.print(TAG);
-        writer.print(" hasDefRelayout=");
-        writer.print(mDeferredTaskViewLayoutAnimation != null ? "Y" : "N");
-        writer.print(" clipDirty="); writer.print(mTaskViewsClipDirty ? "Y" : "N");
-        writer.print(" awaitingStackReload="); writer.print(mFinishedLayoutAfterStackReload ? "Y" : "N");
-        writer.print(" initialState="); writer.print(mInitialState);
-        writer.print(" inMeasureLayout="); writer.print(mInMeasureLayout ? "Y" : "N");
-        writer.print(" enterAnimCompleted="); writer.print(mEnterAnimationComplete ? "Y" : "N");
-        writer.print(" touchExplorationOn="); writer.print(mTouchExplorationEnabled ? "Y" : "N");
-        writer.print(" screenPinningOn="); writer.print(mScreenPinningEnabled ? "Y" : "N");
-        writer.print(" numIgnoreTasks="); writer.print(mIgnoreTasks.size());
-        writer.print(" numViewPool="); writer.print(mViewPool.getViews().size());
-        writer.print(" stableStackBounds="); writer.print(
-                Utilities.dumpRect(mStableStackBounds));
-        writer.print(" stackBounds="); writer.print(
-                Utilities.dumpRect(mStackBounds));
-        writer.print(" stableWindow="); writer.print(
-                Utilities.dumpRect(mStableWindowRect));
-        writer.print(" window="); writer.print(Utilities.dumpRect(mWindowRect));
-        writer.print(" display="); writer.print(Utilities.dumpRect(mDisplayRect));
-        writer.print(" orientation="); writer.print(mDisplayOrientation);
-        writer.print(" [0x"); writer.print(id); writer.print("]");
-        writer.println();
-
-        if (mFocusedTask != null) {
-            writer.print(innerPrefix);
-            writer.print("Focused task: ");
-            mFocusedTask.dump("", writer);
-        }
-
-        int numTaskViews = mTaskViews.size();
-        for (int i = 0; i < numTaskViews; i++) {
-            mTaskViews.get(i).dump(innerPrefix, writer);
-        }
-
-        mLayoutAlgorithm.dump(innerPrefix, writer);
-        mStackScroller.dump(innerPrefix, writer);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackViewScroller.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackViewScroller.java
deleted file mode 100644
index 42efe59..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackViewScroller.java
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.ObjectAnimator;
-import android.animation.TimeInterpolator;
-import android.animation.ValueAnimator;
-import android.content.Context;
-import android.util.FloatProperty;
-import android.util.Log;
-import android.util.Property;
-import android.view.ViewConfiguration;
-import android.view.ViewDebug;
-import android.widget.OverScroller;
-
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.utilities.AnimationProps;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.recents.views.lowram.TaskStackLowRamLayoutAlgorithm;
-import com.android.systemui.statusbar.FlingAnimationUtils;
-
-import java.io.PrintWriter;
-
-/* The scrolling logic for a TaskStackView */
-public class TaskStackViewScroller {
-
-    private static final String TAG = "TaskStackViewScroller";
-    private static final boolean DEBUG = false;
-
-    public interface TaskStackViewScrollerCallbacks {
-        void onStackScrollChanged(float prevScroll, float curScroll, AnimationProps animation);
-    }
-
-    /**
-     * A Property wrapper around the <code>stackScroll</code> functionality handled by the
-     * {@link #setStackScroll(float)} and
-     * {@link #getStackScroll()} methods.
-     */
-    private static final Property<TaskStackViewScroller, Float> STACK_SCROLL =
-            new FloatProperty<TaskStackViewScroller>("stackScroll") {
-                @Override
-                public void setValue(TaskStackViewScroller object, float value) {
-                    object.setStackScroll(value);
-                }
-
-                @Override
-                public Float get(TaskStackViewScroller object) {
-                    return object.getStackScroll();
-                }
-            };
-
-    Context mContext;
-    TaskStackLayoutAlgorithm mLayoutAlgorithm;
-    TaskStackViewScrollerCallbacks mCb;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    float mStackScrollP;
-    @ViewDebug.ExportedProperty(category="recents")
-    float mLastDeltaP = 0f;
-    float mFlingDownScrollP;
-    int mFlingDownY;
-
-    OverScroller mScroller;
-    ObjectAnimator mScrollAnimator;
-    float mFinalAnimatedScroll;
-
-    final FlingAnimationUtils mFlingAnimationUtils;
-
-    public TaskStackViewScroller(Context context, TaskStackViewScrollerCallbacks cb,
-            TaskStackLayoutAlgorithm layoutAlgorithm) {
-        mContext = context;
-        mCb = cb;
-        mScroller = new OverScroller(context);
-        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            mScroller.setFriction(0.06f);
-        }
-        mLayoutAlgorithm = layoutAlgorithm;
-        mFlingAnimationUtils = new FlingAnimationUtils(context, 0.3f);
-    }
-
-    /** Resets the task scroller. */
-    void reset() {
-        mStackScrollP = 0f;
-        mLastDeltaP = 0f;
-    }
-
-    void resetDeltaScroll() {
-        mLastDeltaP = 0f;
-    }
-
-    /** Gets the current stack scroll */
-    public float getStackScroll() {
-        return mStackScrollP;
-    }
-
-    /**
-     * Sets the current stack scroll immediately.
-     */
-    public void setStackScroll(float s) {
-        setStackScroll(s, AnimationProps.IMMEDIATE);
-    }
-
-    /**
-     * Sets the current stack scroll immediately, and returns the difference between the target
-     * scroll and the actual scroll after accounting for the effect on the focus state.
-     */
-    public float setDeltaStackScroll(float downP, float deltaP) {
-        float targetScroll = downP + deltaP;
-        float newScroll = mLayoutAlgorithm.updateFocusStateOnScroll(downP + mLastDeltaP, targetScroll,
-                mStackScrollP);
-        setStackScroll(newScroll, AnimationProps.IMMEDIATE);
-        mLastDeltaP = deltaP;
-        return newScroll - targetScroll;
-    }
-
-    /**
-     * Sets the current stack scroll, but indicates to the callback the preferred animation to
-     * update to this new scroll.
-     */
-    public void setStackScroll(float newScroll, AnimationProps animation) {
-        float prevScroll = mStackScrollP;
-        mStackScrollP = newScroll;
-        if (mCb != null) {
-            mCb.onStackScrollChanged(prevScroll, mStackScrollP, animation);
-        }
-    }
-
-    /**
-     * Sets the current stack scroll to the initial state when you first enter recents.
-     * @return whether the stack progress changed.
-     */
-    public boolean setStackScrollToInitialState() {
-        float prevScroll = mStackScrollP;
-        setStackScroll(mLayoutAlgorithm.mInitialScrollP);
-        return Float.compare(prevScroll, mStackScrollP) != 0;
-    }
-
-    /**
-     * Starts a fling that is coordinated with the {@link TaskStackViewTouchHandler}.
-     */
-    public void fling(float downScrollP, int downY, int y, int velY, int minY, int maxY,
-            int overscroll) {
-        if (DEBUG) {
-            Log.d(TAG, "fling: " + downScrollP + ", downY: " + downY + ", y: " + y +
-                    ", velY: " + velY + ", minY: " + minY + ", maxY: " + maxY);
-        }
-        mFlingDownScrollP = downScrollP;
-        mFlingDownY = downY;
-        mScroller.fling(0, y, 0, velY, 0, 0, minY, maxY, 0, overscroll);
-    }
-
-    /** Bounds the current scroll if necessary */
-    public boolean boundScroll() {
-        float curScroll = getStackScroll();
-        float newScroll = getBoundedStackScroll(curScroll);
-        if (Float.compare(newScroll, curScroll) != 0) {
-            setStackScroll(newScroll);
-            return true;
-        }
-        return false;
-    }
-
-    /** Returns the bounded stack scroll */
-    float getBoundedStackScroll(float scroll) {
-        return Utilities.clamp(scroll, mLayoutAlgorithm.mMinScrollP, mLayoutAlgorithm.mMaxScrollP);
-    }
-
-    /** Returns the amount that the absolute value of how much the scroll is out of bounds. */
-    float getScrollAmountOutOfBounds(float scroll) {
-        if (scroll < mLayoutAlgorithm.mMinScrollP) {
-            return Math.abs(scroll - mLayoutAlgorithm.mMinScrollP);
-        } else if (scroll > mLayoutAlgorithm.mMaxScrollP) {
-            return Math.abs(scroll - mLayoutAlgorithm.mMaxScrollP);
-        }
-        return 0f;
-    }
-
-    /** Returns whether the specified scroll is out of bounds */
-    boolean isScrollOutOfBounds() {
-        return Float.compare(getScrollAmountOutOfBounds(mStackScrollP), 0f) != 0;
-    }
-
-    /**
-     * Scrolls the closest task and snaps into place. Only used in recents for low ram devices.
-     * @param velocity of scroll
-     */
-    void scrollToClosestTask(int velocity) {
-        float stackScroll = getStackScroll();
-
-        // Skip if not in low ram layout and if the scroll is out of min and max bounds
-        if (!LegacyRecentsImpl.getConfiguration().isLowRamDevice || stackScroll < mLayoutAlgorithm.mMinScrollP
-                || stackScroll > mLayoutAlgorithm.mMaxScrollP) {
-            return;
-        }
-        TaskStackLowRamLayoutAlgorithm algorithm = mLayoutAlgorithm.mTaskStackLowRamLayoutAlgorithm;
-
-        float flingThreshold = ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity();
-        if (Math.abs(velocity) > flingThreshold) {
-            int minY = algorithm.percentageToScroll(mLayoutAlgorithm.mMinScrollP);
-            int maxY = algorithm.percentageToScroll(mLayoutAlgorithm.mMaxScrollP);
-
-            // Calculate the fling and snap to closest task from final y position, computeScroll()
-            // never runs when cancelled with animateScroll() and the overscroll is not calculated
-            // here
-            fling(0 /* downScrollP */, 0 /* downY */, algorithm.percentageToScroll(stackScroll),
-                    -velocity, minY, maxY, 0 /* overscroll */);
-            float pos = algorithm.scrollToPercentage(mScroller.getFinalY());
-
-            float newScrollP = algorithm.getClosestTaskP(pos, mLayoutAlgorithm.mNumStackTasks,
-                    velocity);
-            ValueAnimator animator = ObjectAnimator.ofFloat(stackScroll, newScrollP);
-            mFlingAnimationUtils.apply(animator, algorithm.percentageToScroll(stackScroll),
-                    algorithm.percentageToScroll(newScrollP), velocity);
-            animateScroll(newScrollP, (int) animator.getDuration(), animator.getInterpolator(),
-                    null /* postRunnable */);
-        } else {
-            float newScrollP = algorithm.getClosestTaskP(stackScroll,
-                    mLayoutAlgorithm.mNumStackTasks, velocity);
-            animateScroll(newScrollP, 300, Interpolators.ACCELERATE_DECELERATE,
-                    null /* postRunnable */);
-        }
-    }
-
-    /** Animates the stack scroll into bounds */
-    ObjectAnimator animateBoundScroll() {
-        // TODO: Take duration for snap back
-        float curScroll = getStackScroll();
-        float newScroll = getBoundedStackScroll(curScroll);
-        if (Float.compare(newScroll, curScroll) != 0) {
-            // Start a new scroll animation
-            animateScroll(newScroll, null /* postScrollRunnable */);
-        }
-        return mScrollAnimator;
-    }
-
-    /** Animates the stack scroll */
-    void animateScroll(float newScroll, final Runnable postRunnable) {
-        int duration = mContext.getResources().getInteger(
-                R.integer.recents_animate_task_stack_scroll_duration);
-        animateScroll(newScroll, duration, postRunnable);
-    }
-
-    /** Animates the stack scroll */
-    void animateScroll(float newScroll, int duration, final Runnable postRunnable) {
-        animateScroll(newScroll, duration, Interpolators.LINEAR_OUT_SLOW_IN, postRunnable);
-    }
-
-    /** Animates the stack scroll with time interpolator */
-    void animateScroll(float newScroll, int duration, TimeInterpolator interpolator,
-            final Runnable postRunnable) {
-        ObjectAnimator an = ObjectAnimator.ofFloat(this, STACK_SCROLL, getStackScroll(), newScroll);
-        an.setDuration(duration);
-        an.setInterpolator(interpolator);
-        animateScroll(newScroll, an, postRunnable);
-    }
-
-    /** Animates the stack scroll with animator */
-    private void animateScroll(float newScroll, ObjectAnimator animator,
-            final Runnable postRunnable) {
-        // Finish any current scrolling animations
-        if (mScrollAnimator != null && mScrollAnimator.isRunning()) {
-            setStackScroll(mFinalAnimatedScroll);
-            mScroller.forceFinished(true);
-        }
-        stopScroller();
-        stopBoundScrollAnimation();
-
-        if (Float.compare(mStackScrollP, newScroll) != 0) {
-            mFinalAnimatedScroll = newScroll;
-            mScrollAnimator = animator;
-            mScrollAnimator.addListener(new AnimatorListenerAdapter() {
-                @Override
-                public void onAnimationEnd(Animator animation) {
-                    if (postRunnable != null) {
-                        postRunnable.run();
-                    }
-                    mScrollAnimator.removeAllListeners();
-                }
-            });
-            mScrollAnimator.start();
-        } else {
-            if (postRunnable != null) {
-                postRunnable.run();
-            }
-        }
-    }
-
-    /** Aborts any current stack scrolls */
-    void stopBoundScrollAnimation() {
-        Utilities.cancelAnimationWithoutCallbacks(mScrollAnimator);
-    }
-
-    /**** OverScroller ****/
-
-    /** Called from the view draw, computes the next scroll. */
-    boolean computeScroll() {
-        if (mScroller.computeScrollOffset()) {
-            float deltaP = mLayoutAlgorithm.getDeltaPForY(mFlingDownY, mScroller.getCurrY());
-            mFlingDownScrollP += setDeltaStackScroll(mFlingDownScrollP, deltaP);
-            if (DEBUG) {
-                Log.d(TAG, "computeScroll: " + (mFlingDownScrollP + deltaP));
-            }
-            return true;
-        }
-        return false;
-    }
-
-    /** Returns whether the overscroller is scrolling. */
-    boolean isScrolling() {
-        return !mScroller.isFinished();
-    }
-
-    float getScrollVelocity() {
-        return mScroller.getCurrVelocity();
-    }
-
-    /** Stops the scroller and any current fling. */
-    void stopScroller() {
-        if (!mScroller.isFinished()) {
-            mScroller.abortAnimation();
-        }
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        writer.print(prefix); writer.print(TAG);
-        writer.print(" stackScroll:"); writer.print(mStackScrollP);
-        writer.println();
-    }
-}
\ No newline at end of file
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
deleted file mode 100644
index a7fb4fa..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
+++ /dev/null
@@ -1,706 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.animation.Animator;
-import android.animation.ValueAnimator;
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Path;
-import android.util.ArrayMap;
-import android.util.MutableBoolean;
-import android.view.InputDevice;
-import android.view.MotionEvent;
-import android.view.VelocityTracker;
-import android.view.View;
-import android.view.ViewConfiguration;
-import android.view.ViewDebug;
-import android.view.ViewParent;
-import android.view.animation.Interpolator;
-
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.SwipeHelper;
-import com.android.systemui.plugins.FalsingManager;
-import com.android.systemui.recents.Constants;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.HideRecentsEvent;
-import com.android.systemui.recents.events.ui.StackViewScrolledEvent;
-import com.android.systemui.recents.events.ui.TaskViewDismissedEvent;
-import com.android.systemui.recents.misc.FreePathInterpolator;
-import com.android.systemui.recents.utilities.AnimationProps;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.statusbar.FlingAnimationUtils;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Handles touch events for a TaskStackView.
- */
-class TaskStackViewTouchHandler implements SwipeHelper.Callback {
-
-    private static final int INACTIVE_POINTER_ID = -1;
-    private static final float CHALLENGING_SWIPE_ESCAPE_VELOCITY = 800f; // dp/sec
-    // The min overscroll is the amount of task progress overscroll we want / the max overscroll
-    // curve value below
-    private static final float MAX_OVERSCROLL = 0.7f / 0.3f;
-    private static final Interpolator OVERSCROLL_INTERP;
-    static {
-        Path OVERSCROLL_PATH = new Path();
-        OVERSCROLL_PATH.moveTo(0, 0);
-        OVERSCROLL_PATH.cubicTo(0.2f, 0.175f, 0.25f, 0.3f, 1f, 0.3f);
-        OVERSCROLL_INTERP = new FreePathInterpolator(OVERSCROLL_PATH);
-    }
-
-    Context mContext;
-    TaskStackView mSv;
-    TaskStackViewScroller mScroller;
-    VelocityTracker mVelocityTracker;
-    FlingAnimationUtils mFlingAnimUtils;
-    ValueAnimator mScrollFlingAnimator;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    boolean mIsScrolling;
-    float mDownScrollP;
-    int mDownX, mDownY;
-    int mLastY;
-    int mActivePointerId = INACTIVE_POINTER_ID;
-    int mOverscrollSize;
-    TaskView mActiveTaskView = null;
-
-    int mMinimumVelocity;
-    int mMaximumVelocity;
-    // The scroll touch slop is used to calculate when we start scrolling
-    int mScrollTouchSlop;
-    // Used to calculate when a tap is outside a task view rectangle.
-    final int mWindowTouchSlop;
-
-    private final StackViewScrolledEvent mStackViewScrolledEvent = new StackViewScrolledEvent();
-
-    // The current and final set of task transforms, sized to match the list of tasks in the stack
-    private ArrayList<Task> mCurrentTasks = new ArrayList<>();
-    private ArrayList<TaskViewTransform> mCurrentTaskTransforms = new ArrayList<>();
-    private ArrayList<TaskViewTransform> mFinalTaskTransforms = new ArrayList<>();
-    private ArrayMap<View, Animator> mSwipeHelperAnimations = new ArrayMap<>();
-    private TaskViewTransform mTmpTransform = new TaskViewTransform();
-    private float mTargetStackScroll;
-
-    SwipeHelper mSwipeHelper;
-    boolean mInterceptedBySwipeHelper;
-
-    public TaskStackViewTouchHandler(Context context, TaskStackView sv,
-            TaskStackViewScroller scroller, FalsingManager falsingManager) {
-        Resources res = context.getResources();
-        ViewConfiguration configuration = ViewConfiguration.get(context);
-        mContext = context;
-        mSv = sv;
-        mScroller = scroller;
-        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
-        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
-        mScrollTouchSlop = configuration.getScaledTouchSlop();
-        mWindowTouchSlop = configuration.getScaledWindowTouchSlop();
-        mFlingAnimUtils = new FlingAnimationUtils(context, 0.2f);
-        mOverscrollSize = res.getDimensionPixelSize(R.dimen.recents_fling_overscroll_distance);
-        mSwipeHelper = new SwipeHelper(SwipeHelper.X, this, context, falsingManager) {
-            @Override
-            protected float getSize(View v) {
-                return getScaledDismissSize();
-            }
-
-            @Override
-            protected void prepareDismissAnimation(View v, Animator anim) {
-                mSwipeHelperAnimations.put(v, anim);
-            }
-
-            @Override
-            protected void prepareSnapBackAnimation(View v, Animator anim) {
-                anim.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
-                mSwipeHelperAnimations.put(v, anim);
-            }
-
-            @Override
-            protected float getUnscaledEscapeVelocity() {
-                return CHALLENGING_SWIPE_ESCAPE_VELOCITY;
-            }
-
-            @Override
-            protected long getMaxEscapeAnimDuration() {
-                return 700;
-            }
-        };
-        mSwipeHelper.setDisableHardwareLayers(true);
-    }
-
-    /** Velocity tracker helpers */
-    void initOrResetVelocityTracker() {
-        if (mVelocityTracker == null) {
-            mVelocityTracker = VelocityTracker.obtain();
-        } else {
-            mVelocityTracker.clear();
-        }
-    }
-    void recycleVelocityTracker() {
-        if (mVelocityTracker != null) {
-            mVelocityTracker.recycle();
-            mVelocityTracker = null;
-        }
-    }
-
-    /** Touch preprocessing for handling below */
-    public boolean onInterceptTouchEvent(MotionEvent ev) {
-        // Pass through to swipe helper if we are swiping
-        mInterceptedBySwipeHelper = isSwipingEnabled() && mSwipeHelper.onInterceptTouchEvent(ev);
-        if (mInterceptedBySwipeHelper) {
-            return true;
-        }
-
-        return handleTouchEvent(ev);
-    }
-
-    /** Handles touch events once we have intercepted them */
-    public boolean onTouchEvent(MotionEvent ev) {
-        // Pass through to swipe helper if we are swiping
-        if (mInterceptedBySwipeHelper && mSwipeHelper.onTouchEvent(ev)) {
-            return true;
-        }
-
-        handleTouchEvent(ev);
-        return true;
-    }
-
-    /**
-     * Finishes all scroll-fling and non-dismissing animations currently running.
-     */
-    public void cancelNonDismissTaskAnimations() {
-        Utilities.cancelAnimationWithoutCallbacks(mScrollFlingAnimator);
-        if (!mSwipeHelperAnimations.isEmpty()) {
-            // For the non-dismissing tasks, freeze the position into the task overrides
-            List<TaskView> taskViews = mSv.getTaskViews();
-            for (int i = taskViews.size() - 1; i >= 0; i--) {
-                TaskView tv = taskViews.get(i);
-
-                if (mSv.isIgnoredTask(tv.getTask())) {
-                    continue;
-                }
-
-                tv.cancelTransformAnimation();
-                mSv.getStackAlgorithm().addUnfocusedTaskOverride(tv, mTargetStackScroll);
-            }
-            mSv.getStackAlgorithm().setFocusState(TaskStackLayoutAlgorithm.STATE_UNFOCUSED);
-            // Update the scroll to the final scroll position from onBeginDrag()
-            mSv.getScroller().setStackScroll(mTargetStackScroll, null);
-
-            mSwipeHelperAnimations.clear();
-        }
-        mActiveTaskView = null;
-    }
-
-    private boolean handleTouchEvent(MotionEvent ev) {
-        // Short circuit if we have no children
-        if (mSv.getTaskViews().size() == 0) {
-            return false;
-        }
-
-        final TaskStackLayoutAlgorithm layoutAlgorithm = mSv.mLayoutAlgorithm;
-        int action = ev.getAction();
-        switch (action & MotionEvent.ACTION_MASK) {
-            case MotionEvent.ACTION_DOWN: {
-                // Stop the current scroll if it is still flinging
-                mScroller.stopScroller();
-                mScroller.stopBoundScrollAnimation();
-                mScroller.resetDeltaScroll();
-                cancelNonDismissTaskAnimations();
-                mSv.cancelDeferredTaskViewLayoutAnimation();
-
-                // Save the touch down info
-                mDownX = (int) ev.getX();
-                mDownY = (int) ev.getY();
-                mLastY = mDownY;
-                mDownScrollP = mScroller.getStackScroll();
-                mActivePointerId = ev.getPointerId(0);
-                mActiveTaskView = findViewAtPoint(mDownX, mDownY);
-
-                // Initialize the velocity tracker
-                initOrResetVelocityTracker();
-                mVelocityTracker.addMovement(ev);
-                break;
-            }
-            case MotionEvent.ACTION_POINTER_DOWN: {
-                final int index = ev.getActionIndex();
-                mActivePointerId = ev.getPointerId(index);
-                mDownX = (int) ev.getX(index);
-                mDownY = (int) ev.getY(index);
-                mLastY = mDownY;
-                mDownScrollP = mScroller.getStackScroll();
-                mScroller.resetDeltaScroll();
-                mVelocityTracker.addMovement(ev);
-                break;
-            }
-            case MotionEvent.ACTION_MOVE: {
-                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
-                if (activePointerIndex == -1) {
-                    break;
-                }
-                int y = (int) ev.getY(activePointerIndex);
-                int x = (int) ev.getX(activePointerIndex);
-                if (!mIsScrolling) {
-                    int yDiff = Math.abs(y - mDownY);
-                    int xDiff = Math.abs(x - mDownX);
-                    if (Math.abs(y - mDownY) > mScrollTouchSlop && yDiff > xDiff) {
-                        mIsScrolling = true;
-                        float stackScroll = mScroller.getStackScroll();
-                        List<TaskView> taskViews = mSv.getTaskViews();
-                        for (int i = taskViews.size() - 1; i >= 0; i--) {
-                            layoutAlgorithm.addUnfocusedTaskOverride(taskViews.get(i).getTask(),
-                                    stackScroll);
-                        }
-                        layoutAlgorithm.setFocusState(TaskStackLayoutAlgorithm.STATE_UNFOCUSED);
-
-                        // Disallow parents from intercepting touch events
-                        final ViewParent parent = mSv.getParent();
-                        if (parent != null) {
-                            parent.requestDisallowInterceptTouchEvent(true);
-                        }
-
-                        MetricsLogger.action(mSv.getContext(), MetricsEvent.OVERVIEW_SCROLL);
-                        mLastY = mDownY = y;
-                    }
-                }
-                if (mIsScrolling) {
-                    // If we just move linearly on the screen, then that would map to 1/arclength
-                    // of the curve, so just move the scroll proportional to that
-                    float deltaP = layoutAlgorithm.getDeltaPForY(mDownY, y);
-
-                    // Modulate the overscroll to prevent users from pulling the stack too far
-                    float minScrollP = layoutAlgorithm.mMinScrollP;
-                    float maxScrollP = layoutAlgorithm.mMaxScrollP;
-                    float curScrollP = mDownScrollP + deltaP;
-                    if (curScrollP < minScrollP || curScrollP > maxScrollP) {
-                        float clampedScrollP = Utilities.clamp(curScrollP, minScrollP, maxScrollP);
-                        float overscrollP = (curScrollP - clampedScrollP);
-                        float maxOverscroll = LegacyRecentsImpl.getConfiguration().isLowRamDevice
-                                ? layoutAlgorithm.mTaskStackLowRamLayoutAlgorithm.getMaxOverscroll()
-                                : MAX_OVERSCROLL;
-                        float overscrollX = Math.abs(overscrollP) / maxOverscroll;
-                        float interpX = OVERSCROLL_INTERP.getInterpolation(overscrollX);
-                        curScrollP = clampedScrollP + Math.signum(overscrollP) *
-                                (interpX * maxOverscroll);
-                    }
-                    mDownScrollP += mScroller.setDeltaStackScroll(mDownScrollP,
-                            curScrollP - mDownScrollP);
-                    mStackViewScrolledEvent.updateY(y - mLastY);
-                    EventBus.getDefault().send(mStackViewScrolledEvent);
-                }
-
-                mLastY = y;
-                mVelocityTracker.addMovement(ev);
-                break;
-            }
-            case MotionEvent.ACTION_POINTER_UP: {
-                int pointerIndex = ev.getActionIndex();
-                int pointerId = ev.getPointerId(pointerIndex);
-                if (pointerId == mActivePointerId) {
-                    // Select a new active pointer id and reset the motion state
-                    final int newPointerIndex = (pointerIndex == 0) ? 1 : 0;
-                    mActivePointerId = ev.getPointerId(newPointerIndex);
-                    mDownX = (int) ev.getX(pointerIndex);
-                    mDownY = (int) ev.getY(pointerIndex);
-                    mLastY = mDownY;
-                    mDownScrollP = mScroller.getStackScroll();
-                }
-                mVelocityTracker.addMovement(ev);
-                break;
-            }
-            case MotionEvent.ACTION_UP: {
-                mVelocityTracker.addMovement(ev);
-                mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
-                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
-                int y = (int) ev.getY(activePointerIndex);
-                int velocity = (int) mVelocityTracker.getYVelocity(mActivePointerId);
-                if (mIsScrolling) {
-                    if (mScroller.isScrollOutOfBounds()) {
-                        mScroller.animateBoundScroll();
-                    } else if (Math.abs(velocity) > mMinimumVelocity &&
-                            !LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                        float minY = mDownY + layoutAlgorithm.getYForDeltaP(mDownScrollP,
-                                layoutAlgorithm.mMaxScrollP);
-                        float maxY = mDownY + layoutAlgorithm.getYForDeltaP(mDownScrollP,
-                                layoutAlgorithm.mMinScrollP);
-                        mScroller.fling(mDownScrollP, mDownY, y, velocity, (int) minY, (int) maxY,
-                                mOverscrollSize);
-                        mSv.invalidate();
-                    }
-
-                    // Reset the focused task after the user has scrolled, but we have no scrolling
-                    // in grid layout and therefore we don't want to reset the focus there.
-                    if (!mSv.mTouchExplorationEnabled && !mSv.useGridLayout()) {
-                        if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                            mScroller.scrollToClosestTask(velocity);
-                        } else {
-                            mSv.resetFocusedTask(mSv.getFocusedTask());
-                        }
-                    }
-                } else if (mActiveTaskView == null) {
-                    // This tap didn't start on a task.
-                    maybeHideRecentsFromBackgroundTap((int) ev.getX(), (int) ev.getY());
-                }
-
-                mActivePointerId = INACTIVE_POINTER_ID;
-                mIsScrolling = false;
-                recycleVelocityTracker();
-                break;
-            }
-            case MotionEvent.ACTION_CANCEL: {
-                mActivePointerId = INACTIVE_POINTER_ID;
-                mIsScrolling = false;
-                recycleVelocityTracker();
-                break;
-            }
-        }
-        return mIsScrolling;
-    }
-
-    /** Hides recents if the up event at (x, y) is a tap on the background area. */
-    void maybeHideRecentsFromBackgroundTap(int x, int y) {
-        // Ignore the up event if it's too far from its start position. The user might have been
-        // trying to scroll or swipe.
-        int dx = Math.abs(mDownX - x);
-        int dy = Math.abs(mDownY - y);
-        if (dx > mScrollTouchSlop || dy > mScrollTouchSlop) {
-            return;
-        }
-
-        // Shift the tap position toward the center of the task stack and check to see if it would
-        // have hit a view. The user might have tried to tap on a task and missed slightly.
-        int shiftedX = x;
-        if (x > (mSv.getRight() - mSv.getLeft()) / 2) {
-            shiftedX -= mWindowTouchSlop;
-        } else {
-            shiftedX += mWindowTouchSlop;
-        }
-        if (findViewAtPoint(shiftedX, y) != null) {
-            return;
-        }
-
-        // Disallow tapping above and below the stack to dismiss recents
-        if (x > mSv.mLayoutAlgorithm.mStackRect.left && x < mSv.mLayoutAlgorithm.mStackRect.right) {
-            return;
-        }
-
-        // The user intentionally tapped on the background, which is like a tap on the "desktop".
-        // Hide recents and transition to the launcher.
-        EventBus.getDefault().send(new HideRecentsEvent(false, true));
-    }
-
-    /** Handles generic motion events */
-    public boolean onGenericMotionEvent(MotionEvent ev) {
-        if ((ev.getSource() & InputDevice.SOURCE_CLASS_POINTER) ==
-                InputDevice.SOURCE_CLASS_POINTER) {
-            int action = ev.getAction();
-            switch (action & MotionEvent.ACTION_MASK) {
-                case MotionEvent.ACTION_SCROLL:
-                    // Find the front most task and scroll the next task to the front
-                    float vScroll = ev.getAxisValue(MotionEvent.AXIS_VSCROLL);
-                    if (vScroll > 0) {
-                        mSv.setRelativeFocusedTask(true, true /* stackTasksOnly */,
-                                false /* animated */);
-                    } else {
-                        mSv.setRelativeFocusedTask(false, true /* stackTasksOnly */,
-                                false /* animated */);
-                    }
-                    return true;
-            }
-        }
-        return false;
-    }
-
-    /**** SwipeHelper Implementation ****/
-
-    @Override
-    public View getChildAtPosition(MotionEvent ev) {
-        TaskView tv = findViewAtPoint((int) ev.getX(), (int) ev.getY());
-        if (tv != null && canChildBeDismissed(tv)) {
-            return tv;
-        }
-        return null;
-    }
-
-    @Override
-    public boolean canChildBeDismissed(View v) {
-        // Disallow dismissing an already dismissed task
-        TaskView tv = (TaskView) v;
-        Task task = tv.getTask();
-        return !mSwipeHelperAnimations.containsKey(v) &&
-                (mSv.getStack().indexOfTask(task) != -1);
-    }
-
-    /**
-     * Starts a manual drag that goes through the same swipe helper path.
-     */
-    public void onBeginManualDrag(TaskView v) {
-        mActiveTaskView = v;
-        mSwipeHelperAnimations.put(v, null);
-        onBeginDrag(v);
-    }
-
-    @Override
-    public void onBeginDrag(View v) {
-        TaskView tv = (TaskView) v;
-
-        // Disable clipping with the stack while we are swiping
-        tv.setClipViewInStack(false);
-        // Disallow touch events from this task view
-        tv.setTouchEnabled(false);
-        // Disallow parents from intercepting touch events
-        final ViewParent parent = mSv.getParent();
-        if (parent != null) {
-            parent.requestDisallowInterceptTouchEvent(true);
-        }
-
-        // Add this task to the set of tasks we are deleting
-        mSv.addIgnoreTask(tv.getTask());
-
-        // Determine if we are animating the other tasks while dismissing this task
-        mCurrentTasks = new ArrayList<Task>(mSv.getStack().getTasks());
-        MutableBoolean isFrontMostTask = new MutableBoolean(false);
-        Task anchorTask = mSv.findAnchorTask(mCurrentTasks, isFrontMostTask);
-        TaskStackLayoutAlgorithm layoutAlgorithm = mSv.getStackAlgorithm();
-        TaskStackViewScroller stackScroller = mSv.getScroller();
-        if (anchorTask != null) {
-            // Get the current set of task transforms
-            mSv.getCurrentTaskTransforms(mCurrentTasks, mCurrentTaskTransforms);
-
-            // Get the stack scroll of the task to anchor to (since we are removing something, the
-            // front most task will be our anchor task)
-            float prevAnchorTaskScroll = 0;
-            boolean pullStackForward = mCurrentTasks.size() > 0;
-            if (pullStackForward) {
-                if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                    float index = layoutAlgorithm.getStackScrollForTask(anchorTask);
-                    prevAnchorTaskScroll = mSv.getStackAlgorithm().mTaskStackLowRamLayoutAlgorithm
-                            .getScrollPForTask((int) index);
-                } else {
-                    prevAnchorTaskScroll = layoutAlgorithm.getStackScrollForTask(anchorTask);
-                }
-            }
-
-            // Calculate where the views would be without the deleting tasks
-            mSv.updateLayoutAlgorithm(false /* boundScroll */);
-
-            float newStackScroll = stackScroller.getStackScroll();
-            if (isFrontMostTask.value) {
-                // Bound the stack scroll to pull tasks forward if necessary
-                newStackScroll = stackScroller.getBoundedStackScroll(newStackScroll);
-            } else if (pullStackForward) {
-                // Otherwise, offset the scroll by the movement of the anchor task
-                float anchorTaskScroll =
-                        layoutAlgorithm.getStackScrollForTaskIgnoreOverrides(anchorTask);
-                if (LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                    float index = layoutAlgorithm.getStackScrollForTask(anchorTask);
-                    anchorTaskScroll = mSv.getStackAlgorithm().mTaskStackLowRamLayoutAlgorithm
-                            .getScrollPForTask((int) index);
-                }
-                float stackScrollOffset = (anchorTaskScroll - prevAnchorTaskScroll);
-                if (layoutAlgorithm.getFocusState() != TaskStackLayoutAlgorithm.STATE_FOCUSED
-                        && !LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-                    // If we are focused, we don't want the front task to move, but otherwise, we
-                    // allow the back task to move up, and the front task to move back
-                    stackScrollOffset *= 0.75f;
-                }
-                newStackScroll = stackScroller.getBoundedStackScroll(stackScroller.getStackScroll()
-                        + stackScrollOffset);
-            }
-
-            // Pick up the newly visible views, not including the deleting tasks
-            mSv.bindVisibleTaskViews(newStackScroll, true /* ignoreTaskOverrides */);
-
-            // Get the final set of task transforms (with task removed)
-            mSv.getLayoutTaskTransforms(newStackScroll, TaskStackLayoutAlgorithm.STATE_UNFOCUSED,
-                    mCurrentTasks, true /* ignoreTaskOverrides */, mFinalTaskTransforms);
-
-            // Set the target to scroll towards upon dismissal
-            mTargetStackScroll = newStackScroll;
-
-            /*
-             * Post condition: All views that will be visible as a part of the gesture are retrieved
-             *                 and at their initial positions.  The stack is still at the current
-             *                 scroll, but the layout is updated without the task currently being
-             *                 dismissed.  The final layout is in the unfocused stack state, which
-             *                 will be applied when the current task is dismissed.
-             */
-        }
-    }
-
-    @Override
-    public boolean updateSwipeProgress(View v, boolean dismissable, float swipeProgress) {
-        // Only update the swipe progress for the surrounding tasks if the dismiss animation was not
-        // preempted from a call to cancelNonDismissTaskAnimations
-        if ((mActiveTaskView == v || mSwipeHelperAnimations.containsKey(v)) &&
-                !LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            updateTaskViewTransforms(
-                    Interpolators.FAST_OUT_SLOW_IN.getInterpolation(swipeProgress));
-        }
-        return true;
-    }
-
-    /**
-     * Called after the {@link TaskView} is finished animating away.
-     */
-    @Override
-    public void onChildDismissed(View v) {
-        TaskView tv = (TaskView) v;
-
-        // Re-enable clipping with the stack (we will reuse this view)
-        tv.setClipViewInStack(true);
-        // Re-enable touch events from this task view
-        tv.setTouchEnabled(true);
-        // Update the scroll to the final scroll position before laying out the tasks during dismiss
-        if (mSwipeHelperAnimations.containsKey(v)) {
-            mSv.getScroller().setStackScroll(mTargetStackScroll, null);
-        }
-        // Remove the task view from the stack, ignoring the animation if we've started dragging
-        // again
-        EventBus.getDefault().send(new TaskViewDismissedEvent(tv.getTask(), tv,
-                mSwipeHelperAnimations.containsKey(v)
-                    ? new AnimationProps(TaskStackView.DEFAULT_SYNC_STACK_DURATION,
-                        Interpolators.FAST_OUT_SLOW_IN)
-                    : null));
-        // Only update the final scroll and layout state (set in onBeginDrag()) if the dismiss
-        // animation was not preempted from a call to cancelNonDismissTaskAnimations
-        if (mSwipeHelperAnimations.containsKey(v)) {
-            // Update the focus state to the final focus state
-            mSv.getStackAlgorithm().setFocusState(TaskStackLayoutAlgorithm.STATE_UNFOCUSED);
-            mSv.getStackAlgorithm().clearUnfocusedTaskOverrides();
-            // Stop tracking this deletion animation
-            mSwipeHelperAnimations.remove(v);
-        }
-        // Keep track of deletions by keyboard
-        MetricsLogger.histogram(tv.getContext(), "overview_task_dismissed_source",
-                Constants.Metrics.DismissSourceSwipeGesture);
-    }
-
-    /**
-     * Called after the {@link TaskView} is finished animating back into the list.
-     * onChildDismissed() calls.
-     */
-    @Override
-    public void onChildSnappedBack(View v, float targetLeft) {
-        TaskView tv = (TaskView) v;
-
-        // Re-enable clipping with the stack
-        tv.setClipViewInStack(true);
-        // Re-enable touch events from this task view
-        tv.setTouchEnabled(true);
-
-        // Stop tracking this deleting task, and update the layout to include this task again.  The
-        // stack scroll does not need to be reset, since the scroll has not actually changed in
-        // onBeginDrag().
-        mSv.removeIgnoreTask(tv.getTask());
-        mSv.updateLayoutAlgorithm(false /* boundScroll */);
-        mSv.relayoutTaskViews(AnimationProps.IMMEDIATE);
-        mSwipeHelperAnimations.remove(v);
-    }
-
-    @Override
-    public void onDragCancelled(View v) {
-        // Do nothing
-    }
-
-    @Override
-    public boolean isAntiFalsingNeeded() {
-        return false;
-    }
-
-    @Override
-    public float getFalsingThresholdFactor() {
-        return 0;
-    }
-
-    /**
-     * Interpolates the non-deleting tasks to their final transforms from their current transforms.
-     */
-    private void updateTaskViewTransforms(float dismissFraction) {
-        List<TaskView> taskViews = mSv.getTaskViews();
-        int taskViewCount = taskViews.size();
-        for (int i = 0; i < taskViewCount; i++) {
-            TaskView tv = taskViews.get(i);
-            Task task = tv.getTask();
-
-            if (mSv.isIgnoredTask(task)) {
-                continue;
-            }
-
-            int taskIndex = mCurrentTasks.indexOf(task);
-            if (taskIndex == -1) {
-                // If a task was added to the stack view after the start of the dismiss gesture,
-                // just ignore it
-                continue;
-            }
-
-            TaskViewTransform fromTransform = mCurrentTaskTransforms.get(taskIndex);
-            TaskViewTransform toTransform = mFinalTaskTransforms.get(taskIndex);
-
-            mTmpTransform.copyFrom(fromTransform);
-            // We only really need to interpolate the bounds, progress and translation
-            mTmpTransform.rect.set(Utilities.RECTF_EVALUATOR.evaluate(dismissFraction,
-                    fromTransform.rect, toTransform.rect));
-            mTmpTransform.dimAlpha = fromTransform.dimAlpha + (toTransform.dimAlpha -
-                    fromTransform.dimAlpha) * dismissFraction;
-            mTmpTransform.viewOutlineAlpha = fromTransform.viewOutlineAlpha +
-                    (toTransform.viewOutlineAlpha - fromTransform.viewOutlineAlpha) *
-                            dismissFraction;
-            mTmpTransform.translationZ = fromTransform.translationZ +
-                    (toTransform.translationZ - fromTransform.translationZ) * dismissFraction;
-
-            mSv.updateTaskViewToTransform(tv, mTmpTransform, AnimationProps.IMMEDIATE);
-        }
-    }
-
-    /** Returns the view at the specified coordinates */
-    private TaskView findViewAtPoint(int x, int y) {
-        List<Task> tasks = mSv.getStack().getTasks();
-        int taskCount = tasks.size();
-        for (int i = taskCount - 1; i >= 0; i--) {
-            TaskView tv = mSv.getChildViewForTask(tasks.get(i));
-            if (tv != null && tv.getVisibility() == View.VISIBLE) {
-                if (mSv.isTouchPointInView(x, y, tv)) {
-                    return tv;
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Returns the scaled size used to calculate the dismiss fraction.
-     */
-    public float getScaledDismissSize() {
-        return 1.5f * Math.max(mSv.getWidth(), mSv.getHeight());
-    }
-
-    /**
-     * Returns whether swiping is enabled.
-     */
-    private boolean isSwipingEnabled() {
-        return !mSv.useGridLayout();
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskView.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskView.java
deleted file mode 100644
index ab0bf95..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskView.java
+++ /dev/null
@@ -1,737 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
-import android.animation.ValueAnimator;
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Outline;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.util.AttributeSet;
-import android.util.FloatProperty;
-import android.util.Property;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.ViewDebug;
-import android.view.ViewOutlineProvider;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsActivity;
-import com.android.systemui.recents.RecentsConfiguration;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.LaunchTaskEvent;
-import com.android.systemui.recents.events.ui.DismissTaskViewEvent;
-import com.android.systemui.recents.events.ui.TaskViewDismissedEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndCancelledEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
-import com.android.systemui.recents.misc.ReferenceCountedTrigger;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.recents.utilities.AnimationProps;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-
-/**
- * A {@link TaskView} represents a fixed view of a task. Because the TaskView's layout is directed
- * solely by the {@link TaskStackView}, we make it a fixed size layout which allows relayouts down
- * the view hierarchy, but not upwards from any of its children (the TaskView will relayout itself
- * with the previous bounds if any child requests layout).
- */
-public class TaskView extends FixedSizeFrameLayout implements Task.TaskCallbacks,
-        TaskStackAnimationHelper.Callbacks, View.OnClickListener, View.OnLongClickListener {
-
-    /** The TaskView callbacks */
-    interface TaskViewCallbacks {
-        void onTaskViewClipStateChanged(TaskView tv);
-    }
-
-    /**
-     * The dim overlay is generally calculated from the task progress, but occasionally (like when
-     * launching) needs to be animated independently of the task progress.  This call is only used
-     * when animating the task into Recents, when the header dim is already applied
-     */
-    public static final Property<TaskView, Float> DIM_ALPHA_WITHOUT_HEADER =
-            new FloatProperty<TaskView>("dimAlphaWithoutHeader") {
-                @Override
-                public void setValue(TaskView tv, float dimAlpha) {
-                    tv.setDimAlphaWithoutHeader(dimAlpha);
-                }
-
-                @Override
-                public Float get(TaskView tv) {
-                    return tv.getDimAlpha();
-                }
-            };
-
-    /**
-     * The dim overlay is generally calculated from the task progress, but occasionally (like when
-     * launching) needs to be animated independently of the task progress.
-     */
-    public static final Property<TaskView, Float> DIM_ALPHA =
-            new FloatProperty<TaskView>("dimAlpha") {
-                @Override
-                public void setValue(TaskView tv, float dimAlpha) {
-                    tv.setDimAlpha(dimAlpha);
-                }
-
-                @Override
-                public Float get(TaskView tv) {
-                    return tv.getDimAlpha();
-                }
-            };
-
-    /**
-     * The dim overlay is generally calculated from the task progress, but occasionally (like when
-     * launching) needs to be animated independently of the task progress.
-     */
-    public static final Property<TaskView, Float> VIEW_OUTLINE_ALPHA =
-            new FloatProperty<TaskView>("viewOutlineAlpha") {
-                @Override
-                public void setValue(TaskView tv, float alpha) {
-                    tv.getViewBounds().setAlpha(alpha);
-                }
-
-                @Override
-                public Float get(TaskView tv) {
-                    return tv.getViewBounds().getAlpha();
-                }
-            };
-
-    @ViewDebug.ExportedProperty(category="recents")
-    private float mDimAlpha;
-    private float mActionButtonTranslationZ;
-
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="task_")
-    private Task mTask;
-    private boolean mTaskBound;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mClipViewInStack = true;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mTouchExplorationEnabled;
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mIsDisabledInSafeMode;
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="view_bounds_")
-    private AnimateableViewBounds mViewBounds;
-
-    private AnimatorSet mTransformAnimation;
-    private ObjectAnimator mDimAnimator;
-    private ObjectAnimator mOutlineAnimator;
-    private final TaskViewTransform mTargetAnimationTransform = new TaskViewTransform();
-    private ArrayList<Animator> mTmpAnimators = new ArrayList<>();
-
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="thumbnail_")
-    protected TaskViewThumbnail mThumbnailView;
-    @ViewDebug.ExportedProperty(deepExport=true, prefix="header_")
-    protected TaskViewHeader mHeaderView;
-    private View mActionButtonView;
-    private View mIncompatibleAppToastView;
-    private TaskViewCallbacks mCb;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    private Point mDownTouchPos = new Point();
-
-    private Toast mDisabledAppToast;
-
-    public TaskView(Context context) {
-        this(context, null);
-    }
-
-    public TaskView(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public TaskView(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public TaskView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        Resources res = context.getResources();
-        mViewBounds = createOutlineProvider();
-        if (config.fakeShadows) {
-            setBackground(new FakeShadowDrawable(res, config));
-        }
-        setOutlineProvider(mViewBounds);
-        setOnLongClickListener(this);
-        setAccessibilityDelegate(new TaskViewAccessibilityDelegate(this));
-    }
-
-    /** Set callback */
-    void setCallbacks(TaskViewCallbacks cb) {
-        mCb = cb;
-    }
-
-    /**
-     * Called from RecentsActivity when it is relaunched.
-     */
-    void onReload(boolean isResumingFromVisible) {
-        resetNoUserInteractionState();
-        if (!isResumingFromVisible) {
-            resetViewProperties();
-        }
-    }
-
-    /** Gets the task */
-    public Task getTask() {
-        return mTask;
-    }
-
-    /* Create an outline provider to clip and outline the view */
-    protected AnimateableViewBounds createOutlineProvider() {
-        return new AnimateableViewBounds(this, mContext.getResources().getDimensionPixelSize(
-            R.dimen.recents_task_view_shadow_rounded_corners_radius));
-    }
-
-    /** Returns the view bounds. */
-    AnimateableViewBounds getViewBounds() {
-        return mViewBounds;
-    }
-
-    @Override
-    protected void onFinishInflate() {
-        // Bind the views
-        mHeaderView = findViewById(R.id.task_view_bar);
-        mThumbnailView = findViewById(R.id.task_view_thumbnail);
-        mThumbnailView.updateClipToTaskBar(mHeaderView);
-        mActionButtonView = findViewById(R.id.lock_to_app_fab);
-        mActionButtonView.setOutlineProvider(new ViewOutlineProvider() {
-            @Override
-            public void getOutline(View view, Outline outline) {
-                // Set the outline to match the FAB background
-                outline.setOval(0, 0, mActionButtonView.getWidth(), mActionButtonView.getHeight());
-                outline.setAlpha(0.35f);
-            }
-        });
-        mActionButtonView.setOnClickListener(this);
-        mActionButtonTranslationZ = mActionButtonView.getTranslationZ();
-    }
-
-    /**
-     * Update the task view when the configuration changes.
-     */
-    protected void onConfigurationChanged() {
-        mHeaderView.onConfigurationChanged();
-    }
-
-    @Override
-    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
-        super.onSizeChanged(w, h, oldw, oldh);
-        if (w > 0 && h > 0) {
-            mHeaderView.onTaskViewSizeChanged(w, h);
-            mThumbnailView.onTaskViewSizeChanged(w, h);
-
-            mActionButtonView.setTranslationX(w - getMeasuredWidth());
-            mActionButtonView.setTranslationY(h - getMeasuredHeight());
-        }
-    }
-
-    @Override
-    public boolean hasOverlappingRendering() {
-        return false;
-    }
-
-    @Override
-    public boolean onInterceptTouchEvent(MotionEvent ev) {
-        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
-            mDownTouchPos.set((int) (ev.getX() * getScaleX()), (int) (ev.getY() * getScaleY()));
-        }
-        return super.onInterceptTouchEvent(ev);
-    }
-
-    @Override
-    protected void measureContents(int width, int height) {
-        int widthWithoutPadding = width - mPaddingLeft - mPaddingRight;
-        int heightWithoutPadding = height - mPaddingTop - mPaddingBottom;
-        int widthSpec = MeasureSpec.makeMeasureSpec(widthWithoutPadding, MeasureSpec.EXACTLY);
-        int heightSpec = MeasureSpec.makeMeasureSpec(heightWithoutPadding, MeasureSpec.EXACTLY);
-
-        // Measure the content
-        measureChildren(widthSpec, heightSpec);
-
-        setMeasuredDimension(width, height);
-    }
-
-    void updateViewPropertiesToTaskTransform(TaskViewTransform toTransform,
-            AnimationProps toAnimation, ValueAnimator.AnimatorUpdateListener updateCallback) {
-        RecentsConfiguration config = LegacyRecentsImpl.getConfiguration();
-        cancelTransformAnimation();
-
-        // Compose the animations for the transform
-        mTmpAnimators.clear();
-        toTransform.applyToTaskView(this, mTmpAnimators, toAnimation, !config.fakeShadows);
-        if (toAnimation.isImmediate()) {
-            if (Float.compare(getDimAlpha(), toTransform.dimAlpha) != 0) {
-                setDimAlpha(toTransform.dimAlpha);
-            }
-            if (Float.compare(mViewBounds.getAlpha(), toTransform.viewOutlineAlpha) != 0) {
-                mViewBounds.setAlpha(toTransform.viewOutlineAlpha);
-            }
-            // Manually call back to the animator listener and update callback
-            if (toAnimation.getListener() != null) {
-                toAnimation.getListener().onAnimationEnd(null);
-            }
-            if (updateCallback != null) {
-                updateCallback.onAnimationUpdate(null);
-            }
-        } else {
-            // Both the progress and the update are a function of the bounds movement of the task
-            if (Float.compare(getDimAlpha(), toTransform.dimAlpha) != 0) {
-                mDimAnimator = ObjectAnimator.ofFloat(this, DIM_ALPHA, getDimAlpha(),
-                        toTransform.dimAlpha);
-                mTmpAnimators.add(toAnimation.apply(AnimationProps.BOUNDS, mDimAnimator));
-            }
-            if (Float.compare(mViewBounds.getAlpha(), toTransform.viewOutlineAlpha) != 0) {
-                mOutlineAnimator = ObjectAnimator.ofFloat(this, VIEW_OUTLINE_ALPHA,
-                        mViewBounds.getAlpha(), toTransform.viewOutlineAlpha);
-                mTmpAnimators.add(toAnimation.apply(AnimationProps.BOUNDS, mOutlineAnimator));
-            }
-            if (updateCallback != null) {
-                ValueAnimator updateCallbackAnim = ValueAnimator.ofInt(0, 1);
-                updateCallbackAnim.addUpdateListener(updateCallback);
-                mTmpAnimators.add(toAnimation.apply(AnimationProps.BOUNDS, updateCallbackAnim));
-            }
-
-            // Create the animator
-            mTransformAnimation = toAnimation.createAnimator(mTmpAnimators);
-            mTransformAnimation.start();
-            mTargetAnimationTransform.copyFrom(toTransform);
-        }
-    }
-
-    /** Resets this view's properties */
-    void resetViewProperties() {
-        cancelTransformAnimation();
-        setDimAlpha(0);
-        setVisibility(View.VISIBLE);
-        getViewBounds().reset();
-        getHeaderView().reset();
-        TaskViewTransform.reset(this);
-
-        mActionButtonView.setScaleX(1f);
-        mActionButtonView.setScaleY(1f);
-        mActionButtonView.setAlpha(0f);
-        mActionButtonView.setTranslationX(0f);
-        mActionButtonView.setTranslationY(0f);
-        mActionButtonView.setTranslationZ(mActionButtonTranslationZ);
-        if (mIncompatibleAppToastView != null) {
-            mIncompatibleAppToastView.setVisibility(View.INVISIBLE);
-        }
-    }
-
-    /**
-     * @return whether we are animating towards {@param transform}
-     */
-    boolean isAnimatingTo(TaskViewTransform transform) {
-        return mTransformAnimation != null && mTransformAnimation.isStarted()
-                && mTargetAnimationTransform.isSame(transform);
-    }
-
-    /**
-     * Cancels any current transform animations.
-     */
-    public void cancelTransformAnimation() {
-        cancelDimAnimationIfExists();
-        Utilities.cancelAnimationWithoutCallbacks(mTransformAnimation);
-        Utilities.cancelAnimationWithoutCallbacks(mOutlineAnimator);
-    }
-
-    private void cancelDimAnimationIfExists() {
-        if (mDimAnimator != null) {
-            mDimAnimator.cancel();
-        }
-    }
-
-    /** Enables/disables handling touch on this task view. */
-    public void setTouchEnabled(boolean enabled) {
-        setOnClickListener(enabled ? this : null);
-    }
-
-    /** Animates this task view if the user does not interact with the stack after a certain time. */
-    public void startNoUserInteractionAnimation() {
-        mHeaderView.startNoUserInteractionAnimation();
-    }
-
-    /** Mark this task view that the user does has not interacted with the stack after a certain time. */
-    void setNoUserInteractionState() {
-        mHeaderView.setNoUserInteractionState();
-    }
-
-    /** Resets the state tracking that the user has not interacted with the stack after a certain time. */
-    void resetNoUserInteractionState() {
-        mHeaderView.resetNoUserInteractionState();
-    }
-
-    /** Dismisses this task. */
-    void dismissTask() {
-        // Animate out the view and call the callback
-        final TaskView tv = this;
-        DismissTaskViewEvent dismissEvent = new DismissTaskViewEvent(tv);
-        dismissEvent.addPostAnimationCallback(new Runnable() {
-            @Override
-            public void run() {
-                EventBus.getDefault().send(new TaskViewDismissedEvent(mTask, tv,
-                        new AnimationProps(TaskStackView.DEFAULT_SYNC_STACK_DURATION,
-                                Interpolators.FAST_OUT_SLOW_IN)));
-            }
-        });
-        EventBus.getDefault().send(dismissEvent);
-    }
-
-    /**
-     * Returns whether this view should be clipped, or any views below should clip against this
-     * view.
-     */
-    boolean shouldClipViewInStack() {
-        if (getVisibility() != View.VISIBLE || LegacyRecentsImpl.getConfiguration().isLowRamDevice) {
-            return false;
-        }
-        return mClipViewInStack;
-    }
-
-    /** Sets whether this view should be clipped, or clipped against. */
-    void setClipViewInStack(boolean clip) {
-        if (clip != mClipViewInStack) {
-            mClipViewInStack = clip;
-            if (mCb != null) {
-                mCb.onTaskViewClipStateChanged(this);
-            }
-        }
-    }
-
-    public TaskViewHeader getHeaderView() {
-        return mHeaderView;
-    }
-
-    /**
-     * Sets the current dim.
-     */
-    public void setDimAlpha(float dimAlpha) {
-        mDimAlpha = dimAlpha;
-        mThumbnailView.setDimAlpha(dimAlpha);
-        mHeaderView.setDimAlpha(dimAlpha);
-    }
-
-    /**
-     * Sets the current dim without updating the header's dim.
-     */
-    public void setDimAlphaWithoutHeader(float dimAlpha) {
-        mDimAlpha = dimAlpha;
-        mThumbnailView.setDimAlpha(dimAlpha);
-    }
-
-    /**
-     * Returns the current dim.
-     */
-    public float getDimAlpha() {
-        return mDimAlpha;
-    }
-
-    /**
-     * Explicitly sets the focused state of this task.
-     */
-    public void setFocusedState(boolean isFocused, boolean requestViewFocus) {
-        if (isFocused) {
-            if (requestViewFocus && !isFocused()) {
-                requestFocus();
-            }
-        } else {
-            if (isAccessibilityFocused() && mTouchExplorationEnabled) {
-                clearAccessibilityFocus();
-            }
-        }
-    }
-
-    /**
-     * Shows the action button.
-     * @param fadeIn whether or not to animate the action button in.
-     * @param fadeInDuration the duration of the action button animation, only used if
-     *                       {@param fadeIn} is true.
-     */
-    public void showActionButton(boolean fadeIn, int fadeInDuration) {
-        mActionButtonView.setVisibility(View.VISIBLE);
-
-        if (fadeIn && mActionButtonView.getAlpha() < 1f) {
-            mActionButtonView.animate()
-                    .alpha(1f)
-                    .scaleX(1f)
-                    .scaleY(1f)
-                    .setDuration(fadeInDuration)
-                    .setInterpolator(Interpolators.ALPHA_IN)
-                    .start();
-        } else {
-            mActionButtonView.setScaleX(1f);
-            mActionButtonView.setScaleY(1f);
-            mActionButtonView.setAlpha(1f);
-            mActionButtonView.setTranslationZ(mActionButtonTranslationZ);
-        }
-    }
-
-    /**
-     * Immediately hides the action button.
-     *
-     * @param fadeOut whether or not to animate the action button out.
-     */
-    public void hideActionButton(boolean fadeOut, int fadeOutDuration, boolean scaleDown,
-            final Animator.AnimatorListener animListener) {
-        if (fadeOut && mActionButtonView.getAlpha() > 0f) {
-            if (scaleDown) {
-                float toScale = 0.9f;
-                mActionButtonView.animate()
-                        .scaleX(toScale)
-                        .scaleY(toScale);
-            }
-            mActionButtonView.animate()
-                    .alpha(0f)
-                    .setDuration(fadeOutDuration)
-                    .setInterpolator(Interpolators.ALPHA_OUT)
-                    .withEndAction(new Runnable() {
-                        @Override
-                        public void run() {
-                            if (animListener != null) {
-                                animListener.onAnimationEnd(null);
-                            }
-                            mActionButtonView.setVisibility(View.INVISIBLE);
-                        }
-                    })
-                    .start();
-        } else {
-            mActionButtonView.setAlpha(0f);
-            mActionButtonView.setVisibility(View.INVISIBLE);
-            if (animListener != null) {
-                animListener.onAnimationEnd(null);
-            }
-        }
-    }
-
-    /**** TaskStackAnimationHelper.Callbacks Implementation ****/
-
-    @Override
-    public void onPrepareLaunchTargetForEnterAnimation() {
-        // These values will be animated in when onStartLaunchTargetEnterAnimation() is called
-        setDimAlphaWithoutHeader(0);
-        mActionButtonView.setAlpha(0f);
-        if (mIncompatibleAppToastView != null &&
-                mIncompatibleAppToastView.getVisibility() == View.VISIBLE) {
-            mIncompatibleAppToastView.setAlpha(0f);
-        }
-    }
-
-    @Override
-    public void onStartLaunchTargetEnterAnimation(TaskViewTransform transform, int duration,
-            boolean screenPinningEnabled, ReferenceCountedTrigger postAnimationTrigger) {
-        cancelDimAnimationIfExists();
-
-        // Dim the view after the app window transitions down into recents
-        postAnimationTrigger.increment();
-        AnimationProps animation = new AnimationProps(duration, Interpolators.ALPHA_OUT);
-        mDimAnimator = animation.apply(AnimationProps.DIM_ALPHA, ObjectAnimator.ofFloat(this,
-                DIM_ALPHA_WITHOUT_HEADER, getDimAlpha(), transform.dimAlpha));
-        mDimAnimator.addListener(postAnimationTrigger.decrementOnAnimationEnd());
-        mDimAnimator.start();
-
-        if (screenPinningEnabled) {
-            showActionButton(true /* fadeIn */, duration /* fadeInDuration */);
-        }
-
-        if (mIncompatibleAppToastView != null &&
-                mIncompatibleAppToastView.getVisibility() == View.VISIBLE) {
-            mIncompatibleAppToastView.animate()
-                    .alpha(1f)
-                    .setDuration(duration)
-                    .setInterpolator(Interpolators.ALPHA_IN)
-                    .start();
-        }
-    }
-
-    @Override
-    public void onStartLaunchTargetLaunchAnimation(int duration, boolean screenPinningRequested,
-            ReferenceCountedTrigger postAnimationTrigger) {
-        Utilities.cancelAnimationWithoutCallbacks(mDimAnimator);
-
-        // Un-dim the view before/while launching the target
-        AnimationProps animation = new AnimationProps(duration, Interpolators.ALPHA_OUT);
-        mDimAnimator = animation.apply(AnimationProps.DIM_ALPHA, ObjectAnimator.ofFloat(this,
-                DIM_ALPHA, getDimAlpha(), 0));
-        mDimAnimator.start();
-
-        postAnimationTrigger.increment();
-        hideActionButton(true /* fadeOut */, duration,
-                !screenPinningRequested /* scaleDown */,
-                postAnimationTrigger.decrementOnAnimationEnd());
-    }
-
-    @Override
-    public void onStartFrontTaskEnterAnimation(boolean screenPinningEnabled) {
-        if (screenPinningEnabled) {
-            showActionButton(false /* fadeIn */, 0 /* fadeInDuration */);
-        }
-    }
-
-    /**** TaskCallbacks Implementation ****/
-
-    public void onTaskBound(Task t, boolean touchExplorationEnabled, int displayOrientation,
-            Rect displayRect) {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        mTouchExplorationEnabled = touchExplorationEnabled;
-        mTask = t;
-        mTaskBound = true;
-        mTask.addCallback(this);
-        mIsDisabledInSafeMode = !mTask.isSystemApp && ssp.isInSafeMode();
-        mThumbnailView.bindToTask(mTask, mIsDisabledInSafeMode, displayOrientation, displayRect);
-        mHeaderView.bindToTask(mTask, mTouchExplorationEnabled, mIsDisabledInSafeMode);
-
-        if (!t.isDockable && ssp.hasDockedTask()) {
-            if (mIncompatibleAppToastView == null) {
-                mIncompatibleAppToastView = Utilities.findViewStubById(this,
-                        R.id.incompatible_app_toast_stub).inflate();
-                TextView msg = findViewById(com.android.internal.R.id.message);
-                msg.setText(R.string.dock_non_resizeble_failed_to_dock_text);
-            }
-            mIncompatibleAppToastView.setVisibility(View.VISIBLE);
-        } else if (mIncompatibleAppToastView != null) {
-            mIncompatibleAppToastView.setVisibility(View.INVISIBLE);
-        }
-    }
-
-    @Override
-    public void onTaskDataLoaded(Task task, ThumbnailData thumbnailData) {
-        if (mTaskBound) {
-            // Update each of the views to the new task data
-            mThumbnailView.onTaskDataLoaded(thumbnailData);
-            mHeaderView.onTaskDataLoaded();
-        }
-    }
-
-    @Override
-    public void onTaskDataUnloaded() {
-        // Unbind each of the views from the task and remove the task callback
-        mTask.removeCallback(this);
-        mThumbnailView.unbindFromTask();
-        mHeaderView.unbindFromTask(mTouchExplorationEnabled);
-        mTaskBound = false;
-    }
-
-    @Override
-    public void onTaskWindowingModeChanged() {
-        // Force rebind the header, the thumbnail does not change due to stack changes
-        mHeaderView.bindToTask(mTask, mTouchExplorationEnabled, mIsDisabledInSafeMode);
-        mHeaderView.onTaskDataLoaded();
-    }
-
-    /**** View.OnClickListener Implementation ****/
-
-    @Override
-     public void onClick(final View v) {
-        if (mIsDisabledInSafeMode) {
-            Context context = getContext();
-            String msg = context.getString(R.string.recents_launch_disabled_message, mTask.title);
-            if (mDisabledAppToast != null) {
-                mDisabledAppToast.cancel();
-            }
-            mDisabledAppToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
-            mDisabledAppToast.show();
-            return;
-        }
-
-        boolean screenPinningRequested = false;
-        if (v == mActionButtonView) {
-            // Reset the translation of the action button before we animate it out
-            mActionButtonView.setTranslationZ(0f);
-            screenPinningRequested = true;
-        }
-        EventBus.getDefault().send(new LaunchTaskEvent(this, mTask, null, screenPinningRequested));
-
-        MetricsLogger.action(v.getContext(), MetricsEvent.ACTION_OVERVIEW_SELECT,
-                mTask.key.getComponent().toString());
-    }
-
-    /**** View.OnLongClickListener Implementation ****/
-
-    @Override
-    public boolean onLongClick(View v) {
-        if (!LegacyRecentsImpl.getConfiguration().dragToSplitEnabled) {
-            return false;
-        }
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        boolean inBounds = false;
-        Rect clipBounds = new Rect(mViewBounds.getClipBounds());
-        if (!clipBounds.isEmpty()) {
-            // If we are clipping the view to the bounds, manually do the hit test.
-            clipBounds.scale(getScaleX());
-            inBounds = clipBounds.contains(mDownTouchPos.x, mDownTouchPos.y);
-        } else {
-            // Otherwise just make sure we're within the view's bounds.
-            inBounds = mDownTouchPos.x <= getWidth() && mDownTouchPos.y <= getHeight();
-        }
-        if (v == this && inBounds && !ssp.hasDockedTask()) {
-            // Start listening for drag events
-            setClipViewInStack(false);
-
-            mDownTouchPos.x += ((1f - getScaleX()) * getWidth()) / 2;
-            mDownTouchPos.y += ((1f - getScaleY()) * getHeight()) / 2;
-
-            EventBus.getDefault().register(this, RecentsActivity.EVENT_BUS_PRIORITY + 1);
-            EventBus.getDefault().send(new DragStartEvent(mTask, this, mDownTouchPos));
-            return true;
-        }
-        return false;
-    }
-
-    /**** Events ****/
-
-    public final void onBusEvent(DragEndEvent event) {
-        if (!(event.dropTarget instanceof DockState)) {
-            event.addPostAnimationCallback(() -> {
-                // Reset the clip state for the drag view after the end animation completes
-                setClipViewInStack(true);
-            });
-        }
-        EventBus.getDefault().unregister(this);
-    }
-
-    public final void onBusEvent(DragEndCancelledEvent event) {
-        // Reset the clip state for the drag view after the cancel animation completes
-        event.addPostAnimationCallback(() -> {
-            setClipViewInStack(true);
-        });
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        String innerPrefix = prefix + "  ";
-
-        writer.print(prefix); writer.print("TaskView");
-        writer.print(" mTask="); writer.print(mTask.key.id);
-        writer.println();
-
-        mThumbnailView.dump(innerPrefix, writer);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewAccessibilityDelegate.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewAccessibilityDelegate.java
deleted file mode 100644
index 7bcad75..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewAccessibilityDelegate.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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.systemui.recents.views;
-
-import android.app.ActivityTaskManager;
-import android.content.Context;
-import android.graphics.Point;
-import android.os.Bundle;
-import android.util.SparseArray;
-import android.view.View;
-import android.view.accessibility.AccessibilityNodeInfo;
-import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
-import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
-
-public class TaskViewAccessibilityDelegate extends View.AccessibilityDelegate {
-    private static final String TAG = "TaskViewAccessibilityDelegate";
-
-    private final TaskView mTaskView;
-
-    protected static final int SPLIT_TASK_TOP = R.id.action_split_task_to_top;
-    protected static final int SPLIT_TASK_LEFT = R.id.action_split_task_to_left;
-    protected static final int SPLIT_TASK_RIGHT = R.id.action_split_task_to_right;
-
-    protected final SparseArray<AccessibilityAction> mActions = new SparseArray<>();
-
-    public TaskViewAccessibilityDelegate(TaskView taskView) {
-        mTaskView = taskView;
-        Context context = taskView.getContext();
-        mActions.put(SPLIT_TASK_TOP, new AccessibilityAction(SPLIT_TASK_TOP,
-                context.getString(R.string.recents_accessibility_split_screen_top)));
-        mActions.put(SPLIT_TASK_LEFT, new AccessibilityAction(SPLIT_TASK_LEFT,
-                context.getString(R.string.recents_accessibility_split_screen_left)));
-        mActions.put(SPLIT_TASK_RIGHT, new AccessibilityAction(SPLIT_TASK_RIGHT,
-                context.getString(R.string.recents_accessibility_split_screen_right)));
-    }
-
-    @Override
-    public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
-        super.onInitializeAccessibilityNodeInfo(host, info);
-        if (ActivityTaskManager.supportsSplitScreenMultiWindow(mTaskView.getContext())
-                && !LegacyRecentsImpl.getSystemServices().hasDockedTask()) {
-            DockState[] dockStates = LegacyRecentsImpl.getConfiguration()
-                    .getDockStatesForCurrentOrientation();
-            for (DockState dockState: dockStates) {
-                if (dockState == DockState.TOP) {
-                    info.addAction(mActions.get(SPLIT_TASK_TOP));
-                } else if (dockState == DockState.LEFT) {
-                    info.addAction(mActions.get(SPLIT_TASK_LEFT));
-                } else if (dockState == DockState.RIGHT) {
-                    info.addAction(mActions.get(SPLIT_TASK_RIGHT));
-                }
-            }
-        }
-    }
-
-    @Override
-    public boolean performAccessibilityAction(View host, int action, Bundle args) {
-        if (action == SPLIT_TASK_TOP) {
-            simulateDragIntoMultiwindow(DockState.TOP);
-        } else if (action == SPLIT_TASK_LEFT) {
-            simulateDragIntoMultiwindow(DockState.LEFT);
-        } else if (action == SPLIT_TASK_RIGHT) {
-            simulateDragIntoMultiwindow(DockState.RIGHT);
-        } else {
-            return super.performAccessibilityAction(host, action, args);
-        }
-        return true;
-    }
-
-    /** Simulate a user drag event to split the screen to the respected side */
-    private void simulateDragIntoMultiwindow(DockState dockState) {
-        EventBus.getDefault().send(new DragStartEvent(mTaskView.getTask(), mTaskView,
-                new Point(0,0), false /* isUserTouchInitiated */));
-        EventBus.getDefault().send(new DragEndEvent(mTaskView.getTask(), mTaskView, dockState));
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewHeader.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewHeader.java
deleted file mode 100644
index 21c0234..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewHeader.java
+++ /dev/null
@@ -1,685 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
-import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.annotation.Nullable;
-import android.app.AppGlobals;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.pm.ActivityInfo;
-import android.content.res.Resources;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.ColorFilter;
-import android.graphics.Paint;
-import android.graphics.PixelFormat;
-import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.RippleDrawable;
-import android.os.CountDownTimer;
-import androidx.core.graphics.ColorUtils;
-import android.util.AttributeSet;
-import android.util.IconDrawableFactory;
-import android.view.Gravity;
-import android.view.View;
-import android.view.ViewAnimationUtils;
-import android.view.ViewDebug;
-import android.view.ViewGroup;
-import android.widget.FrameLayout;
-import android.widget.ImageView;
-import android.widget.ProgressBar;
-import android.widget.TextView;
-
-import com.android.internal.logging.MetricsLogger;
-import com.android.systemui.Interpolators;
-import com.android.systemui.R;
-import com.android.systemui.recents.Constants;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.activity.LaunchTaskEvent;
-import com.android.systemui.recents.events.ui.ShowApplicationInfoEvent;
-import com.android.systemui.recents.misc.SystemServicesProxy;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-import com.android.systemui.shared.system.PackageManagerWrapper;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-
-/* The task bar view */
-public class TaskViewHeader extends FrameLayout
-        implements View.OnClickListener, View.OnLongClickListener {
-
-    private static IconDrawableFactory sDrawableFactory;
-
-    private static final float HIGHLIGHT_LIGHTNESS_INCREMENT = 0.075f;
-    private static final float OVERLAY_LIGHTNESS_INCREMENT = -0.0625f;
-    private static final int OVERLAY_REVEAL_DURATION = 250;
-    private static final long FOCUS_INDICATOR_INTERVAL_MS = 30;
-
-    /**
-     * A color drawable that draws a slight highlight at the top to help it stand out.
-     */
-    private class HighlightColorDrawable extends Drawable {
-
-        private Paint mHighlightPaint = new Paint();
-        private Paint mBackgroundPaint = new Paint();
-        private int mColor;
-        private float mDimAlpha;
-
-        public HighlightColorDrawable() {
-            mBackgroundPaint.setColor(Color.argb(255, 0, 0, 0));
-            mBackgroundPaint.setAntiAlias(true);
-            mHighlightPaint.setColor(Color.argb(255, 255, 255, 255));
-            mHighlightPaint.setAntiAlias(true);
-        }
-
-        public void setColorAndDim(int color, float dimAlpha) {
-            if (mColor != color || Float.compare(mDimAlpha, dimAlpha) != 0) {
-                mColor = color;
-                mDimAlpha = dimAlpha;
-                if (mShouldDarkenBackgroundColor) {
-                    color = getSecondaryColor(color, false /* useLightOverlayColor */);
-                }
-                mBackgroundPaint.setColor(color);
-
-                ColorUtils.colorToHSL(color, mTmpHSL);
-                // TODO: Consider using the saturation of the color to adjust the lightness as well
-                mTmpHSL[2] = Math.min(1f,
-                        mTmpHSL[2] + HIGHLIGHT_LIGHTNESS_INCREMENT * (1.0f - dimAlpha));
-                mHighlightPaint.setColor(ColorUtils.HSLToColor(mTmpHSL));
-
-                invalidateSelf();
-            }
-        }
-
-        @Override
-        public void setColorFilter(@Nullable ColorFilter colorFilter) {
-            // Do nothing
-        }
-
-        @Override
-        public void setAlpha(int alpha) {
-            // Do nothing
-        }
-
-        @Override
-        public void draw(Canvas canvas) {
-            // Draw the highlight at the top edge (but put the bottom edge just out of view)
-            canvas.drawRoundRect(0, 0, mTaskViewRect.width(),
-                    2 * Math.max(mHighlightHeight, mCornerRadius),
-                    mCornerRadius, mCornerRadius, mHighlightPaint);
-
-            // Draw the background with the rounded corners
-            canvas.drawRoundRect(0, mHighlightHeight, mTaskViewRect.width(),
-                    getHeight() + mCornerRadius,
-                    mCornerRadius, mCornerRadius, mBackgroundPaint);
-        }
-
-        @Override
-        public int getOpacity() {
-            return PixelFormat.OPAQUE;
-        }
-
-        public int getColor() {
-            return mColor;
-        }
-    }
-
-    Task mTask;
-
-    // Header views
-    ImageView mIconView;
-    TextView mTitleView;
-    ImageView mMoveTaskButton;
-    ImageView mDismissButton;
-    FrameLayout mAppOverlayView;
-    ImageView mAppIconView;
-    ImageView mAppInfoView;
-    TextView mAppTitleView;
-    ProgressBar mFocusTimerIndicator;
-
-    // Header drawables
-    @ViewDebug.ExportedProperty(category="recents")
-    Rect mTaskViewRect = new Rect();
-    int mHeaderBarHeight;
-    int mHeaderButtonPadding;
-    int mCornerRadius;
-    int mHighlightHeight;
-    @ViewDebug.ExportedProperty(category="recents")
-    float mDimAlpha;
-    Drawable mLightDismissDrawable;
-    Drawable mDarkDismissDrawable;
-    Drawable mLightFullscreenIcon;
-    Drawable mDarkFullscreenIcon;
-    Drawable mLightInfoIcon;
-    Drawable mDarkInfoIcon;
-    int mTaskBarViewLightTextColor;
-    int mTaskBarViewDarkTextColor;
-    int mDisabledTaskBarBackgroundColor;
-    String mDismissDescFormat;
-    String mAppInfoDescFormat;
-    int mTaskWindowingMode = WINDOWING_MODE_UNDEFINED;
-
-    // Header background
-    private HighlightColorDrawable mBackground;
-    private HighlightColorDrawable mOverlayBackground;
-    private float[] mTmpHSL = new float[3];
-
-    // Header dim, which is only used when task view hardware layers are not used
-    private Paint mDimLayerPaint = new Paint();
-
-    // Whether the background color should be darkened to differentiate from the primary color.
-    // Used in grid layout.
-    private boolean mShouldDarkenBackgroundColor = false;
-
-    private CountDownTimer mFocusTimerCountDown;
-
-    public TaskViewHeader(Context context) {
-        this(context, null);
-    }
-
-    public TaskViewHeader(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public TaskViewHeader(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public TaskViewHeader(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-        setWillNotDraw(false);
-
-        // Load the dismiss resources
-        Resources res = context.getResources();
-        mLightDismissDrawable = context.getDrawable(R.drawable.recents_dismiss_light);
-        mDarkDismissDrawable = context.getDrawable(R.drawable.recents_dismiss_dark);
-        mCornerRadius = LegacyRecentsImpl.getConfiguration().isGridEnabled ?
-                res.getDimensionPixelSize(R.dimen.recents_grid_task_view_rounded_corners_radius) :
-                res.getDimensionPixelSize(R.dimen.recents_task_view_rounded_corners_radius);
-        mHighlightHeight = res.getDimensionPixelSize(R.dimen.recents_task_view_highlight);
-        mTaskBarViewLightTextColor = context.getColor(R.color.recents_task_bar_light_text_color);
-        mTaskBarViewDarkTextColor = context.getColor(R.color.recents_task_bar_dark_text_color);
-        mLightFullscreenIcon = context.getDrawable(R.drawable.recents_move_task_fullscreen_light);
-        mDarkFullscreenIcon = context.getDrawable(R.drawable.recents_move_task_fullscreen_dark);
-        mLightInfoIcon = context.getDrawable(R.drawable.recents_info_light);
-        mDarkInfoIcon = context.getDrawable(R.drawable.recents_info_dark);
-        mDisabledTaskBarBackgroundColor =
-                context.getColor(R.color.recents_task_bar_disabled_background_color);
-        mDismissDescFormat = mContext.getString(
-                R.string.accessibility_recents_item_will_be_dismissed);
-        mAppInfoDescFormat = mContext.getString(R.string.accessibility_recents_item_open_app_info);
-
-        // Configure the background and dim
-        mBackground = new HighlightColorDrawable();
-        mBackground.setColorAndDim(Color.argb(255, 0, 0, 0), 0f);
-        setBackground(mBackground);
-        mOverlayBackground = new HighlightColorDrawable();
-        mDimLayerPaint.setColor(Color.argb(255, 0, 0, 0));
-        mDimLayerPaint.setAntiAlias(true);
-    }
-
-    /**
-     * Resets this header along with the TaskView.
-     */
-    public void reset() {
-        hideAppOverlay(true /* immediate */);
-    }
-
-    @Override
-    protected void onFinishInflate() {
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-
-        // Initialize the icon and description views
-        mIconView = findViewById(R.id.icon);
-        mIconView.setOnLongClickListener(this);
-        mTitleView = findViewById(R.id.title);
-        mDismissButton = findViewById(R.id.dismiss_task);
-
-        onConfigurationChanged();
-    }
-
-    /**
-     * Programmatically sets the layout params for a header bar layout.  This is necessary because
-     * we can't get resources based on the current configuration, but instead need to get them
-     * based on the device configuration.
-     */
-    private void updateLayoutParams(View icon, View title, View secondaryButton, View button) {
-        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
-                ViewGroup.LayoutParams.MATCH_PARENT, mHeaderBarHeight, Gravity.TOP);
-        setLayoutParams(lp);
-        lp = new FrameLayout.LayoutParams(mHeaderBarHeight, mHeaderBarHeight, Gravity.START);
-        icon.setLayoutParams(lp);
-        lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
-                ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL);
-        lp.setMarginStart(mHeaderBarHeight);
-        lp.setMarginEnd(mMoveTaskButton != null
-                ? 2 * mHeaderBarHeight
-                : mHeaderBarHeight);
-        title.setLayoutParams(lp);
-        if (secondaryButton != null) {
-            lp = new FrameLayout.LayoutParams(mHeaderBarHeight, mHeaderBarHeight, Gravity.END);
-            lp.setMarginEnd(mHeaderBarHeight);
-            secondaryButton.setLayoutParams(lp);
-            secondaryButton.setPadding(mHeaderButtonPadding, mHeaderButtonPadding,
-                    mHeaderButtonPadding, mHeaderButtonPadding);
-        }
-        lp = new FrameLayout.LayoutParams(mHeaderBarHeight, mHeaderBarHeight, Gravity.END);
-        button.setLayoutParams(lp);
-        button.setPadding(mHeaderButtonPadding, mHeaderButtonPadding, mHeaderButtonPadding,
-                mHeaderButtonPadding);
-    }
-
-    /**
-     * Update the header view when the configuration changes.
-     */
-    public void onConfigurationChanged() {
-        // Update the dimensions of everything in the header. We do this because we need to use
-        // resources for the display, and not the current configuration.
-        Resources res = getResources();
-        int headerBarHeight = TaskStackLayoutAlgorithm.getDimensionForDevice(getContext(),
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height_tablet_land,
-                R.dimen.recents_task_view_header_height,
-                R.dimen.recents_task_view_header_height_tablet_land,
-                R.dimen.recents_grid_task_view_header_height);
-        int headerButtonPadding = TaskStackLayoutAlgorithm.getDimensionForDevice(getContext(),
-                R.dimen.recents_task_view_header_button_padding,
-                R.dimen.recents_task_view_header_button_padding,
-                R.dimen.recents_task_view_header_button_padding,
-                R.dimen.recents_task_view_header_button_padding_tablet_land,
-                R.dimen.recents_task_view_header_button_padding,
-                R.dimen.recents_task_view_header_button_padding_tablet_land,
-                R.dimen.recents_grid_task_view_header_button_padding);
-        if (headerBarHeight != mHeaderBarHeight || headerButtonPadding != mHeaderButtonPadding) {
-            mHeaderBarHeight = headerBarHeight;
-            mHeaderButtonPadding = headerButtonPadding;
-            updateLayoutParams(mIconView, mTitleView, mMoveTaskButton, mDismissButton);
-            if (mAppOverlayView != null) {
-                updateLayoutParams(mAppIconView, mAppTitleView, null, mAppInfoView);
-            }
-        }
-    }
-
-    @Override
-    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
-        super.onLayout(changed, left, top, right, bottom);
-
-        // Since we update the position of children based on the width of the parent and this view
-        // recompute these changes with the new view size
-        onTaskViewSizeChanged(mTaskViewRect.width(), mTaskViewRect.height());
-    }
-
-    /**
-     * Called when the task view frame changes, allowing us to move the contents of the header
-     * to match the frame changes.
-     */
-    public void onTaskViewSizeChanged(int width, int height) {
-        mTaskViewRect.set(0, 0, width, height);
-
-        boolean showTitle = true;
-        boolean showMoveIcon = true;
-        boolean showDismissIcon = true;
-        int rightInset = width - getMeasuredWidth();
-
-        mTitleView.setVisibility(showTitle ? View.VISIBLE : View.INVISIBLE);
-        if (mMoveTaskButton != null) {
-            mMoveTaskButton.setVisibility(showMoveIcon ? View.VISIBLE : View.INVISIBLE);
-            mMoveTaskButton.setTranslationX(rightInset);
-        }
-        mDismissButton.setVisibility(showDismissIcon ? View.VISIBLE : View.INVISIBLE);
-        mDismissButton.setTranslationX(rightInset);
-
-        setLeftTopRightBottom(0, 0, width, getMeasuredHeight());
-    }
-
-    @Override
-    public void onDrawForeground(Canvas canvas) {
-        super.onDrawForeground(canvas);
-
-        // Draw the dim layer with the rounded corners
-        canvas.drawRoundRect(0, 0, mTaskViewRect.width(), getHeight() + mCornerRadius,
-                mCornerRadius, mCornerRadius, mDimLayerPaint);
-    }
-
-    /** Starts the focus timer. */
-    public void startFocusTimerIndicator(int duration) {
-        if (mFocusTimerIndicator == null) {
-            return;
-        }
-
-        mFocusTimerIndicator.setVisibility(View.VISIBLE);
-        mFocusTimerIndicator.setMax(duration);
-        mFocusTimerIndicator.setProgress(duration);
-        if (mFocusTimerCountDown != null) {
-            mFocusTimerCountDown.cancel();
-        }
-        mFocusTimerCountDown = new CountDownTimer(duration,
-                FOCUS_INDICATOR_INTERVAL_MS) {
-            public void onTick(long millisUntilFinished) {
-                mFocusTimerIndicator.setProgress((int) millisUntilFinished);
-            }
-
-            public void onFinish() {
-                // Do nothing
-            }
-        }.start();
-    }
-
-    /** Cancels the focus timer. */
-    public void cancelFocusTimerIndicator() {
-        if (mFocusTimerIndicator == null) {
-            return;
-        }
-
-        if (mFocusTimerCountDown != null) {
-            mFocusTimerCountDown.cancel();
-            mFocusTimerIndicator.setProgress(0);
-            mFocusTimerIndicator.setVisibility(View.INVISIBLE);
-        }
-    }
-
-    /** Only exposed for the workaround for b/27815919. */
-    public ImageView getIconView() {
-        return mIconView;
-    }
-
-    /** Returns the secondary color for a primary color. */
-    int getSecondaryColor(int primaryColor, boolean useLightOverlayColor) {
-        int overlayColor = useLightOverlayColor ? Color.WHITE : Color.BLACK;
-        return Utilities.getColorWithOverlay(primaryColor, overlayColor, 0.8f);
-    }
-
-    /**
-     * Sets the dim alpha, only used when we are not using hardware layers.
-     * (see RecentsConfiguration.useHardwareLayers)
-     */
-    public void setDimAlpha(float dimAlpha) {
-        if (Float.compare(mDimAlpha, dimAlpha) != 0) {
-            mDimAlpha = dimAlpha;
-            mTitleView.setAlpha(1f - dimAlpha);
-            updateBackgroundColor(mBackground.getColor(), dimAlpha);
-        }
-    }
-
-    /**
-     * Updates the background and highlight colors for this header.
-     */
-    private void updateBackgroundColor(int color, float dimAlpha) {
-        if (mTask != null) {
-            mBackground.setColorAndDim(color, dimAlpha);
-            // TODO: Consider using the saturation of the color to adjust the lightness as well
-            ColorUtils.colorToHSL(color, mTmpHSL);
-            mTmpHSL[2] = Math.min(1f, mTmpHSL[2] + OVERLAY_LIGHTNESS_INCREMENT * (1.0f - dimAlpha));
-            mOverlayBackground.setColorAndDim(ColorUtils.HSLToColor(mTmpHSL), dimAlpha);
-            mDimLayerPaint.setAlpha((int) (dimAlpha * 255));
-            invalidate();
-        }
-    }
-
-    /**
-     * Sets whether the background color should be darkened to differentiate from the primary color.
-     */
-    public void setShouldDarkenBackgroundColor(boolean flag) {
-        mShouldDarkenBackgroundColor = flag;
-    }
-
-    /**
-     * Binds the bar view to the task.
-     */
-    public void bindToTask(Task t, boolean touchExplorationEnabled, boolean disabledInSafeMode) {
-        mTask = t;
-
-        int primaryColor = disabledInSafeMode
-                ? mDisabledTaskBarBackgroundColor
-                : t.colorPrimary;
-        if (mBackground.getColor() != primaryColor) {
-            updateBackgroundColor(primaryColor, mDimAlpha);
-        }
-        if (!mTitleView.getText().toString().equals(t.title)) {
-            mTitleView.setText(t.title);
-        }
-        mTitleView.setContentDescription(t.titleDescription);
-        mTitleView.setTextColor(t.useLightOnPrimaryColor ?
-                mTaskBarViewLightTextColor : mTaskBarViewDarkTextColor);
-        mDismissButton.setImageDrawable(t.useLightOnPrimaryColor ?
-                mLightDismissDrawable : mDarkDismissDrawable);
-        mDismissButton.setContentDescription(String.format(mDismissDescFormat, t.titleDescription));
-        mDismissButton.setOnClickListener(this);
-        mDismissButton.setClickable(false);
-        ((RippleDrawable) mDismissButton.getBackground()).setForceSoftware(true);
-
-        // In accessibility, a single click on the focused app info button will show it
-        if (touchExplorationEnabled) {
-            mIconView.setContentDescription(String.format(mAppInfoDescFormat, t.titleDescription));
-            mIconView.setOnClickListener(this);
-            mIconView.setClickable(true);
-        }
-    }
-
-    /**
-     * Called when the bound task's data has loaded and this view should update to reflect the
-     * changes.
-     */
-    public void onTaskDataLoaded() {
-        if (mTask != null && mTask.icon != null) {
-            mIconView.setImageDrawable(mTask.icon);
-        }
-    }
-
-    /** Unbinds the bar view from the task */
-    void unbindFromTask(boolean touchExplorationEnabled) {
-        mTask = null;
-        mIconView.setImageDrawable(null);
-        if (touchExplorationEnabled) {
-            mIconView.setClickable(false);
-        }
-    }
-
-    /** Animates this task bar if the user does not interact with the stack after a certain time. */
-    void startNoUserInteractionAnimation() {
-        int duration = getResources().getInteger(R.integer.recents_task_enter_from_app_duration);
-        mDismissButton.setVisibility(View.VISIBLE);
-        mDismissButton.setClickable(true);
-        if (mDismissButton.getVisibility() == VISIBLE) {
-            mDismissButton.animate()
-                    .alpha(1f)
-                    .setInterpolator(Interpolators.FAST_OUT_LINEAR_IN)
-                    .setDuration(duration)
-                    .start();
-        } else {
-            mDismissButton.setAlpha(1f);
-        }
-        if (mMoveTaskButton != null) {
-            if (mMoveTaskButton.getVisibility() == VISIBLE) {
-                mMoveTaskButton.setVisibility(View.VISIBLE);
-                mMoveTaskButton.setClickable(true);
-                mMoveTaskButton.animate()
-                        .alpha(1f)
-                        .setInterpolator(Interpolators.FAST_OUT_LINEAR_IN)
-                        .setDuration(duration)
-                        .start();
-            } else {
-                mMoveTaskButton.setAlpha(1f);
-            }
-        }
-    }
-
-    /**
-     * Mark this task view that the user does has not interacted with the stack after a certain
-     * time.
-     */
-    public void setNoUserInteractionState() {
-        mDismissButton.setVisibility(View.VISIBLE);
-        mDismissButton.animate().cancel();
-        mDismissButton.setAlpha(1f);
-        mDismissButton.setClickable(true);
-        if (mMoveTaskButton != null) {
-            mMoveTaskButton.setVisibility(View.VISIBLE);
-            mMoveTaskButton.animate().cancel();
-            mMoveTaskButton.setAlpha(1f);
-            mMoveTaskButton.setClickable(true);
-        }
-    }
-
-    /**
-     * Resets the state tracking that the user has not interacted with the stack after a certain
-     * time.
-     */
-    void resetNoUserInteractionState() {
-        mDismissButton.setVisibility(View.INVISIBLE);
-        mDismissButton.setAlpha(0f);
-        mDismissButton.setClickable(false);
-        if (mMoveTaskButton != null) {
-            mMoveTaskButton.setVisibility(View.INVISIBLE);
-            mMoveTaskButton.setAlpha(0f);
-            mMoveTaskButton.setClickable(false);
-        }
-    }
-
-    @Override
-    protected int[] onCreateDrawableState(int extraSpace) {
-
-        // Don't forward our state to the drawable - we do it manually in onTaskViewFocusChanged.
-        // This is to prevent layer trashing when the view is pressed.
-        return new int[] {};
-    }
-
-    @Override
-    public void onClick(View v) {
-        if (v == mIconView) {
-            // In accessibility, a single click on the focused app info button will show it
-            EventBus.getDefault().send(new ShowApplicationInfoEvent(mTask));
-        } else if (v == mDismissButton) {
-            TaskView tv = Utilities.findParent(this, TaskView.class);
-            tv.dismissTask();
-
-            // Keep track of deletions by the dismiss button
-            MetricsLogger.histogram(getContext(), "overview_task_dismissed_source",
-                    Constants.Metrics.DismissSourceHeaderButton);
-        } else if (v == mMoveTaskButton) {
-            TaskView tv = Utilities.findParent(this, TaskView.class);
-            EventBus.getDefault().send(new LaunchTaskEvent(tv, mTask, null, false,
-                    mTaskWindowingMode, ACTIVITY_TYPE_UNDEFINED));
-        } else if (v == mAppInfoView) {
-            EventBus.getDefault().send(new ShowApplicationInfoEvent(mTask));
-        } else if (v == mAppIconView) {
-            hideAppOverlay(false /* immediate */);
-        }
-    }
-
-    @Override
-    public boolean onLongClick(View v) {
-        if (v == mIconView) {
-            showAppOverlay();
-            return true;
-        } else if (v == mAppIconView) {
-            hideAppOverlay(false /* immediate */);
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Shows the application overlay.
-     */
-    private void showAppOverlay() {
-        // Skip early if the task is invalid
-        SystemServicesProxy ssp = LegacyRecentsImpl.getSystemServices();
-        ComponentName cn = mTask.key.getComponent();
-        int userId = mTask.key.userId;
-        ActivityInfo activityInfo = PackageManagerWrapper.getInstance().getActivityInfo(cn, userId);
-        if (activityInfo == null) {
-            return;
-        }
-
-        // Inflate the overlay if necessary
-        if (mAppOverlayView == null) {
-            mAppOverlayView = (FrameLayout) Utilities.findViewStubById(this,
-                    R.id.app_overlay_stub).inflate();
-            mAppOverlayView.setBackground(mOverlayBackground);
-            mAppIconView = (ImageView) mAppOverlayView.findViewById(R.id.app_icon);
-            mAppIconView.setOnClickListener(this);
-            mAppIconView.setOnLongClickListener(this);
-            mAppInfoView = (ImageView) mAppOverlayView.findViewById(R.id.app_info);
-            mAppInfoView.setOnClickListener(this);
-            mAppTitleView = (TextView) mAppOverlayView.findViewById(R.id.app_title);
-            updateLayoutParams(mAppIconView, mAppTitleView, null, mAppInfoView);
-        }
-
-        // Update the overlay contents for the current app
-        mAppTitleView.setText(ActivityManagerWrapper.getInstance().getBadgedApplicationLabel(
-                activityInfo.applicationInfo, userId));
-        mAppTitleView.setTextColor(mTask.useLightOnPrimaryColor ?
-                mTaskBarViewLightTextColor : mTaskBarViewDarkTextColor);
-        mAppIconView.setImageDrawable(getIconDrawableFactory().getBadgedIcon(
-                activityInfo.applicationInfo, userId));
-        mAppInfoView.setImageDrawable(mTask.useLightOnPrimaryColor
-                ? mLightInfoIcon
-                : mDarkInfoIcon);
-        mAppOverlayView.setVisibility(View.VISIBLE);
-
-        int x = mIconView.getLeft() + mIconView.getWidth() / 2;
-        int y = mIconView.getTop() + mIconView.getHeight() / 2;
-        Animator revealAnim = ViewAnimationUtils.createCircularReveal(mAppOverlayView, x, y, 0,
-                getWidth());
-        revealAnim.setDuration(OVERLAY_REVEAL_DURATION);
-        revealAnim.setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN);
-        revealAnim.start();
-    }
-
-    /**
-     * Hide the application overlay.
-     */
-    private void hideAppOverlay(boolean immediate) {
-        // Skip if we haven't even loaded the overlay yet
-        if (mAppOverlayView == null) {
-            return;
-        }
-
-        if (immediate) {
-            mAppOverlayView.setVisibility(View.GONE);
-        } else {
-            int x = mIconView.getLeft() + mIconView.getWidth() / 2;
-            int y = mIconView.getTop() + mIconView.getHeight() / 2;
-            Animator revealAnim = ViewAnimationUtils.createCircularReveal(mAppOverlayView, x, y,
-                    getWidth(), 0);
-            revealAnim.setDuration(OVERLAY_REVEAL_DURATION);
-            revealAnim.setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN);
-            revealAnim.addListener(new AnimatorListenerAdapter() {
-                @Override
-                public void onAnimationEnd(Animator animation) {
-                    mAppOverlayView.setVisibility(View.GONE);
-                }
-            });
-            revealAnim.start();
-        }
-    }
-
-    private static IconDrawableFactory getIconDrawableFactory() {
-        if (sDrawableFactory == null) {
-            sDrawableFactory = IconDrawableFactory.newInstance(AppGlobals.getInitialApplication());
-        }
-        return sDrawableFactory;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewThumbnail.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewThumbnail.java
deleted file mode 100644
index 68f85a5..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewThumbnail.java
+++ /dev/null
@@ -1,392 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapShader;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.ColorMatrix;
-import android.graphics.ColorMatrixColorFilter;
-import android.graphics.LightingColorFilter;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.Rect;
-import android.graphics.Shader;
-import android.util.AttributeSet;
-import android.view.View;
-import android.view.ViewDebug;
-
-import com.android.systemui.R;
-import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.events.ui.TaskSnapshotChangedEvent;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import java.io.PrintWriter;
-
-
-/**
- * The task thumbnail view.  It implements an image view that allows for animating the dim and
- * alpha of the thumbnail image.
- */
-public class TaskViewThumbnail extends View {
-
-    private static final ColorMatrix TMP_FILTER_COLOR_MATRIX = new ColorMatrix();
-    private static final ColorMatrix TMP_BRIGHTNESS_COLOR_MATRIX = new ColorMatrix();
-
-    private Task mTask;
-
-    private int mDisplayOrientation = Configuration.ORIENTATION_UNDEFINED;
-    private Rect mDisplayRect = new Rect();
-
-    // Drawing
-    @ViewDebug.ExportedProperty(category="recents")
-    protected Rect mTaskViewRect = new Rect();
-    @ViewDebug.ExportedProperty(category="recents")
-    protected Rect mThumbnailRect = new Rect();
-    @ViewDebug.ExportedProperty(category="recents")
-    protected float mThumbnailScale;
-    private float mFullscreenThumbnailScale = 1f;
-    /** The height, in pixels, of the task view's title bar. */
-    private int mTitleBarHeight;
-    private boolean mSizeToFit = false;
-    private boolean mOverlayHeaderOnThumbnailActionBar = true;
-    private ThumbnailData mThumbnailData;
-
-    protected int mCornerRadius;
-    @ViewDebug.ExportedProperty(category="recents")
-    private float mDimAlpha;
-    private Matrix mMatrix = new Matrix();
-    private Paint mDrawPaint = new Paint();
-    protected Paint mLockedPaint = new Paint();
-    protected Paint mBgFillPaint = new Paint();
-    protected BitmapShader mBitmapShader;
-    protected boolean mUserLocked = false;
-    private LightingColorFilter mLightingColorFilter = new LightingColorFilter(0xffffffff, 0);
-
-    // Clip the top of the thumbnail against the opaque header bar that overlaps this view
-    private View mTaskBar;
-
-    // Visibility optimization, if the thumbnail height is less than the height of the header
-    // bar for the task view, then just mark this thumbnail view as invisible
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mInvisible;
-
-    @ViewDebug.ExportedProperty(category="recents")
-    private boolean mDisabledInSafeMode;
-
-    public TaskViewThumbnail(Context context) {
-        this(context, null);
-    }
-
-    public TaskViewThumbnail(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public TaskViewThumbnail(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public TaskViewThumbnail(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-        mDrawPaint.setColorFilter(mLightingColorFilter);
-        mDrawPaint.setFilterBitmap(true);
-        mDrawPaint.setAntiAlias(true);
-        Resources res = getResources();
-        mCornerRadius = res.getDimensionPixelSize(R.dimen.recents_task_view_rounded_corners_radius);
-        mBgFillPaint.setColor(Color.WHITE);
-        mLockedPaint.setColor(Color.WHITE);
-        mTitleBarHeight = res.getDimensionPixelSize(R.dimen.recents_grid_task_view_header_height);
-    }
-
-    /**
-     * Called when the task view frame changes, allowing us to move the contents of the header
-     * to match the frame changes.
-     */
-    public void onTaskViewSizeChanged(int width, int height) {
-        // Return early if the bounds have not changed
-        if (mTaskViewRect.width() == width && mTaskViewRect.height() == height) {
-            return;
-        }
-
-        mTaskViewRect.set(0, 0, width, height);
-        setLeftTopRightBottom(0, 0, width, height);
-        updateThumbnailMatrix();
-    }
-
-    @Override
-    protected void onDraw(Canvas canvas) {
-        if (mInvisible) {
-            return;
-        }
-
-        int viewWidth = mTaskViewRect.width();
-        int viewHeight = mTaskViewRect.height();
-        int thumbnailWidth = Math.min(viewWidth,
-                (int) (mThumbnailRect.width() * mThumbnailScale));
-        int thumbnailHeight = Math.min(viewHeight,
-                (int) (mThumbnailRect.height() * mThumbnailScale));
-
-        if (mUserLocked) {
-            canvas.drawRoundRect(0, 0, viewWidth, viewHeight, mCornerRadius, mCornerRadius,
-                    mLockedPaint);
-        } else if (mBitmapShader != null && thumbnailWidth > 0 && thumbnailHeight > 0) {
-            int topOffset = 0;
-            if (mTaskBar != null && mOverlayHeaderOnThumbnailActionBar) {
-                topOffset = mTaskBar.getHeight() - mCornerRadius;
-            }
-
-            // Draw the background, there will be some small overdraw with the thumbnail
-            if (thumbnailWidth < viewWidth) {
-                // Portrait thumbnail on a landscape task view
-                canvas.drawRoundRect(Math.max(0, thumbnailWidth - mCornerRadius), topOffset,
-                        viewWidth, viewHeight,
-                        mCornerRadius, mCornerRadius, mBgFillPaint);
-            }
-            if (thumbnailHeight < viewHeight) {
-                // Landscape thumbnail on a portrait task view
-                canvas.drawRoundRect(0, Math.max(topOffset, thumbnailHeight - mCornerRadius),
-                        viewWidth, viewHeight,
-                        mCornerRadius, mCornerRadius, mBgFillPaint);
-            }
-
-            // Draw the thumbnail
-            canvas.drawRoundRect(0, topOffset, thumbnailWidth, thumbnailHeight,
-                    mCornerRadius, mCornerRadius, mDrawPaint);
-        } else {
-            canvas.drawRoundRect(0, 0, viewWidth, viewHeight, mCornerRadius, mCornerRadius,
-                    mBgFillPaint);
-        }
-    }
-
-    /** Sets the thumbnail to a given bitmap. */
-    void setThumbnail(ThumbnailData thumbnailData) {
-        if (thumbnailData != null && thumbnailData.thumbnail != null) {
-            Bitmap bm = thumbnailData.thumbnail;
-            bm.prepareToDraw();
-            mFullscreenThumbnailScale = thumbnailData.scale;
-            mBitmapShader = new BitmapShader(bm, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
-            mDrawPaint.setShader(mBitmapShader);
-            mThumbnailRect.set(0, 0,
-                    bm.getWidth() - thumbnailData.insets.left - thumbnailData.insets.right,
-                    bm.getHeight() - thumbnailData.insets.top - thumbnailData.insets.bottom);
-            mThumbnailData = thumbnailData;
-            updateThumbnailMatrix();
-            updateThumbnailPaintFilter();
-        } else {
-            mBitmapShader = null;
-            mDrawPaint.setShader(null);
-            mThumbnailRect.setEmpty();
-            mThumbnailData = null;
-        }
-    }
-
-    /** Updates the paint to draw the thumbnail. */
-    void updateThumbnailPaintFilter() {
-        if (mInvisible) {
-            return;
-        }
-        int mul = (int) ((1.0f - mDimAlpha) * 255);
-        if (mBitmapShader != null) {
-            if (mDisabledInSafeMode) {
-                // Brightness: C-new = C-old*(1-amount) + amount
-                TMP_FILTER_COLOR_MATRIX.setSaturation(0);
-                float scale = 1f - mDimAlpha;
-                float[] mat = TMP_BRIGHTNESS_COLOR_MATRIX.getArray();
-                mat[0] = scale;
-                mat[6] = scale;
-                mat[12] = scale;
-                mat[4] = mDimAlpha * 255f;
-                mat[9] = mDimAlpha * 255f;
-                mat[14] = mDimAlpha * 255f;
-                TMP_FILTER_COLOR_MATRIX.preConcat(TMP_BRIGHTNESS_COLOR_MATRIX);
-                ColorMatrixColorFilter filter = new ColorMatrixColorFilter(TMP_FILTER_COLOR_MATRIX);
-                mDrawPaint.setColorFilter(filter);
-                mBgFillPaint.setColorFilter(filter);
-                mLockedPaint.setColorFilter(filter);
-            } else {
-                mLightingColorFilter.setColorMultiply(Color.argb(255, mul, mul, mul));
-                mDrawPaint.setColorFilter(mLightingColorFilter);
-                mDrawPaint.setColor(0xFFffffff);
-                mBgFillPaint.setColorFilter(mLightingColorFilter);
-                mLockedPaint.setColorFilter(mLightingColorFilter);
-            }
-        } else {
-            int grey = mul;
-            mDrawPaint.setColorFilter(null);
-            mDrawPaint.setColor(Color.argb(255, grey, grey, grey));
-        }
-        if (!mInvisible) {
-            invalidate();
-        }
-    }
-
-    /**
-     * Updates the scale of the bitmap relative to this view.
-     */
-    public void updateThumbnailMatrix() {
-        mThumbnailScale = 1f;
-        if (mBitmapShader != null && mThumbnailData != null) {
-            if (mTaskViewRect.isEmpty()) {
-                // If we haven't measured , skip the thumbnail drawing and only draw the background
-                // color
-                mThumbnailScale = 0f;
-            } else if (mSizeToFit) {
-                // Make sure we fill the entire space regardless of the orientation.
-                float viewAspectRatio = (float) mTaskViewRect.width() /
-                        (float) (mTaskViewRect.height() - mTitleBarHeight);
-                float thumbnailAspectRatio =
-                        (float) mThumbnailRect.width() / (float) mThumbnailRect.height();
-                if (viewAspectRatio > thumbnailAspectRatio) {
-                    mThumbnailScale =
-                            (float) mTaskViewRect.width() / (float) mThumbnailRect.width();
-                } else {
-                    mThumbnailScale = (float) (mTaskViewRect.height() - mTitleBarHeight)
-                            / (float) mThumbnailRect.height();
-                }
-            } else {
-                float invThumbnailScale = 1f / mFullscreenThumbnailScale;
-                if (mDisplayOrientation == Configuration.ORIENTATION_PORTRAIT) {
-                    if (mThumbnailData.orientation == Configuration.ORIENTATION_PORTRAIT) {
-                        // If we are in the same orientation as the screenshot, just scale it to the
-                        // width of the task view
-                        mThumbnailScale = (float) mTaskViewRect.width() / mThumbnailRect.width();
-                    } else {
-                        // Scale the landscape thumbnail up to app size, then scale that to the task
-                        // view size to match other portrait screenshots
-                        mThumbnailScale = invThumbnailScale *
-                                ((float) mTaskViewRect.width() / mDisplayRect.width());
-                    }
-                } else {
-                    // Otherwise, scale the screenshot to fit 1:1 in the current orientation
-                    mThumbnailScale = invThumbnailScale;
-                }
-            }
-            mMatrix.setTranslate(-mThumbnailData.insets.left * mFullscreenThumbnailScale,
-                    -mThumbnailData.insets.top * mFullscreenThumbnailScale);
-            mMatrix.postScale(mThumbnailScale, mThumbnailScale);
-            mBitmapShader.setLocalMatrix(mMatrix);
-        }
-        if (!mInvisible) {
-            invalidate();
-        }
-    }
-
-    /** Sets whether the thumbnail should be resized to fit the task view in all orientations. */
-    public void setSizeToFit(boolean flag) {
-        mSizeToFit = flag;
-    }
-
-    /**
-     * Sets whether the header should overlap (and hide) the action bar in the thumbnail, or
-     * be stacked just above it.
-     */
-    public void setOverlayHeaderOnThumbnailActionBar(boolean flag) {
-        mOverlayHeaderOnThumbnailActionBar = flag;
-    }
-
-    /** Updates the clip rect based on the given task bar. */
-    void updateClipToTaskBar(View taskBar) {
-        mTaskBar = taskBar;
-        invalidate();
-    }
-
-    /** Updates the visibility of the the thumbnail. */
-    void updateThumbnailVisibility(int clipBottom) {
-        boolean invisible = mTaskBar != null && (getHeight() - clipBottom) <= mTaskBar.getHeight();
-        if (invisible != mInvisible) {
-            mInvisible = invisible;
-            if (!mInvisible) {
-                updateThumbnailPaintFilter();
-            }
-        }
-    }
-
-    /**
-     * Sets the dim alpha, only used when we are not using hardware layers.
-     * (see RecentsConfiguration.useHardwareLayers)
-     */
-    public void setDimAlpha(float dimAlpha) {
-        mDimAlpha = dimAlpha;
-        updateThumbnailPaintFilter();
-    }
-
-    /**
-     * Returns the {@link Paint} used to draw a task screenshot, or {@link #mLockedPaint} if the
-     * thumbnail shouldn't be drawn because it belongs to a locked user.
-     */
-    protected Paint getDrawPaint() {
-        if (mUserLocked) {
-            return mLockedPaint;
-        }
-        return mDrawPaint;
-    }
-
-    /**
-     * Binds the thumbnail view to the task.
-     */
-    void bindToTask(Task t, boolean disabledInSafeMode, int displayOrientation, Rect displayRect) {
-        mTask = t;
-        mDisabledInSafeMode = disabledInSafeMode;
-        mDisplayOrientation = displayOrientation;
-        mDisplayRect.set(displayRect);
-        if (t.colorBackground != 0) {
-            mBgFillPaint.setColor(t.colorBackground);
-        }
-        if (t.colorPrimary != 0) {
-            mLockedPaint.setColor(t.colorPrimary);
-        }
-        mUserLocked = t.isLocked;
-        EventBus.getDefault().register(this);
-    }
-
-    /**
-     * Called when the bound task's data has loaded and this view should update to reflect the
-     * changes.
-     */
-    void onTaskDataLoaded(ThumbnailData thumbnailData) {
-        setThumbnail(thumbnailData);
-    }
-
-    /** Unbinds the thumbnail view from the task */
-    void unbindFromTask() {
-        mTask = null;
-        setThumbnail(null);
-        EventBus.getDefault().unregister(this);
-    }
-
-    public final void onBusEvent(TaskSnapshotChangedEvent event) {
-        if (mTask == null || event.taskId != mTask.key.id || event.thumbnailData == null
-                || event.thumbnailData.thumbnail == null) {
-            return;
-        }
-        setThumbnail(event.thumbnailData);
-    }
-
-    public void dump(String prefix, PrintWriter writer) {
-        writer.print(prefix); writer.print("TaskViewThumbnail");
-        writer.print(" mTaskViewRect="); writer.print(Utilities.dumpRect(mTaskViewRect));
-        writer.print(" mThumbnailRect="); writer.print(Utilities.dumpRect(mThumbnailRect));
-        writer.print(" mThumbnailScale="); writer.print(mThumbnailScale);
-        writer.print(" mDimAlpha="); writer.print(mDimAlpha);
-        writer.println();
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewTransform.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewTransform.java
deleted file mode 100644
index 48a7336..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/TaskViewTransform.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.animation.Animator;
-import android.animation.ObjectAnimator;
-import android.animation.PropertyValuesHolder;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.util.Property;
-import android.view.View;
-
-import com.android.systemui.recents.utilities.AnimationProps;
-import com.android.systemui.recents.utilities.Utilities;
-
-import java.util.ArrayList;
-
-/**
- * The visual properties for a {@link TaskView}.
- */
-public class TaskViewTransform {
-
-    public static final Property<View, Rect> LTRB =
-            new Property<View, Rect>(Rect.class, "leftTopRightBottom") {
-
-                private Rect mTmpRect = new Rect();
-
-                @Override
-                public void set(View v, Rect ltrb) {
-                    v.setLeftTopRightBottom(ltrb.left, ltrb.top, ltrb.right, ltrb.bottom);
-                }
-
-                @Override
-                public Rect get(View v) {
-                    mTmpRect.set(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
-                    return mTmpRect;
-                }
-            };
-
-    public float translationZ = 0;
-    public float scale = 1f;
-    public float alpha = 1f;
-    public float dimAlpha = 0f;
-    public float viewOutlineAlpha = 0f;
-
-    public boolean visible = false;
-
-    // This is a window-space rect used for positioning the task in the stack
-    public RectF rect = new RectF();
-
-    /**
-     * Fills int this transform from the state of the given TaskView.
-     */
-    public void fillIn(TaskView tv) {
-        translationZ = tv.getTranslationZ();
-        scale = tv.getScaleX();
-        alpha = tv.getAlpha();
-        visible = true;
-        dimAlpha = tv.getDimAlpha();
-        viewOutlineAlpha = tv.getViewBounds().getAlpha();
-        rect.set(tv.getLeft(), tv.getTop(), tv.getRight(), tv.getBottom());
-    }
-
-    /**
-     * Copies the transform state from another {@link TaskViewTransform}.
-     */
-    public void copyFrom(TaskViewTransform other) {
-        translationZ = other.translationZ;
-        scale = other.scale;
-        alpha = other.alpha;
-        visible = other.visible;
-        dimAlpha = other.dimAlpha;
-        viewOutlineAlpha = other.viewOutlineAlpha;
-        rect.set(other.rect);
-    }
-
-    /**
-     * @return whether {@param other} is the same transform as this
-     */
-    public boolean isSame(TaskViewTransform other) {
-        return translationZ == other.translationZ
-                && scale == other.scale
-                && other.alpha == alpha
-                && dimAlpha == other.dimAlpha
-                && visible == other.visible
-                && rect.equals(other.rect);
-    }
-
-    /**
-     * Resets the current transform.
-     */
-    public void reset() {
-        translationZ = 0;
-        scale = 1f;
-        alpha = 1f;
-        dimAlpha = 0f;
-        viewOutlineAlpha = 0f;
-        visible = false;
-        rect.setEmpty();
-    }
-
-    /** Convenience functions to compare against current property values */
-    public boolean hasAlphaChangedFrom(float v) {
-        return (Float.compare(alpha, v) != 0);
-    }
-
-    public boolean hasScaleChangedFrom(float v) {
-        return (Float.compare(scale, v) != 0);
-    }
-
-    public boolean hasTranslationZChangedFrom(float v) {
-        return (Float.compare(translationZ, v) != 0);
-    }
-
-    public boolean hasRectChangedFrom(View v) {
-        return ((int) rect.left != v.getLeft()) || ((int) rect.right != v.getRight()) ||
-                ((int) rect.top != v.getTop()) || ((int) rect.bottom != v.getBottom());
-    }
-
-    /**
-     * Applies this transform to a view.
-     */
-    public void applyToTaskView(TaskView v, ArrayList<Animator> animators,
-            AnimationProps animation, boolean allowShadows) {
-        // Return early if not visible
-        if (!visible) {
-            return;
-        }
-
-        if (animation.isImmediate()) {
-            if (allowShadows && hasTranslationZChangedFrom(v.getTranslationZ())) {
-                v.setTranslationZ(translationZ);
-            }
-            if (hasScaleChangedFrom(v.getScaleX())) {
-                v.setScaleX(scale);
-                v.setScaleY(scale);
-            }
-            if (hasAlphaChangedFrom(v.getAlpha())) {
-                v.setAlpha(alpha);
-            }
-            if (hasRectChangedFrom(v)) {
-                v.setLeftTopRightBottom((int) rect.left, (int) rect.top, (int) rect.right,
-                        (int) rect.bottom);
-            }
-        } else {
-            if (allowShadows && hasTranslationZChangedFrom(v.getTranslationZ())) {
-                ObjectAnimator anim = ObjectAnimator.ofFloat(v, View.TRANSLATION_Z,
-                        v.getTranslationZ(), translationZ);
-                animators.add(animation.apply(AnimationProps.TRANSLATION_Z, anim));
-            }
-            if (hasScaleChangedFrom(v.getScaleX())) {
-                ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(v,
-                        PropertyValuesHolder.ofFloat(View.SCALE_X, v.getScaleX(), scale),
-                        PropertyValuesHolder.ofFloat(View.SCALE_Y, v.getScaleX(), scale));
-                animators.add(animation.apply(AnimationProps.SCALE, anim));
-            }
-            if (hasAlphaChangedFrom(v.getAlpha())) {
-                ObjectAnimator anim = ObjectAnimator.ofFloat(v, View.ALPHA, v.getAlpha(), alpha);
-                animators.add(animation.apply(AnimationProps.ALPHA, anim));
-            }
-            if (hasRectChangedFrom(v)) {
-                Rect fromViewRect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
-                Rect toViewRect = new Rect();
-                rect.round(toViewRect);
-                ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(v,
-                        PropertyValuesHolder.ofObject(LTRB, Utilities.RECT_EVALUATOR,
-                                fromViewRect, toViewRect));
-                animators.add(animation.apply(AnimationProps.BOUNDS, anim));
-            }
-        }
-    }
-
-    /** Reset the transform on a view. */
-    public static void reset(TaskView v) {
-        v.setTranslationX(0f);
-        v.setTranslationY(0f);
-        v.setTranslationZ(0f);
-        v.setScaleX(1f);
-        v.setScaleY(1f);
-        v.setAlpha(1f);
-        v.getViewBounds().setClipBottom(0);
-        v.setLeftTopRightBottom(0, 0, 0, 0);
-    }
-
-    @Override
-    public String toString() {
-        return "R: " + rect + " V: " + visible;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/ViewPool.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/ViewPool.java
deleted file mode 100644
index a287fe6..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/ViewPool.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2014 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.recents.views;
-
-import android.content.Context;
-
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-
-/* A view pool to manage more views than we can visibly handle */
-public class ViewPool<V, T> {
-
-    /* An interface to the consumer of a view pool */
-    public interface ViewPoolConsumer<V, T> {
-        public V createView(Context context);
-        public void onReturnViewToPool(V v);
-        public void onPickUpViewFromPool(V v, T prepareData, boolean isNewView);
-        public boolean hasPreferredData(V v, T preferredData);
-    }
-
-    Context mContext;
-    ViewPoolConsumer<V, T> mViewCreator;
-    LinkedList<V> mPool = new LinkedList<V>();
-
-    /** Initializes the pool with a fixed predetermined pool size */
-    public ViewPool(Context context, ViewPoolConsumer<V, T> viewCreator) {
-        mContext = context;
-        mViewCreator = viewCreator;
-    }
-
-    /** Returns a view into the pool */
-    void returnViewToPool(V v) {
-        mViewCreator.onReturnViewToPool(v);
-        mPool.push(v);
-    }
-
-    /** Gets a view from the pool and prepares it */
-    V pickUpViewFromPool(T preferredData, T prepareData) {
-        V v = null;
-        boolean isNewView = false;
-        if (mPool.isEmpty()) {
-            v = mViewCreator.createView(mContext);
-            isNewView = true;
-        } else {
-            // Try and find a preferred view
-            Iterator<V> iter = mPool.iterator();
-            while (iter.hasNext()) {
-                V vpv = iter.next();
-                if (mViewCreator.hasPreferredData(vpv, preferredData)) {
-                    v = vpv;
-                    iter.remove();
-                    break;
-                }
-            }
-            // Otherwise, just grab the first view
-            if (v == null) {
-                v = mPool.pop();
-            }
-        }
-        mViewCreator.onPickUpViewFromPool(v, prepareData, isNewView);
-        return v;
-    }
-
-    /**
-     * Returns the list of views in the pool.
-     */
-    List<V> getViews() {
-        return mPool;
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/AnimateableGridViewBounds.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/AnimateableGridViewBounds.java
deleted file mode 100644
index a029478..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/AnimateableGridViewBounds.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.views.grid;
-
-import android.view.View;
-import com.android.systemui.recents.views.AnimateableViewBounds;
-
-/* An outline provider for grid-based task views. */
-class AnimateableGridViewBounds extends AnimateableViewBounds {
-
-    public AnimateableGridViewBounds(View source, int cornerRadius) {
-        super(source, cornerRadius);
-    }
-
-    @Override
-    protected void updateClipBounds() {
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/GridTaskView.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/GridTaskView.java
deleted file mode 100644
index 8b4700c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/GridTaskView.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.views.grid;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import com.android.systemui.R;
-import com.android.systemui.recents.views.AnimateableViewBounds;
-import com.android.systemui.recents.views.TaskView;
-
-public class GridTaskView extends TaskView {
-
-    /** The height, in pixels, of the header view. */
-    private int mHeaderHeight;
-
-    public GridTaskView(Context context) {
-        this(context, null);
-    }
-
-    public GridTaskView(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public GridTaskView(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public GridTaskView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-        mHeaderHeight = context.getResources().getDimensionPixelSize(
-                R.dimen.recents_grid_task_view_header_height);
-    }
-
-    @Override
-    protected void onFinishInflate() {
-        super.onFinishInflate();
-        // Show the full thumbnail and don't overlap with the header.
-        mThumbnailView.setSizeToFit(true);
-        mThumbnailView.setOverlayHeaderOnThumbnailActionBar(false);
-        mThumbnailView.updateThumbnailMatrix();
-        mThumbnailView.setTranslationY(mHeaderHeight);
-        mHeaderView.setShouldDarkenBackgroundColor(true);
-    }
-
-    @Override
-    protected AnimateableViewBounds createOutlineProvider() {
-        return new AnimateableGridViewBounds(this, mContext.getResources().getDimensionPixelSize(
-            R.dimen.recents_task_view_shadow_rounded_corners_radius));
-    }
-
-    @Override
-    protected void onConfigurationChanged() {
-        super.onConfigurationChanged();
-        mHeaderHeight = mContext.getResources().getDimensionPixelSize(
-                R.dimen.recents_grid_task_view_header_height);
-        mThumbnailView.setTranslationY(mHeaderHeight);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/GridTaskViewThumbnail.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/GridTaskViewThumbnail.java
deleted file mode 100644
index 2d7cfb1..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/GridTaskViewThumbnail.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * 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.systemui.recents.views.grid;
-
-import android.content.Context;
-import android.graphics.Canvas;
-import android.graphics.Path;
-import android.util.AttributeSet;
-
-import com.android.systemui.R;
-import com.android.systemui.recents.views.TaskViewThumbnail;
-
-public class GridTaskViewThumbnail extends TaskViewThumbnail {
-
-    private final Path mThumbnailOutline = new Path();
-    private final Path mRestBackgroundOutline = new Path();
-    // True if either this view's size or thumbnail scale has changed and mThumbnailOutline should
-    // be updated.
-    private boolean mUpdateThumbnailOutline = true;
-
-    public GridTaskViewThumbnail(Context context) {
-        this(context, null);
-    }
-
-    public GridTaskViewThumbnail(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public GridTaskViewThumbnail(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public GridTaskViewThumbnail(Context context, AttributeSet attrs, int defStyleAttr,
-        int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-        mCornerRadius = getResources().getDimensionPixelSize(
-                R.dimen.recents_grid_task_view_rounded_corners_radius);
-    }
-
-    /**
-     * Called when the task view frame changes, allowing us to move the contents of the header
-     * to match the frame changes.
-     */
-    public void onTaskViewSizeChanged(int width, int height) {
-        mUpdateThumbnailOutline = true;
-        super.onTaskViewSizeChanged(width, height);
-    }
-
-    /**
-     * Updates the scale of the bitmap relative to this view.
-     */
-    public void updateThumbnailMatrix() {
-        mUpdateThumbnailOutline = true;
-        super.updateThumbnailMatrix();
-    }
-
-    private void updateThumbnailOutline() {
-        final int titleHeight = getResources().getDimensionPixelSize(
-            R.dimen.recents_grid_task_view_header_height);
-        final int viewWidth = mTaskViewRect.width();
-        final int viewHeight = mTaskViewRect.height() - titleHeight;
-        final int thumbnailWidth = Math.min(viewWidth,
-            (int) (mThumbnailRect.width() * mThumbnailScale));
-        final int thumbnailHeight = Math.min(viewHeight,
-            (int) (mThumbnailRect.height() * mThumbnailScale));
-
-        if (mBitmapShader != null && thumbnailWidth > 0 && thumbnailHeight > 0) {
-            // Draw the thumbnail, we only round the bottom corners:
-            //
-            // outerLeft                outerRight
-            //    <----------------------->            mRestBackgroundOutline
-            //    _________________________            (thumbnailWidth < viewWidth)
-            //    |_______________________| outerTop     A ____ B
-            //    |                       |    ↑           |  |
-            //    |                       |    |           |  |
-            //    |                       |    |           |  |
-            //    |                       |    |           |  | C
-            //    \_______________________/    ↓           |__/
-            //  mCornerRadius             outerBottom    E    D
-            //
-            //  mRestBackgroundOutline (thumbnailHeight < viewHeight)
-            //  A _________________________ B
-            //    |                       | C
-            //  F \_______________________/
-            //    E                       D
-            final int outerLeft = 0;
-            final int outerTop = 0;
-            final int outerRight = outerLeft + thumbnailWidth;
-            final int outerBottom = outerTop + thumbnailHeight;
-            createThumbnailPath(outerLeft, outerTop, outerRight, outerBottom, mThumbnailOutline);
-
-            if (thumbnailWidth < viewWidth) {
-                final int l = Math.max(0, outerRight - mCornerRadius);
-                final int r = outerRight;
-                final int t = outerTop;
-                final int b = outerBottom;
-                mRestBackgroundOutline.reset();
-                mRestBackgroundOutline.moveTo(l, t); // A
-                mRestBackgroundOutline.lineTo(r, t); // B
-                mRestBackgroundOutline.lineTo(r, b - mCornerRadius); // C
-                mRestBackgroundOutline.arcTo(r -  2 * mCornerRadius, b - 2 * mCornerRadius, r, b,
-                        0, 90, false); // D
-                mRestBackgroundOutline.lineTo(l, b); // E
-                mRestBackgroundOutline.lineTo(l, t); // A
-                mRestBackgroundOutline.close();
-
-            }
-            if (thumbnailHeight < viewHeight) {
-                final int l = outerLeft;
-                final int r = outerRight;
-                final int t = Math.max(0, thumbnailHeight - mCornerRadius);
-                final int b = outerBottom;
-                mRestBackgroundOutline.reset();
-                mRestBackgroundOutline.moveTo(l, t); // A
-                mRestBackgroundOutline.lineTo(r, t); // B
-                mRestBackgroundOutline.lineTo(r, b - mCornerRadius); // C
-                mRestBackgroundOutline.arcTo(r -  2 * mCornerRadius, b - 2 * mCornerRadius, r, b,
-                        0, 90, false); // D
-                mRestBackgroundOutline.lineTo(l + mCornerRadius, b); // E
-                mRestBackgroundOutline.arcTo(l, b - 2 * mCornerRadius, l + 2 * mCornerRadius, b,
-                        90, 90, false); // F
-                mRestBackgroundOutline.lineTo(l, t); // A
-                mRestBackgroundOutline.close();
-            }
-        } else {
-            createThumbnailPath(0, 0, viewWidth, viewHeight, mThumbnailOutline);
-        }
-    }
-
-    private void createThumbnailPath(int outerLeft, int outerTop, int outerRight, int outerBottom,
-            Path outPath) {
-        outPath.reset();
-        outPath.moveTo(outerLeft, outerTop);
-        outPath.lineTo(outerRight, outerTop);
-        outPath.lineTo(outerRight, outerBottom - mCornerRadius);
-        outPath.arcTo(outerRight -  2 * mCornerRadius, outerBottom - 2 * mCornerRadius, outerRight,
-                outerBottom, 0, 90, false);
-        outPath.lineTo(outerLeft + mCornerRadius, outerBottom);
-        outPath.arcTo(outerLeft, outerBottom - 2 * mCornerRadius, outerLeft + 2 * mCornerRadius,
-                outerBottom, 90, 90, false);
-        outPath.lineTo(outerLeft, outerTop);
-        outPath.close();
-    }
-
-    @Override
-    protected void onDraw(Canvas canvas) {
-        final int titleHeight = getResources().getDimensionPixelSize(
-            R.dimen.recents_grid_task_view_header_height);
-        final int viewWidth = mTaskViewRect.width();
-        final int viewHeight = mTaskViewRect.height() - titleHeight;
-        final int thumbnailWidth = Math.min(viewWidth,
-            (int) (mThumbnailRect.width() * mThumbnailScale));
-        final int thumbnailHeight = Math.min(viewHeight,
-            (int) (mThumbnailRect.height() * mThumbnailScale));
-
-        if (mUpdateThumbnailOutline) {
-            updateThumbnailOutline();
-            mUpdateThumbnailOutline = false;
-        }
-
-        if (mUserLocked) {
-            canvas.drawPath(mThumbnailOutline, mLockedPaint);
-        } else if (mBitmapShader != null && thumbnailWidth > 0 && thumbnailHeight > 0) {
-            // Draw the background, there will be some small overdraw with the thumbnail
-            if (thumbnailWidth < viewWidth) {
-                // Portrait thumbnail on a landscape task view
-                canvas.drawPath(mRestBackgroundOutline, mBgFillPaint);
-            }
-            if (thumbnailHeight < viewHeight) {
-                // Landscape thumbnail on a portrait task view
-                canvas.drawPath(mRestBackgroundOutline, mBgFillPaint);
-            }
-            canvas.drawPath(mThumbnailOutline, getDrawPaint());
-        } else {
-            canvas.drawPath(mThumbnailOutline, mBgFillPaint);
-        }
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/TaskGridLayoutAlgorithm.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/TaskGridLayoutAlgorithm.java
deleted file mode 100644
index 719eaa7..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/TaskGridLayoutAlgorithm.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * Copyright (C) 2016 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.recents.views.grid;
-
-import static com.android.systemui.recents.views.TaskStackLayoutAlgorithm.*;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.view.WindowManager;
-
-import com.android.systemui.R;
-import com.android.systemui.recents.events.ui.focus.NavigateTaskViewEvent.Direction;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.views.TaskStackLayoutAlgorithm;
-import com.android.systemui.recents.views.TaskViewTransform;
-
-import java.util.ArrayList;
-
-public class TaskGridLayoutAlgorithm  {
-
-    private final String TAG = "TaskGridLayoutAlgorithm";
-    public static final int MAX_LAYOUT_TASK_COUNT = 8;
-
-    /** The horizontal padding around the whole recents view. */
-    private int mPaddingLeftRight;
-    /** The vertical padding around the whole recents view. */
-    private int mPaddingTopBottom;
-    /** The padding between task views. */
-    private int mPaddingTaskView;
-
-    private Rect mWindowRect;
-    private Point mScreenSize = new Point();
-
-    private Rect mTaskGridRect;
-
-    /** The height, in pixels, of each task view's title bar. */
-    private int mTitleBarHeight;
-
-    /** The aspect ratio of each task thumbnail, without the title bar. */
-    private float mAppAspectRatio;
-    private Rect mSystemInsets = new Rect();
-
-    /** The thickness of the focused task view frame. */
-    private int mFocusedFrameThickness;
-
-    /**
-     * When the amount of tasks is determined, the size and position of every task view can be
-     * decided. Each instance of TaskGridRectInfo store the task view information for a certain
-     * amount of tasks.
-     */
-    class TaskGridRectInfo {
-        Rect size;
-        int[] xOffsets;
-        int[] yOffsets;
-        int tasksPerLine;
-        int lines;
-
-        TaskGridRectInfo(int taskCount) {
-            size = new Rect();
-            xOffsets = new int[taskCount];
-            yOffsets = new int[taskCount];
-
-            int layoutTaskCount = Math.min(MAX_LAYOUT_TASK_COUNT, taskCount);
-            tasksPerLine = getTasksPerLine(layoutTaskCount);
-            lines = layoutTaskCount < 4 ? 1 : 2;
-
-            // A couple of special cases.
-            boolean landscapeWindow = mWindowRect.width() > mWindowRect.height();
-            boolean landscapeTaskView = mAppAspectRatio > 1;
-            // If we're in portrait but task views are landscape, show more lines of fewer tasks.
-            if (!landscapeWindow && landscapeTaskView) {
-                tasksPerLine = layoutTaskCount < 2 ? 1 : 2;
-                lines = layoutTaskCount < 3 ? 1 : (
-                        layoutTaskCount < 5 ? 2 : (
-                                layoutTaskCount < 7 ? 3 : 4));
-            }
-            // If we're in landscape but task views are portrait, show fewer lines of more tasks.
-            if (landscapeWindow && !landscapeTaskView) {
-                tasksPerLine = layoutTaskCount < 7 ? layoutTaskCount : 6;
-                lines = layoutTaskCount < 7 ? 1 : 2;
-            }
-
-            int taskWidth, taskHeight;
-            int maxTaskWidth = (mWindowRect.width() - 2 * mPaddingLeftRight
-                - (tasksPerLine - 1) * mPaddingTaskView) / tasksPerLine;
-            int maxTaskHeight = (mWindowRect.height() - 2 * mPaddingTopBottom
-                - (lines - 1) * mPaddingTaskView) / lines;
-
-            if (maxTaskHeight >= maxTaskWidth / mAppAspectRatio + mTitleBarHeight) {
-                // Width bound.
-                taskWidth = maxTaskWidth;
-                // Here we should round the height to the nearest integer.
-                taskHeight = (int) (maxTaskWidth / mAppAspectRatio + mTitleBarHeight + 0.5);
-            } else {
-                // Height bound.
-                taskHeight = maxTaskHeight;
-                // Here we should round the width to the nearest integer.
-                taskWidth = (int) ((taskHeight - mTitleBarHeight) * mAppAspectRatio + 0.5);
-            }
-            size.set(0, 0, taskWidth, taskHeight);
-
-            int emptySpaceX = mWindowRect.width() - 2 * mPaddingLeftRight
-                - (tasksPerLine * taskWidth) - (tasksPerLine - 1) * mPaddingTaskView;
-            int emptySpaceY = mWindowRect.height() - 2 * mPaddingTopBottom
-                - (lines * taskHeight) - (lines - 1) * mPaddingTaskView;
-            for (int taskIndex = 0; taskIndex < taskCount; taskIndex++) {
-                // We also need to invert the index in order to display the most recent tasks first.
-                int taskLayoutIndex = taskCount - taskIndex - 1;
-
-                int xIndex = taskLayoutIndex % tasksPerLine;
-                int yIndex = taskLayoutIndex / tasksPerLine;
-                xOffsets[taskIndex] = mWindowRect.left +
-                    emptySpaceX / 2 + mPaddingLeftRight + (taskWidth + mPaddingTaskView) * xIndex;
-                yOffsets[taskIndex] = mWindowRect.top +
-                    emptySpaceY / 2 + mPaddingTopBottom + (taskHeight + mPaddingTaskView) * yIndex;
-            }
-        }
-
-        private int getTasksPerLine(int taskCount) {
-            switch(taskCount) {
-                case 0:
-                    return 0;
-                case 1:
-                    return 1;
-                case 2:
-                case 4:
-                    return 2;
-                case 3:
-                case 5:
-                case 6:
-                    return 3;
-                case 7:
-                case 8:
-                    return 4;
-                default:
-                    throw new IllegalArgumentException("Unsupported task count " + taskCount);
-            }
-        }
-    }
-
-    /**
-     * We can find task view sizes and positions from mTaskGridRectInfoList[k - 1] when there
-     * are k tasks.
-     */
-    private TaskGridRectInfo[] mTaskGridRectInfoList;
-
-    public TaskGridLayoutAlgorithm(Context context) {
-        reloadOnConfigurationChange(context);
-    }
-
-    public void reloadOnConfigurationChange(Context context) {
-        Resources res = context.getResources();
-        mPaddingTaskView = res.getDimensionPixelSize(R.dimen.recents_grid_padding_task_view);
-        mFocusedFrameThickness = res.getDimensionPixelSize(
-            R.dimen.recents_grid_task_view_focused_frame_thickness);
-
-        mTaskGridRect = new Rect();
-        mTitleBarHeight = res.getDimensionPixelSize(R.dimen.recents_grid_task_view_header_height);
-
-        WindowManager windowManager = (WindowManager) context
-                .getSystemService(Context.WINDOW_SERVICE);
-        windowManager.getDefaultDisplay().getRealSize(mScreenSize);
-
-        updateAppAspectRatio();
-    }
-
-    /**
-     * Returns the proper task view transform of a certain task view, according to its index and the
-     * amount of task views.
-     * @param taskIndex     The index of the task view whose transform we want. It's never greater
-     *                      than {@link MAX_LAYOUT_TASK_COUNT}.
-     * @param taskCount     The current amount of task views.
-     * @param transformOut  The result transform that this method returns.
-     * @param stackLayout   The base stack layout algorithm.
-     * @return  The expected transform of the (taskIndex)th task view.
-     */
-    public TaskViewTransform getTransform(int taskIndex, int taskCount,
-        TaskViewTransform transformOut, TaskStackLayoutAlgorithm stackLayout) {
-        if (taskCount == 0) {
-            transformOut.reset();
-            return transformOut;
-        }
-
-        TaskGridRectInfo gridInfo = mTaskGridRectInfoList[taskCount - 1];
-        mTaskGridRect.set(gridInfo.size);
-
-        int x = gridInfo.xOffsets[taskIndex];
-        int y = gridInfo.yOffsets[taskIndex];
-        float z = stackLayout.mMaxTranslationZ;
-
-        // We always set the dim alpha to 0, since we don't want grid task views to dim.
-        float dimAlpha = 0f;
-        // We always set the alpha of the view outline to 1, to make sure the shadow is visible.
-        float viewOutlineAlpha = 1f;
-
-        // We also need to invert the index in order to display the most recent tasks first.
-        int taskLayoutIndex = taskCount - taskIndex - 1;
-        boolean isTaskViewVisible = taskLayoutIndex < MAX_LAYOUT_TASK_COUNT;
-
-        // Fill out the transform
-        transformOut.scale = 1f;
-        transformOut.alpha = isTaskViewVisible ? 1f : 0f;
-        transformOut.translationZ = z;
-        transformOut.dimAlpha = dimAlpha;
-        transformOut.viewOutlineAlpha = viewOutlineAlpha;
-        transformOut.rect.set(mTaskGridRect);
-        transformOut.rect.offset(x, y);
-        Utilities.scaleRectAboutCenter(transformOut.rect, transformOut.scale);
-        // We only show the 8 most recent tasks.
-        transformOut.visible = isTaskViewVisible;
-        return transformOut;
-    }
-
-    /**
-     * Return the proper task index to focus for arrow key navigation.
-     * @param taskCount             The amount of tasks.
-     * @param currentFocusedIndex   The index of the currently focused task.
-     * @param direction             The direction we're navigating.
-     * @return  The index of the task that should get the focus.
-     */
-    public int navigateFocus(int taskCount, int currentFocusedIndex, Direction direction) {
-        if (taskCount < 1 || taskCount > MAX_LAYOUT_TASK_COUNT) {
-            return -1;
-        }
-        if (currentFocusedIndex == -1) {
-            return 0;
-        }
-        int newIndex = currentFocusedIndex;
-        final TaskGridRectInfo gridInfo = mTaskGridRectInfoList[taskCount - 1];
-        final int currentLine = (taskCount - 1 - currentFocusedIndex) / gridInfo.tasksPerLine;
-        switch (direction) {
-            case UP:
-                newIndex += gridInfo.tasksPerLine;
-                newIndex = newIndex >= taskCount ? currentFocusedIndex : newIndex;
-                break;
-            case DOWN:
-                newIndex -= gridInfo.tasksPerLine;
-                newIndex = newIndex < 0 ? currentFocusedIndex : newIndex;
-                break;
-            case LEFT:
-                newIndex++;
-                final int leftMostIndex = (taskCount - 1) - currentLine * gridInfo.tasksPerLine;
-                newIndex = newIndex > leftMostIndex ? currentFocusedIndex : newIndex;
-                break;
-            case RIGHT:
-                newIndex--;
-                int rightMostIndex =
-                    (taskCount - 1) - (currentLine + 1) * gridInfo.tasksPerLine + 1;
-                rightMostIndex = rightMostIndex < 0 ? 0 : rightMostIndex;
-                newIndex = newIndex < rightMostIndex ? currentFocusedIndex : newIndex;
-                break;
-        }
-        return newIndex;
-    }
-
-    public void initialize(Rect windowRect) {
-        mWindowRect = windowRect;
-        // Define paddings in terms of percentage of the total area.
-        mPaddingLeftRight = (int) (0.025f * Math.min(mWindowRect.width(), mWindowRect.height()));
-        mPaddingTopBottom = (int) (0.1 * mWindowRect.height());
-
-        // Pre-calculate the positions and offsets of task views so that we can reuse them directly
-        // in the future.
-        mTaskGridRectInfoList = new TaskGridRectInfo[MAX_LAYOUT_TASK_COUNT];
-        for (int i = 0; i < MAX_LAYOUT_TASK_COUNT; i++) {
-            mTaskGridRectInfoList[i] = new TaskGridRectInfo(i + 1);
-        }
-    }
-
-    public void setSystemInsets(Rect systemInsets) {
-        mSystemInsets = systemInsets;
-        updateAppAspectRatio();
-    }
-
-    private void updateAppAspectRatio() {
-        int usableWidth = mScreenSize.x - mSystemInsets.left - mSystemInsets.right;
-        int usableHeight = mScreenSize.y - mSystemInsets.top - mSystemInsets.bottom;
-        mAppAspectRatio = (float) usableWidth / (float) usableHeight;
-    }
-
-    public Rect getStackActionButtonRect() {
-        Rect buttonRect = new Rect(mWindowRect);
-        buttonRect.right -= mPaddingLeftRight;
-        buttonRect.left += mPaddingLeftRight;
-        buttonRect.bottom = buttonRect.top + mPaddingTopBottom;
-        return buttonRect;
-    }
-
-    public void updateTaskGridRect(int taskCount) {
-        if (taskCount > 0) {
-            TaskGridRectInfo gridInfo = mTaskGridRectInfoList[taskCount - 1];
-            mTaskGridRect.set(gridInfo.size);
-        }
-    }
-
-    public Rect getTaskGridRect() {
-        return mTaskGridRect;
-    }
-
-    public int getFocusFrameThickness() {
-        return mFocusedFrameThickness;
-    }
-
-    public VisibilityReport computeStackVisibilityReport(ArrayList<Task> tasks) {
-        int visibleCount = Math.min(TaskGridLayoutAlgorithm.MAX_LAYOUT_TASK_COUNT, tasks.size());
-        return new VisibilityReport(visibleCount, visibleCount);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/TaskViewFocusFrame.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/TaskViewFocusFrame.java
deleted file mode 100644
index 1655f6c..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/grid/TaskViewFocusFrame.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * 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.systemui.recents.views.grid;
-
-import android.content.Context;
-import android.graphics.Rect;
-import android.util.AttributeSet;
-import android.view.View;
-
-import android.view.ViewTreeObserver.OnGlobalFocusChangeListener;
-import com.android.systemui.R;
-import com.android.systemui.recents.model.TaskStack;
-import com.android.systemui.recents.views.TaskStackView;
-
-public class TaskViewFocusFrame extends View implements OnGlobalFocusChangeListener {
-
-    private TaskStackView mSv;
-    private TaskGridLayoutAlgorithm mTaskGridLayoutAlgorithm;
-    public TaskViewFocusFrame(Context context) {
-        this(context, null);
-    }
-
-    public TaskViewFocusFrame(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
-    }
-
-    public TaskViewFocusFrame(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
-    }
-
-    public TaskViewFocusFrame(Context context, AttributeSet attrs, int defStyleAttr,
-        int defStyleRes) {
-        super(context, attrs, defStyleAttr, defStyleRes);
-        setBackground(mContext.getDrawable(
-            R.drawable.recents_grid_task_view_focus_frame_background));
-        setFocusable(false);
-        hide();
-    }
-
-    public TaskViewFocusFrame(Context context, TaskStackView stackView,
-        TaskGridLayoutAlgorithm taskGridLayoutAlgorithm) {
-        this(context);
-        mSv = stackView;
-        mTaskGridLayoutAlgorithm = taskGridLayoutAlgorithm;
-    }
-
-    /**
-     * Measure the width and height of the focus frame according to the current grid task view size.
-     */
-    public void measure() {
-        int thickness = mTaskGridLayoutAlgorithm.getFocusFrameThickness();
-        Rect rect = mTaskGridLayoutAlgorithm.getTaskGridRect();
-        measure(
-            MeasureSpec.makeMeasureSpec(rect.width() + thickness * 2, MeasureSpec.EXACTLY),
-            MeasureSpec.makeMeasureSpec(rect.height() + thickness * 2, MeasureSpec.EXACTLY));
-    }
-
-    /**
-     * Layout the focus frame with its size.
-     */
-    public void layout() {
-        layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
-    }
-
-    /**
-     * Update the current size of grid task view and the focus frame.
-     */
-    public void resize() {
-        if (mSv.useGridLayout()) {
-            mTaskGridLayoutAlgorithm.updateTaskGridRect(mSv.getStack().getTaskCount());
-            measure();
-            requestLayout();
-        }
-    }
-
-    /**
-     * Move the task view focus frame to surround the newly focused view. If it's {@code null} or
-     * it's not an instance of GridTaskView, we hide the focus frame.
-     * @param newFocus The newly focused view.
-     */
-    public void moveGridTaskViewFocus(View newFocus) {
-        if (mSv.useGridLayout()) {
-            // The frame only shows up in the grid layout. It shouldn't show up in the stack
-            // layout including when we're in the split screen.
-            if (newFocus instanceof GridTaskView) {
-                // If the focus goes to a GridTaskView, we show the frame and layout it.
-                int[] location = new int[2];
-                newFocus.getLocationInWindow(location);
-                int thickness = mTaskGridLayoutAlgorithm.getFocusFrameThickness();
-                setTranslationX(location[0] - thickness);
-                setTranslationY(location[1] - thickness);
-                show();
-            } else {
-                // If focus goes to other views, we hide the frame.
-                hide();
-            }
-        }
-    }
-
-    @Override
-    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
-        if (!mSv.useGridLayout()) {
-            return;
-        }
-        if (newFocus == null) {
-            // We're going to touch mode, unset the focus.
-            moveGridTaskViewFocus(null);
-            return;
-        }
-        if (oldFocus == null) {
-            // We're returning from touch mode, set the focus to the previously focused task.
-            final TaskStack stack = mSv.getStack();
-            final int taskCount = stack.getTaskCount();
-            final int k = stack.indexOfTask(mSv.getFocusedTask());
-            final int taskIndexToFocus = k == -1 ? (taskCount - 1) : (k % taskCount);
-            mSv.setFocusedTask(taskIndexToFocus, false, true);
-        }
-    }
-
-    private void show() {
-        setAlpha(1f);
-    }
-
-    private void hide() {
-        setAlpha(0f);
-    }
-}
diff --git a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/lowram/TaskStackLowRamLayoutAlgorithm.java b/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/lowram/TaskStackLowRamLayoutAlgorithm.java
deleted file mode 100644
index 15c7c87..0000000
--- a/packages/SystemUI/legacy/recents/src/com/android/systemui/recents/views/lowram/TaskStackLowRamLayoutAlgorithm.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * 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.systemui.recents.views.lowram;
-
-import android.content.Context;
-import android.graphics.Rect;
-import android.view.ViewConfiguration;
-
-import com.android.systemui.R;
-import com.android.systemui.recents.LegacyRecentsImpl;
-import com.android.systemui.recents.RecentsActivityLaunchState;
-import com.android.systemui.recents.utilities.Utilities;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.recents.views.TaskStackLayoutAlgorithm;
-import com.android.systemui.recents.views.TaskViewTransform;
-
-import java.util.ArrayList;
-
-import static com.android.systemui.recents.views.TaskStackLayoutAlgorithm.VisibilityReport;
-
-public class TaskStackLowRamLayoutAlgorithm {
-
-    private static final String TAG = "TaskStackLowRamLayoutAlgorithm";
-    private static final float MAX_OVERSCROLL = 0.2f / 0.3f;
-
-    public static final int MAX_LAYOUT_TASK_COUNT = 9;
-    public static final int NUM_TASK_VISIBLE_LAUNCHED_FROM_HOME = 2;
-    public static final int NUM_TASK_VISIBLE_LAUNCHED_FROM_APP =
-            NUM_TASK_VISIBLE_LAUNCHED_FROM_HOME + 1;
-    private Rect mWindowRect;
-
-    private int mFlingThreshold;
-    private int mPadding;
-    private int mPaddingLeftRight;
-    private int mTopOffset;
-    private int mPaddingEndTopBottom;
-    private Rect mTaskRect = new Rect();
-    private Rect mSystemInsets = new Rect();
-
-    public TaskStackLowRamLayoutAlgorithm(Context context) {
-        reloadOnConfigurationChange(context);
-    }
-
-    public void reloadOnConfigurationChange(Context context) {
-        mPadding = context.getResources()
-                .getDimensionPixelSize(R.dimen.recents_layout_side_margin_phone);
-        mFlingThreshold = ViewConfiguration.get(context).getScaledMinimumFlingVelocity();
-    }
-
-    public void initialize(Rect windowRect) {
-        mWindowRect = windowRect;
-        if (mWindowRect.height() > 0) {
-            int windowHeight = mWindowRect.height() - mSystemInsets.bottom;
-            int windowWidth = mWindowRect.width() - mSystemInsets.right - mSystemInsets.left;
-            int width = Math.min(windowWidth, windowHeight) - mPadding * 2;
-            boolean isLandscape = windowWidth > windowHeight;
-            mTaskRect.set(0, 0, width, isLandscape ? width * 2 / 3 : width);
-            mPaddingLeftRight = (windowWidth - mTaskRect.width()) / 2;
-            mPaddingEndTopBottom = (windowHeight - mTaskRect.height()) / 2;
-
-            // Compute the top offset to center tasks in the middle of the screen
-            mTopOffset = (getTotalHeightOfTasks(MAX_LAYOUT_TASK_COUNT) - windowHeight) / 2;
-        }
-    }
-
-    public void setSystemInsets(Rect systemInsets) {
-        mSystemInsets = systemInsets;
-    }
-
-    public VisibilityReport computeStackVisibilityReport(ArrayList<Task> tasks) {
-        RecentsActivityLaunchState launchState = LegacyRecentsImpl.getConfiguration().getLaunchState();
-        int maxVisible = launchState.launchedFromHome || launchState.launchedFromPipApp
-                    || launchState.launchedWithNextPipApp
-                ? NUM_TASK_VISIBLE_LAUNCHED_FROM_HOME
-                : NUM_TASK_VISIBLE_LAUNCHED_FROM_APP;
-        int visibleCount = Math.min(maxVisible, tasks.size());
-        return new VisibilityReport(visibleCount, visibleCount);
-    }
-
-    public void getFrontOfStackTransform(TaskViewTransform transformOut,
-            TaskStackLayoutAlgorithm stackLayout) {
-        if (mWindowRect == null) {
-            transformOut.reset();
-            return;
-        }
-
-        // Calculate the static task y position 2 tasks after/below the middle/current task
-        int windowHeight = mWindowRect.height() - mSystemInsets.bottom;
-        int bottomOfCurrentTask = (windowHeight + mTaskRect.height()) / 2;
-        int y = bottomOfCurrentTask + mTaskRect.height() + mPadding * 2;
-        fillStackTransform(transformOut, y, stackLayout.mMaxTranslationZ, true);
-    }
-
-    public void getBackOfStackTransform(TaskViewTransform transformOut,
-            TaskStackLayoutAlgorithm stackLayout) {
-        if (mWindowRect == null) {
-            transformOut.reset();
-            return;
-        }
-
-        // Calculate the static task y position 2 tasks before/above the middle/current task
-        int windowHeight = mWindowRect.height() - mSystemInsets.bottom;
-        int topOfCurrentTask = (windowHeight - mTaskRect.height()) / 2;
-        int y = topOfCurrentTask - (mTaskRect.height() + mPadding) * 2;
-        fillStackTransform(transformOut, y, stackLayout.mMaxTranslationZ, true);
-    }
-
-    public TaskViewTransform getTransform(int taskIndex, float stackScroll,
-            TaskViewTransform transformOut, int taskCount, TaskStackLayoutAlgorithm stackLayout) {
-        if (taskCount == 0) {
-            transformOut.reset();
-            return transformOut;
-        }
-        boolean visible = true;
-        int y;
-        if (taskCount > 1) {
-            y = getTaskTopFromIndex(taskIndex) - percentageToScroll(stackScroll);
-
-            // Check visibility from the bottom of the task
-            visible = y + mPadding + getTaskRect().height() > 0;
-        } else {
-            int windowHeight = mWindowRect.height() - mSystemInsets.bottom;
-            y = (windowHeight - mTaskRect.height()) / 2 - percentageToScroll(stackScroll);
-        }
-        fillStackTransform(transformOut, y, stackLayout.mMaxTranslationZ, visible);
-        return transformOut;
-    }
-
-    /**
-     * Finds the closest task to the scroll percentage in the y axis and returns the percentage of
-     * the task to scroll to.
-     * @param scrollP percentage to find nearest to
-     * @param numTasks number of tasks in recents stack
-     * @param velocity speed of fling
-     */
-    public float getClosestTaskP(float scrollP, int numTasks, int velocity) {
-        int y = percentageToScroll(scrollP);
-
-        int lastY = getTaskTopFromIndex(0) - mPaddingEndTopBottom;
-        for (int i = 1; i < numTasks; i++) {
-            int taskY = getTaskTopFromIndex(i) - mPaddingEndTopBottom;
-            int diff = taskY - y;
-            if (diff > 0) {
-                int diffPrev = Math.abs(y - lastY);
-                boolean useNext = diff > diffPrev;
-                if (Math.abs(velocity) > mFlingThreshold) {
-                    useNext = velocity > 0;
-                }
-                return useNext
-                        ? scrollToPercentage(lastY) : scrollToPercentage(taskY);
-            }
-            lastY = taskY;
-        }
-        return scrollToPercentage(lastY);
-    }
-
-    /**
-     * Convert a scroll value to a percentage
-     * @param scroll a scroll value
-     * @return a percentage that represents the scroll from the total height of tasks
-     */
-    public float scrollToPercentage(int scroll) {
-        return (float) scroll / (mTaskRect.height() + mPadding);
-    }
-
-    /**
-     * Converts a percentage to the scroll value from the total height of tasks
-     * @param p a percentage that represents the scroll value
-     * @return a scroll value in pixels
-     */
-    public int percentageToScroll(float p) {
-        return (int) (p * (mTaskRect.height() + mPadding));
-    }
-
-    /**
-     * Get the min scroll progress for low ram layout. This computes the top position of the
-     * first task and reduce by the end padding to center the first task
-     * @return position of max scroll
-     */
-    public float getMinScrollP() {
-        return getScrollPForTask(0);
-    }
-
-    /**
-     * Get the max scroll progress for low ram layout. This computes the top position of the last
-     * task and reduce by the end padding to center the last task
-     * @param taskCount the amount of tasks in the recents stack
-     * @return position of max scroll
-     */
-    public float getMaxScrollP(int taskCount) {
-        return getScrollPForTask(taskCount - 1);
-    }
-
-    /**
-     * Get the initial scroll value whether launched from home or from an app.
-     * @param taskCount the amount of tasks currently in recents
-     * @param fromHome if launching recents from home or not
-     * @return from home it will return max value and from app it will return 2nd last task
-     */
-    public float getInitialScrollP(int taskCount, boolean fromHome) {
-        if (fromHome) {
-            return getMaxScrollP(taskCount);
-        }
-        if (taskCount < 2) {
-            return 0;
-        }
-        return getScrollPForTask(taskCount - 2);
-    }
-
-    /**
-     * Get the scroll progress for any task
-     * @param taskIndex task index to get the scroll progress of
-     * @return scroll progress of task
-     */
-    public float getScrollPForTask(int taskIndex) {
-        return scrollToPercentage(getTaskTopFromIndex(taskIndex) - mPaddingEndTopBottom);
-    }
-
-    public Rect getTaskRect() {
-        return mTaskRect;
-    }
-
-    public float getMaxOverscroll() {
-        return MAX_OVERSCROLL;
-    }
-
-    private int getTaskTopFromIndex(int index) {
-        return getTotalHeightOfTasks(index) - mTopOffset;
-    }
-
-    private int getTotalHeightOfTasks(int taskCount) {
-        return taskCount * mTaskRect.height() + (taskCount + 1) * mPadding;
-    }
-
-    private void fillStackTransform(TaskViewTransform transformOut, int y, int translationZ,
-            boolean visible) {
-        transformOut.scale = 1f;
-        transformOut.alpha = 1f;
-        transformOut.translationZ = translationZ;
-        transformOut.dimAlpha = 0f;
-        transformOut.viewOutlineAlpha = 1f;
-        transformOut.rect.set(getTaskRect());
-        transformOut.rect.offset(mPaddingLeftRight + mSystemInsets.left, y);
-        Utilities.scaleRectAboutCenter(transformOut.rect, transformOut.scale);
-        transformOut.visible = visible;
-    }
-}
diff --git a/packages/SystemUI/res-keyguard/values-af/strings.xml b/packages/SystemUI/res-keyguard/values-af/strings.xml
index 11bcc88..b9122d2 100644
--- a/packages/SystemUI/res-keyguard/values-af/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-af/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Voer jou wagwoord in"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Verkeerde PIN-kode."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ongeldige kaart."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Volgelaai"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Gelaai"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Laai tans draadloos"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Laai tans"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Laai tans vinnig"</string>
diff --git a/packages/SystemUI/res-keyguard/values-am/strings.xml b/packages/SystemUI/res-keyguard/values-am/strings.xml
index 4feb9f1..4cabaca 100644
--- a/packages/SystemUI/res-keyguard/values-am/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-am/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"ይለፍ ቃልዎን ያስገቡ"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ትክክል ያልሆነ ፒን  ኮድ።"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ልክ ያልሆነ ካርድ።"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"ሙሉ በሙሉ ኃይል ተሞልቷል"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ባትሪ ሞልቷል"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • በገመድ አልባ ኃይል በመሙላት ላይ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ኃይል በመሙላት ላይ"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • በፍጥነት ኃይልን በመሙላት ላይ"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ar/strings.xml b/packages/SystemUI/res-keyguard/values-ar/strings.xml
index 4e163a2..d017953 100644
--- a/packages/SystemUI/res-keyguard/values-ar/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ar/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"أدخل كلمة المرور"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"رمز رقم التعريف الشخصي غير صحيح."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"بطاقة غير صالحة."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"تم شحن البطارية بالكامل"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"تم الشحن"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • جارٍ الشحن لاسلكيًا"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • جارٍ الشحن"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • جارٍ الشحن سريعًا"</string>
diff --git a/packages/SystemUI/res-keyguard/values-as/strings.xml b/packages/SystemUI/res-keyguard/values-as/strings.xml
index e225675..0c7dec3 100644
--- a/packages/SystemUI/res-keyguard/values-as/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-as/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"আপোনাৰ পাছৱর্ড দিয়ক"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ভুল পিন ক\'ড।"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ব্যৱহাৰৰ অযোগ্য ছিম কাৰ্ড"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"পূৰ্ণৰূপে চ্চাৰ্জ হৈছে"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"চ্চার্জ কৰা হ’ল"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • বেতাঁৰৰ জৰিয়তে চাৰ্জ কৰি থকা হৈছে"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • চ্চার্জ কৰি থকা হৈছে"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • দ্ৰুত গতিৰে চ্চাৰ্জ কৰি থকা হৈছে"</string>
diff --git a/packages/SystemUI/res-keyguard/values-az/strings.xml b/packages/SystemUI/res-keyguard/values-az/strings.xml
index c0cf129..8cdf2f0 100644
--- a/packages/SystemUI/res-keyguard/values-az/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-az/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Şifrənizi daxil edin"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Yanlış PIN kod."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Yanlış Kart."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Tam dolub"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Enerji yığdı"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Simsiz şəkildə batareya yığır"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Enerji yığır"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Sürətlə enerji yığır"</string>
diff --git a/packages/SystemUI/res-keyguard/values-b+sr+Latn/strings.xml b/packages/SystemUI/res-keyguard/values-b+sr+Latn/strings.xml
index 88ca77b..eeda7ce 100644
--- a/packages/SystemUI/res-keyguard/values-b+sr+Latn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-b+sr+Latn/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Unesite lozinku"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN kôd je netačan."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Nevažeća kartica."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Napunjena je u potpunosti"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Napunjena je"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Bežično punjenje"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Puni se"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Brzo se puni"</string>
diff --git a/packages/SystemUI/res-keyguard/values-be/strings.xml b/packages/SystemUI/res-keyguard/values-be/strings.xml
index a897fb2..09cda6b 100644
--- a/packages/SystemUI/res-keyguard/values-be/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-be/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Увядзіце пароль"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Няправільны PIN-код."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Несапраўдная картка."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Акумулятар поўнасцю зараджаны"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Зараджаны"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ідзе бесправадная зарадка"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ідзе зарадка"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ідзе хуткая зарадка"</string>
diff --git a/packages/SystemUI/res-keyguard/values-bg/strings.xml b/packages/SystemUI/res-keyguard/values-bg/strings.xml
index eebdb9e..75942ea 100644
--- a/packages/SystemUI/res-keyguard/values-bg/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-bg/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Въведете паролата си"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Неправилен ПИН код."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Картата е невалидна."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Напълно заредено"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Заредена"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Зарежда се безжично"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Зарежда се"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Зарежда се бързо"</string>
diff --git a/packages/SystemUI/res-keyguard/values-bn/strings.xml b/packages/SystemUI/res-keyguard/values-bn/strings.xml
index b544c14..0e8189f 100644
--- a/packages/SystemUI/res-keyguard/values-bn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-bn/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"পাসওয়ার্ড লিখুন"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ভুল পিন কোড দেওয়া হয়েছে।"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ভুল কার্ড।"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"সম্পূর্ণ চার্জ আছে"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"চার্জ হয়েছে"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ওয়্যারলেস পদ্ধতিতে চার্জ হচ্ছে"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • চার্জ হচ্ছে"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • দ্রুত চার্জ হচ্ছে"</string>
diff --git a/packages/SystemUI/res-keyguard/values-bs/strings.xml b/packages/SystemUI/res-keyguard/values-bs/strings.xml
index 8547bc8..33fe43f 100644
--- a/packages/SystemUI/res-keyguard/values-bs/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-bs/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Unesite lozinku"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Pogrešan PIN."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Nevažeća kartica."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Potpuno napunjen"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Napunjeno"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Bežično punjenje"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Punjenje"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Brzo punjenje"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ca/strings.xml b/packages/SystemUI/res-keyguard/values-ca/strings.xml
index ccde138..6c85fd3 100644
--- a/packages/SystemUI/res-keyguard/values-ca/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ca/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Introdueix la contrasenya"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"El codi PIN no és correcte."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"La targeta no és vàlida."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Completament carregada"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Bateria carregada"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • S\'està carregant sense fil"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • S\'està carregant"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • S\'està carregant ràpidament"</string>
diff --git a/packages/SystemUI/res-keyguard/values-cs/strings.xml b/packages/SystemUI/res-keyguard/values-cs/strings.xml
index 3adc279..e944312 100644
--- a/packages/SystemUI/res-keyguard/values-cs/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-cs/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Zadejte heslo"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Nesprávný kód PIN."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Neplatná karta."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Plně nabito"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Nabito"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Bezdrátové nabíjení"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Nabíjení"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Rychlé nabíjení"</string>
diff --git a/packages/SystemUI/res-keyguard/values-da/strings.xml b/packages/SystemUI/res-keyguard/values-da/strings.xml
index 0e6a1f3..ac1791b 100644
--- a/packages/SystemUI/res-keyguard/values-da/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-da/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Angiv din adgangskode"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Forkert pinkode."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ugyldigt kort."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fuldt opladet"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Opladet"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Trådløs opladning"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Oplader"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Oplader hurtigt"</string>
diff --git a/packages/SystemUI/res-keyguard/values-de/strings.xml b/packages/SystemUI/res-keyguard/values-de/strings.xml
index d44bfbc..0607c8a 100644
--- a/packages/SystemUI/res-keyguard/values-de/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-de/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Passwort eingeben"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Falscher PIN-Code."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ungültige Karte."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Vollständig aufgeladen"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Aufgeladen"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Kabelloses Laden"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Wird geladen"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Wird schnell geladen"</string>
diff --git a/packages/SystemUI/res-keyguard/values-el/strings.xml b/packages/SystemUI/res-keyguard/values-el/strings.xml
index 46b1d30..6997b16 100644
--- a/packages/SystemUI/res-keyguard/values-el/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-el/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Εισαγάγετε κωδικό πρόσβασης"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Λανθασμένος κωδικός PIN."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Μη έγκυρη κάρτα."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Πλήρως φορτισμένη"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Φορτίστηκε"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ασύρματη φόρτιση"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Φόρτιση"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Γρήγορη φόρτιση"</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml b/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml
index 5640b6d..19dd191 100644
--- a/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rAU/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Enter your password"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Incorrect PIN code."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Invalid card."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fully charged"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Charged"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging wirelessly"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging rapidly"</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rCA/strings.xml b/packages/SystemUI/res-keyguard/values-en-rCA/strings.xml
index 5836b72..acfb7e2 100644
--- a/packages/SystemUI/res-keyguard/values-en-rCA/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rCA/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Enter your password"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Incorrect PIN code."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Invalid card."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fully charged"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Charged"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging wirelessly"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging rapidly"</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml b/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml
index 5640b6d..19dd191 100644
--- a/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rGB/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Enter your password"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Incorrect PIN code."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Invalid card."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fully charged"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Charged"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging wirelessly"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging rapidly"</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml b/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml
index 5640b6d..19dd191 100644
--- a/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rIN/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Enter your password"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Incorrect PIN code."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Invalid card."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fully charged"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Charged"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging wirelessly"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Charging rapidly"</string>
diff --git a/packages/SystemUI/res-keyguard/values-en-rXC/strings.xml b/packages/SystemUI/res-keyguard/values-en-rXC/strings.xml
index fb968b7..b29bd60 100644
--- a/packages/SystemUI/res-keyguard/values-en-rXC/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-en-rXC/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‏‎‏‎‏‏‏‎‎‏‏‏‎‎‏‎‏‎‎‏‏‎‎‎‏‎‏‏‏‏‏‎‏‎‏‎‏‎‏‎‏‏‏‎‎‏‎‏‎‎‎‏‏‏‎‎‏‎‏‎‎Enter your password‎‏‎‎‏‎"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‏‎‏‎‏‏‎‎‎‏‎‎‎‎‏‏‎‎‎‏‎‎‎‏‏‏‏‎‏‎‏‏‎‏‏‎‎‎‏‎‎‏‏‏‏‏‏‎‎‎‎‎‏‏‏‏‎‎‎Incorrect PIN code.‎‏‎‎‏‎"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‎‎‎‎‏‏‎‏‏‏‏‎‎‏‏‎‎‎‎‏‏‏‎‏‎‎‎‎‏‎‎‏‎‎‎‏‏‏‏‏‏‏‎‎‎‏‏‏‎‏‏‎‏‏‏‎‎‎‎Invalid Card.‎‏‎‎‏‎"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‏‏‎‎‎‎‎‎‏‎‏‎‎‏‏‎‏‎‏‏‎‎‏‎‎‏‏‎‏‎‎‎‏‏‎‎‏‎‎‎‎‏‎‏‏‏‎‏‎‏‎‎‎‏‎‎‏‎‏‎Fully charged‎‏‎‎‏‎"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‏‏‎‏‏‎‏‎‏‏‏‎‏‎‎‏‏‎‏‎‎‎‏‎‎‏‏‏‏‎‏‏‎‏‏‏‎‎‎‎‎‎‏‎‏‎‏‎‏‏‎‏‎‎‏‎‏‎‏‎Charged‎‏‎‎‏‎"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‏‎‎‏‎‏‎‎‎‎‏‏‎‎‏‎‎‏‎‏‏‏‎‏‏‎‏‎‎‏‏‎‏‎‏‏‎‏‎‏‏‎‎‎‏‏‏‎‎‏‏‎‎‎‎‏‏‎‎‎‎‏‎‎‏‏‎<xliff:g id="PERCENTAGE">%s</xliff:g>‎‏‎‎‏‏‏‎ • Charging wirelessly‎‏‎‎‏‎"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‎‏‏‏‏‎‏‏‏‏‎‎‏‏‏‏‏‎‏‏‎‎‏‏‏‎‎‎‏‎‏‎‏‏‏‏‎‏‎‏‏‏‏‏‎‎‎‏‎‎‏‏‏‎‎‏‎‏‏‎‎‏‎‎‏‏‎<xliff:g id="PERCENTAGE">%s</xliff:g>‎‏‎‎‏‏‏‎ • Charging‎‏‎‎‏‎"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‎‎‏‏‎‎‏‎‎‎‏‎‎‏‎‎‏‏‎‏‏‎‎‏‏‏‏‎‎‎‎‎‎‏‏‏‏‏‏‏‏‏‎‏‎‏‏‏‎‎‏‏‏‏‎‏‏‏‏‎‎‎‏‎‎‏‏‎<xliff:g id="PERCENTAGE">%s</xliff:g>‎‏‎‎‏‏‏‎ • Charging rapidly‎‏‎‎‏‎"</string>
diff --git a/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml b/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml
index 727cbad..aa5c4e0 100644
--- a/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-es-rUS/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Ingresa tu contraseña"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Código PIN incorrecto"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Tarjeta no válida"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Carga completa"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Cargada"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando de manera inalámbrica"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando rápidamente"</string>
diff --git a/packages/SystemUI/res-keyguard/values-es/strings.xml b/packages/SystemUI/res-keyguard/values-es/strings.xml
index 870741e..5f9a456 100644
--- a/packages/SystemUI/res-keyguard/values-es/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-es/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Introduce tu contraseña"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"El código PIN es incorrecto."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Tarjeta no válida."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Carga completa"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Cargada"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando sin cables"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando rápidamente"</string>
diff --git a/packages/SystemUI/res-keyguard/values-et/strings.xml b/packages/SystemUI/res-keyguard/values-et/strings.xml
index 7e03a5c..c555ced 100644
--- a/packages/SystemUI/res-keyguard/values-et/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-et/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Sisestage parool"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Vale PIN-kood."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Kehtetu kaart."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Täielikult laetud"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Laetud"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Juhtmeta laadimine"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Laadimine"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Kiirlaadimine"</string>
@@ -117,7 +117,7 @@
     <string name="kg_pin_accepted" msgid="7637293533973802143">"Kood on õige."</string>
     <string name="keyguard_carrier_default" msgid="4274828292998453695">"Teenus puudub."</string>
     <string name="accessibility_ime_switch_button" msgid="2695096475319405612">"Vaheta sisestusmeetodit"</string>
-    <string name="airplane_mode" msgid="3807209033737676010">"Lennurežiim"</string>
+    <string name="airplane_mode" msgid="3807209033737676010">"Lennukirežiim"</string>
     <string name="kg_prompt_reason_restart_pattern" msgid="7246972020562621506">"Pärast seadme taaskäivitamist tuleb sisestada muster"</string>
     <string name="kg_prompt_reason_restart_pin" msgid="6303592361322290145">"Pärast seadme taaskäivitamist tuleb sisestada PIN-kood"</string>
     <string name="kg_prompt_reason_restart_password" msgid="6984641181515902406">"Pärast seadme taaskäivitamist tuleb sisestada parool"</string>
diff --git a/packages/SystemUI/res-keyguard/values-eu/strings.xml b/packages/SystemUI/res-keyguard/values-eu/strings.xml
index 8ad942b..612b2de 100644
--- a/packages/SystemUI/res-keyguard/values-eu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-eu/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Idatzi pasahitza"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN kode hori ez da zuzena."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Txartelak ez du balio."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Erabat kargatuta"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Kargatuta"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Hari gabe kargatzen"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Kargatzen"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Bizkor kargatzen"</string>
diff --git a/packages/SystemUI/res-keyguard/values-fa/strings.xml b/packages/SystemUI/res-keyguard/values-fa/strings.xml
index 9c9de22..0bf01d9 100644
--- a/packages/SystemUI/res-keyguard/values-fa/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fa/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"گذرواژه‌تان را وارد کنید"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"کد پین اشتباه است."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"کارت نامعتبر"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"شارژ کامل است"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"شارژ کامل شد"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • درحال شارژ بی‌سیم"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • درحال شارژ شدن"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • درحال شارژ سریع"</string>
diff --git a/packages/SystemUI/res-keyguard/values-fi/strings.xml b/packages/SystemUI/res-keyguard/values-fi/strings.xml
index 66f1de5..9b727a4 100644
--- a/packages/SystemUI/res-keyguard/values-fi/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fi/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Kirjoita salasana"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Väärä PIN-koodi"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Virheellinen kortti"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Täyteen ladattu"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Ladattu"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ladataan langattomasti"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ladataan"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ladataan nopeasti"</string>
@@ -74,7 +74,7 @@
     <string name="kg_sim_pin_instructions_multi" msgid="1643757228644271861">"Anna operaattorin <xliff:g id="CARRIER">%1$s</xliff:g> SIM-kortin PIN-koodi."</string>
     <string name="kg_sim_lock_esim_instructions" msgid="4416732549172148542">"<xliff:g id="PREVIOUS_MSG">%1$s</xliff:g> Poista eSIM käytöstä, jos haluat käyttää laitetta ilman mobiililiittymää."</string>
     <string name="kg_pin_instructions" msgid="4069609316644030034">"Anna PIN-koodi."</string>
-    <string name="kg_password_instructions" msgid="136952397352976538">"Anna salasana"</string>
+    <string name="kg_password_instructions" msgid="136952397352976538">"Lisää salasana"</string>
     <string name="kg_puk_enter_puk_hint" msgid="2288964170039899277">"SIM-kortti on nyt poistettu käytöstä. Jatka antamalla PUK-koodi. Saat lisätietoja ottamalla yhteyttä operaattoriin."</string>
     <string name="kg_puk_enter_puk_hint_multi" msgid="1373131883510840794">"Operaattorin <xliff:g id="CARRIER">%1$s</xliff:g> SIM-kortti on nyt lukittu. Jatka antamalla PUK-koodi. Saat lisätietoja operaattoriltasi."</string>
     <string name="kg_puk_enter_pin_hint" msgid="3137789674920391087">"Anna haluamasi PIN-koodi."</string>
diff --git a/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml b/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml
index 66c7c86..a86cdbe 100644
--- a/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fr-rCA/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Entrez votre mot de passe"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"NIP erroné."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Cette carte n\'est pas valide."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Complètement chargé"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Chargé"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • En recharge sans fil"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"En recharge : <xliff:g id="PERCENTAGE">%s</xliff:g>"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"En recharge rapide : <xliff:g id="PERCENTAGE">%s</xliff:g>"</string>
diff --git a/packages/SystemUI/res-keyguard/values-fr/strings.xml b/packages/SystemUI/res-keyguard/values-fr/strings.xml
index d6aa5d2..70075ec 100644
--- a/packages/SystemUI/res-keyguard/values-fr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-fr/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Saisissez votre mot de passe"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Le code est incorrect."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Carte non valide."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Complètement chargée"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Chargé"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Recharge sans fil"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Recharge…"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Recharge rapide…"</string>
diff --git a/packages/SystemUI/res-keyguard/values-gl/strings.xml b/packages/SystemUI/res-keyguard/values-gl/strings.xml
index e6b10a0..9504a3e 100644
--- a/packages/SystemUI/res-keyguard/values-gl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-gl/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Introduce o contrasinal"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Código PIN incorrecto"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"A tarxeta non é válida."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Batería totalmente cargada"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Cargada"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando sen fíos"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Cargando rapidamente"</string>
diff --git a/packages/SystemUI/res-keyguard/values-gu/strings.xml b/packages/SystemUI/res-keyguard/values-gu/strings.xml
index 025462e..a2370d0 100644
--- a/packages/SystemUI/res-keyguard/values-gu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-gu/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"તમારો પાસવર્ડ દાખલ કરો"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ખોટો પિન કોડ."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"અમાન્ય કાર્ડ."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"સંપૂર્ણપણે ચાર્જ થયેલ"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ચાર્જ થઈ ગયું"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • વાયરલેસથી ચાર્જિંગ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ચાર્જિંગ"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ઝડપથી ચાર્જિંગ"</string>
diff --git a/packages/SystemUI/res-keyguard/values-hi/strings.xml b/packages/SystemUI/res-keyguard/values-hi/strings.xml
index 2de75e4..f8e99a6 100644
--- a/packages/SystemUI/res-keyguard/values-hi/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hi/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"अपना पासवर्ड डालें"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"गलत पिन कोड."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"गलत कार्ड."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"पूरी तरह चार्ज हो गया"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"चार्ज हो गई है"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • वायरलेस तरीके से चार्ज हो रहा है"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • चार्ज हो रहा है"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • तेज़ चार्ज हो रहा है"</string>
diff --git a/packages/SystemUI/res-keyguard/values-hr/strings.xml b/packages/SystemUI/res-keyguard/values-hr/strings.xml
index c4f7bba..1c9396a 100644
--- a/packages/SystemUI/res-keyguard/values-hr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hr/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Unesite zaporku"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN kôd nije točan."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Nevažeća kartica."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Potpuno napunjena baterija"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Napunjeno"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • bežično punjenje"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • punjenje"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • brzo punjenje"</string>
diff --git a/packages/SystemUI/res-keyguard/values-hu/strings.xml b/packages/SystemUI/res-keyguard/values-hu/strings.xml
index 06142bc..ea5ab94 100644
--- a/packages/SystemUI/res-keyguard/values-hu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hu/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Adja meg jelszavát"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Helytelen PIN-kód."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Érvénytelen kártya."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Teljesen feltöltve"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Feltöltve"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Vezeték nélküli töltés"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Töltés"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Gyors töltés"</string>
diff --git a/packages/SystemUI/res-keyguard/values-hy/strings.xml b/packages/SystemUI/res-keyguard/values-hy/strings.xml
index f501fcc..b34eced 100644
--- a/packages/SystemUI/res-keyguard/values-hy/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-hy/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Մուտքագրեք գաղտնաբառը"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN կոդը սխալ է։"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Սխալ քարտ"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Ամբողջությամբ լիցքավորված է"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Լիցքավորված է"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Անլար լիցքավորում"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Լիցքավորում"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Արագ լիցքավորում"</string>
diff --git a/packages/SystemUI/res-keyguard/values-in/strings.xml b/packages/SystemUI/res-keyguard/values-in/strings.xml
index 64f396e..3dd6c91 100644
--- a/packages/SystemUI/res-keyguard/values-in/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-in/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Masukkan sandi"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Kode PIN salah."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Kartu Tidak Valid"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Terisi penuh"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Terisi"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Mengisi daya secara nirkabel"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Mengisi daya"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Mengisi daya dengan cepat"</string>
diff --git a/packages/SystemUI/res-keyguard/values-is/strings.xml b/packages/SystemUI/res-keyguard/values-is/strings.xml
index aa33215..c09dcc6 100644
--- a/packages/SystemUI/res-keyguard/values-is/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-is/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Sláðu inn aðgangsorðið þitt"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Rangt PIN-númer."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ógilt kort."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fullhlaðin"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Fullhlaðin"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Í þráðlausri hleðslu"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Í hleðslu"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Hröð hleðsla"</string>
diff --git a/packages/SystemUI/res-keyguard/values-it/strings.xml b/packages/SystemUI/res-keyguard/values-it/strings.xml
index 761640c..3f5cfbb 100644
--- a/packages/SystemUI/res-keyguard/values-it/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-it/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Inserisci la password"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Codice PIN errato."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Scheda non valida."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Completamente carica"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Carico"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • In carica wireless"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • In carica"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ricarica veloce"</string>
diff --git a/packages/SystemUI/res-keyguard/values-iw/strings.xml b/packages/SystemUI/res-keyguard/values-iw/strings.xml
index e72c808..95caf91 100644
--- a/packages/SystemUI/res-keyguard/values-iw/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-iw/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"יש להזין סיסמה"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"קוד הגישה שגוי"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"כרטיס לא חוקי."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"טעונה במלואה"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"הסוללה טעונה"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • בטעינה אלחוטית"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • בטעינה"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • בטעינה מהירה"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ja/strings.xml b/packages/SystemUI/res-keyguard/values-ja/strings.xml
index 27adb8c..9872a07 100644
--- a/packages/SystemUI/res-keyguard/values-ja/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ja/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"パスワードを入力してください"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN コードが無効です。"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"無効なカードです。"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"充電完了"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"充電が完了しました"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ワイヤレス充電中"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 充電中"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 急速充電中"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ka/strings.xml b/packages/SystemUI/res-keyguard/values-ka/strings.xml
index d165230..c3b5047 100644
--- a/packages/SystemUI/res-keyguard/values-ka/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ka/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"შეიყვანეთ პაროლი"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN-კოდი არასწორია."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ბარათი არასწორია."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"ბოლომდე დატენილი"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"დატენილია"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • იტენება უსადენოდ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • იტენება"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • სწრაფად იტენება"</string>
diff --git a/packages/SystemUI/res-keyguard/values-kk/strings.xml b/packages/SystemUI/res-keyguard/values-kk/strings.xml
index 8522346..e8741f9 100644
--- a/packages/SystemUI/res-keyguard/values-kk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-kk/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Құпия сөзді енгізіңіз"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN коды қате"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Жарамсыз карта."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Толық зарядталды"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Зарядталды"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Сымсыз зарядталуда"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Зарядталуда"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Жылдам зарядталуда"</string>
diff --git a/packages/SystemUI/res-keyguard/values-km/strings.xml b/packages/SystemUI/res-keyguard/values-km/strings.xml
index 7b4266a..d48de15 100644
--- a/packages/SystemUI/res-keyguard/values-km/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-km/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"បញ្ចូល​ពាក្យ​សម្ងាត់​របស់អ្នក"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"កូដ PIN មិន​ត្រឹមត្រូវ​ទេ។"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"បណ្ណមិនត្រឹមត្រូវទេ។"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"បានសាក​ថ្មពេញ"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"បាន​សាក​ថ្ម"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • កំពុងសាកថ្ម​ឥតខ្សែ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • កំពុង​សាកថ្ម"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • កំពុង​សាកថ្មយ៉ាង​ឆាប់រហ័ស"</string>
diff --git a/packages/SystemUI/res-keyguard/values-kn/strings.xml b/packages/SystemUI/res-keyguard/values-kn/strings.xml
index eaaa829..7a6a0bf 100644
--- a/packages/SystemUI/res-keyguard/values-kn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-kn/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"ನಿಮ್ಮ ಪಾಸ್‌ವರ್ಡ್ ನಮೂದಿಸಿ"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ತಪ್ಪಾದ ಪಿನ್‌ ಕೋಡ್."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ಅಮಾನ್ಯ ಕಾರ್ಡ್."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"ಪೂರ್ಣವಾಗಿ ಚಾರ್ಜ್ ಆಗಿದೆ"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ಚಾರ್ಜ್ ಆಗಿದೆ"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ವೈರ್‌ಲೆಸ್ ಆಗಿ ಚಾರ್ಜ್ ಆಗುತ್ತಿದೆ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ಚಾರ್ಜ್‌ ಮಾಡಲಾಗುತ್ತಿದೆ"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ವೇಗವಾಗಿ ಚಾರ್ಜ್‌ಮಾಡಲಾಗುತ್ತಿದೆ"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ko/strings.xml b/packages/SystemUI/res-keyguard/values-ko/strings.xml
index ca84937..9c1ffc8 100644
--- a/packages/SystemUI/res-keyguard/values-ko/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ko/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"비밀번호 입력"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"잘못된 PIN 코드입니다."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"유효하지 않은 카드"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"충전 완료"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"충전됨"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 무선 충전 중"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 충전 중"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 고속 충전 중"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ky/strings.xml b/packages/SystemUI/res-keyguard/values-ky/strings.xml
index 805a567..a106000 100644
--- a/packages/SystemUI/res-keyguard/values-ky/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ky/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Сырсөзүңүздү киргизиңиз"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN-код туура эмес."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"SIM-карта жараксыз."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Толук кубатталды"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Кубатталды"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Зымсыз кубатталууда"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Кубатталууда"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Тез кубатталууда"</string>
diff --git a/packages/SystemUI/res-keyguard/values-lo/strings.xml b/packages/SystemUI/res-keyguard/values-lo/strings.xml
index 1418d27..e4d66a7 100644
--- a/packages/SystemUI/res-keyguard/values-lo/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-lo/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"ປ້ອນລະຫັດຜ່ານຂອງທ່ານ"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ລະຫັດ PIN ບໍ່ຖືກຕ້ອງ."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ບັດບໍ່ຖືກຕ້ອງ."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"ສາກເຕັມແລ້ວ"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ສາກເຕັມແລ້ວ."</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ກຳ​ລັງ​ສາກ​ໄຟໄຮ້​ສາຍ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ກຳລັງສາກ"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ກຳລັງສາກແບບດ່ວນ"</string>
diff --git a/packages/SystemUI/res-keyguard/values-lt/strings.xml b/packages/SystemUI/res-keyguard/values-lt/strings.xml
index bbd25b2..30e7cad 100644
--- a/packages/SystemUI/res-keyguard/values-lt/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-lt/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Įveskite slaptažodį"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Netinkamas PIN kodas."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Netinkama kortelė."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Visiškai įkrautas"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Įkrauta"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Kraunama be laidų"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Įkraunama"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Greitai įkraunama"</string>
diff --git a/packages/SystemUI/res-keyguard/values-lv/strings.xml b/packages/SystemUI/res-keyguard/values-lv/strings.xml
index 58ca8ce..8cafcd3 100644
--- a/packages/SystemUI/res-keyguard/values-lv/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-lv/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Ievadiet paroli"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN kods nav pareizs."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Nederīga karte."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Pilnībā uzlādēts"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Akumulators uzlādēts"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Notiek bezvadu uzlāde"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Notiek uzlāde"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Notiek ātrā uzlāde"</string>
diff --git a/packages/SystemUI/res-keyguard/values-mk/strings.xml b/packages/SystemUI/res-keyguard/values-mk/strings.xml
index 1ffd8a4..e2ab170 100644
--- a/packages/SystemUI/res-keyguard/values-mk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-mk/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Внесете ја лозинката"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Погрешен PIN-код."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Неважечка картичка."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Целосно полна"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Полна"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Се полни безжично"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Се полни"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Брзо полнење"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ml/strings.xml b/packages/SystemUI/res-keyguard/values-ml/strings.xml
index 1f60c73..33765b4 100644
--- a/packages/SystemUI/res-keyguard/values-ml/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ml/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"നിങ്ങളുടെ പാസ്‌വേഡ് നല്‍‌കുക"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"പിൻ കോഡ് തെറ്റാണ്."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"അസാധുവായ കാർഡ്."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"പൂർണ്ണമായി ചാർജ് ചെയ്‌തു"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ചാർജായി"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • വയർലെസ്സ് ആയി ചാർജ് ചെയ്യുന്നു"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ചാർജ് ചെയ്യുന്നു"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • വേഗത്തിൽ ചാർജ് ചെയ്യുന്നു"</string>
diff --git a/packages/SystemUI/res-keyguard/values-mn/strings.xml b/packages/SystemUI/res-keyguard/values-mn/strings.xml
index 55dd70c..3451fb8 100644
--- a/packages/SystemUI/res-keyguard/values-mn/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-mn/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Нууц үгээ оруулна уу"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ПИН код буруу байна."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Карт хүчингүй байна."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Бүрэн цэнэглэсэн"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Цэнэглэсэн"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Утасгүй цэнэглэж байна"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Цэнэглэж байна"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Хурдан цэнэглэж байна"</string>
diff --git a/packages/SystemUI/res-keyguard/values-mr/strings.xml b/packages/SystemUI/res-keyguard/values-mr/strings.xml
index 0ba82e0..e86fa10 100644
--- a/packages/SystemUI/res-keyguard/values-mr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-mr/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"तुमचा पासवर्ड एंटर करा"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"चुकीचा पिन कोड."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"अवैध कार्ड."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"पूर्णपणे चार्ज"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"चार्ज झाली"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • वायरलेस पद्धतीने चार्ज करत आहे"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • चार्ज होत आहे"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • वेगाने चार्ज होत आहे"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ms/strings.xml b/packages/SystemUI/res-keyguard/values-ms/strings.xml
index 17e1056..80ccd3e 100644
--- a/packages/SystemUI/res-keyguard/values-ms/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ms/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Masukkan kata laluan anda"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Kod PIN salah."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Kad Tidak Sah."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Dicas penuh"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Sudah dicas"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Mengecas secara wayarles"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Mengecas"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Mengecas dengan cepat"</string>
diff --git a/packages/SystemUI/res-keyguard/values-my/strings.xml b/packages/SystemUI/res-keyguard/values-my/strings.xml
index 28fe2b2..c1fa6be 100644
--- a/packages/SystemUI/res-keyguard/values-my/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-my/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"သင့်စကားဝှက် ထည့်ပါ"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ပင်နံပါတ် မှားနေသည်။"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ကတ် မမှန်ကန်ပါ။"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"အားအပြည့်သွင်းထားသည်"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"အားသွင်းပြီးပါပြီ"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ကြိုးမဲ့ အားသွင်းနေသည်"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • အားသွင်းနေသည်"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • အမြန်အားသွင်းနေသည်"</string>
diff --git a/packages/SystemUI/res-keyguard/values-nb/strings.xml b/packages/SystemUI/res-keyguard/values-nb/strings.xml
index 692dcad..af99aa7 100644
--- a/packages/SystemUI/res-keyguard/values-nb/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-nb/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Skriv inn passordet ditt"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Feil PIN-kode."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ugyldig kort."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fulladet"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Oppladet"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Lader trådløst"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Lader"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Lader raskt"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ne/strings.xml b/packages/SystemUI/res-keyguard/values-ne/strings.xml
index 8102021..82a4a19 100644
--- a/packages/SystemUI/res-keyguard/values-ne/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ne/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"आफ्नो पासवर्ड प्रविष्ट गर्नु…"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN कोड गलत छ।"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"अमान्य कार्ड।"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"पूर्ण चार्ज भएको"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"चार्ज भयो"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • तारविनै चार्ज गर्दै"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • चार्ज गरिँदै"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • द्रुत गतिमा चार्ज गरिँदै"</string>
diff --git a/packages/SystemUI/res-keyguard/values-nl/strings.xml b/packages/SystemUI/res-keyguard/values-nl/strings.xml
index c79f2f7..c533956 100644
--- a/packages/SystemUI/res-keyguard/values-nl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-nl/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Geef je wachtwoord op"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Onjuiste pincode."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ongeldige kaart."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Volledig opgeladen"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Opgeladen"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Draadloos opladen"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Opladen"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Snel opladen"</string>
diff --git a/packages/SystemUI/res-keyguard/values-or/strings.xml b/packages/SystemUI/res-keyguard/values-or/strings.xml
index c28561a..258c2a8 100644
--- a/packages/SystemUI/res-keyguard/values-or/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-or/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"ନିଜ ପାସ୍‌ୱର୍ଡ ଲେଖନ୍ତୁ"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ଭୁଲ PIN କୋଡ୍।"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ଅମାନ୍ୟ କାର୍ଡ।"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"ସମ୍ପୂର୍ଣ୍ଣ ଭାବରେ ଚାର୍ଜ ହୋ‍ଇଗଲା"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ଚାର୍ଜ ହୋଇଗଲା"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"ୱାୟାର୍‍ଲେସ୍‍ଭାବରେ <xliff:g id="PERCENTAGE">%s</xliff:g> • ଚାର୍ଜ ହୋଇଛି"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ଚାର୍ଜ ହେଉଛି"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ଦ୍ରୁତ ଭାବେ ଚାର୍ଜ ହେଉଛି"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pa/strings.xml b/packages/SystemUI/res-keyguard/values-pa/strings.xml
index 01b5d8e..2c3f64e 100644
--- a/packages/SystemUI/res-keyguard/values-pa/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pa/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"ਆਪਣਾ ਪਾਸਵਰਡ ਦਾਖਲ ਕਰੋ"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"ਗਲਤ ਪਿੰਨ ਕੋਡ।"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"ਅਵੈਧ ਕਾਰਡ।"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"ਪੂਰਾ ਚਾਰਜ"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ਚਾਰਜ ਹੋ ਗਿਆ"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ਬਿਨਾਂ ਤਾਰ ਤੋਂ ਚਾਰਜ ਹੋ ਰਿਹਾ ਹੈ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ਚਾਰਜ ਹੋ ਰਿਹਾ ਹੈ"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ਤੇਜ਼ੀ ਨਾਲ ਚਾਰਜ ਹੋ ਰਿਹਾ ਹੈ"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pl/strings.xml b/packages/SystemUI/res-keyguard/values-pl/strings.xml
index f86a082..b88440f 100644
--- a/packages/SystemUI/res-keyguard/values-pl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pl/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Wpisz hasło"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Nieprawidłowy kod PIN."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Nieprawidłowa karta."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Bateria w pełni naładowana"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Naładowana"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ładowanie bezprzewodowe"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ładowanie"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Szybkie ładowanie"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml b/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml
index 436dd55..ed552d4 100644
--- a/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pt-rBR/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Digite sua senha"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Código PIN incorreto."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Cartão inválido."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Carga completa"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Carregada"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Carregando sem fio"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Carregando"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Carregando rapidamente"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml b/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
index 2ba4268..5dd0beb 100644
--- a/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pt-rPT/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Introduza a palavra-passe."</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Código PIN incorreto."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Cartão inválido."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Totalmente carregada"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Carregada"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • A carregar sem fios"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • A carregar…"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • A carregar rapidamente…"</string>
diff --git a/packages/SystemUI/res-keyguard/values-pt/strings.xml b/packages/SystemUI/res-keyguard/values-pt/strings.xml
index 436dd55..ed552d4 100644
--- a/packages/SystemUI/res-keyguard/values-pt/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-pt/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Digite sua senha"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Código PIN incorreto."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Cartão inválido."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Carga completa"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Carregada"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Carregando sem fio"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Carregando"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Carregando rapidamente"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ro/strings.xml b/packages/SystemUI/res-keyguard/values-ro/strings.xml
index 6fdc958..13e15e3 100644
--- a/packages/SystemUI/res-keyguard/values-ro/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ro/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Introduceți parola"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Cod PIN incorect."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Card nevalid"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Complet încărcată"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Încărcată"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Se încarcă wireless"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Se încarcă"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Se încarcă rapid"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ru/strings.xml b/packages/SystemUI/res-keyguard/values-ru/strings.xml
index f9bd05b..781a3e4 100644
--- a/packages/SystemUI/res-keyguard/values-ru/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ru/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Введите пароль"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Неверный PIN-код."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ошибка SIM-карты."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Аккумулятор полностью заряжен"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Батарея заряжена"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Беспроводная зарядка"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"Идет зарядка (<xliff:g id="PERCENTAGE">%s</xliff:g>)"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"Идет быстрая зарядка (<xliff:g id="PERCENTAGE">%s</xliff:g>)"</string>
diff --git a/packages/SystemUI/res-keyguard/values-si/strings.xml b/packages/SystemUI/res-keyguard/values-si/strings.xml
index e40be05..e51aa96 100644
--- a/packages/SystemUI/res-keyguard/values-si/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-si/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"ඔබේ මුරපදය ඇතුළු කරන්න"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"වැරදි PIN කේතයකි."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"වලංගු නොවන කාඩ්පත."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"සම්පූර්ණයෙන් ආරෝපණය වී ඇත"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"අරෝපිතයි"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • නොරැහැන්ව ආරෝපණ කෙරේ"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ආරෝපණය වෙමින්"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • වේගයෙන් ආරෝපණය වෙමින්"</string>
diff --git a/packages/SystemUI/res-keyguard/values-sk/strings.xml b/packages/SystemUI/res-keyguard/values-sk/strings.xml
index e7800e9..4fe1e4f 100644
--- a/packages/SystemUI/res-keyguard/values-sk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sk/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Zadajte heslo"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Nesprávny kód PIN."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Neplatná karta."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Úplne nabité"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Nabité"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Nabíja sa bezdrôtovo"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Nabíja sa"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Nabíja sa rýchlo"</string>
diff --git a/packages/SystemUI/res-keyguard/values-sl/strings.xml b/packages/SystemUI/res-keyguard/values-sl/strings.xml
index cce3a31..822e162 100644
--- a/packages/SystemUI/res-keyguard/values-sl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sl/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Vnesite geslo"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Napačna koda PIN."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Neveljavna kartica"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Popolnoma napolnjen"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Akumulator napolnjen"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • brezžično polnjenje"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • polnjenje"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • hitro polnjenje"</string>
diff --git a/packages/SystemUI/res-keyguard/values-sq/strings.xml b/packages/SystemUI/res-keyguard/values-sq/strings.xml
index e4b37d0..4636e6a 100644
--- a/packages/SystemUI/res-keyguard/values-sq/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sq/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Fut fjalëkalimin"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Kodi PIN është i pasaktë."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Karta e pavlefshme."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"I ngarkuar plotësisht"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"I ngarkuar"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Po karikohet me valë"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Po karikohet"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Po karikohet me shpejtësi"</string>
diff --git a/packages/SystemUI/res-keyguard/values-sr/strings.xml b/packages/SystemUI/res-keyguard/values-sr/strings.xml
index 1e6de94..033e93b 100644
--- a/packages/SystemUI/res-keyguard/values-sr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sr/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Унесите лозинку"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN кôд је нетачан."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Неважећа картица."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Напуњена је у потпуности"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Напуњена је"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Бежично пуњење"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Пуни се"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Брзо се пуни"</string>
diff --git a/packages/SystemUI/res-keyguard/values-sv/strings.xml b/packages/SystemUI/res-keyguard/values-sv/strings.xml
index 4cca176..8d7be97 100644
--- a/packages/SystemUI/res-keyguard/values-sv/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sv/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Ange ditt lösenord"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Fel pinkod."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ogiltigt kort."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Fulladdad"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Laddat"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Laddas trådlöst"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Laddas"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Laddas snabbt"</string>
diff --git a/packages/SystemUI/res-keyguard/values-sw/strings.xml b/packages/SystemUI/res-keyguard/values-sw/strings.xml
index df51859..5ab4d07 100644
--- a/packages/SystemUI/res-keyguard/values-sw/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-sw/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Weka nenosiri lako"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Nambari ya PIN si sahihi."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Kadi si Sahihi."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Imejaa chaji"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Betri imejaa"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Inachaji bila kutumia waya"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Inachaji"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Inachaji kwa kasi"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ta/strings.xml b/packages/SystemUI/res-keyguard/values-ta/strings.xml
index 9aa1972..fa75b4d 100644
--- a/packages/SystemUI/res-keyguard/values-ta/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ta/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"கடவுச்சொல்லை உள்ளிடுக"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"தவறான பின் குறியீடு."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"செல்லாத சிம் கார்டு."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"முழுவதுமாகச் சார்ஜ் ஆகிவிட்டது"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"சார்ஜ் செய்யப்பட்டது"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • வயர்லெஸ் முறையில் சார்ஜாகிறது"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • சார்ஜாகிறது"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • வேகமாகச் சார்ஜாகிறது"</string>
diff --git a/packages/SystemUI/res-keyguard/values-te/strings.xml b/packages/SystemUI/res-keyguard/values-te/strings.xml
index 925d673..ad89ba7 100644
--- a/packages/SystemUI/res-keyguard/values-te/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-te/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"మీ పాస్‌వర్డ్‌ను నమోదు చేయండి"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"పిన్ కోడ్ తప్పు."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"చెల్లని కార్డ్."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"పూర్తిగా ఛార్జ్ చేయబడింది"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ఛార్జ్ చేయబడింది"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • వైర్‌ లేకుండా ఛార్జ్ అవుతోంది"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • ఛార్జ్ అవుతోంది"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • వేగంగా ఛార్జ్ అవుతోంది"</string>
diff --git a/packages/SystemUI/res-keyguard/values-th/strings.xml b/packages/SystemUI/res-keyguard/values-th/strings.xml
index c439c32..caa60f3 100644
--- a/packages/SystemUI/res-keyguard/values-th/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-th/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"ป้อนรหัสผ่าน"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"รหัส PIN ไม่ถูกต้อง"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"การ์ดไม่ถูกต้อง"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"ชาร์จเต็มแล้ว"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"ชาร์จแล้ว"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • กำลังชาร์จแบบไร้สาย"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • กำลังชาร์จ"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • กำลังชาร์จอย่างเร็ว"</string>
diff --git a/packages/SystemUI/res-keyguard/values-tl/strings.xml b/packages/SystemUI/res-keyguard/values-tl/strings.xml
index a9ca1b6..65b87e3 100644
--- a/packages/SystemUI/res-keyguard/values-tl/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-tl/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Ilagay ang iyong password"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Mali ang PIN code."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Di-wasto ang Card."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Puno na ang baterya"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Tapos nang mag-charge"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Wireless na nagcha-charge"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Nagcha-charge"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Mabilis na nagcha-charge"</string>
diff --git a/packages/SystemUI/res-keyguard/values-tr/strings.xml b/packages/SystemUI/res-keyguard/values-tr/strings.xml
index 4e81505..c35e99e 100644
--- a/packages/SystemUI/res-keyguard/values-tr/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-tr/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Şifrenizi girin"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Yanlış PIN kodu."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Geçersiz Kart."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Tamamen şarj edildi"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Şarj oldu"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Kablosuz olarak şarj ediliyor"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Şarj oluyor"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Hızlı şarj oluyor"</string>
diff --git a/packages/SystemUI/res-keyguard/values-uk/strings.xml b/packages/SystemUI/res-keyguard/values-uk/strings.xml
index c683e32..c2b9419 100644
--- a/packages/SystemUI/res-keyguard/values-uk/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-uk/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Введіть пароль"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Неправильний PIN-код."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Недійсна картка."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Повністю заряджений"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Заряджено"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Бездротове заряджання"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Заряджання"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Швидке заряджання"</string>
diff --git a/packages/SystemUI/res-keyguard/values-ur/strings.xml b/packages/SystemUI/res-keyguard/values-ur/strings.xml
index 96b949b..8a74093 100644
--- a/packages/SystemUI/res-keyguard/values-ur/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-ur/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"اپنا پاس ورڈ درج کریں"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"‏غلط PIN کوڈ۔"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"غلط کارڈ۔"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"مکمل طور پر چارج ہو گيا"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"چارج ہوگئی"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • وائرلیس طریقے سے چارج ہو رہا ہے"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • چارج ہو رہا ہے"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • تیزی سے چارج ہو رہا ہے"</string>
diff --git a/packages/SystemUI/res-keyguard/values-uz/strings.xml b/packages/SystemUI/res-keyguard/values-uz/strings.xml
index 80509ac..5bf38ec 100644
--- a/packages/SystemUI/res-keyguard/values-uz/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-uz/strings.xml
@@ -33,9 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Parolni kiriting"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN kodi xato."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"SIM karta yaroqsiz."</string>
-    <!-- String.format failed for translation -->
-    <!-- no translation found for keyguard_charged (3316115607283493413) -->
-    <skip />
+    <string name="keyguard_charged" msgid="2222329688813033109">"Batareya quvvati to‘ldi"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Simsiz quvvatlanyapti"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Quvvat olmoqda"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Tezkor quvvat olmoqda"</string>
diff --git a/packages/SystemUI/res-keyguard/values-vi/strings.xml b/packages/SystemUI/res-keyguard/values-vi/strings.xml
index b8c1998..c50891e 100644
--- a/packages/SystemUI/res-keyguard/values-vi/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-vi/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Nhập mật khẩu của bạn"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Mã PIN không chính xác."</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Thẻ không hợp lệ."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Đã sạc đầy"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Đã sạc đầy"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Đang sạc không dây"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Đang sạc"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Đang sạc nhanh"</string>
diff --git a/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml b/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml
index 88fc363..e4438f9 100644
--- a/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zh-rCN/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"输入您的密码"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN 码有误。"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"SIM 卡无效。"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"充电完成"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"已充满电"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 正在无线充电"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 正在充电"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 正在快速充电"</string>
diff --git a/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml b/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml
index 2d84106..4134527 100644
--- a/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zh-rHK/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"請輸入密碼"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN 碼不正確。"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"SIM 卡無效。"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"充電完成"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"已完成充電"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 無線充電中"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 正在充電"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 正在快速充電"</string>
diff --git a/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml b/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml
index 18b9479..fd95559 100644
--- a/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zh-rTW/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"輸入密碼"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"PIN 碼不正確。"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"卡片無效。"</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"充電完成"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"充電完成"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 無線充電"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 充電中"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • 快速充電中"</string>
diff --git a/packages/SystemUI/res-keyguard/values-zu/strings.xml b/packages/SystemUI/res-keyguard/values-zu/strings.xml
index 6a7f647..f60599d 100644
--- a/packages/SystemUI/res-keyguard/values-zu/strings.xml
+++ b/packages/SystemUI/res-keyguard/values-zu/strings.xml
@@ -33,7 +33,7 @@
     <string name="keyguard_enter_your_password" msgid="5397328359341314506">"Faka iphasiwedi yakho"</string>
     <string name="keyguard_password_wrong_pin_code" msgid="6535018036285012028">"Ikhodi ye-PIN engalungile!"</string>
     <string name="keyguard_sim_error_message_short" msgid="592109500618448312">"Ikhadi elingavumelekile."</string>
-    <string name="keyguard_charged" msgid="3316115607283493413">"Ishaje ngokuphelele"</string>
+    <string name="keyguard_charged" msgid="2222329688813033109">"Kushajiwe"</string>
     <string name="keyguard_plugged_in_wireless" msgid="8404159927155454732">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Iyashaja ngaphandle kwentambo"</string>
     <string name="keyguard_plugged_in" msgid="3161102098900158923">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Iyashaja"</string>
     <string name="keyguard_plugged_in_charging_fast" msgid="3684592786276709342">"<xliff:g id="PERCENTAGE">%s</xliff:g> • Ishaja kaningi"</string>
diff --git a/packages/SystemUI/res-keyguard/values/strings.xml b/packages/SystemUI/res-keyguard/values/strings.xml
index 0fe7084..485240a 100644
--- a/packages/SystemUI/res-keyguard/values/strings.xml
+++ b/packages/SystemUI/res-keyguard/values/strings.xml
@@ -62,7 +62,7 @@
 
     <!-- When the lock screen is showing, the phone is plugged in and the battery is fully
          charged, say that it is charged. -->
-    <string name="keyguard_charged">Fully charged</string>
+    <string name="keyguard_charged">Charged</string>
 
     <!-- When the lock screen is showing and the phone plugged in, and the battery is not fully charged, say that it's wirelessly charging. [CHAR LIMIT=50]  -->
     <string name="keyguard_plugged_in_wireless"><xliff:g id="percentage" example="20%">%s</xliff:g> • Charging wirelessly</string>
diff --git a/packages/SystemUI/res/drawable-xhdpi/tv_card_gradient_protection.png b/packages/SystemUI/res/drawable-xhdpi/tv_card_gradient_protection.png
new file mode 100644
index 0000000..135dabb
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xhdpi/tv_card_gradient_protection.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable/auth_dialog_lock.xml b/packages/SystemUI/res/drawable/auth_dialog_lock.xml
new file mode 100644
index 0000000..8146c16
--- /dev/null
+++ b/packages/SystemUI/res/drawable/auth_dialog_lock.xml
@@ -0,0 +1,27 @@
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="32dp"
+    android:height="32dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+    <path
+        android:fillColor="?android:attr/colorAccent"
+        android:pathData="M12,15m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0"/>
+    <path
+        android:fillColor="?android:attr/colorAccent"
+        android:pathData="M18,8h-1.5V5.5C16.5,3.01 14.49,1 12,1S7.5,3.01 7.5,5.5V8H6c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2V10C20,8.9 19.1,8 18,8zM9.5,5.5C9.5,4.12 10.62,3 12,3c1.38,0 2.5,1.12 2.5,2.5V8h-5V5.5zM18,20H6V10h1.5h9H18V20z"/>
+</vector>
diff --git a/packages/SystemUI/res/drawable/circle_red.xml b/packages/SystemUI/res/drawable/circle_red.xml
new file mode 100644
index 0000000..fd3c125
--- /dev/null
+++ b/packages/SystemUI/res/drawable/circle_red.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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"
+       android:shape="oval">
+    <solid android:color="@color/red"/>
+</shape>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/tv_bg_item_app_info.xml b/packages/SystemUI/res/drawable/tv_bg_item_app_info.xml
new file mode 100644
index 0000000..1bbb8c3
--- /dev/null
+++ b/packages/SystemUI/res/drawable/tv_bg_item_app_info.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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"
+       android:shape="rectangle">
+    <corners android:radius="24dp"/>
+    <solid android:color="@color/tv_audio_recording_bar_chip_background"/>
+</shape>
diff --git a/packages/SystemUI/res/drawable/tv_gradient_protection.xml b/packages/SystemUI/res/drawable/tv_gradient_protection.xml
new file mode 100644
index 0000000..ee5cbc7
--- /dev/null
+++ b/packages/SystemUI/res/drawable/tv_gradient_protection.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<!-- gradient protection for cards -->
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@drawable/tv_card_gradient_protection"
+        android:tileMode="repeat"
+/>
diff --git a/packages/SystemUI/res/drawable/tv_ic_mic_white.xml b/packages/SystemUI/res/drawable/tv_ic_mic_white.xml
new file mode 100644
index 0000000..1bea8a1
--- /dev/null
+++ b/packages/SystemUI/res/drawable/tv_ic_mic_white.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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
+  -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+        android:viewportWidth="44"
+        android:viewportHeight="44"
+        android:width="44dp"
+        android:height="44dp">
+    <path
+        android:pathData="M22 25.6666667C25.0433333 25.6666667 27.4816667 23.21 27.4816667 20.1666667L27.5 9.16666667C27.5 6.12333333 25.0433333 3.66666667 22 3.66666667C18.9566667 3.66666667 16.5 6.12333333 16.5 9.16666667L16.5 20.1666667C16.5 23.21 18.9566667 25.6666667 22 25.6666667ZM31.7166667 20.1666667C31.7166667 25.6666667 27.06 29.5166667 22 29.5166667C16.94 29.5166667 12.2833333 25.6666667 12.2833333 20.1666667L9.16666667 20.1666667C9.16666667 26.4183333 14.1533333 31.5883333 20.1666667 32.4866667L20.1666667 38.5L23.8333333 38.5L23.8333333 32.4866667C29.8466667 31.6066667 34.8333333 26.4366667 34.8333333 20.1666667L31.7166667 20.1666667Z"
+        android:fillColor="@android:color/white" />
+</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout-land/auth_credential_pattern_view.xml b/packages/SystemUI/res/layout-land/auth_credential_pattern_view.xml
new file mode 100644
index 0000000..c3fa39e
--- /dev/null
+++ b/packages/SystemUI/res/layout-land/auth_credential_pattern_view.xml
@@ -0,0 +1,113 @@
+<!--
+  ~ Copyright (C) 2019 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.biometrics.AuthCredentialPatternView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="horizontal"
+    android:elevation="@dimen/biometric_dialog_elevation">
+
+    <LinearLayout
+        android:layout_width="0dp"
+        android:layout_height="match_parent"
+        android:layout_weight="1"
+        android:gravity="center"
+        android:orientation="vertical">
+
+        <Space
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:layout_weight="1"/>
+
+        <ImageView
+            android:layout_width="32dp"
+            android:layout_height="32dp"
+            android:background="@drawable/auth_dialog_lock"/>
+
+        <TextView
+            android:id="@+id/title"
+            android:fontFamily="@*android:string/config_headlineFontFamilyMedium"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginHorizontal="24dp"
+            android:layout_marginTop="12dp"
+            android:textSize="20sp"
+            android:gravity="center"
+            android:textColor="?android:attr/textColorPrimary"/>
+
+        <TextView
+            android:id="@+id/subtitle"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginHorizontal="24dp"
+            android:layout_marginTop="8dp"
+            android:textSize="16sp"
+            android:gravity="center"
+            android:textColor="?android:attr/textColorPrimary"/>
+
+        <TextView
+            android:id="@+id/description"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginHorizontal="24dp"
+            android:layout_marginTop="8dp"
+            android:gravity="center"
+            android:textSize="16sp"
+            android:textColor="?android:attr/textColorPrimary"/>
+
+        <Space
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:layout_weight="1"/>
+
+        <TextView
+            android:id="@+id/error"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginHorizontal="24dp"
+            android:textSize="16sp"
+            android:gravity="center"
+            android:textColor="?android:attr/colorError"/>
+
+        <Space
+            android:layout_width="0dp"
+            android:layout_height="0dp"
+            android:layout_weight="1"/>
+
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="0dp"
+        android:layout_height="match_parent"
+        android:layout_weight="1"
+        android:orientation="vertical"
+        android:gravity="center">
+
+        <com.android.internal.widget.LockPatternView
+            android:id="@+id/lockPattern"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginLeft="40dp"
+            android:layout_marginRight="40dp"
+            android:layout_gravity="center"
+            android:clipChildren="false"
+            android:clipToPadding="false"
+            style="@style/LockPatternStyleBiometricPrompt"/>
+
+    </LinearLayout>
+
+</com.android.systemui.biometrics.AuthCredentialPatternView>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/auth_container_view.xml b/packages/SystemUI/res/layout/auth_container_view.xml
index 23199aa..3db01a4 100644
--- a/packages/SystemUI/res/layout/auth_container_view.xml
+++ b/packages/SystemUI/res/layout/auth_container_view.xml
@@ -34,7 +34,7 @@
         android:elevation="@dimen/biometric_dialog_elevation"/>
 
     <ScrollView
-        android:id="@+id/scrollview"
+        android:id="@+id/biometric_scrollview"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center_horizontal|bottom"
diff --git a/packages/SystemUI/res/layout/auth_credential_password_view.xml b/packages/SystemUI/res/layout/auth_credential_password_view.xml
new file mode 100644
index 0000000..4aed033
--- /dev/null
+++ b/packages/SystemUI/res/layout/auth_credential_password_view.xml
@@ -0,0 +1,101 @@
+<!--
+  ~ Copyright (C) 2019 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.biometrics.AuthCredentialPasswordView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+    android:gravity="center_horizontal"
+    android:elevation="@dimen/biometric_dialog_elevation">
+
+    <Space
+        android:layout_width="0dp"
+        android:layout_height="0dp"
+        android:layout_weight="1"/>
+
+    <ImageView
+        android:layout_width="32dp"
+        android:layout_height="32dp"
+        android:background="@drawable/auth_dialog_lock"/>
+
+    <TextView
+        android:id="@+id/title"
+        android:fontFamily="@*android:string/config_headlineFontFamilyMedium"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:layout_marginTop="12dp"
+        android:textSize="20sp"
+        android:gravity="center"
+        android:textColor="?android:attr/textColorPrimary"/>
+
+    <TextView
+        android:id="@+id/subtitle"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:layout_marginTop="8dp"
+        android:textSize="16sp"
+        android:gravity="center"
+        android:textColor="?android:attr/textColorPrimary"/>
+
+    <TextView
+        android:id="@+id/description"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:layout_marginTop="8dp"
+        android:gravity="center"
+        android:textSize="16sp"
+        android:textColor="?android:attr/textColorPrimary"/>
+
+    <Space
+        android:layout_width="0dp"
+        android:layout_height="0dp"
+        android:layout_weight="1"/>
+
+    <TextView
+        android:id="@+id/error"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:textSize="16sp"
+        android:gravity="center"
+        android:textColor="?android:attr/colorError"/>
+
+    <EditText
+        android:id="@+id/lockPassword"
+        android:layout_marginBottom="20dp"
+        android:layout_marginLeft="100dp"
+        android:layout_marginRight="100dp"
+        android:layout_width="208dp"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:gravity="center"
+        android:inputType="textPassword"
+        android:maxLength="500"
+        android:textSize="16sp"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+        android:imeOptions="flagForceAscii"
+        style="@style/LockPatternStyleBiometricPrompt"/>
+
+    <Space
+        android:layout_width="0dp"
+        android:layout_height="0dp"
+        android:layout_weight="5"/>
+
+</com.android.systemui.biometrics.AuthCredentialPasswordView>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/auth_credential_pattern_view.xml b/packages/SystemUI/res/layout/auth_credential_pattern_view.xml
new file mode 100644
index 0000000..c9edcd6
--- /dev/null
+++ b/packages/SystemUI/res/layout/auth_credential_pattern_view.xml
@@ -0,0 +1,97 @@
+<!--
+  ~ Copyright (C) 2019 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.biometrics.AuthCredentialPatternView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+    android:gravity="center_horizontal"
+    android:elevation="@dimen/biometric_dialog_elevation">
+
+    <Space
+        android:layout_width="0dp"
+        android:layout_height="0dp"
+        android:layout_weight="1"/>
+
+    <ImageView
+        android:layout_width="32dp"
+        android:layout_height="32dp"
+        android:background="@drawable/auth_dialog_lock"/>
+
+    <TextView
+        android:id="@+id/title"
+        android:fontFamily="@*android:string/config_headlineFontFamilyMedium"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:layout_marginTop="12dp"
+        android:textSize="20sp"
+        android:gravity="center"
+        android:textColor="?android:attr/textColorPrimary"/>
+
+    <TextView
+        android:id="@+id/subtitle"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:layout_marginTop="8dp"
+        android:textSize="16sp"
+        android:gravity="center"
+        android:textColor="?android:attr/textColorPrimary"/>
+
+    <TextView
+        android:id="@+id/description"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:layout_marginTop="8dp"
+        android:gravity="center"
+        android:textSize="16sp"
+        android:textColor="?android:attr/textColorPrimary"/>
+
+    <Space
+        android:layout_width="0dp"
+        android:layout_height="0dp"
+        android:layout_weight="3"/>
+
+    <TextView
+        android:id="@+id/error"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginHorizontal="24dp"
+        android:textSize="16sp"
+        android:gravity="center"
+        android:textColor="?android:attr/colorError"/>
+
+    <com.android.internal.widget.LockPatternView
+        android:id="@+id/lockPattern"
+        android:layout_marginBottom="20dp"
+        android:layout_marginLeft="40dp"
+        android:layout_marginRight="40dp"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:clipChildren="false"
+        android:clipToPadding="false"
+        style="@style/LockPatternStyleBiometricPrompt"/>
+
+    <Space
+        android:layout_width="0dp"
+        android:layout_height="0dp"
+        android:layout_weight="1"/>
+
+</com.android.systemui.biometrics.AuthCredentialPatternView>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/navigation_bar.xml b/packages/SystemUI/res/layout/navigation_bar.xml
index 8ba4c9c..ba6b695 100644
--- a/packages/SystemUI/res/layout/navigation_bar.xml
+++ b/packages/SystemUI/res/layout/navigation_bar.xml
@@ -24,6 +24,21 @@
     android:layout_width="match_parent"
     android:background="@drawable/system_bar_background">
 
+    <com.android.systemui.CornerHandleView
+        android:id="@+id/assist_hint_left"
+        android:layout_width="36dp"
+        android:layout_height="36dp"
+        android:layout_gravity="left|bottom"
+        android:rotation="270"
+        android:visibility="gone"/>
+    <com.android.systemui.CornerHandleView
+        android:id="@+id/assist_hint_right"
+        android:layout_width="36dp"
+        android:layout_height="36dp"
+        android:layout_gravity="right|bottom"
+        android:rotation="180"
+        android:visibility="gone"/>
+
     <com.android.systemui.statusbar.phone.NavigationBarInflaterView
         android:id="@+id/navigation_inflater"
         android:layout_width="match_parent"
diff --git a/packages/SystemUI/res/layout/qs_carrier_group.xml b/packages/SystemUI/res/layout/qs_carrier_group.xml
index 56efb49..f2b0606 100644
--- a/packages/SystemUI/res/layout/qs_carrier_group.xml
+++ b/packages/SystemUI/res/layout/qs_carrier_group.xml
@@ -29,6 +29,9 @@
         android:id="@+id/no_carrier_text"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
+        android:minWidth="48dp"
+        android:minHeight="48dp"
+        android:gravity="center_vertical"
         android:textAppearance="@style/TextAppearance.QS.Status"
         android:textDirection="locale"
         android:marqueeRepeatLimit="marquee_forever"
diff --git a/packages/SystemUI/res/layout/rounded_corners.xml b/packages/SystemUI/res/layout/rounded_corners.xml
index b409c8f..1849068 100644
--- a/packages/SystemUI/res/layout/rounded_corners.xml
+++ b/packages/SystemUI/res/layout/rounded_corners.xml
@@ -18,18 +18,6 @@
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
-    <com.android.systemui.CornerHandleView
-        android:id="@+id/assist_hint_left"
-        android:layout_width="36dp"
-        android:layout_height="36dp"
-        android:layout_gravity="left|top"
-        android:visibility="gone"/>
-    <com.android.systemui.CornerHandleView
-        android:id="@+id/assist_hint_right"
-        android:layout_width="36dp"
-        android:layout_height="36dp"
-        android:layout_gravity="right|bottom"
-        android:visibility="gone"/>
     <ImageView
         android:id="@+id/left"
         android:layout_width="12dp"
diff --git a/packages/SystemUI/res/layout/status_bar_expanded.xml b/packages/SystemUI/res/layout/status_bar_expanded.xml
index e7c6b25..0e59a41 100644
--- a/packages/SystemUI/res/layout/status_bar_expanded.xml
+++ b/packages/SystemUI/res/layout/status_bar_expanded.xml
@@ -17,14 +17,9 @@
 */
 -->
 
-<com.android.systemui.statusbar.phone.NotificationPanelView
+<merge
     xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:systemui="http://schemas.android.com/apk/res-auto"
-    android:id="@+id/notification_panel"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:background="@android:color/transparent" >
-
+    xmlns:systemui="http://schemas.android.com/apk/res-auto">
     <FrameLayout
         android:id="@+id/big_clock_container"
         android:layout_width="match_parent"
@@ -112,5 +107,4 @@
         android:background="@drawable/qs_navbar_scrim" />
 
     <include layout="@layout/status_bar_expanded_plugin_frame"/>
-
-</com.android.systemui.statusbar.phone.NotificationPanelView>
+</merge>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/status_bar_expanded_plugin_frame.xml b/packages/SystemUI/res/layout/status_bar_expanded_plugin_frame.xml
index 4849dfb..7d6ff3b1 100644
--- a/packages/SystemUI/res/layout/status_bar_expanded_plugin_frame.xml
+++ b/packages/SystemUI/res/layout/status_bar_expanded_plugin_frame.xml
@@ -20,10 +20,10 @@
     android:id="@+id/plugin_frame"
     android:theme="@style/qs_theme"
     android:layout_width="@dimen/qs_panel_width"
-    android:layout_height="96dp"
+    android:layout_height="105dp"
     android:layout_gravity="center_horizontal"
-    android:layout_marginTop="@*android:dimen/quick_qs_total_height"
+    android:layout_marginTop="@dimen/notification_side_paddings"
     android:layout_marginLeft="@dimen/notification_side_paddings"
     android:layout_marginRight="@dimen/notification_side_paddings"
     android:visibility="gone"
-    android:background="@drawable/qs_background_primary"/>
\ No newline at end of file
+    android:background="@drawable/qs_background_primary"/>
diff --git a/packages/SystemUI/res/layout/super_status_bar.xml b/packages/SystemUI/res/layout/super_status_bar.xml
index 9716a00..57834da 100644
--- a/packages/SystemUI/res/layout/super_status_bar.xml
+++ b/packages/SystemUI/res/layout/super_status_bar.xml
@@ -64,7 +64,7 @@
         sysui:ignoreRightInset="true"
         />
 
-    <include layout="@layout/status_bar_expanded"
+    <ViewStub android:id="@+id/status_bar_expanded"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:visibility="invisible" />
diff --git a/packages/SystemUI/res/layout/tv_item_app_info.xml b/packages/SystemUI/res/layout/tv_item_app_info.xml
new file mode 100644
index 0000000..b40589e
--- /dev/null
+++ b/packages/SystemUI/res/layout/tv_item_app_info.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:orientation="horizontal"
+              android:layout_width="wrap_content"
+              android:layout_height="48dp"
+              android:layout_marginLeft="8dp"
+              android:paddingHorizontal="12dp"
+              android:gravity="center_vertical"
+              android:background="@drawable/tv_bg_item_app_info">
+
+    <ImageView
+        android:id="@+id/icon"
+        android:layout_width="24dp"
+        android:layout_height="24dp"
+        android:layout_marginRight="8dp"/>
+
+    <TextView
+        android:id="@+id/title"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:textColor="@color/tv_audio_recording_bar_text"
+        android:fontFamily="sans-serif"
+        android:textSize="14sp"/>
+
+</LinearLayout>
diff --git a/packages/SystemUI/res/layout/tv_status_bar_audio_recording.xml b/packages/SystemUI/res/layout/tv_status_bar_audio_recording.xml
new file mode 100644
index 0000000..b9dffbb
--- /dev/null
+++ b/packages/SystemUI/res/layout/tv_status_bar_audio_recording.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:layout_width="match_parent"
+              android:layout_height="wrap_content"
+              android:layout_gravity="bottom"
+              android:orientation="vertical">
+
+    <!-- Gradient Protector -->
+    <View
+        android:layout_width="match_parent"
+        android:layout_height="102.5dp"
+        android:background="@drawable/tv_gradient_protection"/>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="72dp"
+        android:background="@color/tv_audio_recording_bar_background"
+        android:gravity="center_vertical"
+        android:orientation="horizontal">
+
+        <ImageView
+            android:layout_width="48dp"
+            android:layout_height="48dp"
+            android:layout_marginLeft="42dp"
+            android:layout_marginVertical="12dp"
+            android:padding="8dp"
+            android:background="@drawable/circle_red"
+            android:scaleType="centerInside"
+            android:src="@drawable/tv_ic_mic_white"/>
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginLeft="24dp"
+            android:text="Audio recording by"
+            android:textColor="@color/tv_audio_recording_bar_text"
+            android:fontFamily="sans-serif"
+            android:textSize="14sp"/>
+
+        <LinearLayout
+            android:id="@+id/container"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"/>
+
+    </LinearLayout>
+
+</LinearLayout>
diff --git a/packages/SystemUI/res/values-af/strings.xml b/packages/SystemUI/res/values-af/strings.xml
index 538fdce..b0b4615 100644
--- a/packages/SystemUI/res/values-af/strings.xml
+++ b/packages/SystemUI/res/values-af/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Stel invoer metodes op"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fisiese sleutelbord"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Gee <xliff:g id="APPLICATION">%1$s</xliff:g> toegang tot <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Gee <xliff:g id="APPLICATION">%1$s</xliff:g> toegang tot <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Maak <xliff:g id="APPLICATION">%1$s</xliff:g> oop om <xliff:g id="USB_DEVICE">%2$s</xliff:g> te hanteer?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Maak <xliff:g id="APPLICATION">%1$s</xliff:g> oop om <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> te hanteer?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Kanselleer"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Bevestig"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Probeer weer"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Leë gebied; tik om stawing te kanselleer"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tik om stawing te kanselleer"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Probeer asseblief weer"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Soek tans jou gesig"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Gesig is gestaaf"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Bevestig"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tik op Bevestig om te voltooi"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Gestaaf"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Raak die vingerafdruksensor"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Vingerafdrukikoon"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Soek tans vir jou …"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Kennisgewings"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Flitslig"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobiele data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Datagebruik"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Oorblywende data"</string>
diff --git a/packages/SystemUI/res/values-am/strings.xml b/packages/SystemUI/res/values-am/strings.xml
index a3ff5b4..e423c6a 100644
--- a/packages/SystemUI/res/values-am/strings.xml
+++ b/packages/SystemUI/res/values-am/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"የግቤት ስልቶችን አዘጋጅ"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"የሚዳሰስ የቁልፍ ሰሌዳ"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> <xliff:g id="USB_DEVICE">%2$s</xliff:g>ን እንዲደርስበት ይፈቀድለት?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ን እንዲደርስበት ይፈቀድለት?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ን እንዲይዘው <xliff:g id="APPLICATION">%1$s</xliff:g> ይክፈት?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ን እንዲይዘው <xliff:g id="APPLICATION">%1$s</xliff:g> ይክፈት?"</string>
@@ -108,7 +110,7 @@
     <string name="accessibility_phone_button" msgid="6738112589538563574">"ስልክ"</string>
     <string name="accessibility_voice_assist_button" msgid="487611083884852965">"የድምጽ እርዳታ"</string>
     <string name="accessibility_unlock_button" msgid="128158454631118828">"ክፈት"</string>
-    <string name="accessibility_waiting_for_fingerprint" msgid="4808860050517462885">"አሻራን በመጠባበቅ ላይ"</string>
+    <string name="accessibility_waiting_for_fingerprint" msgid="4808860050517462885">"የጣት አሻራን በመጠባበቅ ላይ"</string>
     <string name="accessibility_unlock_without_fingerprint" msgid="7541705575183694446">"የጣት አሻራዎን ሳይጠቀሙ ይክፈቱ"</string>
     <string name="accessibility_scanning_face" msgid="769545173211758586">"የቅኝት ፊት"</string>
     <string name="accessibility_send_smart_reply" msgid="7766727839703044493">"ላክ"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"ይቅር"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"አረጋግጥ"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"እንደገና ይሞክሩ"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ባዶ ክልል፣ ፈቃድን ለመሰረዝ መታ ያድርጉ"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ማረጋገጥን ለመሰረዝ መታ ያድርጉ"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"እባክዎ እንደገና ይሞክሩ"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"መልክዎን በመፈለግ ላይ"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"መልክ ተረጋግጧል"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"ተረጋግጧል"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"ለማጠናቀቅ አረጋግጥን መታ ያድርጉ"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"የተረጋገጠ"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"የጣት አሻራ ዳሳሹን ይንኩ"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"የጣት አሻራ አዶ"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"እርስዎን በመፈለግ ላይ…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"ማሳወቂያዎች"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"የባትሪ ብርሃን"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"የተንቀሳቃሽ ስልክ ውሂብ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"የውሂብ አጠቃቀም"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ቀሪ ውሂብ"</string>
diff --git a/packages/SystemUI/res/values-ar/strings.xml b/packages/SystemUI/res/values-ar/strings.xml
index 529ca5c..3b145105 100644
--- a/packages/SystemUI/res/values-ar/strings.xml
+++ b/packages/SystemUI/res/values-ar/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"إعداد أسلوب الإدخال"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"لوحة مفاتيح فعلية"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"هل تريد السماح لتطبيق <xliff:g id="APPLICATION">%1$s</xliff:g> بالدخول إلى <xliff:g id="USB_DEVICE">%2$s</xliff:g>؟"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"هل تريد السماح لتطبيق <xliff:g id="APPLICATION">%1$s</xliff:g> بالدخول إلى <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>؟"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"هل تريد فتح <xliff:g id="APPLICATION">%1$s</xliff:g> للتعامل مع <xliff:g id="USB_DEVICE">%2$s</xliff:g>؟"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"هل تريد فتح تطبيق <xliff:g id="APPLICATION">%1$s</xliff:g> للتعامل مع <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>؟"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"إلغاء"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"تأكيد"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"إعادة المحاولة"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"منطقة خالية، يُرجى النقر لإلغاء المصادقة."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"انقر لإلغاء المصادقة."</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"يُرجى إعادة المحاولة."</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"جارٍ البحث عن وجهك"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"تمّت مصادقة الوجه."</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"تمّ التأكيد."</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"يمكنك النقر على \"تأكيد\" لإكمال المهمة."</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"مصادقة"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"المس زر استشعار بصمة الإصبع"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"رمز بصمة الإصبع"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"جارٍ البحث عن وجهك…"</string>
@@ -371,6 +388,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"الإشعارات"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"الفلاش"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"بيانات الجوّال"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"استخدام البيانات"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"البيانات المتبقية"</string>
@@ -555,8 +574,8 @@
     <string name="screen_pinning_description_gestural" msgid="1191513974909607884">"يؤدي هذا إلى استمرار عرض الشاشة المُختارة إلى أن تتم إزالة تثبيتها. مرّر الشاشة بسرعة للأعلى مع الاستمرار لإزالة تثبيت الشاشة."</string>
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"يؤدي هذا إلى استمرار عرض الشاشة المُختارة إلى أن تتم إزالة تثبيتها. المس مع الاستمرار زر \"نظرة عامة\" لإزالة التثبيت."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"يؤدي هذا إلى استمرار عرض الشاشة المُختارة إلى أن تتم إزالة تثبيتها. المس مع الاستمرار زر \"الشاشة الرئيسية\" لإزالة التثبيت."</string>
-    <string name="screen_pinning_toast" msgid="2266705122951934150">"لإزالة تثبيت هذه الشاشة، يمكنك أن تلمس مع الاستمرار زرّي \"رجوع\" و\"نظرة عامة\"."</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"لإزالة تثبيت هذه الشاشة، يمكنك أن تلمس مع الاستمرار زرّي \"رجوع\" و\"الشاشة الرئيسية\"."</string>
+    <string name="screen_pinning_toast" msgid="2266705122951934150">"لإزالة تثبيت هذه الشاشة، يمكنك النقر مع الاستمرار على زرّي \"الرجوع\" و\"النظرة العامة\"."</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"لإزالة تثبيت هذه الشاشة، يمكنك النقر مع الاستمرار على زرّي \"الرجوع\" و\"الشاشة الرئيسية\"."</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"مرّر الشاشة بسرعة للأعلى مع الاستمرار لإزالة تثبيت الشاشة."</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"حسنًا"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"لا، شكرًا"</string>
diff --git a/packages/SystemUI/res/values-as/strings.xml b/packages/SystemUI/res/values-as/strings.xml
index 7d8ba64..c3ca88a 100644
--- a/packages/SystemUI/res/values-as/strings.xml
+++ b/packages/SystemUI/res/values-as/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ইনপুট পদ্ধতি ছেট আপ কৰক"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"বাস্তৱিক কীব\'ৰ্ড"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ত প্ৰৱেশ কৰিবলৈ <xliff:g id="APPLICATION">%1$s</xliff:g>ক অনুমতি দিবনে?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g>ক <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ত প্ৰৱেশ কৰিবলৈ অনুমতি দিবনে?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ক ব্যৱহাৰ কৰিবলৈ <xliff:g id="APPLICATION">%1$s</xliff:g>ক খোলেনে?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ক ব্যৱহাৰ কৰিবলৈ <xliff:g id="APPLICATION">%1$s</xliff:g>ক খোলেনে?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"বাতিল কৰক"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"নিশ্চিত কৰক"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"আকৌ চেষ্টা কৰক"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"এলেকা খালী আছে, বিশ্বাসযোগ্যতা প্ৰমাণীকৰণ বাতিল কৰিবলৈ টিপক"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"বিশ্বাসযোগ্যতা প্ৰমাণীকৰণ বাতিল কৰিবলৈ টিপক"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"অনুগ্ৰহ কৰি আকৌ চেষ্টা কৰক"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"আপোনাৰ মুখমণ্ডল বিচাৰি থকা হৈছে"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"মুখমণ্ডলৰ বিশ্বাসযোগ্যতা প্ৰমাণীকৰণ কৰা হ’ল"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"নিশ্চিত কৰিলে"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"সম্পূৰ্ণ কৰিবলৈ নিশ্চিত কৰক-ত টিপক"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"বিশ্বাসযোগ্যতা প্ৰমাণীকৰণ কৰা হ’ল"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ফিংগাৰপ্ৰিণ্ট ছেন্সৰটো স্পৰ্শ কৰক"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ফিংগাৰপ্ৰিণ্ট আইকন"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"আপোনাৰ মুখমণ্ডল বিচাৰি আছে…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"জাননীসমূহ"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ফ্লাশ্বলাইট"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"ম’বাইল ডেটা"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ডেটা ব্যৱহাৰ"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"বাকী থকা ডেটা"</string>
diff --git a/packages/SystemUI/res/values-az/strings.xml b/packages/SystemUI/res/values-az/strings.xml
index 5ae4d2d..67e24c5 100644
--- a/packages/SystemUI/res/values-az/strings.xml
+++ b/packages/SystemUI/res/values-az/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Daxiletmə metodlarını ayarlayın"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fiziki klaviatura"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> tətbiqinə <xliff:g id="USB_DEVICE">%2$s</xliff:g> cihazına giriş icazəsi verilsin?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> tətbiqinə <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> cihazına giriş icazəsi verilsin?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> cihazını idarə etmək üçün <xliff:g id="APPLICATION">%1$s</xliff:g> tətbiqi açılsın?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> cihazını idarə etmək üçün <xliff:g id="APPLICATION">%1$s</xliff:g> tətbiqi açılsın?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Ləğv et"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Təsdiq"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Yenidən cəhd edin"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Region boşdur, identifikasiyanı ləğv etmək üçün toxunun"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Doğrulanmanı ləğv etmək üçün toxunun"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Yenidən cəhd edin"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Üzünüz axtarılır"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Üz doğrulandı"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Təsdiqləndi"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tamamlamaq üçün \"Təsdiq edin\" seçiminə toxunun"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Doğrulandı"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Barmaq izi sensoruna klikləyin"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Barmaq izi ikonası"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Siz axtarılırsınız…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Bildirişlər"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"İşartı"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobil data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Data istifadəsi"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Qalan data"</string>
diff --git a/packages/SystemUI/res/values-b+sr+Latn/strings.xml b/packages/SystemUI/res/values-b+sr+Latn/strings.xml
index 95346e4..3def744 100644
--- a/packages/SystemUI/res/values-b+sr+Latn/strings.xml
+++ b/packages/SystemUI/res/values-b+sr+Latn/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Podesi metode unosa"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fizička tastatura"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Želite li da dozvolite da <xliff:g id="APPLICATION">%1$s</xliff:g> pristupa uređaju <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Želite li da dozvolite da <xliff:g id="APPLICATION">%1$s</xliff:g> pristupa uređaju <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Želite li da otvorite aplikaciju <xliff:g id="APPLICATION">%1$s</xliff:g> da biste koristili uređaj <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Želite li da otvorite aplikaciju <xliff:g id="APPLICATION">%1$s</xliff:g> da biste koristili uređaj <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Otkaži"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Potvrdi"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Probaj ponovo"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Prazna oblast, dodirnite da biste otkazali potvrdu identiteta"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Dodirnite da biste otkazali potvrdu identiteta"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Probajte ponovo"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Traži se vaše lice"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Lice je potvrđeno"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Potvrđeno"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Dodirnite Potvrdi da biste završili"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Identitet je potvrđen"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Dodirnite senzor za otisak prsta"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona otiska prsta"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Tražimo vas…"</string>
@@ -365,6 +382,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Obaveštenja"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lampa"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobilni podaci"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Potrošnja podataka"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Preostala količina podataka"</string>
diff --git a/packages/SystemUI/res/values-be/strings.xml b/packages/SystemUI/res/values-be/strings.xml
index 3674564..cdb4ddb 100644
--- a/packages/SystemUI/res/values-be/strings.xml
+++ b/packages/SystemUI/res/values-be/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Налада метадаў уводу"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Фізічная клавіятура"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Дазволіць праграме <xliff:g id="APPLICATION">%1$s</xliff:g> доступ да прылады <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Дазволіць праграме <xliff:g id="APPLICATION">%1$s</xliff:g> доступ да прылады <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Адкрыць праграму <xliff:g id="APPLICATION">%1$s</xliff:g> для працы з прыладай <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Адкрыць праграму <xliff:g id="APPLICATION">%1$s</xliff:g> для працы з прыладай <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Скасаваць"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Пацвердзіць"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Паўтарыць спробу"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Пустая вобласць. Націсніце, каб скасаваць аўтэнтыфікацыю"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Націсніце, каб скасаваць аўтэнтыфікацыю"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Паўтарыце спробу"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Ідзе пошук твару"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Твар распазнаны"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Пацверджана"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Націсніце \"Пацвердзіць\", каб завяршыць"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Распазнана"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Дакраніцеся да сканера адбіткаў пальцаў"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Значок адбіткаў пальцаў"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Ідзе пошук вашага твару…"</string>
@@ -369,6 +386,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Апавяшчэнні"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Ліхтарык"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мабільная перадача даных"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Выкарыстанне трафіка"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Засталося трафіку"</string>
diff --git a/packages/SystemUI/res/values-bg/strings.xml b/packages/SystemUI/res/values-bg/strings.xml
index 1618e05..cd22290 100644
--- a/packages/SystemUI/res/values-bg/strings.xml
+++ b/packages/SystemUI/res/values-bg/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Методи на въвеждане: Настройка"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Физическа клавиатура"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Да се разреши ли на <xliff:g id="APPLICATION">%1$s</xliff:g> достъп до <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Да се разреши ли на <xliff:g id="APPLICATION">%1$s</xliff:g> достъп до <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Да се използва ли <xliff:g id="APPLICATION">%1$s</xliff:g> за работата с/ъс <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Да се използва ли <xliff:g id="APPLICATION">%1$s</xliff:g> за работата с/ъс <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Отказ"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Потвърждаване"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Нов опит"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Празна област. Докоснете, за да анулирате удостоверяването"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Докоснете, за да анулирате удостоверяването"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Моля, опитайте отново"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Лицето ви се търси"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Лицето е удостоверено"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Потвърдено"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Докоснете „Потвърждаване“ за завършване"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Удостоверено"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Докоснете сензора за отпечатъци"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Икона за отпечатък"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Търсим ви…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Известия"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Фенерче"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобилни данни"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Пренос на данни"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Оставащи данни"</string>
@@ -401,7 +420,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"Ппоказване на по-малко спешните известия по-долу"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"Докоснете отново, за да отворите"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"Прекарайте пръст нагоре, за да отключите"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"Прекарайте пръст нагоре, за да опитате отново"</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"Плъзнете бързо нагоре, за да опитате отново"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"Това устройство се управлява от организацията ви"</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"Това устройство се управлява от <xliff:g id="ORGANIZATION_NAME">%s</xliff:g>"</string>
     <string name="phone_hint" msgid="4872890986869209950">"Плъзнете с пръст от иконата, за да използвате телефона"</string>
diff --git a/packages/SystemUI/res/values-bn/strings.xml b/packages/SystemUI/res/values-bn/strings.xml
index 6b7561b..11a6e90 100644
--- a/packages/SystemUI/res/values-bn/strings.xml
+++ b/packages/SystemUI/res/values-bn/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ইনপুট পদ্ধতিগুলি সেট-আপ করুন"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ফিজিক্যাল কীবোর্ড"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> কে <xliff:g id="USB_DEVICE">%2$s</xliff:g> অ্যাক্সেস করতে দেবেন?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> কে <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> অ্যাক্সেস করতে দেবেন?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ব্যবহার করার জন্য <xliff:g id="APPLICATION">%1$s</xliff:g> চালু করবেন?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ব্যবহার করার জন্য <xliff:g id="APPLICATION">%1$s</xliff:g> চালু করবেন?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"বাতিল করুন"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"কনফার্ম করুন"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"আবার চেষ্টা করুন"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"জায়গাটি খালি, যাচাইকরণ বাতিল করতে এখানে ট্যাপ করুন"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"যাচাইকরণ বাতিল করতে ট্যাপ করুন"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"আবার চেষ্টা করুন"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"আপনার ফেস খোঁজা হচ্ছে"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ফেস যাচাই করা হয়েছে"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"কনফার্ম করা হয়েছে"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"সম্পূর্ণ করতে \'কনফার্ম করুন\' বোতামে ট্যাপ করুন"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"প্রমাণীকৃত"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"আঙ্গুলের ছাপের সেন্সর স্পর্শ করুন"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"আঙ্গুলের ছাপের আইকন"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"আপনার জন্য খোঁজা হচ্ছে…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"বিজ্ঞপ্তি"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ফ্ল্যাশলাইট"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"মোবাইল ডেটা"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ডেটার ব্যবহার"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"অবশিষ্ট ডেটা"</string>
diff --git a/packages/SystemUI/res/values-bs/strings.xml b/packages/SystemUI/res/values-bs/strings.xml
index c22ddfd..7eaa9c4 100644
--- a/packages/SystemUI/res/values-bs/strings.xml
+++ b/packages/SystemUI/res/values-bs/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Postavljanje načina unosa"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fizička tastatura"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Dozvoliti aplikaciji <xliff:g id="APPLICATION">%1$s</xliff:g> pristup uređaju: <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Dozvoliti aplikaciji <xliff:g id="APPLICATION">%1$s</xliff:g> pristup dodatku: <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Otvoriti aplikaciju <xliff:g id="APPLICATION">%1$s</xliff:g> za upravljanje uređajem: <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Otvoriti aplikaciju <xliff:g id="APPLICATION">%1$s</xliff:g> za upravljanje dodatkom: <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Otkaži"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Potvrdite"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Pokušaj ponovo"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Područje je prazno. Dodirnite da otkažete autentifikaciju."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Dodirnite da otkažete autentifikaciju"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Pokušajte ponovo"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Traženje vašeg lica"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Lice je provjereno"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Potvrđeno"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Dodirnite Potvrdi da završite"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentificirano"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Dodirnite senzor za otisak prsta"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona za otisak prsta"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Tražimo vas…"</string>
@@ -365,6 +382,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Obavještenja"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Svjetiljka"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Prijenos podataka na mobilnoj mreži"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Prijenos podataka"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Preostala količina podataka"</string>
diff --git a/packages/SystemUI/res/values-ca/strings.xml b/packages/SystemUI/res/values-ca/strings.xml
index d4147ba..3bd72b3 100644
--- a/packages/SystemUI/res/values-ca/strings.xml
+++ b/packages/SystemUI/res/values-ca/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configura els mètodes d\'entrada"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teclat físic"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Vols permetre que <xliff:g id="APPLICATION">%1$s</xliff:g> accedeixi a <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Vols permetre que <xliff:g id="APPLICATION">%1$s</xliff:g> accedeixi a <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Vols obrir <xliff:g id="APPLICATION">%1$s</xliff:g> per gestionar <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Vols obrir <xliff:g id="APPLICATION">%1$s</xliff:g> per gestionar <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancel·la"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirma"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Torna-ho a provar"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Zona buida; toca per cancel·lar l\'autenticació"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Toca per cancel·lar l\'autenticació"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Torna-ho a provar"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"S\'està cercant la teva cara"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Cara autenticada"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmat"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Toca Confirma per completar"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenticat"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Toca el sensor d\'empremtes digitals"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icona d\'empremta digital"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"S\'està cercant la teva cara…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificacions"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Llanterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Dades mòbils"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Ús de dades"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Dades restants"</string>
diff --git a/packages/SystemUI/res/values-cs/strings.xml b/packages/SystemUI/res/values-cs/strings.xml
index 87aaa94..b3a8596 100644
--- a/packages/SystemUI/res/values-cs/strings.xml
+++ b/packages/SystemUI/res/values-cs/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Nastavit metody zadávání"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fyzická klávesnice"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Povolit aplikaci <xliff:g id="APPLICATION">%1$s</xliff:g> přístup k zařízení <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Povolit aplikaci <xliff:g id="APPLICATION">%1$s</xliff:g> přístup k zařízení <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Otevřít aplikaci <xliff:g id="APPLICATION">%1$s</xliff:g> ke správě zařízení <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Otevřít aplikaci <xliff:g id="APPLICATION">%1$s</xliff:g> ke správě zařízení <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Zrušit"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Potvrdit"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Zkusit znovu"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Prázdná oblast, klepnutím ověření zrušíte"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Klepnutím zrušíte ověření"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Zkuste to prosím znovu"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Vyhledávání obličeje"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Obličej byl ověřen"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Potvrzeno"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Ověření dokončíte klepnutím na Potvrdit"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Ověřeno"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Dotkněte se snímače otisků prstů"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona otisku prstu"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Hledáme vás…"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Oznámení"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Svítilna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobilní data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Využití dat"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Zbývající data"</string>
diff --git a/packages/SystemUI/res/values-da/strings.xml b/packages/SystemUI/res/values-da/strings.xml
index 57c934e..f0e5898 100644
--- a/packages/SystemUI/res/values-da/strings.xml
+++ b/packages/SystemUI/res/values-da/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Konfigurer inputmetoder"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fysisk tastatur"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Vil du give <xliff:g id="APPLICATION">%1$s</xliff:g> adgang til <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Vil du give <xliff:g id="APPLICATION">%1$s</xliff:g> adgang til <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Vil du åbne <xliff:g id="APPLICATION">%1$s</xliff:g> til håndtering af <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Vil du åbne <xliff:g id="APPLICATION">%1$s</xliff:g> til håndtering af <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Annuller"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Bekræft"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Prøv igen"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Tomt område. Tryk for at annullere godkendelsen."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tryk for at annullere godkendelsen"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Prøv igen"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Søger efter dit ansigt"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Ansigtet er godkendt"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Bekræftet"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tryk på Bekræft for at udføre"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Godkendt"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Sæt fingeren på fingeraftrykslæseren"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikon for fingeraftryk"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Forsøger at finde dig…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifikationer"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lommelygte"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobildata"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Dataforbrug"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Resterende data"</string>
@@ -544,7 +563,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"Dette fastholder skærmen i visningen, indtil du frigør den. Tryk på Tilbage, og hold fingeren nede for at frigøre skærmen."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"Dette fastholder skærmen i visningen, indtil du frigør den. Hold Startskærm nede for at frigøre skærmen."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"Hold knapperne Tilbage og Oversigt nede for at frigøre skærmen"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Hold knapperne Tilbage og Startskærm nede for at frigøre skærmen"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Hold knapperne Tilbage og Hjem nede for at frigøre skærmen"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"Stryg opad, og hold fingeren nede for at frigøre denne skærm"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"OK, det er forstået"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"Nej tak"</string>
diff --git a/packages/SystemUI/res/values-de/strings.xml b/packages/SystemUI/res/values-de/strings.xml
index e1fd8db..f32c577 100644
--- a/packages/SystemUI/res/values-de/strings.xml
+++ b/packages/SystemUI/res/values-de/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Eingabemethoden festlegen"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Physische Tastatur"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> den Zugriff auf <xliff:g id="USB_DEVICE">%2$s</xliff:g> gewähren?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> den Zugriff auf <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> gewähren?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Für <xliff:g id="USB_DEVICE">%2$s</xliff:g> <xliff:g id="APPLICATION">%1$s</xliff:g> öffnen?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Für <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> <xliff:g id="APPLICATION">%1$s</xliff:g> öffnen?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Abbrechen"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Bestätigen"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Noch einmal versuchen"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Feld \"Region\" ist leer, zum Abbrechen der Authentifizierung tippen"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Zum Abbrechen der Authentifizierung tippen"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Noch einmal versuchen"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Nach deinem Gesicht wird gesucht"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Gesicht authentifiziert"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Bestätigt"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Zum Abschließen auf \"Bestätigen\" tippen"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Authentifiziert"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Berühre den Fingerabdrucksensor"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Fingerabdruck-Symbol"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Wir suchen nach dir…"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Benachrichtigungen"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Taschenlampe"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobile Daten"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Datennutzung"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Verbleibende Daten"</string>
diff --git a/packages/SystemUI/res/values-el/strings.xml b/packages/SystemUI/res/values-el/strings.xml
index dfb5edf..ce693ee 100644
--- a/packages/SystemUI/res/values-el/strings.xml
+++ b/packages/SystemUI/res/values-el/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Ρύθμιση μεθόδων εισαγωγής"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Φυσικό πληκτρολόγιο"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Να επιτρέπεται η πρόσβαση της εφαρμογής <xliff:g id="APPLICATION">%1$s</xliff:g> στη συσκευή <xliff:g id="USB_DEVICE">%2$s</xliff:g>;"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Να επιτρέπεται η πρόσβαση της εφαρμογής <xliff:g id="APPLICATION">%1$s</xliff:g> στο αξεσουάρ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>;"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Να ανοίγει η εφαρμογή <xliff:g id="APPLICATION">%1$s</xliff:g> για τη διαχείριση της συσκευής <xliff:g id="USB_DEVICE">%2$s</xliff:g>;"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Να ανοίγει η εφαρμογή <xliff:g id="APPLICATION">%1$s</xliff:g> για τη διαχείριση του αξεσουάρ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>;"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Ακύρωση"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Επιβεβαίωση"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Δοκιμάστε ξανά"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Κενή περιοχή, πατήστε για ακύρωση ελέγχου ταυτότητας"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Πατήστε για ακύρωση του ελέγχου ταυτότητας"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Δοκιμάστε ξανά"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Αναζήτηση για το πρόσωπό σας"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Έγινε έλεγχος ταυτότητας προσώπου"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Επιβεβαιώθηκε"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Πατήστε Επιβεβαίωση για ολοκλήρωση"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Ολοκληρώθηκε ο έλεγχος ταυτότητας"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Αγγίξτε τον αισθητήρα δακτυλικών αποτυπωμάτων"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Εικονίδιο δακτυλικών αποτυπωμάτων"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Αναζήτηση για εσάς…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Ειδοποιήσεις"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Φακός"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Δεδομένα κινητής τηλεφωνίας"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Χρήση δεδομένων"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Υπολειπόμενα δεδομένα"</string>
diff --git a/packages/SystemUI/res/values-en-rAU/strings.xml b/packages/SystemUI/res/values-en-rAU/strings.xml
index 4fd8ed9..013b4cb 100644
--- a/packages/SystemUI/res/values-en-rAU/strings.xml
+++ b/packages/SystemUI/res/values-en-rAU/strings.xml
@@ -47,6 +47,7 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Set up input methods"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Physical keyboard"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <string name="usb_device_permission_prompt_warn" msgid="1842558472039505091">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?\nThis app has not been granted record permission but could capture audio through this USB device."</string>
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +120,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancel"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirm"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Try again"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Empty region, tap to cancel authentication"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tap to cancel authentication"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Please try again"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Looking for your face"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Face authenticated"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmed"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tap Confirm to complete"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Authenticated"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Touch the fingerprint sensor"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Fingerprint icon"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Looking for you…"</string>
@@ -363,6 +379,7 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifications"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Torch"</string>
+    <string name="quick_settings_flashlight_camera_in_use" msgid="6120370795890963385">"Camera in use"</string>
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobile data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Data usage"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Remaining data"</string>
@@ -544,7 +561,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"This keeps it in view until you unpin. Touch &amp; hold Overview to unpin."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"This keeps it in view until you unpin. Touch &amp; hold Home to unpin."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"To unpin this screen, touch &amp; hold Back and Overview buttons"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch &amp; hold Back and Home buttons"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch and hold Back and Home buttons"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"To unpin this screen, swipe up &amp; hold"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Got it"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"No, thanks"</string>
diff --git a/packages/SystemUI/res/values-en-rCA/strings.xml b/packages/SystemUI/res/values-en-rCA/strings.xml
index 938cb0d..a21ecb49 100644
--- a/packages/SystemUI/res/values-en-rCA/strings.xml
+++ b/packages/SystemUI/res/values-en-rCA/strings.xml
@@ -47,6 +47,7 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Set up input methods"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Physical keyboard"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <string name="usb_device_permission_prompt_warn" msgid="1842558472039505091">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?\nThis app has not been granted record permission but could capture audio through this USB device."</string>
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +120,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancel"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirm"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Try again"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Empty region, tap to cancel authentication"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tap to cancel authentication"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Please try again"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Looking for your face"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Face authenticated"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmed"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tap Confirm to complete"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Authenticated"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Touch the fingerprint sensor"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Fingerprint icon"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Looking for you…"</string>
@@ -363,6 +379,7 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifications"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Flashlight"</string>
+    <string name="quick_settings_flashlight_camera_in_use" msgid="6120370795890963385">"Camera in use"</string>
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobile data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Data usage"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Remaining data"</string>
@@ -544,7 +561,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"This keeps it in view until you unpin. Touch &amp; hold Overview to unpin."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"This keeps it in view until you unpin. Touch &amp; hold Home to unpin."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"To unpin this screen, touch &amp; hold Back and Overview buttons"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch &amp; hold Back and Home buttons"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch and hold Back and Home buttons"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"To unpin this screen, swipe up &amp; hold"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Got it"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"No, thanks"</string>
diff --git a/packages/SystemUI/res/values-en-rGB/strings.xml b/packages/SystemUI/res/values-en-rGB/strings.xml
index 4fd8ed9..013b4cb 100644
--- a/packages/SystemUI/res/values-en-rGB/strings.xml
+++ b/packages/SystemUI/res/values-en-rGB/strings.xml
@@ -47,6 +47,7 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Set up input methods"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Physical keyboard"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <string name="usb_device_permission_prompt_warn" msgid="1842558472039505091">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?\nThis app has not been granted record permission but could capture audio through this USB device."</string>
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +120,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancel"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirm"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Try again"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Empty region, tap to cancel authentication"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tap to cancel authentication"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Please try again"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Looking for your face"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Face authenticated"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmed"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tap Confirm to complete"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Authenticated"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Touch the fingerprint sensor"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Fingerprint icon"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Looking for you…"</string>
@@ -363,6 +379,7 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifications"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Torch"</string>
+    <string name="quick_settings_flashlight_camera_in_use" msgid="6120370795890963385">"Camera in use"</string>
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobile data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Data usage"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Remaining data"</string>
@@ -544,7 +561,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"This keeps it in view until you unpin. Touch &amp; hold Overview to unpin."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"This keeps it in view until you unpin. Touch &amp; hold Home to unpin."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"To unpin this screen, touch &amp; hold Back and Overview buttons"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch &amp; hold Back and Home buttons"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch and hold Back and Home buttons"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"To unpin this screen, swipe up &amp; hold"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Got it"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"No, thanks"</string>
diff --git a/packages/SystemUI/res/values-en-rIN/strings.xml b/packages/SystemUI/res/values-en-rIN/strings.xml
index 4fd8ed9..013b4cb 100644
--- a/packages/SystemUI/res/values-en-rIN/strings.xml
+++ b/packages/SystemUI/res/values-en-rIN/strings.xml
@@ -47,6 +47,7 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Set up input methods"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Physical keyboard"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <string name="usb_device_permission_prompt_warn" msgid="1842558472039505091">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_DEVICE">%2$s</xliff:g>?\nThis app has not been granted record permission but could capture audio through this USB device."</string>
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Allow <xliff:g id="APPLICATION">%1$s</xliff:g> to access <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Open <xliff:g id="APPLICATION">%1$s</xliff:g> to handle <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +120,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancel"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirm"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Try again"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Empty region, tap to cancel authentication"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tap to cancel authentication"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Please try again"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Looking for your face"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Face authenticated"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmed"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tap Confirm to complete"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Authenticated"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Touch the fingerprint sensor"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Fingerprint icon"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Looking for you…"</string>
@@ -363,6 +379,7 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifications"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Torch"</string>
+    <string name="quick_settings_flashlight_camera_in_use" msgid="6120370795890963385">"Camera in use"</string>
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobile data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Data usage"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Remaining data"</string>
@@ -544,7 +561,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"This keeps it in view until you unpin. Touch &amp; hold Overview to unpin."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"This keeps it in view until you unpin. Touch &amp; hold Home to unpin."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"To unpin this screen, touch &amp; hold Back and Overview buttons"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch &amp; hold Back and Home buttons"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"To unpin this screen, touch and hold Back and Home buttons"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"To unpin this screen, swipe up &amp; hold"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Got it"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"No, thanks"</string>
diff --git a/packages/SystemUI/res/values-en-rXC/strings.xml b/packages/SystemUI/res/values-en-rXC/strings.xml
index 139215aa..d8cfb30 100644
--- a/packages/SystemUI/res/values-en-rXC/strings.xml
+++ b/packages/SystemUI/res/values-en-rXC/strings.xml
@@ -47,6 +47,7 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‎‎‎‎‏‎‏‎‎‎‎‏‏‎‏‏‏‏‏‏‎‏‏‎‏‏‏‏‏‎‏‏‎‎‎‏‏‎‎‏‎‎‎‏‎‎‏‏‏‏‏‏‏‎‎‎‎‎‏‏‎Set up input methods‎‏‎‎‏‎"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‏‎‎‎‏‏‎‎‏‏‎‏‏‎‏‏‏‏‏‏‏‏‎‏‎‏‏‏‏‏‏‏‎‏‎‎‏‏‎‎‏‎‏‏‏‏‎‎‎‎‎‏‏‏‎‏‎‎‏‎‎Physical keyboard‎‏‎‎‏‎"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‎‏‎‏‎‏‎‏‏‎‎‎‏‎‎‎‏‏‏‎‏‎‏‎‎‏‎‏‏‏‎‎‎‎‎‏‏‎‎‏‏‏‎‎‎‎‎‏‎‎‏‏‏‏‏‏‏‏‎Allow ‎‏‎‎‏‏‎<xliff:g id="APPLICATION">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to access ‎‏‎‎‏‏‎<xliff:g id="USB_DEVICE">%2$s</xliff:g>‎‏‎‎‏‏‏‎?‎‏‎‎‏‎"</string>
+    <string name="usb_device_permission_prompt_warn" msgid="1842558472039505091">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‎‏‏‎‎‏‎‎‏‎‎‎‎‏‎‏‎‏‎‎‏‎‏‎‏‏‎‎‎‎‎‎‏‏‏‏‎‎‏‏‎‏‎‎‎‏‏‏‎‎‏‏‎‎‎‎‏‏‎Allow ‎‏‎‎‏‏‎<xliff:g id="APPLICATION">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to access ‎‏‎‎‏‏‎<xliff:g id="USB_DEVICE">%2$s</xliff:g>‎‏‎‎‏‏‏‎?‎‏‎‎‏‏‎\n‎‏‎‎‏‏‏‎This app has not been granted record permission but could capture audio through this USB device.‎‏‎‎‏‎"</string>
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‎‎‏‎‎‎‏‏‎‏‏‏‎‏‎‏‎‏‎‎‎‎‎‎‎‎‏‏‏‏‏‏‎‎‏‎‏‎‏‎‏‎‎‎‎‎‎‎‎‏‏‎‏‏‎‏‎‏‏‏‎Allow ‎‏‎‎‏‏‎<xliff:g id="APPLICATION">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to access ‎‏‎‎‏‏‎<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>‎‏‎‎‏‏‏‎?‎‏‎‎‏‎"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‎‏‏‏‎‏‎‎‎‎‏‎‎‎‏‎‏‏‏‏‏‏‏‏‎‏‏‏‎‏‏‏‎‏‏‎‎‏‎‎‎‎‎‎‎‏‏‏‎‏‎‎‏‎‎‎‎‎‎‏‎Open ‎‏‎‎‏‏‎<xliff:g id="APPLICATION">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to handle ‎‏‎‎‏‏‎<xliff:g id="USB_DEVICE">%2$s</xliff:g>‎‏‎‎‏‏‏‎?‎‏‎‎‏‎"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‎‎‎‎‏‎‎‏‎‎‎‏‎‎‏‎‏‎‎‏‎‏‏‏‏‏‏‏‏‏‏‎‏‏‏‎‎‎‏‏‎‏‏‏‏‏‎‏‏‏‏‏‎‏‏‎‎‏‎Open ‎‏‎‎‏‏‎<xliff:g id="APPLICATION">%1$s</xliff:g>‎‏‎‎‏‏‏‎ to handle ‎‏‎‎‏‏‎<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>‎‏‎‎‏‏‏‎?‎‏‎‎‏‎"</string>
@@ -119,12 +120,27 @@
     <string name="cancel" msgid="6442560571259935130">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‎‏‎‏‏‎‏‎‎‎‏‎‎‏‎‎‏‎‏‎‏‏‎‏‎‎‏‎‎‏‎‏‎‏‏‏‏‎‎‎‏‎‏‏‎‏‏‎‎‏‏‎‎‏‏‎‏‎‎Cancel‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‏‎‎‏‏‏‎‎‎‏‎‎‏‎‎‏‎‎‏‏‏‎‏‏‎‎‎‎‎‏‎‎‎‎‏‎‎‎‎‎‎‎‎‎‎‎‏‏‏‎‎‎‎‎‏‎‎‎‏‎‎Confirm‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‏‎‎‏‎‏‏‏‏‎‏‏‎‏‎‎‎‎‎‏‎‏‏‎‎‎‏‏‎‎‏‏‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‎‏‏‏‏‏‎‎‎‎‏‎Try again‎‏‎‎‏‎"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‏‏‏‎‏‏‏‏‏‏‏‎‎‏‏‎‎‎‎‏‎‏‎‎‏‏‎‎‎‎‏‎‏‎‏‎‎‎‏‎‎‏‎‏‎‏‎‎‎‏‎‎‎‎‏‏‎‏‎‏‎Empty region, tap to cancel authentication‎‏‎‎‏‎"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‏‏‏‏‏‏‏‎‏‎‎‎‎‎‎‏‎‎‎‎‏‎‎‎‏‎‏‏‏‎‏‎‎‎‏‎‏‏‏‏‏‏‏‏‎‎‎‏‎‎‏‎‏‎‏‏‏‏‏‎Tap to cancel authentication‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‏‎‎‏‏‎‏‎‏‏‎‎‎‎‎‏‎‏‏‎‎‎‎‎‎‏‏‎‏‏‎‎‏‏‎‏‎‎‎‎‏‎‎‏‏‏‏‎‏‎‏‏‏‎‎‏‏‎‎Please try again‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‏‎‏‎‏‎‎‎‎‎‎‏‏‎‏‏‎‏‏‏‏‏‏‎‏‏‏‎‏‏‎‏‏‎‏‏‎‎‏‎‏‏‎‎‏‏‏‏‎‎‏‎‎‎‏‎‎‎‎Looking for your face‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‎‎‎‏‎‎‎‎‏‏‎‎‏‏‎‏‏‏‎‏‎‏‏‏‎‏‏‎‏‏‎‎‏‏‎‏‏‏‎‏‏‎‏‎‏‏‎‏‏‎‎‏‏‎‏‎‏‏‎Face authenticated‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‏‏‏‏‎‎‏‏‎‎‏‎‎‏‎‏‏‎‎‏‏‏‏‏‎‏‏‎‎‏‎‏‎‎‏‏‏‏‎‎‏‏‏‎‎‎‎‏‎‏‏‏‎‎‏‏‏‏‎Confirmed‎‏‎‎‏‎"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‏‏‏‏‎‎‎‎‎‎‏‏‏‏‎‏‏‏‎‎‎‏‏‏‏‎‎‎‏‎‏‏‎‎‏‏‏‏‏‎‎‏‏‎‏‏‎‎‎‎‎‎‏‎‎‎‎‏‎‎‎Tap Confirm to complete‎‏‎‎‏‎"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‎‏‎‎‎‏‎‎‎‏‎‎‎‏‏‎‏‏‎‏‎‎‎‏‏‏‎‎‏‎‎‎‏‎‏‏‎‏‎‎‎‎‏‎‏‏‎‎‎‏‏‏‎‎‏‏‏‎‏‎Authenticated‎‏‎‎‏‎"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‏‎‏‏‎‎‎‎‏‏‏‏‏‎‎‏‎‎‎‎‎‏‎‎‏‏‏‏‏‏‎‎‏‏‏‎‏‎‎‏‏‏‎‎‏‎‎‎‏‏‏‎‏‏‏‎‎‎‎‎‏‎Touch the fingerprint sensor‎‏‎‎‏‎"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‎‏‎‏‏‎‏‎‏‏‏‏‎‏‎‏‎‏‎‏‎‎‏‎‏‏‎‏‎‎‎‎‏‏‎‏‎‏‎‏‏‏‏‏‏‏‎‏‏‎‏‏‎‏‎‏‎‏‎‏‎‎Fingerprint icon‎‏‎‎‏‎"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‏‎‎‎‎‏‏‏‎‏‎‏‎‎‎‎‎‎‏‏‏‏‎‏‏‎‏‎‏‎‎‏‎‏‎‎‏‎‏‏‏‏‎‏‏‎‎‏‎‏‎‏‏‎‏‏‏‎‎‎‎‏‎Looking for you…‎‏‎‎‏‎"</string>
@@ -363,6 +379,7 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‎‎‎‏‎‏‏‎‏‏‏‎‏‏‎‎‎‎‏‏‏‏‏‎‎‎‎‎‏‏‎‏‎‎‏‏‏‏‏‎‎‎‎‎‎‏‎‎‏‏‎‏‏‏‏‎‏‏‎‏‏‎Notifications‎‏‎‎‏‎"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‏‎‏‏‎‎‏‏‎‏‎‎‏‎‎‎‏‎‏‎‎‏‏‏‏‎‎‎‎‎‎‏‎‏‎‏‎‎‏‏‎‏‏‎‏‏‎‎‏‎‎‏‏‏‎‏‎‏‎‎Flashlight‎‏‎‎‏‎"</string>
+    <string name="quick_settings_flashlight_camera_in_use" msgid="6120370795890963385">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‏‏‎‏‎‏‎‎‏‏‏‎‏‏‏‏‏‏‏‎‏‏‎‎‏‏‎‎‏‏‏‏‏‏‎‎‏‏‏‎‏‏‎‎‎‎‎‏‎‏‏‏‎‎‏‏‏‎‏‏‏‎‎‏‎Camera in use‎‏‎‎‏‎"</string>
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‏‎‏‏‎‎‏‎‏‏‎‎‏‏‏‏‎‎‏‎‏‏‎‏‎‎‏‎‏‎‏‏‎‎‏‏‎‏‎‎‏‎‏‏‎‎‏‎‏‏‎‎‎‏‎‏‎‎‏‎‎‎‏‏‎Mobile data‎‏‎‎‏‎"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‏‏‏‎‏‏‎‏‎‎‎‎‏‎‎‏‏‏‎‏‎‎‎‏‏‎‎‎‏‏‏‏‏‏‏‎‏‏‏‎‏‎‎‎‏‏‎‎‎‏‏‎‎‏‏‎‎‎‎‎‏‎‎Data usage‎‏‎‎‏‎"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"‎‏‎‎‎‎‎‏‎‏‏‏‎‎‎‎‎‎‏‎‎‏‎‎‎‎‏‏‏‏‏‎‎‏‎‏‎‎‎‎‎‎‏‏‏‏‎‎‏‏‎‎‏‏‏‎‏‎‏‏‏‎‏‏‎‎‎‎‏‎‎‏‎‏‎‏‏‏‏‏‎‏‏‏‎‎‎‎‎‎‎‎‏‎Remaining data‎‏‎‎‏‎"</string>
diff --git a/packages/SystemUI/res/values-es-rUS/strings.xml b/packages/SystemUI/res/values-es-rUS/strings.xml
index 6adf6d5..4b2943c 100644
--- a/packages/SystemUI/res/values-es-rUS/strings.xml
+++ b/packages/SystemUI/res/values-es-rUS/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurar métodos de intro."</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teclado físico"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"¿Deseas permitir que <xliff:g id="APPLICATION">%1$s</xliff:g> acceda a <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"¿Deseas permitir que <xliff:g id="APPLICATION">%1$s</xliff:g> acceda a <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"¿Deseas abrir <xliff:g id="APPLICATION">%1$s</xliff:g> para usar <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"¿Deseas abrir <xliff:g id="APPLICATION">%1$s</xliff:g> para usar <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancelar"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmar"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Volver a intentarlo"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Espacio vacío; presiona para cancelar la autenticación"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Presiona para cancelar la autenticación"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Vuelve a intentarlo"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Buscando tu rostro"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Se autenticó el rostro"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmado"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Presiona Confirmar para completarla"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenticado"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Toca el sensor de huellas digitales"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ícono de huella digital"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Autenticando tu rostro…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificaciones"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Linterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Datos móviles"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Uso de datos"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Datos restantes"</string>
diff --git a/packages/SystemUI/res/values-es/strings.xml b/packages/SystemUI/res/values-es/strings.xml
index c4f3445..903c50a 100644
--- a/packages/SystemUI/res/values-es/strings.xml
+++ b/packages/SystemUI/res/values-es/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurar métodos de entrada"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teclado físico"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"¿Quieres permitir que <xliff:g id="APPLICATION">%1$s</xliff:g> acceda a <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"¿Quieres permitir que <xliff:g id="APPLICATION">%1$s</xliff:g> acceda a <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"¿Quieres abrir <xliff:g id="APPLICATION">%1$s</xliff:g> para utilizar <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"¿Quieres abrir <xliff:g id="APPLICATION">%1$s</xliff:g> para utilizar <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancelar"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmar"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Reintentar"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Zona vacía. Toca para cancelar la autenticación."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Toca para cancelar la autenticación"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Vuelve a intentarlo"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Buscando tu cara"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Cara autenticada"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmada"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Toca Confirmar para completar la acción"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Se ha autenticado"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Toca el sensor de huellas digitales"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icono de huella digital"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Buscando tu cara…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificaciones"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Linterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Datos móviles"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Uso de datos"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Datos restantes"</string>
@@ -544,7 +563,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"La pantalla se mantiene visible hasta que dejas de fijarla. Para ello, mantén pulsado el botón Aplicaciones recientes."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"La pantalla se mantiene visible hasta que dejas de fijarla. Para ello, mantén pulsado el botón Inicio."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"Mantén pulsado el botón Atrás y el de aplicaciones recientes para dejar de fijar esta pantalla"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Mantén pulsado el botón Atrás y el de Inicio para dejar de fijar esta pantalla"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Mantén pulsados los botones Atrás e Inicio para dejar de fijar esta pantalla"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"Para dejar de fijar esta pantalla, desliza el dedo hacia arriba y mantenla pulsada"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Entendido"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"No, gracias"</string>
diff --git a/packages/SystemUI/res/values-et/strings.xml b/packages/SystemUI/res/values-et/strings.xml
index a8ad1ec..113b207 100644
--- a/packages/SystemUI/res/values-et/strings.xml
+++ b/packages/SystemUI/res/values-et/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Seadista sisestusmeetodeid"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Füüsiline klaviatuur"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Kas lubada rakendusele <xliff:g id="APPLICATION">%1$s</xliff:g> juurdepääs seadmele <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Kas lubada rakendusele <xliff:g id="APPLICATION">%1$s</xliff:g> juurdepääs seadmele <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Kas avada rakendus <xliff:g id="APPLICATION">%1$s</xliff:g> seadme <xliff:g id="USB_DEVICE">%2$s</xliff:g> kasutamiseks?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Kas avada rakendus <xliff:g id="APPLICATION">%1$s</xliff:g> seadme <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> kasutamiseks?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Tühista"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Kinnita"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Proovi uuesti"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Tühi piirkond, puudutage autentimise tühistamiseks"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Puudutage autentimise tühistamiseks"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Proovige uuesti"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Teie näo vaatamine"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Nägu on autenditud"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Kinnitatud"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Lõpuleviimiseks puudutage nuppu Kinnita"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenditud"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Puudutage sõrmejäljeandurit"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Sõrmejälje ikoon"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Otsitakse teid …"</string>
@@ -192,7 +209,7 @@
     <string name="not_default_data_content_description" msgid="9194667237765917844">"Ei ole andmeside kasutamiseks seadistatud"</string>
     <string name="cell_data_off" msgid="1051264981229902873">"Väljas"</string>
     <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Jagamine Bluetoothiga."</string>
-    <string name="accessibility_airplane_mode" msgid="834748999790763092">"Lennurežiim."</string>
+    <string name="accessibility_airplane_mode" msgid="834748999790763092">"Lennukirežiim."</string>
     <string name="accessibility_vpn_on" msgid="5993385083262856059">"VPN on sees."</string>
     <string name="accessibility_no_sims" msgid="3957997018324995781">"SIM-kaarti pole."</string>
     <string name="carrier_network_change_mode" msgid="8149202439957837762">"Operaatori võrku muudetakse"</string>
@@ -229,7 +246,7 @@
     <string name="accessibility_quick_settings_airplane_off" msgid="7786329360056634412">"Lennurežiim on väljas."</string>
     <string name="accessibility_quick_settings_airplane_on" msgid="6406141469157599296">"Lennurežiim on sees."</string>
     <string name="accessibility_quick_settings_airplane_changed_off" msgid="66846307818850664">"Lennurežiim on välja lülitatud."</string>
-    <string name="accessibility_quick_settings_airplane_changed_on" msgid="8983005603505087728">"Lennurežiim on sisse lülitatud."</string>
+    <string name="accessibility_quick_settings_airplane_changed_on" msgid="8983005603505087728">"Lennukirežiim on sisse lülitatud."</string>
     <string name="accessibility_quick_settings_dnd_none_on" msgid="2960643943620637020">"täielik vaikus"</string>
     <string name="accessibility_quick_settings_dnd_alarms_on" msgid="3357131899365865386">"ainult alarmid"</string>
     <string name="accessibility_quick_settings_dnd" msgid="5555155552520665891">"Mitte segada."</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Märguanded"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Taskulamp"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobiilne andmeside"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Andmeside kasutus"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Järelejäänud andmemaht"</string>
@@ -597,7 +616,7 @@
     <string name="status_bar_ethernet" msgid="5044290963549500128">"Ethernet"</string>
     <string name="status_bar_alarm" msgid="8536256753575881818">"Äratus"</string>
     <string name="status_bar_work" msgid="6022553324802866373">"Tööprofiil"</string>
-    <string name="status_bar_airplane" msgid="7057575501472249002">"Lennurežiim"</string>
+    <string name="status_bar_airplane" msgid="7057575501472249002">"Lennukirežiim"</string>
     <string name="add_tile" msgid="2995389510240786221">"Paani lisamine"</string>
     <string name="broadcast_tile" msgid="3894036511763289383">"Paani ülekandmine"</string>
     <string name="zen_alarm_warning_indef" msgid="3482966345578319605">"Kuulete järgmist äratust kell <xliff:g id="WHEN">%1$s</xliff:g> vaid siis, kui lülitate selle enne seda välja"</string>
diff --git a/packages/SystemUI/res/values-eu/strings.xml b/packages/SystemUI/res/values-eu/strings.xml
index 799d773..e541329 100644
--- a/packages/SystemUI/res/values-eu/strings.xml
+++ b/packages/SystemUI/res/values-eu/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Konfiguratu idazketa-metodoak"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teklatu fisikoa"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> atzitzeko baimena eman nahi diozu <xliff:g id="APPLICATION">%1$s</xliff:g> aplikazioari?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> atzitzeko baimena eman nahi diozu <xliff:g id="APPLICATION">%1$s</xliff:g> aplikazioari?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="APPLICATION">%1$s</xliff:g> ireki nahi duzu <xliff:g id="USB_DEVICE">%2$s</xliff:g> kudeatzeko?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="APPLICATION">%1$s</xliff:g> ireki nahi duzu <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> kudeatzeko?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Utzi"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Berretsi"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Saiatu berriro"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Hutsik dago eremua. Sakatu autentifikatzeari uzteko."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Sakatu hau autentifikazioa bertan behera uzteko"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Saiatu berriro"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Aurpegia bilatzen"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Autentifikatu da aurpegia"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Berretsita"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Amaitzeko, sakatu \"Berretsi\""</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentifikatuta"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Sakatu hatz-marken sentsorea"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Hatz-markaren ikonoa"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Zure bila…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Jakinarazpenak"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Linterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Datu-konexioa"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Datuen erabilera"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Geratzen diren datuak"</string>
@@ -896,7 +915,7 @@
     <string name="mobile_data_disable_message" msgid="4756541658791493506">"<xliff:g id="CARRIER">%s</xliff:g> erabilita ezingo dituzu erabili datuak edo Internet. Wifi-sare baten bidez soilik konektatu ahal izango zara Internetera."</string>
     <string name="mobile_data_disable_message_default_carrier" msgid="6078110473451946831">"Uneko operadorea"</string>
     <string name="touch_filtered_warning" msgid="8671693809204767551">"Aplikazio bat baimen-eskaera oztopatzen ari denez, ezarpenek ezin dute egiaztatu erantzuna."</string>
-    <string name="slice_permission_title" msgid="7465009437851044444">"<xliff:g id="APP_0">%1$s</xliff:g> aplikazioari <xliff:g id="APP_2">%2$s</xliff:g> aplikazioaren zatiak erakusteko baimena eman nahi diozu?"</string>
+    <string name="slice_permission_title" msgid="7465009437851044444">"<xliff:g id="APP_2">%2$s</xliff:g> aplikazioaren zatiak erakusteko baimena eman nahi diozu <xliff:g id="APP_0">%1$s</xliff:g> aplikazioari?"</string>
     <string name="slice_permission_text_1" msgid="3514586565609596523">"- <xliff:g id="APP">%1$s</xliff:g> aplikazioaren informazioa irakur dezake."</string>
     <string name="slice_permission_text_2" msgid="3146758297471143723">"- <xliff:g id="APP">%1$s</xliff:g> aplikazioan ekintzak gauza ditzake."</string>
     <string name="slice_permission_checkbox" msgid="7986504458640562900">"Baimendu <xliff:g id="APP">%1$s</xliff:g> aplikazioari edozein aplikazioren zatiak erakustea"</string>
diff --git a/packages/SystemUI/res/values-fa/strings.xml b/packages/SystemUI/res/values-fa/strings.xml
index eeb30a0..232f7a2 100644
--- a/packages/SystemUI/res/values-fa/strings.xml
+++ b/packages/SystemUI/res/values-fa/strings.xml
@@ -28,15 +28,15 @@
     <string name="battery_low_percent_format" msgid="2900940511201380775">"<xliff:g id="PERCENTAGE">%s</xliff:g> باقی مانده است"</string>
     <string name="battery_low_percent_format_hybrid" msgid="6838677459286775617">"<xliff:g id="PERCENTAGE">%1$s</xliff:g> باقی مانده، براساس اشتفاده شما حدود <xliff:g id="TIME">%2$s</xliff:g> باقی مانده است"</string>
     <string name="battery_low_percent_format_hybrid_short" msgid="9025795469949145586">"<xliff:g id="PERCENTAGE">%1$s</xliff:g> باقی مانده، حدود <xliff:g id="TIME">%2$s</xliff:g> باقی مانده است"</string>
-    <string name="battery_low_percent_format_saver_started" msgid="7879389868952879166">"<xliff:g id="PERCENTAGE">%s</xliff:g> باقی مانده است. بهینه‌سازی باتری روشن است."</string>
+    <string name="battery_low_percent_format_saver_started" msgid="7879389868952879166">"<xliff:g id="PERCENTAGE">%s</xliff:g> باقی مانده است. «بهینه‌سازی باتری» روشن است."</string>
     <string name="invalid_charger" msgid="2741987096648693172">"‏ازطریق USB شارژ نمی‌شود. از شارژر ارائه‌شده با دستگاه استفاده کنید."</string>
     <string name="invalid_charger_title" msgid="2836102177577255404">"‏ازطریق USB شارژ نمی‌شود"</string>
     <string name="invalid_charger_text" msgid="6480624964117840005">"از شارژر ارائه‌شده با دستگاه استفاده کنید"</string>
     <string name="battery_low_why" msgid="4553600287639198111">"تنظیمات"</string>
-    <string name="battery_saver_confirmation_title" msgid="2052100465684817154">"بهینه‌سازی باتری روشن شود؟"</string>
-    <string name="battery_saver_confirmation_title_generic" msgid="2090922638411744540">"درباره بهینه‌سازی باتری"</string>
+    <string name="battery_saver_confirmation_title" msgid="2052100465684817154">"«بهینه‌سازی باتری» روشن شود؟"</string>
+    <string name="battery_saver_confirmation_title_generic" msgid="2090922638411744540">"درباره «بهینه‌سازی باتری»"</string>
     <string name="battery_saver_confirmation_ok" msgid="7507968430447930257">"روشن کردن"</string>
-    <string name="battery_saver_start_action" msgid="8187820911065797519">"بهینه‌سازی باتری را روشن کنید"</string>
+    <string name="battery_saver_start_action" msgid="8187820911065797519">"«بهینه‌سازی باتری» را روشن کنید"</string>
     <string name="status_bar_settings_settings_button" msgid="3023889916699270224">"تنظیمات"</string>
     <string name="status_bar_settings_wifi_button" msgid="1733928151698311923">"Wi-Fi"</string>
     <string name="status_bar_settings_auto_rotation" msgid="3790482541357798421">"چرخش خودکار صفحه"</string>
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"تنظیم روش‌های ورودی"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"صفحه‌کلید فیزیکی"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"به <xliff:g id="APPLICATION">%1$s</xliff:g> برای دسترسی به <xliff:g id="USB_DEVICE">%2$s</xliff:g> اجازه داده شود؟"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"به <xliff:g id="APPLICATION">%1$s</xliff:g> برای دسترسی به <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> اجازه داده شود؟"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"برای استفاده از <xliff:g id="USB_DEVICE">%2$s</xliff:g>، <xliff:g id="APPLICATION">%1$s</xliff:g> باز شود؟"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"برای استفاده از <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>، <xliff:g id="APPLICATION">%1$s</xliff:g> باز شود؟"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"لغو"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"تأیید"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"امتحان مجدد"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"برای لغو احراز هویت، در قسمت خالی ضربه بزنید"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"برای لغو راستی‌آزمایی ضربه بزنید"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"لطفاً دوباره امتحان کنید"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"درحال جستجوی چهره"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"چهره احراز هویت شد"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"تأیید شد"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"برای تکمیل، روی تأیید ضربه بزنید"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"راستی‌آزمایی‌شده"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"حسگر اثر انگشت را لمس کنید"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"نماد اثر انگشت"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"درحال جستجوی شما…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"اعلان‌ها"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"چراغ قوه"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"داده تلفن همراه"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"مصرف داده"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"داده‌های باقی‌مانده"</string>
@@ -450,9 +469,9 @@
     <string name="user_remove_user_title" msgid="4681256956076895559">"کاربر حذف شود؟"</string>
     <string name="user_remove_user_message" msgid="1453218013959498039">"همه برنامه‌ها و داده‌های این کاربر حذف می‌شود."</string>
     <string name="user_remove_user_remove" msgid="7479275741742178297">"حذف"</string>
-    <string name="battery_saver_notification_title" msgid="8614079794522291840">"بهینه‌سازی باتری روشن است"</string>
+    <string name="battery_saver_notification_title" msgid="8614079794522291840">"«بهینه‌سازی باتری» روشن است"</string>
     <string name="battery_saver_notification_text" msgid="820318788126672692">"عملکرد و اطلاعات پس‌زمینه را کاهش می‌دهد"</string>
-    <string name="battery_saver_notification_action_text" msgid="132118784269455533">"بهینه‌سازی باتری را خاموش کنید"</string>
+    <string name="battery_saver_notification_action_text" msgid="132118784269455533">"«بهینه‌سازی باتری» را خاموش کنید"</string>
     <string name="media_projection_dialog_text" msgid="8585357687598538511">"هنگام ضبط یا ارسال محتوا، <xliff:g id="APP_SEEKING_PERMISSION">%s</xliff:g> می‌تواند هرگونه اطلاعات حساس را (مانند صوت، گذرواژه، اطلاعات پرداخت، عکس و پیام) که روی صفحه‌تان نشان داده می‌شود یا از دستگاهتان پخش می‌شود ضبط کند."</string>
     <string name="media_projection_dialog_service_text" msgid="3075544489835858258">"هنگام ضبط یا ارسال محتوا، ارائه‌دهنده خدمات این عملکرد می‌تواند هرگونه اطلاعات حساس (مانند صوت، گذرواژه، اطلاعات پرداخت، عکس و پیام) را که روی صفحه‌تان نشان داده می‌شود یا از دستگاهتان پخش می‌شود ضبط کند."</string>
     <string name="media_projection_dialog_title" msgid="8124184308671641248">"افشای اطلاعات حساس درحین ارسال/ضبط محتوا"</string>
diff --git a/packages/SystemUI/res/values-fi/strings.xml b/packages/SystemUI/res/values-fi/strings.xml
index 7be438a..5767c3c 100644
--- a/packages/SystemUI/res/values-fi/strings.xml
+++ b/packages/SystemUI/res/values-fi/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Määritä syöttötavat"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fyysinen näppäimistö"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Saako <xliff:g id="APPLICATION">%1$s</xliff:g> käyttöoikeuden (<xliff:g id="USB_DEVICE">%2$s</xliff:g>)?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Saako <xliff:g id="APPLICATION">%1$s</xliff:g> käyttöoikeuden (<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>)?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Avataanko <xliff:g id="APPLICATION">%1$s</xliff:g>, jotta <xliff:g id="USB_DEVICE">%2$s</xliff:g> voidaan ottaa käyttöön?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Avataanko <xliff:g id="APPLICATION">%1$s</xliff:g>, jotta <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> voidaan ottaa käyttöön?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Peruuta"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Vahvista"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Yritä uudelleen"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Tyhjä alue, napauta sitä peruuttaaksesi tunnistuksen"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Peruuta todennus napauttamalla"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Yritä uudelleen"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Kasvojasi katsotaan"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Kasvot tunnistettu"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Vahvistettu"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Valitse lopuksi Vahvista"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Todennettu"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Kosketa sormenjälkitunnistinta"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Sormenjälkikuvake"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Etsitään kasvoja…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Ilmoitukset"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Taskulamppu"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobiilidata"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Datakäyttö"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Käytettävissä"</string>
diff --git a/packages/SystemUI/res/values-fr-rCA/strings.xml b/packages/SystemUI/res/values-fr-rCA/strings.xml
index e8e4232..04138c0 100644
--- a/packages/SystemUI/res/values-fr-rCA/strings.xml
+++ b/packages/SystemUI/res/values-fr-rCA/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurer les modes de saisie"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Clavier physique"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Autoriser <xliff:g id="APPLICATION">%1$s</xliff:g> à accéder à <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Autoriser <xliff:g id="APPLICATION">%1$s</xliff:g> à accéder à <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Ouvrir <xliff:g id="APPLICATION">%1$s</xliff:g> pour utiliser <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Ouvrir <xliff:g id="APPLICATION">%1$s</xliff:g> pour utiliser <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -56,7 +58,7 @@
     <string name="always_use_device" msgid="4015357883336738417">"Toujours ouvrir <xliff:g id="APPLICATION">%1$s</xliff:g> lorsque <xliff:g id="USB_DEVICE">%2$s</xliff:g> est connecté"</string>
     <string name="always_use_accessory" msgid="3257892669444535154">"Toujours ouvrir <xliff:g id="APPLICATION">%1$s</xliff:g> lorsque <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> est connecté"</string>
     <string name="usb_debugging_title" msgid="4513918393387141949">"Autoriser le débogage USB?"</string>
-    <string name="usb_debugging_message" msgid="2220143855912376496">"Empreinte numérique de la clé RSA de l\'ordinateur : \n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
+    <string name="usb_debugging_message" msgid="2220143855912376496">"Empreinte digitale numérique de la clé RSA de l\'ordinateur : \n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
     <string name="usb_debugging_always" msgid="303335496705863070">"Toujours autoriser sur cet ordinateur"</string>
     <string name="usb_debugging_allow" msgid="2272145052073254852">"Autoriser"</string>
     <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"Débogage USB non autorisé"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Annuler"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmer"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Réessayer"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Région vide, touchez l\'écran pour annuler l\'authentification"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Touchez ici pour annuler l\'authentification"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Veuillez réessayer"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"L\'appareil recherche votre visage…"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Visage authentifié"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmé"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Touchez Confirmer pour terminer"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Authentifié"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Touchez le capteur d\'empreintes digitales"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icône d\'empreinte digitale"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Recherche de votre visage…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifications"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lampe de poche"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Données cellulaires"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Utilisation de données"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Données restantes"</string>
diff --git a/packages/SystemUI/res/values-fr/strings.xml b/packages/SystemUI/res/values-fr/strings.xml
index 3bc9378..7191426 100644
--- a/packages/SystemUI/res/values-fr/strings.xml
+++ b/packages/SystemUI/res/values-fr/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurer les modes de saisie"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Clavier physique"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Autoriser <xliff:g id="APPLICATION">%1$s</xliff:g> à accéder à <xliff:g id="USB_DEVICE">%2$s</xliff:g> ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Autoriser <xliff:g id="APPLICATION">%1$s</xliff:g> à accéder à <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Ouvrir <xliff:g id="APPLICATION">%1$s</xliff:g> pour utiliser <xliff:g id="USB_DEVICE">%2$s</xliff:g> ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Ouvrir <xliff:g id="APPLICATION">%1$s</xliff:g> pour utiliser <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Annuler"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmer"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Réessayer"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Zone vide : appuyez pour annuler l\'authentification"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Appuyer pour annuler l\'authentification"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Veuillez réessayer"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Recherche de votre visage…"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Visage authentifié"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmé"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Appuyez sur \"Confirmer\" pour terminer"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Authentifié"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Appuyez sur le lecteur d\'empreinte digitale"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icône d\'empreinte digitale"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Recherche de votre visage…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifications"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lampe de poche"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Données mobiles"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Conso des données"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Données restantes"</string>
diff --git a/packages/SystemUI/res/values-gl/strings.xml b/packages/SystemUI/res/values-gl/strings.xml
index 5480eab..4262d88 100644
--- a/packages/SystemUI/res/values-gl/strings.xml
+++ b/packages/SystemUI/res/values-gl/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurar métodos de entrada"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teclado físico"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Queres permitir que <xliff:g id="APPLICATION">%1$s</xliff:g> acceda a <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Queres permitir que <xliff:g id="APPLICATION">%1$s</xliff:g> acceda a <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Queres abrir <xliff:g id="APPLICATION">%1$s</xliff:g> para utilizar <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Queres abrir <xliff:g id="APPLICATION">%1$s</xliff:g> para utilizar <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancelar"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmar"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Tentar de novo"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"A rexión está baleira; tócaa para cancelar a autenticación"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Toca para cancelar a autenticación"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Téntao de novo"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Buscando a túa cara"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Autenticouse a cara"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmada"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Toca Confirmar para completar o proceso"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenticado"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Toca o sensor de impresión dixital"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icona de impresión dixital"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Buscándote…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificacións"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lanterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Datos móbiles"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Uso de datos"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Datos restantes"</string>
diff --git a/packages/SystemUI/res/values-gu/strings.xml b/packages/SystemUI/res/values-gu/strings.xml
index 1a15cf7..66f9a7a 100644
--- a/packages/SystemUI/res/values-gu/strings.xml
+++ b/packages/SystemUI/res/values-gu/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ઇનપુટ પદ્ધતિઓ સેટ કરો"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ભૌતિક કીબોર્ડ"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ના ઍક્સેસ માટે <xliff:g id="APPLICATION">%1$s</xliff:g>ને મંજૂરી આપીએ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ના ઍક્સેસ માટે <xliff:g id="APPLICATION">%1$s</xliff:g>ને મંજૂરી આપીએ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ને હૅન્ડલ કરવા માટે <xliff:g id="APPLICATION">%1$s</xliff:g>ને ખોલીએ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ને હૅન્ડલ કરવા માટે <xliff:g id="APPLICATION">%1$s</xliff:g>ને ખોલીએ?"</string>
@@ -56,7 +58,7 @@
     <string name="always_use_device" msgid="4015357883336738417">"જ્યારે <xliff:g id="USB_DEVICE">%2$s</xliff:g> કનેક્ટેડ હોય ત્યારે <xliff:g id="APPLICATION">%1$s</xliff:g>ને હંમેશા ખોલો"</string>
     <string name="always_use_accessory" msgid="3257892669444535154">"જ્યારે <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> કનેક્ટેડ હોય ત્યારે <xliff:g id="APPLICATION">%1$s</xliff:g>ને હંમેશા ખોલો"</string>
     <string name="usb_debugging_title" msgid="4513918393387141949">"USB ડિબગિંગને મંજૂરી આપીએ?"</string>
-    <string name="usb_debugging_message" msgid="2220143855912376496">"કમ્પ્યુટરની RSA મુખ્ય ફિંગરપ્રિંટ આ છે:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
+    <string name="usb_debugging_message" msgid="2220143855912376496">"કમ્પ્યુટરની RSA મુખ્ય ફિંગરપ્રિન્ટ આ છે:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
     <string name="usb_debugging_always" msgid="303335496705863070">"હંમેશા આ કમ્પ્યુટરથી મંજૂરી આપો"</string>
     <string name="usb_debugging_allow" msgid="2272145052073254852">"મંજૂરી આપો"</string>
     <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"USB ડીબગિંગની મંજૂરી નથી"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"રદ કરો"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"કન્ફર્મ કરો"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ફરી પ્રયાસ કરો"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ખાલી વિસ્તાર, પ્રમાણીકરણ રદ કરવા માટે ટૅપ કરો"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"પ્રમાણીકરણ રદ કરવા માટે ટૅપ કરો"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"કૃપા કરી ફરી પ્રયાસ કરો"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"તમારો ચહેરો શોધી રહ્યાં છીએ"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ચહેરાનું પ્રમાણીકરણ થયું"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"પુષ્ટિ કરી"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"પરીક્ષણ પૂર્ણ કરવા કન્ફર્મ કરોને ટૅપ કરો"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"પ્રમાણિત"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ફિંગરપ્રિન્ટના સેન્સરને સ્પર્શ કરો"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ફિંગરપ્રિન્ટનું આઇકન"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"તમારા માટે શોધી રહ્યાં છે..."</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"નોટિફિકેશનો"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ફ્લેશલાઇટ"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"મોબાઇલ ડેટા"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ડેટા વપરાશ"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"બાકી ડેટા"</string>
diff --git a/packages/SystemUI/res/values-hi/strings.xml b/packages/SystemUI/res/values-hi/strings.xml
index 3c18b0d..c49cae4 100644
--- a/packages/SystemUI/res/values-hi/strings.xml
+++ b/packages/SystemUI/res/values-hi/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"इनपुट का तरीका सेट करें"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"सामान्य कीबोर्ड"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> को <xliff:g id="USB_DEVICE">%2$s</xliff:g> के ऐक्सेस की अनुमति दें?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> को <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> के ऐक्सेस की अनुमति दें?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> के लिए <xliff:g id="APPLICATION">%1$s</xliff:g> खोलें?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> के लिए <xliff:g id="APPLICATION">%1$s</xliff:g> खोलें?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"रद्द करें"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"पुष्टि करें"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"फिर से कोशिश करें"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"कोई चेहरा नहीं मिला, टैप करके पुष्टि की प्रक्रिया रद्द करें"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"पुष्टि की प्रक्रिया रद्द करने के लिए टैप करें"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"कृपया फिर से कोशिश करें"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"आपके चेहरे की पुष्टि की जा रही है"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"चेहरे की पुष्टि हो गई"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"पुष्टि हो गई"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"\'पुष्टि करें\' पर टैप करके पूरा करें"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"पुष्टि हो गई"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"फ़िंगरप्रिंट सेंसर को छुएं"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"फ़िंगरप्रिंट आइकॉन"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"आपको पहचान रहा है…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"सूचनाएं"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"फ़्लैशलाइट"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"मोबाइल डेटा"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"डेटा खर्च"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"शेष डेटा"</string>
@@ -401,7 +420,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"कम अत्यावश्यक सूचनाएं नीचे दी गई हैं"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"खोलने के लिए फिर से टैप करें"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"खोलने के लिए ऊपर स्वाइप करें"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"फिर से कोशिश करने के लिए स्वाइप करें"</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"फिर से कोशिश करने के लिए ऊपर की ओर स्वाइप करें"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"इस डिवाइस का प्रबंधन आपका संगठन करता है"</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"इस डिवाइस के प्रबंधक <xliff:g id="ORGANIZATION_NAME">%s</xliff:g> हैं"</string>
     <string name="phone_hint" msgid="4872890986869209950">"फ़ोन के लिए आइकॉन से स्वाइप करें"</string>
diff --git a/packages/SystemUI/res/values-hr/strings.xml b/packages/SystemUI/res/values-hr/strings.xml
index 052a0d2..6086764 100644
--- a/packages/SystemUI/res/values-hr/strings.xml
+++ b/packages/SystemUI/res/values-hr/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Postavljanje načina unosa"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fizička tipkovnica"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Želite li dopustiti aplikaciji <xliff:g id="APPLICATION">%1$s</xliff:g> pristup uređaju <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Želite li dopustiti aplikaciji <xliff:g id="APPLICATION">%1$s</xliff:g> pristup uređaju <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Želite li otvoriti aplikaciju <xliff:g id="APPLICATION">%1$s</xliff:g> radi upravljanja uređajem <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Želite li otvoriti aplikaciju <xliff:g id="APPLICATION">%1$s</xliff:g> radi upravljanja uređajem <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Odustani"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Potvrdi"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Pokušaj ponovo"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Prazno područje, dodirnite da biste otkazali autentifikaciju"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Dodirnite da biste otkazali autentifikaciju"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Pokušajte ponovo"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Traženje lica"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Lice je autentificirano"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Potvrđeno"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Dodirnite Potvrdi za dovršetak"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentičnost provjerena"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Dodirnite senzor otiska prsta"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona otiska prsta"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Tražimo vas…"</string>
@@ -365,6 +382,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Obavijesti"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Svjetiljka"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobilni podaci"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Potrošnja podataka"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Preostali podaci"</string>
diff --git a/packages/SystemUI/res/values-hu/strings.xml b/packages/SystemUI/res/values-hu/strings.xml
index 3e3696b..be039c7 100644
--- a/packages/SystemUI/res/values-hu/strings.xml
+++ b/packages/SystemUI/res/values-hu/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Beviteli módok beállítása"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fizikai billentyűzet"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Engedélyezi a(z) <xliff:g id="APPLICATION">%1$s</xliff:g> számára, hogy hozzáférjen a következőhöz: <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Engedélyezi a(z) <xliff:g id="APPLICATION">%1$s</xliff:g> számára, hogy hozzáférjen a következőhöz: <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Megnyitja a(z) <xliff:g id="APPLICATION">%1$s</xliff:g> alkalmazást a(z) <xliff:g id="USB_DEVICE">%2$s</xliff:g> kezeléséhez?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Megnyitja a(z) <xliff:g id="APPLICATION">%1$s</xliff:g> alkalmazást a(z) <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> kezeléséhez?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Mégse"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Megerősítés"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Újrapróbálkozás"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Üres régió. Koppintson a hitelesítés visszavonásához"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Koppintson a hitelesítés visszavonásához"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Próbálja újra"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Arc keresése"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Arc hitelesítve"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Megerősítve"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Koppintson a Megerősítés lehetőségre"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Hitelesítve"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Érintse meg az ujjlenyomat-érzékelőt"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ujjlenyomat ikonja"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Keresem az Ön arcát…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Értesítések"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Zseblámpa"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobiladatok"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Adathasználat"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Fennmaradó adatmennyiség"</string>
diff --git a/packages/SystemUI/res/values-hy/strings.xml b/packages/SystemUI/res/values-hy/strings.xml
index 4d19cec..0f84b50 100644
--- a/packages/SystemUI/res/values-hy/strings.xml
+++ b/packages/SystemUI/res/values-hy/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Կարգավորել մուտքագրման եղանակները"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Ֆիզիկական ստեղնաշար"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Թույլատրե՞լ <xliff:g id="APPLICATION">%1$s</xliff:g> հավելվածին օգտագործել <xliff:g id="USB_DEVICE">%2$s</xliff:g> լրասարքը։"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Թույլատրե՞լ <xliff:g id="APPLICATION">%1$s</xliff:g> հավելվածին օգտագործել <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> լրասարքը։"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Բացե՞լ <xliff:g id="APPLICATION">%1$s</xliff:g> հավելվածը <xliff:g id="USB_DEVICE">%2$s</xliff:g> լրասարքը մշակելու համար։"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Բացե՞լ <xliff:g id="APPLICATION">%1$s</xliff:g> հավելվածը <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> լրասարքը մշակելու համար։"</string>
@@ -55,12 +57,12 @@
     <string name="label_view" msgid="6304565553218192990">"Դիտել"</string>
     <string name="always_use_device" msgid="4015357883336738417">"Միշտ բացել <xliff:g id="APPLICATION">%1$s</xliff:g> հավելվածը, երբ <xliff:g id="USB_DEVICE">%2$s</xliff:g> լրասարքը միացված է"</string>
     <string name="always_use_accessory" msgid="3257892669444535154">"Միշտ բացել <xliff:g id="APPLICATION">%1$s</xliff:g> հավելվածը, երբ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> լրասարքը միացված է"</string>
-    <string name="usb_debugging_title" msgid="4513918393387141949">"Թույլատրե՞լ USB-ի կարգաբերումը:"</string>
+    <string name="usb_debugging_title" msgid="4513918393387141949">"Թույլատրե՞լ USB-ով վրիպազերծումը"</string>
     <string name="usb_debugging_message" msgid="2220143855912376496">"Համակարգչի RSA-ի բանալի մատնահետքն է`\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
     <string name="usb_debugging_always" msgid="303335496705863070">"Միշտ թույլատրել այս համակարգչից"</string>
     <string name="usb_debugging_allow" msgid="2272145052073254852">"Թույլատրել"</string>
-    <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"USB վրիպազերծումը արգելված է"</string>
-    <string name="usb_debugging_secondary_user_message" msgid="6067122453571699801">"Ընթացիկ հաշվի օգտատերը չի կարող միացնել USB վրիպազերծումը: Այս գործառույթը միացնելու համար մուտք գործեք հիմնական օգտատիրոջ հաշվով:"</string>
+    <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"USB-ով վրիպազերծումը թույլատրված չէ"</string>
+    <string name="usb_debugging_secondary_user_message" msgid="6067122453571699801">"Ընթացիկ հաշվի միջոցով չեք կարող միացնել USB-ով վրիպազերծումը: Այս գործառույթը միացնելու համար մուտք գործեք հիմնական օգտատիրոջ հաշիվ:"</string>
     <string name="usb_contaminant_title" msgid="206854874263058490">"USB միացքն անջատված է"</string>
     <string name="usb_contaminant_message" msgid="7379089091591609111">"USB միացքն անջատվել է, որպեսզի ձեր սարքը չթրջվի կամ չաղտոտվի: Այժմ USB միացքի միջոցով հնարավոր չէ միացնել այլ սարքեր:\n\nԴուք ծանուցում կստանաք, երբ այն նորից անվտանգ լինի օգտագործել:"</string>
     <string name="usb_port_enabled" msgid="7906141351687694867">"USB միացքը միացվել է՝ լիցքավորիչներն ու լրասարքերը հայտնաբերելու համար"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Չեղարկել"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Հաստատել"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Նորից փորձել"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Ոչինչ չկա։ Հպեք՝ նույնականացումը չեղարկելու համար։"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Հպեք՝ նույնականացումը չեղարկելու համար"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Նորից փորձեք"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Դեմքի նույնականացում"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Դեմքը ճանաչվեց"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Հաստատվեց"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Ավարտելու համար հպեք «Հաստատել»"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Նույնականացված է"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Հպեք մատնահետքի սկաներին"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Մատնահետքի պատկերակ"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Դեմքի ճանաչում…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Ծանուցումներ"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Լապտեր"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Բջջային ինտերնետ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Տվյալների օգտագործումը"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Մնացած տվյալները"</string>
@@ -539,12 +558,12 @@
     <string name="accessibility_output_chooser" msgid="8185317493017988680">"Փոխել արտածման սարքը"</string>
     <string name="screen_pinning_title" msgid="3273740381976175811">"Էկրանն ամրացված է"</string>
     <string name="screen_pinning_description" msgid="8909878447196419623">"Էկրանը կմնա տեսադաշտում, մինչև այն ապամրացնեք: Ապամրացնելու համար հպեք և պահեք Հետ և Համատեսք կոճակները:"</string>
-    <string name="screen_pinning_description_recents_invisible" msgid="8281145542163727971">"Էկրանը կցուցադրվի այնքան ժամանակ, մինչև որ չապամրացնեք այն: Ապամրացնելու համար հպեք և պահեք Հետ և գլխավոր էկրանի կոճակները:"</string>
+    <string name="screen_pinning_description_recents_invisible" msgid="8281145542163727971">"Էկրանը կցուցադրվի այնքան ժամանակ, մինչև չապամրացնեք այն: Ապամրացնելու համար հպեք և պահեք «Հետ» և «Գլխավոր էկրան» կոճակները"</string>
     <string name="screen_pinning_description_gestural" msgid="1191513974909607884">"Էկրանը կցուցադրվի այնքան ժամանակ, մինչև որ չապամրացնեք այն: Ապամրացնելու համար մատը սահեցրեք վեր և պահեք։"</string>
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"Էկրանը կմնա տեսադաշտում, մինչև այն ապամրացնեք: Ապամրացնելու համար հպեք և պահեք Համատեսք կոճակը:"</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"Էկրանը կցուցադրվի այնքան ժամանակ, մինչև որ չապամրացնեք այն: Ապամրացնելու համար հպեք և պահեք գլխավոր էկրանի կոճակը:"</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"Էկրանն ապամրացնելու համար հպեք և պահեք Հետ և Համատեսք կոճակները"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Էկրանն ապամրացնելու համար հպեք և պահեք Հետ և գլխավոր էկրանի կոճակները"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Էկրանն ապամրացնելու համար հպեք և պահեք «Հետ» և «Գլխավոր էկրան» կոճակները"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"Էկրանն ապամրացնելու համար մատը սահեցրեք վերև և պահեք"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Եղավ"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"Ոչ"</string>
diff --git a/packages/SystemUI/res/values-in/strings.xml b/packages/SystemUI/res/values-in/strings.xml
index b18beed..0b3ef70 100644
--- a/packages/SystemUI/res/values-in/strings.xml
+++ b/packages/SystemUI/res/values-in/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Menyiapkan metode masukan"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Keyboard fisik"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Izinkan <xliff:g id="APPLICATION">%1$s</xliff:g> mengakses <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Izinkan <xliff:g id="APPLICATION">%1$s</xliff:g> mengakses <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Buka <xliff:g id="APPLICATION">%1$s</xliff:g> untuk menangani <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Buka <xliff:g id="APPLICATION">%1$s</xliff:g> untuk menangani <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Batal"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Konfirmasi"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Coba lagi"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Area kosong. Ketuk untuk membatalkan autentikasi"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Ketuk untuk membatalkan autentikasi"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Coba lagi"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Mencari wajah Anda"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Wajah diautentikasi"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Dikonfirmasi"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Ketuk Konfirmasi untuk menyelesaikan"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Diautentikasi"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Sentuh sensor sidik jari"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikon sidik jari"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Mencari wajah Anda…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifikasi"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lampu senter"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Data seluler"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Penggunaan kuota"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Data tersisa"</string>
diff --git a/packages/SystemUI/res/values-is/strings.xml b/packages/SystemUI/res/values-is/strings.xml
index 129319d..7a8d290 100644
--- a/packages/SystemUI/res/values-is/strings.xml
+++ b/packages/SystemUI/res/values-is/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Setja upp innsláttaraðferðir"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Vélbúnaðarlyklaborð"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Viltu veita <xliff:g id="APPLICATION">%1$s</xliff:g> aðgang að <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Viltu veita <xliff:g id="APPLICATION">%1$s</xliff:g> aðgang að <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Viltu opna <xliff:g id="APPLICATION">%1$s</xliff:g> til að sjá um <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Viltu opna <xliff:g id="APPLICATION">%1$s</xliff:g> til að sjá um <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Hætta við"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Staðfesta"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Reyna aftur"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Autt rými, ýttu til að hætta við greiningu"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Ýttu til að hætta við auðkenningu"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Reyndu aftur"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Leitar að andliti þínu"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Andlit staðfest"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Staðfest"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Ýttu á „Staðfesta“ til að ljúka"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Auðkennt"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Snertu fingrafaralesarann"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Fingrafaratákn"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Leitar að þér ..."</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Tilkynningar"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Vasaljós"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Farsímagögn"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Gagnanotkun"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Gögn eftir"</string>
diff --git a/packages/SystemUI/res/values-it/strings.xml b/packages/SystemUI/res/values-it/strings.xml
index a9427e5..cc053be 100644
--- a/packages/SystemUI/res/values-it/strings.xml
+++ b/packages/SystemUI/res/values-it/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configura metodi di immissione"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Tastiera fisica"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Consentire a <xliff:g id="APPLICATION">%1$s</xliff:g> di accedere a <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Consentire a <xliff:g id="APPLICATION">%1$s</xliff:g> di accedere a <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Vuoi aprire <xliff:g id="APPLICATION">%1$s</xliff:g> per gestire <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Vuoi aprire <xliff:g id="APPLICATION">%1$s</xliff:g> per gestire <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -56,7 +58,7 @@
     <string name="always_use_device" msgid="4015357883336738417">"Apri sempre <xliff:g id="APPLICATION">%1$s</xliff:g> quando si collega <xliff:g id="USB_DEVICE">%2$s</xliff:g>"</string>
     <string name="always_use_accessory" msgid="3257892669444535154">"Apri sempre <xliff:g id="APPLICATION">%1$s</xliff:g> quando si collega <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>"</string>
     <string name="usb_debugging_title" msgid="4513918393387141949">"Consentire debug USB?"</string>
-    <string name="usb_debugging_message" msgid="2220143855912376496">"Fingerprint della chiave RSA del computer: \n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
+    <string name="usb_debugging_message" msgid="2220143855912376496">"Impronta della chiave RSA del computer: \n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
     <string name="usb_debugging_always" msgid="303335496705863070">"Consenti sempre da questo computer"</string>
     <string name="usb_debugging_allow" msgid="2272145052073254852">"Consenti"</string>
     <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"Debug USB non consentito"</string>
@@ -108,8 +110,8 @@
     <string name="accessibility_phone_button" msgid="6738112589538563574">"Telefono"</string>
     <string name="accessibility_voice_assist_button" msgid="487611083884852965">"Voice Assist"</string>
     <string name="accessibility_unlock_button" msgid="128158454631118828">"Sblocca"</string>
-    <string name="accessibility_waiting_for_fingerprint" msgid="4808860050517462885">"In attesa dell\'impronta digitale"</string>
-    <string name="accessibility_unlock_without_fingerprint" msgid="7541705575183694446">"Sblocca senza utilizzare l\'impronta digitale"</string>
+    <string name="accessibility_waiting_for_fingerprint" msgid="4808860050517462885">"In attesa dell\'impronta"</string>
+    <string name="accessibility_unlock_without_fingerprint" msgid="7541705575183694446">"Sblocca senza utilizzare l\'impronta"</string>
     <string name="accessibility_scanning_face" msgid="769545173211758586">"Scansione del viso"</string>
     <string name="accessibility_send_smart_reply" msgid="7766727839703044493">"Invia"</string>
     <string name="accessibility_manage_notification" msgid="2026361503393549753">"Gestisci notifiche"</string>
@@ -119,14 +121,29 @@
     <string name="cancel" msgid="6442560571259935130">"Annulla"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Conferma"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Riprova"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Spazio vuoto, tocca per annullare l\'autenticazione"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tocca per annullare l\'autenticazione"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Riprova"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Ricerca del tuo volto"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Volto autenticato"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confermato"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tocca Conferma per completare"</string>
-    <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Tocca il sensore di impronte digitali"</string>
-    <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icona dell\'impronta digitale"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenticazione eseguita"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
+    <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Tocca il sensore di impronte"</string>
+    <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icona dell\'impronta"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"In attesa del volto…"</string>
     <string name="accessibility_face_dialog_face_icon" msgid="2658119009870383490">"Icona volto"</string>
     <string name="accessibility_compatibility_zoom_button" msgid="8461115318742350699">"Pulsante zoom compatibilità."</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notifiche"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Torcia"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Dati mobili"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Utilizzo dati"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Dati rimanenti"</string>
diff --git a/packages/SystemUI/res/values-iw/strings.xml b/packages/SystemUI/res/values-iw/strings.xml
index 52d4a13..09e4f0e 100644
--- a/packages/SystemUI/res/values-iw/strings.xml
+++ b/packages/SystemUI/res/values-iw/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"הגדר שיטות קלט"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"מקלדת פיזית"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"האם לתת לאפליקציה <xliff:g id="APPLICATION">%1$s</xliff:g> גישה אל <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"האם לתת לאפליקציה <xliff:g id="APPLICATION">%1$s</xliff:g> גישה אל <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"האם לפתוח את <xliff:g id="APPLICATION">%1$s</xliff:g> כדי לעבוד עם <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"האם לפתוח את <xliff:g id="APPLICATION">%1$s</xliff:g> כדי לעבוד עם <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"ביטול"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"אישור"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ניסיון נוסף"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"אזור ריק, יש להקיש עליו כדי לבטל את האימות"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"יש להקיש כדי לבטל את האימות"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"עליך לנסות שוב"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"המערכת מחפשת את הפנים שלך"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"זיהוי הפנים בוצע"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"מאושר"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"יש להקיש על \'אישור\' לסיום"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"מאומת"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"יש לגעת בחיישן טביעות האצבע"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"סמל טביעת אצבע"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"מחפש אותך…"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"התראות"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"פנס"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"חבילת גלישה"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"שימוש בנתונים"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"מכסת נתונים נותרת"</string>
@@ -463,7 +482,7 @@
     <string name="media_projection_dialog_service_text" msgid="3075544489835858258">"בזמן הקלטה או העברה, השירות שמספק את הפונקציה הזו יכול לקלוט מידע רגיש שמוצג במסך או מופעל מהמכשיר שלך, כולל מידע רגיש כמו אודיו, סיסמאות, פרטי תשלום, תמונות והודעות."</string>
     <string name="media_projection_dialog_title" msgid="8124184308671641248">"חשיפת מידע רגיש בזמן העברה/הקלטה"</string>
     <string name="media_projection_remember_text" msgid="3103510882172746752">"אל תציג שוב"</string>
-    <string name="clear_all_notifications_text" msgid="814192889771462828">"נקה הכל"</string>
+    <string name="clear_all_notifications_text" msgid="814192889771462828">"ניקוי הכל"</string>
     <string name="manage_notifications_text" msgid="2386728145475108753">"ניהול"</string>
     <string name="notification_section_header_gentle" msgid="4372438504154095677">"התראות שקטות"</string>
     <string name="accessibility_notification_section_header_gentle_clear_all" msgid="4286716295850400959">"ניקוי כל ההתראות השקטות"</string>
@@ -625,7 +644,7 @@
     <string name="clock_seconds_desc" msgid="6282693067130470675">"הצג שניות בשעון בשורת הסטטוס. פעולה זו עשויה להשפיע על אורך חיי הסוללה."</string>
     <string name="qs_rearrange" msgid="8060918697551068765">"סידור מחדש של הגדרות מהירות"</string>
     <string name="show_brightness" msgid="6613930842805942519">"הצג בהירות בהגדרות מהירות"</string>
-    <string name="experimental" msgid="6198182315536726162">"ניסיוניות"</string>
+    <string name="experimental" msgid="6198182315536726162">"ניסיוני"</string>
     <string name="enable_bluetooth_title" msgid="5027037706500635269">"‏האם להפעיל את ה-Bluetooth?"</string>
     <string name="enable_bluetooth_message" msgid="9106595990708985385">"‏כדי לחבר את המקלדת לטאבלט, תחילה עליך להפעיל את ה-Bluetooth."</string>
     <string name="enable_bluetooth_confirmation_ok" msgid="6258074250948309715">"הפעל"</string>
diff --git a/packages/SystemUI/res/values-ja/strings.xml b/packages/SystemUI/res/values-ja/strings.xml
index 05f254f..3dc9fb7 100644
--- a/packages/SystemUI/res/values-ja/strings.xml
+++ b/packages/SystemUI/res/values-ja/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"入力方法をセットアップ"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"物理キーボード"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> に <xliff:g id="USB_DEVICE">%2$s</xliff:g> へのアクセスを許可しますか?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> に <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> へのアクセスを許可しますか?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="APPLICATION">%1$s</xliff:g> を起動して <xliff:g id="USB_DEVICE">%2$s</xliff:g> を処理しますか?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="APPLICATION">%1$s</xliff:g> を起動して <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> を処理しますか?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"キャンセル"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"確認"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"再試行"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"空白の領域をタップすると、認証をキャンセルできます"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"タップすると認証をキャンセルします"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"もう一度お試しください"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"顔を認証中です"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"顔を認証しました"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"確認しました"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"完了するには [確認] をタップしてください"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"認証済み"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"指紋認証センサーをタップしてください"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"指紋アイコン"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"顔を認証しています…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"通知"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ライト"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"モバイルデータ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"データ使用量"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"残りのデータ"</string>
diff --git a/packages/SystemUI/res/values-ka/strings.xml b/packages/SystemUI/res/values-ka/strings.xml
index 6a7460d..24db256 100644
--- a/packages/SystemUI/res/values-ka/strings.xml
+++ b/packages/SystemUI/res/values-ka/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"შეყვანის მეთოდების დაყენება"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ფიზიკური კლავიატურა"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"მიეცეს <xliff:g id="APPLICATION">%1$s</xliff:g>-ს <xliff:g id="USB_DEVICE">%2$s</xliff:g>-ზე წვდომის უფლება?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"მიეცეს <xliff:g id="APPLICATION">%1$s</xliff:g>-ს <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>-ზე წვდომის უფლება?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"გსურთ, გახსნათ <xliff:g id="APPLICATION">%1$s</xliff:g>, <xliff:g id="USB_DEVICE">%2$s</xliff:g>-ის გამოსაყენებლად?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"გსურთ, გახსნათ <xliff:g id="APPLICATION">%1$s</xliff:g>, <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>-ის გამოსაყენებლად?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"გაუქმება"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"დადასტურება"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ხელახლა ცდა"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"დაფიქსირდა ცარიელი უბანი, შეეხეთ ამოცნობის გასაუქმებლად"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"შეეხეთ ავტორიზაციის გასაუქმებლად"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"გთხოვთ, ცადოთ ხელახლა"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"მიმდინარეობს თქვენი სახის ძებნა"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"სახის ამოცნობილია"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"დადასტურებული"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"დასასრულებლად შეეხეთ „დადასტურებას“"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ავტორიზებულია"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"შეეხეთ თითის ანაბეჭდის სენსორს"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"თითის ანაბეჭდის ხატულა"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"მიმდინარეობს თქვენი ძიება…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"შეტყობინებები"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ფანარი"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"მობილური ინტერნეტი"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"მონაცემთა მოხმარება"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"დარჩენილი მონაცემები"</string>
diff --git a/packages/SystemUI/res/values-kk/strings.xml b/packages/SystemUI/res/values-kk/strings.xml
index 6e0fca7..ff1b9fc 100644
--- a/packages/SystemUI/res/values-kk/strings.xml
+++ b/packages/SystemUI/res/values-kk/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Енгізу әдістерін орнату"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Физикалық пернетақта"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> қолданбасына <xliff:g id="USB_DEVICE">%2$s</xliff:g> құрылғысына кіруге рұқсат берілсін бе?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> қолданбасына <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> жабдығына кіруге рұқсат берілсін бе?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> жабдығын басқару үшін <xliff:g id="APPLICATION">%1$s</xliff:g> ашылсын ба?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> жабдығын басқару үшін <xliff:g id="APPLICATION">%1$s</xliff:g> ашылсын ба?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Бас тарту"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Растау"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Қайталап көріңіз"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Аймақта ештеңе көрсетілмеген. Оны басып, аутентификациядан бас тартыңыз."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Аутентификациядан бас тарту үшін түртіңіз."</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Қайталап көріңіз."</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Құрылғы бетіңізді талдап жатыр."</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Бет танылды."</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Расталды"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Аяқтау үшін \"Растау\" түймесін түртіңіз."</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Аутентификацияланған"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Саусақ ізін оқу сканерін түртіңіз"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Саусақ ізі белгішесі"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Бет ізделуде…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Хабарландырулар"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Қалта шам"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобильдік деректер"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Дерек шығыны"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Қалған деректер"</string>
diff --git a/packages/SystemUI/res/values-km/strings.xml b/packages/SystemUI/res/values-km/strings.xml
index 16272fc..323138c 100644
--- a/packages/SystemUI/res/values-km/strings.xml
+++ b/packages/SystemUI/res/values-km/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"រៀបចំ​វិធីសាស្ត្រ​បញ្ចូល"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ក្ដារ​ចុច​ពិតប្រាកដ"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"អនុញ្ញាត <xliff:g id="APPLICATION">%1$s</xliff:g> ឱ្យចូលប្រើ <xliff:g id="USB_DEVICE">%2$s</xliff:g> មែនទេ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"អនុញ្ញាត <xliff:g id="APPLICATION">%1$s</xliff:g> ឱ្យចូលប្រើ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> មែនទេ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"បើក <xliff:g id="APPLICATION">%1$s</xliff:g> ដើម្បីគ្រប់គ្រង <xliff:g id="USB_DEVICE">%2$s</xliff:g> មែនទេ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"បើក <xliff:g id="APPLICATION">%1$s</xliff:g> ដើម្បីគ្រប់គ្រង <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> មែនទេ?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"បោះ​បង់​"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"បញ្ជាក់"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ព្យាយាម​ម្ដង​ទៀត"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"កន្លែង​ទំនេរ សូមចុច​ដើម្បីបោះបង់​ការផ្ទៀងផ្ទាត់"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ចុចដើម្បីបោះបង់​ការផ្ទៀងផ្ទាត់"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"សូម​ព្យាយាម​ម្ដងទៀត"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"កំពុង​ផ្ទៀងផ្ទាត់​មុខរបស់អ្នក"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"បានផ្ទៀងផ្ទាត់​មុខ"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"បានបញ្ជាក់"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"ចុច \"បញ្ជាក់\" ដើម្បីបញ្ចប់"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"បាន​ផ្ទៀងផ្ទាត់"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ប៉ះ​ឧបករណ៍​ចាប់ស្នាម​ម្រាមដៃ"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"រូបតំណាង​ស្នាម​ម្រាមដៃ"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"កំពុងស្វែងរកអ្នក…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"ការ​ជូនដំណឹង"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ពិល"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"ទិន្នន័យ​ទូរសព្ទចល័ត"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ការ​ប្រើ​ទិន្នន័យ"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ទិន្នន័យ​នៅសល់"</string>
@@ -543,8 +562,8 @@
     <string name="screen_pinning_description_gestural" msgid="1191513974909607884">"វា​នឹង​នៅតែ​បង្ហាញ រហូតទាល់​តែអ្នក​ដកការដៅ។ អូសឡើងលើ​ឱ្យជាប់ ដើម្បី​ដក​ការដៅ។"</string>
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"វា​នឹង​នៅតែ​បង្ហាញ រហូត​ទាល់​តែ​អ្នក​ដក​ការ​ដៅ។ សូម​សង្កត់​ប៊ូតុង​ទិដ្ឋភាពរួម​​ឲ្យ​ជាប់ ដើម្បី​ដក​ការ​ដៅ។"</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"វា​នឹង​នៅតែ​បង្ហាញ រហូត​ទាល់​តែ​អ្នក​ដក​ការដៅ។ សូម​ចុច​ប៊ូតុង​ទំព័រដើម​ឱ្យ​ជាប់ ដើម្បី​ដក​ការ​ដៅ។"</string>
-    <string name="screen_pinning_toast" msgid="2266705122951934150">"ដើម្បី​ដក​ការ​ដៅ​អេក្រង់​នេះ សូម​ចុច​ប៊ូតុង​ថយ​ក្រោយ និង​ប៊ូតុង​ទិដ្ឋភាពរួម​ឱ្យ​ជាប់"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"ដើម្បី​ដក​ការ​ដៅ​អេក្រង់​នេះ សូម​ចុច​ប៊ូតុង​ថយ​ក្រោយ និង​ប៊ូតុងទំព័រដើម​ឱ្យ​ជាប់"</string>
+    <string name="screen_pinning_toast" msgid="2266705122951934150">"ដើម្បី​ដកខ្ទាស់​អេក្រង់​នេះ សូម​ចុច​ប៊ូតុង​ថយ​ក្រោយ និង​ប៊ូតុង​ទិដ្ឋភាពរួម​ឱ្យ​ជាប់"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"ដើម្បី​ដកខ្ទាស់​អេក្រង់​នេះ សូម​ចុច​ប៊ូតុង​ថយ​ក្រោយ និង​ប៊ូតុងទំព័រដើម​ឱ្យ​ជាប់"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"អូសឡើងលើ​ឱ្យជាប់ ដើម្បី​ដកការដៅ​អេក្រង់​នេះ"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"យល់​ហើយ"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"ទេ អរគុណ"</string>
diff --git a/packages/SystemUI/res/values-kn/strings.xml b/packages/SystemUI/res/values-kn/strings.xml
index 79c4f2d..ac593e8 100644
--- a/packages/SystemUI/res/values-kn/strings.xml
+++ b/packages/SystemUI/res/values-kn/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ಇನ್‌ಪುಟ್ ವಿಧಾನಗಳನ್ನು ಹೊಂದಿಸು"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ಭೌತಿಕ ಕೀಬೋರ್ಡ್"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ಪ್ರವೇಶಿಸಲು <xliff:g id="APPLICATION">%1$s</xliff:g> ಅನ್ನು ಅನುಮತಿಸುವುದೇ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ಗೆ ಪ್ರವೇಶಿಸಲು <xliff:g id="APPLICATION">%1$s</xliff:g> ಅನ್ನು ಅನುಮತಿಸುವುದೇ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ಅನ್ನು ನಿರ್ವಹಿಸಲು <xliff:g id="APPLICATION">%1$s</xliff:g> ಅನ್ನು ತೆರೆಯುವುದೇ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ಅನ್ನು ನಿರ್ವಹಿಸಲು <xliff:g id="APPLICATION">%1$s</xliff:g> ಅನ್ನು ತೆರೆಯುವುದೇ?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"ರದ್ದುಮಾಡಿ"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"ದೃಢೀಕರಿಸಿ"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ಖಾಲಿ ಪ್ರದೇಶ, ದೃಢೀಕರಣವನ್ನು ರದ್ದುಗೊಳಿಸಲು ಟ್ಯಾಪ್ ಮಾಡಿ"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ದೃಢೀಕರಣವನ್ನು ರದ್ದುಗೊಳಿಸಲು ಟ್ಯಾಪ್ ಮಾಡಿ"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"ಪುನಃ ಪ್ರಯತ್ನಿಸಿ"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"ನಿಮ್ಮ ಮುಖದ ದೃಢೀಕರಣಕ್ಕಾಗಿ ನಿರೀಕ್ಷಿಸಲಾಗುತ್ತಿದೆ"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ಮುಖವನ್ನು ದೃಢೀಕರಿಸಲಾಗಿದೆ"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"ದೃಢೀಕರಿಸಲಾಗಿದೆ"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"ಪೂರ್ಣಗೊಳಿಸಲು ದೃಢೀಕರಿಸಿ ಅನ್ನು ಟ್ಯಾಪ್ ಮಾಡಿ"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ದೃಢೀಕರಿಸಲಾಗಿದೆ"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ಫಿಂಗರ್‌ಪ್ರಿಂಟ್ ಸೆನ್ಸರ್‌‌ ಅನ್ನು ಸ್ಪರ್ಶಿಸಿ"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ಫಿಂಗರ್‌ಪ್ರಿಂಟ್ ಐಕಾನ್"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"ನಿಮಗಾಗಿ ಹುಡುಕಲಾಗುತ್ತಿದೆ…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"ಅಧಿಸೂಚನೆಗಳು"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ಫ್ಲಾಶ್‌ಲೈಟ್‌"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"ಮೊಬೈಲ್ ಡೇಟಾ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ಡೇಟಾ ಬಳಕೆ"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ಉಳಿದಿರುವ ಡೇಟಾ"</string>
@@ -450,7 +469,7 @@
     <string name="user_remove_user_title" msgid="4681256956076895559">"ಬಳಕೆದಾರರನ್ನು ತೆಗೆದುಹಾಕುವುದೇ?"</string>
     <string name="user_remove_user_message" msgid="1453218013959498039">"ಈ ಬಳಕೆದಾರರ ಎಲ್ಲಾ ಅಪ್ಲಿಕೇಶನ್‌ಗಳು ಮತ್ತು ಡೇಟಾವನ್ನು ಅಳಿಸಲಾಗುವುದು."</string>
     <string name="user_remove_user_remove" msgid="7479275741742178297">"ತೆಗೆದುಹಾಕಿ"</string>
-    <string name="battery_saver_notification_title" msgid="8614079794522291840">"ಬ್ಯಾಟರಿ ರಕ್ಷಕ ಆನ್ ಆಗಿದೆ"</string>
+    <string name="battery_saver_notification_title" msgid="8614079794522291840">"ಬ್ಯಾಟರಿ ಸೇವರ್ ಆನ್ ಆಗಿದೆ"</string>
     <string name="battery_saver_notification_text" msgid="820318788126672692">"ಕಾರ್ಯಕ್ಷಮತೆ ಮತ್ತು ಹಿನ್ನೆಲೆ ಡೇಟಾವನ್ನು ಕಡಿಮೆ ಮಾಡುತ್ತದೆ"</string>
     <string name="battery_saver_notification_action_text" msgid="132118784269455533">"ಬ್ಯಾಟರಿ ಸೇವರ್‌ ಆಫ್ ಮಾಡಿ"</string>
     <string name="media_projection_dialog_text" msgid="8585357687598538511">"ರೆಕಾರ್ಡ್ ಮಾಡುವಾಗ ಅಥವಾ ಕ್ಯಾಸ್ಟಿಂಗ್ ಮಾಡುವಾಗ, ಸೂಕ್ಷ್ಮ ಮಾಹಿತಿಯಂತಹ ಆಡಿಯೋ, ಪಾಸ್‌ವರ್ಡ್‌ಗಳು, ಪಾವತಿ ಮಾಹಿತಿ, ಫೋಟೋಗಳು ಮತ್ತು ಸಂದೇಶಗಳನ್ನು ಒಳಗೊಂಡಂತೆ ನಿಮ್ಮ ಸ್ಕ್ರೀನ್ ಮೇಲೆ ಡಿಸ್‌ಪ್ಲೇ ಮಾಡಿದ ಅಥವಾ ನಿಮ್ಮ ಸಾಧನದಿಂದ ಪ್ಲೇ ಮಾಡಿದ ಯಾವುದೇ ಸೂಕ್ಷ್ಮ ಮಾಹಿತಿಯನ್ನು <xliff:g id="APP_SEEKING_PERMISSION">%s</xliff:g> ಕ್ಯಾಪ್ಚರ್ ಮಾಡಬಹುದು."</string>
diff --git a/packages/SystemUI/res/values-ko/strings.xml b/packages/SystemUI/res/values-ko/strings.xml
index b0a1671..f37ec00 100644
--- a/packages/SystemUI/res/values-ko/strings.xml
+++ b/packages/SystemUI/res/values-ko/strings.xml
@@ -39,7 +39,7 @@
     <string name="battery_saver_start_action" msgid="8187820911065797519">"절전 모드 사용 설정"</string>
     <string name="status_bar_settings_settings_button" msgid="3023889916699270224">"설정"</string>
     <string name="status_bar_settings_wifi_button" msgid="1733928151698311923">"Wi-Fi"</string>
-    <string name="status_bar_settings_auto_rotation" msgid="3790482541357798421">"자동 화면 회전"</string>
+    <string name="status_bar_settings_auto_rotation" msgid="3790482541357798421">"화면 자동 회전"</string>
     <string name="status_bar_settings_mute_label" msgid="554682549917429396">"무시"</string>
     <string name="status_bar_settings_auto_brightness_label" msgid="511453614962324674">"자동"</string>
     <string name="status_bar_settings_notifications" msgid="397146176280905137">"알림"</string>
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"입력 방법 설정"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"물리적 키보드"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> 앱이 <xliff:g id="USB_DEVICE">%2$s</xliff:g>에 액세스하도록 허용하시겠습니까?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> 앱이 <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>에 액세스하도록 허용하시겠습니까?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="APPLICATION">%1$s</xliff:g> 앱을 열어 <xliff:g id="USB_DEVICE">%2$s</xliff:g>을(를) 처리하시겠습니까?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="APPLICATION">%1$s</xliff:g> 앱을 열어 <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>을(를) 처리하시겠습니까?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"취소"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"확인"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"다시 시도하세요."</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"비어 있는 공간, 탭하여 인증 취소"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"탭하여 인증 취소"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"다시 시도해 주세요."</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"얼굴을 찾는 중"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"얼굴이 인증되었습니다."</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"확인함"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"완료하려면 확인을 탭하세요."</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"인증됨"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"지문 센서를 터치하세요."</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"지문 아이콘"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"찾는 중..."</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"알림"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"손전등"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"모바일 데이터"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"데이터 사용"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"잔여 데이터"</string>
@@ -401,7 +420,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"아래에 덜 급한 알림 표시"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"다시 탭하여 열기"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"위로 스와이프하여 열기"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"위로 스와이프하여 다시 시도해 주세요."</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"위로 스와이프하여 다시 시도해 주세요"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"조직에서 관리하는 기기입니다."</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"<xliff:g id="ORGANIZATION_NAME">%s</xliff:g>에서 관리하는 기기입니다."</string>
     <string name="phone_hint" msgid="4872890986869209950">"전화 기능을 사용하려면 아이콘에서 스와이프하세요."</string>
diff --git a/packages/SystemUI/res/values-ky/strings.xml b/packages/SystemUI/res/values-ky/strings.xml
index dd985c6..beb2b02 100644
--- a/packages/SystemUI/res/values-ky/strings.xml
+++ b/packages/SystemUI/res/values-ky/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Киргизүү ыкмасын тууралоо"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Аппараттык тергич"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> колдонмосу <xliff:g id="USB_DEVICE">%2$s</xliff:g> түзмөгүн колдоно берсинби?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> колдонмосу <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> кабелин колдоно берсинби?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> түзмөгүнө туташуу үчүн <xliff:g id="APPLICATION">%1$s</xliff:g> колдонмосу ачылсынбы?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> кабелине туташуу үчүн <xliff:g id="APPLICATION">%1$s</xliff:g> колдонмосу ачылсынбы?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Жокко чыгаруу"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Ырастоо"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Кайталоо"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Бош жер калып калды, аутентификацияны жокко чыгаруу үчүн таптап коюңуз"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Аныктыгын текшерүүнү жокко чыгаруу үчүн таптаңыз"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Кайра аракет кылыңыз"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Жүзүңүз изделүүдө"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Жүздүн аныктыгы текшерилди"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Ырасталды"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Бүтүрүү үчүн \"Ырастоо\" баскычын басыңыз"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Аныктыгы текшерилди"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Манжа изинин сенсорун басыңыз"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Манжа изинин сүрөтчөсү"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Жүзүңүз изделүүдө…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Билдирмелер"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Кол чырак"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобилдик Интернет"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Дайындардын өткөрүлүшү"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Калган дайындар"</string>
@@ -401,7 +420,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"Анчейин шашылыш эмес эскертмелер төмөндө"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"Ачуу үчүн кайра таптап коюңуз"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"Ачуу үчүн өйдө сүрүңүз"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"Кайра аракет кылуу үчүн экранды өйдө сүрүңүз"</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"Кайталоо үчүн экранды өйдө сүрүңүз"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"Бул түзмөк уюмуңуз тарабынан башкарылат"</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"Бул түзмөк <xliff:g id="ORGANIZATION_NAME">%s</xliff:g> тарабынан башкарылат"</string>
     <string name="phone_hint" msgid="4872890986869209950">"Сүрөтчөнү серпип телефонго өтүңүз"</string>
@@ -457,7 +476,7 @@
     <string name="media_projection_dialog_service_text" msgid="3075544489835858258">"Жаздырып же тышкы экранга чыгаруу учурунда, бул функцияны аткарып жаткан колдонмо ойноткон аудиоңуз, сырсөздөрүңүз, төлөө маалыматыңыз, сүрөттөрүңүз жана билдирүүлөрүңүз сыяктуу экранда көрсөтүлгөн купуя маалыматты жаздырып калышы мүмкүн."</string>
     <string name="media_projection_dialog_title" msgid="8124184308671641248">"Тышкы экранга чыгарууда/жаздырууда купуя маалыматты ачыктоо"</string>
     <string name="media_projection_remember_text" msgid="3103510882172746752">"Экинчи көрсөтүлбөсүн"</string>
-    <string name="clear_all_notifications_text" msgid="814192889771462828">"Бардыгын тазалап салуу"</string>
+    <string name="clear_all_notifications_text" msgid="814192889771462828">"Баарын тазалап салуу"</string>
     <string name="manage_notifications_text" msgid="2386728145475108753">"Башкаруу"</string>
     <string name="notification_section_header_gentle" msgid="4372438504154095677">"Үнсүз билдирмелер"</string>
     <string name="accessibility_notification_section_header_gentle_clear_all" msgid="4286716295850400959">"Маанилүү эмес билдирмелердин баарын өчүрүү"</string>
@@ -901,7 +920,7 @@
     <string name="slice_permission_text_2" msgid="3146758297471143723">"- <xliff:g id="APP">%1$s</xliff:g> колдонмосунда аракеттерди аткарат"</string>
     <string name="slice_permission_checkbox" msgid="7986504458640562900">"<xliff:g id="APP">%1$s</xliff:g> бардык колдонмолордун үлгүлөрүн көрсөтүүгө уруксат берүү"</string>
     <string name="slice_permission_allow" msgid="2340244901366722709">"Уруксат берүү"</string>
-    <string name="slice_permission_deny" msgid="7683681514008048807">"Жок"</string>
+    <string name="slice_permission_deny" msgid="7683681514008048807">"Тыюу салынат"</string>
     <string name="auto_saver_title" msgid="1217959994732964228">"Батареяны үнөмдөгүчтүн тартибин жөндөө үчүн басыңыз"</string>
     <string name="auto_saver_text" msgid="2563289953551438248">"Батареянын кубаты түгөнүп калганда, күйгүзүлсүн"</string>
     <string name="no_auto_saver_action" msgid="8086002101711328500">"Жок, рахмат"</string>
@@ -925,7 +944,7 @@
     <string name="bubbles_settings_button_description" msgid="2970630476657287189">"<xliff:g id="APP_NAME">%1$s</xliff:g> көбүктөрүнүн жөндөөлөрү"</string>
     <string name="bubbles_prompt" msgid="8807968030159469710">"<xliff:g id="APP_NAME">%1$s</xliff:g> колдонмосунун калкып чыкма билдирмелерине уруксат бересизби?"</string>
     <string name="manage_bubbles_text" msgid="7027739766859191408">"Башкаруу"</string>
-    <string name="no_bubbles" msgid="337101288173078247">"Жок"</string>
+    <string name="no_bubbles" msgid="337101288173078247">"Тыюу салынат"</string>
     <string name="yes_bubbles" msgid="668809525728633841">"Уруксат берүү"</string>
     <string name="ask_me_later_bubbles" msgid="2147688438402939029">"Кийинчерээк суралсын"</string>
     <string name="bubble_content_description_single" msgid="1184462974339387516">"<xliff:g id="APP_NAME">%2$s</xliff:g> колдонмосунан <xliff:g id="NOTIFICATION_TITLE">%1$s</xliff:g>"</string>
diff --git a/packages/SystemUI/res/values-lo/strings.xml b/packages/SystemUI/res/values-lo/strings.xml
index d99db74..68c9951 100644
--- a/packages/SystemUI/res/values-lo/strings.xml
+++ b/packages/SystemUI/res/values-lo/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ຕັ້ງຄ່າວິທີການປ້ອນຂໍ້ມູນ"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ແປ້ນພິມແທ້"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"ອະນຸຍາດໃຫ້ <xliff:g id="APPLICATION">%1$s</xliff:g> ເຂົ້າເຖິງ <xliff:g id="USB_DEVICE">%2$s</xliff:g> ໄດ້ບໍ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"ອະນຸຍາດໃຫ້ <xliff:g id="APPLICATION">%1$s</xliff:g> ເຂົ້າເຖິງ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ໄດ້ບໍ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"ເປີດ <xliff:g id="APPLICATION">%1$s</xliff:g> ເພື່ອໃຊ້ກັບ <xliff:g id="USB_DEVICE">%2$s</xliff:g> ບໍ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"ເປີດ <xliff:g id="APPLICATION">%1$s</xliff:g> ເພື່ອໃຊ້ກັບ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ບໍ?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"ຍົກເລີກ"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"ຢືນຢັນ"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ລອງໃໝ່"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ພື້ນທີ່ຫວ່າງເປົ່າ, ແຕະເພື່ອຍົກເລີກການພິສູດຢືນຢັນ"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ແຕະເພື່ອຍົກເລີກການກວດສອບຄວາມຖືກຕ້ອງ"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"ກະລຸນາລອງໃໝ່"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"ກຳລັງເບິ່ງໃບໜ້າຂອງທ່ານ"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ພິສູດຢືນຢັນໃບໜ້າແລ້ວ"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"ຢືນຢັນແລ້ວ"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"ແຕະຢືນຢັນເພື່ອສຳເລັດ"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ຮັບຮອງຄວາມຖືກຕ້ອງແລ້ວ"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ແຕະໃສ່ເຊັນເຊີລາຍນິ້ວມື"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ໄອຄອນລາຍນິ້ວມື"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"ກຳລັງຊອກຫາທ່ານ…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"ການແຈ້ງເຕືອນ"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"​ໄຟ​ສາຍ"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"ອິນເຕີເນັດມືຖື"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"​ການ​​ນຳ​ໃຊ້​​ຂໍ້​ມູນ"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"​ຂໍ້​ມູນ​ທີ່​ຍັງ​ເຫຼືອ"</string>
diff --git a/packages/SystemUI/res/values-lt/strings.xml b/packages/SystemUI/res/values-lt/strings.xml
index 0355fc0..230194d 100644
--- a/packages/SystemUI/res/values-lt/strings.xml
+++ b/packages/SystemUI/res/values-lt/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Nustatyti įvesties metodus"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fizinė klaviatūra"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Leisti „<xliff:g id="APPLICATION">%1$s</xliff:g>“ pasiekti įrenginį (<xliff:g id="USB_DEVICE">%2$s</xliff:g>)?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Leisti „<xliff:g id="APPLICATION">%1$s</xliff:g>“ pasiekti įrenginį (<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>)?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Atidaryti „<xliff:g id="APPLICATION">%1$s</xliff:g>“, kad būtų galima tvarkyti įrenginį (<xliff:g id="USB_DEVICE">%2$s</xliff:g>)?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Atidaryti „<xliff:g id="APPLICATION">%1$s</xliff:g>“, kad būtų galima tvarkyti įrenginį (<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>)?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Atšaukti"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Patvirtinkite"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Bandyti dar kartą"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Tuščia sritis; palieskite, kad atšauktumėte autentifikavimą"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Palieskite, jei norite atšaukti autentifikavimą"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Bandykite dar kartą"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Ieškoma veido"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Veidas autentifikuotas"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Patvirtinta"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Paliesk. „Patvirtinti“, kad užbaigtumėte"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentifikuota"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Palieskite piršto antspaudo jutiklį"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Piršto antspaudo piktograma"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Ieškoma jūsų…"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Pranešimai"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Žibintuvėlis"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobiliojo ryšio duomenys"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Duomenų naudojimas"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Likę duomenys"</string>
@@ -465,7 +484,7 @@
     <string name="media_projection_remember_text" msgid="3103510882172746752">"Daugiau neberodyti"</string>
     <string name="clear_all_notifications_text" msgid="814192889771462828">"Viską išvalyti"</string>
     <string name="manage_notifications_text" msgid="2386728145475108753">"Tvarkyti"</string>
-    <string name="notification_section_header_gentle" msgid="4372438504154095677">"Tylūs pranešimai"</string>
+    <string name="notification_section_header_gentle" msgid="4372438504154095677">"Tylieji pranešimai"</string>
     <string name="accessibility_notification_section_header_gentle_clear_all" msgid="4286716295850400959">"Išvalyti visus tylius pranešimus"</string>
     <string name="dnd_suppressing_shade_text" msgid="1904574852846769301">"Pranešimai pristabdyti naudojant netrukdymo režimą"</string>
     <string name="media_projection_action_text" msgid="8470872969457985954">"Pradėti dabar"</string>
@@ -511,7 +530,7 @@
     <string name="monitoring_description_do_header_with_name" msgid="5511133708978206460">"„<xliff:g id="ORGANIZATION_NAME">%1$s</xliff:g>“ naudoja „<xliff:g id="DEVICE_OWNER_APP">%2$s</xliff:g>“ įrenginiui tvarkyti."</string>
     <string name="monitoring_description_do_body" msgid="3639594537660975895">"Administrat. gali stebėti ir tvark. nustat., įmonės prieigos par., progr., su įreng. susietus duomenis ir įreng. vietovės inform."</string>
     <string name="monitoring_description_do_learn_more_separator" msgid="3785251953067436862">" "</string>
-    <string name="monitoring_description_do_learn_more" msgid="1849514470437907421">"Sužinoti daugiau"</string>
+    <string name="monitoring_description_do_learn_more" msgid="1849514470437907421">"Sužinokite daugiau"</string>
     <string name="monitoring_description_do_body_vpn" msgid="8255218762488901796">"Esate prisijungę prie programos „<xliff:g id="VPN_APP">%1$s</xliff:g>“, kuri gali stebėti tinklo veiklą, įskaitant el. laiškus, programas ir svetaines."</string>
     <string name="monitoring_description_vpn_settings_separator" msgid="1933186756733474388">" "</string>
     <string name="monitoring_description_vpn_settings" msgid="6434859242636063861">"Atidaryti VPN nustatymus"</string>
diff --git a/packages/SystemUI/res/values-lv/strings.xml b/packages/SystemUI/res/values-lv/strings.xml
index e6ac235..e1905f5 100644
--- a/packages/SystemUI/res/values-lv/strings.xml
+++ b/packages/SystemUI/res/values-lv/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Iestatīt ievades metodes"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fiziskā tastatūra"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Vai atļaut lietotnei <xliff:g id="APPLICATION">%1$s</xliff:g> piekļūt šai ierīcei: <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Vai atļaut lietotnei <xliff:g id="APPLICATION">%1$s</xliff:g> piekļūt šim piederumam: <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Vai atvērt lietotni <xliff:g id="APPLICATION">%1$s</xliff:g>, lai izmantotu šo ierīci: <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Vai atvērt lietotni <xliff:g id="APPLICATION">%1$s</xliff:g>, lai izmantotu šo piederumu: <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Atcelt"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Apstiprināt"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Mēģināt vēlreiz"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Tukšs apgabals. Pieskarieties tam, lai atceltu autentificēšanu."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Pieskarieties, lai atceltu autentifikāciju."</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Lūdzu, mēģiniet vēlreiz."</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Tiek meklēta jūsu seja"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Seja autentificēta"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Apstiprināts"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Lai pabeigtu, pieskarieties Apstiprināt"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentifikācija veikta"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Pieskarieties pirksta nospieduma sensoram"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Pirksta nospieduma ikona"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Notiek jūsu sejas meklēšana…"</string>
@@ -365,6 +382,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Paziņojumi"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Zibspuldze"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobilie dati"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Datu lietojums"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Atlikušie dati"</string>
diff --git a/packages/SystemUI/res/values-mk/strings.xml b/packages/SystemUI/res/values-mk/strings.xml
index a529dfe..300dff5 100644
--- a/packages/SystemUI/res/values-mk/strings.xml
+++ b/packages/SystemUI/res/values-mk/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Постави методи на внес."</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Физичка тастатура"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Ќе дозволите <xliff:g id="APPLICATION">%1$s</xliff:g> да пристапува до <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Ќе дозволите <xliff:g id="APPLICATION">%1$s</xliff:g> да пристапува до <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Да се отвори <xliff:g id="APPLICATION">%1$s</xliff:g> за да управува со <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Да се отвори <xliff:g id="APPLICATION">%1$s</xliff:g> за да управува со <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Откажи"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Потврди"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Обиди се повторно"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Празен регион, допрете за да ја откажете проверката"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Допрете за да ја откажете проверката"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Обидете се повторно"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Го бараме вашето лице"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Лицето е проверено"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Потврдено"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Допрете „Потврди“ за да се заврши"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Проверена"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Допрете го сензорот за отпечатоци"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Икона за отпечатоци"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Ве бараме вас…"</string>
@@ -192,7 +209,7 @@
     <string name="not_default_data_content_description" msgid="9194667237765917844">"Не е поставен да користи интернет"</string>
     <string name="cell_data_off" msgid="1051264981229902873">"Исклучи"</string>
     <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Се поврзува со Bluetooth."</string>
-    <string name="accessibility_airplane_mode" msgid="834748999790763092">"Режим на работа во авион."</string>
+    <string name="accessibility_airplane_mode" msgid="834748999790763092">"Авионски режим."</string>
     <string name="accessibility_vpn_on" msgid="5993385083262856059">"VPN е вклучена."</string>
     <string name="accessibility_no_sims" msgid="3957997018324995781">"Нема SIM-картичка"</string>
     <string name="carrier_network_change_mode" msgid="8149202439957837762">"Променување на мрежата на операторот"</string>
@@ -347,7 +364,7 @@
     <string name="quick_settings_brightness_dialog_title" msgid="8599674057673605368">"Осветленост"</string>
     <string name="quick_settings_brightness_dialog_auto_brightness_label" msgid="5064982743784071218">"Автоматски"</string>
     <string name="quick_settings_inversion_label" msgid="8790919884718619648">"Преврти ги боите"</string>
-    <string name="quick_settings_color_space_label" msgid="853443689745584770">"Режим за корекција на боја"</string>
+    <string name="quick_settings_color_space_label" msgid="853443689745584770">"Режим за корекција на бои"</string>
     <string name="quick_settings_more_settings" msgid="326112621462813682">"Повеќе поставки"</string>
     <string name="quick_settings_done" msgid="3402999958839153376">"Готово"</string>
     <string name="quick_settings_connected" msgid="1722253542984847487">"Поврзано"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Известувања"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Светилка"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобилен интернет"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Потрошен интернет"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Преостанати податоци"</string>
@@ -457,7 +476,7 @@
     <string name="media_projection_dialog_service_text" msgid="3075544489835858258">"При снимањето или емитувањето, услугата што ја обезбедува функцијава може да ги сними чувствителните информации што се прикажани на вашиот екран или пуштени од вашиот уред, вклучувајќи чувствителни информации како што се аудио, лозинки, информации за плаќање, фотографии и пораки."</string>
     <string name="media_projection_dialog_title" msgid="8124184308671641248">"Изложување чувствителни информации при емитување/снимање"</string>
     <string name="media_projection_remember_text" msgid="3103510882172746752">"Не покажувај повторно"</string>
-    <string name="clear_all_notifications_text" msgid="814192889771462828">"Исчисти сè"</string>
+    <string name="clear_all_notifications_text" msgid="814192889771462828">"Избриши сѐ"</string>
     <string name="manage_notifications_text" msgid="2386728145475108753">"Управувајте"</string>
     <string name="notification_section_header_gentle" msgid="4372438504154095677">"Тивки известувања"</string>
     <string name="accessibility_notification_section_header_gentle_clear_all" msgid="4286716295850400959">"Исчисти ги сите тивки известувања"</string>
@@ -597,7 +616,7 @@
     <string name="status_bar_ethernet" msgid="5044290963549500128">"Етернет"</string>
     <string name="status_bar_alarm" msgid="8536256753575881818">"Аларм"</string>
     <string name="status_bar_work" msgid="6022553324802866373">"Работен профил"</string>
-    <string name="status_bar_airplane" msgid="7057575501472249002">"Режим на работа во авион"</string>
+    <string name="status_bar_airplane" msgid="7057575501472249002">"Авионски режим"</string>
     <string name="add_tile" msgid="2995389510240786221">"Додај плочка"</string>
     <string name="broadcast_tile" msgid="3894036511763289383">"Емитувај плочка"</string>
     <string name="zen_alarm_warning_indef" msgid="3482966345578319605">"Нема да го слушнете следниот аларм <xliff:g id="WHEN">%1$s</xliff:g> освен ако претходно не го исклучите ова"</string>
diff --git a/packages/SystemUI/res/values-ml/strings.xml b/packages/SystemUI/res/values-ml/strings.xml
index 181eb4a..0a06b2c 100644
--- a/packages/SystemUI/res/values-ml/strings.xml
+++ b/packages/SystemUI/res/values-ml/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ടൈപ്പുചെയ്യൽ രീതികൾ സജ്ജീകരിക്കുക"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ഫിസിക്കൽ കീബോഡ്"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ആക്‌സസ് ചെയ്യാൻ <xliff:g id="APPLICATION">%1$s</xliff:g>-നെ അനുവദിക്കണോ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ആക്‌സസ് ചെയ്യാൻ <xliff:g id="APPLICATION">%1$s</xliff:g>-നെ അനുവദിക്കണോ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> കൈകാര്യം ചെയ്യാൻ <xliff:g id="APPLICATION">%1$s</xliff:g> തുറക്കണോ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> കൈകാര്യം ചെയ്യാൻ <xliff:g id="APPLICATION">%1$s</xliff:g> തുറക്കണോ?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"റദ്ദാക്കുക"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"സ്ഥിരീകരിക്കുക"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"വീണ്ടും ശ്രമിക്കുക"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ശൂന്യമായ ഇടം, പരിശോധിച്ചുറപ്പിക്കൽ റദ്ദാക്കാൻ ടാപ്പ് ചെയ്യുക"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"പരിശോധിച്ചുറപ്പിക്കൽ റദ്ദാക്കാൻ ടാപ്പ് ചെയ്യുക"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"വീണ്ടും ശ്രമിക്കുക"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"നിങ്ങളുടെ മുഖത്തിന് വേണ്ടി തിരയുന്നു"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"മുഖം പരിശോധിച്ചുറപ്പിച്ചു"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"സ്ഥിരീകരിച്ചു"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"പൂർത്തിയാക്കാൻ സ്ഥിരീകരിക്കുക ടാപ്പ് ചെയ്യൂ"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"പരിശോധിച്ചുറപ്പിച്ചു"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"വിരലടയാള സെൻസർ സ്‌പർശിക്കുക"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"വിരലടയാള ഐക്കൺ"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"നിങ്ങൾക്കായി തിരയുന്നു…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"അറിയിപ്പുകൾ"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ടോർച്ച്"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"മൊബൈൽ ഡാറ്റ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ഡാറ്റാ ഉപയോഗം"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ശേഷിക്കുന്ന ഡാറ്റ"</string>
@@ -376,7 +395,7 @@
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4453017157391574402">"സൂര്യോദയം വരെ"</string>
     <string name="quick_settings_night_secondary_label_on_at" msgid="6256314040368487637">"<xliff:g id="TIME">%s</xliff:g>-ന്"</string>
     <string name="quick_settings_secondary_label_until" msgid="2749196569462600150">"<xliff:g id="TIME">%s</xliff:g> വരെ"</string>
-    <string name="quick_settings_ui_mode_night_label" msgid="3419947801072692538">"ഇരുണ്ട തീം"</string>
+    <string name="quick_settings_ui_mode_night_label" msgid="3419947801072692538">"ഡാർക്ക് തീം"</string>
     <string name="quick_settings_ui_mode_night_label_battery_saver" msgid="7438725724589758362">"ഇരുണ്ട തീം\nബാറ്ററി ലാഭിക്കൽ"</string>
     <string name="quick_settings_nfc_label" msgid="9012153754816969325">"NFC"</string>
     <string name="quick_settings_nfc_off" msgid="6883274004315134333">"NFC പ്രവർത്തനരഹിതമാക്കി"</string>
diff --git a/packages/SystemUI/res/values-mn/strings.xml b/packages/SystemUI/res/values-mn/strings.xml
index 085a0aeeb..0298d20 100644
--- a/packages/SystemUI/res/values-mn/strings.xml
+++ b/packages/SystemUI/res/values-mn/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Оруулах аргыг тохируулах"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Бодит гар"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g>-г <xliff:g id="USB_DEVICE">%2$s</xliff:g>-д хандахыг зөвшөөрөх үү?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g>-г <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>-д хандахыг зөвшөөрөх үү?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>-г зохицуулахын тулд <xliff:g id="APPLICATION">%1$s</xliff:g>-г нээх үү?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>-г зохицуулахын тулд <xliff:g id="APPLICATION">%1$s</xliff:g>-г нээх үү?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Цуцлах"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Баталгаажуулах"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Дахин оролдох"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Нотолгоог цуцлахын тулд хоосон бүсийг товшино уу"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Нотолгоог цуцлахын тулд товшино уу"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Дахин оролдоно уу"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Таны царайг хайж байна"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Царайг баталгаажууллаа"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Баталгаажсан"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Дуусгахын тулд баталгаажуулахыг товших"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Баталгаажуулагдсан"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Хурууны хээ мэдрэгчид хүрэх"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Хурууны хээний дүрс тэмдэг"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Таныг хайж байна…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Мэдэгдэл"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Гар чийдэн"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобайл дата"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Дата ашиглалт"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Үлдсэн дата"</string>
diff --git a/packages/SystemUI/res/values-mr/strings.xml b/packages/SystemUI/res/values-mr/strings.xml
index 4722ae9..07b985f 100644
--- a/packages/SystemUI/res/values-mr/strings.xml
+++ b/packages/SystemUI/res/values-mr/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"इनपुट पद्धती सेट करा"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"वास्तविक कीबोर्ड"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> ला <xliff:g id="USB_DEVICE">%2$s</xliff:g> अ‍ॅक्सेस करण्याची अनुमती द्यायची का?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> ला <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> अ‍ॅक्सेस करण्याची अनुमती द्यायची का?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> हाताळण्यासाठी <xliff:g id="APPLICATION">%1$s</xliff:g> उघडायचे का?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> हाताळण्यासाठी <xliff:g id="APPLICATION">%1$s</xliff:g> उघडायचे का?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"रद्द करा"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"खात्री करा"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"पुन्हा प्रयत्न करा"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"प्रदेशाचे नाव रिक्त आहे, ऑथेंटिकेशन रद्द करण्यासाठी टॅप करा"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ऑथेंटिकेशन रद्द करण्यासाठी टॅप करा"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"कृपया पुन्हा प्रयत्न करा"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"तुमचा चेहरा शोधत आहे"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"चेहरा ऑथेंटिकेशन केलेला आहे"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"निश्चित केले"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"पूर्ण करण्यासाठी खात्री करा वर टॅप करा"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ऑथेंटिकेशन केलेले"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"फिंगरप्रिंट सेन्सरला स्पर्श करा"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"फिंगरप्रिंट आयकन"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"तुमच्यासाठी शोधत आहे…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"सूचना"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"फ्लॅशलाइट"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"मोबाइल डेटा"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"डेटा वापर"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"शिल्लक डेटा"</string>
diff --git a/packages/SystemUI/res/values-ms/strings.xml b/packages/SystemUI/res/values-ms/strings.xml
index 1bc7ca9..f696ee3 100644
--- a/packages/SystemUI/res/values-ms/strings.xml
+++ b/packages/SystemUI/res/values-ms/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Sediakan kaedah input"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Papan kekunci fizikal"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Benarkan <xliff:g id="APPLICATION">%1$s</xliff:g> mengakses <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Benarkan <xliff:g id="APPLICATION">%1$s</xliff:g> mengakses <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Buka <xliff:g id="APPLICATION">%1$s</xliff:g> untuk mengendalikan <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Buka <xliff:g id="APPLICATION">%1$s</xliff:g> untuk mengendalikan <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Batal"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Sahkan"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Cuba lagi"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Kawasan kosong. Ketik untuk membatalkan pengesahan"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Ketik untuk membatalkan pengesahan"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Sila cuba lagi"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Mencari wajah anda"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Wajah disahkan"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Disahkan"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Ketik Sahkan untuk menyelesaikan"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Disahkan"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Sentuh penderia cap jari"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikon cap jari"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Mencari anda…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Pemberitahuan"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lampu suluh"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Data mudah alih"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Penggunaan data"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Baki data"</string>
diff --git a/packages/SystemUI/res/values-my/strings.xml b/packages/SystemUI/res/values-my/strings.xml
index 51aaaa2..eb73df7 100644
--- a/packages/SystemUI/res/values-my/strings.xml
+++ b/packages/SystemUI/res/values-my/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ထည့်သွင်းနည်းများ သတ်မှတ်ခြင်း"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ခလုတ်ပါဝင်သော ကီးဘုတ်"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> အား ဝင်သုံးရန် <xliff:g id="APPLICATION">%1$s</xliff:g> ကို ခွင့်ပြုပါသလား။"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> အား ဝင်သုံးရန် <xliff:g id="APPLICATION">%1$s</xliff:g> ကို ခွင့်ပြုပါသလား။"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ဆောင်ရွက်ရန် <xliff:g id="APPLICATION">%1$s</xliff:g> ကို ဖွင့်လိုပါသလား။"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ဆောင်ရွက်ရန် <xliff:g id="APPLICATION">%1$s</xliff:g> ကို ဖွင့်လိုပါသလား။"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"မလုပ်တော့"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"အတည်ပြုပါ"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ထပ်စမ်းကြည့်ရန်"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"နေရာလွတ်၊ အထောက်အထားစိစစ်ခြင်းကို မလုပ်တော့ရန် တို့ပါ"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"အထောက်အထားစိစစ်ခြင်းကို ပယ်ဖျက်ရန် တို့ပါ"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"ထပ်စမ်းကြည့်ပါ"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"သင့်မျက်နှာကို ရှာနေသည်"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"မျက်နှာ အထောက်အထားစိစစ်ပြီးပြီ"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"အတည်ပြုပြီးပြီ"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"အပြီးသတ်ရန်အတွက် \'အတည်ပြုရန်\' ကို တို့ပါ"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"အထောက်အထားစိစစ်ပြီးပြီ"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"လက်ဗွေအာရုံခံကိရိယာကို တို့ပါ"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"လက်ဗွေ သင်္ကေတ"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"သင့်ကို ရှာဖွေနေသည်…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"အကြောင်းကြားချက်များ"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ဖလက်ရှ်မီး"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"မိုဘိုင်းဒေတာ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ဒေတာ သုံးစွဲမှု"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ကျန်ရှိ ဒေတာ"</string>
diff --git a/packages/SystemUI/res/values-nb/strings.xml b/packages/SystemUI/res/values-nb/strings.xml
index ce611e0..9e1c5db 100644
--- a/packages/SystemUI/res/values-nb/strings.xml
+++ b/packages/SystemUI/res/values-nb/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Konfigurer inndatametoder"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fysisk tastatur"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Vil du gi <xliff:g id="APPLICATION">%1$s</xliff:g> tilgang til <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Vil du gi <xliff:g id="APPLICATION">%1$s</xliff:g> tilgang til <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Vil du åpne <xliff:g id="APPLICATION">%1$s</xliff:g> for å behandle <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Vil du åpne <xliff:g id="APPLICATION">%1$s</xliff:g> for å behandle <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Avbryt"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Bekreft"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Prøv på nytt"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Tomt område – trykk for å avbryte autentisering"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Trykk for å avbryte autentiseringen"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Prøv igjen"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Ser etter ansiktet ditt"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Ansiktet er autentisert"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Bekreftet"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Trykk på Bekreft for å fullføre"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentisert"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Trykk på fingeravtrykkssensoren"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikon for fingeravtrykk"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Ser etter deg …"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Varsler"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lommelykt"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobildata"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Databruk"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Gjenværende data"</string>
diff --git a/packages/SystemUI/res/values-ne/strings.xml b/packages/SystemUI/res/values-ne/strings.xml
index 6ef85b5..5a00002 100644
--- a/packages/SystemUI/res/values-ne/strings.xml
+++ b/packages/SystemUI/res/values-ne/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"इनपुट विधिहरू सेटअप गर्नुहोस्"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"वास्तविक किबोर्ड"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> लाई <xliff:g id="USB_DEVICE">%2$s</xliff:g> माथि पहुँच राख्ने अनुमति दिने हो?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> लाई <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> माथि पहुँच राख्ने अनुमति दिने हो?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> को व्यवस्थापन गर्न <xliff:g id="APPLICATION">%1$s</xliff:g> खोल्ने हो?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> को व्यवस्थापन गर्न <xliff:g id="APPLICATION">%1$s</xliff:g> खोल्ने हो?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"रद्द गर्नुहोस्"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"पुष्टि गर्नुहोस्"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"फेरि प्रयास गर्नुहोस्"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"खाली क्षेत्र, प्रमाणीकरण रद्द गर्न ट्याप गर्नुहोस्"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"प्रमाणीकरण रद्द गर्न ट्याप गर्नुहोस्"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"कृपया फेरि प्रयास गर्नुहोस्"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"तपाईंको अनुहार खोज्दै"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"अनुहार प्रमाणीकरण गरियो"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"पुष्टि भयो"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"पूरा गर्नका लागि पुष्टि गर्नुहोस् नामक विकल्पमा ट्याप गर्नुहोस्"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"प्रमाणीकरण गरियो"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"फिंगरप्रिन्ट सेन्सरमा छुनुहोस्‌"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"फिंगरप्रिन्ट जनाउने आइकन"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"तपाईंलाई खोज्दै…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"अधिसूचनाहरू"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"फ्ल्यासलाइट"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"मोबाइल डेटा"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"डेटाको प्रयोग"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"बाँकी डेटा"</string>
@@ -544,7 +563,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"तपाईंले अनपिन नगरेसम्म यसले त्यसलाई दृश्यमा कायम राख्छ। अनपिन गर्न परिदृश्य बटनलाई छोइराख्नुहोस्।"</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"तपाईंले अनपिन नगरेसम्म यसले त्यसलाई दृश्यमा कायम राख्छ। अनपिन गर्न गृह नामक बटनलाई छोइराख्नुहोस्।"</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"यस स्क्रिनलाई अनपनि गर्न पछाडि र परिदृश्य नामक बटनहरूलाई छोइराख्नुहोस्"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"यस स्क्रिनलाई अनपनि गर्न पछाडि र गृह नामक बटनहरूलाई छोइराख्नुहोस्"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"यस स्क्रिनलाई अनपिन गर्न पछाडि र गृह नामक बटनहरूलाई छोइराख्नुहोस्"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"यो स्क्रिन अनपिन गर्न माथितिर स्वाइप गरी थिचिराख्नुहोस्"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"बुझेँ"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"धन्यवाद पर्दैन"</string>
diff --git a/packages/SystemUI/res/values-nl/strings.xml b/packages/SystemUI/res/values-nl/strings.xml
index 305b46a..dacbd53 100644
--- a/packages/SystemUI/res/values-nl/strings.xml
+++ b/packages/SystemUI/res/values-nl/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Invoermethoden instellen"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fysiek toetsenbord"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> toegang geven tot <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> toegang geven tot <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="APPLICATION">%1$s</xliff:g> openen om <xliff:g id="USB_DEVICE">%2$s</xliff:g> te verwerken?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="APPLICATION">%1$s</xliff:g> openen om <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> te verwerken?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Annuleren"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Bevestigen"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Opnieuw proberen"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Leeg gebied. Tik om de verificatie te annuleren."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tik om de verificatie te annuleren"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Probeer het opnieuw"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Er wordt naar je gezicht gezocht"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Gezicht geverifieerd"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Bevestigd"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tik op Bevestigen om te voltooien"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Geverifieerd"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Raak de vingerafdruksensor aan"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Vingerafdrukpictogram"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Jouw gezicht zoeken…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Meldingen"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Zaklamp"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobiele data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Datagebruik"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Resterende gegevens"</string>
diff --git a/packages/SystemUI/res/values-or/strings.xml b/packages/SystemUI/res/values-or/strings.xml
index e9b150c..2720abf 100644
--- a/packages/SystemUI/res/values-or/strings.xml
+++ b/packages/SystemUI/res/values-or/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ଇନପୁଟ୍‍ ପଦ୍ଧତି ସେଟ୍‍ କରନ୍ତୁ"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ଫିଜିକଲ୍ କୀ’ବୋର୍ଡ୍"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ଆକ୍ସେସ୍‍ କରିବାକୁ <xliff:g id="APPLICATION">%1$s</xliff:g>କୁ ଅନୁମତି ଦେବେ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ଆକ୍ସେସ୍‍ କରିବାକୁ <xliff:g id="APPLICATION">%1$s</xliff:g>କୁ ଅନୁମତି ଦେବେ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ନିୟନ୍ତ୍ରଣ କରିବାକୁ <xliff:g id="APPLICATION">%1$s</xliff:g> ଖୋଲିବେ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ନିୟନ୍ତ୍ରଣ କରିବାକୁ <xliff:g id="APPLICATION">%1$s</xliff:g> ଖୋଲିବେ?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"କ୍ୟାନ୍ସଲ୍‍ କରନ୍ତୁ"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"ନିଶ୍ଚିତ କରନ୍ତୁ"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ପୁଣି ଚେଷ୍ଟା କରନ୍ତୁ"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ଖାଲି ଅଞ୍ଚଳ, ପ୍ରାମାଣିକତା ବାତିଲ୍ କରିବାକୁ ଟାପ୍ କରନ୍ତୁ"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ପ୍ରାମାଣିକତା ବାତିଲ୍ କରିବାକୁ ଟାପ୍ କରନ୍ତୁ"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"ଦୟାକରି ପୁଣି ଚେଷ୍ଟା କରନ୍ତୁ"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"ଆପଣଙ୍କର ମୁହଁକୁ ପ୍ରମାଣ କରୁଛି"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ମୁହଁ ପ୍ରାମାଣିକତା ହୋଇଛି"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"ସୁନିଶ୍ଚିତ କରାଯାଇଛି"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"ସମ୍ପୂର୍ଣ୍ଣ କରିବାକୁ ସୁନିଶ୍ଚିତ କରନ୍ତୁରେ ଟାପ୍ କରନ୍ତୁ"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ପ୍ରାମାଣିକତା ହୋଇଛି"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ଟିପଚିହ୍ନ ସେନସର୍‌କୁ ଛୁଅଁନ୍ତୁ"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ଆଙ୍ଗୁଠି ଚିହ୍ନ ଆଇକନ୍"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"ଆପଣଙ୍କୁ ଚିହ୍ନଟ କରୁଛି…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"ବିଜ୍ଞପ୍ତି"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ଫ୍ଲାସ୍‍ଲାଇଟ୍"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"ମୋବାଇଲ୍‌ ଡାଟା"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ଡାଟାର ବ୍ୟବହାର"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ଅବଶିଷ୍ଟ ଡାଟା"</string>
diff --git a/packages/SystemUI/res/values-pa/strings.xml b/packages/SystemUI/res/values-pa/strings.xml
index 742080c..805a580 100644
--- a/packages/SystemUI/res/values-pa/strings.xml
+++ b/packages/SystemUI/res/values-pa/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ਇਨਪੁਟ ਵਿਧੀਆਂ ਸੈਟ ਅਪ ਕਰੋ"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"ਫਿਜੀਕਲ ਕੀ-ਬੋਰਡ"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"ਕੀ <xliff:g id="USB_DEVICE">%2$s</xliff:g> ਤੱਕ <xliff:g id="APPLICATION">%1$s</xliff:g> ਨੂੰ ਪਹੁੰਚ ਕਰਨ ਦੇਣੀ ਹੈ?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"ਕੀ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ਤੱਕ <xliff:g id="APPLICATION">%1$s</xliff:g> ਨੂੰ ਪਹੁੰਚ ਕਰਨ ਦੇਣੀ ਹੈ?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"ਕੀ <xliff:g id="USB_DEVICE">%2$s</xliff:g> ਨੂੰ ਵਰਤਣ ਲਈ <xliff:g id="APPLICATION">%1$s</xliff:g> ਖੋਲ੍ਹਣੀ ਹੈ?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"ਕੀ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ਨੂੰ ਵਰਤਣ ਲਈ <xliff:g id="APPLICATION">%1$s</xliff:g> ਖੋਲ੍ਹਣੀ ਹੈ?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"ਰੱਦ ਕਰੋ"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"ਪੁਸ਼ਟੀ ਕਰੋ"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ਖਾਲੀ ਖੇਤਰ, ਪ੍ਰਮਾਣੀਕਰਨ ਰੱਦ ਕਰਨ ਲਈ ਟੈਪ ਕਰੋ"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ਪ੍ਰਮਾਣੀਕਰਨ ਰੱਦ ਕਰਨ ਲਈ ਟੈਪ ਕਰੋ"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"ਕਿਰਪਾ ਕਰਕੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"ਤੁਹਾਡਾ ਚਿਹਰਾ ਲੱਭਿਆ ਜਾ ਰਿਹਾ ਹੈ"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ਚਿਹਰਾ ਪ੍ਰਮਾਣੀਕਿਰਤ ਹੋਇਆ"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"ਪੁਸ਼ਟੀ ਕੀਤੀ ਗਈ"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"ਪੂਰਾ ਕਰਨ ਲਈ ਪੁਸ਼ਟੀ ਕਰੋ \'ਤੇ ਟੈਪ ਕਰੋ"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ਪ੍ਰਮਾਣਿਤ ਹੋਇਆ"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ਫਿੰਗਰਪ੍ਰਿੰਟ ਸੈਂਸਰ ਨੂੰ ਸਪੱਰਸ਼ ਕਰੋ"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ਫਿੰਗਰਪ੍ਰਿੰਟ ਦਾ ਪ੍ਰਤੀਕ"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"ਤੁਹਾਡੀ ਪਛਾਣ ਕੀਤੀ ਜਾ ਰਹੀ ਹੈ…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"ਸੂਚਨਾਵਾਂ"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ਫਲੈਸ਼ਲਾਈਟ"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"ਮੋਬਾਈਲ ਡਾਟਾ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ਡਾਟਾ ਵਰਤੋਂ"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ਬਾਕੀ  ਡਾਟਾ"</string>
@@ -401,7 +420,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"ਹੇਠਾਂ ਘੱਟ ਲਾਜ਼ਮੀ ਸੂਚਨਾਵਾਂ"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"ਖੋਲ੍ਹਣ ਲਈ ਦੁਬਾਰਾ ਟੈਪ ਕਰੋ"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"ਖੋਲ੍ਹਣ ਲਈ ਉੱਪਰ ਵੱਲ ਸਵਾਈਪ ਕਰੋ"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰਨ ਲਈ ਸਵਾਈਪ ਕਰੋ"</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰਨ ਲਈ ਉੱਤੇ ਵੱਲ ਸਵਾਈਪ ਕਰੋ"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"ਇਸ ਡੀਵਾਈਸ ਦਾ ਪ੍ਰਬੰਧਨ ਤੁਹਾਡੇ ਸੰਗਠਨ ਵੱਲੋਂ ਕੀਤਾ ਜਾਂਦਾ ਹੈ"</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"ਇਹ ਡੀਵਾਈਸ <xliff:g id="ORGANIZATION_NAME">%s</xliff:g> ਵੱਲੋਂ ਪ੍ਰਬੰਧਿਤ ਕੀਤਾ ਗਿਆ ਹੈ"</string>
     <string name="phone_hint" msgid="4872890986869209950">"ਫ਼ੋਨ ਲਈ ਪ੍ਰਤੀਕ ਤੋਂ ਸਵਾਈਪ ਕਰੋ"</string>
diff --git a/packages/SystemUI/res/values-pl/strings.xml b/packages/SystemUI/res/values-pl/strings.xml
index 4be1a0f..16dfff3 100644
--- a/packages/SystemUI/res/values-pl/strings.xml
+++ b/packages/SystemUI/res/values-pl/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Konfiguruj metody wprowadzania"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Klawiatura fizyczna"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Zezwolić aplikacji <xliff:g id="APPLICATION">%1$s</xliff:g> na dostęp do urządzenia <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Zezwolić aplikacji <xliff:g id="APPLICATION">%1$s</xliff:g> na dostęp do urządzenia <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Otworzyć aplikację <xliff:g id="APPLICATION">%1$s</xliff:g> do obsługi urządzenia <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Otworzyć aplikację <xliff:g id="APPLICATION">%1$s</xliff:g> do obsługi urządzenia <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Anuluj"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Potwierdź"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Spróbuj jeszcze raz"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Pusty obszar, kliknij, by anulować uwierzytelnianie"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Kliknij, by anulować uwierzytelnianie"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Spróbuj ponownie"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Szukam Twojej twarzy"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Twarz rozpoznana"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Potwierdzono"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Aby zakończyć, kliknij Potwierdź"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Uwierzytelniono"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Dotknij czytnika linii papilarnych"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona odcisku palca"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Szukam Cię…"</string>
@@ -369,6 +386,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Powiadomienia"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Latarka"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobilna transmisja danych"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Użycie danych"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Pozostały limit"</string>
diff --git a/packages/SystemUI/res/values-pt-rBR/strings.xml b/packages/SystemUI/res/values-pt-rBR/strings.xml
index 7a57049..25ca226 100644
--- a/packages/SystemUI/res/values-pt-rBR/strings.xml
+++ b/packages/SystemUI/res/values-pt-rBR/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurar métodos de entrada"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teclado físico"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Permitir que o app <xliff:g id="APPLICATION">%1$s</xliff:g> acesse <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Permitir que o app <xliff:g id="APPLICATION">%1$s</xliff:g> acesse <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Abrir o app <xliff:g id="APPLICATION">%1$s</xliff:g> para lidar com o <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Abrir o app <xliff:g id="APPLICATION">%1$s</xliff:g> para lidar com o <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancelar"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmar"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Tentar novamente"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Região vazia. Toque nela para cancelar a autenticação"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Toque para cancelar a autenticação"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Tente novamente"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Procurando seu rosto"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Rosto autenticado"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmada"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Toque em \"Confirmar\" para concluir"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenticado"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Toque no sensor de impressão digital"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ícone de impressão digital"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Procurando você…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificações"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lanterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Dados móveis"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Uso de dados"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Dados restantes"</string>
@@ -544,7 +563,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"Ela é mantida à vista até que seja liberada. Toque em Visão geral e mantenha essa opção pressionada para liberar."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"Ela é mantida à vista até que seja liberada. Toque em Início e mantenha essa opção pressionada para liberar."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"Para liberar esta tela, mantenha os botões Voltar e Visão geral pressionados"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Para liberar essa tela, toque nos botões Voltar e Início e mantenha-os pressionados"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Para liberar esta tela, mantenha os botões Voltar e Início pressionados"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"Para liberar esta tela, deslize para cima e pressione"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Entendi"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"Não, obrigado"</string>
diff --git a/packages/SystemUI/res/values-pt-rPT/strings.xml b/packages/SystemUI/res/values-pt-rPT/strings.xml
index fb45ea7..fdb98fa 100644
--- a/packages/SystemUI/res/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res/values-pt-rPT/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurar métodos introdução"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teclado físico"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Pretende permitir que a aplicação <xliff:g id="APPLICATION">%1$s</xliff:g> aceda ao dispositivo <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Pretende permitir que a aplicação <xliff:g id="APPLICATION">%1$s</xliff:g> aceda ao acessório <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Pretende abrir a aplicação <xliff:g id="APPLICATION">%1$s</xliff:g> para controlar o acessório <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Pretende abrir a aplicação <xliff:g id="APPLICATION">%1$s</xliff:g> para controlar o acessório <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -68,7 +70,7 @@
     <string name="learn_more" msgid="5000517160980853569">"Saiba mais"</string>
     <string name="compat_mode_on" msgid="6623839244840638213">"Zoom para preencher o ecrã"</string>
     <string name="compat_mode_off" msgid="4434467572461327898">"Esticar p. caber em ec. int."</string>
-    <string name="global_action_screenshot" msgid="8329831278085426283">"Captura de ecrã"</string>
+    <string name="global_action_screenshot" msgid="8329831278085426283">"Capt. ecrã"</string>
     <string name="screenshot_saving_ticker" msgid="7403652894056693515">"A guardar captura de ecrã..."</string>
     <string name="screenshot_saving_title" msgid="8242282144535555697">"A guardar captura de ecrã..."</string>
     <string name="screenshot_saved_title" msgid="5637073968117370753">"Captura de ecrã guardada"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancelar"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmar"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Tentar novamente"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Região vazia. Toque para cancelar a autenticação."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Toque para cancelar a autenticação."</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Tente novamente."</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"A procurar o seu rosto…"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Rosto autenticado"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmado"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Toque em Confirmar para concluir."</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenticado"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Toque no sensor de impressões digitais."</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ícone de impressão digital"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"À sua procura…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificações"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lanterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Dados móveis"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Utilização de dados"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Dados restantes"</string>
diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml
index 7a57049..25ca226 100644
--- a/packages/SystemUI/res/values-pt/strings.xml
+++ b/packages/SystemUI/res/values-pt/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Configurar métodos de entrada"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Teclado físico"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Permitir que o app <xliff:g id="APPLICATION">%1$s</xliff:g> acesse <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Permitir que o app <xliff:g id="APPLICATION">%1$s</xliff:g> acesse <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Abrir o app <xliff:g id="APPLICATION">%1$s</xliff:g> para lidar com o <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Abrir o app <xliff:g id="APPLICATION">%1$s</xliff:g> para lidar com o <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Cancelar"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmar"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Tentar novamente"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Região vazia. Toque nela para cancelar a autenticação"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Toque para cancelar a autenticação"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Tente novamente"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Procurando seu rosto"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Rosto autenticado"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmada"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Toque em \"Confirmar\" para concluir"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autenticado"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Toque no sensor de impressão digital"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ícone de impressão digital"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Procurando você…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificações"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lanterna"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Dados móveis"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Uso de dados"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Dados restantes"</string>
@@ -544,7 +563,7 @@
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"Ela é mantida à vista até que seja liberada. Toque em Visão geral e mantenha essa opção pressionada para liberar."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"Ela é mantida à vista até que seja liberada. Toque em Início e mantenha essa opção pressionada para liberar."</string>
     <string name="screen_pinning_toast" msgid="2266705122951934150">"Para liberar esta tela, mantenha os botões Voltar e Visão geral pressionados"</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Para liberar essa tela, toque nos botões Voltar e Início e mantenha-os pressionados"</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Para liberar esta tela, mantenha os botões Voltar e Início pressionados"</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"Para liberar esta tela, deslize para cima e pressione"</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"Entendi"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"Não, obrigado"</string>
diff --git a/packages/SystemUI/res/values-ro/strings.xml b/packages/SystemUI/res/values-ro/strings.xml
index e897f16..171ca9a 100644
--- a/packages/SystemUI/res/values-ro/strings.xml
+++ b/packages/SystemUI/res/values-ro/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Setați metode introducere text"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Tastatură fizică"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Permiteți <xliff:g id="APPLICATION">%1$s</xliff:g> să acceseze <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Permiteți <xliff:g id="APPLICATION">%1$s</xliff:g> să acceseze <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Deschideți <xliff:g id="APPLICATION">%1$s</xliff:g> ca să gestioneze <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Deschideți <xliff:g id="APPLICATION">%1$s</xliff:g> ca să gestioneze <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -56,7 +58,7 @@
     <string name="always_use_device" msgid="4015357883336738417">"Deschideți întotdeauna <xliff:g id="APPLICATION">%1$s</xliff:g> când este conectat <xliff:g id="USB_DEVICE">%2$s</xliff:g>"</string>
     <string name="always_use_accessory" msgid="3257892669444535154">"Deschideți întotdeauna <xliff:g id="APPLICATION">%1$s</xliff:g> când este conectat <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>"</string>
     <string name="usb_debugging_title" msgid="4513918393387141949">"Permiteți remedierea erorilor prin USB?"</string>
-    <string name="usb_debugging_message" msgid="2220143855912376496">"Amprenta digitală din cheia RSA a computerului este:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
+    <string name="usb_debugging_message" msgid="2220143855912376496">"Amprenta din cheia RSA a computerului este:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
     <string name="usb_debugging_always" msgid="303335496705863070">"Permiteți întotdeauna de pe acest computer"</string>
     <string name="usb_debugging_allow" msgid="2272145052073254852">"Permiteți"</string>
     <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"Remedierea erorilor prin USB nu este permisă"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Anulați"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Confirmați"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Încercați din nou"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Zonă goală, atingeți pentru a anula autentificarea"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Atingeți pentru a anula autentificarea"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Încercați din nou"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Se caută chipul"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Chip autentificat"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Confirmat"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Atingeți Confirmați pentru a finaliza"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentificat"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Atingeți senzorul de amprente"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Pictograma amprentă"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Vă căutăm…"</string>
@@ -365,6 +382,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Notificări"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Lanternă"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Date mobile"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Utilizarea datelor"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Date rămase"</string>
diff --git a/packages/SystemUI/res/values-ru/strings.xml b/packages/SystemUI/res/values-ru/strings.xml
index c68f81e..1d7f6c8 100644
--- a/packages/SystemUI/res/values-ru/strings.xml
+++ b/packages/SystemUI/res/values-ru/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Настройка способов ввода"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Физическая клавиатура"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Предоставить приложению \"<xliff:g id="APPLICATION">%1$s</xliff:g>\" доступ к устройству \"<xliff:g id="USB_DEVICE">%2$s</xliff:g>\"?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Предоставить приложению \"<xliff:g id="APPLICATION">%1$s</xliff:g>\" доступ к устройству \"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>\"?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Открыть приложение \"<xliff:g id="APPLICATION">%1$s</xliff:g>\" для управления устройством \"<xliff:g id="USB_DEVICE">%2$s</xliff:g>\"?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Открыть приложение \"<xliff:g id="APPLICATION">%1$s</xliff:g>\" для управления устройством \"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>\"?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Отмена"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Подтвердить"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Повторить попытку"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Пустая область. Нажмите на нее, чтобы отменить аутентификацию."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Нажмите, чтобы отменить аутентификацию"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Повторите попытку"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Распознавание лица"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Лицо распознано"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Подтверждено"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Нажмите \"Подтвердить\""</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Аутентификация выполнена"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Прикоснитесь к сканеру отпечатков пальцев."</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Значок отпечатка пальца"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Поиск лица…"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Уведомления"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Фонарик"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобильный Интернет"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Передача данных"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Остается данных"</string>
@@ -405,7 +424,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"Показать менее важные уведомления"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"Нажмите ещё раз, чтобы открыть"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"Проведите вверх, чтобы открыть"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"Чтобы повторить попытку, проведите по экрану вверх."</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"Чтобы повторить попытку, проведите вверх"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"Этим устройством управляет ваша организация"</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"Этим устройством управляет компания \"<xliff:g id="ORGANIZATION_NAME">%s</xliff:g>\""</string>
     <string name="phone_hint" msgid="4872890986869209950">"Телефон: проведите от значка"</string>
@@ -549,8 +568,8 @@
     <string name="screen_pinning_description_gestural" msgid="1191513974909607884">"Экран будет зафиксирован, пока вы не отмените блокировку (для этого нужно провести вверх и удерживать)."</string>
     <string name="screen_pinning_description_accessible" msgid="426190689254018656">"Приложение останется активным, пока вы не отмените блокировку, нажав и удерживая кнопку \"Обзор\"."</string>
     <string name="screen_pinning_description_recents_invisible_accessible" msgid="6134833683151189507">"Приложение останется активным, пока вы не отмените блокировку, нажав и удерживая кнопку \"Главный экран\"."</string>
-    <string name="screen_pinning_toast" msgid="2266705122951934150">"Чтобы отменить блокировку, нажмите и удерживайте кнопки \"Назад\" и \"Обзор\""</string>
-    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Чтобы отменить блокировку, нажмите и удерживайте кнопки \"Назад\" и \"Главный экран\""</string>
+    <string name="screen_pinning_toast" msgid="2266705122951934150">"Чтобы открепить экран, нажмите и удерживайте кнопки \"Назад\" и \"Обзор\"."</string>
+    <string name="screen_pinning_toast_recents_invisible" msgid="8252402309499161281">"Чтобы открепить экран, нажмите и удерживайте кнопки \"Назад\" и \"Главный экран\"."</string>
     <string name="screen_pinning_toast_gesture_nav" msgid="5070548776081664958">"Чтобы открепить этот экран, проведите по нему вверх и задержите руку в крайнем положении."</string>
     <string name="screen_pinning_positive" msgid="3783985798366751226">"ОК"</string>
     <string name="screen_pinning_negative" msgid="3741602308343880268">"Нет, спасибо"</string>
diff --git a/packages/SystemUI/res/values-si/strings.xml b/packages/SystemUI/res/values-si/strings.xml
index 2c54218..fa1c109 100644
--- a/packages/SystemUI/res/values-si/strings.xml
+++ b/packages/SystemUI/res/values-si/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ආදාන ක්‍රම සකසන්න"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"භෞතික යතුරු පුවරුව"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> හට <xliff:g id="USB_DEVICE">%2$s</xliff:g> වෙත පිවිසීමට ඉඩ දෙන්නද?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> හට <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> වෙත පිවිසීමට ඉඩ දෙන්නද?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> හැසිරවීමට <xliff:g id="APPLICATION">%1$s</xliff:g> විවෘත කරන්නද?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> හැසිරවීමට <xliff:g id="APPLICATION">%1$s</xliff:g> විවෘත කරන්නද?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"අවලංගු කරන්න"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"තහවුරු කරන්න"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"නැවත උත්සාහ කරන්න"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"හිස් කලාපය, සත්‍යාපනය අවලංගු කිරීමට තට්ටු කරන්න"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"සත්‍යාපනය අවලංගු කිරීමට තට්ටු කරන්න"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"නැවත උත්සාහ කරන්න"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"ඔබේ මුහුණ සොයනු ලැබේ"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"මුහුණ සත්‍යාපන කළා"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"තහවුරු කළා"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"සම්පූර්ණ කිරීමට තහවුරු කරන්න තට්ටු කර."</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"සත්‍යාපනය විය"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"ඇඟිලි සලකුණු සංවේදකය ස්පර්ශ කරන්න"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ඇඟිලි සලකුණු නිරූපකය"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"ඔබව සොයමින්…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"දැනුම්දීම්"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"සැණෙළි ආලෝකය"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"ජංගම දත්ත"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"දත්ත භාවිතය"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ඉතිරි ඇති දත්ත"</string>
diff --git a/packages/SystemUI/res/values-sk/strings.xml b/packages/SystemUI/res/values-sk/strings.xml
index d14f928..ddb0ed4 100644
--- a/packages/SystemUI/res/values-sk/strings.xml
+++ b/packages/SystemUI/res/values-sk/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Nastavenie metód vstupu"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fyzická klávesnica"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Povoliť aplikácii <xliff:g id="APPLICATION">%1$s</xliff:g> prístup k zariadeniu <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Povoliť aplikácii <xliff:g id="APPLICATION">%1$s</xliff:g> prístup k zariadeniu <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Otvoriť aplikáciu <xliff:g id="APPLICATION">%1$s</xliff:g> na použitie zariadenia <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Otvoriť aplikáciu <xliff:g id="APPLICATION">%1$s</xliff:g> na použitie zariadenia <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Zrušiť"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Potvrdiť"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Skúsiť znova"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Prázdna oblasť, klepnutím zrušte overenie"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Klepnutím zrušíte overenie"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Skúste to znova"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Hľadá sa vaša tvár"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Tvár bola overená"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Potvrdené"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Overenie dokončíte klepnutím na Potvrdiť"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Overené"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Dotknite sa senzora odtlačkov prstov"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona odtlačku prsta"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Hľadáme vás…"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Upozornenia"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Baterka"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobilné dáta"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Spotreba dát"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Zostávajúce údaje"</string>
@@ -405,7 +424,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"Menej naliehavé upozornenia sa nachádzajú nižšie"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"Upozornenie otvoríte opätovným klepnutím"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"Otvorte potiahnutím prstom nahor"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"Potiahnutím nahor to skúsite znova"</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"Potiahnutím nahor to skúste znova"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"Toto zariadenie spravuje vaša organizácia"</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"Toto zariadenie spravuje organizácia <xliff:g id="ORGANIZATION_NAME">%s</xliff:g>"</string>
     <string name="phone_hint" msgid="4872890986869209950">"Telefón otvoríte prejdením prstom od ikony"</string>
diff --git a/packages/SystemUI/res/values-sl/strings.xml b/packages/SystemUI/res/values-sl/strings.xml
index 63358ba..1af84fe 100644
--- a/packages/SystemUI/res/values-sl/strings.xml
+++ b/packages/SystemUI/res/values-sl/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Nastavi načine vnosa"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fizična tipkovnica"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Ali aplikaciji <xliff:g id="APPLICATION">%1$s</xliff:g> dovolite dostop do dodatka USB <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Ali aplikaciji <xliff:g id="APPLICATION">%1$s</xliff:g> dovolite dostop do dodatka USB <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Želite odpreti aplikacijo <xliff:g id="APPLICATION">%1$s</xliff:g> za upravljanje dodatka USB <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Želite odpreti aplikacijo <xliff:g id="APPLICATION">%1$s</xliff:g> za upravljanje dodatka USB <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Prekliči"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Potrdite"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Poskusi znova"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Prazno območje. Dotaknite se, da prekličete preverjanje pristnosti."</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Če želite preklicati preverjanje pristnosti, se dotaknite"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Poskusite znova"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Iskanje obraza"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Pristnost obraza je potrjena"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Potrjeno"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Za dokončanje se dotaknite »Potrdite«"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Preverjena pristnost"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Dotaknite se tipala prstnih odtisov"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona prstnih odtisov"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Preverjanje vašega obraza …"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Obvestila"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Svetilka"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Prenos podatkov v mobilnem omrežju"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Poraba podatkov"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Preostala količina podatkov"</string>
diff --git a/packages/SystemUI/res/values-sq/strings.xml b/packages/SystemUI/res/values-sq/strings.xml
index c948328..344aae3 100644
--- a/packages/SystemUI/res/values-sq/strings.xml
+++ b/packages/SystemUI/res/values-sq/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Konfiguro metodat e hyrjes"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Tastierë fizike"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Të lejohet <xliff:g id="APPLICATION">%1$s</xliff:g> të ketë qasje te <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Të lejohet <xliff:g id="APPLICATION">%1$s</xliff:g> të ketë qasje te <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Të hapet <xliff:g id="APPLICATION">%1$s</xliff:g> për të përdorur <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Të hapet <xliff:g id="APPLICATION">%1$s</xliff:g> për të përdorur <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -56,7 +58,7 @@
     <string name="always_use_device" msgid="4015357883336738417">"Hap gjithmonë <xliff:g id="APPLICATION">%1$s</xliff:g> kur lidhet <xliff:g id="USB_DEVICE">%2$s</xliff:g>"</string>
     <string name="always_use_accessory" msgid="3257892669444535154">"Hap gjithmonë <xliff:g id="APPLICATION">%1$s</xliff:g> kur lidhet <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>"</string>
     <string name="usb_debugging_title" msgid="4513918393387141949">"Të lejohet korrigjimi i USB-së?"</string>
-    <string name="usb_debugging_message" msgid="2220143855912376496">"Shenja e gishtit të tastit \"RSA\" së kompjuterit është:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
+    <string name="usb_debugging_message" msgid="2220143855912376496">"Gjurma e gishtit të tastit \"RSA\" së kompjuterit është:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
     <string name="usb_debugging_always" msgid="303335496705863070">"Lejo gjithmonë nga ky kompjuter"</string>
     <string name="usb_debugging_allow" msgid="2272145052073254852">"Lejo"</string>
     <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"Korrigjimi i USB-së nuk lejohet"</string>
@@ -96,7 +98,7 @@
     <string name="usb_preference_title" msgid="6551050377388882787">"Opsionet e transferimit të dosjeve të USB-së"</string>
     <string name="use_mtp_button_title" msgid="4333504413563023626">"Lidh si një lexues \"media\" (MTP)"</string>
     <string name="use_ptp_button_title" msgid="7517127540301625751">"Montoje si kamerë (PTP)"</string>
-    <string name="installer_cd_button_title" msgid="2312667578562201583">"Instalo apl. \"Transferimi i skedarëve\" për \"Mac\""</string>
+    <string name="installer_cd_button_title" msgid="2312667578562201583">"Instalo \"Transferimi i skedarëve të Android\" për Mac"</string>
     <string name="accessibility_back" msgid="567011538994429120">"Prapa"</string>
     <string name="accessibility_home" msgid="8217216074895377641">"Faqja bazë"</string>
     <string name="accessibility_menu" msgid="316839303324695949">"Menyja"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Anulo"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Konfirmo"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Provo përsëri"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Rajon bosh, trokit për të anuluar vërtetimin"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Trokit për të anuluar vërtetimin"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Provo përsëri"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Po kërkon për fytyrën tënde"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Fytyra u vërtetua"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Konfirmuar"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Trokit \"Konfirmo\" për ta përfunduar"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"U vërtetua"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Prek sensorin e gjurmës së gishtit"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikona e gjurmës së gishtit"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Po të kërkojmë…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Njoftimet"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Elektriku"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Të dhënat celulare"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Përdorimi i të dhënave"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Të dhënat e mbetura"</string>
diff --git a/packages/SystemUI/res/values-sr/strings.xml b/packages/SystemUI/res/values-sr/strings.xml
index 4d289dc..b36b9dc 100644
--- a/packages/SystemUI/res/values-sr/strings.xml
+++ b/packages/SystemUI/res/values-sr/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Подеси методе уноса"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Физичка тастатура"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Желите ли да дозволите да <xliff:g id="APPLICATION">%1$s</xliff:g> приступа уређају <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Желите ли да дозволите да <xliff:g id="APPLICATION">%1$s</xliff:g> приступа уређају <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Желите ли да отворите апликацију <xliff:g id="APPLICATION">%1$s</xliff:g> да бисте користили уређај <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Желите ли да отворите апликацију <xliff:g id="APPLICATION">%1$s</xliff:g> да бисте користили уређај <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Откажи"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Потврди"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Пробај поново"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Празна област, додирните да бисте отказали потврду идентитета"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Додирните да бисте отказали потврду идентитета"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Пробајте поново"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Тражи се ваше лице"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Лице је потврђено"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Потврђено"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Додирните Потврди да бисте завршили"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Идентитет је потврђен"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Додирните сензор за отисак прста"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Икона отиска прста"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Тражимо вас…"</string>
@@ -365,6 +382,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Обавештења"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Лампа"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобилни подаци"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Потрошња података"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Преостала количина података"</string>
diff --git a/packages/SystemUI/res/values-sv/strings.xml b/packages/SystemUI/res/values-sv/strings.xml
index b891b93..24e0b1e 100644
--- a/packages/SystemUI/res/values-sv/strings.xml
+++ b/packages/SystemUI/res/values-sv/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Konfigurera inmatningsmetoder"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fysiskt tangentbord"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Vill du ge <xliff:g id="APPLICATION">%1$s</xliff:g> åtkomst till <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Vill du ge <xliff:g id="APPLICATION">%1$s</xliff:g> åtkomst till <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Vill du öppna <xliff:g id="APPLICATION">%1$s</xliff:g> och hantera <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Vill du öppna <xliff:g id="APPLICATION">%1$s</xliff:g> och hantera <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Avbryt"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Bekräfta"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Försök igen"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Området är tomt. Tryck för att avbryta autentiseringen"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tryck för att avbryta autentiseringen"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Försök igen"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Söker efter ditt ansikte"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Ansiktet har autentiserats"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Bekräftat"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Slutför genom att trycka på Bekräfta"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Autentiserad"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Tryck på fingeravtryckssensorn"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Ikon för fingeravtryck"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Håller utkik efter dig …"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Aviseringar"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Ficklampa"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobildata"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Dataanvändning"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Återstående data"</string>
diff --git a/packages/SystemUI/res/values-sw/strings.xml b/packages/SystemUI/res/values-sw/strings.xml
index b37405a..93f5b7d 100644
--- a/packages/SystemUI/res/values-sw/strings.xml
+++ b/packages/SystemUI/res/values-sw/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Weka mbinu za ingizo"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Kibodi halisi"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Ungependa kuruhusu <xliff:g id="APPLICATION">%1$s</xliff:g> ifikie <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Ungependa kuruhusu <xliff:g id="APPLICATION">%1$s</xliff:g> ifikie <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Ungependa kufungua <xliff:g id="APPLICATION">%1$s</xliff:g> ili itumie <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Ungependa kufungua <xliff:g id="APPLICATION">%1$s</xliff:g> ili itumie <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Ghairi"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Thibitisha"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Jaribu tena"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Eneo lisilo na chochote, gusa ili ughairi uthibitishaji"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Gusa ili ughairi uthibitishaji"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Tafadhali jaribu tena"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Inatafuta uso wako"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Uso umethibitishwa"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Imethibitishwa"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Gusa Thibitisha ili ukamilishe"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Umethibitishwa"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Gusa kitambua alama ya kidole"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Aikoni ya alama ya kidole"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Inakutafuta…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Arifa"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Tochi"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Data ya simu"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Matumizi ya data"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Data iliyosalia"</string>
diff --git a/packages/SystemUI/res/values-ta/strings.xml b/packages/SystemUI/res/values-ta/strings.xml
index 2b12149..a5aa91d 100644
--- a/packages/SystemUI/res/values-ta/strings.xml
+++ b/packages/SystemUI/res/values-ta/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"உள்ளீட்டு முறைகளை அமை"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"கைமுறை விசைப்பலகை"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ஐ அணுக, <xliff:g id="APPLICATION">%1$s</xliff:g> ஆப்ஸை அனுமதிக்கவா?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ஐ அணுக, <xliff:g id="APPLICATION">%1$s</xliff:g> ஆப்ஸை அனுமதிக்கவா?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ஐக் கையாள, <xliff:g id="APPLICATION">%1$s</xliff:g> பயன்பாட்டைத் திறக்கவா?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ஐக் கையாள, <xliff:g id="APPLICATION">%1$s</xliff:g> பயன்பாட்டைத் திறக்கவா?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"ரத்துசெய்"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"உறுதிப்படுத்துக"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"மீண்டும் முயல்க"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"காலியான பகுதி, அங்கீகாரத்தை ரத்துசெய்யத் தட்டவும்"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"பயோமெட்ரிக் அடையாளத்தை ரத்துசெய்ய தட்டவும்"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"மீண்டும் முயலவும்"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"உங்கள் முகத்தை அங்கீகரிக்கிறது"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"முகம் அங்கீகரிக்கப்பட்டது"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"உறுதிப்படுத்தப்பட்டது"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"முடிக்க \'உறுதிப்படுத்து\' என்பதை தட்டவும்"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"அங்கீகரிக்கப்பட்டது"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"கைரேகை சென்சாரைத் தொடவும்"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"கைரேகை ஐகான்"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"உங்கள் முகத்தைத் தேடுகிறது…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"அறிவிப்புகள்"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"டார்ச் லைட்"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"மொபைல் டேட்டா"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"டேட்டா உபயோகம்"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"மீதமுள்ள தரவு"</string>
@@ -497,29 +516,29 @@
     <string name="monitoring_description_managed_profile_ca_certificate" msgid="4683248196789897964">"உங்கள் நிறுவனம், பணிக் கணக்கில் சான்றிதழ் அங்கீகாரத்தை நிறுவியுள்ளது. உங்களின் பாதுகாப்பான நெட்வொர்க் ட்ராஃபிக் கண்காணிக்கப்படலாம் அல்லது மாற்றப்படலாம்."</string>
     <string name="monitoring_description_ca_certificate" msgid="7886985418413598352">"இந்தச் சாதனத்தில் சான்றிதழ் அங்கீகாரம் நிறுவப்பட்டுள்ளது. உங்களின் பாதுகாப்பான நெட்வொர்க் ட்ராஃபிக் கண்காணிக்கப்படலாம் அல்லது மாற்றப்படலாம்."</string>
     <string name="monitoring_description_management_network_logging" msgid="7184005419733060736">"உங்கள் நிர்வாகி, நெட்வொர்க் பதிவெடுத்தலை இயக்கியுள்ளார். இது சாதனத்தில் ட்ராஃபிக்கைக் கண்காணிக்கும்."</string>
-    <string name="monitoring_description_named_vpn" msgid="7403457334088909254">"மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள்."</string>
-    <string name="monitoring_description_two_named_vpns" msgid="4198511413729213802">"மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP_0">%1$s</xliff:g> மற்றும் <xliff:g id="VPN_APP_1">%2$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள்."</string>
-    <string name="monitoring_description_managed_profile_named_vpn" msgid="1427905889862420559">"மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP">%1$s</xliff:g> உடன் உங்கள் பணிக் கணக்கு இணைக்கப்பட்டுள்ளது."</string>
-    <string name="monitoring_description_personal_profile_named_vpn" msgid="3133980926929069283">"மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP">%1$s</xliff:g> உடன் உங்களின் தனிப்பட்ட சுயவிவரம் இணைக்கப்பட்டுள்ளது."</string>
+    <string name="monitoring_description_named_vpn" msgid="7403457334088909254">"மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள்."</string>
+    <string name="monitoring_description_two_named_vpns" msgid="4198511413729213802">"மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP_0">%1$s</xliff:g> மற்றும் <xliff:g id="VPN_APP_1">%2$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள்."</string>
+    <string name="monitoring_description_managed_profile_named_vpn" msgid="1427905889862420559">"மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP">%1$s</xliff:g> உடன் உங்கள் பணிக் கணக்கு இணைக்கப்பட்டுள்ளது."</string>
+    <string name="monitoring_description_personal_profile_named_vpn" msgid="3133980926929069283">"மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="VPN_APP">%1$s</xliff:g> உடன் உங்களின் தனிப்பட்ட சுயவிவரம் இணைக்கப்பட்டுள்ளது."</string>
     <string name="monitoring_description_do_header_generic" msgid="96588491028288691">"உங்கள் சாதனத்தை நிர்வகிப்பது: <xliff:g id="DEVICE_OWNER_APP">%1$s</xliff:g>."</string>
     <string name="monitoring_description_do_header_with_name" msgid="5511133708978206460">"உங்கள் சாதனத்தை நிர்வகிக்க, <xliff:g id="DEVICE_OWNER_APP">%2$s</xliff:g> ஆப்ஸை <xliff:g id="ORGANIZATION_NAME">%1$s</xliff:g> பயன்படுத்தும்."</string>
     <string name="monitoring_description_do_body" msgid="3639594537660975895">"உங்கள் நிர்வாகியால் அமைப்புகள், நிறுவன அணுகல், ஆப்ஸ், சாதனத்துடன் தொடர்புடைய டேட்டா, சாதன இருப்பிடத் தகவல் ஆகியவற்றைக் கண்காணிக்கவும் நிர்வகிக்கவும் முடியும்."</string>
     <string name="monitoring_description_do_learn_more_separator" msgid="3785251953067436862">" "</string>
     <string name="monitoring_description_do_learn_more" msgid="1849514470437907421">"மேலும் அறிக"</string>
-    <string name="monitoring_description_do_body_vpn" msgid="8255218762488901796">"<xliff:g id="VPN_APP">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள். இந்தப் பயன்பாட்டால் மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்."</string>
+    <string name="monitoring_description_do_body_vpn" msgid="8255218762488901796">"<xliff:g id="VPN_APP">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள். இந்த ஆப்ஸால் மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்."</string>
     <string name="monitoring_description_vpn_settings_separator" msgid="1933186756733474388">" "</string>
     <string name="monitoring_description_vpn_settings" msgid="6434859242636063861">"VPN அமைப்புகளைத் திற"</string>
     <string name="monitoring_description_ca_cert_settings_separator" msgid="4987350385906393626">" "</string>
     <string name="monitoring_description_ca_cert_settings" msgid="5489969458872997092">"நம்பகமான அனுமதிச் சான்றுகளைத் திற"</string>
     <string name="monitoring_description_network_logging" msgid="7223505523384076027">"உங்கள் நிர்வாகி நெட்வொர்க் பதிவெடுத்தலை இயக்கியுள்ளார், இது சாதனத்தில் ட்ராஃபிக்கைக் கண்காணிக்கும்.\n\nமேலும் தகவலுக்கு, உங்கள் நிர்வாகியைத் தொடர்புகொள்ளவும்."</string>
-    <string name="monitoring_description_vpn" msgid="4445150119515393526">"VPN இணைப்பை அமைக்க, பயன்பாட்டிற்கு அனுமதி வழங்கியுள்ளீர்கள்.\n\nஇந்தப் பயன்பாட்டால் மின்னஞ்சல்கள், பயன்பாடுகள் மற்றும் இணையதளங்கள் உட்பட, உங்கள் சாதனத்தையும் நெட்வொர்க் செயல்பாட்டையும் கண்காணிக்க முடியும்."</string>
-    <string name="monitoring_description_vpn_profile_owned" msgid="2958019119161161530">"உங்கள் பணிக் கணக்கை <xliff:g id="ORGANIZATION">%1$s</xliff:g> நிர்வகிக்கிறது.\n\nஉங்கள் நிர்வாகியால் பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்.\n\nமேலும் தகவலுக்கு, உங்கள் நிர்வாகியைத் தொடர்புகொள்ளவும்.\n\nஉங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய VPN உடனும் இணைக்கப்பட்டுள்ளீர்கள்."</string>
+    <string name="monitoring_description_vpn" msgid="4445150119515393526">"VPN இணைப்பை அமைக்க, பயன்பாட்டிற்கு அனுமதி வழங்கியுள்ளீர்கள்.\n\nஇந்த ஆப்ஸால் மின்னஞ்சல்கள், ஆப்ஸ் மற்றும் இணையதளங்கள் உட்பட, உங்கள் சாதனத்தையும் நெட்வொர்க் செயல்பாட்டையும் கண்காணிக்க முடியும்."</string>
+    <string name="monitoring_description_vpn_profile_owned" msgid="2958019119161161530">"உங்கள் பணிக் கணக்கை <xliff:g id="ORGANIZATION">%1$s</xliff:g> நிர்வகிக்கிறது.\n\nஉங்கள் நிர்வாகியால் ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்.\n\nமேலும் தகவலுக்கு, உங்கள் நிர்வாகியைத் தொடர்புகொள்ளவும்.\n\nஉங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய VPN உடனும் இணைக்கப்பட்டுள்ளீர்கள்."</string>
     <string name="legacy_vpn_name" msgid="6604123105765737830">"VPN"</string>
-    <string name="monitoring_description_app" msgid="1828472472674709532">"மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள்."</string>
-    <string name="monitoring_description_app_personal" msgid="484599052118316268">"<xliff:g id="APPLICATION">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள். இந்தப் பயன்பாட்டால், மின்னஞ்சல்கள், பயன்பாடுகள் மற்றும் இணையதளங்கள் உட்பட உங்கள் தனிப்பட்ட நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்."</string>
-    <string name="branded_monitoring_description_app_personal" msgid="2669518213949202599">"<xliff:g id="APPLICATION">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள். இந்தப் பயன்பாட்டால் மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் தனிப்பட்ட நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்."</string>
-    <string name="monitoring_description_app_work" msgid="4612997849787922906">"உங்கள் பணிக் கணக்கை <xliff:g id="ORGANIZATION">%1$s</xliff:g> நிர்வகிக்கிறது. மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் பணி நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION">%2$s</xliff:g> உடன் அது இணைக்கப்பட்டுள்ளது.\n\nமேலும் தகவலுக்கு, நிர்வாகியைத் தொடர்புகொள்ளவும்."</string>
-    <string name="monitoring_description_app_personal_work" msgid="5664165460056859391">"உங்கள் பணிக் கணக்கை <xliff:g id="ORGANIZATION">%1$s</xliff:g> நிர்வகிக்கிறது. மின்னஞ்சல்கள், பயன்பாடுகள், இணையதளங்கள் உட்பட உங்கள் பணி நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> உடன் அது இணைக்கப்பட்டுள்ளது.\n\nஉங்கள் தனிப்பட்ட நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> உடனும் இணைக்கப்பட்டுள்ளீர்கள்."</string>
+    <string name="monitoring_description_app" msgid="1828472472674709532">"மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள்."</string>
+    <string name="monitoring_description_app_personal" msgid="484599052118316268">"<xliff:g id="APPLICATION">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள். இந்த ஆப்ஸால், மின்னஞ்சல்கள், ஆப்ஸ் மற்றும் இணையதளங்கள் உட்பட உங்கள் தனிப்பட்ட நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்."</string>
+    <string name="branded_monitoring_description_app_personal" msgid="2669518213949202599">"<xliff:g id="APPLICATION">%1$s</xliff:g> உடன் இணைக்கப்பட்டுள்ளீர்கள். இந்த ஆப்ஸால் மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் தனிப்பட்ட நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்க முடியும்."</string>
+    <string name="monitoring_description_app_work" msgid="4612997849787922906">"உங்கள் பணிக் கணக்கை <xliff:g id="ORGANIZATION">%1$s</xliff:g> நிர்வகிக்கிறது. மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் பணி நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION">%2$s</xliff:g> உடன் அது இணைக்கப்பட்டுள்ளது.\n\nமேலும் தகவலுக்கு, நிர்வாகியைத் தொடர்புகொள்ளவும்."</string>
+    <string name="monitoring_description_app_personal_work" msgid="5664165460056859391">"உங்கள் பணிக் கணக்கை <xliff:g id="ORGANIZATION">%1$s</xliff:g> நிர்வகிக்கிறது. மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் பணி நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> உடன் அது இணைக்கப்பட்டுள்ளது.\n\nஉங்கள் தனிப்பட்ட நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> உடனும் இணைக்கப்பட்டுள்ளீர்கள்."</string>
     <string name="keyguard_indication_trust_unlocked" msgid="2712865815371519117">"TrustAgent இதைத் திறந்தே வைத்துள்ளது"</string>
     <string name="keyguard_indication_trust_disabled" msgid="7412534203633528135">"நீங்கள் கைமுறையாகத் திறக்கும் வரை, சாதனம் பூட்டப்பட்டிருக்கும்"</string>
     <string name="hidden_notifications_title" msgid="7139628534207443290">"விரைவாக அறிவிப்புகளைப் பெறுதல்"</string>
@@ -845,7 +864,7 @@
     <string name="pip_skip_to_prev" msgid="1955311326688637914">"முந்தையதற்குச் செல்"</string>
     <string name="thermal_shutdown_title" msgid="4458304833443861111">"வெப்பத்தினால் ஃபோன் ஆஃப் செய்யப்பட்டது"</string>
     <string name="thermal_shutdown_message" msgid="9006456746902370523">"இப்போது உங்கள் ஃபோன் இயல்புநிலையில் இயங்குகிறது"</string>
-    <string name="thermal_shutdown_dialog_message" msgid="566347880005304139">"உங்கள் ஃபோன் அதிகமாகச் சூடானதால், அதன் சூட்டைக் குறைக்க, ஆஃப் செய்யப்பட்டது. இப்போது உங்கள் ஃபோன் இயல்புநிலையில் இயங்குகிறது.\n\nபின்வருவனவற்றைச் செய்தால், ஃபோன் சூடாகலாம்:\n	• அதிகளவு தரவைப் பயன்படுத்தும் ஆப்ஸை (எ.கா: கேமிங், வீடியோ (அ) வழிகாட்டுதல் பயன்பாடுகள்) பயன்படுத்துவது\n	• பெரிய கோப்புகளைப் பதிவிறக்குவது/பதிவேற்றுவது\n	• அதிக வெப்பநிலையில் ஃபோனைப் பயன்படுத்துவது"</string>
+    <string name="thermal_shutdown_dialog_message" msgid="566347880005304139">"உங்கள் ஃபோன் அதிகமாகச் சூடானதால், அதன் சூட்டைக் குறைக்க, ஆஃப் செய்யப்பட்டது. இப்போது உங்கள் ஃபோன் இயல்புநிலையில் இயங்குகிறது.\n\nபின்வருவனவற்றைச் செய்தால், ஃபோன் சூடாகலாம்:\n	• அதிகளவு தரவைப் பயன்படுத்தும் ஆப்ஸை (எ.கா: கேமிங், வீடியோ (அ) வழிகாட்டுதல் ஆப்ஸ்) பயன்படுத்துவது\n	• பெரிய கோப்புகளைப் பதிவிறக்குவது/பதிவேற்றுவது\n	• அதிக வெப்பநிலையில் ஃபோனைப் பயன்படுத்துவது"</string>
     <string name="high_temp_title" msgid="4589508026407318374">"மொபைல் சூடாகிறது"</string>
     <string name="high_temp_notif_message" msgid="5642466103153429279">"மொபைலின் வெப்ப அளவு குறையும் போது, சில அம்சங்களைப் பயன்படுத்த முடியாது"</string>
     <string name="high_temp_dialog_message" msgid="6840700639374113553">"உங்கள் மொபைலின் வெப்ப அளவு தானாகவே குறையும். தொடர்ந்து நீங்கள் மொபைலைப் பயன்படுத்தலாம், ஆனால் அதன் வேகம் குறைவாக இருக்கக்கூடும்.\n\nமொபைலின் வெப்ப அளவு குறைந்தவுடன், அது இயல்பு நிலையில் இயங்கும்."</string>
@@ -890,7 +909,7 @@
     <string name="qs_dnd_until" msgid="3469471136280079874">"<xliff:g id="ID_1">%s</xliff:g> வரை"</string>
     <string name="qs_dnd_keep" msgid="1825009164681928736">"வைத்திரு"</string>
     <string name="qs_dnd_replace" msgid="8019520786644276623">"மாற்று"</string>
-    <string name="running_foreground_services_title" msgid="381024150898615683">"பின்னணியில் இயங்கும் பயன்பாடுகள்"</string>
+    <string name="running_foreground_services_title" msgid="381024150898615683">"பின்னணியில் இயங்கும் ஆப்ஸ்"</string>
     <string name="running_foreground_services_msg" msgid="6326247670075574355">"பேட்டரி மற்றும் டேட்டா உபயோக விவரங்களைக் காண, தட்டவும்"</string>
     <string name="mobile_data_disable_title" msgid="1068272097382942231">"மொபைல் டேட்டாவை ஆஃப் செய்யவா?"</string>
     <string name="mobile_data_disable_message" msgid="4756541658791493506">"<xliff:g id="CARRIER">%s</xliff:g> மூலம் டேட்டா அல்லது இணையத்தை உங்களால் பயன்படுத்த முடியாது. வைஃபை வழியாக மட்டுமே இணையத்தைப் பயன்படுத்த முடியும்."</string>
diff --git a/packages/SystemUI/res/values-te/strings.xml b/packages/SystemUI/res/values-te/strings.xml
index 350ccc6..c6b2bb7 100644
--- a/packages/SystemUI/res/values-te/strings.xml
+++ b/packages/SystemUI/res/values-te/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ఇన్‌పుట్ పద్ధతులను సెటప్ చేయండి"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"భౌతిక కీబోర్డ్"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ని యాక్సెస్ చేయడానికి <xliff:g id="APPLICATION">%1$s</xliff:g>ని అనుమతించాలా?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ని యాక్సెస్ చేయడానికి <xliff:g id="APPLICATION">%1$s</xliff:g>ని అనుమతించాలా?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g>ని నిర్వహించడానికి <xliff:g id="APPLICATION">%1$s</xliff:g>ని తెరవాలా?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>ని నిర్వహించడానికి <xliff:g id="APPLICATION">%1$s</xliff:g>ని తెరవాలా?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"రద్దు చేయి"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"నిర్ధారించు"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"మళ్లీ ప్రయత్నించు"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"ఖాళీ ప్రదేశం, ప్రామాణీకరణను రద్దు చేయడానికి నొక్కండి"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"ప్రామాణీకరణను రద్దు చేయడానికి నొక్కండి"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"దయచేసి మళ్ళీ ప్రయత్నించండి"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"మీ ముఖాన్ని క్యాప్చర్ చేస్తోంది"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ముఖం ప్రామాణీకరించబడింది"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"నిర్ధారించబడింది"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"పూర్తి చేయడానికి \"నిర్ధారించు\" నొక్కండి"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ప్రామాణీకరించబడింది"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"వేలిముద్ర సెన్సార్‌ను తాకండి"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"వేలిముద్ర చిహ్నం"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"మీ కోసం చూస్తోంది…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"నోటిఫికేషన్‌లు"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ఫ్లాష్‌లైట్"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"మొబైల్ డేటా"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"డేటా వినియోగం"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"మిగిలిన డేటా"</string>
diff --git a/packages/SystemUI/res/values-th/strings.xml b/packages/SystemUI/res/values-th/strings.xml
index 9d39859..2907524 100644
--- a/packages/SystemUI/res/values-th/strings.xml
+++ b/packages/SystemUI/res/values-th/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ตั้งค่าวิธีการป้อนข้อมูล"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"แป้นพิมพ์บนเครื่อง"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"อนุญาตให้ <xliff:g id="APPLICATION">%1$s</xliff:g> เข้าถึง <xliff:g id="USB_DEVICE">%2$s</xliff:g> ไหม"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"อนุญาตให้ <xliff:g id="APPLICATION">%1$s</xliff:g> เข้าถึง <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ไหม"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"เปิด <xliff:g id="APPLICATION">%1$s</xliff:g> เพื่อจัดการ <xliff:g id="USB_DEVICE">%2$s</xliff:g> ไหม"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"เปิด <xliff:g id="APPLICATION">%1$s</xliff:g> เพื่อจัดการ <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ไหม"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"ยกเลิก"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"ยืนยัน"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"ลองอีกครั้ง"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"พื้นที่ว่าง แตะเพื่อยกเลิกการตรวจสอบสิทธิ์"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"แตะเพื่อยกเลิกการตรวจสอบสิทธิ์"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"โปรดลองอีกครั้ง"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"กำลังมองหาใบหน้าของคุณ"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"ตรวจสอบสิทธิ์ใบหน้าแล้ว"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"ยืนยันแล้ว"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"แตะยืนยันเพื่อดำเนินการให้เสร็จสมบูรณ์"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"ตรวจสอบสิทธิ์แล้ว"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"แตะเซ็นเซอร์ลายนิ้วมือ"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"ไอคอนลายนิ้วมือ"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"กำลังหาใบหน้าคุณ…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"การแจ้งเตือน"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"ไฟฉาย"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"เน็ตมือถือ"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"การใช้อินเทอร์เน็ต"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"ข้อมูลที่เหลืออยู่"</string>
diff --git a/packages/SystemUI/res/values-tl/strings.xml b/packages/SystemUI/res/values-tl/strings.xml
index 56da232..ce8c88b 100644
--- a/packages/SystemUI/res/values-tl/strings.xml
+++ b/packages/SystemUI/res/values-tl/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"I-set up paraan ng pag-input"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Aktwal na keyboard"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Payagan ang <xliff:g id="APPLICATION">%1$s</xliff:g> na ma-access ang <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Payagan ang <xliff:g id="APPLICATION">%1$s</xliff:g> na ma-access ang <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Buksan ang <xliff:g id="APPLICATION">%1$s</xliff:g> upang pamahalaan ang <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Buksan ang <xliff:g id="APPLICATION">%1$s</xliff:g> upang pamahalaan ang <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Kanselahin"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Kumpirmahin"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Subukang muli"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Walang laman na rehiyon, mag-tap para kanselahin ang pag-authenticate"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"I-tap para kanselahin ang pag-authenticate"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Pakisubukan ulit"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Hinahanap ang iyong mukha"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Na-authenticate ang mukha"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Nakumpirma"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"I-tap ang Kumpirmahin para kumpletuhin"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Na-authenticate"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Pindutin ang fingerprint sensor"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Icon ng fingerprint"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Hinahanap ka…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Mga Notification"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Flashlight"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobile data"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Paggamit ng data"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Natitirang data"</string>
diff --git a/packages/SystemUI/res/values-tr/strings.xml b/packages/SystemUI/res/values-tr/strings.xml
index 257b9de..7976014 100644
--- a/packages/SystemUI/res/values-tr/strings.xml
+++ b/packages/SystemUI/res/values-tr/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Giriş yöntemlerini ayarla"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Fiziksel klavye"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> uygulamasının <xliff:g id="USB_DEVICE">%2$s</xliff:g> cihazına erişmesine izin verilsin mi?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> uygulamasının <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> aksesuarına erişmesine izin verilsin mi?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> cihazını işlemek için <xliff:g id="APPLICATION">%1$s</xliff:g> uygulaması açılsın mı?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> aksesuarını işlemek için <xliff:g id="APPLICATION">%1$s</xliff:g> uygulaması açılsın mı?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"İptal"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Onaylayın"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Tekrar dene"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Boş alan, yetkilendirmeyi iptal etmek için dokunun"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Kimlik doğrulama işlemini iptal etmek için dokunun"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Lütfen tekrar deneyin"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Yüzünüz aranıyor"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Yüz kimliği doğrulandı"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Onaylandı"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tamamlamak için Onayla\'ya dokunun"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Kimliği Doğrulandı"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Parmak izi sensörüne dokunun"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Parmak izi simgesi"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Yüzünüz tanınmaya çalışılıyor…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Bildirimler"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Fener"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobil veri"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Veri kullanımı"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Kalan veri"</string>
diff --git a/packages/SystemUI/res/values-uk/strings.xml b/packages/SystemUI/res/values-uk/strings.xml
index d82acf7..ea2f376 100644
--- a/packages/SystemUI/res/values-uk/strings.xml
+++ b/packages/SystemUI/res/values-uk/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Налаштувати методи введення"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Фізична клавіатура"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Надати додатку <xliff:g id="APPLICATION">%1$s</xliff:g> доступ до такого аксесуара: <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Надати додатку <xliff:g id="APPLICATION">%1$s</xliff:g> доступ до такого аксесуара: <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Відкрити додаток <xliff:g id="APPLICATION">%1$s</xliff:g>, щоб використовувати такий аксесуар: <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Відкрити додаток <xliff:g id="APPLICATION">%1$s</xliff:g>, щоб використовувати такий аксесуар: <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Скасувати"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Підтвердити"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Повторити спробу"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Порожнє місце, торкніться, щоб скасувати автентифікацію"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Натисніть, щоб скасувати автентифікацію"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Повторіть спробу"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Триває розпізнавання обличчя"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Обличчя автентифіковано"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Підтверджено"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Щоб завершити, натисніть \"Підтвердити\""</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Автентифіковано"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Торкніться сканера відбитків пальців"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Значок відбитка пальця"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Пошук обличчя…"</string>
@@ -367,6 +384,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Сповіщення"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Ліхтарик"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Мобільне передавання даних"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Використання даних"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Залишилося даних"</string>
diff --git a/packages/SystemUI/res/values-ur/strings.xml b/packages/SystemUI/res/values-ur/strings.xml
index 7d4f177..1c28431 100644
--- a/packages/SystemUI/res/values-ur/strings.xml
+++ b/packages/SystemUI/res/values-ur/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"ان پٹ کے طریقوں کو ترتیب دیں"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"طبعی کی بورڈ"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> کو <xliff:g id="USB_DEVICE">%2$s</xliff:g> تک رسائی حاصل کرنے کی اجازت دیں؟"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> کو <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> تک رسائی حاصل کرنے کی اجازت دیں؟"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> ہینڈل کرنے کیلئے <xliff:g id="APPLICATION">%1$s</xliff:g> کھولیں؟"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> ہینڈل کرنے کیلئے <xliff:g id="APPLICATION">%1$s</xliff:g> کھولیں؟"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"منسوخ کریں"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"تصدیق کریں"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"دوبارہ کوشش کریں"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"خالی جگہیں، تصدیق کو منسوخ کرنے کے لیے تھپتھپائیں"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"تصدیق کو منسوخ کرنے کے لیے تھپتھپائیں"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"براہ کرم دوبارہ کوشش کریں"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"آپ کا چہرہ تلاش کیا جا رہا ہے"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"چہرے کی تصدیق ہو گئی"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"تصدیق شدہ"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"مکمل کرنے کیلئے \'تصدیق کریں\' تھپتھپائیں"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"تصدیق کردہ"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"فنگر پرنٹ سینسر پر ٹچ کریں"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"فنگر پرنٹ آئیکن"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"آپ کے لیے تلاش کیا جا رہا ہے…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"اطلاعات"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"فلیش لائٹ"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"موبائل ڈیٹا"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"ڈیٹا کا استعمال"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"باقی ڈیٹا"</string>
diff --git a/packages/SystemUI/res/values-uz/strings.xml b/packages/SystemUI/res/values-uz/strings.xml
index eaca944..c3e39e5 100644
--- a/packages/SystemUI/res/values-uz/strings.xml
+++ b/packages/SystemUI/res/values-uz/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Kiritish usullarini moslash"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Tashqi tugmatag"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"<xliff:g id="APPLICATION">%1$s</xliff:g> ilovasiga <xliff:g id="USB_DEVICE">%2$s</xliff:g> qurilmasidan foydalanishga ruxsat berilsinmi?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"<xliff:g id="APPLICATION">%1$s</xliff:g> ilovasiga <xliff:g id="USB_ACCESSORY">%2$s</xliff:g> qurilmasidan foydalanishga ruxsat berilsinmi?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"<xliff:g id="USB_DEVICE">%2$s</xliff:g> bilan ishlash uchun <xliff:g id="APPLICATION">%1$s</xliff:g> ochilsinmi?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"<xliff:g id="USB_ACCESSORY">%2$s</xliff:g> bilan ishlash uchun <xliff:g id="APPLICATION">%1$s</xliff:g> ochilsinmi?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Bekor qilish"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"OK"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Qayta urinish"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Boʻsh hudud, tekshiruvni bekor qilish uchun bosing"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Tekshiruvni bekor qilish uchun bosing"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Qayta urining"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Yuz tekshirilmoqda"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Yuzingiz aniqlandi"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Tasdiqlangan"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Tasdiqlash uchun tegining"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Tasdiqlandi"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Barmoq izi skaneriga tegining"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Barmoq izi belgisi"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Yuzingiz tekshirilmoqda…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Bildirishnomalar"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Fonar"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Mobil internet"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Trafik sarfi"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Qolgan trafik"</string>
@@ -401,7 +420,7 @@
     <string name="speed_bump_explanation" msgid="1288875699658819755">"Kam ahamiyatli bildirishnomalarni pastda ko‘rsatish"</string>
     <string name="notification_tap_again" msgid="7590196980943943842">"Ochish uchun yana bosing"</string>
     <string name="keyguard_unlock" msgid="6035822649218712063">"Ochish uchun tepaga suring"</string>
-    <string name="keyguard_retry" msgid="5221600879614948709">"Tepaga suring va qayta urining"</string>
+    <string name="keyguard_retry" msgid="5221600879614948709">"Qayta urinish uchun tepaga suring"</string>
     <string name="do_disclosure_generic" msgid="5615898451805157556">"Bu – tashkilotingiz tomonidan boshqariladigan qurilma"</string>
     <string name="do_disclosure_with_name" msgid="5640615509915445501">"Bu – <xliff:g id="ORGANIZATION_NAME">%s</xliff:g> tomonidan boshqariladigan qurilma"</string>
     <string name="phone_hint" msgid="4872890986869209950">"Telefonni ochish uchun suring"</string>
diff --git a/packages/SystemUI/res/values-vi/strings.xml b/packages/SystemUI/res/values-vi/strings.xml
index d3caa2b..d2da39b 100644
--- a/packages/SystemUI/res/values-vi/strings.xml
+++ b/packages/SystemUI/res/values-vi/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Thiết lập phương thức nhập"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Bàn phím vật lý"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Cho phép <xliff:g id="APPLICATION">%1$s</xliff:g> truy cập <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Cho phép <xliff:g id="APPLICATION">%1$s</xliff:g> truy cập <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Mở <xliff:g id="APPLICATION">%1$s</xliff:g> để điều khiển <xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Mở <xliff:g id="APPLICATION">%1$s</xliff:g> để điều khiển <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -56,7 +58,7 @@
     <string name="always_use_device" msgid="4015357883336738417">"Luôn mở <xliff:g id="APPLICATION">%1$s</xliff:g> khi kết nối <xliff:g id="USB_DEVICE">%2$s</xliff:g>"</string>
     <string name="always_use_accessory" msgid="3257892669444535154">"Luôn mở <xliff:g id="APPLICATION">%1$s</xliff:g> khi kết nối <xliff:g id="USB_ACCESSORY">%2$s</xliff:g>"</string>
     <string name="usb_debugging_title" msgid="4513918393387141949">"Cho phép gỡ lỗi qua USB?"</string>
-    <string name="usb_debugging_message" msgid="2220143855912376496">"Tệp tham chiếu khóa RSA của máy tính là:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
+    <string name="usb_debugging_message" msgid="2220143855912376496">"Vân tay khóa RSA của máy tính là:\n<xliff:g id="FINGERPRINT">%1$s</xliff:g>"</string>
     <string name="usb_debugging_always" msgid="303335496705863070">"Luôn cho phép từ máy tính này"</string>
     <string name="usb_debugging_allow" msgid="2272145052073254852">"Cho phép"</string>
     <string name="usb_debugging_secondary_user_title" msgid="6353808721761220421">"Không cho phép chế độ gỡ lỗi qua USB"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Hủy"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Xác nhận"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Thử lại"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Vùng trống, nhấn để hủy quá trình xác thực"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Nhấn để hủy quá trình xác thực"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Vui lòng thử lại"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Đang tìm khuôn mặt của bạn"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Đã xác thực khuôn mặt"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Ðã xác nhận"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Nhấn vào Xác nhận để hoàn tất"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Đã xác thực"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Chạm vào cảm biến vân tay"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Biểu tượng vân tay"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Đang tìm kiếm bạn…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Thông báo"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"Đèn pin"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Dữ liệu di động"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Sử dụng dữ liệu"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Dữ liệu còn lại"</string>
diff --git a/packages/SystemUI/res/values-zh-rCN/strings.xml b/packages/SystemUI/res/values-zh-rCN/strings.xml
index ca72b08..551e54e 100644
--- a/packages/SystemUI/res/values-zh-rCN/strings.xml
+++ b/packages/SystemUI/res/values-zh-rCN/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"设置输入法"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"物理键盘"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"要允许<xliff:g id="APPLICATION">%1$s</xliff:g>访问<xliff:g id="USB_DEVICE">%2$s</xliff:g>吗?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"要允许<xliff:g id="APPLICATION">%1$s</xliff:g>访问<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>吗?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"要打开<xliff:g id="APPLICATION">%1$s</xliff:g>来处理<xliff:g id="USB_DEVICE">%2$s</xliff:g>吗?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"要打开<xliff:g id="APPLICATION">%1$s</xliff:g>来处理<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>吗?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"取消"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"确认"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"重试"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"空白区域,点按即可取消身份验证"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"点按即可取消身份验证"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"请重试"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"正在查找您的面孔"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"面孔身份验证成功"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"已确认"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"点按“确认”即可完成"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"已经过身份验证"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"请触摸指纹传感器"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"指纹图标"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"正在查找您的面孔…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"通知"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"手电筒"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"移动数据"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"流量使用情况"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"剩余流量"</string>
@@ -376,7 +395,7 @@
     <string name="quick_settings_night_secondary_label_until_sunrise" msgid="4453017157391574402">"在日出时关闭"</string>
     <string name="quick_settings_night_secondary_label_on_at" msgid="6256314040368487637">"在<xliff:g id="TIME">%s</xliff:g> 开启"</string>
     <string name="quick_settings_secondary_label_until" msgid="2749196569462600150">"直到<xliff:g id="TIME">%s</xliff:g>"</string>
-    <string name="quick_settings_ui_mode_night_label" msgid="3419947801072692538">"深色主题背景"</string>
+    <string name="quick_settings_ui_mode_night_label" msgid="3419947801072692538">"深色主题"</string>
     <string name="quick_settings_ui_mode_night_label_battery_saver" msgid="7438725724589758362">"深色主题背景\n省电模式"</string>
     <string name="quick_settings_nfc_label" msgid="9012153754816969325">"NFC"</string>
     <string name="quick_settings_nfc_off" msgid="6883274004315134333">"NFC 已停用"</string>
diff --git a/packages/SystemUI/res/values-zh-rHK/strings.xml b/packages/SystemUI/res/values-zh-rHK/strings.xml
index 128e1ca..206fcfc 100644
--- a/packages/SystemUI/res/values-zh-rHK/strings.xml
+++ b/packages/SystemUI/res/values-zh-rHK/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"設定輸入法"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"實體鍵盤"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"要允許「<xliff:g id="APPLICATION">%1$s</xliff:g>」存取「<xliff:g id="USB_DEVICE">%2$s</xliff:g>」嗎?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"要允許「<xliff:g id="APPLICATION">%1$s</xliff:g>」存取「<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>」嗎?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"要開啟「<xliff:g id="APPLICATION">%1$s</xliff:g>」處理「<xliff:g id="USB_DEVICE">%2$s</xliff:g>」嗎?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"要開啟「<xliff:g id="APPLICATION">%1$s</xliff:g>」處理「<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>」嗎?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"取消"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"確認"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"請再試一次"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"空白區域,輕按即可取消驗證"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"輕按即可取消驗證"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"請再試一次"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"正在尋找您的臉孔"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"臉孔已經驗證"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"已確認"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"輕按 [確定] 以完成"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"驗證咗"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"請輕觸指紋感應器"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"指紋圖示"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"正在搜尋您的臉孔…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"通知"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"電筒"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"流動數據"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"數據用量"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"剩餘資料"</string>
diff --git a/packages/SystemUI/res/values-zh-rTW/strings.xml b/packages/SystemUI/res/values-zh-rTW/strings.xml
index 457206d..c1f299d 100644
--- a/packages/SystemUI/res/values-zh-rTW/strings.xml
+++ b/packages/SystemUI/res/values-zh-rTW/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"設定輸入法"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"實體鍵盤"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"要允許「<xliff:g id="APPLICATION">%1$s</xliff:g>」存取「<xliff:g id="USB_DEVICE">%2$s</xliff:g>」嗎?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"要允許「<xliff:g id="APPLICATION">%1$s</xliff:g>」存取「<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>」嗎?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"要開啟「<xliff:g id="APPLICATION">%1$s</xliff:g>」處理「<xliff:g id="USB_DEVICE">%2$s</xliff:g>」嗎?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"要開啟「<xliff:g id="APPLICATION">%1$s</xliff:g>」處理「<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>」嗎?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"取消"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"確認"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"再試一次"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"空白的區域,輕觸即可取消驗證"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"輕觸即可取消驗證"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"請再試一次"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"正在尋找你的臉孔"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"臉孔驗證成功"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"確認完畢"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"輕觸 [確認] 完成驗證設定"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"已通過驗證"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"請輕觸指紋感應器"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"指紋圖示"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"正在尋找你的臉孔…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"通知"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"手電筒"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"行動數據"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"數據用量"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"剩餘資料"</string>
diff --git a/packages/SystemUI/res/values-zu/strings.xml b/packages/SystemUI/res/values-zu/strings.xml
index 2306e4a..37eca51 100644
--- a/packages/SystemUI/res/values-zu/strings.xml
+++ b/packages/SystemUI/res/values-zu/strings.xml
@@ -47,6 +47,8 @@
     <string name="status_bar_input_method_settings_configure_input_methods" msgid="3504292471512317827">"Izilungiselelo zezindlela zokufakwayo"</string>
     <string name="status_bar_use_physical_keyboard" msgid="7551903084416057810">"Ukwakheka kwekhibhodi"</string>
     <string name="usb_device_permission_prompt" msgid="1825685909587559679">"Vumela i-<xliff:g id="APPLICATION">%1$s</xliff:g> ukufinyelela i-<xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
+    <!-- no translation found for usb_device_permission_prompt_warn (1842558472039505091) -->
+    <skip />
     <string name="usb_accessory_permission_prompt" msgid="2465531696941369047">"Vumela i-<xliff:g id="APPLICATION">%1$s</xliff:g> ukufinyelela i-<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
     <string name="usb_device_confirm_prompt" msgid="7440562274256843905">"Vula i-<xliff:g id="APPLICATION">%1$s</xliff:g> ukuze uphath i-<xliff:g id="USB_DEVICE">%2$s</xliff:g>?"</string>
     <string name="usb_accessory_confirm_prompt" msgid="4333670517539993561">"Vula i-<xliff:g id="APPLICATION">%1$s</xliff:g> ukuze uphath i-<xliff:g id="USB_ACCESSORY">%2$s</xliff:g>?"</string>
@@ -119,12 +121,27 @@
     <string name="cancel" msgid="6442560571259935130">"Khansela"</string>
     <string name="biometric_dialog_confirm" msgid="6468457350041712674">"Qinisekisa"</string>
     <string name="biometric_dialog_try_again" msgid="1900185172633183201">"Zama futhi"</string>
-    <string name="biometric_dialog_empty_space_description" msgid="7997936968009073717">"Isifunda esingenalutho, thepha ukuze ukhansele ukufakazela ubuqiniso"</string>
+    <string name="biometric_dialog_empty_space_description" msgid="6337699671577692511">"Thepha ukuze ukhansele ukufakazela ubuqiniso"</string>
     <string name="biometric_dialog_face_icon_description_idle" msgid="4497694707475970790">"Sicela uzame futhi"</string>
     <string name="biometric_dialog_face_icon_description_authenticating" msgid="4512727754496228488">"Ifuna ubuso bakho"</string>
     <string name="biometric_dialog_face_icon_description_authenticated" msgid="595380451325425259">"Ubuso bufakazelwe ubuqiniso"</string>
     <string name="biometric_dialog_face_icon_description_confirmed" msgid="2003141400387093967">"Kuqinisekisiwe"</string>
     <string name="biometric_dialog_tap_confirm" msgid="4540715260292022404">"Thepha okuthi Qinisekisa ukuze uqedele"</string>
+    <string name="biometric_dialog_authenticated" msgid="5918352844999713693">"Kugunyaziwe"</string>
+    <!-- no translation found for biometric_dialog_use_pin (2506187927478996039) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_pattern (4721877831431699442) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_use_password (3426428493718969343) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pin (4600590473629948574) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_pattern (4808369401645512099) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_wrong_password (2343518162282889518) -->
+    <skip />
+    <!-- no translation found for biometric_dialog_credential_too_many_attempts (1556206869468265728) -->
+    <skip />
     <string name="fingerprint_dialog_touch_sensor" msgid="8511557690663181761">"Thinta inzwa yesigxivizo somunwe"</string>
     <string name="accessibility_fingerprint_dialog_fingerprint_icon" msgid="3125122495414253226">"Isithonjana sezigxivizo zeminwe"</string>
     <string name="face_dialog_looking_for_face" msgid="7049276266074494689">"Kufunwa wena…"</string>
@@ -363,6 +380,8 @@
     </plurals>
     <string name="quick_settings_notifications_label" msgid="4818156442169154523">"Izaziso"</string>
     <string name="quick_settings_flashlight_label" msgid="2133093497691661546">"I-Flashlight"</string>
+    <!-- no translation found for quick_settings_flashlight_camera_in_use (6120370795890963385) -->
+    <skip />
     <string name="quick_settings_cellular_detail_title" msgid="3661194685666477347">"Idatha yeselula"</string>
     <string name="quick_settings_cellular_detail_data_usage" msgid="1964260360259312002">"Ukusetshenziswa kwedatha"</string>
     <string name="quick_settings_cellular_detail_remaining_data" msgid="722715415543541249">"Idatha esele"</string>
diff --git a/packages/SystemUI/res/values/arrays_tv.xml b/packages/SystemUI/res/values/arrays_tv.xml
index 9197bb5..1fe6141 100644
--- a/packages/SystemUI/res/values/arrays_tv.xml
+++ b/packages/SystemUI/res/values/arrays_tv.xml
@@ -33,4 +33,8 @@
         <item>com.google.android.tungsten.setupwraith/.settings.usage.UsageDiagnosticsSettingActivity</item>
         <item>com.google.android.tvlauncher/.notifications.NotificationsSidePanelActivity</item>
     </string-array>
+
+    <string-array name="audio_recording_disclosure_exempt_apps" translatable="false">
+      <item>com.google.android.katniss</item>
+    </string-array>
 </resources>
diff --git a/packages/SystemUI/res/values/colors_tv.xml b/packages/SystemUI/res/values/colors_tv.xml
index 6e56d4a..db22542 100644
--- a/packages/SystemUI/res/values/colors_tv.xml
+++ b/packages/SystemUI/res/values/colors_tv.xml
@@ -21,4 +21,14 @@
     <color name="recents_tv_card_title_text_color">#CCEEEEEE</color>
     <color name="recents_tv_dismiss_text_color">#7FEEEEEE</color>
     <color name="recents_tv_text_shadow_color">#7F000000</color>
+
+
+    <!-- Text color used in audio recording bar: G50 -->
+    <color name="tv_audio_recording_bar_text">#FFF8F9FA</color>
+    <!-- Background color for a chip in audio recording bar: G800 -->
+    <color name="tv_audio_recording_bar_chip_background">#FF3C4043</color>
+    <!-- Audio recording bar background color: G900 -->
+    <color name="tv_audio_recording_bar_background">#FF202124</color>
+
+    <color name="red">#FFCC0000</color>
 </resources>
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index 61210d3..105b27e 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -279,7 +279,7 @@
         <item>com.android.systemui.recents.Recents</item>
         <item>com.android.systemui.volume.VolumeUI</item>
         <item>com.android.systemui.stackdivider.Divider</item>
-        <item>com.android.systemui.SystemBars</item>
+        <item>com.android.systemui.statusbar.phone.StatusBar</item>
         <item>com.android.systemui.usb.StorageNotification</item>
         <item>com.android.systemui.power.PowerUI</item>
         <item>com.android.systemui.media.RingtonePlayer</item>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 1079206..d722d61 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -1009,10 +1009,15 @@
     <!-- Biometric Dialog values -->
     <dimen name="biometric_dialog_biometric_icon_size">64dp</dimen>
     <dimen name="biometric_dialog_corner_size">4dp</dimen>
+    <!-- Y translation when showing/dismissing the dialog-->
     <dimen name="biometric_dialog_animation_translation_offset">350dp</dimen>
     <dimen name="biometric_dialog_border_padding">4dp</dimen>
     <dimen name="biometric_dialog_elevation">1dp</dimen>
     <dimen name="biometric_dialog_icon_padding">16dp</dimen>
+    <!-- Y translation for biometric contents when transitioning to device credential UI -->
+    <dimen name="biometric_dialog_medium_to_large_translation_offset">100dp</dimen>
+    <!-- Y translation for credential contents when animating in -->
+    <dimen name="biometric_dialog_credential_translation_offset">60dp</dimen>
 
     <!-- Wireless Charging Animation values -->
     <dimen name="wireless_charging_dots_radius_start">0dp</dimen>
diff --git a/packages/SystemUI/res/values/ids.xml b/packages/SystemUI/res/values/ids.xml
index 3727181..04640f4 100644
--- a/packages/SystemUI/res/values/ids.xml
+++ b/packages/SystemUI/res/values/ids.xml
@@ -141,5 +141,8 @@
 
     <!-- Global Actions Menu -->
     <item type="id" name="global_actions_view" />
+
+    <!-- NotificationPanelView -->
+    <item type="id" name="notification_panel" />
 </resources>
 
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 97e2f0f..8335c11 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -118,10 +118,13 @@
     <string name="status_bar_use_physical_keyboard">Physical keyboard</string>
 
     <!-- Prompt for the USB device permission dialog [CHAR LIMIT=80] -->
-    <string name="usb_device_permission_prompt">Allow <xliff:g id="application">%1$s</xliff:g> to access <xliff:g id="usb_device">%2$s</xliff:g>?</string>
+    <string name="usb_device_permission_prompt">Allow <xliff:g id="application" example= "Usb Mega Player">%1$s</xliff:g> to access <xliff:g id="usb_device" example="USB Headphones">%2$s</xliff:g>?</string>
+
+    <!-- Checkbox label for USB device dialogs with warning text for USB device dialogs.  [CHAR LIMIT=200]-->
+    <string name="usb_device_permission_prompt_warn">Allow <xliff:g id="application" example= "Usb Mega Player">%1$s</xliff:g> to access <xliff:g id="usb_device" example="USB Headphones">%2$s</xliff:g>?\nThis app has not been granted record permission but could capture audio through this USB device.</string>
 
     <!-- Prompt for the USB accessory permission dialog [CHAR LIMIT=80] -->
-    <string name="usb_accessory_permission_prompt">Allow <xliff:g id="application">%1$s</xliff:g> to access <xliff:g id="usb_accessory">%2$s</xliff:g>?</string>
+    <string name="usb_accessory_permission_prompt">Allow <xliff:g id="application" example= "Usb Mega Player">%1$s</xliff:g> to access <xliff:g id="usb_accessory"  example="USB Dock">%2$s</xliff:g>?</string>
 
     <!-- Prompt for the USB device confirm dialog [CHAR LIMIT=80] -->
     <string name="usb_device_confirm_prompt">Open <xliff:g id="application">%1$s</xliff:g> to handle <xliff:g id="usb_device">%2$s</xliff:g>?</string>
@@ -308,6 +311,21 @@
     <!-- Talkback string when a biometric is authenticated [CHAR LIMIT=NONE] -->
     <string name="biometric_dialog_authenticated">Authenticated</string>
 
+    <!-- Button text shown on BiometricPrompt giving the user the option to use an alternate form of authentication (Pin) [CHAR LIMIT=30] -->
+    <string name="biometric_dialog_use_pin">Use PIN</string>
+    <!-- Button text shown on BiometricPrompt giving the user the option to use an alternate form of authentication (Pattern) [CHAR LIMIT=30] -->
+    <string name="biometric_dialog_use_pattern">Use pattern</string>
+    <!-- Button text shown on BiometricPrompt giving the user the option to use an alternate form of authentication (Pass) [CHAR LIMIT=30] -->
+    <string name="biometric_dialog_use_password">Use password</string>
+    <!-- Error string shown when the user enters an incorrect PIN [CHAR LIMIT=40]-->
+    <string name="biometric_dialog_wrong_pin">Wrong PIN</string>
+    <!-- Error string shown when the user enters an incorrect pattern [CHAR LIMIT=40]-->
+    <string name="biometric_dialog_wrong_pattern">Wrong pattern</string>
+    <!-- Error string shown when the user enters an incorrect password [CHAR LIMIT=40]-->
+    <string name="biometric_dialog_wrong_password">Wrong password</string>
+    <!-- Error string shown when the user enters too many incorrect attempts [CHAR LIMIT=120]-->
+    <string name="biometric_dialog_credential_too_many_attempts">Too many incorrect attempts.\nTry again in <xliff:g id="number">%d</xliff:g> seconds.</string>
+
     <!-- Message shown when the system-provided fingerprint dialog is shown, asking for authentication -->
     <string name="fingerprint_dialog_touch_sensor">Touch the fingerprint sensor</string>
     <!-- Content description of the fingerprint icon when the system-provided fingerprint dialog is showing, for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
@@ -860,6 +878,8 @@
     <string name="quick_settings_notifications_label">Notifications</string>
     <!-- QuickSettings: Flashlight [CHAR LIMIT=NONE] -->
     <string name="quick_settings_flashlight_label">Flashlight</string>
+    <!-- QuickSettings: Flashlight, used when it's not available due to camera in use [CHAR LIMIT=NONE] -->
+    <string name="quick_settings_flashlight_camera_in_use">Camera in use</string>
     <!-- QuickSettings: Cellular detail panel title [CHAR LIMIT=NONE] -->
     <string name="quick_settings_cellular_detail_title">Mobile data</string>
     <!-- QuickSettings: Cellular detail panel, data usage title [CHAR LIMIT=NONE] -->
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 6374191..96fbcbb 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -314,6 +314,12 @@
         <item name="*android:errorColor">?android:attr/colorError</item>
     </style>
 
+    <style name="LockPatternStyleBiometricPrompt">
+        <item name="*android:regularColor">?android:attr/colorForeground</item>
+        <item name="*android:successColor">?android:attr/colorForeground</item>
+        <item name="*android:errorColor">?android:attr/colorError</item>
+    </style>
+
     <style name="qs_theme" parent="@*android:style/Theme.DeviceDefault.QuickSettings">
         <item name="lightIconTheme">@style/QSIconTheme</item>
         <item name="darkIconTheme">@style/QSIconTheme</item>
diff --git a/packages/SystemUI/shared/Android.bp b/packages/SystemUI/shared/Android.bp
index 31a538c..4471818 100644
--- a/packages/SystemUI/shared/Android.bp
+++ b/packages/SystemUI/shared/Android.bp
@@ -27,4 +27,6 @@
     // Enforce that the library is built against java 7 so that there are
     // no compatibility issues with launcher
     java_version: "1.7",
+
+    min_sdk_version: "26",
 }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl
index 9228b17..1cabee1 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/ISystemUiProxy.aidl
@@ -109,4 +109,9 @@
      * Ends the system screen pinning.
      */
     void stopScreenPinning() = 17;
+
+    /**
+     * Sets the shelf height and visibility.
+     */
+    void setShelfHeight(boolean visible, int shelfHeight) = 20;
 }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java
index 2797042..fe5a57a 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/PinnedStackListenerForwarder.java
@@ -69,13 +69,6 @@
     }
 
     @Override
-    public void onShelfVisibilityChanged(boolean shelfVisible, int shelfHeight) {
-        for (PinnedStackListener listener : mListeners) {
-            listener.onShelfVisibilityChanged(shelfVisible, shelfHeight);
-        }
-    }
-
-    @Override
     public void onMinimizedStateChanged(boolean isMinimized) {
         for (PinnedStackListener listener : mListeners) {
             listener.onMinimizedStateChanged(isMinimized);
@@ -143,8 +136,6 @@
 
         public void onImeVisibilityChanged(boolean imeVisible, int imeHeight) {}
 
-        public void onShelfVisibilityChanged(boolean shelfVisible, int shelfHeight) {}
-
         public void onMinimizedStateChanged(boolean isMinimized) {}
 
         public void onActionsChanged(ParceledListSlice actions) {}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
index 5ddf89c..6186589 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
@@ -17,6 +17,7 @@
 package com.android.systemui.shared.system;
 
 import android.app.ActivityManager.RunningTaskInfo;
+import android.app.ITaskStackListener;
 import android.content.ComponentName;
 import android.os.IBinder;
 import android.os.UserHandle;
@@ -106,6 +107,9 @@
      */
     public void onRecentTaskListUpdated() { }
 
+    /** @see ITaskStackListener#onRecentTaskListFrozenChanged(boolean) */
+    public void onRecentTaskListFrozenChanged(boolean frozen) { }
+
     /**
      * Checks that the current user matches the process. Since
      * {@link android.app.ITaskStackListener} is not multi-user aware, handlers of
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
index 820057a..8d823ca 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
@@ -224,6 +224,12 @@
         mHandler.obtainMessage(H.ON_TASK_LIST_UPDATED).sendToTarget();
     }
 
+    @Override
+    public void onRecentTaskListFrozenChanged(boolean frozen) {
+        mHandler.obtainMessage(H.ON_TASK_LIST_FROZEN_UNFROZEN, frozen ? 1 : 0, 0 /* unused */)
+                .sendToTarget();
+    }
+
     private final class H extends Handler {
         private static final int ON_TASK_STACK_CHANGED = 1;
         private static final int ON_TASK_SNAPSHOT_CHANGED = 2;
@@ -247,6 +253,7 @@
         private static final int ON_TASK_DISPLAY_CHANGED = 20;
         private static final int ON_TASK_LIST_UPDATED = 21;
         private static final int ON_SINGLE_TASK_DISPLAY_EMPTY = 22;
+        private static final int ON_TASK_LIST_FROZEN_UNFROZEN = 23;
 
 
         public H(Looper looper) {
@@ -408,6 +415,12 @@
                         }
                         break;
                     }
+                    case ON_TASK_LIST_FROZEN_UNFROZEN: {
+                        for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) {
+                            mTaskStackListeners.get(i).onRecentTaskListFrozenChanged(msg.arg1 != 0);
+                        }
+                        break;
+                    }
                 }
             }
         }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java
index 9f1a1fa..ad182fe 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/WindowManagerWrapper.java
@@ -143,14 +143,6 @@
         }
     }
 
-    public void setShelfHeight(boolean visible, int shelfHeight) {
-        try {
-            WindowManagerGlobal.getWindowManagerService().setShelfHeight(visible, shelfHeight);
-        } catch (RemoteException e) {
-            Log.w(TAG, "Failed to set shelf height");
-        }
-    }
-
     public void setRecentsVisibility(boolean visible) {
         try {
             WindowManagerGlobal.getWindowManagerService().setRecentsVisibility(visible);
diff --git a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
index e1b723e..ef9538d 100644
--- a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
+++ b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java
@@ -35,6 +35,7 @@
 import android.text.TextUtils;
 import android.util.Log;
 
+import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 
 import com.android.internal.telephony.IccCardConstants;
@@ -57,6 +58,7 @@
     private static final String TAG = "CarrierTextController";
 
     private final boolean mIsEmergencyCallCapable;
+    private final Handler mMainHandler;
     private boolean mTelephonyCapable;
     private boolean mShowMissingSim;
     private boolean mShowAirplaneMode;
@@ -65,6 +67,7 @@
     private WifiManager mWifiManager;
     private boolean[] mSimErrorState;
     private final int mSimSlotsNumber;
+    @Nullable // Check for nullability before dispatching
     private CarrierTextCallback mCarrierTextCallback;
     private Context mContext;
     private CharSequence mSeparator;
@@ -73,12 +76,12 @@
             new WakefulnessLifecycle.Observer() {
                 @Override
                 public void onFinishedWakingUp() {
-                    mCarrierTextCallback.finishedWakingUp();
+                    if (mCarrierTextCallback != null) mCarrierTextCallback.finishedWakingUp();
                 }
 
                 @Override
                 public void onStartedGoingToSleep() {
-                    mCarrierTextCallback.startedGoingToSleep();
+                    if (mCarrierTextCallback != null) mCarrierTextCallback.startedGoingToSleep();
                 }
             };
 
@@ -167,8 +170,9 @@
         mSeparator = separator;
         mWakefulnessLifecycle = Dependency.get(WakefulnessLifecycle.class);
         mSimSlotsNumber = ((TelephonyManager) context.getSystemService(
-                Context.TELEPHONY_SERVICE)).getPhoneCount();
+                Context.TELEPHONY_SERVICE)).getMaxPhoneCount();
         mSimErrorState = new boolean[mSimSlotsNumber];
+        mMainHandler = Dependency.get(Dependency.MAIN_HANDLER);
     }
 
     /**
@@ -227,7 +231,12 @@
             if (whitelistIpcs(() -> ConnectivityManager.from(mContext).isNetworkSupported(
                     ConnectivityManager.TYPE_MOBILE))) {
                 mKeyguardUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
-                mKeyguardUpdateMonitor.registerCallback(mCallback);
+                // Keyguard update monitor expects callbacks from main thread
+                mMainHandler.post(() -> {
+                    if (mKeyguardUpdateMonitor != null) {
+                        mKeyguardUpdateMonitor.registerCallback(mCallback);
+                    }
+                });
                 mWakefulnessLifecycle.addObserver(mWakefulnessObserver);
                 telephonyManager.listen(mPhoneStateListener,
                         LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE);
@@ -239,7 +248,12 @@
         } else {
             mCarrierTextCallback = null;
             if (mKeyguardUpdateMonitor != null) {
-                mKeyguardUpdateMonitor.removeCallback(mCallback);
+                // Keyguard update monitor expects callbacks from main thread
+                mMainHandler.post(() -> {
+                    if (mKeyguardUpdateMonitor != null) {
+                        mKeyguardUpdateMonitor.removeCallback(mCallback);
+                    }
+                });
                 mWakefulnessLifecycle.removeObserver(mWakefulnessObserver);
             }
             telephonyManager.listen(mPhoneStateListener, LISTEN_NONE);
@@ -364,10 +378,9 @@
 
     @VisibleForTesting
     protected void postToCallback(CarrierTextCallbackInfo info) {
-        Handler handler = Dependency.get(Dependency.MAIN_HANDLER);
         final CarrierTextCallback callback = mCarrierTextCallback;
         if (callback != null) {
-            handler.post(() -> callback.updateCarrierInfo(info));
+            mMainHandler.post(() -> callback.updateCarrierInfo(info));
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
index eaaa3ed..e3ac0f6 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPasswordView.java
@@ -86,13 +86,12 @@
             mSecurityMessageDisplay.setMessage("");
         }
         final boolean wasDisabled = mPasswordEntry.isEnabled();
-        // Don't set enabled password entry & showSoftInput when PasswordEntry is invisible or in
-        // pausing stage.
+        setPasswordEntryEnabled(true);
+        setPasswordEntryInputEnabled(true);
+        // Don't call showSoftInput when PasswordEntry is invisible or in pausing stage.
         if (!mResumed || !mPasswordEntry.isVisibleToUser()) {
             return;
         }
-        setPasswordEntryEnabled(true);
-        setPasswordEntryInputEnabled(true);
         if (wasDisabled) {
             mImm.showSoftInput(mPasswordEntry, InputMethodManager.SHOW_IMPLICIT);
         }
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
index 35eb272..b9fe933 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -49,7 +49,7 @@
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.SystemUIFactory;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.util.InjectionInflationController;
 
 public class KeyguardSecurityContainer extends FrameLayout implements KeyguardSecurityView {
@@ -76,7 +76,7 @@
     // How much you need to drag the bouncer to trigger an auth retry (in dps.)
     private static final float MIN_DRAG_SIZE = 10;
     // How much to scale the default slop by, to avoid accidental drags.
-    private static final float SLOP_SCALE = 2f;
+    private static final float SLOP_SCALE = 4f;
 
     private KeyguardSecurityModel mSecurityModel;
     private LockPatternUtils mLockPatternUtils;
@@ -94,7 +94,7 @@
     private final SpringAnimation mSpringAnimation;
     private final VelocityTracker mVelocityTracker = VelocityTracker.obtain();
     private final KeyguardUpdateMonitor mUpdateMonitor;
-    private final UnlockMethodCache mUnlockMethodCache;
+    private final KeyguardStateController mKeyguardStateController;
 
     private final MetricsLogger mMetricsLogger = Dependency.get(MetricsLogger.class);
     private float mLastTouchY = -1;
@@ -128,14 +128,14 @@
 
     public KeyguardSecurityContainer(Context context, AttributeSet attrs, int defStyle) {
         super(context, attrs, defStyle);
-        mSecurityModel = new KeyguardSecurityModel(context);
+        mSecurityModel = Dependency.get(KeyguardSecurityModel.class);
         mLockPatternUtils = new LockPatternUtils(context);
         mUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
         mSpringAnimation = new SpringAnimation(this, DynamicAnimation.Y);
         mInjectionInflationController =  new InjectionInflationController(
             SystemUIFactory.getInstance().getRootComponent());
-        mUnlockMethodCache = UnlockMethodCache.getInstance(context);
         mViewConfiguration = ViewConfiguration.get(context);
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
     }
 
     public void setSecurityCallback(SecurityCallback callback) {
@@ -272,7 +272,7 @@
      */
     private void updateBiometricRetry() {
         SecurityMode securityMode = getSecurityMode();
-        mSwipeUpToRetry = mUnlockMethodCache.isFaceAuthEnabled()
+        mSwipeUpToRetry = mKeyguardStateController.isFaceAuthEnabled()
                 && securityMode != SecurityMode.SimPin
                 && securityMode != SecurityMode.SimPuk
                 && securityMode != SecurityMode.None;
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityModel.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityModel.java
index bb89959..1395fd9 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityModel.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityModel.java
@@ -25,6 +25,10 @@
 import com.android.internal.widget.LockPatternUtils;
 import com.android.systemui.Dependency;
 
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+@Singleton
 public class KeyguardSecurityModel {
 
     /**
@@ -46,6 +50,7 @@
 
     private LockPatternUtils mLockPatternUtils;
 
+    @Inject
     KeyguardSecurityModel(Context context) {
         mContext = context;
         mLockPatternUtils = new LockPatternUtils(context);
@@ -57,7 +62,7 @@
         mLockPatternUtils = utils;
     }
 
-    SecurityMode getSecurityMode(int userId) {
+    public SecurityMode getSecurityMode(int userId) {
         KeyguardUpdateMonitor monitor = Dependency.get(KeyguardUpdateMonitor.class);
 
         if (mIsPukScreenAvailable && SubscriptionManager.isValidSubscriptionId(
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
index 63da533..5a1c997 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardStatusView.java
@@ -22,7 +22,6 @@
 import android.content.res.Resources;
 import android.graphics.Color;
 import android.os.Handler;
-import android.os.Looper;
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.text.TextUtils;
@@ -135,7 +134,7 @@
         super(context, attrs, defStyle);
         mIActivityManager = ActivityManager.getService();
         mLockPatternUtils = new LockPatternUtils(getContext());
-        mHandler = new Handler(Looper.myLooper());
+        mHandler = new Handler();
         onDensityOrFontScaleChanged();
     }
 
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 720074b..9bcccbc 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -58,6 +58,7 @@
 import android.content.pm.IPackageManager;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
+import android.content.pm.UserInfo;
 import android.database.ContentObserver;
 import android.hardware.biometrics.BiometricManager;
 import android.hardware.biometrics.BiometricSourceType;
@@ -117,12 +118,14 @@
 
 import javax.inject.Inject;
 import javax.inject.Named;
+import javax.inject.Singleton;
 
 /**
  * Watches for updates that may be interesting to the keyguard, and provides
  * the up to date information as well as a registration for callbacks that care
  * to be updated.
  */
+@Singleton
 public class KeyguardUpdateMonitor implements TrustManager.TrustListener {
 
     private static final String TAG = "KeyguardUpdateMonitor";
@@ -219,7 +222,7 @@
 
     private final Context mContext;
     private final boolean mIsPrimaryUser;
-    HashMap<Integer, SimData> mSimDatas = new HashMap<Integer, SimData>();
+    HashMap<Integer, SimData> mSimDatas = new HashMap<>();
     HashMap<Integer, ServiceState> mServiceStates = new HashMap<Integer, ServiceState>();
 
     private int mRingMode;
@@ -329,6 +332,7 @@
     private SparseBooleanArray mUserIsUnlocked = new SparseBooleanArray();
     private SparseBooleanArray mUserHasTrust = new SparseBooleanArray();
     private SparseBooleanArray mUserTrustIsManaged = new SparseBooleanArray();
+    private SparseBooleanArray mUserTrustIsUsuallyManaged = new SparseBooleanArray();
     private SparseBooleanArray mUserFingerprintAuthenticated = new SparseBooleanArray();
     private SparseBooleanArray mUserFaceAuthenticated = new SparseBooleanArray();
     private SparseBooleanArray mUserFaceUnlockRunning = new SparseBooleanArray();
@@ -472,6 +476,7 @@
     public void onTrustManagedChanged(boolean managed, int userId) {
         checkIsHandlerThread();
         mUserTrustIsManaged.put(userId, managed);
+        mUserTrustIsUsuallyManaged.put(userId, mTrustManager.isTrustUsuallyManaged(userId));
         for (int i = 0; i < mCallbacks.size(); i++) {
             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
             if (cb != null) {
@@ -925,6 +930,14 @@
         return mUserTrustIsManaged.get(userId) && !isTrustDisabled(userId);
     }
 
+    /**
+     * Cached version of {@link TrustManager#isTrustUsuallyManaged(int)}.
+     */
+    public boolean isTrustUsuallyManaged(int userId) {
+        checkIsHandlerThread();
+        return mUserTrustIsUsuallyManaged.get(userId);
+    }
+
     public boolean isUnlockingWithBiometricAllowed() {
         return mStrongAuthTracker.isUnlockingWithBiometricAllowed();
     }
@@ -1474,9 +1487,11 @@
         mUserIsUnlocked.put(userId, mUserManager.isUserUnlocked(userId));
     }
 
-    private void handleUserRemoved(int userId) {
+    @VisibleForTesting
+    void handleUserRemoved(int userId) {
         checkIsHandlerThread();
         mUserIsUnlocked.delete(userId);
+        mUserTrustIsUsuallyManaged.delete(userId);
     }
 
     @VisibleForTesting
@@ -1662,7 +1677,7 @@
             e.rethrowAsRuntimeException();
         }
 
-        mTrustManager = (TrustManager) context.getSystemService(Context.TRUST_SERVICE);
+        mTrustManager = context.getSystemService(TrustManager.class);
         mTrustManager.registerTrustListener(this);
         mLockPatternUtils = new LockPatternUtils(context);
         mLockPatternUtils.registerStrongAuthTracker(mStrongAuthTracker);
@@ -1697,6 +1712,11 @@
         mUserIsUnlocked.put(user, mUserManager.isUserUnlocked(user));
         mDevicePolicyManager = context.getSystemService(DevicePolicyManager.class);
         mLogoutEnabled = mDevicePolicyManager.isLogoutEnabled();
+        List<UserInfo> allUsers = mUserManager.getUsers();
+        for (UserInfo userInfo : allUsers) {
+            mUserTrustIsUsuallyManaged.put(userInfo.id,
+                    mTrustManager.isTrustUsuallyManaged(userInfo.id));
+        }
         updateAirplaneModeState();
 
         TelephonyManager telephony =
@@ -2048,6 +2068,7 @@
      */
     private void handleUserSwitching(int userId, IRemoteCallback reply) {
         checkIsHandlerThread();
+        mUserTrustIsUsuallyManaged.put(userId, mTrustManager.isTrustUsuallyManaged(userId));
         for (int i = 0; i < mCallbacks.size(); i++) {
             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
             if (cb != null) {
@@ -2512,8 +2533,7 @@
     @MainThread
     public void reportSimUnlocked(int subId) {
         if (DEBUG_SIM_STATES) Log.v(TAG, "reportSimUnlocked(subId=" + subId + ")");
-        int slotId = SubscriptionManager.getSlotIndex(subId);
-        handleSimStateChange(subId, slotId, State.READY);
+        handleSimStateChange(subId, getSlotId(subId), State.READY);
     }
 
     /**
@@ -2586,6 +2606,13 @@
         }
     }
 
+    private int getSlotId(int subId) {
+        if (!mSimDatas.containsKey(subId)) {
+            refreshSimState(subId, SubscriptionManager.getSlotIndex(subId));
+        }
+        return mSimDatas.get(subId).slotId;
+    }
+
     private final TaskStackChangeListener
             mTaskStackListener = new TaskStackChangeListener() {
         @Override
@@ -2710,7 +2737,7 @@
         for (int i = 0; i < list.size(); i++) {
             final SubscriptionInfo info = list.get(i);
             final int id = info.getSubscriptionId();
-            int slotId = SubscriptionManager.getSlotIndex(id);
+            int slotId = getSlotId(id);
             if (state == getSimState(id) && bestSlotId > slotId) {
                 resultId = id;
                 bestSlotId = slotId;
@@ -2752,7 +2779,7 @@
 
     private void checkIsHandlerThread() {
         if (!mHandler.getLooper().isCurrentThread()) {
-            Log.wtf(TAG, "must call on mHandler's thread "
+            Log.wtfStack(TAG, "must call on mHandler's thread "
                     + mHandler.getLooper().getThread() + ", not " + Thread.currentThread());
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index 7771f86..07bfa71 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -30,6 +30,7 @@
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.internal.util.Preconditions;
+import com.android.keyguard.KeyguardSecurityModel;
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.keyguard.clock.ClockManager;
 import com.android.settingslib.bluetooth.LocalBluetoothManager;
@@ -97,7 +98,7 @@
 import com.android.systemui.statusbar.policy.ExtensionController;
 import com.android.systemui.statusbar.policy.FlashlightController;
 import com.android.systemui.statusbar.policy.HotspotController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.LocationController;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.statusbar.policy.NextAlarmController;
@@ -221,7 +222,7 @@
     @Inject Lazy<FlashlightController> mFlashlightController;
     @Inject Lazy<UserSwitcherController> mUserSwitcherController;
     @Inject Lazy<UserInfoController> mUserInfoController;
-    @Inject Lazy<KeyguardMonitor> mKeyguardMonitor;
+    @Inject Lazy<KeyguardStateController> mKeyguardMonitor;
     @Inject Lazy<KeyguardUpdateMonitor> mKeyguardUpdateMonitor;
     @Inject Lazy<BatteryController> mBatteryController;
     @Inject Lazy<NightDisplayListener> mNightDisplayListener;
@@ -316,6 +317,7 @@
     @Inject Lazy<FalsingManager> mFalsingManager;
     @Inject Lazy<SysUiState> mSysUiStateFlagsContainer;
     @Inject Lazy<AlarmManager> mAlarmManager;
+    @Inject Lazy<KeyguardSecurityModel> mKeyguardSecurityModel;
 
     @Inject
     public Dependency() {
@@ -355,7 +357,7 @@
 
         mProviders.put(FlashlightController.class, mFlashlightController::get);
 
-        mProviders.put(KeyguardMonitor.class, mKeyguardMonitor::get);
+        mProviders.put(KeyguardStateController.class, mKeyguardMonitor::get);
 
         mProviders.put(KeyguardUpdateMonitor.class, mKeyguardUpdateMonitor::get);
 
@@ -501,6 +503,7 @@
         mProviders.put(FalsingManager.class, mFalsingManager::get);
         mProviders.put(SysUiState.class, mSysUiStateFlagsContainer::get);
         mProviders.put(AlarmManager.class, mAlarmManager::get);
+        mProviders.put(KeyguardSecurityModel.class, mKeyguardSecurityModel::get);
 
         // TODO(b/118592525): to support multi-display , we start to add something which is
         //                    per-display, while others may be global. I think it's time to add
diff --git a/packages/SystemUI/src/com/android/systemui/DependencyBinder.java b/packages/SystemUI/src/com/android/systemui/DependencyBinder.java
index 4df7f0d..f9f0f1b 100644
--- a/packages/SystemUI/src/com/android/systemui/DependencyBinder.java
+++ b/packages/SystemUI/src/com/android/systemui/DependencyBinder.java
@@ -30,6 +30,7 @@
 import com.android.systemui.qs.QSTileHost;
 import com.android.systemui.statusbar.NotificationRemoteInputManager;
 import com.android.systemui.statusbar.StatusBarStateControllerImpl;
+import com.android.systemui.statusbar.SysuiStatusBarStateController;
 import com.android.systemui.statusbar.phone.DarkIconDispatcherImpl;
 import com.android.systemui.statusbar.phone.ManagedProfileController;
 import com.android.systemui.statusbar.phone.ManagedProfileControllerImpl;
@@ -48,8 +49,8 @@
 import com.android.systemui.statusbar.policy.FlashlightControllerImpl;
 import com.android.systemui.statusbar.policy.HotspotController;
 import com.android.systemui.statusbar.policy.HotspotControllerImpl;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
-import com.android.systemui.statusbar.policy.KeyguardMonitorImpl;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
+import com.android.systemui.statusbar.policy.KeyguardStateControllerImpl;
 import com.android.systemui.statusbar.policy.LocationController;
 import com.android.systemui.statusbar.policy.LocationControllerImpl;
 import com.android.systemui.statusbar.policy.NetworkController;
@@ -146,7 +147,8 @@
     /**
      */
     @Binds
-    public abstract KeyguardMonitor provideKeyguardMonitor(KeyguardMonitorImpl controllerImpl);
+    public abstract KeyguardStateController provideKeyguardMonitor(
+            KeyguardStateControllerImpl controllerImpl);
 
     /**
      */
@@ -198,6 +200,12 @@
     /**
      */
     @Binds
+    public abstract SysuiStatusBarStateController providesSysuiStatusBarStateController(
+            StatusBarStateControllerImpl statusBarStateControllerImpl);
+
+    /**
+     */
+    @Binds
     public abstract StatusBarIconController provideStatusBarIconController(
             StatusBarIconControllerImpl controllerImpl);
 
diff --git a/packages/SystemUI/src/com/android/systemui/DependencyProvider.java b/packages/SystemUI/src/com/android/systemui/DependencyProvider.java
index 239cbfe..0d24321 100644
--- a/packages/SystemUI/src/com/android/systemui/DependencyProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/DependencyProvider.java
@@ -40,6 +40,7 @@
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.statusbar.IStatusBarService;
+import com.android.internal.widget.LockPatternUtils;
 import com.android.settingslib.bluetooth.LocalBluetoothManager;
 import com.android.systemui.plugins.PluginInitializerImpl;
 import com.android.systemui.shared.plugins.PluginManager;
@@ -238,4 +239,10 @@
     public AlarmManager provideAlarmManager(Context context) {
         return context.getSystemService(AlarmManager.class);
     }
+
+    /** */
+    @Provides
+    public LockPatternUtils provideLockPatternUtils(Context context) {
+        return new LockPatternUtils(context);
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/ForegroundServiceLifetimeExtender.java b/packages/SystemUI/src/com/android/systemui/ForegroundServiceLifetimeExtender.java
index 0e079e3..5c561e5 100644
--- a/packages/SystemUI/src/com/android/systemui/ForegroundServiceLifetimeExtender.java
+++ b/packages/SystemUI/src/com/android/systemui/ForegroundServiceLifetimeExtender.java
@@ -83,7 +83,9 @@
                 }
             }
         };
-        mHandler.postDelayed(r, MIN_FGS_TIME_MS);
+        long delayAmt = MIN_FGS_TIME_MS
+                - (System.currentTimeMillis() - entry.notification.getPostTime());
+        mHandler.postDelayed(r, delayAmt);
     }
 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
index bd91333..1c0e0b3 100644
--- a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.graphics.Rect;
 import android.os.HandlerThread;
+import android.os.Trace;
 import android.service.wallpaper.WallpaperService;
 import android.util.Log;
 import android.util.Size;
@@ -48,6 +49,7 @@
     private static final int DELAY_FINISH_RENDERING = 1000;
     private static final int INTERVAL_WAIT_FOR_RENDERING = 100;
     private static final int PATIENCE_WAIT_FOR_RENDERING = 10;
+    private static final boolean DEBUG = true;
     private HandlerThread mWorker;
 
     @Override
@@ -125,6 +127,10 @@
         @Override
         public void onAmbientModeChanged(boolean inAmbientMode, long animationDuration) {
             if (!mNeedTransition) return;
+            if (DEBUG) {
+                Log.d(TAG, "onAmbientModeChanged: inAmbient=" + inAmbientMode
+                        + ", duration=" + animationDuration);
+            }
             mWorker.getThreadHandler().post(
                     () -> mRenderer.updateAmbientMode(inAmbientMode, animationDuration));
             if (inAmbientMode && animationDuration == 0) {
@@ -184,17 +190,32 @@
 
         @Override
         public void onSurfaceRedrawNeeded(SurfaceHolder holder) {
+            if (DEBUG) {
+                Log.d(TAG, "onSurfaceRedrawNeeded: mNeedRedraw=" + mNeedRedraw);
+            }
+
             mWorker.getThreadHandler().post(() -> {
                 if (mNeedRedraw) {
-                    preRender();
-                    requestRender();
-                    postRender();
+                    drawFrame();
                     mNeedRedraw = false;
                 }
             });
         }
 
         @Override
+        public void onVisibilityChanged(boolean visible) {
+            if (DEBUG) {
+                Log.d(TAG, "wallpaper visibility changes: " + visible);
+            }
+        }
+
+        private void drawFrame() {
+            preRender();
+            requestRender();
+            postRender();
+        }
+
+        @Override
         public void onStatePostChange() {
             // When back to home, we try to release EGL, which is preserved in lock screen or aod.
             if (mController.getState() == StatusBarState.SHADE) {
@@ -205,7 +226,9 @@
         @Override
         public void preRender() {
             // This method should only be invoked from worker thread.
+            Trace.beginSection("ImageWallpaper#preRender");
             preRenderInternal();
+            Trace.endSection();
         }
 
         private void preRenderInternal() {
@@ -240,7 +263,9 @@
         @Override
         public void requestRender() {
             // This method should only be invoked from worker thread.
+            Trace.beginSection("ImageWallpaper#requestRender");
             requestRenderInternal();
+            Trace.endSection();
         }
 
         private void requestRenderInternal() {
@@ -263,8 +288,10 @@
         @Override
         public void postRender() {
             // This method should only be invoked from worker thread.
+            Trace.beginSection("ImageWallpaper#postRender");
             notifyWaitingThread();
             scheduleFinishRendering();
+            Trace.endSection();
         }
 
         private void notifyWaitingThread() {
@@ -289,12 +316,14 @@
         }
 
         private void finishRendering() {
+            Trace.beginSection("ImageWallpaper#finishRendering");
             if (mEglHelper != null) {
                 mEglHelper.destroyEglSurface();
                 if (!needPreserveEglContext()) {
                     mEglHelper.destroyEglContext();
                 }
             }
+            Trace.endSection();
         }
 
         private boolean needPreserveEglContext() {
diff --git a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
index f38b4f2..3e068b0 100644
--- a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
+++ b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
@@ -25,9 +25,6 @@
 import static com.android.systemui.tuner.TunablePadding.FLAG_END;
 import static com.android.systemui.tuner.TunablePadding.FLAG_START;
 
-import android.animation.Animator;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
 import android.annotation.Dimension;
 import android.app.ActivityManager;
 import android.app.Fragment;
@@ -52,7 +49,6 @@
 import android.provider.Settings.Secure;
 import android.util.DisplayMetrics;
 import android.util.Log;
-import android.util.MathUtils;
 import android.view.DisplayCutout;
 import android.view.DisplayInfo;
 import android.view.Gravity;
@@ -64,9 +60,6 @@
 import android.view.ViewGroup.LayoutParams;
 import android.view.ViewTreeObserver;
 import android.view.WindowManager;
-import android.view.animation.AccelerateInterpolator;
-import android.view.animation.Interpolator;
-import android.view.animation.PathInterpolator;
 import android.widget.FrameLayout;
 import android.widget.ImageView;
 
@@ -78,10 +71,7 @@
 import com.android.systemui.fragments.FragmentHostManager.FragmentListener;
 import com.android.systemui.plugins.qs.QS;
 import com.android.systemui.qs.SecureSetting;
-import com.android.systemui.shared.system.QuickStepContract;
 import com.android.systemui.statusbar.phone.CollapsedStatusBarFragment;
-import com.android.systemui.statusbar.phone.NavigationBarTransitions;
-import com.android.systemui.statusbar.phone.NavigationModeController;
 import com.android.systemui.statusbar.phone.StatusBar;
 import com.android.systemui.tuner.TunablePadding;
 import com.android.systemui.tuner.TunerService;
@@ -95,8 +85,7 @@
  * An overlay that draws screen decorations in software (e.g for rounded corners or display cutout)
  * for antialiasing and emulation purposes.
  */
-public class ScreenDecorations extends SystemUI implements Tunable,
-        NavigationBarTransitions.DarkIntensityListener {
+public class ScreenDecorations extends SystemUI implements Tunable {
     private static final boolean DEBUG = false;
     private static final String TAG = "ScreenDecorations";
 
@@ -120,15 +109,11 @@
     private float mDensity;
     private WindowManager mWindowManager;
     private int mRotation;
-    private boolean mAssistHintVisible;
     private DisplayCutoutView mCutoutTop;
     private DisplayCutoutView mCutoutBottom;
     private SecureSetting mColorInversionSetting;
     private boolean mPendingRotationChange;
     private Handler mHandler;
-    private boolean mAssistHintBlocked = false;
-    private boolean mIsReceivingNavBarColor = false;
-    private boolean mInGesturalMode;
 
     /**
      * Converts a set of {@link Rect}s into a {@link Region}
@@ -153,160 +138,6 @@
         mHandler.post(this::startOnScreenDecorationsThread);
         setupStatusBarPaddingIfNeeded();
         putComponent(ScreenDecorations.class, this);
-        mInGesturalMode = QuickStepContract.isGesturalMode(
-                Dependency.get(NavigationModeController.class)
-                        .addListener(this::handleNavigationModeChange));
-    }
-
-    @VisibleForTesting
-    void handleNavigationModeChange(int navigationMode) {
-        if (!mHandler.getLooper().isCurrentThread()) {
-            mHandler.post(() -> handleNavigationModeChange(navigationMode));
-            return;
-        }
-        boolean inGesturalMode = QuickStepContract.isGesturalMode(navigationMode);
-        if (mInGesturalMode != inGesturalMode) {
-            mInGesturalMode = inGesturalMode;
-
-            if (mInGesturalMode && mOverlay == null) {
-                setupDecorations();
-                if (mOverlay != null) {
-                    updateLayoutParams();
-                }
-            }
-        }
-    }
-
-    /**
-     * Returns an animator that animates the given view from start to end over durationMs. Start and
-     * end represent total animation progress: 0 is the start, 1 is the end, 1.1 would be an
-     * overshoot.
-     */
-    Animator getHandleAnimator(View view, float start, float end, boolean isLeft, long durationMs,
-            Interpolator interpolator) {
-        // Note that lerp does allow overshoot, in cases where start and end are outside of [0,1].
-        float scaleStart = MathUtils.lerp(2f, 1f, start);
-        float scaleEnd = MathUtils.lerp(2f, 1f, end);
-        Animator scaleX = ObjectAnimator.ofFloat(view, View.SCALE_X, scaleStart, scaleEnd);
-        Animator scaleY = ObjectAnimator.ofFloat(view, View.SCALE_Y, scaleStart, scaleEnd);
-        float translationStart = MathUtils.lerp(0.2f, 0f, start);
-        float translationEnd = MathUtils.lerp(0.2f, 0f, end);
-        int xDirection = isLeft ? -1 : 1;
-        Animator translateX = ObjectAnimator.ofFloat(view, View.TRANSLATION_X,
-                xDirection * translationStart * view.getWidth(),
-                xDirection * translationEnd * view.getWidth());
-        Animator translateY = ObjectAnimator.ofFloat(view, View.TRANSLATION_Y,
-                translationStart * view.getHeight(), translationEnd * view.getHeight());
-
-        AnimatorSet set = new AnimatorSet();
-        set.play(scaleX).with(scaleY);
-        set.play(scaleX).with(translateX);
-        set.play(scaleX).with(translateY);
-        set.setDuration(durationMs);
-        set.setInterpolator(interpolator);
-        return set;
-    }
-
-    private void fade(View view, boolean fadeIn, boolean isLeft) {
-        if (fadeIn) {
-            view.animate().cancel();
-            view.setAlpha(1f);
-            view.setVisibility(View.VISIBLE);
-
-            // A piecewise spring-like interpolation.
-            // End value in one animator call must match the start value in the next, otherwise
-            // there will be a discontinuity.
-            AnimatorSet anim = new AnimatorSet();
-            Animator first = getHandleAnimator(view, 0, 1.1f, isLeft, 750,
-                    new PathInterpolator(0, 0.45f, .67f, 1f));
-            Interpolator secondInterpolator = new PathInterpolator(0.33f, 0, 0.67f, 1f);
-            Animator second = getHandleAnimator(view, 1.1f, 0.97f, isLeft, 400,
-                    secondInterpolator);
-            Animator third = getHandleAnimator(view, 0.97f, 1.02f, isLeft, 400,
-                    secondInterpolator);
-            Animator fourth = getHandleAnimator(view, 1.02f, 1f, isLeft, 400,
-                    secondInterpolator);
-            anim.play(first).before(second);
-            anim.play(second).before(third);
-            anim.play(third).before(fourth);
-            anim.start();
-        } else {
-            view.animate().cancel();
-            view.animate()
-                    .setInterpolator(new AccelerateInterpolator(1.5f))
-                    .setDuration(250)
-                    .alpha(0f);
-        }
-
-    }
-
-    /**
-     * Controls the visibility of the assist gesture handles.
-     *
-     * @param visible whether the handles should be shown
-     */
-    public void setAssistHintVisible(boolean visible) {
-        if (!mHandler.getLooper().isCurrentThread()) {
-            mHandler.post(() -> setAssistHintVisible(visible));
-            return;
-        }
-
-        if (mAssistHintBlocked && visible) {
-            if (VERBOSE) {
-                Log.v(TAG, "Assist hint blocked, cannot make it visible");
-            }
-            return;
-        }
-
-        if (mOverlay == null || mBottomOverlay == null) {
-            return;
-        }
-
-        if (mAssistHintVisible != visible) {
-            mAssistHintVisible = visible;
-
-            CornerHandleView assistHintTopLeft = mOverlay.findViewById(R.id.assist_hint_left);
-            CornerHandleView assistHintTopRight = mOverlay.findViewById(R.id.assist_hint_right);
-            CornerHandleView assistHintBottomLeft = mBottomOverlay.findViewById(
-                    R.id.assist_hint_left);
-            CornerHandleView assistHintBottomRight = mBottomOverlay.findViewById(
-                    R.id.assist_hint_right);
-
-            switch (mRotation) {
-                case RotationUtils.ROTATION_NONE:
-                    fade(assistHintBottomLeft, mAssistHintVisible, /* isLeft = */ true);
-                    fade(assistHintBottomRight, mAssistHintVisible, /* isLeft = */ false);
-                    break;
-                case RotationUtils.ROTATION_LANDSCAPE:
-                    fade(assistHintTopRight, mAssistHintVisible, /* isLeft = */ true);
-                    fade(assistHintBottomRight, mAssistHintVisible, /* isLeft = */ false);
-                    break;
-                case RotationUtils.ROTATION_SEASCAPE:
-                    fade(assistHintTopLeft, mAssistHintVisible, /* isLeft = */ false);
-                    fade(assistHintBottomLeft, mAssistHintVisible,  /* isLeft = */ true);
-                    break;
-                case RotationUtils.ROTATION_UPSIDE_DOWN:
-                    fade(assistHintTopLeft, mAssistHintVisible, /* isLeft = */ false);
-                    fade(assistHintTopRight, mAssistHintVisible, /* isLeft = */ true);
-                    break;
-            }
-        }
-        updateWindowVisibilities();
-    }
-
-    /**
-     * Prevents the assist hint from becoming visible even if `mAssistHintVisible` is true.
-     */
-    public void setAssistHintBlocked(boolean blocked) {
-        if (!mHandler.getLooper().isCurrentThread()) {
-            mHandler.post(() -> setAssistHintBlocked(blocked));
-            return;
-        }
-
-        mAssistHintBlocked = blocked;
-        if (mAssistHintVisible && mAssistHintBlocked) {
-            hideAssistHandles();
-        }
     }
 
     @VisibleForTesting
@@ -316,15 +147,11 @@
         return thread.getThreadHandler();
     }
 
-    private boolean shouldHostHandles() {
-        return mInGesturalMode;
-    }
-
     private void startOnScreenDecorationsThread() {
         mRotation = RotationUtils.getExactRotation(mContext);
         mWindowManager = mContext.getSystemService(WindowManager.class);
         updateRoundedCornerRadii();
-        if (hasRoundedCorners() || shouldDrawCutout() || shouldHostHandles()) {
+        if (hasRoundedCorners() || shouldDrawCutout()) {
             setupDecorations();
         }
 
@@ -501,26 +328,10 @@
             if (mOverlay != null) {
                 updateLayoutParams();
                 updateViews();
-                if (mAssistHintVisible) {
-                    // If assist handles are visible, hide them without animation and then make them
-                    // show once again (with corrected rotation).
-                    hideAssistHandles();
-                    setAssistHintVisible(true);
-                }
             }
         }
     }
 
-    private void hideAssistHandles() {
-        if (mOverlay != null && mBottomOverlay != null) {
-            mOverlay.findViewById(R.id.assist_hint_left).setVisibility(View.GONE);
-            mOverlay.findViewById(R.id.assist_hint_right).setVisibility(View.GONE);
-            mBottomOverlay.findViewById(R.id.assist_hint_left).setVisibility(View.GONE);
-            mBottomOverlay.findViewById(R.id.assist_hint_right).setVisibility(View.GONE);
-            mAssistHintVisible = false;
-        }
-    }
-
     private void updateRoundedCornerRadii() {
         final int newRoundedDefault = mContext.getResources().getDimensionPixelSize(
                 com.android.internal.R.dimen.rounded_corner_radius);
@@ -569,52 +380,12 @@
             updateView(bottomRight, Gravity.TOP | Gravity.LEFT, 0);
         }
 
-        updateAssistantHandleViews();
         mCutoutTop.setRotation(mRotation);
         mCutoutBottom.setRotation(mRotation);
 
         updateWindowVisibilities();
     }
 
-    private void updateAssistantHandleViews() {
-        View assistHintTopLeft = mOverlay.findViewById(R.id.assist_hint_left);
-        View assistHintTopRight = mOverlay.findViewById(R.id.assist_hint_right);
-        View assistHintBottomLeft = mBottomOverlay.findViewById(R.id.assist_hint_left);
-        View assistHintBottomRight = mBottomOverlay.findViewById(R.id.assist_hint_right);
-
-        final int assistHintVisibility = mAssistHintVisible ? View.VISIBLE : View.INVISIBLE;
-
-        if (mRotation == RotationUtils.ROTATION_NONE) {
-            assistHintTopLeft.setVisibility(View.GONE);
-            assistHintTopRight.setVisibility(View.GONE);
-            assistHintBottomLeft.setVisibility(assistHintVisibility);
-            assistHintBottomRight.setVisibility(assistHintVisibility);
-            updateView(assistHintBottomLeft, Gravity.BOTTOM | Gravity.LEFT, 270);
-            updateView(assistHintBottomRight, Gravity.BOTTOM | Gravity.RIGHT, 180);
-        } else if (mRotation == RotationUtils.ROTATION_LANDSCAPE) {
-            assistHintTopLeft.setVisibility(View.GONE);
-            assistHintTopRight.setVisibility(assistHintVisibility);
-            assistHintBottomLeft.setVisibility(View.GONE);
-            assistHintBottomRight.setVisibility(assistHintVisibility);
-            updateView(assistHintTopRight, Gravity.BOTTOM | Gravity.LEFT, 270);
-            updateView(assistHintBottomRight, Gravity.BOTTOM | Gravity.RIGHT, 180);
-        } else if (mRotation == RotationUtils.ROTATION_UPSIDE_DOWN) {
-            assistHintTopLeft.setVisibility(assistHintVisibility);
-            assistHintTopRight.setVisibility(assistHintVisibility);
-            assistHintBottomLeft.setVisibility(View.GONE);
-            assistHintBottomRight.setVisibility(View.GONE);
-            updateView(assistHintTopLeft, Gravity.BOTTOM | Gravity.LEFT, 270);
-            updateView(assistHintTopRight, Gravity.BOTTOM | Gravity.RIGHT, 180);
-        } else if (mRotation == RotationUtils.ROTATION_SEASCAPE) {
-            assistHintTopLeft.setVisibility(assistHintVisibility);
-            assistHintTopRight.setVisibility(View.GONE);
-            assistHintBottomLeft.setVisibility(assistHintVisibility);
-            assistHintBottomRight.setVisibility(View.GONE);
-            updateView(assistHintTopLeft, Gravity.BOTTOM | Gravity.RIGHT, 180);
-            updateView(assistHintBottomLeft, Gravity.BOTTOM | Gravity.LEFT, 270);
-        }
-    }
-
     private void updateView(View v, int gravity, int rotation) {
         ((FrameLayout.LayoutParams) v.getLayoutParams()).gravity = gravity;
         v.setRotation(rotation);
@@ -629,10 +400,7 @@
         boolean visibleForCutout = shouldDrawCutout()
                 && overlay.findViewById(R.id.display_cutout).getVisibility() == View.VISIBLE;
         boolean visibleForRoundedCorners = hasRoundedCorners();
-        boolean visibleForHandles = overlay.findViewById(R.id.assist_hint_left).getVisibility()
-                == View.VISIBLE || overlay.findViewById(R.id.assist_hint_right).getVisibility()
-                == View.VISIBLE;
-        overlay.setVisibility(visibleForCutout || visibleForRoundedCorners || visibleForHandles
+        overlay.setVisibility(visibleForCutout || visibleForRoundedCorners
                 ? View.VISIBLE : View.GONE);
     }
 
@@ -766,31 +534,6 @@
         view.setLayoutParams(params);
     }
 
-    @Override
-    public void onDarkIntensity(float darkIntensity) {
-        if (!mHandler.getLooper().isCurrentThread()) {
-            mHandler.post(() -> onDarkIntensity(darkIntensity));
-            return;
-        }
-        if (mOverlay != null) {
-            CornerHandleView assistHintTopLeft = mOverlay.findViewById(R.id.assist_hint_left);
-            CornerHandleView assistHintTopRight = mOverlay.findViewById(R.id.assist_hint_right);
-
-            assistHintTopLeft.updateDarkness(darkIntensity);
-            assistHintTopRight.updateDarkness(darkIntensity);
-        }
-
-        if (mBottomOverlay != null) {
-            CornerHandleView assistHintBottomLeft = mBottomOverlay.findViewById(
-                    R.id.assist_hint_left);
-            CornerHandleView assistHintBottomRight = mBottomOverlay.findViewById(
-                    R.id.assist_hint_right);
-
-            assistHintBottomLeft.updateDarkness(darkIntensity);
-            assistHintBottomRight.updateDarkness(darkIntensity);
-        }
-    }
-
     @VisibleForTesting
     static class TunablePaddingTagListener implements FragmentListener {
 
diff --git a/packages/SystemUI/src/com/android/systemui/SystemBars.java b/packages/SystemUI/src/com/android/systemui/SystemBars.java
deleted file mode 100644
index c4c0fd6..0000000
--- a/packages/SystemUI/src/com/android/systemui/SystemBars.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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.systemui;
-
-import android.util.Log;
-
-import com.android.systemui.statusbar.phone.StatusBar;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-
-/**
- * Ensure a single status bar service implementation is running at all times, using the in-process
- * implementation according to the product config.
- */
-public class SystemBars extends SystemUI {
-    private static final String TAG = "SystemBars";
-    private static final boolean DEBUG = false;
-    private static final int WAIT_FOR_BARS_TO_DIE = 500;
-
-    // in-process fallback implementation, per the product config
-    private SystemUI mStatusBar;
-
-    @Override
-    public void start() {
-        if (DEBUG) Log.d(TAG, "start");
-        createStatusBarFromConfig();
-    }
-
-    @Override
-    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        if (mStatusBar != null) {
-            mStatusBar.dump(fd, pw, args);
-        }
-    }
-
-    @Override
-    public void onBootCompleted() {
-        if (mStatusBar != null) {
-            mStatusBar.onBootCompleted();
-        }
-    }
-
-    private void createStatusBarFromConfig() {
-        if (DEBUG) Log.d(TAG, "createStatusBarFromConfig");
-        final String clsName = mContext.getString(R.string.config_statusBarComponent);
-        if (clsName == null || clsName.length() == 0) {
-            throw andLog("No status bar component configured", null);
-        }
-        Class<?> cls = null;
-        try {
-            cls = mContext.getClassLoader().loadClass(clsName);
-        } catch (Throwable t) {
-            throw andLog("Error loading status bar component: " + clsName, t);
-        }
-        try {
-            mStatusBar = (SystemUI) cls.newInstance();
-        } catch (Throwable t) {
-            throw andLog("Error creating status bar component: " + clsName, t);
-        }
-        mStatusBar.mContext = mContext;
-        mStatusBar.mComponents = mComponents;
-        if (mStatusBar instanceof StatusBar) {
-            SystemUIFactory.getInstance().getRootComponent()
-                    .getStatusBarInjector()
-                    .createStatusBar((StatusBar) mStatusBar);
-        }
-        mStatusBar.start();
-        if (DEBUG) Log.d(TAG, "started " + mStatusBar.getClass().getSimpleName());
-    }
-
-    private RuntimeException andLog(String msg, Throwable t) {
-        Log.w(TAG, msg, t);
-        throw new RuntimeException(msg, t);
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIAppComponentFactory.java b/packages/SystemUI/src/com/android/systemui/SystemUIAppComponentFactory.java
index 2c8324c..aa13fa8 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIAppComponentFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIAppComponentFactory.java
@@ -92,6 +92,12 @@
     public Activity instantiateActivityCompat(@NonNull ClassLoader cl, @NonNull String className,
             @Nullable Intent intent)
             throws InstantiationException, IllegalAccessException, ClassNotFoundException {
+        if (mComponentHelper == null) {
+            // This shouldn't happen, but is seen on occasion.
+            // Bug filed against framework to take a look: http://b/141008541
+            SystemUIFactory.getInstance().getRootComponent().inject(
+                    SystemUIAppComponentFactory.this);
+        }
         Activity activity = mComponentHelper.resolveActivity(className);
         if (activity != null) {
             return activity;
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIBinder.java b/packages/SystemUI/src/com/android/systemui/SystemUIBinder.java
index 4531c89..785038f 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIBinder.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIBinder.java
@@ -17,6 +17,10 @@
 package com.android.systemui;
 
 import com.android.systemui.keyguard.KeyguardViewMediator;
+import com.android.systemui.power.PowerUI;
+import com.android.systemui.recents.Recents;
+import com.android.systemui.recents.RecentsModule;
+import com.android.systemui.util.leak.GarbageMonitor;
 
 import dagger.Binds;
 import dagger.Module;
@@ -26,11 +30,29 @@
 /**
  * SystemUI objects that are injectable should go here.
  */
-@Module
+@Module(includes = {RecentsModule.class})
 public abstract class SystemUIBinder {
     /** Inject into KeyguardViewMediator. */
     @Binds
     @IntoMap
     @ClassKey(KeyguardViewMediator.class)
     public abstract SystemUI bindKeyguardViewMediator(KeyguardViewMediator sysui);
+
+    /** Inject into PowerUI. */
+    @Binds
+    @IntoMap
+    @ClassKey(PowerUI.class)
+    public abstract SystemUI bindPowerUI(PowerUI sysui);
+
+    /** Inject into Recents. */
+    @Binds
+    @IntoMap
+    @ClassKey(Recents.class)
+    public abstract SystemUI bindRecents(Recents sysui);
+
+    /** Inject into GarbageMonitor.Service. */
+    @Binds
+    @IntoMap
+    @ClassKey(GarbageMonitor.Service.class)
+    public abstract SystemUI bindGarbageMonitorService(GarbageMonitor.Service service);
 }
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIDefaultModule.java b/packages/SystemUI/src/com/android/systemui/SystemUIDefaultModule.java
index 262b5ec..176bcbf 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIDefaultModule.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIDefaultModule.java
@@ -19,8 +19,6 @@
 import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME;
 import static com.android.systemui.Dependency.LEAK_REPORT_EMAIL_NAME;
 
-import android.content.Context;
-
 import androidx.annotation.Nullable;
 
 import com.android.systemui.dock.DockManager;
@@ -40,6 +38,8 @@
 import dagger.Binds;
 import dagger.Module;
 import dagger.Provides;
+import dagger.multibindings.ClassKey;
+import dagger.multibindings.IntoMap;
 
 /**
  * A dagger module for injecting default implementations of components of System UI that may be
@@ -70,11 +70,13 @@
     abstract NotificationData.KeyguardEnvironment bindKeyguardEnvironment(
             KeyguardEnvironmentImpl keyguardEnvironment);
 
-    @Singleton
-    @Provides
-    static ShadeController provideShadeController(Context context) {
-        return SysUiServiceProvider.getComponent(context, StatusBar.class);
-    }
+    @Binds
+    abstract ShadeController provideShadeController(StatusBar statusBar);
+
+    @Binds
+    @IntoMap
+    @ClassKey(StatusBar.class)
+    public abstract SystemUI providesStatusBar(StatusBar statusBar);
 
     @Singleton
     @Provides
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java b/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
index 8e69318..530dcdc 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
@@ -47,8 +47,7 @@
 import com.android.systemui.statusbar.phone.ScrimState;
 import com.android.systemui.statusbar.phone.StatusBar;
 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.volume.VolumeDialogComponent;
 
 import java.util.function.Consumer;
@@ -136,10 +135,11 @@
             LockPatternUtils lockPatternUtils, ViewGroup container,
             DismissCallbackRegistry dismissCallbackRegistry,
             KeyguardBouncer.BouncerExpansionCallback expansionCallback,
-            FalsingManager falsingManager, KeyguardBypassController bypassController) {
+            KeyguardStateController keyguardStateController, FalsingManager falsingManager,
+            KeyguardBypassController bypassController) {
         return new KeyguardBouncer(context, callback, lockPatternUtils, container,
                 dismissCallbackRegistry, falsingManager,
-                expansionCallback, UnlockMethodCache.getInstance(context),
+                expansionCallback, keyguardStateController,
                 Dependency.get(KeyguardUpdateMonitor.class), bypassController,
                 new Handler(Looper.getMainLooper()));
     }
@@ -149,9 +149,9 @@
             LockscreenWallpaper lockscreenWallpaper,
             TriConsumer<ScrimState, Float, GradientColors> scrimStateListener,
             Consumer<Integer> scrimVisibleListener, DozeParameters dozeParameters,
-            AlarmManager alarmManager, KeyguardMonitor keyguardMonitor) {
+            AlarmManager alarmManager, KeyguardStateController keyguardStateController) {
         return new ScrimController(scrimBehind, scrimInFront, scrimForBubble, scrimStateListener,
-                scrimVisibleListener, dozeParameters, alarmManager, keyguardMonitor);
+                scrimVisibleListener, dozeParameters, alarmManager, keyguardStateController);
     }
 
     public NotificationIconAreaController createNotificationIconAreaController(Context context,
diff --git a/packages/SystemUI/src/com/android/systemui/SystemUIRootComponent.java b/packages/SystemUI/src/com/android/systemui/SystemUIRootComponent.java
index c70b2fc..bcbe672 100644
--- a/packages/SystemUI/src/com/android/systemui/SystemUIRootComponent.java
+++ b/packages/SystemUI/src/com/android/systemui/SystemUIRootComponent.java
@@ -23,7 +23,6 @@
 import com.android.systemui.fragments.FragmentService;
 import com.android.systemui.statusbar.phone.StatusBar;
 import com.android.systemui.util.InjectionInflationController;
-import com.android.systemui.util.leak.GarbageMonitor;
 
 import javax.inject.Named;
 import javax.inject.Singleton;
@@ -43,7 +42,7 @@
 public interface SystemUIRootComponent {
 
     /**
-     * Creates a GarbageMonitor.
+     * Creates a ContextComponentHelper.
      */
     @Singleton
     ContextComponentHelper getContextComponentHelper();
@@ -72,12 +71,6 @@
     InjectionInflationController.ViewCreator createViewCreator();
 
     /**
-     * Creates a GarbageMonitor.
-     */
-    @Singleton
-    GarbageMonitor createGarbageMonitor();
-
-    /**
      * Whether notification long press is allowed.
      */
     @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME)
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java
index 9bdfa03..4516996 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleBehaviorController.java
@@ -32,7 +32,6 @@
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.DumpController;
 import com.android.systemui.Dumpable;
-import com.android.systemui.ScreenDecorations;
 import com.android.systemui.shared.system.QuickStepContract;
 import com.android.systemui.statusbar.phone.NavigationModeController;
 
@@ -71,7 +70,7 @@
     private final Handler mHandler;
     private final Runnable mHideHandles = this::hideHandles;
     private final Runnable mShowAndGo = this::showAndGoInternal;
-    private final Provider<ScreenDecorations> mScreenDecorations;
+    private final Provider<AssistHandleViewController> mAssistHandleViewController;
     private final PhenotypeHelper mPhenotypeHelper;
     private final Map<AssistHandleBehavior, BehaviorController> mBehaviorMap;
 
@@ -90,7 +89,7 @@
             Context context,
             AssistUtils assistUtils,
             @Named(ASSIST_HANDLE_THREAD_NAME) Handler handler,
-            Provider<ScreenDecorations> screenDecorations,
+            Provider<AssistHandleViewController> assistHandleViewController,
             PhenotypeHelper phenotypeHelper,
             Map<AssistHandleBehavior, BehaviorController> behaviorMap,
             NavigationModeController navigationModeController,
@@ -98,7 +97,7 @@
         mContext = context;
         mAssistUtils = assistUtils;
         mHandler = handler;
-        mScreenDecorations = screenDecorations;
+        mAssistHandleViewController = assistHandleViewController;
         mPhenotypeHelper = phenotypeHelper;
         mBehaviorMap = behaviorMap;
 
@@ -193,7 +192,7 @@
         try {
             setBehavior(AssistHandleBehavior.valueOf(behavior));
         } catch (IllegalArgumentException | NullPointerException e) {
-            Log.e(TAG, "Invalid behavior: " + behavior, e);
+            Log.e(TAG, "Invalid behavior: " + behavior);
         }
     }
 
@@ -229,12 +228,13 @@
         }
 
         if (handlesUnblocked(ignoreThreshold)) {
-            ScreenDecorations screenDecorations = mScreenDecorations.get();
-            if (screenDecorations == null) {
-                Log.w(TAG, "Couldn't show handles, ScreenDecorations unavailable");
+            mHandlesShowing = true;
+            AssistHandleViewController assistHandleViewController =
+                    mAssistHandleViewController.get();
+            if (assistHandleViewController == null) {
+                Log.w(TAG, "Couldn't show handles, AssistHandleViewController unavailable");
             } else {
-                mHandlesShowing = true;
-                screenDecorations.setAssistHintVisible(true);
+                assistHandleViewController.setAssistHintVisible(true);
             }
         }
     }
@@ -244,13 +244,14 @@
             return;
         }
 
-        ScreenDecorations screenDecorations = mScreenDecorations.get();
-        if (screenDecorations == null) {
-            Log.w(TAG, "Couldn't hide handles, ScreenDecorations unavailable");
+        mHandlesShowing = false;
+        mHandlesLastHiddenAt = SystemClock.elapsedRealtime();
+        AssistHandleViewController assistHandleViewController =
+                mAssistHandleViewController.get();
+        if (assistHandleViewController == null) {
+            Log.w(TAG, "Couldn't show handles, AssistHandleViewController unavailable");
         } else {
-            mHandlesShowing = false;
-            mHandlesLastHiddenAt = SystemClock.elapsedRealtime();
-            screenDecorations.setAssistHintVisible(false);
+            assistHandleViewController.setAssistHintVisible(false);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleViewController.java b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleViewController.java
new file mode 100644
index 0000000..5010f31
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleViewController.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2019 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.assist;
+
+import android.animation.Animator;
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
+import android.os.Handler;
+import android.util.Log;
+import android.util.MathUtils;
+import android.view.View;
+import android.view.animation.AccelerateInterpolator;
+import android.view.animation.Interpolator;
+import android.view.animation.PathInterpolator;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.systemui.CornerHandleView;
+import com.android.systemui.R;
+import com.android.systemui.statusbar.phone.NavigationBarTransitions;
+
+/**
+ * A class for managing Assistant handle show, hide and animation.
+ */
+public class AssistHandleViewController implements NavigationBarTransitions.DarkIntensityListener {
+
+    private static final boolean DEBUG = false;
+    private static final String TAG = "AssistHandleViewController";
+
+    private Handler mHandler;
+    private CornerHandleView mAssistHintLeft;
+    private CornerHandleView mAssistHintRight;
+    private int mBottomOffset;
+
+    @VisibleForTesting
+    boolean mAssistHintVisible;
+    @VisibleForTesting
+    boolean mAssistHintBlocked = false;
+
+    public AssistHandleViewController(Handler handler, View navBar) {
+        mHandler = handler;
+        mAssistHintLeft = navBar.findViewById(R.id.assist_hint_left);
+        mAssistHintRight = navBar.findViewById(R.id.assist_hint_right);
+    }
+
+    @Override
+    public void onDarkIntensity(float darkIntensity) {
+        mAssistHintLeft.updateDarkness(darkIntensity);
+        mAssistHintRight.updateDarkness(darkIntensity);
+    }
+
+    /**
+     * Set the bottom offset.
+     *
+     * @param bottomOffset the bottom offset to translate.
+     */
+    public void setBottomOffset(int bottomOffset) {
+        if (mBottomOffset != bottomOffset) {
+            mBottomOffset = bottomOffset;
+            if (mAssistHintVisible) {
+                // If assist handles are visible, hide them without animation and then make them
+                // show once again (with corrected bottom offset).
+                hideAssistHandles();
+                setAssistHintVisible(true);
+            }
+        }
+    }
+
+    /**
+     * Controls the visibility of the assist gesture handles.
+     *
+     * @param visible whether the handles should be shown
+     */
+    public void setAssistHintVisible(boolean visible) {
+        if (!mHandler.getLooper().isCurrentThread()) {
+            mHandler.post(() -> setAssistHintVisible(visible));
+            return;
+        }
+
+        if (mAssistHintBlocked && visible) {
+            if (DEBUG) {
+                Log.v(TAG, "Assist hint blocked, cannot make it visible");
+            }
+            return;
+        }
+
+        if (mAssistHintVisible != visible) {
+            mAssistHintVisible = visible;
+            fade(mAssistHintLeft, mAssistHintVisible, /* isLeft = */ true);
+            fade(mAssistHintRight, mAssistHintVisible, /* isLeft = */ false);
+        }
+    }
+
+    /**
+     * Prevents the assist hint from becoming visible even if `mAssistHintVisible` is true.
+     */
+    public void setAssistHintBlocked(boolean blocked) {
+        if (!mHandler.getLooper().isCurrentThread()) {
+            mHandler.post(() -> setAssistHintBlocked(blocked));
+            return;
+        }
+
+        mAssistHintBlocked = blocked;
+        if (mAssistHintVisible && mAssistHintBlocked) {
+            hideAssistHandles();
+        }
+    }
+
+    private void hideAssistHandles() {
+        mAssistHintLeft.setVisibility(View.GONE);
+        mAssistHintRight.setVisibility(View.GONE);
+        mAssistHintVisible = false;
+    }
+
+    /**
+     * Returns an animator that animates the given view from start to end over durationMs. Start and
+     * end represent total animation progress: 0 is the start, 1 is the end, 1.1 would be an
+     * overshoot.
+     */
+    Animator getHandleAnimator(View view, float start, float end, boolean isLeft, long durationMs,
+            Interpolator interpolator) {
+        // Note that lerp does allow overshoot, in cases where start and end are outside of [0,1].
+        float scaleStart = MathUtils.lerp(2f, 1f, start);
+        float scaleEnd = MathUtils.lerp(2f, 1f, end);
+        Animator scaleX = ObjectAnimator.ofFloat(view, View.SCALE_X, scaleStart, scaleEnd);
+        Animator scaleY = ObjectAnimator.ofFloat(view, View.SCALE_Y, scaleStart, scaleEnd);
+        float translationStart = MathUtils.lerp(0.2f, 0f, start);
+        float translationEnd = MathUtils.lerp(0.2f, 0f, end);
+        int xDirection = isLeft ? -1 : 1;
+        Animator translateX = ObjectAnimator.ofFloat(view, View.TRANSLATION_X,
+                xDirection * translationStart * view.getWidth(),
+                xDirection * translationEnd * view.getWidth());
+        Animator translateY = ObjectAnimator.ofFloat(view, View.TRANSLATION_Y,
+                translationStart * view.getHeight() + mBottomOffset,
+                translationEnd * view.getHeight() + mBottomOffset);
+
+        AnimatorSet set = new AnimatorSet();
+        set.play(scaleX).with(scaleY);
+        set.play(scaleX).with(translateX);
+        set.play(scaleX).with(translateY);
+        set.setDuration(durationMs);
+        set.setInterpolator(interpolator);
+        return set;
+    }
+
+    private void fade(View view, boolean fadeIn, boolean isLeft) {
+        if (fadeIn) {
+            view.animate().cancel();
+            view.setAlpha(1f);
+            view.setVisibility(View.VISIBLE);
+
+            // A piecewise spring-like interpolation.
+            // End value in one animator call must match the start value in the next, otherwise
+            // there will be a discontinuity.
+            AnimatorSet anim = new AnimatorSet();
+            Animator first = getHandleAnimator(view, 0, 1.1f, isLeft, 750,
+                    new PathInterpolator(0, 0.45f, .67f, 1f));
+            Interpolator secondInterpolator = new PathInterpolator(0.33f, 0, 0.67f, 1f);
+            Animator second = getHandleAnimator(view, 1.1f, 0.97f, isLeft, 400,
+                    secondInterpolator);
+            Animator third = getHandleAnimator(view, 0.97f, 1.02f, isLeft, 400,
+                    secondInterpolator);
+            Animator fourth = getHandleAnimator(view, 1.02f, 1f, isLeft, 400,
+                    secondInterpolator);
+            anim.play(first).before(second);
+            anim.play(second).before(third);
+            anim.play(third).before(fourth);
+            anim.start();
+        } else {
+            view.animate().cancel();
+            view.animate()
+                .setInterpolator(new AccelerateInterpolator(1.5f))
+                .setDuration(250)
+                .alpha(0f);
+        }
+
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java b/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java
index 2a82d21..739eade 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistModule.java
@@ -24,8 +24,7 @@
 import androidx.slice.Clock;
 
 import com.android.internal.app.AssistUtils;
-import com.android.systemui.ScreenDecorations;
-import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.statusbar.NavigationBarController;
 
 import java.util.EnumMap;
 import java.util.Map;
@@ -69,8 +68,9 @@
     }
 
     @Provides
-    static ScreenDecorations provideScreenDecorations(Context context) {
-        return SysUiServiceProvider.getComponent(context, ScreenDecorations.class);
+    static AssistHandleViewController provideAssistHandleViewController(
+            NavigationBarController navigationBarController) {
+        return navigationBarController.getAssistHandlerViewController();
     }
 
     @Provides
diff --git a/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java b/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
index 0c4f051..9958124 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/ui/DefaultUiController.java
@@ -17,6 +17,7 @@
 package com.android.systemui.assist.ui;
 
 import static com.android.systemui.assist.AssistManager.DISMISS_REASON_INVOCATION_CANCELLED;
+import static com.android.systemui.assist.AssistManager.INVOCATION_TYPE_GESTURE;
 
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
@@ -24,6 +25,7 @@
 import android.content.Context;
 import android.graphics.PixelFormat;
 import android.metrics.LogMaker;
+import android.os.Build;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.Gravity;
@@ -36,9 +38,11 @@
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
-import com.android.systemui.ScreenDecorations;
-import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.assist.AssistHandleViewController;
 import com.android.systemui.assist.AssistManager;
+import com.android.systemui.statusbar.NavigationBarController;
+
+import java.util.Locale;
 
 /**
  * Default UiController implementation. Shows white edge lights along the bottom of the phone,
@@ -50,6 +54,9 @@
 
     private static final long ANIM_DURATION_MS = 200;
 
+    private static final boolean VERBOSE = Build.TYPE.toLowerCase(Locale.ROOT).contains("debug")
+            || Build.TYPE.toLowerCase(Locale.ROOT).equals("eng");
+
     protected final FrameLayout mRoot;
     protected InvocationLightsView mInvocationLightsView;
 
@@ -114,6 +121,7 @@
     @Override // AssistManager.UiController
     public void onGestureCompletion(float velocity) {
         animateInvocationCompletion(AssistManager.INVOCATION_TYPE_GESTURE, velocity);
+        logInvocationProgressMetrics(INVOCATION_TYPE_GESTURE, 1, mInvocationInProgress);
     }
 
     @Override // AssistManager.UiController
@@ -127,16 +135,28 @@
         updateAssistHandleVisibility();
     }
 
-    protected static void logInvocationProgressMetrics(
+    protected void logInvocationProgressMetrics(
             int type, float progress, boolean invocationWasInProgress) {
         // Logs assistant invocation start.
+        if (progress == 1f) {
+            if (VERBOSE) {
+                Log.v(TAG, "Invocation complete: type=" + type);
+            }
+        }
         if (!invocationWasInProgress && progress > 0.f) {
+            if (VERBOSE) {
+                Log.v(TAG, "Invocation started: type=" + type);
+            }
             MetricsLogger.action(new LogMaker(MetricsEvent.ASSISTANT)
                     .setType(MetricsEvent.TYPE_ACTION)
                     .setSubtype(Dependency.get(AssistManager.class).toLoggingSubType(type)));
         }
         // Logs assistant invocation cancelled.
-        if (invocationWasInProgress && progress == 0f) {
+        if ((mInvocationAnimator == null || !mInvocationAnimator.isRunning())
+                && invocationWasInProgress && progress == 0f) {
+            if (VERBOSE) {
+                Log.v(TAG, "Invocation cancelled: type=" + type);
+            }
             MetricsLogger.action(new LogMaker(MetricsEvent.ASSISTANT)
                     .setType(MetricsEvent.TYPE_DISMISS)
                     .setSubtype(DISMISS_REASON_INVOCATION_CANCELLED));
@@ -144,9 +164,11 @@
     }
 
     private void updateAssistHandleVisibility() {
-        ScreenDecorations decorations = SysUiServiceProvider.getComponent(mRoot.getContext(),
-                ScreenDecorations.class);
-        decorations.setAssistHintBlocked(mInvocationInProgress);
+        AssistHandleViewController controller = Dependency.get(NavigationBarController.class)
+                .getAssistHandlerViewController();
+        if (controller != null) {
+            controller.setAssistHintBlocked(mInvocationInProgress);
+        }
     }
 
     private void attach() {
diff --git a/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java b/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java
index 9ae02c5..baa3a4a 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java
@@ -16,6 +16,8 @@
 
 package com.android.systemui.assist.ui;
 
+import android.util.Log;
+
 import androidx.annotation.ColorInt;
 
 /**
@@ -29,9 +31,12 @@
  * counter-clockwise.
  */
 public final class EdgeLight {
+
+    private static final String TAG = "EdgeLight";
+
     @ColorInt
     private int mColor;
-    private float mOffset;
+    private float mStart;
     private float mLength;
 
     /** Copies a list of EdgeLights. */
@@ -45,13 +50,13 @@
 
     public EdgeLight(@ColorInt int color, float offset, float length) {
         mColor = color;
-        mOffset = offset;
+        mStart = offset;
         mLength = length;
     }
 
     public EdgeLight(EdgeLight sourceLight) {
         mColor = sourceLight.getColor();
-        mOffset = sourceLight.getOffset();
+        mStart = sourceLight.getStart();
         mLength = sourceLight.getLength();
     }
 
@@ -77,23 +82,41 @@
     }
 
     /**
-     * Returns the current offset, in units of the total device perimeter and measured from the
-     * bottom-left corner (see class description).
+     * Sets the endpoints of the edge light, both measured from the bottom-left corner (see class
+     * description). This is a convenience method to avoid separate setStart and setLength calls.
      */
-    public float getOffset() {
-        return mOffset;
+    public void setEndpoints(float start, float end) {
+        if (start > end) {
+            Log.e(TAG, String.format("Endpoint must be >= start (add 1 if necessary). Got [%f, %f]",
+                    start, end));
+            return;
+        }
+        mStart = start;
+        mLength = end - start;
+    }
+
+    /**
+     * Returns the current starting position, in units of the total device perimeter and measured
+     * from the bottom-left corner (see class description).
+     */
+    public float getStart() {
+        return mStart;
     }
 
     /**
      * Sets the current offset, in units of the total device perimeter and measured from the
      * bottom-left corner (see class description).
      */
-    public void setOffset(float offset) {
-        mOffset = offset;
+    public void setStart(float start) {
+        mStart = start;
+    }
+
+    public float getEnd() {
+        return mStart + mLength;
     }
 
     /** Returns the center, measured from the bottom-left corner (see class description). */
     public float getCenter() {
-        return mOffset + (mLength / 2.f);
+        return mStart + (mLength / 2.f);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java b/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java
index bb3bd78..570b911 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java
@@ -140,10 +140,10 @@
             float rightStart = mGuide.getRegionWidth(PerimeterPathGuide.Region.BOTTOM)
                     + (cornerLengthNormalized - arcOffsetNormalized) * (1 - progress);
 
-            setLight(0, leftStart, lightLength);
-            setLight(1, leftStart + lightLength, lightLength);
-            setLight(2, rightStart - (lightLength * 2), lightLength);
-            setLight(3, rightStart - lightLength, lightLength);
+            setLight(0, leftStart, leftStart + lightLength);
+            setLight(1, leftStart + lightLength, leftStart + lightLength * 2);
+            setLight(2, rightStart - (lightLength * 2), rightStart - lightLength);
+            setLight(3, rightStart - lightLength, rightStart);
             setVisibility(View.VISIBLE);
         }
         invalidate();
@@ -155,7 +155,7 @@
     public void hide() {
         setVisibility(GONE);
         for (EdgeLight light : mAssistInvocationLights) {
-            light.setLength(0);
+            light.setEndpoints(0, 0);
         }
         attemptUnregisterNavBarListener();
     }
@@ -235,12 +235,11 @@
         }
     }
 
-    protected void setLight(int index, float offset, float length) {
+    protected void setLight(int index, float start, float end) {
         if (index < 0 || index >= 4) {
             Log.w(TAG, "invalid invocation light index: " + index);
         }
-        mAssistInvocationLights.get(index).setOffset(offset);
-        mAssistInvocationLights.get(index).setLength(length);
+        mAssistInvocationLights.get(index).setEndpoints(start, end);
     }
 
     /**
@@ -268,9 +267,11 @@
     }
 
     private void renderLight(EdgeLight light, Canvas canvas) {
-        mGuide.strokeSegment(mPath, light.getOffset(), light.getOffset() + light.getLength());
-        mPaint.setColor(light.getColor());
-        canvas.drawPath(mPath, mPaint);
+        if (light.getLength() > 0) {
+            mGuide.strokeSegment(mPath, light.getStart(), light.getStart() + light.getLength());
+            mPaint.setColor(light.getColor());
+            canvas.drawPath(mPath, mPaint);
+        }
     }
 
     private void attemptRegisterNavBarListener() {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java
index 73bbce9..d20cd72 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java
@@ -16,8 +16,6 @@
 
 package com.android.systemui.biometrics;
 
-import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE;
-
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
 import android.animation.AnimatorSet;
@@ -25,6 +23,7 @@
 import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.app.admin.DevicePolicyManager;
 import android.content.Context;
 import android.hardware.biometrics.BiometricPrompt;
 import android.os.Bundle;
@@ -34,7 +33,7 @@
 import android.util.AttributeSet;
 import android.util.Log;
 import android.view.View;
-import android.view.accessibility.AccessibilityEvent;
+import android.view.ViewGroup;
 import android.view.accessibility.AccessibilityManager;
 import android.widget.Button;
 import android.widget.ImageView;
@@ -42,10 +41,13 @@
 import android.widget.TextView;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.widget.LockPatternUtils;
 import com.android.systemui.R;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * Contains the Biometric views (title, subtitle, icon, buttons, etc) and its controllers.
@@ -97,6 +99,7 @@
         int ACTION_BUTTON_NEGATIVE = 3;
         int ACTION_BUTTON_TRY_AGAIN = 4;
         int ACTION_ERROR = 5;
+        int ACTION_USE_DEVICE_CREDENTIAL = 6;
 
         /**
          * When an action has occurred. The caller will only invoke this when the callback should
@@ -145,6 +148,14 @@
         public int getDelayAfterError() {
             return BiometricPrompt.HIDE_DIALOG_DELAY;
         }
+
+        public int getMediumToLargeAnimationDurationMs() {
+            return AuthDialog.ANIMATE_MEDIUM_TO_LARGE_DURATION_MS;
+        }
+
+        public int getAnimateCredentialStartDelayMs() {
+            return AuthDialog.ANIMATE_CREDENTIAL_START_DELAY_MS;
+        }
     }
 
     private final Injector mInjector;
@@ -154,8 +165,9 @@
     private final int mTextColorHint;
 
     private AuthPanelController mPanelController;
-    private Bundle mBundle;
+    private Bundle mBiometricPromptBundle;
     private boolean mRequireConfirmation;
+    private int mUserId;
     @AuthDialog.DialogSize int mSize = AuthDialog.SIZE_UNKNOWN;
 
     private TextView mTitleView;
@@ -212,6 +224,9 @@
         } else if (mSize == AuthDialog.SIZE_SMALL) {
             Log.w(TAG, "Ignoring background click during small dialog");
             return;
+        } else if (mSize == AuthDialog.SIZE_LARGE) {
+            Log.w(TAG, "Ignoring background click during large dialog");
+            return;
         }
         mCallback.onAction(Callback.ACTION_USER_CANCELED);
     };
@@ -256,7 +271,7 @@
     }
 
     public void setBiometricPromptBundle(Bundle bundle) {
-        mBundle = bundle;
+        mBiometricPromptBundle = bundle;
     }
 
     public void setCallback(Callback callback) {
@@ -267,6 +282,10 @@
         backgroundView.setOnClickListener(mBackgroundClickListener);
     }
 
+    public void setUserId(int userId) {
+        mUserId = userId;
+    }
+
     public void setRequireConfirmation(boolean requireConfirmation) {
         mRequireConfirmation = requireConfirmation;
     }
@@ -287,7 +306,7 @@
 
             final int newHeight = mIconView.getHeight() + 2 * (int) iconPadding;
             mPanelController.updateForContentDimensions(mMediumWidth, newHeight,
-                    false /* animate */);
+                    0 /* animateDurationMs */);
 
             mSize = newSize;
         } else if (mSize == AuthDialog.SIZE_SMALL && newSize == AuthDialog.SIZE_MEDIUM) {
@@ -305,10 +324,8 @@
 
             // Animate the text
             final ValueAnimator opacityAnimator = ValueAnimator.ofFloat(0, 1);
-            opacityAnimator.setDuration(AuthDialog.ANIMATE_DURATION_MS);
             opacityAnimator.addUpdateListener((animation) -> {
                 final float opacity = (float) animation.getAnimatedValue();
-
                 mTitleView.setAlpha(opacity);
                 mIndicatorView.setAlpha(opacity);
                 mNegativeButton.setAlpha(opacity);
@@ -324,7 +341,7 @@
 
             // Choreograph together
             final AnimatorSet as = new AnimatorSet();
-            as.setDuration(AuthDialog.ANIMATE_DURATION_MS);
+            as.setDuration(AuthDialog.ANIMATE_SMALL_TO_MEDIUM_DURATION_MS);
             as.addListener(new AnimatorListenerAdapter() {
                 @Override
                 public void onAnimationStart(Animator animation) {
@@ -355,11 +372,73 @@
             as.start();
             // Animate the panel
             mPanelController.updateForContentDimensions(mMediumWidth, mMediumHeight,
-                    true /* animate */);
+                    AuthDialog.ANIMATE_SMALL_TO_MEDIUM_DURATION_MS);
         } else if (newSize == AuthDialog.SIZE_MEDIUM) {
             mPanelController.updateForContentDimensions(mMediumWidth, mMediumHeight,
-                    false /* animate */);
+                    0 /* animateDurationMs */);
             mSize = newSize;
+        } else if (newSize == AuthDialog.SIZE_LARGE) {
+            final boolean isManagedProfile = Utils.isManagedProfile(mContext, mUserId);
+
+            // If it's a managed profile, animate the contents and panel down, since the credential
+            // contents will be shown on the same "layer" as the background. If it's not a managed
+            // profile, animate the contents up and expand the panel to full-screen - the credential
+            // contents will be shown on the same "layer" as the panel.
+            final float translationY = isManagedProfile ?
+                    -getResources().getDimension(
+                            R.dimen.biometric_dialog_animation_translation_offset)
+                    : getResources().getDimension(
+                            R.dimen.biometric_dialog_medium_to_large_translation_offset);
+            final AuthBiometricView biometricView = this;
+
+            // Translate at full duration
+            final ValueAnimator translationAnimator = ValueAnimator.ofFloat(
+                    biometricView.getY(), biometricView.getY() - translationY);
+            translationAnimator.setDuration(mInjector.getMediumToLargeAnimationDurationMs());
+            translationAnimator.addUpdateListener((animation) -> {
+                final float translation = (float) animation.getAnimatedValue();
+                biometricView.setTranslationY(translation);
+            });
+            translationAnimator.addListener(new AnimatorListenerAdapter() {
+                @Override
+                public void onAnimationEnd(Animator animation) {
+                    super.onAnimationEnd(animation);
+                    if (biometricView.getParent() != null) {
+                        ((ViewGroup) biometricView.getParent()).removeView(biometricView);
+                    }
+                    mSize = newSize;
+                }
+            });
+
+            // Opacity to 0 in half duration
+            final ValueAnimator opacityAnimator = ValueAnimator.ofFloat(1, 0);
+            opacityAnimator.setDuration(mInjector.getMediumToLargeAnimationDurationMs() / 2);
+            opacityAnimator.addUpdateListener((animation) -> {
+                final float opacity = (float) animation.getAnimatedValue();
+                biometricView.setAlpha(opacity);
+            });
+
+            if (!isManagedProfile) {
+                mPanelController.setUseFullScreen(true);
+                mPanelController.updateForContentDimensions(
+                        mPanelController.getContainerWidth(),
+                        mPanelController.getContainerHeight(),
+                        mInjector.getMediumToLargeAnimationDurationMs());
+            }
+
+            // Start the animations together
+            AnimatorSet as = new AnimatorSet();
+            List<Animator> animators = new ArrayList<>();
+            animators.add(translationAnimator);
+            animators.add(opacityAnimator);
+            if (isManagedProfile) {
+                animators.add(mPanelController.getTranslationAnimator(translationY));
+                animators.add(mPanelController.getAlphaAnimator(0));
+            }
+            as.playTogether(animators);
+            as.setDuration(isManagedProfile ? mInjector.getMediumToLargeAnimationDurationMs()
+                    : mInjector.getMediumToLargeAnimationDurationMs() * 2 / 3);
+            as.start();
         } else {
             Log.e(TAG, "Unknown transition from: " + mSize + " to: " + newSize);
         }
@@ -528,7 +607,11 @@
             if (mState == STATE_PENDING_CONFIRMATION) {
                 mCallback.onAction(Callback.ACTION_USER_CANCELED);
             } else {
-                mCallback.onAction(Callback.ACTION_BUTTON_NEGATIVE);
+                if (isDeviceCredentialAllowed()) {
+                    startTransitionToCredentialUI();
+                } else {
+                    mCallback.onAction(Callback.ACTION_BUTTON_NEGATIVE);
+                }
             }
         });
 
@@ -544,6 +627,16 @@
         });
     }
 
+    /**
+     * Kicks off the animation process and invokes the callback.
+     */
+    void startTransitionToCredentialUI() {
+        updateSize(AuthDialog.SIZE_LARGE);
+        mHandler.postDelayed(() -> {
+            mCallback.onAction(Callback.ACTION_USE_DEVICE_CREDENTIAL);
+        }, mInjector.getAnimateCredentialStartDelayMs());
+    }
+
     @Override
     protected void onAttachedToWindow() {
         super.onAttachedToWindow();
@@ -556,11 +649,37 @@
      */
     @VisibleForTesting
     void onAttachedToWindowInternal() {
-        setText(mTitleView, mBundle.getString(BiometricPrompt.KEY_TITLE));
-        setText(mNegativeButton, mBundle.getString(BiometricPrompt.KEY_NEGATIVE_TEXT));
+        setText(mTitleView, mBiometricPromptBundle.getString(BiometricPrompt.KEY_TITLE));
 
-        setTextOrHide(mSubtitleView, mBundle.getString(BiometricPrompt.KEY_SUBTITLE));
-        setTextOrHide(mDescriptionView, mBundle.getString(BiometricPrompt.KEY_DESCRIPTION));
+        final String negativeText;
+        if (isDeviceCredentialAllowed()) {
+
+            final @Utils.CredentialType int credentialType =
+                    Utils.getCredentialType(mContext, mUserId);
+            switch(credentialType) {
+                case Utils.CREDENTIAL_PIN:
+                    negativeText = getResources().getString(R.string.biometric_dialog_use_pin);
+                    break;
+                case Utils.CREDENTIAL_PATTERN:
+                    negativeText = getResources().getString(R.string.biometric_dialog_use_pattern);
+                    break;
+                case Utils.CREDENTIAL_PASSWORD:
+                    negativeText = getResources().getString(R.string.biometric_dialog_use_password);
+                    break;
+                default:
+                    negativeText = getResources().getString(R.string.biometric_dialog_use_password);
+                    break;
+            }
+
+        } else {
+            negativeText = mBiometricPromptBundle.getString(BiometricPrompt.KEY_NEGATIVE_TEXT);
+        }
+        setText(mNegativeButton, negativeText);
+
+        setTextOrHide(mSubtitleView,
+                mBiometricPromptBundle.getString(BiometricPrompt.KEY_SUBTITLE));
+        setTextOrHide(mDescriptionView,
+                mBiometricPromptBundle.getString(BiometricPrompt.KEY_DESCRIPTION));
 
         if (mSavedState == null) {
             updateState(STATE_AUTHENTICATING_ANIMATING_IN);
@@ -655,4 +774,8 @@
             }
         }
     }
+
+    private boolean isDeviceCredentialAllowed() {
+        return Utils.isDeviceCredentialAllowed(mBiometricPromptBundle);
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
index 6555c75..a9359d4 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
@@ -24,7 +24,9 @@
 import android.graphics.PixelFormat;
 import android.graphics.PorterDuff;
 import android.graphics.drawable.Drawable;
+import android.hardware.biometrics.Authenticator;
 import android.hardware.biometrics.BiometricAuthenticator;
+import android.hardware.biometrics.BiometricPrompt;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.IBinder;
@@ -36,6 +38,7 @@
 import android.view.ViewGroup;
 import android.view.WindowManager;
 import android.view.animation.Interpolator;
+import android.widget.FrameLayout;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 import android.widget.ScrollView;
@@ -72,17 +75,20 @@
     @interface ContainerState {}
 
     final Config mConfig;
+    private final Injector mInjector;
     private final IBinder mWindowToken = new Binder();
     private final WindowManager mWindowManager;
     private final AuthPanelController mPanelController;
     private final Interpolator mLinearOutSlowIn;
     @VisibleForTesting final BiometricCallback mBiometricCallback;
+    private final CredentialCallback mCredentialCallback;
 
-    private final ViewGroup mContainerView;
-    private final AuthBiometricView mBiometricView;
+    @VisibleForTesting final FrameLayout mFrameLayout;
+    @VisibleForTesting @Nullable AuthBiometricView mBiometricView;
+    @VisibleForTesting @Nullable AuthCredentialView mCredentialView;
 
     private final ImageView mBackgroundView;
-    private final ScrollView mScrollView;
+    @VisibleForTesting final ScrollView mBiometricScrollView;
     private final View mPanelView;
 
     private final float mTranslationY;
@@ -145,7 +151,31 @@
 
         public AuthContainerView build(int modalityMask) {
             mConfig.mModalityMask = modalityMask;
-            return new AuthContainerView(mConfig);
+            return new AuthContainerView(mConfig, new Injector());
+        }
+    }
+
+    public static class Injector {
+        ScrollView getBiometricScrollView(FrameLayout parent) {
+            return parent.findViewById(R.id.biometric_scrollview);
+        }
+
+        FrameLayout inflateContainerView(LayoutInflater factory, ViewGroup root) {
+            return (FrameLayout) factory.inflate(
+                    R.layout.auth_container_view, root, false /* attachToRoot */);
+        }
+
+        AuthPanelController getPanelController(Context context, View panelView,
+                boolean isManagedProfile) {
+            return new AuthPanelController(context, panelView, isManagedProfile);
+        }
+
+        ImageView getBackgroundView(FrameLayout parent) {
+            return parent.findViewById(R.id.background);
+        }
+
+        View getPanelView(FrameLayout parent) {
+            return parent.findViewById(R.id.panel);
         }
     }
 
@@ -155,7 +185,7 @@
         public void onAction(int action) {
             switch (action) {
                 case AuthBiometricView.Callback.ACTION_AUTHENTICATED:
-                    animateAway(AuthDialogCallback.DISMISSED_AUTHENTICATED);
+                    animateAway(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED);
                     break;
                 case AuthBiometricView.Callback.ACTION_USER_CANCELED:
                     animateAway(AuthDialogCallback.DISMISSED_USER_CANCELED);
@@ -169,17 +199,30 @@
                 case AuthBiometricView.Callback.ACTION_ERROR:
                     animateAway(AuthDialogCallback.DISMISSED_ERROR);
                     break;
+                case AuthBiometricView.Callback.ACTION_USE_DEVICE_CREDENTIAL:
+                    mConfig.mCallback.onDeviceCredentialPressed();
+                    addCredentialView(false /* animatePanel */, true /* animateContents */);
+                    break;
                 default:
                     Log.e(TAG, "Unhandled action: " + action);
             }
         }
     }
 
+    final class CredentialCallback implements AuthCredentialView.Callback {
+        @Override
+        public void onCredentialMatched() {
+            animateAway(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED);
+        }
+    }
+
     @VisibleForTesting
-    AuthContainerView(Config config) {
+    AuthContainerView(Config config, Injector injector) {
         super(config.mContext);
 
         mConfig = config;
+        mInjector = injector;
+
         mWindowManager = mContext.getSystemService(WindowManager.class);
         mWakefulnessLifecycle = Dependency.get(WakefulnessLifecycle.class);
 
@@ -187,51 +230,48 @@
                 .getDimension(R.dimen.biometric_dialog_animation_translation_offset);
         mLinearOutSlowIn = Interpolators.LINEAR_OUT_SLOW_IN;
         mBiometricCallback = new BiometricCallback();
+        mCredentialCallback = new CredentialCallback();
 
         final LayoutInflater factory = LayoutInflater.from(mContext);
-        mContainerView = (ViewGroup) factory.inflate(
-                R.layout.auth_container_view, this, false /* attachToRoot */);
+        mFrameLayout = mInjector.inflateContainerView(factory, this);
 
-        mPanelView = mContainerView.findViewById(R.id.panel);
-        mPanelController = new AuthPanelController(mContext, mPanelView);
+        final boolean isManagedProfile = Utils.isManagedProfile(mContext, mConfig.mUserId);
 
-        // TODO: Update with new controllers if multi-modal authentication can occur simultaneously
-        if (config.mModalityMask == BiometricAuthenticator.TYPE_FINGERPRINT) {
-            mBiometricView = (AuthBiometricFingerprintView)
-                    factory.inflate(R.layout.auth_biometric_fingerprint_view, null, false);
-        } else if (config.mModalityMask == BiometricAuthenticator.TYPE_FACE) {
-            mBiometricView = (AuthBiometricFaceView)
-                    factory.inflate(R.layout.auth_biometric_face_view, null, false);
-        } else {
-            Log.e(TAG, "Unsupported modality mask: " + config.mModalityMask);
-            mBiometricView = null;
-            mBackgroundView = null;
-            mScrollView = null;
-            return;
+        mPanelView = mInjector.getPanelView(mFrameLayout);
+        mPanelController = mInjector.getPanelController(mContext, mPanelView, isManagedProfile);
+
+        // Inflate biometric view only if necessary.
+        if (Utils.isBiometricAllowed(mConfig.mBiometricPromptBundle)) {
+            if (config.mModalityMask == BiometricAuthenticator.TYPE_FINGERPRINT) {
+                mBiometricView = (AuthBiometricFingerprintView)
+                        factory.inflate(R.layout.auth_biometric_fingerprint_view, null, false);
+            } else if (config.mModalityMask == BiometricAuthenticator.TYPE_FACE) {
+                mBiometricView = (AuthBiometricFaceView)
+                        factory.inflate(R.layout.auth_biometric_face_view, null, false);
+            } else {
+                Log.e(TAG, "Unsupported biometric modality: " + config.mModalityMask);
+                mBiometricView = null;
+                mBackgroundView = null;
+                mBiometricScrollView = null;
+                return;
+            }
         }
 
-        mBackgroundView = mContainerView.findViewById(R.id.background);
+        mBiometricScrollView = mInjector.getBiometricScrollView(mFrameLayout);
+        mBackgroundView = mInjector.getBackgroundView(mFrameLayout);
 
-        UserManager userManager = mContext.getSystemService(UserManager.class);
-        DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
-        if (userManager.isManagedProfile(mConfig.mUserId)) {
+
+        if (isManagedProfile) {
             final Drawable image = getResources().getDrawable(R.drawable.work_challenge_background,
                     mContext.getTheme());
+            final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
             image.setColorFilter(dpm.getOrganizationColorForUser(mConfig.mUserId),
                     PorterDuff.Mode.DARKEN);
             mBackgroundView.setScaleType(ImageView.ScaleType.CENTER_CROP);
             mBackgroundView.setImageDrawable(image);
         }
 
-        mBiometricView.setRequireConfirmation(mConfig.mRequireConfirmation);
-        mBiometricView.setPanelController(mPanelController);
-        mBiometricView.setBiometricPromptBundle(config.mBiometricPromptBundle);
-        mBiometricView.setCallback(mBiometricCallback);
-        mBiometricView.setBackgroundView(mBackgroundView);
-
-        mScrollView = mContainerView.findViewById(R.id.scrollview);
-        mScrollView.addView(mBiometricView);
-        addView(mContainerView);
+        addView(mFrameLayout);
 
         setOnKeyListener((v, keyCode, event) -> {
             if (keyCode != KeyEvent.KEYCODE_BACK) {
@@ -248,6 +288,53 @@
     }
 
     @Override
+    public boolean isAllowDeviceCredentials() {
+        return Utils.isDeviceCredentialAllowed(mConfig.mBiometricPromptBundle);
+    }
+
+    private void addBiometricView() {
+        mBiometricView.setRequireConfirmation(mConfig.mRequireConfirmation);
+        mBiometricView.setPanelController(mPanelController);
+        mBiometricView.setBiometricPromptBundle(mConfig.mBiometricPromptBundle);
+        mBiometricView.setCallback(mBiometricCallback);
+        mBiometricView.setBackgroundView(mBackgroundView);
+        mBiometricView.setUserId(mConfig.mUserId);
+        mBiometricScrollView.addView(mBiometricView);
+    }
+
+    /**
+     * Adds the credential view. When going from biometric to credential view, the biometric
+     * view starts the panel expansion animation. If the credential view is being shown first,
+     * it should own the panel expansion.
+     * @param animatePanel if the credential view needs to own the panel expansion animation
+     */
+    private void addCredentialView(boolean animatePanel, boolean animateContents) {
+        final LayoutInflater factory = LayoutInflater.from(mContext);
+        final int credentialType = Utils.getCredentialType(mContext, mConfig.mUserId);
+        switch (credentialType) {
+            case Utils.CREDENTIAL_PATTERN:
+                mCredentialView = (AuthCredentialView) factory.inflate(
+                        R.layout.auth_credential_pattern_view, null, false);
+                break;
+            case Utils.CREDENTIAL_PIN:
+            case Utils.CREDENTIAL_PASSWORD:
+                mCredentialView = (AuthCredentialView) factory.inflate(
+                        R.layout.auth_credential_password_view, null, false);
+                break;
+            default:
+                throw new IllegalStateException("Unknown credential type: " + credentialType);
+        }
+
+        mCredentialView.setContainerView(this);
+        mCredentialView.setUser(mConfig.mUserId);
+        mCredentialView.setCallback(mCredentialCallback);
+        mCredentialView.setBiometricPromptBundle(mConfig.mBiometricPromptBundle);
+        mCredentialView.setPanelController(mPanelController, animatePanel);
+        mCredentialView.setShouldAnimateContents(animateContents);
+        mFrameLayout.addView(mCredentialView);
+    }
+
+    @Override
     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
         mPanelController.setContainerDimensions(getMeasuredWidth(), getMeasuredHeight());
@@ -256,8 +343,22 @@
     @Override
     public void onAttachedToWindow() {
         super.onAttachedToWindow();
+        onAttachedToWindowInternal();
+    }
+
+    @VisibleForTesting
+    void onAttachedToWindowInternal() {
         mWakefulnessLifecycle.addObserver(this);
 
+        if (Utils.isBiometricAllowed(mConfig.mBiometricPromptBundle)) {
+            addBiometricView();
+        } else if (Utils.isDeviceCredentialAllowed(mConfig.mBiometricPromptBundle)) {
+            addCredentialView(true /* animatePanel */, false /* animateContents */);
+        } else {
+            throw new IllegalStateException("Unknown configuration: "
+                    + Utils.getAuthenticators(mConfig.mBiometricPromptBundle));
+        }
+
         if (mConfig.mSkipIntro) {
             mContainerState = STATE_SHOWING;
         } else {
@@ -265,7 +366,7 @@
             // The background panel and content are different views since we need to be able to
             // animate them separately in other places.
             mPanelView.setY(mTranslationY);
-            mScrollView.setY(mTranslationY);
+            mBiometricScrollView.setY(mTranslationY);
 
             setAlpha(0f);
             postOnAnimation(() -> {
@@ -276,12 +377,21 @@
                         .withLayer()
                         .withEndAction(this::onDialogAnimatedIn)
                         .start();
-                mScrollView.animate()
+                mBiometricScrollView.animate()
                         .translationY(0)
                         .setDuration(ANIMATION_DURATION_SHOW_MS)
                         .setInterpolator(mLinearOutSlowIn)
                         .withLayer()
                         .start();
+                if (mCredentialView != null && mCredentialView.isAttachedToWindow()) {
+                    mCredentialView.setY(mTranslationY);
+                    mCredentialView.animate()
+                            .translationY(0)
+                            .setDuration(ANIMATION_DURATION_SHOW_MS)
+                            .setInterpolator(mLinearOutSlowIn)
+                            .withLayer()
+                            .start();
+                }
                 animate()
                         .alpha(1f)
                         .setDuration(ANIMATION_DURATION_SHOW_MS)
@@ -305,7 +415,9 @@
 
     @Override
     public void show(WindowManager wm, @Nullable Bundle savedState) {
-        mBiometricView.restoreState(savedState);
+        if (mBiometricView != null) {
+            mBiometricView.restoreState(savedState);
+        }
         wm.addView(this, getLayoutParams(mWindowToken));
     }
 
@@ -346,7 +458,15 @@
     @Override
     public void onSaveState(@NonNull Bundle outState) {
         outState.putInt(AuthDialog.KEY_CONTAINER_STATE, mContainerState);
-        mBiometricView.onSaveState(outState);
+        // In the case where biometric and credential are both allowed, we can assume that
+        // biometric isn't showing if credential is showing since biometric is shown first.
+        outState.putBoolean(AuthDialog.KEY_BIOMETRIC_SHOWING,
+                mBiometricView != null && mCredentialView == null);
+        outState.putBoolean(AuthDialog.KEY_CREDENTIAL_SHOWING, mCredentialView != null);
+
+        if (mBiometricView != null) {
+            mBiometricView.onSaveState(outState);
+        }
     }
 
     @Override
@@ -354,6 +474,11 @@
         return mConfig.mOpPackageName;
     }
 
+    @Override
+    public void animateToCredentialUI() {
+        mBiometricView.startTransitionToCredentialUI();
+    }
+
     @VisibleForTesting
     void animateAway(int reason) {
         animateAway(true /* sendReason */, reason);
@@ -391,12 +516,20 @@
                     .withLayer()
                     .withEndAction(endActionRunnable)
                     .start();
-            mScrollView.animate()
+            mBiometricScrollView.animate()
                     .translationY(mTranslationY)
                     .setDuration(ANIMATION_DURATION_AWAY_MS)
                     .setInterpolator(mLinearOutSlowIn)
                     .withLayer()
                     .start();
+            if (mCredentialView != null && mCredentialView.isAttachedToWindow()) {
+                mCredentialView.animate()
+                        .translationY(mTranslationY)
+                        .setDuration(ANIMATION_DURATION_AWAY_MS)
+                        .setInterpolator(mLinearOutSlowIn)
+                        .withLayer()
+                        .start();
+            }
             animate()
                     .alpha(0f)
                     .setDuration(ANIMATION_DURATION_AWAY_MS)
@@ -431,7 +564,9 @@
             return;
         }
         mContainerState = STATE_SHOWING;
-        mBiometricView.onDialogAnimatedIn();
+        if (mBiometricView != null) {
+            mBiometricView.onDialogAnimatedIn();
+        }
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
index d10a3fe..4c2afb0 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
@@ -23,6 +23,8 @@
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.content.res.Configuration;
+import android.hardware.biometrics.Authenticator;
+import android.hardware.biometrics.BiometricConstants;
 import android.hardware.biometrics.BiometricPrompt;
 import android.hardware.biometrics.IBiometricServiceReceiverInternal;
 import android.os.Bundle;
@@ -105,6 +107,15 @@
     }
 
     @Override
+    public void onDeviceCredentialPressed() {
+        try {
+            mReceiver.onDeviceCredentialPressed();
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException when handling credential button", e);
+        }
+    }
+
+    @Override
     public void onDismissed(@DismissedReason int reason) {
         switch (reason) {
             case AuthDialogCallback.DISMISSED_USER_CANCELED:
@@ -116,11 +127,12 @@
                 break;
 
             case AuthDialogCallback.DISMISSED_BUTTON_POSITIVE:
-                sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_CONFIRMED);
+                sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED);
                 break;
 
-            case AuthDialogCallback.DISMISSED_AUTHENTICATED:
-                sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_CONFIRM_NOT_REQUIRED);
+            case AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED:
+                sendResultAndCleanUp(
+                        BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED);
                 break;
 
             case AuthDialogCallback.DISMISSED_ERROR:
@@ -131,6 +143,10 @@
                 sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED);
                 break;
 
+            case AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED:
+                sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED);
+                break;
+
             default:
                 Log.e(TAG, "Unhandled reason: " + reason);
                 break;
@@ -185,16 +201,19 @@
     }
 
     @Override
-    public void showBiometricDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
-            int type, boolean requireConfirmation, int userId, String opPackageName) {
+    public void showAuthenticationDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
+            int biometricModality, boolean requireConfirmation, int userId, String opPackageName) {
+        final int authenticators = Utils.getAuthenticators(bundle);
+
         if (DEBUG) {
-            Log.d(TAG, "showBiometricDialog, type: " + type
+            Log.d(TAG, "showAuthenticationDialog, authenticators: " + authenticators
+                    + ", biometricModality: " + biometricModality
                     + ", requireConfirmation: " + requireConfirmation);
         }
         SomeArgs args = SomeArgs.obtain();
         args.arg1 = bundle;
         args.arg2 = receiver;
-        args.argi1 = type;
+        args.argi1 = biometricModality;
         args.arg3 = requireConfirmation;
         args.argi2 = userId;
         args.arg4 = opPackageName;
@@ -204,6 +223,7 @@
             Log.w(TAG, "mCurrentDialog: " + mCurrentDialog);
             skipAnimation = true;
         }
+
         showDialog(args, skipAnimation, null /* savedState */);
     }
 
@@ -227,14 +247,21 @@
     }
 
     @Override
-    public void onBiometricError(String error) {
-        if (DEBUG) Log.d(TAG, "onBiometricError: " + error);
-        mCurrentDialog.onError(error);
+    public void onBiometricError(int errorCode, String error) {
+        if (DEBUG) Log.d(TAG, "onBiometricError: " + errorCode + ", " + error);
+
+        final boolean isLockout = errorCode == BiometricConstants.BIOMETRIC_ERROR_LOCKOUT
+                || errorCode == BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
+        if (mCurrentDialog.isAllowDeviceCredentials() && isLockout) {
+            mCurrentDialog.animateToCredentialUI();
+        } else {
+            mCurrentDialog.onError(error);
+        }
     }
 
     @Override
-    public void hideBiometricDialog() {
-        if (DEBUG) Log.d(TAG, "hideBiometricDialog");
+    public void hideAuthenticationDialog() {
+        if (DEBUG) Log.d(TAG, "hideAuthenticationDialog");
 
         mCurrentDialog.dismissFromSystemServer();
     }
@@ -262,7 +289,7 @@
         }
 
         if (DEBUG) {
-            Log.d(TAG, "showDialog, "
+            Log.d(TAG, "showDialog: " + args
                     + " savedState: " + savedState
                     + " mCurrentDialog: " + mCurrentDialog
                     + " newDialog: " + newDialog
@@ -306,6 +333,15 @@
             // to send its pending callback immediately.
             if (savedState.getInt(AuthDialog.KEY_CONTAINER_STATE)
                     != AuthContainerView.STATE_ANIMATING_OUT) {
+                final boolean credentialShowing =
+                        savedState.getBoolean(AuthDialog.KEY_CREDENTIAL_SHOWING);
+                if (credentialShowing) {
+                    // TODO: Clean this up
+                    Bundle bundle = (Bundle) mCurrentDialogArgs.arg1;
+                    bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED,
+                            Authenticator.TYPE_CREDENTIAL);
+                }
+
                 showDialog(mCurrentDialogArgs, true /* skipAnimation */, savedState);
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPasswordView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPasswordView.java
new file mode 100644
index 0000000..8df072e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPasswordView.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2019 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.biometrics;
+
+import android.content.Context;
+import android.text.InputType;
+import android.util.AttributeSet;
+import android.view.KeyEvent;
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.widget.EditText;
+import android.widget.TextView;
+
+import com.android.internal.widget.LockPatternChecker;
+import com.android.internal.widget.LockPatternUtils;
+import com.android.systemui.R;
+
+/**
+ * Pin and Password UI
+ */
+public class AuthCredentialPasswordView extends AuthCredentialView
+        implements TextView.OnEditorActionListener {
+
+    private static final String TAG = "BiometricPrompt/AuthCredentialPasswordView";
+
+    private final InputMethodManager mImm;
+    private EditText mPasswordField;
+
+    public AuthCredentialPasswordView(Context context,
+            AttributeSet attrs) {
+        super(context, attrs);
+        mImm = mContext.getSystemService(InputMethodManager.class);
+    }
+
+    @Override
+    protected void onFinishInflate() {
+        super.onFinishInflate();
+        mPasswordField = findViewById(R.id.lockPassword);
+        mPasswordField.setOnEditorActionListener(this);
+        mPasswordField.setOnKeyListener((v, keyCode, event) -> {
+            if (keyCode != KeyEvent.KEYCODE_BACK) {
+                return false;
+            }
+            if (event.getAction() == KeyEvent.ACTION_UP) {
+                mContainerView.animateAway(AuthDialogCallback.DISMISSED_USER_CANCELED);
+            }
+            return true;
+        });
+    }
+
+    @Override
+    protected void onAttachedToWindow() {
+        super.onAttachedToWindow();
+
+        if (mCredentialType == Utils.CREDENTIAL_PIN) {
+            mPasswordField.setInputType(
+                    InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
+        }
+
+        // Wait a bit to focus the field so the focusable flag on the window is already set then.
+        post(() -> {
+            mPasswordField.requestFocus();
+            mImm.showSoftInput(mPasswordField, InputMethodManager.SHOW_IMPLICIT);
+        });
+    }
+
+    @Override
+    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
+        // Check if this was the result of hitting the enter key
+        final boolean isSoftImeEvent = event == null
+                && (actionId == EditorInfo.IME_NULL
+                || actionId == EditorInfo.IME_ACTION_DONE
+                || actionId == EditorInfo.IME_ACTION_NEXT);
+        final boolean isKeyboardEnterKey = event != null
+                && KeyEvent.isConfirmKey(event.getKeyCode())
+                && event.getAction() == KeyEvent.ACTION_DOWN;
+        if (isSoftImeEvent || isKeyboardEnterKey) {
+            checkPasswordAndUnlock();
+            return true;
+        }
+        return false;
+    }
+
+    private void checkPasswordAndUnlock() {
+        final byte[] password = LockPatternUtils.charSequenceToByteArray(mPasswordField.getText());
+        if (password == null || password.length == 0) {
+            return;
+        }
+
+        mPendingLockCheck = LockPatternChecker.checkPassword(mLockPatternUtils,
+                password, mUserId, this::onCredentialChecked);
+    }
+
+    @Override
+    protected void onCredentialChecked(boolean matched, int timeoutMs) {
+        super.onCredentialChecked(matched, timeoutMs);
+
+        if (matched) {
+            mImm.hideSoftInputFromWindow(getWindowToken(), 0 /* flags */);
+        } else {
+            mPasswordField.setText("");
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPatternView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPatternView.java
new file mode 100644
index 0000000..6c36f82
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPatternView.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2019 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.biometrics;
+
+import android.content.Context;
+import android.util.AttributeSet;
+
+import com.android.internal.widget.LockPatternChecker;
+import com.android.internal.widget.LockPatternUtils;
+import com.android.internal.widget.LockPatternView;
+import com.android.systemui.R;
+
+import java.util.List;
+
+/**
+ * Pattern UI
+ */
+public class AuthCredentialPatternView extends AuthCredentialView {
+
+    private LockPatternView mLockPatternView;
+
+    private class UnlockPatternListener implements LockPatternView.OnPatternListener {
+
+        @Override
+        public void onPatternStart() {
+
+        }
+
+        @Override
+        public void onPatternCleared() {
+
+        }
+
+        @Override
+        public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {
+
+        }
+
+        @Override
+        public void onPatternDetected(List<LockPatternView.Cell> pattern) {
+            if (mPendingLockCheck != null) {
+                mPendingLockCheck.cancel(false);
+            }
+
+            mLockPatternView.setEnabled(false);
+
+            if (pattern.size() < LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
+                // Pattern size is less than the minimum, do not count it as a failed attempt.
+                onPatternChecked(false /* matched */, 0 /* timeoutMs */);
+                return;
+            }
+
+            mPendingLockCheck = LockPatternChecker.checkPattern(
+                    mLockPatternUtils,
+                    pattern,
+                    mUserId,
+                    this::onPatternChecked);
+        }
+
+        private void onPatternChecked(boolean matched, int timeoutMs) {
+            AuthCredentialPatternView.this.onCredentialChecked(matched, timeoutMs);
+            if (timeoutMs > 0) {
+                mLockPatternView.setEnabled(false);
+            } else {
+                mLockPatternView.setEnabled(true);
+            }
+        }
+    }
+
+    @Override
+    protected void onErrorTimeoutFinish() {
+        super.onErrorTimeoutFinish();
+        mLockPatternView.setEnabled(true);
+    }
+
+    public AuthCredentialPatternView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    @Override
+    protected void onFinishInflate() {
+        super.onFinishInflate();
+        mLockPatternView = findViewById(R.id.lockPattern);
+        mLockPatternView.setOnPatternListener(new UnlockPatternListener());
+        mLockPatternView.setInStealthMode(!mLockPatternUtils.isVisiblePatternEnabled(mUserId));
+        mLockPatternView.setTactileFeedbackEnabled(mLockPatternUtils.isTactileFeedbackEnabled());
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialView.java
new file mode 100644
index 0000000..8c8611e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialView.java
@@ -0,0 +1,265 @@
+/*
+ * Copyright (C) 2019 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.biometrics;
+
+import android.content.Context;
+import android.hardware.biometrics.BiometricPrompt;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.CountDownTimer;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.SystemClock;
+import android.text.TextUtils;
+import android.util.AttributeSet;
+import android.view.View;
+import android.view.accessibility.AccessibilityManager;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.systemui.Interpolators;
+import com.android.systemui.R;
+
+/**
+ * Abstract base class for Pin, Pattern, or Password authentication, for
+ * {@link BiometricPrompt.Builder#setDeviceCredentialAllowed(boolean)}
+ */
+public abstract class AuthCredentialView extends LinearLayout {
+
+    private static final String TAG = "BiometricPrompt/AuthCredentialView";
+    private static final int ERROR_DURATION_MS = 3000;
+
+    private final AccessibilityManager mAccessibilityManager;
+
+    protected final Handler mHandler;
+
+    private Bundle mBiometricPromptBundle;
+    private AuthPanelController mPanelController;
+    private boolean mShouldAnimatePanel;
+    private boolean mShouldAnimateContents;
+
+    private TextView mTitleView;
+    private TextView mSubtitleView;
+    private TextView mDescriptionView;
+    protected TextView mErrorView;
+
+    protected @Utils.CredentialType int mCredentialType;
+    protected final LockPatternUtils mLockPatternUtils;
+    protected AuthContainerView mContainerView;
+    protected Callback mCallback;
+    protected AsyncTask<?, ?, ?> mPendingLockCheck;
+    protected int mUserId;
+    protected ErrorTimer mErrorTimer;
+
+    interface Callback {
+        void onCredentialMatched();
+    }
+
+    protected static class ErrorTimer extends CountDownTimer {
+        private final TextView mErrorView;
+        private final Context mContext;
+
+        /**
+         * @param millisInFuture    The number of millis in the future from the call
+         *                          to {@link #start()} until the countdown is done and {@link
+         *                          #onFinish()}
+         *                          is called.
+         * @param countDownInterval The interval along the way to receive
+         *                          {@link #onTick(long)} callbacks.
+         */
+        public ErrorTimer(Context context, long millisInFuture, long countDownInterval,
+                TextView errorView) {
+            super(millisInFuture, countDownInterval);
+            mErrorView = errorView;
+            mContext = context;
+        }
+
+        @Override
+        public void onTick(long millisUntilFinished) {
+            final int secondsCountdown = (int) (millisUntilFinished / 1000);
+            mErrorView.setText(mContext.getString(
+                    R.string.biometric_dialog_credential_too_many_attempts, secondsCountdown));
+        }
+
+        @Override
+        public void onFinish() {
+            mErrorView.setText("");
+        }
+    }
+
+    protected final Runnable mClearErrorRunnable = new Runnable() {
+        @Override
+        public void run() {
+            mErrorView.setText("");
+        }
+    };
+
+    public AuthCredentialView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+
+        mLockPatternUtils = new LockPatternUtils(mContext);
+        mHandler = new Handler(Looper.getMainLooper());
+        mAccessibilityManager = mContext.getSystemService(AccessibilityManager.class);
+    }
+
+    protected void showError(String error) {
+        mHandler.removeCallbacks(mClearErrorRunnable);
+        mErrorView.setText(error);
+        mHandler.postDelayed(mClearErrorRunnable, ERROR_DURATION_MS);
+    }
+
+    private void setTextOrHide(TextView view, String string) {
+        if (TextUtils.isEmpty(string)) {
+            view.setVisibility(View.GONE);
+        } else {
+            view.setText(string);
+        }
+
+        Utils.notifyAccessibilityContentChanged(mAccessibilityManager, this);
+    }
+
+    private void setText(TextView view, String string) {
+        view.setText(string);
+    }
+
+    void setUser(int user) {
+        mUserId = user;
+    }
+
+    void setCallback(Callback callback) {
+        mCallback = callback;
+    }
+
+    void setBiometricPromptBundle(Bundle bundle) {
+        mBiometricPromptBundle = bundle;
+    }
+
+    void setPanelController(AuthPanelController panelController, boolean animatePanel) {
+        mPanelController = panelController;
+        mShouldAnimatePanel = animatePanel;
+    }
+
+    void setShouldAnimateContents(boolean animateContents) {
+        mShouldAnimateContents = animateContents;
+    }
+
+    void setContainerView(AuthContainerView containerView) {
+        mContainerView = containerView;
+    }
+
+    @Override
+    protected void onAttachedToWindow() {
+        super.onAttachedToWindow();
+
+        mCredentialType = Utils.getCredentialType(mContext, mUserId);
+
+        setText(mTitleView, mBiometricPromptBundle.getString(BiometricPrompt.KEY_TITLE));
+        setTextOrHide(mSubtitleView,
+                mBiometricPromptBundle.getString(BiometricPrompt.KEY_SUBTITLE));
+        setTextOrHide(mDescriptionView,
+                mBiometricPromptBundle.getString(BiometricPrompt.KEY_DESCRIPTION));
+
+        // Only animate this if we're transitioning from a biometric view.
+        if (mShouldAnimateContents) {
+            setTranslationY(getResources()
+                    .getDimension(R.dimen.biometric_dialog_credential_translation_offset));
+            setAlpha(0);
+
+            postOnAnimation(() -> {
+                animate().translationY(0)
+                        .setDuration(AuthDialog.ANIMATE_CREDENTIAL_INITIAL_DURATION_MS)
+                        .alpha(1.f)
+                        .setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN)
+                        .withLayer()
+                        .start();
+            });
+        }
+    }
+
+    @Override
+    protected void onDetachedFromWindow() {
+        super.onDetachedFromWindow();
+        if (mErrorTimer != null) {
+            mErrorTimer.cancel();
+        }
+    }
+
+    @Override
+    protected void onFinishInflate() {
+        super.onFinishInflate();
+        mTitleView = findViewById(R.id.title);
+        mSubtitleView = findViewById(R.id.subtitle);
+        mDescriptionView = findViewById(R.id.description);
+        mErrorView = findViewById(R.id.error);
+    }
+
+    @Override
+    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+        super.onLayout(changed, left, top, right, bottom);
+
+        if (mShouldAnimatePanel) {
+            // Credential view is always full screen.
+            mPanelController.setUseFullScreen(true);
+            mPanelController.updateForContentDimensions(mPanelController.getContainerWidth(),
+                    mPanelController.getContainerHeight(), 0 /* animateDurationMs */);
+            mShouldAnimatePanel = false;
+        }
+    }
+
+    protected void onErrorTimeoutFinish() {}
+
+    protected void onCredentialChecked(boolean matched, int timeoutMs) {
+        if (matched) {
+            mClearErrorRunnable.run();
+            mCallback.onCredentialMatched();
+        } else {
+            if (timeoutMs > 0) {
+                mHandler.removeCallbacks(mClearErrorRunnable);
+                long deadline = mLockPatternUtils.setLockoutAttemptDeadline(mUserId, timeoutMs);
+                mErrorTimer = new ErrorTimer(mContext,
+                        deadline - SystemClock.elapsedRealtime(),
+                        LockPatternUtils.FAILED_ATTEMPT_COUNTDOWN_INTERVAL_MS,
+                        mErrorView) {
+                    @Override
+                    public void onFinish() {
+                        onErrorTimeoutFinish();
+                        mClearErrorRunnable.run();
+                    }
+                };
+                mErrorTimer.start();
+            } else {
+                final int error;
+                switch (mCredentialType) {
+                    case Utils.CREDENTIAL_PIN:
+                        error = R.string.biometric_dialog_wrong_pin;
+                        break;
+                    case Utils.CREDENTIAL_PATTERN:
+                        error = R.string.biometric_dialog_wrong_pattern;
+                        break;
+                    case Utils.CREDENTIAL_PASSWORD:
+                        error = R.string.biometric_dialog_wrong_password;
+                        break;
+                    default:
+                        error = R.string.biometric_dialog_wrong_password;
+                        break;
+                }
+                showError(getResources().getString(error));
+            }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialog.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialog.java
index edb2953..ca95f9d 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialog.java
@@ -31,6 +31,8 @@
 public interface AuthDialog {
 
     String KEY_CONTAINER_STATE = "container_state";
+    String KEY_BIOMETRIC_SHOWING = "biometric_showing";
+    String KEY_CREDENTIAL_SHOWING = "credential_showing";
 
     String KEY_BIOMETRIC_TRY_AGAIN_VISIBILITY = "try_agian_visibility";
     String KEY_BIOMETRIC_STATE = "state";
@@ -40,17 +42,38 @@
     String KEY_BIOMETRIC_DIALOG_SIZE = "size";
 
     int SIZE_UNKNOWN = 0;
+    /**
+     * Minimal UI, showing only biometric icon.
+     */
     int SIZE_SMALL = 1;
+    /**
+     * Normal-sized biometric UI, showing title, icon, buttons, etc.
+     */
     int SIZE_MEDIUM = 2;
+    /**
+     * Full-screen credential UI.
+     */
     int SIZE_LARGE = 3;
     @Retention(RetentionPolicy.SOURCE)
     @IntDef({SIZE_UNKNOWN, SIZE_SMALL, SIZE_MEDIUM, SIZE_LARGE})
     @interface DialogSize {}
 
     /**
-     * Animation duration, e.g. small to medium dialog, icon translation, etc.
+     * Animation duration, from small to medium dialog, including back panel, icon translation, etc
      */
-    int ANIMATE_DURATION_MS = 150;
+    int ANIMATE_SMALL_TO_MEDIUM_DURATION_MS = 150;
+    /**
+     * Animation duration from medium to large dialog, including biometric fade out, back panel, etc
+     */
+    int ANIMATE_MEDIUM_TO_LARGE_DURATION_MS = 450;
+    /**
+     * Delay before notifying {@link AuthCredentialView} to start animating in.
+     */
+    int ANIMATE_CREDENTIAL_START_DELAY_MS = ANIMATE_MEDIUM_TO_LARGE_DURATION_MS * 2 / 3;
+    /**
+     * Animation duration when sliding in credential UI
+     */
+    int ANIMATE_CREDENTIAL_INITIAL_DURATION_MS = 150;
 
     /**
      * Show the dialog.
@@ -101,4 +124,14 @@
      * Get the client's package name
      */
     String getOpPackageName();
+
+    /**
+     * Animate to credential UI. Typically called after biometric is locked out.
+     */
+    void animateToCredentialUI();
+
+    /**
+     * @return true if device credential is allowed.
+     */
+    boolean isAllowDeviceCredentials();
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java
index 70752f5..12bb122 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java
@@ -27,17 +27,18 @@
     int DISMISSED_USER_CANCELED = 1;
     int DISMISSED_BUTTON_NEGATIVE = 2;
     int DISMISSED_BUTTON_POSITIVE = 3;
-
-    int DISMISSED_AUTHENTICATED = 4;
+    int DISMISSED_BIOMETRIC_AUTHENTICATED = 4;
     int DISMISSED_ERROR = 5;
     int DISMISSED_BY_SYSTEM_SERVER = 6;
+    int DISMISSED_CREDENTIAL_AUTHENTICATED = 7;
 
     @IntDef({DISMISSED_USER_CANCELED,
             DISMISSED_BUTTON_NEGATIVE,
             DISMISSED_BUTTON_POSITIVE,
-            DISMISSED_AUTHENTICATED,
+            DISMISSED_BIOMETRIC_AUTHENTICATED,
             DISMISSED_ERROR,
-            DISMISSED_BY_SYSTEM_SERVER})
+            DISMISSED_BY_SYSTEM_SERVER,
+            DISMISSED_CREDENTIAL_AUTHENTICATED})
     @interface DismissedReason {}
 
     /**
@@ -50,4 +51,9 @@
      * Invoked when the "try again" button is clicked
      */
     void onTryAgainPressed();
+
+    /**
+     * Invoked when the "use password" button is clicked
+     */
+    void onDeviceCredentialPressed();
 }
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthPanelController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthPanelController.java
index 55ba049..2b8b586 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthPanelController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthPanelController.java
@@ -16,15 +16,17 @@
 
 package com.android.systemui.biometrics;
 
+import android.animation.AnimatorSet;
 import android.animation.ValueAnimator;
 import android.content.Context;
+import android.graphics.Color;
 import android.graphics.Outline;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewOutlineProvider;
+import android.view.animation.AccelerateDecelerateInterpolator;
 
 import com.android.systemui.R;
-import com.android.systemui.biometrics.AuthDialog;
 
 /**
  * Controls the back panel and its animations for the BiometricPrompt UI.
@@ -36,8 +38,9 @@
 
     private final Context mContext;
     private final View mPanelView;
-    private final float mCornerRadius;
-    private final int mBiometricMargin;
+    private final boolean mIsManagedProfile;
+
+    private boolean mUseFullScreen;
 
     private int mContainerWidth;
     private int mContainerHeight;
@@ -45,14 +48,23 @@
     private int mContentWidth;
     private int mContentHeight;
 
+    private float mCornerRadius;
+    private int mMargin;
+
     @Override
     public void getOutline(View view, Outline outline) {
         final int left = (mContainerWidth - mContentWidth) / 2;
         final int right = mContainerWidth - left;
+
+        // If the content fits within the container, shrink the height to wrap the content.
+        // Otherwise, set the outline to be the display size minus the margin - the content within
+        // is scrollable.
         final int top = mContentHeight < mContainerHeight
-                ? mContainerHeight - mContentHeight - mBiometricMargin
-                : mBiometricMargin;
-        final int bottom = mContainerHeight - mBiometricMargin;
+                ? mContainerHeight - mContentHeight - mMargin
+                : mMargin;
+
+        // TODO(b/139954942) Likely don't need to "+1" after we resolve the navbar styling.
+        final int bottom = mContainerHeight - mMargin + 1;
         outline.setRoundRect(left, top, right, bottom, mCornerRadius);
     }
 
@@ -64,11 +76,34 @@
         mContainerHeight = containerHeight;
     }
 
-    public void updateForContentDimensions(int contentWidth, int contentHeight, boolean animate) {
+    public void setUseFullScreen(boolean fullScreen) {
+        mUseFullScreen = fullScreen;
+    }
+
+    public ValueAnimator getTranslationAnimator(float relativeTranslationY) {
+        final ValueAnimator animator = ValueAnimator.ofFloat(
+                mPanelView.getY(), mPanelView.getY() - relativeTranslationY);
+        animator.addUpdateListener(animation -> {
+            final float translation = (float) animation.getAnimatedValue();
+            mPanelView.setTranslationY(translation);
+        });
+        return animator;
+    }
+
+    public ValueAnimator getAlphaAnimator(float alpha) {
+        final ValueAnimator animator = ValueAnimator.ofFloat(mPanelView.getAlpha(), alpha);
+        animator.addUpdateListener(animation -> {
+            mPanelView.setAlpha((float) animation.getAnimatedValue());
+        });
+        return animator;
+    }
+
+    public void updateForContentDimensions(int contentWidth, int contentHeight,
+            int animateDurationMs) {
         if (DEBUG) {
             Log.v(TAG, "Content Width: " + contentWidth
                     + " Height: " + contentHeight
-                    + " Animate: " + animate);
+                    + " Animate: " + animateDurationMs);
         }
 
         if (mContainerWidth == 0 || mContainerHeight == 0) {
@@ -76,27 +111,86 @@
             return;
         }
 
-        if (animate) {
+        final int margin = mUseFullScreen ? 0 : (int) mContext.getResources()
+                .getDimension(R.dimen.biometric_dialog_border_padding);
+        final float cornerRadius = mUseFullScreen ? 0 : mContext.getResources()
+                .getDimension(R.dimen.biometric_dialog_corner_size);
+
+        // When going to full-screen for managed profiles, fade away so the managed profile
+        // background behind this view becomes visible.
+        final boolean shouldFadeAway = mUseFullScreen && mIsManagedProfile;
+        final int alpha = shouldFadeAway ? 0 : 255;
+        final float elevation = shouldFadeAway ? 0 :
+                mContext.getResources().getDimension(R.dimen.biometric_dialog_elevation);
+
+        if (animateDurationMs > 0) {
+            // Animate margin
+            ValueAnimator marginAnimator = ValueAnimator.ofInt(mMargin, margin);
+            marginAnimator.addUpdateListener((animation) -> {
+                mMargin = (int) animation.getAnimatedValue();
+            });
+
+            // Animate corners
+            ValueAnimator cornerAnimator = ValueAnimator.ofFloat(mCornerRadius, cornerRadius);
+            cornerAnimator.addUpdateListener((animation) -> {
+                mCornerRadius = (float) animation.getAnimatedValue();
+            });
+
+            // Animate height
             ValueAnimator heightAnimator = ValueAnimator.ofInt(mContentHeight, contentHeight);
-            heightAnimator.setDuration(AuthDialog.ANIMATE_DURATION_MS);
             heightAnimator.addUpdateListener((animation) -> {
                 mContentHeight = (int) animation.getAnimatedValue();
                 mPanelView.invalidateOutline();
             });
             heightAnimator.start();
+
+            // Animate width
+            ValueAnimator widthAnimator = ValueAnimator.ofInt(mContentWidth, contentWidth);
+            widthAnimator.addUpdateListener((animation) -> {
+                mContentWidth = (int) animation.getAnimatedValue();
+            });
+
+            // Animate background
+            ValueAnimator alphaAnimator = ValueAnimator.ofInt(
+                    mPanelView.getBackground().getAlpha(), alpha);
+            alphaAnimator.addUpdateListener((animation) -> {
+                if (shouldFadeAway) {
+                    mPanelView.getBackground().setAlpha((int) animation.getAnimatedValue());
+                }
+            });
+
+            // Play together
+            AnimatorSet as = new AnimatorSet();
+            as.setDuration(animateDurationMs);
+            as.setInterpolator(new AccelerateDecelerateInterpolator());
+            as.playTogether(cornerAnimator, widthAnimator, marginAnimator, alphaAnimator);
+            as.start();
+
         } else {
+            mMargin = margin;
+            mCornerRadius = cornerRadius;
             mContentWidth = contentWidth;
             mContentHeight = contentHeight;
+            mPanelView.getBackground().setAlpha(alpha);
             mPanelView.invalidateOutline();
         }
     }
 
-    AuthPanelController(Context context, View panelView) {
+    int getContainerWidth() {
+        return mContainerWidth;
+    }
+
+    int getContainerHeight() {
+        return mContainerHeight;
+    }
+
+    AuthPanelController(Context context, View panelView, boolean isManagedProfile) {
         mContext = context;
         mPanelView = panelView;
+        mIsManagedProfile = isManagedProfile;
         mCornerRadius = context.getResources()
                 .getDimension(R.dimen.biometric_dialog_corner_size);
-        mBiometricMargin = (int) context.getResources()
+        mMargin = (int) context.getResources()
                 .getDimension(R.dimen.biometric_dialog_border_padding);
         mPanelView.setOutlineProvider(this);
         mPanelView.setClipToOutline(true);
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java b/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java
index e00cf6a..d6f830d 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/Utils.java
@@ -18,14 +18,36 @@
 
 import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE;
 
+import android.annotation.IntDef;
+import android.app.admin.DevicePolicyManager;
 import android.content.Context;
+import android.hardware.biometrics.Authenticator;
+import android.hardware.biometrics.BiometricPrompt;
+import android.os.Bundle;
+import android.os.UserManager;
 import android.util.DisplayMetrics;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityManager;
 
+import com.android.internal.widget.LockPatternUtils;
+import com.android.systemui.R;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
 public class Utils {
+
+    public static final int CREDENTIAL_PIN = 1;
+    public static final int CREDENTIAL_PATTERN = 2;
+    public static final int CREDENTIAL_PASSWORD = 3;
+
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({CREDENTIAL_PIN, CREDENTIAL_PATTERN, CREDENTIAL_PASSWORD})
+    @interface CredentialType {}
+
+
     static float dpToPixels(Context context, float dp) {
         return dp * ((float) context.getResources().getDisplayMetrics().densityDpi
                 / DisplayMetrics.DENSITY_DEFAULT);
@@ -46,4 +68,41 @@
         view.sendAccessibilityEventUnchecked(event);
         view.notifySubtreeAccessibilityStateChanged(view, view, CONTENT_CHANGE_TYPE_SUBTREE);
     }
+
+    static boolean isDeviceCredentialAllowed(Bundle biometricPromptBundle) {
+        final int authenticators = getAuthenticators(biometricPromptBundle);
+        return (authenticators & Authenticator.TYPE_CREDENTIAL) != 0;
+    }
+
+    static boolean isBiometricAllowed(Bundle biometricPromptBundle) {
+        final int authenticators = getAuthenticators(biometricPromptBundle);
+        return (authenticators & Authenticator.TYPE_BIOMETRIC) != 0;
+    }
+
+    static int getAuthenticators(Bundle biometricPromptBundle) {
+        return biometricPromptBundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED);
+    }
+
+    static @CredentialType int getCredentialType(Context context, int userId) {
+        final LockPatternUtils lpu = new LockPatternUtils(context);
+        switch (lpu.getKeyguardStoredPasswordQuality(userId)) {
+            case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
+                return CREDENTIAL_PATTERN;
+            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
+            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
+                return CREDENTIAL_PIN;
+            case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
+            case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
+            case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
+            case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
+                return CREDENTIAL_PASSWORD;
+            default:
+                return CREDENTIAL_PASSWORD;
+        }
+    }
+
+    static boolean isManagedProfile(Context context, int userId) {
+        final UserManager userManager = context.getSystemService(UserManager.class);
+        return userManager.isManagedProfile(userId);
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt b/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt
index f0e8c16..5e977b4 100644
--- a/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt
+++ b/packages/SystemUI/src/com/android/systemui/broadcast/BroadcastDispatcher.kt
@@ -75,7 +75,7 @@
      * @param filter A filter to determine what broadcasts should be dispatched to this receiver.
      *               It will only take into account actions and categories for filtering.
      * @param handler A handler to dispatch [BroadcastReceiver.onReceive]. By default, it is the
-     *                main handler.
+     *                main handler. Pass `null` to use the default.
      * @param user A user handle to determine which broadcast should be dispatched to this receiver.
      *             By default, it is the current user.
      */
@@ -83,10 +83,12 @@
     fun registerReceiver(
         receiver: BroadcastReceiver,
         filter: IntentFilter,
-        handler: Handler = mainHandler,
+        handler: Handler? = mainHandler,
         user: UserHandle = context.user
     ) {
-        this.handler.obtainMessage(MSG_ADD_RECEIVER, ReceiverData(receiver, filter, handler, user))
+        this.handler
+                .obtainMessage(MSG_ADD_RECEIVER,
+                ReceiverData(receiver, filter, handler ?: mainHandler, user))
                 .sendToTarget()
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/broadcast/UserBroadcastDispatcher.kt b/packages/SystemUI/src/com/android/systemui/broadcast/UserBroadcastDispatcher.kt
index d44b63e..54f9950 100644
--- a/packages/SystemUI/src/com/android/systemui/broadcast/UserBroadcastDispatcher.kt
+++ b/packages/SystemUI/src/com/android/systemui/broadcast/UserBroadcastDispatcher.kt
@@ -34,7 +34,7 @@
 
 private const val MSG_REGISTER_RECEIVER = 0
 private const val MSG_UNREGISTER_RECEIVER = 1
-private const val TAG = "UniversalReceiver"
+private const val TAG = "UserBroadcastDispatcher"
 private const val DEBUG = false
 
 /**
@@ -97,7 +97,7 @@
     private val receiverToReceiverData = ArrayMap<BroadcastReceiver, MutableSet<ReceiverData>>()
 
     override fun onReceive(context: Context, intent: Intent) {
-        bgHandler.post(HandleBroadcastRunnable(actionsToReceivers, context, intent))
+        bgHandler.post(HandleBroadcastRunnable(actionsToReceivers, context, intent, pendingResult))
     }
 
     /**
@@ -160,7 +160,8 @@
     private class HandleBroadcastRunnable(
         val actionsToReceivers: Map<String, Set<ReceiverData>>,
         val context: Context,
-        val intent: Intent
+        val intent: Intent,
+        val pendingResult: PendingResult
     ) : Runnable {
         override fun run() {
             if (DEBUG) Log.w(TAG, "Dispatching $intent")
@@ -171,6 +172,7 @@
                     ?.forEach {
                         it.handler.post {
                             if (DEBUG) Log.w(TAG, "Dispatching to ${it.receiver}")
+                            it.receiver.pendingResult = pendingResult
                             it.receiver.onReceive(context, intent)
                         }
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
index 72ada6e..cc548d0 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
@@ -126,8 +126,6 @@
     static final int DISMISS_GROUP_CANCELLED = 9;
     static final int DISMISS_INVALID_INTENT = 10;
 
-    public static final int MAX_BUBBLES = 5; // TODO: actually enforce this
-
     private final Context mContext;
     private final NotificationEntryManager mNotificationEntryManager;
     private final BubbleTaskStackListener mTaskStackListener;
@@ -571,7 +569,8 @@
                     if (mStackView != null) {
                         mStackView.updateDotVisibility(entry.key);
                     }
-                    mNotificationEntryManager.updateNotifications();
+                    mNotificationEntryManager.updateNotifications(
+                            "BubbleController.onNotificationRemoveRequested");
                     return true;
                 } else if (!userRemovedNotif && entry != null) {
                     // This wasn't a user removal so we should remove the bubble as well
@@ -611,7 +610,8 @@
                 mBubbleData.addSummaryToSuppress(summary.notification.getGroupKey(),
                         summary.key);
                 // Tell shade to update for the suppression
-                mNotificationEntryManager.updateNotifications();
+                mNotificationEntryManager.updateNotifications(
+                        "BubbleController.handleSummaryRemovalInterception");
             }
             return !isAutogroupSummary;
         } else {
@@ -762,7 +762,8 @@
                 mStackView.setExpanded(true);
             }
 
-            mNotificationEntryManager.updateNotifications();
+            mNotificationEntryManager.updateNotifications(
+                    "BubbleData.Listener.applyUpdate");
             updateStack();
 
             if (DEBUG_BUBBLE_CONTROLLER) {
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
index 31cf853..340dced 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
@@ -181,7 +181,9 @@
      */
     private float mVerticalPosPercentBeforeRotation = -1;
 
+    private int mMaxBubbles;
     private int mBubbleSize;
+    private int mBubbleElevation;
     private int mBubblePaddingTop;
     private int mBubbleTouchPadding;
     private int mExpandedViewPadding;
@@ -326,7 +328,9 @@
         mInflater = LayoutInflater.from(context);
 
         Resources res = getResources();
+        mMaxBubbles = res.getInteger(R.integer.bubbles_max_rendered);
         mBubbleSize = res.getDimensionPixelSize(R.dimen.individual_bubble_size);
+        mBubbleElevation = res.getDimensionPixelSize(R.dimen.bubble_elevation);
         mBubblePaddingTop = res.getDimensionPixelSize(R.dimen.bubble_padding_top);
         mBubbleTouchPadding = res.getDimensionPixelSize(R.dimen.bubble_touch_padding);
         mExpandedAnimateXDistance =
@@ -1597,8 +1601,7 @@
         for (int i = 0; i < bubbleCount; i++) {
             BubbleView bv = (BubbleView) mBubbleContainer.getChildAt(i);
             bv.updateDotVisibility(true /* animate */);
-            bv.setZ((BubbleController.MAX_BUBBLES
-                    * getResources().getDimensionPixelSize(R.dimen.bubble_elevation)) - i);
+            bv.setZ((mMaxBubbles * mBubbleElevation) - i);
             // If the dot is on the left, and so is the stack, we need to change the dot position.
             if (bv.getDotPositionOnLeft() == mStackOnLeftOrWillBe) {
                 bv.setDotPosition(!mStackOnLeftOrWillBe, animate);
diff --git a/packages/SystemUI/src/com/android/systemui/classifier/FalsingLog.java b/packages/SystemUI/src/com/android/systemui/classifier/FalsingLog.java
index cb7c998..8105c6a 100644
--- a/packages/SystemUI/src/com/android/systemui/classifier/FalsingLog.java
+++ b/packages/SystemUI/src/com/android/systemui/classifier/FalsingLog.java
@@ -37,7 +37,7 @@
  *  adb shell setprop debug.falsing_log true
  *
  * The log gets dumped as part of the SystemUI services. To dump on demand:
- *  adb shell dumpsys activity service com.android.systemui SystemBars | grep -A 999 FALSING | less
+ *  adb shell dumpsys activity service com.android.systemui StatusBar | grep -A 999 FALSING | less
  *
  * To dump into logcat:
  *  adb shell setprop debug.falsing_logcat true
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java b/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java
index 1d7e9ea..419fd62 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeDockHandler.java
@@ -82,7 +82,7 @@
 
     private void requestPulse(State dozeState) {
         if (!mDozeHost.isPulsingBlocked() && dozeState.canPulse()) {
-            mMachine.requestPulse(DozeLog.PULSE_REASON_DOCKING);
+            mMachine.requestPulse(DozeEvent.PULSE_REASON_DOCKING);
         }
         mPulsePending = false;
     }
@@ -91,7 +91,7 @@
         if (dozeState == State.DOZE_REQUEST_PULSE || dozeState == State.DOZE_PULSING
                 || dozeState == State.DOZE_PULSING_BRIGHT) {
             final int pulseReason = mMachine.getPulseReason();
-            if (pulseReason == DozeLog.PULSE_REASON_DOCKING) {
+            if (pulseReason == DozeEvent.PULSE_REASON_DOCKING) {
                 mDozeHost.stopPulsing();
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java b/packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java
new file mode 100644
index 0000000..ea1def0
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeEvent.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2019 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.doze;
+
+import android.annotation.IntDef;
+
+import com.android.systemui.log.RichEvent;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * An event related to dozing. {@link DozeLog} stores and prints these events for debugging
+ * and triaging purposes.
+ */
+public class DozeEvent extends RichEvent {
+    public static final int TOTAL_EVENT_TYPES = 19;
+
+    public DozeEvent(int logLevel, int type, String reason) {
+        super(logLevel, type, reason);
+    }
+
+    /**
+     * Event labels for each doze event
+     * Index corresponds to the integer associated with each {@link EventType}
+     */
+    @Override
+    public String[] getEventLabels() {
+        final String[] events = new String[]{
+                "PickupWakeup",
+                "PulseStart",
+                "PulseFinish",
+                "NotificationPulse",
+                "Dozing",
+                "Fling",
+                "EmergencyCall",
+                "KeyguardBouncerChanged",
+                "ScreenOn",
+                "ScreenOff",
+                "MissedTick",
+                "TimeTickScheduled",
+                "KeyguardVisibilityChanged",
+                "DozeStateChanged",
+                "WakeDisplay",
+                "ProximityResult",
+                "PulseDropped",
+                "PulseDisabledByProx",
+                "SensorTriggered"
+        };
+
+        if (events.length != TOTAL_EVENT_TYPES) {
+            throw new IllegalStateException("DozeEvent events.length should match TOTAL_EVENT_TYPES"
+                    + " events.length=" + events.length
+                    + " TOTAL_EVENT_LENGTH=" + TOTAL_EVENT_TYPES);
+        }
+        return events;
+    }
+
+    /**
+     * Converts the reason (integer) to a user-readable string
+     */
+    public static String reasonToString(@Reason int pulseReason) {
+        switch (pulseReason) {
+            case PULSE_REASON_INTENT: return "intent";
+            case PULSE_REASON_NOTIFICATION: return "notification";
+            case PULSE_REASON_SENSOR_SIGMOTION: return "sigmotion";
+            case REASON_SENSOR_PICKUP: return "pickup";
+            case REASON_SENSOR_DOUBLE_TAP: return "doubletap";
+            case PULSE_REASON_SENSOR_LONG_PRESS: return "longpress";
+            case PULSE_REASON_DOCKING: return "docking";
+            case PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN: return "wakelockscreen";
+            case REASON_SENSOR_WAKE_UP: return "wakeup";
+            case REASON_SENSOR_TAP: return "tap";
+            default: throw new IllegalArgumentException("invalid reason: " + pulseReason);
+        }
+    }
+
+    /**
+     * Builds a DozeEvent.
+     */
+    public static class DozeEventBuilder extends RichEvent.Builder<DozeEventBuilder> {
+        @Override
+        public DozeEventBuilder getBuilder() {
+            return this;
+        }
+
+        @Override
+        public RichEvent build() {
+            return new DozeEvent(mLogLevel, mType, mReason);
+        }
+    }
+
+    @IntDef({PICKUP_WAKEUP, PULSE_START, PULSE_FINISH, NOTIFICATION_PULSE, DOZING, FLING,
+            EMERGENCY_CALL, KEYGUARD_BOUNCER_CHANGED, SCREEN_ON, SCREEN_OFF, MISSED_TICK,
+            TIME_TICK_SCHEDULED, KEYGUARD_VISIBILITY_CHANGE, DOZE_STATE_CHANGED, WAKE_DISPLAY,
+            PROXIMITY_RESULT, PULSE_DROPPED, PULSE_DISABLED_BY_PROX, SENSOR_TRIGGERED})
+    /**
+     * Types of DozeEvents
+     */
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface EventType {}
+    public static final int PICKUP_WAKEUP = 0;
+    public static final int PULSE_START = 1;
+    public static final int PULSE_FINISH = 2;
+    public static final int NOTIFICATION_PULSE = 3;
+    public static final int DOZING = 4;
+    public static final int FLING = 5;
+    public static final int EMERGENCY_CALL = 6;
+    public static final int KEYGUARD_BOUNCER_CHANGED = 7;
+    public static final int SCREEN_ON = 8;
+    public static final int SCREEN_OFF = 9;
+    public static final int MISSED_TICK = 10;
+    public static final int TIME_TICK_SCHEDULED = 11;
+    public static final int KEYGUARD_VISIBILITY_CHANGE = 12;
+    public static final int DOZE_STATE_CHANGED = 13;
+    public static final int WAKE_DISPLAY = 14;
+    public static final int PROXIMITY_RESULT = 15;
+    public static final int PULSE_DROPPED = 16;
+    public static final int PULSE_DISABLED_BY_PROX = 17;
+    public static final int SENSOR_TRIGGERED = 18;
+
+    public static final int TOTAL_REASONS = 10;
+    @IntDef({PULSE_REASON_NONE, PULSE_REASON_INTENT, PULSE_REASON_NOTIFICATION,
+            PULSE_REASON_SENSOR_SIGMOTION, REASON_SENSOR_PICKUP, REASON_SENSOR_DOUBLE_TAP,
+            PULSE_REASON_SENSOR_LONG_PRESS, PULSE_REASON_DOCKING, REASON_SENSOR_WAKE_UP,
+            PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN, REASON_SENSOR_TAP})
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface Reason {}
+    public static final int PULSE_REASON_NONE = -1;
+    public static final int PULSE_REASON_INTENT = 0;
+    public static final int PULSE_REASON_NOTIFICATION = 1;
+    public static final int PULSE_REASON_SENSOR_SIGMOTION = 2;
+    public static final int REASON_SENSOR_PICKUP = 3;
+    public static final int REASON_SENSOR_DOUBLE_TAP = 4;
+    public static final int PULSE_REASON_SENSOR_LONG_PRESS = 5;
+    public static final int PULSE_REASON_DOCKING = 6;
+    public static final int REASON_SENSOR_WAKE_UP = 7;
+    public static final int PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN = 8;
+    public static final int REASON_SENSOR_TAP = 9;
+}
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java b/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
index bb8c7f1..ca4ec6d 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeFactory.java
@@ -33,7 +33,9 @@
 import com.android.systemui.plugins.FalsingManager;
 import com.android.systemui.statusbar.phone.BiometricUnlockController;
 import com.android.systemui.statusbar.phone.DozeParameters;
+import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.util.sensors.AsyncSensorManager;
+import com.android.systemui.util.sensors.ProximitySensor;
 import com.android.systemui.util.wakelock.DelayedWakeLock;
 import com.android.systemui.util.wakelock.WakeLock;
 
@@ -43,7 +45,8 @@
     }
 
     /** Creates a DozeMachine with its parts for {@code dozeService}. */
-    public DozeMachine assembleMachine(DozeService dozeService, FalsingManager falsingManager) {
+    public DozeMachine assembleMachine(DozeService dozeService, FalsingManager falsingManager,
+            DozeLog dozeLog) {
         Context context = dozeService;
         AsyncSensorManager sensorManager = Dependency.get(AsyncSensorManager.class);
         AlarmManager alarmManager = context.getSystemService(AlarmManager.class);
@@ -64,13 +67,14 @@
                 params);
 
         DozeMachine machine = new DozeMachine(wrappedService, config, wakeLock,
-                wakefulnessLifecycle);
+                wakefulnessLifecycle, Dependency.get(BatteryController.class), dozeLog);
         machine.setParts(new DozeMachine.Part[]{
                 new DozePauser(handler, machine, alarmManager, params.getPolicy()),
                 new DozeFalsingManagerAdapter(falsingManager),
                 createDozeTriggers(context, sensorManager, host, alarmManager, config, params,
-                        handler, wakeLock, machine, dockManager),
-                createDozeUi(context, host, wakeLock, machine, handler, alarmManager, params),
+                        handler, wakeLock, machine, dockManager, dozeLog),
+                createDozeUi(context, host, wakeLock, machine, handler, alarmManager, params,
+                        dozeLog),
                 new DozeScreenState(wrappedService, handler, params, wakeLock),
                 createDozeScreenBrightness(context, wrappedService, sensorManager, host, params,
                         handler),
@@ -94,17 +98,19 @@
     private DozeTriggers createDozeTriggers(Context context, AsyncSensorManager sensorManager,
             DozeHost host, AlarmManager alarmManager, AmbientDisplayConfiguration config,
             DozeParameters params, Handler handler, WakeLock wakeLock, DozeMachine machine,
-            DockManager dockManager) {
+            DockManager dockManager, DozeLog dozeLog) {
         boolean allowPulseTriggers = true;
         return new DozeTriggers(context, machine, host, alarmManager, config, params,
-                sensorManager, handler, wakeLock, allowPulseTriggers, dockManager);
+                sensorManager, handler, wakeLock, allowPulseTriggers, dockManager,
+                new ProximitySensor(context, sensorManager), dozeLog);
+
     }
 
     private DozeMachine.Part createDozeUi(Context context, DozeHost host, WakeLock wakeLock,
             DozeMachine machine, Handler handler, AlarmManager alarmManager,
-            DozeParameters params) {
+            DozeParameters params, DozeLog dozeLog) {
         return new DozeUi(context, alarmManager, machine, wakeLock, host, handler, params,
-                Dependency.get(KeyguardUpdateMonitor.class));
+                Dependency.get(KeyguardUpdateMonitor.class), dozeLog);
     }
 
     public static DozeHost getHost(DozeService service) {
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
index 8fe9f92..2e4466d 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java
@@ -16,282 +16,284 @@
 
 package com.android.systemui.doze;
 
-import android.content.Context;
-import android.os.Build;
-import android.util.Log;
 import android.util.TimeUtils;
 
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.keyguard.KeyguardUpdateMonitorCallback;
-import com.android.systemui.Dependency;
+import com.android.systemui.DumpController;
+import com.android.systemui.log.SysuiLog;
 
 import java.io.PrintWriter;
-import java.text.SimpleDateFormat;
 import java.util.Date;
 
-public class DozeLog {
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+/**
+ * Logs doze events for debugging and triaging purposes. Logs are dumped in bugreports or on demand:
+ *      adb shell dumpsys activity service com.android.systemui/.SystemUIService \
+ *      dependency DumpController DozeLog
+ */
+@Singleton
+public class DozeLog extends SysuiLog {
     private static final String TAG = "DozeLog";
-    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
-    private static final boolean ENABLED = true;
-    private static final int SIZE = Build.IS_DEBUGGABLE ? 400 : 50;
-    static final SimpleDateFormat FORMAT = new SimpleDateFormat("MM-dd HH:mm:ss.SSS");
 
-    public static final int REASONS = 10;
+    private boolean mPulsing;
+    private long mSince;
+    private SummaryStats mPickupPulseNearVibrationStats;
+    private SummaryStats mPickupPulseNotNearVibrationStats;
+    private SummaryStats mNotificationPulseStats;
+    private SummaryStats mScreenOnPulsingStats;
+    private SummaryStats mScreenOnNotPulsingStats;
+    private SummaryStats mEmergencyCallStats;
+    private SummaryStats[][] mProxStats; // [reason][near/far]
 
-    public static final int PULSE_REASON_NONE = -1;
-    public static final int PULSE_REASON_INTENT = 0;
-    public static final int PULSE_REASON_NOTIFICATION = 1;
-    public static final int PULSE_REASON_SENSOR_SIGMOTION = 2;
-    public static final int REASON_SENSOR_PICKUP = 3;
-    public static final int REASON_SENSOR_DOUBLE_TAP = 4;
-    public static final int PULSE_REASON_SENSOR_LONG_PRESS = 5;
-    public static final int PULSE_REASON_DOCKING = 6;
-    public static final int REASON_SENSOR_WAKE_UP = 7;
-    public static final int PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN = 8;
-    public static final int REASON_SENSOR_TAP = 9;
+    @Inject
+    public DozeLog(KeyguardUpdateMonitor keyguardUpdateMonitor, DumpController dumpController) {
+        super(dumpController, TAG, MAX_DOZE_DEBUG_LOGS, MAX_DOZE_LOGS);
+        mSince = System.currentTimeMillis();
+        mPickupPulseNearVibrationStats = new SummaryStats();
+        mPickupPulseNotNearVibrationStats = new SummaryStats();
+        mNotificationPulseStats = new SummaryStats();
+        mScreenOnPulsingStats = new SummaryStats();
+        mScreenOnNotPulsingStats = new SummaryStats();
+        mEmergencyCallStats = new SummaryStats();
+        mProxStats = new SummaryStats[DozeEvent.TOTAL_REASONS][2];
+        for (int i = 0; i < DozeEvent.TOTAL_REASONS; i++) {
+            mProxStats[i][0] = new SummaryStats();
+            mProxStats[i][1] = new SummaryStats();
+        }
 
-    private static boolean sRegisterKeyguardCallback = true;
-
-    private static long[] sTimes;
-    private static String[] sMessages;
-    private static int sPosition;
-    private static int sCount;
-    private static boolean sPulsing;
-
-    private static long sSince;
-    private static SummaryStats sPickupPulseNearVibrationStats;
-    private static SummaryStats sPickupPulseNotNearVibrationStats;
-    private static SummaryStats sNotificationPulseStats;
-    private static SummaryStats sScreenOnPulsingStats;
-    private static SummaryStats sScreenOnNotPulsingStats;
-    private static SummaryStats sEmergencyCallStats;
-    private static SummaryStats[][] sProxStats; // [reason][near/far]
-
-    public static void tracePickupWakeUp(Context context, boolean withinVibrationThreshold) {
-        if (!ENABLED) return;
-        init(context);
-        log("pickupWakeUp withinVibrationThreshold=" + withinVibrationThreshold);
-        (withinVibrationThreshold ? sPickupPulseNearVibrationStats
-                : sPickupPulseNotNearVibrationStats).append();
-    }
-
-    public static void tracePulseStart(int reason) {
-        if (!ENABLED) return;
-        sPulsing = true;
-        log("pulseStart reason=" + reasonToString(reason));
-    }
-
-    public static void tracePulseFinish() {
-        if (!ENABLED) return;
-        sPulsing = false;
-        log("pulseFinish");
-    }
-
-    public static void traceNotificationPulse(Context context) {
-        if (!ENABLED) return;
-        init(context);
-        log("notificationPulse");
-        sNotificationPulseStats.append();
-    }
-
-    private static void init(Context context) {
-        synchronized (DozeLog.class) {
-            if (sMessages == null) {
-                sTimes = new long[SIZE];
-                sMessages = new String[SIZE];
-                sSince = System.currentTimeMillis();
-                sPickupPulseNearVibrationStats = new SummaryStats();
-                sPickupPulseNotNearVibrationStats = new SummaryStats();
-                sNotificationPulseStats = new SummaryStats();
-                sScreenOnPulsingStats = new SummaryStats();
-                sScreenOnNotPulsingStats = new SummaryStats();
-                sEmergencyCallStats = new SummaryStats();
-                sProxStats = new SummaryStats[REASONS][2];
-                for (int i = 0; i < REASONS; i++) {
-                    sProxStats[i][0] = new SummaryStats();
-                    sProxStats[i][1] = new SummaryStats();
-                }
-                log("init");
-                if (sRegisterKeyguardCallback) {
-                    Dependency.get(KeyguardUpdateMonitor.class).registerCallback(sKeyguardCallback);
-                }
-            }
+        if (keyguardUpdateMonitor != null) {
+            keyguardUpdateMonitor.registerCallback(mKeyguardCallback);
         }
     }
 
-    public static void traceDozing(Context context, boolean dozing) {
-        if (!ENABLED) return;
-        sPulsing = false;
-        init(context);
-        log("dozing " + dozing);
+    /**
+     * Appends pickup wakeup event to the logs
+     */
+    public void tracePickupWakeUp(boolean withinVibrationThreshold) {
+        if (log(DozeEvent.PICKUP_WAKEUP,
+                "withinVibrationThreshold=" + withinVibrationThreshold)) {
+            (withinVibrationThreshold ? mPickupPulseNearVibrationStats
+                    : mPickupPulseNotNearVibrationStats).append();
+        }
     }
 
-    public static void traceFling(boolean expand, boolean aboveThreshold, boolean thresholdNeeded,
+    /**
+     * Appends pulse started event to the logs.
+     * @param reason why the pulse started
+     */
+    public void tracePulseStart(@DozeEvent.Reason int reason) {
+        if (log(DozeEvent.PULSE_START, DozeEvent.reasonToString(reason))) {
+            mPulsing = true;
+        }
+    }
+
+    /**
+     * Appends pulse finished event to the logs
+     */
+    public void tracePulseFinish() {
+        if (log(DozeEvent.PULSE_FINISH)) {
+            mPulsing = false;
+        }
+    }
+
+    /**
+     * Appends pulse event to the logs
+     */
+    public void traceNotificationPulse() {
+        if (log(DozeEvent.NOTIFICATION_PULSE)) {
+            mNotificationPulseStats.append();
+        }
+    }
+
+    /**
+     * Appends dozing event to the logs
+     * @param dozing true if dozing, else false
+     */
+    public void traceDozing(boolean dozing) {
+        if (log(DozeEvent.DOZING, "dozing=" + dozing)) {
+            mPulsing = false;
+        }
+    }
+
+    /**
+     * Appends fling event to the logs
+     */
+    public void traceFling(boolean expand, boolean aboveThreshold, boolean thresholdNeeded,
             boolean screenOnFromTouch) {
-        if (!ENABLED) return;
-        log("fling expand=" + expand + " aboveThreshold=" + aboveThreshold + " thresholdNeeded="
-                + thresholdNeeded + " screenOnFromTouch=" + screenOnFromTouch);
+        log(DozeEvent.FLING, "expand=" + expand
+                + " aboveThreshold=" + aboveThreshold
+                + " thresholdNeeded=" + thresholdNeeded
+                + " screenOnFromTouch=" + screenOnFromTouch);
     }
 
-    public static void traceEmergencyCall() {
-        if (!ENABLED) return;
-        log("emergencyCall");
-        sEmergencyCallStats.append();
-    }
-
-    public static void traceKeyguardBouncerChanged(boolean showing) {
-        if (!ENABLED) return;
-        log("bouncer " + showing);
-    }
-
-    public static void traceScreenOn() {
-        if (!ENABLED) return;
-        log("screenOn pulsing=" + sPulsing);
-        (sPulsing ? sScreenOnPulsingStats : sScreenOnNotPulsingStats).append();
-        sPulsing = false;
-    }
-
-    public static void traceScreenOff(int why) {
-        if (!ENABLED) return;
-        log("screenOff why=" + why);
-    }
-
-    public static void traceMissedTick(String delay) {
-        if (!ENABLED) return;
-        log("missedTick by=" + delay);
-    }
-
-    public static void traceTimeTickScheduled(long when, long triggerAt) {
-        if (!ENABLED) return;
-        log("timeTickScheduled at=" + FORMAT.format(new Date(when)) + " triggerAt="
-                + FORMAT.format(new Date(triggerAt)));
-    }
-
-    public static void traceKeyguard(boolean showing) {
-        if (!ENABLED) return;
-        log("keyguard " + showing);
-        if (!showing) {
-            sPulsing = false;
+    /**
+     * Appends emergency call event to the logs
+     */
+    public void traceEmergencyCall() {
+        if (log(DozeEvent.EMERGENCY_CALL)) {
+            mEmergencyCallStats.append();
         }
     }
 
-    public static void traceState(DozeMachine.State state) {
-        if (!ENABLED) return;
-        log("state " + state);
+    /**
+     * Appends keyguard bouncer changed event to the logs
+     * @param showing true if the keyguard bouncer is showing, else false
+     */
+    public void traceKeyguardBouncerChanged(boolean showing) {
+        log(DozeEvent.KEYGUARD_BOUNCER_CHANGED, "showing=" + showing);
+    }
+
+    /**
+     * Appends screen-on event to the logs
+     */
+    public void traceScreenOn() {
+        if (log(DozeEvent.SCREEN_ON, "pulsing=" + mPulsing)) {
+            (mPulsing ? mScreenOnPulsingStats : mScreenOnNotPulsingStats).append();
+            mPulsing = false;
+        }
+    }
+
+    /**
+     * Appends screen-off event to the logs
+     * @param why reason the screen is off
+     */
+    public void traceScreenOff(int why) {
+        log(DozeEvent.SCREEN_OFF, "why=" + why);
+    }
+
+    /**
+     * Appends missed tick event to the logs
+     * @param delay of the missed tick
+     */
+    public void traceMissedTick(String delay) {
+        log(DozeEvent.MISSED_TICK, "delay=" + delay);
+    }
+
+    /**
+     * Appends time tick scheduled event to the logs
+     * @param when time tick scheduled at
+     * @param triggerAt time tick trigger at
+     */
+    public void traceTimeTickScheduled(long when, long triggerAt) {
+        log(DozeEvent.TIME_TICK_SCHEDULED,
+                "scheduledAt=" + DATE_FORMAT.format(new Date(when))
+                + " triggerAt=" + DATE_FORMAT.format(new Date(triggerAt)));
+    }
+
+    /**
+     * Appends keyguard visibility change event to the logs
+     * @param showing whether the keyguard is now showing
+     */
+    public void traceKeyguard(boolean showing) {
+        if (log(DozeEvent.KEYGUARD_VISIBILITY_CHANGE, "showing=" + showing)
+                && !showing) {
+            mPulsing = false;
+        }
+    }
+
+    /**
+     * Appends doze state changed event to the logs
+     * @param state new DozeMachine state
+     */
+    public void traceState(DozeMachine.State state) {
+        log(DozeEvent.DOZE_STATE_CHANGED, state.name());
     }
 
     /**
      * Appends wake-display event to the logs.
      * @param wake if we're waking up or sleeping.
      */
-    public static void traceWakeDisplay(boolean wake) {
-        if (!ENABLED) return;
-        log("wakeDisplay " + wake);
+    public void traceWakeDisplay(boolean wake) {
+        log(DozeEvent.WAKE_DISPLAY, "wake=" + wake);
     }
 
-    public static void traceProximityResult(Context context, boolean near, long millis,
-            int reason) {
-        if (!ENABLED) return;
-        init(context);
-        log("proximityResult reason=" + reasonToString(reason) + " near=" + near
-                + " millis=" + millis);
-        sProxStats[reason][near ? 0 : 1].append();
-    }
-
-    public static String reasonToString(int pulseReason) {
-        switch (pulseReason) {
-            case PULSE_REASON_INTENT: return "intent";
-            case PULSE_REASON_NOTIFICATION: return "notification";
-            case PULSE_REASON_SENSOR_SIGMOTION: return "sigmotion";
-            case REASON_SENSOR_PICKUP: return "pickup";
-            case REASON_SENSOR_DOUBLE_TAP: return "doubletap";
-            case PULSE_REASON_SENSOR_LONG_PRESS: return "longpress";
-            case PULSE_REASON_DOCKING: return "docking";
-            case PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN: return "wakelockscreen";
-            case REASON_SENSOR_WAKE_UP: return "wakeup";
-            case REASON_SENSOR_TAP: return "tap";
-            default: throw new IllegalArgumentException("bad reason: " + pulseReason);
+    /**
+     * Appends proximity result event to the logs
+     * @param near true if near, else false
+     * @param millis
+     * @param reason why proximity result was triggered
+     */
+    public void traceProximityResult(boolean near, long millis, @DozeEvent.Reason int reason) {
+        if (log(DozeEvent.PROXIMITY_RESULT,
+                " reason=" + DozeEvent.reasonToString(reason)
+                + " near=" + near
+                + " millis=" + millis)) {
+            mProxStats[reason][near ? 0 : 1].append();
         }
     }
 
-    public static void dump(PrintWriter pw) {
+    /**
+     * Prints doze log timeline and consolidated stats
+     * @param pw
+     */
+    public void dump(PrintWriter pw) {
         synchronized (DozeLog.class) {
-            if (sMessages == null) return;
-            pw.println("  Doze log:");
-            final int start = (sPosition - sCount + SIZE) % SIZE;
-            for (int i = 0; i < sCount; i++) {
-                final int j = (start + i) % SIZE;
-                pw.print("    ");
-                pw.print(FORMAT.format(new Date(sTimes[j])));
-                pw.print(' ');
-                pw.println(sMessages[j]);
-            }
+            super.dump(null, pw, null); // prints timeline
+
             pw.print("  Doze summary stats (for ");
-            TimeUtils.formatDuration(System.currentTimeMillis() - sSince, pw);
+            TimeUtils.formatDuration(System.currentTimeMillis() - mSince, pw);
             pw.println("):");
-            sPickupPulseNearVibrationStats.dump(pw, "Pickup pulse (near vibration)");
-            sPickupPulseNotNearVibrationStats.dump(pw, "Pickup pulse (not near vibration)");
-            sNotificationPulseStats.dump(pw, "Notification pulse");
-            sScreenOnPulsingStats.dump(pw, "Screen on (pulsing)");
-            sScreenOnNotPulsingStats.dump(pw, "Screen on (not pulsing)");
-            sEmergencyCallStats.dump(pw, "Emergency call");
-            for (int i = 0; i < REASONS; i++) {
-                final String reason = reasonToString(i);
-                sProxStats[i][0].dump(pw, "Proximity near (" + reason + ")");
-                sProxStats[i][1].dump(pw, "Proximity far (" + reason + ")");
+            mPickupPulseNearVibrationStats.dump(pw, "Pickup pulse (near vibration)");
+            mPickupPulseNotNearVibrationStats.dump(pw, "Pickup pulse (not near vibration)");
+            mNotificationPulseStats.dump(pw, "Notification pulse");
+            mScreenOnPulsingStats.dump(pw, "Screen on (pulsing)");
+            mScreenOnNotPulsingStats.dump(pw, "Screen on (not pulsing)");
+            mEmergencyCallStats.dump(pw, "Emergency call");
+            for (int i = 0; i < DozeEvent.TOTAL_REASONS; i++) {
+                final String reason = DozeEvent.reasonToString(i);
+                mProxStats[i][0].dump(pw, "Proximity near (" + reason + ")");
+                mProxStats[i][1].dump(pw, "Proximity far (" + reason + ")");
             }
         }
     }
 
-    private static void log(String msg) {
-        synchronized (DozeLog.class) {
-            if (sMessages == null) return;
-            sTimes[sPosition] = System.currentTimeMillis();
-            sMessages[sPosition] = msg;
-            sPosition = (sPosition + 1) % SIZE;
-            sCount = Math.min(sCount + 1, SIZE);
-        }
-        if (DEBUG) Log.d(TAG, msg);
+    private boolean log(@DozeEvent.EventType int eventType) {
+        return log(eventType, "");
     }
 
-    public static void tracePulseDropped(Context context, boolean pulsePending,
-            DozeMachine.State state, boolean blocked) {
-        if (!ENABLED) return;
-        init(context);
-        log("pulseDropped pulsePending=" + pulsePending + " state="
-                + state + " blocked=" + blocked);
+    private boolean log(@DozeEvent.EventType int eventType, String msg) {
+        return super.log(new DozeEvent.DozeEventBuilder()
+                .setType(eventType)
+                .setReason(msg)
+                .build());
     }
 
-    public static void tracePulseDropped(Context context, String why) {
-        if (!ENABLED) return;
-        init(context);
-        log("pulseDropped why=" + why);
+    /**
+     * Appends pulse dropped event to logs
+     */
+    public void tracePulseDropped(boolean pulsePending, DozeMachine.State state, boolean blocked) {
+        log(DozeEvent.PULSE_DROPPED, "pulsePending=" + pulsePending + " state="
+                + state.name() + " blocked=" + blocked);
     }
 
-    public static void tracePulseTouchDisabledByProx(Context context, boolean disabled) {
-        if (!ENABLED) return;
-        init(context);
-        log("pulseTouchDisabledByProx " + disabled);
+    /**
+     * Appends pulse dropped event to logs
+     * @param reason why the pulse was dropped
+     */
+    public void tracePulseDropped(String reason) {
+        log(DozeEvent.PULSE_DROPPED, "why=" + reason);
     }
 
-    public static void setRegisterKeyguardCallback(boolean registerKeyguardCallback) {
-        if (!ENABLED) return;
-        synchronized (DozeLog.class) {
-            if (sRegisterKeyguardCallback != registerKeyguardCallback && sMessages != null) {
-                throw new IllegalStateException("Cannot change setRegisterKeyguardCallback "
-                        + "after init()");
-            }
-            sRegisterKeyguardCallback = registerKeyguardCallback;
-        }
+    /**
+     * Appends pulse touch displayed by prox sensor event to logs
+     * @param disabled
+     */
+    public void tracePulseTouchDisabledByProx(boolean disabled) {
+        log(DozeEvent.PULSE_DISABLED_BY_PROX, "disabled=" + disabled);
     }
 
-    public static void traceSensor(Context context, int reason) {
-        if (!ENABLED) return;
-        init(context);
-        log("sensor type=" + reasonToString(reason));
+    /**
+     * Appends sensor triggered event to logs
+     * @param reason why the sensor was triggered
+     */
+    public void traceSensor(@DozeEvent.Reason int reason) {
+        log(DozeEvent.SENSOR_TRIGGERED, "type=" + DozeEvent.reasonToString(reason));
     }
 
-    private static class SummaryStats {
+    private class SummaryStats {
         private int mCount;
 
         public void append() {
@@ -305,7 +307,7 @@
             pw.print(": n=");
             pw.print(mCount);
             pw.print(" (");
-            final double perHr = (double) mCount / (System.currentTimeMillis() - sSince)
+            final double perHr = (double) mCount / (System.currentTimeMillis() - mSince)
                     * 1000 * 60 * 60;
             pw.print(perHr);
             pw.print("/hr)");
@@ -313,7 +315,7 @@
         }
     }
 
-    private static final KeyguardUpdateMonitorCallback sKeyguardCallback =
+    private final KeyguardUpdateMonitorCallback mKeyguardCallback =
             new KeyguardUpdateMonitorCallback() {
         @Override
         public void onEmergencyCallAction() {
@@ -340,4 +342,7 @@
             traceKeyguard(showing);
         }
     };
+
+    private static final int MAX_DOZE_DEBUG_LOGS = 400;
+    private static final int MAX_DOZE_LOGS = 50;
 }
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
index 93a51cc..75b1d6c 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeMachine.java
@@ -27,6 +27,7 @@
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.keyguard.WakefulnessLifecycle.Wakefulness;
 import com.android.systemui.statusbar.phone.DozeParameters;
+import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.util.Assert;
 import com.android.systemui.util.wakelock.WakeLock;
 
@@ -45,6 +46,7 @@
 
     static final String TAG = "DozeMachine";
     static final boolean DEBUG = DozeService.DEBUG;
+    private final DozeLog mDozeLog;
     private static final String REASON_CHANGE_STATE = "DozeMachine#requestState";
     private static final String REASON_HELD_FOR_STATE = "DozeMachine#heldForState";
 
@@ -121,6 +123,7 @@
     private final WakeLock mWakeLock;
     private final AmbientDisplayConfiguration mConfig;
     private final WakefulnessLifecycle mWakefulnessLifecycle;
+    private final BatteryController mBatteryController;
     private Part[] mParts;
 
     private final ArrayList<State> mQueuedRequests = new ArrayList<>();
@@ -129,11 +132,14 @@
     private boolean mWakeLockHeldForCurrentState = false;
 
     public DozeMachine(Service service, AmbientDisplayConfiguration config,
-            WakeLock wakeLock, WakefulnessLifecycle wakefulnessLifecycle) {
+            WakeLock wakeLock, WakefulnessLifecycle wakefulnessLifecycle,
+            BatteryController batteryController, DozeLog dozeLog) {
         mDozeService = service;
         mConfig = config;
         mWakefulnessLifecycle = wakefulnessLifecycle;
         mWakeLock = wakeLock;
+        mBatteryController = batteryController;
+        mDozeLog = dozeLog;
     }
 
     /** Initializes the set of {@link Part}s. Must be called exactly once after construction. */
@@ -155,7 +161,7 @@
     @MainThread
     public void requestState(State requestedState) {
         Preconditions.checkArgument(requestedState != State.DOZE_REQUEST_PULSE);
-        requestState(requestedState, DozeLog.PULSE_REASON_NONE);
+        requestState(requestedState, DozeEvent.PULSE_REASON_NONE);
     }
 
     @MainThread
@@ -243,7 +249,7 @@
         State oldState = mState;
         mState = newState;
 
-        DozeLog.traceState(newState);
+        mDozeLog.traceState(newState);
         Trace.traceCounter(Trace.TRACE_TAG_APP, "doze_machine_state", newState.ordinal());
 
         updatePulseReason(newState, oldState, pulseReason);
@@ -257,7 +263,7 @@
         if (newState == State.DOZE_REQUEST_PULSE) {
             mPulseReason = pulseReason;
         } else if (oldState == State.DOZE_PULSE_DONE) {
-            mPulseReason = DozeLog.PULSE_REASON_NONE;
+            mPulseReason = DozeEvent.PULSE_REASON_NONE;
         }
     }
 
@@ -316,6 +322,9 @@
             Log.i(TAG, "Dropping pulse done because current state is already done: " + mState);
             return mState;
         }
+        if (requestedState == State.DOZE_AOD && mBatteryController.isAodPowerSave()) {
+            return State.DOZE;
+        }
         if (requestedState == State.DOZE_REQUEST_PULSE && !mState.canPulse()) {
             Log.i(TAG, "Dropping pulse request because current state can't pulse: " + mState);
             return mState;
@@ -349,7 +358,7 @@
                     nextState = State.DOZE;
                 }
 
-                transitionTo(nextState, DozeLog.PULSE_REASON_NONE);
+                transitionTo(nextState, DozeEvent.PULSE_REASON_NONE);
                 break;
             default:
                 break;
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
index 67eefc5..7d86028 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
@@ -42,9 +42,7 @@
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto;
-import com.android.systemui.Dependency;
 import com.android.systemui.plugins.SensorManagerPlugin;
-import com.android.systemui.shared.plugins.PluginManager;
 import com.android.systemui.statusbar.phone.DozeParameters;
 import com.android.systemui.util.sensors.AsyncSensorManager;
 import com.android.systemui.util.sensors.ProximitySensor;
@@ -82,7 +80,8 @@
 
     public DozeSensors(Context context, AlarmManager alarmManager, AsyncSensorManager sensorManager,
             DozeParameters dozeParameters, AmbientDisplayConfiguration config, WakeLock wakeLock,
-            Callback callback, Consumer<Boolean> proxCallback, AlwaysOnDisplayPolicy policy) {
+            Callback callback, Consumer<Boolean> proxCallback, AlwaysOnDisplayPolicy policy,
+            DozeLog dozeLog) {
         mContext = context;
         mAlarmManager = alarmManager;
         mSensorManager = sensorManager;
@@ -99,59 +98,69 @@
                         mSensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION),
                         null /* setting */,
                         dozeParameters.getPulseOnSigMotion(),
-                        DozeLog.PULSE_REASON_SENSOR_SIGMOTION, false /* touchCoords */,
-                        false /* touchscreen */),
+                        DozeEvent.PULSE_REASON_SENSOR_SIGMOTION, false /* touchCoords */,
+                        false /* touchscreen */, dozeLog),
                 mPickupSensor = new TriggerSensor(
                         mSensorManager.getDefaultSensor(Sensor.TYPE_PICK_UP_GESTURE),
                         Settings.Secure.DOZE_PICK_UP_GESTURE,
                         true /* settingDef */,
                         config.dozePickupSensorAvailable(),
-                        DozeLog.REASON_SENSOR_PICKUP, false /* touchCoords */,
+                        DozeEvent.REASON_SENSOR_PICKUP, false /* touchCoords */,
                         false /* touchscreen */,
-                        false /* ignoresSetting */),
+                        false /* ignoresSetting */,
+                        dozeLog),
                 new TriggerSensor(
                         findSensorWithType(config.doubleTapSensorType()),
                         Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
                         true /* configured */,
-                        DozeLog.REASON_SENSOR_DOUBLE_TAP,
+                        DozeEvent.REASON_SENSOR_DOUBLE_TAP,
                         dozeParameters.doubleTapReportsTouchCoordinates(),
-                        true /* touchscreen */),
+                        true /* touchscreen */,
+                        dozeLog),
                 new TriggerSensor(
                         findSensorWithType(config.tapSensorType()),
                         Settings.Secure.DOZE_TAP_SCREEN_GESTURE,
                         true /* configured */,
-                        DozeLog.REASON_SENSOR_TAP,
+                        DozeEvent.REASON_SENSOR_TAP,
                         false /* reports touch coordinates */,
-                        true /* touchscreen */),
+                        true /* touchscreen */,
+                        dozeLog),
                 new TriggerSensor(
                         findSensorWithType(config.longPressSensorType()),
                         Settings.Secure.DOZE_PULSE_ON_LONG_PRESS,
                         false /* settingDef */,
                         true /* configured */,
-                        DozeLog.PULSE_REASON_SENSOR_LONG_PRESS,
+                        DozeEvent.PULSE_REASON_SENSOR_LONG_PRESS,
                         true /* reports touch coordinates */,
-                        true /* touchscreen */),
+                        true /* touchscreen */,
+                        dozeLog),
                 new PluginSensor(
                         new SensorManagerPlugin.Sensor(TYPE_WAKE_DISPLAY),
                         Settings.Secure.DOZE_WAKE_DISPLAY_GESTURE,
                         mConfig.wakeScreenGestureAvailable() && alwaysOn,
-                        DozeLog.REASON_SENSOR_WAKE_UP,
+                        DozeEvent.REASON_SENSOR_WAKE_UP,
                         false /* reports touch coordinates */,
-                        false /* touchscreen */),
+                        false /* touchscreen */,
+                        dozeLog),
                 new PluginSensor(
                         new SensorManagerPlugin.Sensor(TYPE_WAKE_LOCK_SCREEN),
                         Settings.Secure.DOZE_WAKE_LOCK_SCREEN_GESTURE,
                         mConfig.wakeScreenGestureAvailable(),
-                        DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN,
+                        DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN,
                         false /* reports touch coordinates */,
-                        false /* touchscreen */, mConfig.getWakeLockScreenDebounce()),
+                        false /* touchscreen */,
+                        mConfig.getWakeLockScreenDebounce(),
+                        dozeLog),
         };
 
-        mProximitySensor = new ProximitySensor(
-                context, sensorManager, Dependency.get(PluginManager.class));
+        mProximitySensor = new ProximitySensor(context, sensorManager);
 
         mProximitySensor.register(
-                proximityEvent -> mProxCallback.accept(!proximityEvent.getNear()));
+                proximityEvent -> {
+                    if (proximityEvent != null) {
+                        mProxCallback.accept(!proximityEvent.getNear());
+                    }
+                });
     }
 
     /**
@@ -305,23 +314,24 @@
         protected boolean mRegistered;
         protected boolean mDisabled;
         protected boolean mIgnoresSetting;
+        protected final DozeLog mDozeLog;
 
         public TriggerSensor(Sensor sensor, String setting, boolean configured, int pulseReason,
-                boolean reportsTouchCoordinates, boolean requiresTouchscreen) {
+                boolean reportsTouchCoordinates, boolean requiresTouchscreen, DozeLog dozeLog) {
             this(sensor, setting, true /* settingDef */, configured, pulseReason,
-                    reportsTouchCoordinates, requiresTouchscreen);
+                    reportsTouchCoordinates, requiresTouchscreen, dozeLog);
         }
 
         public TriggerSensor(Sensor sensor, String setting, boolean settingDef,
                 boolean configured, int pulseReason, boolean reportsTouchCoordinates,
-                boolean requiresTouchscreen) {
+                boolean requiresTouchscreen, DozeLog dozeLog) {
             this(sensor, setting, settingDef, configured, pulseReason, reportsTouchCoordinates,
-                    requiresTouchscreen, false /* ignoresSetting */);
+                    requiresTouchscreen, false /* ignoresSetting */, dozeLog);
         }
 
         private TriggerSensor(Sensor sensor, String setting, boolean settingDef,
                 boolean configured, int pulseReason, boolean reportsTouchCoordinates,
-                boolean requiresTouchscreen, boolean ignoresSetting) {
+                boolean requiresTouchscreen, boolean ignoresSetting, DozeLog dozeLog) {
             mSensor = sensor;
             mSetting = setting;
             mSettingDefault = settingDef;
@@ -330,6 +340,7 @@
             mReportsTouchCoordinates = reportsTouchCoordinates;
             mRequiresTouchscreen = requiresTouchscreen;
             mIgnoresSetting = ignoresSetting;
+            mDozeLog = dozeLog;
         }
 
         public void setListening(boolean listen) {
@@ -386,7 +397,7 @@
         @Override
         @AnyThread
         public void onTrigger(TriggerEvent event) {
-            DozeLog.traceSensor(mContext, mPulseReason);
+            mDozeLog.traceSensor(mPulseReason);
             mHandler.post(mWakeLock.wrap(() -> {
                 if (DEBUG) Log.d(TAG, "onTrigger: " + triggerEventToString(event));
                 if (mSensor != null && mSensor.getType() == Sensor.TYPE_PICK_UP_GESTURE) {
@@ -442,16 +453,17 @@
         private long mDebounce;
 
         PluginSensor(SensorManagerPlugin.Sensor sensor, String setting, boolean configured,
-                int pulseReason, boolean reportsTouchCoordinates, boolean requiresTouchscreen) {
+                int pulseReason, boolean reportsTouchCoordinates, boolean requiresTouchscreen,
+                DozeLog dozeLog) {
             this(sensor, setting, configured, pulseReason, reportsTouchCoordinates,
-                    requiresTouchscreen, 0L /* debounce */);
+                    requiresTouchscreen, 0L /* debounce */, dozeLog);
         }
 
         PluginSensor(SensorManagerPlugin.Sensor sensor, String setting, boolean configured,
                 int pulseReason, boolean reportsTouchCoordinates, boolean requiresTouchscreen,
-                long debounce) {
+                long debounce, DozeLog dozeLog) {
             super(null, setting, configured, pulseReason, reportsTouchCoordinates,
-                    requiresTouchscreen);
+                    requiresTouchscreen, dozeLog);
             mPluginSensor = sensor;
             mDebounce = debounce;
         }
@@ -497,7 +509,7 @@
 
         @Override
         public void onSensorChanged(SensorManagerPlugin.SensorEvent event) {
-            DozeLog.traceSensor(mContext, mPulseReason);
+            mDozeLog.traceSensor(mPulseReason);
             mHandler.post(mWakeLock.wrap(() -> {
                 final long now = SystemClock.uptimeMillis();
                 if (now < mDebounceFrom + mDebounce) {
@@ -514,7 +526,7 @@
 
         /**
          * Called when a sensor requests a pulse
-         * @param pulseReason Requesting sensor, e.g. {@link DozeLog#REASON_SENSOR_PICKUP}
+         * @param pulseReason Requesting sensor, e.g. {@link DozeEvent#REASON_SENSOR_PICKUP}
          * @param screenX the location on the screen where the sensor fired or -1
          *                if the sensor doesn't support reporting screen locations.
          * @param screenY the location on the screen where the sensor fired or -1
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeService.java b/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
index e92acfc..17559c9 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
@@ -39,15 +39,17 @@
     private static final String TAG = "DozeService";
     static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
     private final FalsingManager mFalsingManager;
+    private final DozeLog mDozeLog;
 
     private DozeMachine mDozeMachine;
     private DozeServicePlugin mDozePlugin;
     private PluginManager mPluginManager;
 
     @Inject
-    public DozeService(FalsingManager falsingManager) {
+    public DozeService(FalsingManager falsingManager, DozeLog dozeLog) {
         setDebug(DEBUG);
         mFalsingManager = falsingManager;
+        mDozeLog = dozeLog;
     }
 
     @Override
@@ -62,7 +64,7 @@
         }
         mPluginManager = Dependency.get(PluginManager.class);
         mPluginManager.addPluginListener(this, DozeServicePlugin.class, false /* allowMultiple */);
-        mDozeMachine = new DozeFactory().assembleMachine(this, mFalsingManager);
+        mDozeMachine = new DozeFactory().assembleMachine(this, mFalsingManager, mDozeLog);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
index 80d4b63..b212884 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java
@@ -67,12 +67,12 @@
 
     private final Context mContext;
     private final DozeMachine mMachine;
+    private final DozeLog mDozeLog;
     private final DozeSensors mDozeSensors;
     private final DozeHost mDozeHost;
     private final AmbientDisplayConfiguration mConfig;
     private final DozeParameters mDozeParameters;
     private final AsyncSensorManager mSensorManager;
-    private final Handler mHandler;
     private final WakeLock mWakeLock;
     private final boolean mAllowPulseTriggers;
     private final UiModeManager mUiModeManager;
@@ -89,24 +89,24 @@
     public DozeTriggers(Context context, DozeMachine machine, DozeHost dozeHost,
             AlarmManager alarmManager, AmbientDisplayConfiguration config,
             DozeParameters dozeParameters, AsyncSensorManager sensorManager, Handler handler,
-            WakeLock wakeLock, boolean allowPulseTriggers, DockManager dockManager) {
+            WakeLock wakeLock, boolean allowPulseTriggers, DockManager dockManager,
+            ProximitySensor proximitySensor,
+            DozeLog dozeLog) {
         mContext = context;
         mMachine = machine;
         mDozeHost = dozeHost;
         mConfig = config;
         mDozeParameters = dozeParameters;
         mSensorManager = sensorManager;
-        mHandler = handler;
         mWakeLock = wakeLock;
         mAllowPulseTriggers = allowPulseTriggers;
         mDozeSensors = new DozeSensors(context, alarmManager, mSensorManager, dozeParameters,
                 config, wakeLock, this::onSensor, this::onProximityFar,
-                dozeParameters.getPolicy());
+                dozeParameters.getPolicy(), dozeLog);
         mUiModeManager = mContext.getSystemService(UiModeManager.class);
         mDockManager = dockManager;
-        mProxCheck = new ProximitySensor.ProximityCheck(
-                new ProximitySensor(mContext, mSensorManager, null),
-                mHandler);
+        mProxCheck = new ProximitySensor.ProximityCheck(proximitySensor, handler);
+        mDozeLog = dozeLog;
     }
 
     private void onNotification(Runnable onPulseSuppressedListener) {
@@ -116,18 +116,18 @@
         if (!sWakeDisplaySensorState) {
             Log.d(TAG, "Wake display false. Pulse denied.");
             runIfNotNull(onPulseSuppressedListener);
-            DozeLog.tracePulseDropped(mContext, "wakeDisplaySensor");
+            mDozeLog.tracePulseDropped("wakeDisplaySensor");
             return;
         }
         mNotificationPulseTime = SystemClock.elapsedRealtime();
         if (!mConfig.pulseOnNotificationEnabled(UserHandle.USER_CURRENT)) {
             runIfNotNull(onPulseSuppressedListener);
-            DozeLog.tracePulseDropped(mContext, "pulseOnNotificationsDisabled");
+            mDozeLog.tracePulseDropped("pulseOnNotificationsDisabled");
             return;
         }
-        requestPulse(DozeLog.PULSE_REASON_NOTIFICATION, false /* performedProxCheck */,
+        requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION, false /* performedProxCheck */,
                 onPulseSuppressedListener);
-        DozeLog.traceNotificationPulse(mContext);
+        mDozeLog.traceNotificationPulse();
     }
 
     private static void runIfNotNull(Runnable runnable) {
@@ -148,8 +148,7 @@
             final long start = SystemClock.uptimeMillis();
             mProxCheck.check(PROXIMITY_TIMEOUT_DELAY_MS, near -> {
                 final long end = SystemClock.uptimeMillis();
-                DozeLog.traceProximityResult(
-                        mContext,
+                mDozeLog.traceProximityResult(
                         near == null ? false : near,
                         end - start,
                         reason);
@@ -162,12 +161,12 @@
 
     @VisibleForTesting
     void onSensor(int pulseReason, float screenX, float screenY, float[] rawValues) {
-        boolean isDoubleTap = pulseReason == DozeLog.REASON_SENSOR_DOUBLE_TAP;
-        boolean isTap = pulseReason == DozeLog.REASON_SENSOR_TAP;
-        boolean isPickup = pulseReason == DozeLog.REASON_SENSOR_PICKUP;
-        boolean isLongPress = pulseReason == DozeLog.PULSE_REASON_SENSOR_LONG_PRESS;
-        boolean isWakeDisplay = pulseReason == DozeLog.REASON_SENSOR_WAKE_UP;
-        boolean isWakeLockScreen = pulseReason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN;
+        boolean isDoubleTap = pulseReason == DozeEvent.REASON_SENSOR_DOUBLE_TAP;
+        boolean isTap = pulseReason == DozeEvent.REASON_SENSOR_TAP;
+        boolean isPickup = pulseReason == DozeEvent.REASON_SENSOR_PICKUP;
+        boolean isLongPress = pulseReason == DozeEvent.PULSE_REASON_SENSOR_LONG_PRESS;
+        boolean isWakeDisplay = pulseReason == DozeEvent.REASON_SENSOR_WAKE_UP;
+        boolean isWakeLockScreen = pulseReason == DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN;
         boolean wakeEvent = rawValues != null && rawValues.length > 0 && rawValues[0] != 0;
 
         if (isWakeDisplay) {
@@ -182,7 +181,7 @@
             }
         } else {
             proximityCheckThenCall((result) -> {
-                if (result) {
+                if (result != null && result) {
                     // In pocket, drop event.
                     return;
                 }
@@ -204,7 +203,7 @@
                     SystemClock.elapsedRealtime() - mNotificationPulseTime;
             final boolean withinVibrationThreshold =
                     timeSinceNotification < mDozeParameters.getPickupVibrationThreshold();
-            DozeLog.tracePickupWakeUp(mContext, withinVibrationThreshold);
+            mDozeLog.tracePickupWakeUp(withinVibrationThreshold);
         }
     }
 
@@ -266,12 +265,12 @@
      *              transitions.
      */
     private void onWakeScreen(boolean wake, @Nullable DozeMachine.State state) {
-        DozeLog.traceWakeDisplay(wake);
+        mDozeLog.traceWakeDisplay(wake);
         sWakeDisplaySensorState = wake;
 
         if (wake) {
             proximityCheckThenCall((result) -> {
-                if (result) {
+                if (result !=  null && result) {
                     // In pocket, drop event.
                     return;
                 }
@@ -280,9 +279,9 @@
                     // Logs AOD open due to sensor wake up.
                     mMetricsLogger.write(new LogMaker(MetricsEvent.DOZING)
                             .setType(MetricsEvent.TYPE_OPEN)
-                            .setSubtype(DozeLog.REASON_SENSOR_WAKE_UP));
+                            .setSubtype(DozeEvent.REASON_SENSOR_WAKE_UP));
                 }
-            }, true /* alreadyPerformedProxCheck */, DozeLog.REASON_SENSOR_WAKE_UP);
+            }, true /* alreadyPerformedProxCheck */, DozeEvent.REASON_SENSOR_WAKE_UP);
         } else {
             boolean paused = (state == DozeMachine.State.DOZE_AOD_PAUSED);
             boolean pausing = (state == DozeMachine.State.DOZE_AOD_PAUSING);
@@ -291,7 +290,7 @@
                 // Logs AOD close due to sensor wake up.
                 mMetricsLogger.write(new LogMaker(MetricsEvent.DOZING)
                         .setType(MetricsEvent.TYPE_CLOSE)
-                        .setSubtype(DozeLog.REASON_SENSOR_WAKE_UP));
+                        .setSubtype(DozeEvent.REASON_SENSOR_WAKE_UP));
             }
         }
     }
@@ -349,7 +348,6 @@
 
     private void checkTriggersAtInit() {
         if (mUiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR
-                || mDozeHost.isPowerSaveActive()
                 || mDozeHost.isBlockingDoze()
                 || !mDozeHost.isProvisioned()) {
             mMachine.requestState(DozeMachine.State.FINISH);
@@ -364,14 +362,14 @@
         // When already pulsing we're allowed to show the wallpaper directly without
         // requesting a new pulse.
         if (mMachine.getState() == DozeMachine.State.DOZE_PULSING
-                && reason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN) {
+                && reason == DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN) {
             mMachine.requestState(DozeMachine.State.DOZE_PULSING_BRIGHT);
             return;
         }
 
         if (mPulsePending || !mAllowPulseTriggers || !canPulse()) {
             if (mAllowPulseTriggers) {
-                DozeLog.tracePulseDropped(mContext, mPulsePending, mMachine.getState(),
+                mDozeLog.tracePulseDropped(mPulsePending, mMachine.getState(),
                         mDozeHost.isPulsingBlocked());
             }
             runIfNotNull(onPulseSuppressedListener);
@@ -380,9 +378,9 @@
 
         mPulsePending = true;
         proximityCheckThenCall((result) -> {
-            if (result) {
+            if (result != null && result) {
                 // in pocket, abort pulse
-                DozeLog.tracePulseDropped(mContext, "inPocket");
+                mDozeLog.tracePulseDropped("inPocket");
                 mPulsePending = false;
                 runIfNotNull(onPulseSuppressedListener);
             } else {
@@ -404,7 +402,7 @@
     private void continuePulseRequest(int reason) {
         mPulsePending = false;
         if (mDozeHost.isPulsingBlocked() || !canPulse()) {
-            DozeLog.tracePulseDropped(mContext, mPulsePending, mMachine.getState(),
+            mDozeLog.tracePulseDropped(mPulsePending, mMachine.getState(),
                     mDozeHost.isPulsingBlocked());
             return;
         }
@@ -428,7 +426,7 @@
         public void onReceive(Context context, Intent intent) {
             if (PULSE_ACTION.equals(intent.getAction())) {
                 if (DozeMachine.DEBUG) Log.d(TAG, "Received pulse intent");
-                requestPulse(DozeLog.PULSE_REASON_INTENT, false, /* performedProxCheck */
+                requestPulse(DozeEvent.PULSE_REASON_INTENT, false, /* performedProxCheck */
                         null /* onPulseSupressedListener */);
             }
             if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
@@ -485,8 +483,8 @@
 
         @Override
         public void onPowerSaveChanged(boolean active) {
-            if (active) {
-                mMachine.requestState(DozeMachine.State.FINISH);
+            if (mDozeHost.isPowerSaveActive()) {
+                mMachine.requestState(DozeMachine.State.DOZE);
             }
         }
     };
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java b/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java
index 1f33af8..2c0ccd21 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeUi.java
@@ -49,6 +49,7 @@
     private final AlarmTimeout mTimeTicker;
     private final boolean mCanAnimateTransition;
     private final DozeParameters mDozeParameters;
+    private final DozeLog mDozeLog;
 
     private boolean mKeyguardShowing;
     private final KeyguardUpdateMonitorCallback mKeyguardVisibilityCallback =
@@ -65,7 +66,8 @@
 
     public DozeUi(Context context, AlarmManager alarmManager, DozeMachine machine,
             WakeLock wakeLock, DozeHost host, Handler handler,
-            DozeParameters params, KeyguardUpdateMonitor keyguardUpdateMonitor) {
+            DozeParameters params, KeyguardUpdateMonitor keyguardUpdateMonitor,
+            DozeLog dozeLog) {
         mContext = context;
         mMachine = machine;
         mWakeLock = wakeLock;
@@ -75,6 +77,7 @@
         mDozeParameters = params;
         mTimeTicker = new AlarmTimeout(alarmManager, this::onTimeTick, "doze_time_tick", handler);
         keyguardUpdateMonitor.registerCallback(mKeyguardVisibilityCallback);
+        mDozeLog = dozeLog;
     }
 
     /**
@@ -83,7 +86,8 @@
      */
     private void updateAnimateScreenOff() {
         if (mCanAnimateTransition) {
-            final boolean controlScreenOff = mDozeParameters.getAlwaysOn() && mKeyguardShowing;
+            final boolean controlScreenOff = mDozeParameters.getAlwaysOn() && mKeyguardShowing
+                    && !mHost.isPowerSaveActive();
             mDozeParameters.setControlScreenOffAnimation(controlScreenOff);
             mHost.setAnimateScreenOff(controlScreenOff);
         }
@@ -96,7 +100,7 @@
                     public void onPulseStarted() {
                         try {
                             mMachine.requestState(
-                                    reason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN
+                                    reason == DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN
                                             ? DozeMachine.State.DOZE_PULSING_BRIGHT
                                             : DozeMachine.State.DOZE_PULSING);
                         } catch (IllegalStateException e) {
@@ -175,7 +179,7 @@
         long delta = roundToNextMinute(time) - System.currentTimeMillis();
         boolean scheduled = mTimeTicker.schedule(delta, AlarmTimeout.MODE_IGNORE_IF_SCHEDULED);
         if (scheduled) {
-            DozeLog.traceTimeTickScheduled(time, time + delta);
+            mDozeLog.traceTimeTickScheduled(time, time + delta);
         }
         mLastTimeTickElapsed = SystemClock.elapsedRealtime();
     }
@@ -192,7 +196,7 @@
         long millisSinceLastTick = SystemClock.elapsedRealtime() - mLastTimeTickElapsed;
         if (millisSinceLastTick > TIME_TICK_DEADLINE_MILLIS) {
             String delay = Formatter.formatShortElapsedTime(mContext, millisSinceLastTick);
-            DozeLog.traceMissedTick(delay);
+            mDozeLog.traceMissedTick(delay);
             Log.e(DozeMachine.TAG, "Missed AOD time tick by " + delay);
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
index c9c6a0c..22846bc 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
@@ -90,14 +90,15 @@
 import com.android.systemui.Interpolators;
 import com.android.systemui.MultiListLayout;
 import com.android.systemui.MultiListLayout.MultiListAdapter;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.colorextraction.SysuiColorExtractor;
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.GlobalActions.GlobalActionsManager;
 import com.android.systemui.plugins.GlobalActionsPanelPlugin;
 import com.android.systemui.statusbar.phone.ScrimController;
 import com.android.systemui.statusbar.phone.StatusBarWindowController;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
 import com.android.systemui.statusbar.policy.ConfigurationController;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.util.EmergencyDialerConstants;
 import com.android.systemui.util.leak.RotationUtils;
 import com.android.systemui.volume.SystemUIInterpolators.LogAccelerateInterpolator;
@@ -187,7 +188,7 @@
         filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
         filter.addAction(Intent.ACTION_SCREEN_OFF);
         filter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
-        context.registerReceiver(mBroadcastReceiver, filter);
+        Dependency.get(BroadcastDispatcher.class).registerReceiver(mBroadcastReceiver, filter);
 
         ConnectivityManager cm = (ConnectivityManager)
                 context.getSystemService(Context.CONNECTIVITY_SERVICE);
@@ -213,14 +214,17 @@
         Dependency.get(ConfigurationController.class).addCallback(this);
 
         mActivityStarter = Dependency.get(ActivityStarter.class);
-        UnlockMethodCache unlockMethodCache = UnlockMethodCache.getInstance(context);
-        unlockMethodCache.addListener(
-                () -> {
-                    if (mDialog != null && mDialog.mPanelController != null) {
-                        boolean locked = !unlockMethodCache.canSkipBouncer();
-                        mDialog.mPanelController.onDeviceLockStateChanged(locked);
-                    }
-                });
+        KeyguardStateController keyguardStateController =
+                Dependency.get(KeyguardStateController.class);
+        keyguardStateController.addCallback(new KeyguardStateController.Callback() {
+            @Override
+            public void onUnlockedChanged() {
+                if (mDialog != null && mDialog.mPanelController != null) {
+                    boolean locked = !keyguardStateController.canDismissLockScreen();
+                    mDialog.mPanelController.onDeviceLockStateChanged(locked);
+                }
+            }
+        });
     }
 
     /**
@@ -665,8 +669,7 @@
                         // Take an "interactive" bugreport.
                         MetricsLogger.action(mContext,
                                 MetricsEvent.ACTION_BUGREPORT_FROM_POWER_MENU_INTERACTIVE);
-                        ActivityManager.getService().requestBugReport(
-                                ActivityManager.BUGREPORT_OPTION_INTERACTIVE);
+                        ActivityManager.getService().requestInteractiveBugReport();
                     } catch (RemoteException e) {
                     }
                 }
@@ -683,8 +686,7 @@
             try {
                 // Take a "full" bugreport.
                 MetricsLogger.action(mContext, MetricsEvent.ACTION_BUGREPORT_FROM_POWER_MENU_FULL);
-                ActivityManager.getService().requestBugReport(
-                        ActivityManager.BUGREPORT_OPTION_FULL);
+                ActivityManager.getService().requestFullBugReport();
             } catch (RemoteException e) {
             }
             return false;
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
index 6f8665a..b9fe827 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
@@ -40,14 +40,14 @@
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
 import com.android.systemui.statusbar.policy.ExtensionController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 public class GlobalActionsImpl implements GlobalActions, CommandQueue.Callbacks {
 
     private static final float SHUTDOWN_SCRIM_ALPHA = 0.95f;
 
     private final Context mContext;
-    private final KeyguardMonitor mKeyguardMonitor;
+    private final KeyguardStateController mKeyguardStateController;
     private final DeviceProvisionedController mDeviceProvisionedController;
     private final ExtensionController.Extension<GlobalActionsPanelPlugin> mPanelExtension;
     private GlobalActionsDialog mGlobalActions;
@@ -55,7 +55,7 @@
 
     public GlobalActionsImpl(Context context) {
         mContext = context;
-        mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
         mDeviceProvisionedController = Dependency.get(DeviceProvisionedController.class);
         SysUiServiceProvider.getComponent(context, CommandQueue.class).addCallback(this);
         mPanelExtension = Dependency.get(ExtensionController.class)
@@ -79,7 +79,7 @@
         if (mGlobalActions == null) {
             mGlobalActions = new GlobalActionsDialog(mContext, manager);
         }
-        mGlobalActions.showDialog(mKeyguardMonitor.isShowing(),
+        mGlobalActions.showDialog(mKeyguardStateController.isShowing(),
                 mDeviceProvisionedController.isDeviceProvisioned(),
                 mPanelExtension.get());
         Dependency.get(KeyguardUpdateMonitor.class).requestFaceAuth();
diff --git a/packages/SystemUI/src/com/android/systemui/glwallpaper/EglHelper.java b/packages/SystemUI/src/com/android/systemui/glwallpaper/EglHelper.java
index aac721e..c6812a7 100644
--- a/packages/SystemUI/src/com/android/systemui/glwallpaper/EglHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/glwallpaper/EglHelper.java
@@ -22,6 +22,7 @@
 import static android.opengl.EGL14.EGL_CONTEXT_CLIENT_VERSION;
 import static android.opengl.EGL14.EGL_DEFAULT_DISPLAY;
 import static android.opengl.EGL14.EGL_DEPTH_SIZE;
+import static android.opengl.EGL14.EGL_EXTENSIONS;
 import static android.opengl.EGL14.EGL_GREEN_SIZE;
 import static android.opengl.EGL14.EGL_NONE;
 import static android.opengl.EGL14.EGL_NO_CONTEXT;
@@ -41,6 +42,7 @@
 import static android.opengl.EGL14.eglGetError;
 import static android.opengl.EGL14.eglInitialize;
 import static android.opengl.EGL14.eglMakeCurrent;
+import static android.opengl.EGL14.eglQueryString;
 import static android.opengl.EGL14.eglSwapBuffers;
 import static android.opengl.EGL14.eglTerminate;
 
@@ -63,6 +65,8 @@
     // Below two constants make drawing at low priority, so other things can preempt our drawing.
     private static final int EGL_CONTEXT_PRIORITY_LEVEL_IMG = 0x3100;
     private static final int EGL_CONTEXT_PRIORITY_LOW_IMG = 0x3103;
+    private static final boolean DEBUG = true;
+    private static final String EGL_IMG_CONTEXT_PRIORITY = "EGL_IMG_context_priority";
 
     private EGLDisplay mEglDisplay;
     private EGLConfig mEglConfig;
@@ -70,6 +74,7 @@
     private EGLSurface mEglSurface;
     private final int[] mEglVersion = new int[2];
     private boolean mEglReady;
+    private boolean mContextPrioritySupported;
 
     /**
      * Initialize EGL and prepare EglSurface.
@@ -105,10 +110,22 @@
             return false;
         }
 
+        mContextPrioritySupported = isContextPrioritySuppported();
+
         mEglReady = true;
         return true;
     }
 
+    private boolean isContextPrioritySuppported() {
+        String[] extensions = eglQueryString(mEglDisplay, EGL_EXTENSIONS).split(" ");
+        for (String extension : extensions) {
+            if (extension.equals(EGL_IMG_CONTEXT_PRIORITY)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     private EGLConfig chooseEglConfig() {
         int[] configsCount = new int[1];
         EGLConfig[] configs = new EGLConfig[1];
@@ -146,6 +163,10 @@
      * @return true if EglSurface is ready.
      */
     public boolean createEglSurface(SurfaceHolder surfaceHolder) {
+        if (DEBUG) {
+            Log.d(TAG, "createEglSurface start");
+        }
+
         if (hasEglDisplay()) {
             mEglSurface = eglCreateWindowSurface(mEglDisplay, mEglConfig, surfaceHolder, null, 0);
         } else {
@@ -163,6 +184,9 @@
             return false;
         }
 
+        if (DEBUG) {
+            Log.d(TAG, "createEglSurface done");
+        }
         return true;
     }
 
@@ -190,8 +214,19 @@
      * @return true if EglContext is ready.
      */
     public boolean createEglContext() {
-        int[] attrib_list = new int[] {EGL_CONTEXT_CLIENT_VERSION, 2,
-                EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_LOW_IMG, EGL_NONE};
+        if (DEBUG) {
+            Log.d(TAG, "createEglContext start");
+        }
+
+        int[] attrib_list = new int[5];
+        int idx = 0;
+        attrib_list[idx++] = EGL_CONTEXT_CLIENT_VERSION;
+        attrib_list[idx++] = 2;
+        if (mContextPrioritySupported) {
+            attrib_list[idx++] = EGL_CONTEXT_PRIORITY_LEVEL_IMG;
+            attrib_list[idx++] = EGL_CONTEXT_PRIORITY_LOW_IMG;
+        }
+        attrib_list[idx++] = EGL_NONE;
         if (hasEglDisplay()) {
             mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT, attrib_list, 0);
         } else {
@@ -203,6 +238,10 @@
             Log.w(TAG, "eglCreateContext failed: " + GLUtils.getEGLErrorString(eglGetError()));
             return false;
         }
+
+        if (DEBUG) {
+            Log.d(TAG, "createEglContext done");
+        }
         return true;
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageRevealHelper.java b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageRevealHelper.java
index b154e66..99c55f1 100644
--- a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageRevealHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageRevealHelper.java
@@ -19,6 +19,7 @@
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
 import android.animation.ValueAnimator;
+import android.util.Log;
 
 import com.android.systemui.Interpolators;
 
@@ -30,6 +31,7 @@
     private static final String TAG = ImageRevealHelper.class.getSimpleName();
     private static final float MAX_REVEAL = 0f;
     private static final float MIN_REVEAL = 1f;
+    private static final boolean DEBUG = true;
 
     private final ValueAnimator mAnimator;
     private final RevealStateListener mRevealListener;
@@ -57,6 +59,9 @@
             @Override
             public void onAnimationEnd(Animator animation) {
                 if (!mIsCanceled && mRevealListener != null) {
+                    if (DEBUG) {
+                        Log.d(TAG, "transition end");
+                    }
                     mRevealListener.onRevealEnd();
                 }
                 mIsCanceled = false;
@@ -65,6 +70,9 @@
             @Override
             public void onAnimationStart(Animator animation) {
                 if (mRevealListener != null) {
+                    if (DEBUG) {
+                        Log.d(TAG, "transition start");
+                    }
                     mRevealListener.onRevealStart(true /* animate */);
                 }
             }
@@ -82,6 +90,9 @@
     }
 
     void updateAwake(boolean awake, long duration) {
+        if (DEBUG) {
+            Log.d(TAG, "updateAwake: awake=" + awake + ", duration=" + duration);
+        }
         mAwake = awake;
         mAnimator.setDuration(duration);
         if (duration == 0) {
diff --git a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java
index 2960634..a8371e3 100644
--- a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java
+++ b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java
@@ -46,6 +46,7 @@
     private static final String TAG = ImageWallpaperRenderer.class.getSimpleName();
     private static final float SCALE_VIEWPORT_MIN = 1f;
     private static final float SCALE_VIEWPORT_MAX = 1.1f;
+    private static final boolean DEBUG = true;
 
     private final WallpaperManager mWallpaperManager;
     private final ImageGLProgram mProgram;
@@ -107,6 +108,9 @@
     }
 
     private boolean loadBitmap() {
+        if (DEBUG) {
+            Log.d(TAG, "loadBitmap: mBitmap=" + mBitmap);
+        }
         if (mWallpaperManager != null && mBitmap == null) {
             mBitmap = mWallpaperManager.getBitmap();
             mWallpaperManager.forgetLoadedWallpaper();
@@ -119,6 +123,9 @@
                 mSurfaceSize.set(0, 0, surfaceWidth, surfaceHeight);
             }
         }
+        if (DEBUG) {
+            Log.d(TAG, "loadBitmap done");
+        }
         return mBitmap != null;
     }
 
@@ -223,6 +230,7 @@
         out.print(prefix); out.print("mXOffset="); out.print(mXOffset);
         out.print(prefix); out.print("mYOffset="); out.print(mYOffset);
         out.print(prefix); out.print("threshold="); out.print(mImageProcessHelper.getThreshold());
+        out.print(prefix); out.print("mReveal="); out.print(mImageRevealHelper.getReveal());
         mWallpaper.dump(prefix, fd, out, args);
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index d2a9c75..a8027c0 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -100,6 +100,7 @@
 import java.util.ArrayList;
 
 import javax.inject.Inject;
+import javax.inject.Singleton;
 
 /**
  * Mediates requests related to the keyguard.  This includes queries about the
@@ -142,6 +143,7 @@
  * directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI
  * thread of the keyguard.
  */
+@Singleton
 public class KeyguardViewMediator extends SystemUI {
     private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
     private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000;
@@ -232,7 +234,7 @@
      */
     private PowerManager.WakeLock mShowKeyguardWakeLock;
 
-    private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
+    private final StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
 
     // these are protected by synchronized (this)
 
@@ -315,7 +317,7 @@
      * the keyguard.
      */
     private boolean mWaitingUntilKeyguardVisible = false;
-    private LockPatternUtils mLockPatternUtils;
+    private final LockPatternUtils mLockPatternUtils;
     private boolean mKeyguardDonePending = false;
     private boolean mHideAnimationRun = false;
     private boolean mHideAnimationRunning = false;
@@ -648,29 +650,26 @@
 
         @Override
         public int getBouncerPromptReason() {
-            // TODO(b/140053364)
-            return whitelistIpcs(() -> {
-                int currentUser = ActivityManager.getCurrentUser();
-                boolean trust = mTrustManager.isTrustUsuallyManaged(currentUser);
-                boolean biometrics = mUpdateMonitor.isUnlockingWithBiometricsPossible(currentUser);
-                boolean any = trust || biometrics;
-                KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
-                        mUpdateMonitor.getStrongAuthTracker();
-                int strongAuth = strongAuthTracker.getStrongAuthForUser(currentUser);
+            int currentUser = KeyguardUpdateMonitor.getCurrentUser();
+            boolean trust = mUpdateMonitor.isTrustUsuallyManaged(currentUser);
+            boolean biometrics = mUpdateMonitor.isUnlockingWithBiometricsPossible(currentUser);
+            boolean any = trust || biometrics;
+            KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
+                    mUpdateMonitor.getStrongAuthTracker();
+            int strongAuth = strongAuthTracker.getStrongAuthForUser(currentUser);
 
-                if (any && !strongAuthTracker.hasUserAuthenticatedSinceBoot()) {
-                    return KeyguardSecurityView.PROMPT_REASON_RESTART;
-                } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_TIMEOUT) != 0) {
-                    return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
-                } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) != 0) {
-                    return KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN;
-                } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_USER_REQUEST) != 0) {
-                    return KeyguardSecurityView.PROMPT_REASON_USER_REQUEST;
-                } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) != 0) {
-                    return KeyguardSecurityView.PROMPT_REASON_AFTER_LOCKOUT;
-                }
-                return KeyguardSecurityView.PROMPT_REASON_NONE;
-            });
+            if (any && !strongAuthTracker.hasUserAuthenticatedSinceBoot()) {
+                return KeyguardSecurityView.PROMPT_REASON_RESTART;
+            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_TIMEOUT) != 0) {
+                return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
+            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) != 0) {
+                return KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN;
+            } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_USER_REQUEST) != 0) {
+                return KeyguardSecurityView.PROMPT_REASON_USER_REQUEST;
+            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) != 0) {
+                return KeyguardSecurityView.PROMPT_REASON_AFTER_LOCKOUT;
+            }
+            return KeyguardSecurityView.PROMPT_REASON_NONE;
         }
 
         @Override
@@ -682,10 +681,21 @@
     };
 
     @Inject
-    public KeyguardViewMediator(FalsingManager falsingManager) {
+    public KeyguardViewMediator(
+            Context context,
+            FalsingManager falsingManager,
+            LockPatternUtils lockPatternUtils) {
         super();
 
+        mContext = context;
         mFalsingManager = falsingManager;
+
+        mLockPatternUtils = lockPatternUtils;
+        mStatusBarKeyguardViewManager =
+                SystemUIFactory.getInstance().createStatusBarKeyguardViewManager(
+                        mContext,
+                        mViewMediatorCallback,
+                        mLockPatternUtils);
     }
 
     public void userActivity() {
@@ -699,7 +709,7 @@
 
     private void setupLocked() {
         mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
-        mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
+        mTrustManager = mContext.getSystemService(TrustManager.class);
 
         mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
         mShowKeyguardWakeLock.setReferenceCounted(false);
@@ -723,7 +733,6 @@
 
         mUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
 
-        mLockPatternUtils = new LockPatternUtils(mContext);
         KeyguardUpdateMonitor.setCurrentUser(ActivityManager.getCurrentUser());
 
         // Assume keyguard is showing (unless it's disabled) until we know for sure, unless Keyguard
@@ -737,9 +746,6 @@
             setShowingLocked(false /* showing */, true /* forceCallbacks */);
         }
 
-        mStatusBarKeyguardViewManager =
-                SystemUIFactory.getInstance().createStatusBarKeyguardViewManager(mContext,
-                        mViewMediatorCallback, mLockPatternUtils);
         final ContentResolver cr = mContext.getContentResolver();
 
         mDeviceInteractive = mPM.isInteractive();
diff --git a/packages/SystemUI/src/com/android/systemui/log/Event.java b/packages/SystemUI/src/com/android/systemui/log/Event.java
new file mode 100644
index 0000000..92862a2
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/log/Event.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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.log;
+
+import android.annotation.IntDef;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Stores information about an event that occurred in SystemUI to be used for debugging and triage.
+ * Every event has a time stamp, log level and message.
+ * Events are stored in {@link SysuiLog} and can be printed in a dumpsys.
+ */
+public class Event {
+    public static final int UNINITIALIZED = -1;
+
+    @IntDef({ERROR, WARN, INFO, DEBUG, VERBOSE})
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface Level {}
+    public static final int VERBOSE = 2;
+    public static final int DEBUG = 3;
+    public static final int INFO = 4;
+    public static final int WARN = 5;
+    public static final int ERROR = 6;
+
+    private long mTimestamp;
+    private @Level int mLogLevel = DEBUG;
+    protected String mMessage;
+
+    public Event(String message) {
+        mTimestamp = System.currentTimeMillis();
+        mMessage = message;
+    }
+
+    public Event(@Level int logLevel, String message) {
+        mTimestamp = System.currentTimeMillis();
+        mLogLevel = logLevel;
+        mMessage = message;
+    }
+
+    public String getMessage() {
+        return mMessage;
+    }
+
+    public long getTimestamp() {
+        return mTimestamp;
+    }
+
+    public @Level int getLogLevel() {
+        return mLogLevel;
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/log/RichEvent.java b/packages/SystemUI/src/com/android/systemui/log/RichEvent.java
new file mode 100644
index 0000000..89b7a818
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/log/RichEvent.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2019 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.log;
+
+/**
+ * Stores information about an event that occurred in SystemUI to be used for debugging and triage.
+ * Every rich event has a time stamp, event type, and log level, with the option to provide the
+ * reason this event was triggered.
+ * Events are stored in {@link SysuiLog} and can be printed in a dumpsys.
+ */
+public abstract class RichEvent extends Event {
+    private final int mType;
+    private final String mReason;
+
+    /**
+     * Create a rich event that includes an event type that matches with an index in the array
+     * getEventLabels().
+     */
+    public RichEvent(@Event.Level int logLevel, int type, String reason) {
+        super(logLevel, null);
+        final int numEvents = getEventLabels().length;
+        if (type < 0 || type >= numEvents) {
+            throw new IllegalArgumentException("Unsupported event type. Events only supported"
+                    + " from 0 to " + (numEvents - 1) + ", but given type=" + type);
+        }
+        mType = type;
+        mReason = reason;
+        mMessage = getEventLabels()[mType] + " " + mReason;
+    }
+
+    /**
+     * Returns an array of the event labels.  The index represents the event type and the
+     * corresponding String stored at that index is the user-readable representation of that event.
+     * @return array of user readable events, where the index represents its event type constant
+     */
+    public abstract String[] getEventLabels();
+
+    public int getType() {
+        return mType;
+    }
+
+    public String getReason() {
+        return mReason;
+    }
+
+    /**
+     * Builder to build a RichEvent.
+     * @param <B> Log specific builder that is extending this builder
+     */
+    public abstract static class Builder<B extends Builder<B>> {
+        public static final int UNINITIALIZED = -1;
+
+        private B mBuilder = getBuilder();
+        protected int mType = UNINITIALIZED;
+        protected String mReason;
+        protected @Level int mLogLevel;
+
+        /**
+         * Get the log-specific builder.
+         */
+        public abstract B getBuilder();
+
+        /**
+         * Build the log-specific event.
+         */
+        public abstract RichEvent build();
+
+        /**
+         * Optional - set the log level. Defaults to DEBUG.
+         */
+        public B setLogLevel(@Level int logLevel) {
+            mLogLevel = logLevel;
+            return mBuilder;
+        }
+
+        /**
+         * Required - set the event type.  These events must correspond with the events from
+         * getEventLabels().
+         */
+        public B setType(int type) {
+            mType = type;
+            return mBuilder;
+        }
+
+        /**
+         * Optional - set the reason why this event was triggered.
+         */
+        public B setReason(String reason) {
+            mReason = reason;
+            return mBuilder;
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/log/SysuiLog.java b/packages/SystemUI/src/com/android/systemui/log/SysuiLog.java
new file mode 100644
index 0000000..a6e10e6
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/log/SysuiLog.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2019 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.log;
+
+import android.os.Build;
+import android.os.SystemProperties;
+import android.util.Log;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.systemui.DumpController;
+import com.android.systemui.Dumpable;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.ArrayDeque;
+import java.util.Locale;
+
+/**
+ * Thread-safe logger in SystemUI which prints logs to logcat and stores logs to be
+ * printed by the DumpController. This is an alternative to printing directly
+ * to avoid logs being deleted by chatty. The number of logs retained is varied based on
+ * whether the build is {@link Build.IS_DEBUGGABLE}.
+ *
+ * To manually view the logs via adb:
+ *      adb shell dumpsys activity service com.android.systemui/.SystemUIService \
+ *      dependency DumpController <SysuiLogId>
+ */
+public class SysuiLog implements Dumpable {
+    public static final SimpleDateFormat DATE_FORMAT =
+            new SimpleDateFormat("MM-dd HH:mm:ss", Locale.US);
+
+    private final Object mDataLock = new Object();
+    private final String mId;
+    private final int mMaxLogs;
+    private boolean mEnabled;
+
+    @VisibleForTesting protected ArrayDeque<Event> mTimeline;
+
+    /**
+     * Creates a SysuiLog
+     * To enable or disable logs, set the system property and then restart the device:
+     *      adb shell setprop sysui.log.enabled.<id> true/false && adb reboot
+     * @param dumpController where to register this logger's dumpsys
+     * @param id user-readable tag for this logger
+     * @param maxDebugLogs maximum number of logs to retain when {@link sDebuggable} is true
+     * @param maxLogs maximum number of logs to retain when {@link sDebuggable} is false
+     */
+    public SysuiLog(DumpController dumpController, String id, int maxDebugLogs, int maxLogs) {
+        this(dumpController, id, sDebuggable ? maxDebugLogs : maxLogs,
+                SystemProperties.getBoolean(SYSPROP_ENABLED_PREFIX + id, DEFAULT_ENABLED));
+    }
+
+    @VisibleForTesting
+    protected SysuiLog(DumpController dumpController, String id, int maxLogs, boolean enabled) {
+        mId = id;
+        mMaxLogs = maxLogs;
+        mEnabled = enabled;
+        mTimeline = mEnabled ? new ArrayDeque<>(mMaxLogs) : null;
+        dumpController.registerDumpable(mId, this);
+    }
+
+    public SysuiLog(DumpController dumpController, String id) {
+        this(dumpController, id, DEFAULT_MAX_DEBUG_LOGS, DEFAULT_MAX_LOGS);
+    }
+
+    /**
+     * Logs an event to the timeline which can be printed by the dumpsys.
+     * May also log to logcat if enabled.
+     * @return true if event was logged, else false
+     */
+    public boolean log(Event event) {
+        if (!mEnabled) {
+            return false;
+        }
+
+        synchronized (mDataLock) {
+            if (mTimeline.size() >= mMaxLogs) {
+                mTimeline.removeFirst();
+            }
+
+            mTimeline.add(event);
+        }
+
+        if (LOG_TO_LOGCAT_ENABLED) {
+            final String strEvent = eventToString(event);
+            switch (event.getLogLevel()) {
+                case Event.VERBOSE:
+                    Log.v(mId, strEvent);
+                    break;
+                case Event.DEBUG:
+                    Log.d(mId, strEvent);
+                    break;
+                case Event.ERROR:
+                    Log.e(mId, strEvent);
+                    break;
+                case Event.INFO:
+                    Log.i(mId, strEvent);
+                    break;
+                case Event.WARN:
+                    Log.w(mId, strEvent);
+                    break;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * @return user-readable string of the given event
+     */
+    public String eventToString(Event event) {
+        StringBuilder sb = new StringBuilder();
+        sb.append(SysuiLog.DATE_FORMAT.format(event.getTimestamp()));
+        sb.append(" ");
+        sb.append(event.getMessage());
+        return sb.toString();
+    }
+
+    /**
+     * only call on this method if you have the mDataLock
+     */
+    private void dumpTimelineLocked(PrintWriter pw) {
+        pw.println("\tTimeline:");
+
+        for (Event event : mTimeline) {
+            pw.println("\t" + eventToString(event));
+        }
+    }
+
+    @Override
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.println(mId + ":");
+
+        if (mEnabled) {
+            synchronized (mDataLock) {
+                dumpTimelineLocked(pw);
+            }
+        } else {
+            pw.print(" - Logging disabled.");
+        }
+    }
+
+    private static boolean sDebuggable = Build.IS_DEBUGGABLE;
+    private static final String SYSPROP_ENABLED_PREFIX = "sysui.log.enabled.";
+    private static final boolean LOG_TO_LOGCAT_ENABLED = sDebuggable;
+    private static final boolean DEFAULT_ENABLED = sDebuggable;
+    private static final int DEFAULT_MAX_DEBUG_LOGS = 100;
+    private static final int DEFAULT_MAX_LOGS = 50;
+}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/BasePipManager.java b/packages/SystemUI/src/com/android/systemui/pip/BasePipManager.java
index e0fc31b..05be425 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/BasePipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/BasePipManager.java
@@ -27,5 +27,6 @@
     default void expandPip() {}
     default void hidePipMenu(Runnable onStartCallback, Runnable onEndCallback) {}
     void onConfigurationChanged(Configuration newConfig);
+    default void setShelfHeight(boolean visible, int height) {}
     default void dump(PrintWriter pw) {}
 }
diff --git a/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java b/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java
index 6795bff..686e7db 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java
@@ -55,6 +55,12 @@
     private final Rect mTmpInsets = new Rect();
     private final Point mTmpDisplaySize = new Point();
 
+    /**
+     * Tracks the destination bounds, used for any following
+     * {@link #onMovementBoundsChanged(Rect, Rect, Rect, DisplayInfo)} calculations.
+     */
+    private final Rect mLastDestinationBounds = new Rect();
+
     private IPinnedStackController mPinnedStackController;
     private ComponentName mLastPipComponentName;
     private float mReentrySnapFraction = INVALID_SNAP_FRACTION;
@@ -120,6 +126,21 @@
     }
 
     /**
+     * Sets both shelf visibility and its height if applicable.
+     * @return {@code true} if the internal shelf state is changed, {@code false} otherwise.
+     */
+    public boolean setShelfHeight(boolean shelfVisible, int shelfHeight) {
+        final boolean shelfShowing = shelfVisible && shelfHeight > 0;
+        if (shelfShowing == mIsShelfShowing && shelfHeight == mShelfHeight) {
+            return false;
+        }
+
+        mIsShelfShowing = shelfVisible;
+        mShelfHeight = shelfHeight;
+        return true;
+    }
+
+    /**
      * Responds to IPinnedStackListener on IME visibility change.
      */
     public void onImeVisibilityChanged(boolean imeVisible, int imeHeight) {
@@ -128,14 +149,6 @@
     }
 
     /**
-     * Responds to IPinnedStackListener on shelf visibility change.
-     */
-    public void onShelfVisibilityChanged(boolean shelfVisible, int shelfHeight) {
-        mIsShelfShowing = shelfVisible;
-        mShelfHeight = shelfHeight;
-    }
-
-    /**
      * Responds to IPinnedStackListener on minimized state change.
      */
     public void onMinimizedStateChanged(boolean minimized) {
@@ -185,6 +198,10 @@
         mLastPipComponentName = null;
     }
 
+    public Rect getLastDestinationBounds() {
+        return mLastDestinationBounds;
+    }
+
     /**
      * Responds to IPinnedStackListener on {@link DisplayInfo} change.
      * It will normally follow up with a
@@ -232,6 +249,7 @@
         try {
             mPinnedStackController.startAnimation(destinationBounds, sourceRectHint,
                     -1 /* animationDuration */);
+            mLastDestinationBounds.set(destinationBounds);
         } catch (RemoteException e) {
             Log.e(TAG, "Failed to start PiP animation from SysUI", e);
         }
diff --git a/packages/SystemUI/src/com/android/systemui/pip/PipUI.java b/packages/SystemUI/src/com/android/systemui/pip/PipUI.java
index 37c8163..682c76c 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/PipUI.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/PipUI.java
@@ -85,6 +85,14 @@
         mPipManager.onConfigurationChanged(newConfig);
     }
 
+    public void setShelfHeight(boolean visible, int height) {
+        if (mPipManager == null) {
+            return;
+        }
+
+        mPipManager.setShelfHeight(visible, height);
+    }
+
     @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         if (mPipManager == null) {
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
index 8dfae32..369073c 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
@@ -143,14 +143,6 @@
         }
 
         @Override
-        public void onShelfVisibilityChanged(boolean shelfVisible, int shelfHeight) {
-            mHandler.post(() -> {
-                mPipBoundsHandler.onShelfVisibilityChanged(shelfVisible, shelfHeight);
-                mTouchHandler.onShelfVisibilityChanged(shelfVisible, shelfHeight);
-            });
-        }
-
-        @Override
         public void onMinimizedStateChanged(boolean isMinimized) {
             mHandler.post(() -> {
                 mPipBoundsHandler.onMinimizedStateChanged(isMinimized);
@@ -161,14 +153,8 @@
         @Override
         public void onMovementBoundsChanged(Rect animatingBounds, boolean fromImeAdjustment,
                 boolean fromShelfAdjustment) {
-            mHandler.post(() -> {
-                // Populate the inset / normal bounds and DisplayInfo from mPipBoundsHandler first.
-                mPipBoundsHandler.onMovementBoundsChanged(mTmpInsetBounds, mTmpNormalBounds,
-                        animatingBounds, mTmpDisplayInfo);
-                mTouchHandler.onMovementBoundsChanged(mTmpInsetBounds, mTmpNormalBounds,
-                        animatingBounds, fromImeAdjustment, fromShelfAdjustment,
-                        mTmpDisplayInfo.rotation);
-            });
+            mHandler.post(() -> updateMovementBounds(animatingBounds, fromImeAdjustment,
+                    fromShelfAdjustment));
         }
 
         @Override
@@ -280,6 +266,31 @@
     }
 
     /**
+     * Sets both shelf visibility and its height.
+     */
+    @Override
+    public void setShelfHeight(boolean visible, int height) {
+        mHandler.post(() -> {
+            final boolean changed = mPipBoundsHandler.setShelfHeight(visible, height);
+            if (changed) {
+                mTouchHandler.onShelfVisibilityChanged(visible, height);
+                updateMovementBounds(mPipBoundsHandler.getLastDestinationBounds(),
+                        false /* fromImeAdjustment */, true /* fromShelfAdjustment */);
+            }
+        });
+    }
+
+    private void updateMovementBounds(Rect animatingBounds, boolean fromImeAdjustment,
+            boolean fromShelfAdjustment) {
+        // Populate inset / normal bounds and DisplayInfo from mPipBoundsHandler first.
+        mPipBoundsHandler.onMovementBoundsChanged(mTmpInsetBounds, mTmpNormalBounds,
+                animatingBounds, mTmpDisplayInfo);
+        mTouchHandler.onMovementBoundsChanged(mTmpInsetBounds, mTmpNormalBounds,
+                animatingBounds, fromImeAdjustment, fromShelfAdjustment,
+                mTmpDisplayInfo.rotation);
+    }
+
+    /**
      * Gets an instance of {@link PipManager}.
      */
     public static PipManager getInstance() {
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
index 4f2a6d8..5723afd 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
@@ -247,6 +247,9 @@
     protected void onStop() {
         super.onStop();
 
+        // In cases such as device lock, hide and finish it so that it can be recreated on the top
+        // next time it starts, see also {@link #onUserLeaveHint}
+        hideMenu();
         cancelDelayedFinish();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
index 75dc397..a258f35 100644
--- a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
+++ b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
@@ -45,6 +45,7 @@
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.SystemUI;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.statusbar.phone.StatusBar;
 
 import java.io.FileDescriptor;
@@ -53,6 +54,8 @@
 import java.util.Arrays;
 import java.util.concurrent.Future;
 
+import javax.inject.Inject;
+
 public class PowerUI extends SystemUI {
 
     static final String TAG = "PowerUI";
@@ -97,6 +100,12 @@
 
     private IThermalEventListener mSkinThermalEventListener;
     private IThermalEventListener mUsbThermalEventListener;
+    private final BroadcastDispatcher mBroadcastDispatcher;
+
+    @Inject
+    public PowerUI(BroadcastDispatcher broadcastDispatcher) {
+        mBroadcastDispatcher = broadcastDispatcher;
+    }
 
     public void start() {
         mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
@@ -211,7 +220,7 @@
             filter.addAction(Intent.ACTION_SCREEN_OFF);
             filter.addAction(Intent.ACTION_SCREEN_ON);
             filter.addAction(Intent.ACTION_USER_SWITCHED);
-            mContext.registerReceiver(this, filter, null, mHandler);
+            mBroadcastDispatcher.registerReceiver(this, filter, mHandler);
         }
 
         @Override
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java b/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java
index 55ae61d..b9f3a7f 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSCarrierGroup.java
@@ -18,11 +18,16 @@
 
 import static com.android.systemui.Dependency.BG_HANDLER;
 import static com.android.systemui.Dependency.BG_HANDLER_NAME;
+import static com.android.systemui.Dependency.MAIN_LOOPER;
+import static com.android.systemui.Dependency.MAIN_LOOPER_NAME;
 import static com.android.systemui.util.InjectionInflationController.VIEW_CONTEXT;
 
+import android.annotation.MainThread;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
 import android.provider.Settings;
 import android.telephony.SubscriptionManager;
 import android.util.AttributeSet;
@@ -39,6 +44,8 @@
 import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.statusbar.policy.NetworkController;
 
+import java.util.function.Consumer;
+
 import javax.inject.Inject;
 import javax.inject.Named;
 
@@ -46,7 +53,6 @@
  * Displays Carrier name and network status in QS
  */
 public class QSCarrierGroup extends LinearLayout implements
-        CarrierTextController.CarrierTextCallback,
         NetworkController.SignalCallback, View.OnClickListener {
 
     private static final String TAG = "QSCarrierGroup";
@@ -56,12 +62,14 @@
     private static final int SIM_SLOTS = 3;
     private final NetworkController mNetworkController;
     private final Handler mBgHandler;
+    private final H mMainHandler;
 
     private View[] mCarrierDividers = new View[SIM_SLOTS - 1];
     private QSCarrier[] mCarrierGroups = new QSCarrier[SIM_SLOTS];
     private TextView mNoSimTextView;
     private final CellSignalState[] mInfos = new CellSignalState[SIM_SLOTS];
     private CarrierTextController mCarrierTextController;
+    private CarrierTextController.CarrierTextCallback mCallback;
     private ActivityStarter mActivityStarter;
 
     private boolean mListening;
@@ -69,11 +77,19 @@
     @Inject
     public QSCarrierGroup(@Named(VIEW_CONTEXT) Context context, AttributeSet attrs,
             NetworkController networkController, ActivityStarter activityStarter,
-            @Named(BG_HANDLER_NAME) Handler handler) {
+            @Named(BG_HANDLER_NAME) Handler handler,
+            @Named(MAIN_LOOPER_NAME) Looper looper) {
         super(context, attrs);
         mNetworkController = networkController;
         mActivityStarter = activityStarter;
         mBgHandler = handler;
+        mMainHandler = new H(looper, this::handleUpdateCarrierInfo, this::handleUpdateState);
+        mCallback = new Callback(mMainHandler);
+    }
+
+    @VisibleForTesting
+    protected CarrierTextController.CarrierTextCallback getCallback() {
+        return mCallback;
     }
 
     @VisibleForTesting
@@ -81,7 +97,8 @@
         this(context, attrs,
                 Dependency.get(NetworkController.class),
                 Dependency.get(ActivityStarter.class),
-                Dependency.get(BG_HANDLER));
+                Dependency.get(BG_HANDLER),
+                Dependency.get(MAIN_LOOPER));
     }
 
     @Override
@@ -136,14 +153,20 @@
             if (mNetworkController.hasVoiceCallingFeature()) {
                 mNetworkController.addCallback(this);
             }
-            mCarrierTextController.setListening(this);
+            mCarrierTextController.setListening(mCallback);
         } else {
             mNetworkController.removeCallback(this);
             mCarrierTextController.setListening(null);
         }
     }
 
+    @MainThread
     private void handleUpdateState() {
+        if (!mMainHandler.getLooper().isCurrentThread()) {
+            mMainHandler.obtainMessage(H.MSG_UPDATE_STATE).sendToTarget();
+            return;
+        }
+
         for (int i = 0; i < SIM_SLOTS; i++) {
             mCarrierGroups[i].updateState(mInfos[i]);
         }
@@ -163,8 +186,13 @@
         return SubscriptionManager.getSlotIndex(subscriptionId);
     }
 
-    @Override
-    public void updateCarrierInfo(CarrierTextController.CarrierTextCallbackInfo info) {
+    @MainThread
+    private void handleUpdateCarrierInfo(CarrierTextController.CarrierTextCallbackInfo info) {
+        if (!mMainHandler.getLooper().isCurrentThread()) {
+            mMainHandler.obtainMessage(H.MSG_UPDATE_CARRIER_INFO, info).sendToTarget();
+            return;
+        }
+
         mNoSimTextView.setVisibility(View.GONE);
         if (!info.airplaneMode && info.anySimReady) {
             boolean[] slotSeen = new boolean[SIM_SLOTS];
@@ -207,7 +235,7 @@
             mNoSimTextView.setText(info.carrierText);
             mNoSimTextView.setVisibility(View.VISIBLE);
         }
-        handleUpdateState();
+        handleUpdateState(); // handleUpdateCarrierInfo is always called from main thread.
     }
 
     @Override
@@ -230,7 +258,7 @@
         mInfos[slotIndex].contentDescription = statusIcon.contentDescription;
         mInfos[slotIndex].typeContentDescription = typeContentDescription;
         mInfos[slotIndex].roaming = roaming;
-        handleUpdateState();
+        mMainHandler.obtainMessage(H.MSG_UPDATE_STATE).sendToTarget();
     }
 
     @Override
@@ -240,7 +268,7 @@
                 mInfos[i].visible = false;
             }
         }
-        handleUpdateState();
+        mMainHandler.obtainMessage(H.MSG_UPDATE_STATE).sendToTarget();
     }
 
     static final class CellSignalState {
@@ -250,4 +278,47 @@
         String typeContentDescription;
         boolean roaming;
     }
+
+    private static class H extends Handler {
+        private Consumer<CarrierTextController.CarrierTextCallbackInfo> mUpdateCarrierInfo;
+        private Runnable mUpdateState;
+        static final int MSG_UPDATE_CARRIER_INFO = 0;
+        static final int MSG_UPDATE_STATE = 1;
+
+        H(Looper looper,
+                Consumer<CarrierTextController.CarrierTextCallbackInfo> updateCarrierInfo,
+                Runnable updateState) {
+            super(looper);
+            mUpdateCarrierInfo = updateCarrierInfo;
+            mUpdateState = updateState;
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case MSG_UPDATE_CARRIER_INFO:
+                    mUpdateCarrierInfo.accept(
+                            (CarrierTextController.CarrierTextCallbackInfo) msg.obj);
+                    break;
+                case MSG_UPDATE_STATE:
+                    mUpdateState.run();
+                    break;
+                default:
+                    super.handleMessage(msg);
+            }
+        }
+    }
+
+    private static class Callback implements CarrierTextController.CarrierTextCallback {
+        private H mMainHandler;
+
+        Callback(H handler) {
+            mMainHandler = handler;
+        }
+
+        @Override
+        public void updateCarrierInfo(CarrierTextController.CarrierTextCallbackInfo info) {
+            mMainHandler.obtainMessage(H.MSG_UPDATE_CARRIER_INFO, info).sendToTarget();
+        }
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
index d20b228..4013586 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
@@ -257,10 +257,6 @@
         mNextAlarmTextView.setSelected(true);
 
         mPermissionsHubEnabled = PrivacyItemControllerKt.isPermissionsHubEnabled();
-        // Change the ignored slots when DeviceConfig flag changes
-        DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_PRIVACY,
-                mContext.getMainExecutor(), mPropertiesListener);
-
     }
 
     private List<String> getIgnoredIconSlots() {
@@ -489,6 +485,9 @@
         super.onAttachedToWindow();
         mStatusBarIconController.addIconGroup(mIconManager);
         requestApplyInsets();
+        // Change the ignored slots when DeviceConfig flag changes
+        DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_PRIVACY,
+                mContext.getMainExecutor(), mPropertiesListener);
     }
 
     @Override
@@ -527,6 +526,7 @@
     public void onDetachedFromWindow() {
         setListening(false);
         mStatusBarIconController.removeIconGroup(mIconManager);
+        DeviceConfig.removeOnPropertiesChangedListener(mPropertiesListener);
         super.onDetachedFromWindow();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
index 38153ec..7fb5207 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
@@ -46,8 +46,8 @@
 import com.android.systemui.qs.QSTileHost;
 import com.android.systemui.statusbar.phone.LightBarController;
 import com.android.systemui.statusbar.phone.NotificationsQuickSettingsContainer;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
-import com.android.systemui.statusbar.policy.KeyguardMonitor.Callback;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
+import com.android.systemui.statusbar.policy.KeyguardStateController.Callback;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -68,7 +68,7 @@
 
     private final QSDetailClipper mClipper;
     private final LightBarController mLightBarController;
-    private KeyguardMonitor mKeyguardMonitor;
+    private KeyguardStateController mKeyguardStateController;
     private final ScreenLifecycle mScreenLifecycle;
     private final TileQueryHelper mTileQueryHelper;
     private final View mTransparentView;
@@ -89,7 +89,7 @@
     @Inject
     public QSCustomizer(Context context, AttributeSet attrs,
             LightBarController lightBarController,
-            KeyguardMonitor keyguardMonitor,
+            KeyguardStateController keyguardStateController,
             ScreenLifecycle screenLifecycle) {
         super(new ContextThemeWrapper(context, R.style.edit_theme), attrs);
 
@@ -124,7 +124,7 @@
         animator.setMoveDuration(TileAdapter.MOVE_DURATION);
         mRecyclerView.setItemAnimator(animator);
         mLightBarController = lightBarController;
-        mKeyguardMonitor = keyguardMonitor;
+        mKeyguardStateController = keyguardStateController;
         mScreenLifecycle = screenLifecycle;
         updateNavBackDrop(getResources().getConfiguration());
     }
@@ -187,7 +187,7 @@
             queryTiles();
             mNotifQsContainer.setCustomizerAnimating(true);
             mNotifQsContainer.setCustomizerShowing(true);
-            mKeyguardMonitor.addCallback(mKeyguardCallback);
+            mKeyguardStateController.addCallback(mKeyguardCallback);
             updateNavColors();
         }
     }
@@ -203,7 +203,7 @@
             queryTiles();
             mNotifQsContainer.setCustomizerAnimating(false);
             mNotifQsContainer.setCustomizerShowing(true);
-            mKeyguardMonitor.addCallback(mKeyguardCallback);
+            mKeyguardStateController.addCallback(mKeyguardCallback);
             updateNavColors();
         }
     }
@@ -227,7 +227,7 @@
             }
             mNotifQsContainer.setCustomizerAnimating(animate);
             mNotifQsContainer.setCustomizerShowing(false);
-            mKeyguardMonitor.removeCallback(mKeyguardCallback);
+            mKeyguardStateController.removeCallback(mKeyguardCallback);
             updateNavColors();
         }
     }
@@ -283,7 +283,7 @@
 
     public void saveInstanceState(Bundle outState) {
         if (isShown) {
-            mKeyguardMonitor.removeCallback(mKeyguardCallback);
+            mKeyguardStateController.removeCallback(mKeyguardCallback);
         }
         outState.putBoolean(EXTRA_QS_CUSTOMIZING, mCustomizing);
     }
@@ -315,7 +315,7 @@
         @Override
         public void onKeyguardShowingChanged() {
             if (!isAttachedToWindow()) return;
-            if (mKeyguardMonitor.isShowing() && !mOpening) {
+            if (mKeyguardStateController.isShowing() && !mOpening) {
                 hide();
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
index 2542abd..bd3297b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
@@ -277,20 +277,7 @@
                     selectPosition(holder.getAdapterPosition(), v);
                 }
             });
-            if (mNeedsFocus) {
-                // Wait for this to get laid out then set its focus.
-                // Ensure that tile gets laid out so we get the callback.
-                holder.mTileView.requestLayout();
-                holder.mTileView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
-                    @Override
-                    public void onLayoutChange(View v, int left, int top, int right, int bottom,
-                            int oldLeft, int oldTop, int oldRight, int oldBottom) {
-                        holder.mTileView.removeOnLayoutChangeListener(this);
-                        holder.mTileView.requestFocus();
-                    }
-                });
-                mNeedsFocus = false;
-            }
+            focusOnHolder(holder);
             return;
         }
 
@@ -330,16 +317,38 @@
                         } else {
                             if (position < mEditIndex && canRemoveTiles()) {
                                 showAccessibilityDialog(position, v);
+                            } else if (position < mEditIndex && !canRemoveTiles()) {
+                                startAccessibleMove(position);
                             } else {
                                 startAccessibleAdd(position);
                             }
                         }
                     }
                 });
+                if (position == mAccessibilityFromIndex) {
+                    focusOnHolder(holder);
+                }
             }
         }
     }
 
+    private void focusOnHolder(Holder holder) {
+        if (mNeedsFocus) {
+            // Wait for this to get laid out then set its focus.
+            // Ensure that tile gets laid out so we get the callback.
+            holder.mTileView.requestLayout();
+            holder.mTileView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
+                @Override
+                public void onLayoutChange(View v, int left, int top, int right, int bottom,
+                        int oldLeft, int oldTop, int oldRight, int oldBottom) {
+                    holder.mTileView.removeOnLayoutChangeListener(this);
+                    holder.mTileView.requestFocus();
+                }
+            });
+            mNeedsFocus = false;
+        }
+    }
+
     private boolean canRemoveTiles() {
         return mCurrentSpecs.size() > mMinNumTiles;
     }
@@ -396,6 +405,7 @@
         mAccessibilityFromIndex = position;
         mAccessibilityFromLabel = mTiles.get(position).state.label;
         mAccessibilityAction = ACTION_MOVE;
+        mNeedsFocus = true;
         notifyDataSetChanged();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/external/TileServices.java b/packages/SystemUI/src/com/android/systemui/qs/external/TileServices.java
index 23f36e9..13cfa78 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/external/TileServices.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/external/TileServices.java
@@ -39,7 +39,7 @@
 import com.android.systemui.Dependency;
 import com.android.systemui.qs.QSTileHost;
 import com.android.systemui.statusbar.phone.StatusBarIconController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -296,14 +296,16 @@
 
     @Override
     public boolean isLocked() {
-        KeyguardMonitor keyguardMonitor = Dependency.get(KeyguardMonitor.class);
-        return keyguardMonitor.isShowing();
+        KeyguardStateController keyguardStateController =
+                Dependency.get(KeyguardStateController.class);
+        return keyguardStateController.isShowing();
     }
 
     @Override
     public boolean isSecure() {
-        KeyguardMonitor keyguardMonitor = Dependency.get(KeyguardMonitor.class);
-        return keyguardMonitor.isSecure() && keyguardMonitor.isShowing();
+        KeyguardStateController keyguardStateController =
+                Dependency.get(KeyguardStateController.class);
+        return keyguardStateController.isMethodSecure() && keyguardStateController.isShowing();
     }
 
     private CustomTile getTileForToken(IBinder token) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
index b1dfbb5..0e813d1 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
@@ -45,7 +45,7 @@
 import com.android.systemui.statusbar.phone.SystemUIDialog;
 import com.android.systemui.statusbar.policy.CastController;
 import com.android.systemui.statusbar.policy.CastController.CastDevice;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.NetworkController;
 
 import java.util.ArrayList;
@@ -61,7 +61,7 @@
 
     private final CastController mController;
     private final CastDetailAdapter mDetailAdapter;
-    private final KeyguardMonitor mKeyguard;
+    private final KeyguardStateController mKeyguard;
     private final NetworkController mNetworkController;
     private final Callback mCallback = new Callback();
     private final ActivityStarter mActivityStarter;
@@ -69,12 +69,13 @@
     private boolean mWifiConnected;
 
     @Inject
-    public CastTile(QSHost host, CastController castController, KeyguardMonitor keyguardMonitor,
-            NetworkController networkController, ActivityStarter activityStarter) {
+    public CastTile(QSHost host, CastController castController,
+            KeyguardStateController keyguardStateController, NetworkController networkController,
+            ActivityStarter activityStarter) {
         super(host);
         mController = castController;
         mDetailAdapter = new CastDetailAdapter();
-        mKeyguard = keyguardMonitor;
+        mKeyguard = keyguardStateController;
         mNetworkController = networkController;
         mActivityStarter = activityStarter;
         mController.observe(this, mCallback);
@@ -257,7 +258,8 @@
                 }
             };
 
-    private final class Callback implements CastController.Callback, KeyguardMonitor.Callback {
+    private final class Callback implements CastController.Callback,
+            KeyguardStateController.Callback {
         @Override
         public void onCastDevicesChanged() {
             refreshState();
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
index 4de42cc..22470c7 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
@@ -95,6 +95,9 @@
 
     @Override
     public Intent getLongClickIntent() {
+        if (getState().state == Tile.STATE_UNAVAILABLE) {
+            return new Intent(Settings.ACTION_WIRELESS_SETTINGS);
+        }
         return getCellularSettingIntent();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java
index 2755e98..dafdd89 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/FlashlightTile.java
@@ -101,11 +101,15 @@
             state.slash = new SlashState();
         }
         state.label = mHost.getContext().getString(R.string.quick_settings_flashlight_label);
+        state.secondaryLabel = "";
         if (!mFlashlightController.isAvailable()) {
             state.icon = mIcon;
             state.slash.isSlashed = true;
+            state.secondaryLabel = mContext.getString(
+                    R.string.quick_settings_flashlight_camera_in_use);
             state.contentDescription = mContext.getString(
-                    R.string.accessibility_quick_settings_flashlight_unavailable);
+                    R.string.accessibility_quick_settings_flashlight_unavailable)
+                    + ", " + state.secondaryLabel;
             state.state = Tile.STATE_UNAVAILABLE;
             return;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java
index 837ea9f..fbdca3b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/LocationTile.java
@@ -28,7 +28,7 @@
 import com.android.systemui.plugins.qs.QSTile.BooleanState;
 import com.android.systemui.qs.QSHost;
 import com.android.systemui.qs.tileimpl.QSTileImpl;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.LocationController;
 import com.android.systemui.statusbar.policy.LocationController.LocationChangeCallback;
 
@@ -40,16 +40,16 @@
     private final Icon mIcon = ResourceIcon.get(R.drawable.ic_location);
 
     private final LocationController mController;
-    private final KeyguardMonitor mKeyguard;
+    private final KeyguardStateController mKeyguard;
     private final ActivityStarter mActivityStarter;
     private final Callback mCallback = new Callback();
 
     @Inject
     public LocationTile(QSHost host, LocationController locationController,
-            KeyguardMonitor keyguardMonitor, ActivityStarter activityStarter) {
+            KeyguardStateController keyguardStateController, ActivityStarter activityStarter) {
         super(host);
         mController = locationController;
-        mKeyguard = keyguardMonitor;
+        mKeyguard = keyguardStateController;
         mActivityStarter = activityStarter;
         mController.observe(this, mCallback);
         mKeyguard.observe(this, mCallback);
@@ -71,7 +71,7 @@
 
     @Override
     protected void handleClick() {
-        if (mKeyguard.isSecure() && mKeyguard.isShowing()) {
+        if (mKeyguard.isMethodSecure() && mKeyguard.isShowing()) {
             mActivityStarter.postQSRunnableDismissingKeyguard(() -> {
                 final boolean wasEnabled = mState.value;
                 mHost.openPanels();
@@ -97,7 +97,7 @@
 
         // Work around for bug 15916487: don't show location tile on top of lock screen. After the
         // bug is fixed, this should be reverted to only hiding it on secure lock screens:
-        // state.visible = !(mKeyguard.isSecure() && mKeyguard.isShowing());
+        // state.visible = !(mKeyguard.isMethodSecure() && mKeyguard.isShowing());
         state.value = locationEnabled;
         checkIfRestrictionEnforcedByAdminOnly(state, UserManager.DISALLOW_SHARE_LOCATION);
         if (state.disabledByPolicy == false) {
@@ -133,7 +133,7 @@
     }
 
     private final class Callback implements LocationChangeCallback,
-            KeyguardMonitor.Callback {
+            KeyguardStateController.Callback {
         @Override
         public void onLocationSettingsChanged(boolean enabled) {
             refreshState();
diff --git a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
index 9268ee0..e0ae8ed 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
@@ -58,6 +58,7 @@
 import com.android.systemui.Dumpable;
 import com.android.systemui.SysUiServiceProvider;
 import com.android.systemui.model.SysUiState;
+import com.android.systemui.pip.PipUI;
 import com.android.systemui.recents.OverviewProxyService.OverviewProxyListener;
 import com.android.systemui.shared.recents.IOverviewProxy;
 import com.android.systemui.shared.recents.ISystemUiProxy;
@@ -353,6 +354,20 @@
             }
         }
 
+        @Override
+        public void setShelfHeight(boolean visible, int shelfHeight) {
+            if (!verifyCaller("setShelfHeight")) {
+                return;
+            }
+            long token = Binder.clearCallingIdentity();
+            try {
+                final PipUI component = SysUiServiceProvider.getComponent(mContext, PipUI.class);
+                component.setShelfHeight(visible, shelfHeight);
+            } finally {
+                Binder.restoreCallingIdentity(token);
+            }
+        }
+
         private boolean verifyCaller(String reason) {
             final int callerId = Binder.getCallingUserHandle().getIdentifier();
             if (callerId != mCurrentBoundedUserId) {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/Recents.java b/packages/SystemUI/src/com/android/systemui/recents/Recents.java
index 0fc4fe7..a1b4a93 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/Recents.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/Recents.java
@@ -21,25 +21,30 @@
 import android.graphics.Rect;
 import android.provider.Settings;
 
-import com.android.systemui.R;
 import com.android.systemui.SystemUI;
 import com.android.systemui.statusbar.CommandQueue;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 
+import javax.inject.Inject;
+
 /**
  * A proxy to a Recents implementation.
  */
 public class Recents extends SystemUI implements CommandQueue.Callbacks {
 
-    private RecentsImplementation mImpl;
+    private final RecentsImplementation mImpl;
+
+    @Inject
+    public Recents(RecentsImplementation impl) {
+        mImpl = impl;
+    }
 
     @Override
     public void start() {
         getComponent(CommandQueue.class).addCallback(this);
         putComponent(Recents.class, this);
-        mImpl = createRecentsImplementationFromConfig();
         mImpl.onStart(mContext, this);
     }
 
@@ -139,28 +144,6 @@
                 (Settings.Secure.getInt(cr, Settings.Secure.USER_SETUP_COMPLETE, 0) != 0);
     }
 
-    /**
-     * @return The recents implementation from the config.
-     */
-    private RecentsImplementation createRecentsImplementationFromConfig() {
-        final String clsName = mContext.getString(R.string.config_recentsComponent);
-        if (clsName == null || clsName.length() == 0) {
-            throw new RuntimeException("No recents component configured", null);
-        }
-        Class<?> cls = null;
-        try {
-            cls = mContext.getClassLoader().loadClass(clsName);
-        } catch (Throwable t) {
-            throw new RuntimeException("Error loading recents component: " + clsName, t);
-        }
-        try {
-            RecentsImplementation impl = (RecentsImplementation) cls.newInstance();
-            return impl;
-        } catch (Throwable t) {
-            throw new RuntimeException("Error creating recents component: " + clsName, t);
-        }
-    }
-
     @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         mImpl.dump(pw);
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsModule.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsModule.java
new file mode 100644
index 0000000..5555285
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsModule.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2019 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.recents;
+
+import android.content.Context;
+
+import com.android.systemui.R;
+
+import dagger.Module;
+import dagger.Provides;
+
+/**
+ * Dagger injection module for {@link RecentsImplementation}
+ */
+@Module
+public class RecentsModule {
+    /**
+     * @return The {@link RecentsImplementation} from the config.
+     */
+    @Provides
+    public RecentsImplementation provideRecentsImpl(Context context) {
+        final String clsName = context.getString(R.string.config_recentsComponent);
+        if (clsName == null || clsName.length() == 0) {
+            throw new RuntimeException("No recents component configured", null);
+        }
+        Class<?> cls = null;
+        try {
+            cls = context.getClassLoader().loadClass(clsName);
+        } catch (Throwable t) {
+            throw new RuntimeException("Error loading recents component: " + clsName, t);
+        }
+        try {
+            RecentsImplementation impl = (RecentsImplementation) cls.newInstance();
+            return impl;
+        } catch (Throwable t) {
+            throw new RuntimeException("Error creating recents component: " + clsName, t);
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsOnboarding.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsOnboarding.java
index d0c4734..c1ce163 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsOnboarding.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsOnboarding.java
@@ -61,8 +61,10 @@
 import android.widget.ImageView;
 import android.widget.TextView;
 
+import com.android.systemui.Dependency;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.shared.recents.IOverviewProxy;
 import com.android.systemui.shared.system.ActivityManagerWrapper;
 import com.android.systemui.shared.system.QuickStepContract;
@@ -245,10 +247,15 @@
 
     private final View.OnAttachStateChangeListener mOnAttachStateChangeListener
             = new View.OnAttachStateChangeListener() {
+
+        private final BroadcastDispatcher mBroadcastDispatcher = Dependency.get(
+                BroadcastDispatcher.class);
+
         @Override
         public void onViewAttachedToWindow(View view) {
             if (view == mLayout) {
-                mContext.registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
+                mBroadcastDispatcher.registerReceiver(mReceiver,
+                        new IntentFilter(Intent.ACTION_SCREEN_OFF));
                 mLayoutAttachedToWindow = true;
                 if (view.getTag().equals(R.string.recents_swipe_up_onboarding)) {
                     mHasDismissedSwipeUpTip = false;
@@ -273,7 +280,7 @@
                     }
                     mOverviewOpenedCountSinceQuickScrubTipDismiss = 0;
                 }
-                mContext.unregisterReceiver(mReceiver);
+                mBroadcastDispatcher.unregisterReceiver(mReceiver);
             }
         }
     };
@@ -335,10 +342,11 @@
     private void notifyOnTip(int action, int target) {
         try {
             IOverviewProxy overviewProxy = mOverviewProxyService.getProxy();
-            if(overviewProxy != null) {
+            if (overviewProxy != null) {
                 overviewProxy.onTip(action, target);
             }
-        } catch (RemoteException e) {}
+        } catch (RemoteException e) {
+        }
     }
 
     public void onNavigationModeChanged(int mode) {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java b/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
index c3c0d63..0f277ca 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
@@ -47,6 +47,7 @@
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.shared.system.QuickStepContract;
 import com.android.systemui.shared.system.WindowManagerWrapper;
 import com.android.systemui.statusbar.phone.NavigationBarView;
@@ -159,6 +160,8 @@
         private ValueAnimator mColorAnim;
         private ViewGroup mLayout;
         private boolean mShowCancel;
+        private final BroadcastDispatcher mBroadcastDispatcher =
+                Dependency.get(BroadcastDispatcher.class);
 
         public RequestWindowView(Context context, boolean showCancel) {
             super(context);
@@ -212,7 +215,7 @@
             IntentFilter filter = new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED);
             filter.addAction(Intent.ACTION_USER_SWITCHED);
             filter.addAction(Intent.ACTION_SCREEN_OFF);
-            mContext.registerReceiver(mReceiver, filter);
+            mBroadcastDispatcher.registerReceiver(mReceiver, filter);
         }
 
         private void inflateView(int rotation) {
@@ -313,7 +316,7 @@
 
         @Override
         public void onDetachedFromWindow() {
-            mContext.unregisterReceiver(mReceiver);
+            mBroadcastDispatcher.unregisterReceiver(mReceiver);
         }
 
         protected void onConfigurationChanged() {
diff --git a/packages/SystemUI/src/com/android/systemui/settings/BrightnessController.java b/packages/SystemUI/src/com/android/systemui/settings/BrightnessController.java
index 1e0a9f1..176676f 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/BrightnessController.java
+++ b/packages/SystemUI/src/com/android/systemui/settings/BrightnessController.java
@@ -152,6 +152,20 @@
     private final Runnable mStartListeningRunnable = new Runnable() {
         @Override
         public void run() {
+            if (mListening) {
+                return;
+            }
+            mListening = true;
+
+            if (mVrManager != null) {
+                try {
+                    mVrManager.registerListener(mVrStateCallbacks);
+                    mIsVrModeEnabled = mVrManager.getVrModeState();
+                } catch (RemoteException e) {
+                    Log.e(TAG, "Failed to register VR mode state listener: ", e);
+                }
+            }
+
             mBrightnessObserver.startObserving();
             mUserTracker.startTracking();
 
@@ -167,6 +181,19 @@
     private final Runnable mStopListeningRunnable = new Runnable() {
         @Override
         public void run() {
+            if (!mListening) {
+                return;
+            }
+            mListening = false;
+
+            if (mVrManager != null) {
+                try {
+                    mVrManager.unregisterListener(mVrStateCallbacks);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "Failed to unregister VR mode state listener: ", e);
+                }
+            }
+
             mBrightnessObserver.stopObserving();
             mUserTracker.stopTracking();
 
@@ -297,39 +324,12 @@
     }
 
     public void registerCallbacks() {
-        if (mListening) {
-            return;
-        }
-
-        if (mVrManager != null) {
-            try {
-                mVrManager.registerListener(mVrStateCallbacks);
-                mIsVrModeEnabled = mVrManager.getVrModeState();
-            } catch (RemoteException e) {
-                Log.e(TAG, "Failed to register VR mode state listener: ", e);
-            }
-        }
-
         mBackgroundHandler.post(mStartListeningRunnable);
-        mListening = true;
     }
 
     /** Unregister all call backs, both to and from the controller */
     public void unregisterCallbacks() {
-        if (!mListening) {
-            return;
-        }
-
-        if (mVrManager != null) {
-            try {
-                mVrManager.unregisterListener(mVrStateCallbacks);
-            } catch (RemoteException e) {
-                Log.e(TAG, "Failed to unregister VR mode state listener: ", e);
-            }
-        }
-
         mBackgroundHandler.post(mStopListeningRunnable);
-        mListening = false;
         mControlValueInitialized = false;
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
index 134d4b8..36e04fe 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
@@ -270,12 +270,13 @@
 
         default void onRotationProposal(int rotation, boolean isValid) { }
 
-        default void showBiometricDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
-                int type, boolean requireConfirmation, int userId, String opPackageName) { }
+        default void showAuthenticationDialog(Bundle bundle,
+                IBiometricServiceReceiverInternal receiver, int biometricModality,
+                boolean requireConfirmation, int userId, String opPackageName) { }
         default void onBiometricAuthenticated(boolean authenticated, String failureReason) { }
         default void onBiometricHelp(String message) { }
-        default void onBiometricError(String error) { }
-        default void hideBiometricDialog() { }
+        default void onBiometricError(int errorCode, String error) { }
+        default void hideAuthenticationDialog() { }
 
         /**
          * @see IStatusBar#onDisplayReady(int)
@@ -740,13 +741,13 @@
     }
 
     @Override
-    public void showBiometricDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
-            int type, boolean requireConfirmation, int userId, String opPackageName) {
+    public void showAuthenticationDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
+            int biometricModality, boolean requireConfirmation, int userId, String opPackageName) {
         synchronized (mLock) {
             SomeArgs args = SomeArgs.obtain();
             args.arg1 = bundle;
             args.arg2 = receiver;
-            args.argi1 = type;
+            args.argi1 = biometricModality;
             args.arg3 = requireConfirmation;
             args.argi2 = userId;
             args.arg4 = opPackageName;
@@ -773,14 +774,14 @@
     }
 
     @Override
-    public void onBiometricError(String error) {
+    public void onBiometricError(int errorCode, String error) {
         synchronized (mLock) {
-            mHandler.obtainMessage(MSG_BIOMETRIC_ERROR, error).sendToTarget();
+            mHandler.obtainMessage(MSG_BIOMETRIC_ERROR, errorCode, 0, error).sendToTarget();
         }
     }
 
     @Override
-    public void hideBiometricDialog() {
+    public void hideAuthenticationDialog() {
         synchronized (mLock) {
             mHandler.obtainMessage(MSG_BIOMETRIC_HIDE).sendToTarget();
         }
@@ -1032,10 +1033,10 @@
                     mHandler.removeMessages(MSG_BIOMETRIC_AUTHENTICATED);
                     SomeArgs someArgs = (SomeArgs) msg.obj;
                     for (int i = 0; i < mCallbacks.size(); i++) {
-                        mCallbacks.get(i).showBiometricDialog(
+                        mCallbacks.get(i).showAuthenticationDialog(
                                 (Bundle) someArgs.arg1,
                                 (IBiometricServiceReceiverInternal) someArgs.arg2,
-                                someArgs.argi1 /* type */,
+                                someArgs.argi1 /* biometricModality */,
                                 (boolean) someArgs.arg3 /* requireConfirmation */,
                                 someArgs.argi2 /* userId */,
                                 (String) someArgs.arg4 /* opPackageName */);
@@ -1060,12 +1061,12 @@
                     break;
                 case MSG_BIOMETRIC_ERROR:
                     for (int i = 0; i < mCallbacks.size(); i++) {
-                        mCallbacks.get(i).onBiometricError((String) msg.obj);
+                        mCallbacks.get(i).onBiometricError(msg.arg1, (String) msg.obj);
                     }
                     break;
                 case MSG_BIOMETRIC_HIDE:
                     for (int i = 0; i < mCallbacks.size(); i++) {
-                        mCallbacks.get(i).hideBiometricDialog();
+                        mCallbacks.get(i).hideAuthenticationDialog();
                     }
                     break;
                 case MSG_SHOW_CHARGING_ANIMATION:
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
index 156e3c0..681f3ab 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardIndicationController.java
@@ -57,8 +57,8 @@
 import com.android.systemui.statusbar.phone.LockscreenGestureLogger;
 import com.android.systemui.statusbar.phone.ShadeController;
 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
 import com.android.systemui.statusbar.policy.AccessibilityController;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.UserInfoController;
 import com.android.systemui.util.wakelock.SettableWakeLock;
 import com.android.systemui.util.wakelock.WakeLock;
@@ -72,7 +72,7 @@
  * Controls the indications and error messages shown on the Keyguard
  */
 public class KeyguardIndicationController implements StateListener,
-        UnlockMethodCache.OnUnlockMethodChangedListener {
+        KeyguardStateController.Callback {
 
     private static final String TAG = "KeyguardIndication";
     private static final boolean DEBUG_CHARGING_SPEED = false;
@@ -86,7 +86,7 @@
     private final Context mContext;
     private final ShadeController mShadeController;
     private final AccessibilityController mAccessibilityController;
-    private final UnlockMethodCache mUnlockMethodCache;
+    private final KeyguardStateController mKeyguardStateController;
     private final StatusBarStateController mStatusBarStateController;
     private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
     private ViewGroup mIndicationArea;
@@ -137,7 +137,7 @@
                 WakeLock.createPartial(context, "Doze:KeyguardIndication"),
                 Dependency.get(ShadeController.class),
                 Dependency.get(AccessibilityController.class),
-                UnlockMethodCache.getInstance(context),
+                Dependency.get(KeyguardStateController.class),
                 Dependency.get(StatusBarStateController.class),
                 Dependency.get(KeyguardUpdateMonitor.class));
     }
@@ -148,14 +148,15 @@
     @VisibleForTesting
     KeyguardIndicationController(Context context, ViewGroup indicationArea, LockIcon lockIcon,
             LockPatternUtils lockPatternUtils, WakeLock wakeLock, ShadeController shadeController,
-            AccessibilityController accessibilityController, UnlockMethodCache unlockMethodCache,
+            AccessibilityController accessibilityController,
+            KeyguardStateController keyguardStateController,
             StatusBarStateController statusBarStateController,
             KeyguardUpdateMonitor keyguardUpdateMonitor) {
         mContext = context;
         mLockIcon = lockIcon;
         mShadeController = shadeController;
         mAccessibilityController = accessibilityController;
-        mUnlockMethodCache = unlockMethodCache;
+        mKeyguardStateController = keyguardStateController;
         mStatusBarStateController = statusBarStateController;
         mKeyguardUpdateMonitor = keyguardUpdateMonitor;
         // lock icon is not used on all form factors.
@@ -181,7 +182,7 @@
         mKeyguardUpdateMonitor.registerCallback(getKeyguardCallback());
         mKeyguardUpdateMonitor.registerCallback(mTickReceiver);
         mStatusBarStateController.addCallback(this);
-        mUnlockMethodCache.addListener(this);
+        mKeyguardStateController.addCallback(this);
     }
 
     public void setIndicationArea(ViewGroup indicationArea) {
@@ -583,7 +584,7 @@
     }
 
     @Override
-    public void onUnlockMethodStateChanged() {
+    public void onUnlockedChanged() {
         updateIndication(!mDozing);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
index 7bcbd36..16cdfaa 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
@@ -37,6 +37,7 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.statusbar.RegisterStatusBarResult;
 import com.android.systemui.Dependency;
+import com.android.systemui.assist.AssistHandleViewController;
 import com.android.systemui.plugins.DarkIconDispatcher;
 import com.android.systemui.statusbar.CommandQueue.Callbacks;
 import com.android.systemui.statusbar.phone.AutoHideController;
@@ -233,4 +234,10 @@
     public NavigationBarFragment getDefaultNavigationBarFragment() {
         return mNavigationBars.get(DEFAULT_DISPLAY);
     }
+
+    /** @return {@link AssistHandleViewController} (only on the default display). */
+    public AssistHandleViewController getAssistHandlerViewController() {
+        NavigationBarFragment navBar = getDefaultNavigationBarFragment();
+        return navBar == null ? null : navBar.getAssistHandlerViewController();
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
index 1400921..c4de2d3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
@@ -21,6 +21,7 @@
 import static com.android.systemui.statusbar.phone.StatusBar.DEBUG;
 import static com.android.systemui.statusbar.phone.StatusBar.ENABLE_CHILD_NOTIFICATIONS;
 
+import android.annotation.Nullable;
 import android.annotation.SuppressLint;
 import android.app.NotificationManager;
 import android.content.ComponentName;
@@ -57,8 +58,9 @@
     private final NotificationGroupManager mGroupManager =
             Dependency.get(NotificationGroupManager.class);
 
-    private final ArrayList<NotificationSettingsListener> mSettingsListeners = new ArrayList<>();
     private final Context mContext;
+    private final ArrayList<NotificationSettingsListener> mSettingsListeners = new ArrayList<>();
+    @Nullable private NotifServiceListener mDownstreamListener;
 
     @Inject
     public NotificationListener(Context context) {
@@ -69,6 +71,10 @@
         mSettingsListeners.add(listener);
     }
 
+    public void setDownstreamListener(NotifServiceListener downstreamListener) {
+        mDownstreamListener = downstreamListener;
+    }
+
     @Override
     public void onListenerConnected() {
         if (DEBUG) Log.d(TAG, "onListenerConnected");
@@ -81,6 +87,9 @@
         final RankingMap currentRanking = getCurrentRanking();
         Dependency.get(Dependency.MAIN_HANDLER).post(() -> {
             for (StatusBarNotification sbn : notifications) {
+                if (mDownstreamListener != null) {
+                    mDownstreamListener.onNotificationPosted(sbn, currentRanking);
+                }
                 mEntryManager.addNotification(sbn, currentRanking);
             }
         });
@@ -95,6 +104,11 @@
         if (sbn != null && !onPluginNotificationPosted(sbn, rankingMap)) {
             Dependency.get(Dependency.MAIN_HANDLER).post(() -> {
                 processForRemoteInput(sbn.getNotification(), mContext);
+
+                if (mDownstreamListener != null) {
+                    mDownstreamListener.onNotificationPosted(sbn, rankingMap);
+                }
+
                 String key = sbn.getKey();
                 boolean isUpdate =
                         mEntryManager.getNotificationData().get(key) != null;
@@ -113,7 +127,7 @@
                         mEntryManager.removeNotification(key, rankingMap, UNDEFINED_DISMISS_REASON);
                     } else {
                         mEntryManager.getNotificationData()
-                                .updateRanking(rankingMap);
+                                .updateRanking(rankingMap, "onNotificationPosted");
                     }
                     return;
                 }
@@ -133,6 +147,9 @@
         if (sbn != null && !onPluginNotificationRemoved(sbn, rankingMap)) {
             final String key = sbn.getKey();
             Dependency.get(Dependency.MAIN_HANDLER).post(() -> {
+                if (mDownstreamListener != null) {
+                    mDownstreamListener.onNotificationRemoved(sbn, rankingMap, reason);
+                }
                 mEntryManager.removeNotification(key, rankingMap, reason);
             });
         }
@@ -149,6 +166,9 @@
         if (rankingMap != null) {
             RankingMap r = onPluginRankingUpdate(rankingMap);
             Dependency.get(Dependency.MAIN_HANDLER).post(() -> {
+                if (mDownstreamListener != null) {
+                    mDownstreamListener.onNotificationRankingUpdate(rankingMap);
+                }
                 mEntryManager.updateNotificationRanking(r);
             });
         }
@@ -175,4 +195,12 @@
 
         default void onStatusBarIconsBehaviorChanged(boolean hideSilentStatusIcons) { }
     }
+
+    /** Interface for listening to add/remove events that we receive from NotificationManager. */
+    public interface NotifServiceListener {
+        void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap);
+        void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap);
+        void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap, int reason);
+        void onNotificationRankingUpdate(RankingMap rankingMap);
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
index f782fab..6ffea79 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
@@ -54,7 +54,7 @@
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -76,7 +76,8 @@
 
     private final DeviceProvisionedController mDeviceProvisionedController =
             Dependency.get(DeviceProvisionedController.class);
-    private final KeyguardMonitor mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+    private final KeyguardStateController mKeyguardStateController = Dependency.get(
+            KeyguardStateController.class);
 
     // Lazy
     private NotificationEntryManager mEntryManager;
@@ -105,7 +106,7 @@
                     isCurrentProfile(getSendingUserId())) {
                 mUsersAllowingPrivateNotifications.clear();
                 updateLockscreenNotificationSetting();
-                getEntryManager().updateNotifications();
+                getEntryManager().updateNotifications("ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED");
             }
         }
     };
@@ -123,7 +124,7 @@
                 updatePublicMode();
                 // The filtering needs to happen before the update call below in order to make sure
                 // the presenter has the updated notifications from the new user
-                getEntryManager().getNotificationData().filterAndSort();
+                getEntryManager().getNotificationData().filterAndSort("user switched");
                 mPresenter.onUserSwitched(mCurrentUserId);
 
                 for (UserChangedListener listener : mListeners) {
@@ -204,7 +205,8 @@
                 mUsersAllowingNotifications.clear();
                 // ... and refresh all the notifications
                 updateLockscreenNotificationSetting();
-                getEntryManager().updateNotifications();
+                getEntryManager().updateNotifications("LOCK_SCREEN_SHOW_NOTIFICATIONS,"
+                        + " or LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS change");
             }
         };
 
@@ -213,7 +215,8 @@
             public void onChange(boolean selfChange) {
                 updateLockscreenNotificationSetting();
                 if (mDeviceProvisionedController.isDeviceProvisioned()) {
-                    getEntryManager().updateNotifications();
+                    getEntryManager().updateNotifications("LOCK_SCREEN_ALLOW_REMOTE_INPUT"
+                            + " or ZEN_MODE change");
                 }
             }
         };
@@ -507,8 +510,8 @@
         // asking if the keyguard is showing. We still need to check it though because showing the
         // camera on the keyguard has a state of SHADE but the keyguard is still showing.
         final boolean showingKeyguard = mState != StatusBarState.SHADE
-              || mKeyguardMonitor.isShowing();
-        final boolean devicePublic = showingKeyguard && isSecure(getCurrentUserId());
+                || mKeyguardStateController.isShowing();
+        final boolean devicePublic = showingKeyguard && mKeyguardStateController.isMethodSecure();
 
 
         // Look for public mode users. Users are considered public in either case of:
@@ -523,7 +526,7 @@
             boolean needsSeparateChallenge = whitelistIpcs(() ->
                     mLockPatternUtils.isSeparateProfileChallengeEnabled(userId));
             if (!devicePublic && userId != getCurrentUserId()
-                    && needsSeparateChallenge && isSecure(userId)) {
+                    && needsSeparateChallenge && mLockPatternUtils.isSecure(userId)) {
                 // Keyguard.isDeviceLocked is updated asynchronously, assume that all profiles
                 // with separate challenge are locked when keyguard is visible to avoid race.
                 isProfilePublic = showingKeyguard || mKeyguardManager.isDeviceLocked(userId);
@@ -531,7 +534,7 @@
             setLockscreenPublicMode(isProfilePublic, userId);
             mUsersWithSeperateWorkChallenge.put(userId, needsSeparateChallenge);
         }
-        getEntryManager().updateNotifications();
+        getEntryManager().updateNotifications("NotificationLockscreenUserManager.updatePublicMode");
     }
 
     @Override
@@ -545,7 +548,7 @@
 //        // asking if the keyguard is showing. We still need to check it though because showing the
 //        // camera on the keyguard has a state of SHADE but the keyguard is still showing.
 //        final boolean showingKeyguard = mState != StatusBarState.SHADE
-//              || mKeyguardMonitor.isShowing();
+//              || mKeyguardStateController.isShowing();
 //        final boolean devicePublic = showingKeyguard && isSecure(getCurrentUserId());
 //
 //
@@ -570,10 +573,6 @@
 //        }
 //    }
 
-    private boolean isSecure(int userId) {
-        return mKeyguardMonitor.isSecure() || mLockPatternUtils.isSecure(userId);
-    }
-
     @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         pw.println("NotificationLockscreenUserManager state:");
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
index 00a12a9..3616b54 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
@@ -17,10 +17,6 @@
 
 import static com.android.systemui.Dependency.MAIN_HANDLER;
 import static com.android.systemui.statusbar.StatusBarState.KEYGUARD;
-import static com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_UNLOCK_FADING;
-import static com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_WAKE_AND_UNLOCK;
-import static com.android.systemui.statusbar.phone.BiometricUnlockController
-        .MODE_WAKE_AND_UNLOCK_PULSING;
 import static com.android.systemui.statusbar.phone.StatusBar.DEBUG_MEDIA_FAKE_ARTWORK;
 import static com.android.systemui.statusbar.phone.StatusBar.ENABLE_LOCKSCREEN_WALLPAPER;
 import static com.android.systemui.statusbar.phone.StatusBar.SHOW_LOCKSCREEN_MEDIA_ARTWORK;
@@ -67,7 +63,7 @@
 import com.android.systemui.statusbar.phone.ScrimState;
 import com.android.systemui.statusbar.phone.ShadeController;
 import com.android.systemui.statusbar.phone.StatusBarWindowController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -94,7 +90,8 @@
     private final StatusBarStateController mStatusBarStateController
             = Dependency.get(StatusBarStateController.class);
     private final SysuiColorExtractor mColorExtractor = Dependency.get(SysuiColorExtractor.class);
-    private final KeyguardMonitor mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+    private final KeyguardStateController mKeyguardStateController = Dependency.get(
+            KeyguardStateController.class);
     private final KeyguardBypassController mKeyguardBypassController;
     private static final HashSet<Integer> PAUSED_MEDIA_STATES = new HashSet<>();
     static {
@@ -364,7 +361,7 @@
         }
 
         if (metaDataChanged) {
-            mEntryManager.updateNotifications();
+            mEntryManager.updateNotifications("NotificationMediaManager - metaDataChanged");
         }
 
         dispatchUpdateMediaMetaData(metaDataChanged, true /* allowEnterAnimation */);
@@ -461,7 +458,7 @@
 
         boolean wakeAndUnlock = mBiometricUnlockController != null
             && mBiometricUnlockController.isWakeAndUnlock();
-        if (mKeyguardMonitor.isLaunchTransitionFadingAway() || wakeAndUnlock) {
+        if (mKeyguardStateController.isLaunchTransitionFadingAway() || wakeAndUnlock) {
             mBackdrop.setVisibility(View.INVISIBLE);
             Trace.endSection();
             return;
@@ -599,7 +596,7 @@
                 boolean cannotAnimateDoze = shadeController != null
                         && shadeController.isDozing()
                         && !ScrimState.AOD.getAnimateChange();
-                boolean needsBypassFading = mKeyguardMonitor.isBypassFadingAnimation();
+                boolean needsBypassFading = mKeyguardStateController.isBypassFadingAnimation();
                 if (((mBiometricUnlockController != null && mBiometricUnlockController.getMode()
                         == BiometricUnlockController.MODE_WAKE_AND_UNLOCK_PULSING
                                 || cannotAnimateDoze) && !needsBypassFading)
@@ -626,10 +623,12 @@
                                 mBackdropBack.setImageDrawable(null);
                                 mHandler.post(mHideBackdropFront);
                             });
-                    if (mKeyguardMonitor.isKeyguardFadingAway()) {
+                    if (mKeyguardStateController.isKeyguardFadingAway()) {
                         mBackdrop.animate()
-                                .setDuration(mKeyguardMonitor.getShortenedFadingAwayDuration())
-                                .setStartDelay(mKeyguardMonitor.getKeyguardFadingAwayDelay())
+                                .setDuration(
+                                        mKeyguardStateController.getShortenedFadingAwayDuration())
+                                .setStartDelay(
+                                        mKeyguardStateController.getKeyguardFadingAwayDelay())
                                 .setInterpolator(Interpolators.LINEAR)
                                 .start();
                     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/PulseExpansionHandler.kt b/packages/SystemUI/src/com/android/systemui/statusbar/PulseExpansionHandler.kt
index a70dc7c..e516af5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/PulseExpansionHandler.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/PulseExpansionHandler.kt
@@ -27,7 +27,6 @@
 import android.view.MotionEvent
 import android.view.VelocityTracker
 import android.view.ViewConfiguration
-import com.android.systemui.Dependency
 
 import com.android.systemui.Gefingerpoken
 import com.android.systemui.Interpolators
@@ -58,7 +57,8 @@
     private val bypassController: KeyguardBypassController,
     private val headsUpManager: HeadsUpManagerPhone,
     private val roundnessManager: NotificationRoundnessManager,
-    private val statusBarStateController: StatusBarStateController
+    private val statusBarStateController: StatusBarStateController,
+    private val falsingManager: FalsingManager
 ) : Gefingerpoken {
     companion object {
         private val RUBBERBAND_FACTOR_STATIC = 0.25f
@@ -99,7 +99,6 @@
     private val mTemp2 = IntArray(2)
     private var mDraggedFarEnough: Boolean = false
     private var mStartingChild: ExpandableView? = null
-    private val mFalsingManager: FalsingManager
     private var mPulsing: Boolean = false
     var isWakingToShadeLocked: Boolean = false
         private set
@@ -109,7 +108,7 @@
     private var velocityTracker: VelocityTracker? = null
 
     private val isFalseTouch: Boolean
-        get() = mFalsingManager.isFalseTouch
+        get() = falsingManager.isFalseTouch
     var qsExpanded: Boolean = false
     var pulseExpandAbortListener: Runnable? = null
     var bouncerShowing: Boolean = false
@@ -118,7 +117,6 @@
         mMinDragDistance = context.resources.getDimensionPixelSize(
                 R.dimen.keyguard_drag_down_min_distance)
         mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
-        mFalsingManager = Dependency.get(FalsingManager::class.java)
         mPowerManager = context.getSystemService(PowerManager::class.java)
     }
 
@@ -151,7 +149,7 @@
             MotionEvent.ACTION_MOVE -> {
                 val h = y - mInitialTouchY
                 if (h > mTouchSlop && h > Math.abs(x - mInitialTouchX)) {
-                    mFalsingManager.onStartExpandingFromPulse()
+                    falsingManager.onStartExpandingFromPulse()
                     isExpanding = true
                     captureStartingChild(mInitialTouchX, mInitialTouchY)
                     mInitialTouchY = y
@@ -192,7 +190,7 @@
                 velocityTracker!!.computeCurrentVelocity(1000 /* units */)
                 val canExpand = moveDistance > 0 && velocityTracker!!.getYVelocity() > -1000 &&
                         statusBarStateController.state != StatusBarState.SHADE
-                if (!mFalsingManager.isUnlockingDisabled && !isFalseTouch && canExpand) {
+                if (!falsingManager.isUnlockingDisabled && !isFalseTouch && canExpand) {
                     finishExpansion()
                 } else {
                     cancelExpansion()
@@ -297,7 +295,7 @@
 
     private fun cancelExpansion() {
         isExpanding = false
-        mFalsingManager.onExpansionFromPulseStopped()
+        falsingManager.onExpansionFromPulseStopped()
         if (mStartingChild != null) {
             reset(mStartingChild!!)
             mStartingChild = null
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java
index 13c6f27..9b31234 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java
@@ -38,7 +38,7 @@
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
 import com.android.systemui.statusbar.phone.CollapsedStatusBarFragment;
 import com.android.systemui.statusbar.phone.NotificationPanelView;
-import com.android.systemui.statusbar.phone.StatusBarWindowView;
+import com.android.systemui.statusbar.phone.StatusBarWindowViewController;
 
 /**
  * A class that allows activities to be launched in a seamless way where the notification
@@ -55,8 +55,8 @@
     private static final long LAUNCH_TIMEOUT = 500;
     private final NotificationPanelView mNotificationPanel;
     private final NotificationListContainer mNotificationContainer;
-    private final StatusBarWindowView mStatusBarWindow;
     private final float mWindowCornerRadius;
+    private final StatusBarWindowViewController mStatusBarWindowViewController;
     private Callback mCallback;
     private final Runnable mTimeoutRunnable = () -> {
         setAnimationPending(false);
@@ -66,16 +66,17 @@
     private boolean mAnimationRunning;
     private boolean mIsLaunchForActivity;
 
-    public ActivityLaunchAnimator(StatusBarWindowView statusBarWindow,
+    public ActivityLaunchAnimator(
+            StatusBarWindowViewController statusBarWindowViewController,
             Callback callback,
             NotificationPanelView notificationPanel,
             NotificationListContainer container) {
         mNotificationPanel = notificationPanel;
         mNotificationContainer = container;
-        mStatusBarWindow = statusBarWindow;
+        mStatusBarWindowViewController = statusBarWindowViewController;
         mCallback = callback;
         mWindowCornerRadius = ScreenDecorationsUtils
-                .getWindowCornerRadius(statusBarWindow.getResources());
+                .getWindowCornerRadius(mStatusBarWindowViewController.getView().getResources());
     }
 
     public RemoteAnimationAdapter getLaunchAnimation(
@@ -112,11 +113,11 @@
 
     private void setAnimationPending(boolean pending) {
         mAnimationPending = pending;
-        mStatusBarWindow.setExpandAnimationPending(pending);
+        mStatusBarWindowViewController.setExpandAnimationPending(pending);
         if (pending) {
-            mStatusBarWindow.postDelayed(mTimeoutRunnable, LAUNCH_TIMEOUT);
+            mStatusBarWindowViewController.getView().postDelayed(mTimeoutRunnable, LAUNCH_TIMEOUT);
         } else {
-            mStatusBarWindow.removeCallbacks(mTimeoutRunnable);
+            mStatusBarWindowViewController.getView().removeCallbacks(mTimeoutRunnable);
         }
     }
 
@@ -246,7 +247,7 @@
         private void setExpandAnimationRunning(boolean running) {
             mNotificationPanel.setLaunchingNotification(running);
             mSourceNotification.setExpandAnimationRunning(running);
-            mStatusBarWindow.setExpandAnimationRunning(running);
+            mStatusBarWindowViewController.setExpandAnimationRunning(running);
             mNotificationContainer.setExpandingNotification(running ? mSourceNotification : null);
             mAnimationRunning = running;
             if (!running) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java
index e4bd4fa..a0b144b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/DynamicPrivacyController.java
@@ -16,16 +16,13 @@
 
 package com.android.systemui.statusbar.notification;
 
-import android.content.Context;
 import android.util.ArraySet;
 
-import com.android.internal.annotations.VisibleForTesting;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.NotificationLockscreenUserManager;
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import javax.inject.Inject;
 import javax.inject.Singleton;
@@ -34,12 +31,11 @@
  * A controller which dynamically controls the visibility of Notification content
  */
 @Singleton
-public class DynamicPrivacyController implements UnlockMethodCache.OnUnlockMethodChangedListener {
+public class DynamicPrivacyController implements KeyguardStateController.Callback {
 
-    private final UnlockMethodCache mUnlockMethodCache;
+    private final KeyguardStateController mKeyguardStateController;
     private final NotificationLockscreenUserManager mLockscreenUserManager;
     private final StatusBarStateController mStateController;
-    private final KeyguardMonitor mKeyguardMonitor;
     private ArraySet<Listener> mListeners = new ArraySet<>();
 
     private boolean mLastDynamicUnlocked;
@@ -47,30 +43,18 @@
     private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
 
     @Inject
-    DynamicPrivacyController(Context context,
-            KeyguardMonitor keyguardMonitor,
-            NotificationLockscreenUserManager notificationLockscreenUserManager,
-            StatusBarStateController stateController) {
-        this(notificationLockscreenUserManager, keyguardMonitor,
-                UnlockMethodCache.getInstance(context),
-                stateController);
-    }
-
-    @VisibleForTesting
     DynamicPrivacyController(NotificationLockscreenUserManager notificationLockscreenUserManager,
-            KeyguardMonitor keyguardMonitor,
-            UnlockMethodCache unlockMethodCache,
+            KeyguardStateController keyguardStateController,
             StatusBarStateController stateController) {
         mLockscreenUserManager = notificationLockscreenUserManager;
         mStateController = stateController;
-        mUnlockMethodCache = unlockMethodCache;
-        mKeyguardMonitor = keyguardMonitor;
-        mUnlockMethodCache.addListener(this);
+        mKeyguardStateController = keyguardStateController;
+        mKeyguardStateController.addCallback(this);
         mLastDynamicUnlocked = isDynamicallyUnlocked();
     }
 
     @Override
-    public void onUnlockMethodStateChanged() {
+    public void onUnlockedChanged() {
         if (isDynamicPrivacyEnabled()) {
             // We only want to notify our listeners if dynamic privacy is actually active
             boolean dynamicallyUnlocked = isDynamicallyUnlocked();
@@ -92,8 +76,9 @@
     }
 
     public boolean isDynamicallyUnlocked() {
-        return (mUnlockMethodCache.canSkipBouncer() || mKeyguardMonitor.isKeyguardGoingAway()
-                || mKeyguardMonitor.isKeyguardFadingAway())
+        return (mKeyguardStateController.canDismissLockScreen()
+                || mKeyguardStateController.isKeyguardGoingAway()
+                || mKeyguardStateController.isKeyguardFadingAway())
                 && isDynamicPrivacyEnabled();
     }
 
@@ -107,7 +92,7 @@
      */
     public boolean isInLockedDownShade() {
         if (!mStatusBarKeyguardViewManager.isShowing()
-                || !mUnlockMethodCache.isMethodSecure()) {
+                || !mKeyguardStateController.isMethodSecure()) {
             return false;
         }
         int state = mStateController.getState();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java
index f3201ec..a5b7fa7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/InstantAppNotifier.java
@@ -55,7 +55,7 @@
 import com.android.systemui.SystemUI;
 import com.android.systemui.UiOffloadThread;
 import com.android.systemui.statusbar.CommandQueue;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.util.NotificationChannels;
 
 import java.util.List;
@@ -64,7 +64,7 @@
  * splitted screen.
  */
 public class InstantAppNotifier extends SystemUI
-        implements CommandQueue.Callbacks, KeyguardMonitor.Callback {
+        implements CommandQueue.Callbacks, KeyguardStateController.Callback {
     private static final String TAG = "InstantAppNotifier";
     public static final int NUM_TASKS_FOR_INSTANT_APP_INFO = 5;
 
@@ -72,13 +72,13 @@
     private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class);
     private final ArraySet<Pair<String, Integer>> mCurrentNotifs = new ArraySet<>();
     private boolean mDockedStackExists;
-    private KeyguardMonitor mKeyguardMonitor;
+    private KeyguardStateController mKeyguardStateController;
 
     public InstantAppNotifier() {}
 
     @Override
     public void start() {
-        mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
 
         // listen for user / profile change.
         try {
@@ -88,7 +88,7 @@
         }
 
         SysUiServiceProvider.getComponent(mContext, CommandQueue.class).addCallback(this);
-        mKeyguardMonitor.addCallback(this);
+        mKeyguardStateController.addCallback(this);
 
         DockedStackExistsListener.register(
                 exists -> {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotifPipelineInitializer.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotifPipelineInitializer.java
new file mode 100644
index 0000000..df70828
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotifPipelineInitializer.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2019 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.statusbar.notification;
+
+import android.service.notification.NotificationListenerService;
+import android.service.notification.StatusBarNotification;
+import android.util.Log;
+
+import com.android.systemui.statusbar.NotificationListener;
+
+import javax.inject.Inject;
+
+/**
+ * Initialization code for the new notification pipeline.
+ */
+public class NotifPipelineInitializer {
+
+    @Inject
+    public NotifPipelineInitializer() {
+    }
+
+    public void initialize(
+            NotificationListener notificationService) {
+
+        // TODO Put real code here
+        notificationService.setDownstreamListener(new NotificationListener.NotifServiceListener() {
+            @Override
+            public void onNotificationPosted(StatusBarNotification sbn,
+                    NotificationListenerService.RankingMap rankingMap) {
+                Log.d(TAG, "onNotificationPosted " + sbn.getKey());
+            }
+
+            @Override
+            public void onNotificationRemoved(StatusBarNotification sbn,
+                    NotificationListenerService.RankingMap rankingMap) {
+                Log.d(TAG, "onNotificationRemoved " + sbn.getKey());
+            }
+
+            @Override
+            public void onNotificationRemoved(StatusBarNotification sbn,
+                    NotificationListenerService.RankingMap rankingMap, int reason) {
+                Log.d(TAG, "onNotificationRemoved " + sbn.getKey());
+            }
+
+            @Override
+            public void onNotificationRankingUpdate(
+                    NotificationListenerService.RankingMap rankingMap) {
+                Log.d(TAG, "onNotificationRankingUpdate");
+            }
+        });
+    }
+
+    private static final String TAG = "NotifInitializer";
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
index b6b149d..01c79b3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
@@ -20,8 +20,8 @@
 
 import android.annotation.Nullable;
 import android.app.Notification;
-import android.content.Context;
 import android.service.notification.NotificationListenerService;
+import android.service.notification.NotificationListenerService.Ranking;
 import android.service.notification.StatusBarNotification;
 import android.util.ArrayMap;
 import android.util.Log;
@@ -40,6 +40,8 @@
 import com.android.systemui.statusbar.notification.collection.NotificationData.KeyguardEnvironment;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.collection.NotificationRowBinder;
+import com.android.systemui.statusbar.notification.logging.NotifEvent;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater.InflationFlag;
@@ -92,6 +94,7 @@
     private NotificationListenerService.RankingMap mLatestRankingMap;
     @VisibleForTesting
     protected NotificationData mNotificationData;
+    private NotifLog mNotifLog;
 
     @VisibleForTesting
     final ArrayList<NotificationLifetimeExtender> mNotificationLifetimeExtenders
@@ -123,8 +126,9 @@
     }
 
     @Inject
-    public NotificationEntryManager(Context context) {
-        mNotificationData = new NotificationData(context);
+    public NotificationEntryManager(NotificationData notificationData, NotifLog notifLog) {
+        mNotificationData = notificationData;
+        mNotifLog = notifLog;
     }
 
     /** Adds a {@link NotificationEntryListener}. */
@@ -178,7 +182,7 @@
 
     @Override
     public void onReorderingAllowed() {
-        updateNotifications();
+        updateNotifications("reordering is now allowed");
     }
 
     /**
@@ -203,15 +207,19 @@
         return NotificationVisibility.obtain(key, rank, count, true, location);
     }
 
-    private void abortExistingInflation(String key) {
+    private void abortExistingInflation(String key, String reason) {
         if (mPendingNotifications.containsKey(key)) {
             NotificationEntry entry = mPendingNotifications.get(key);
             entry.abortTask();
             mPendingNotifications.remove(key);
+            mNotifLog.log(NotifEvent.INFLATION_ABORTED, entry.sbn(), null,
+                    "PendingNotification aborted. " + reason);
         }
         NotificationEntry addedEntry = mNotificationData.get(key);
         if (addedEntry != null) {
             addedEntry.abortTask();
+            mNotifLog.log(NotifEvent.INFLATION_ABORTED, addedEntry.sbn(),
+                    null, reason);
         }
     }
 
@@ -247,7 +255,7 @@
                 for (NotificationEntryListener listener : mNotificationEntryListeners) {
                     listener.onBeforeNotificationAdded(entry);
                 }
-                updateNotifications();
+                updateNotifications("onAsyncInflationFinished");
                 for (NotificationEntryListener listener : mNotificationEntryListeners) {
                     listener.onNotificationAdded(entry);
                 }
@@ -276,7 +284,8 @@
 
         if (mRemoveInterceptor != null
                 && mRemoveInterceptor.onNotificationRemoveRequested(key, reason)) {
-            // Remove intercepted; skip
+            // Remove intercepted; log and skip
+            mNotifLog.log(NotifEvent.REMOVE_INTERCEPTED);
             return;
         }
 
@@ -291,13 +300,17 @@
                     if (extender.shouldExtendLifetimeForPendingNotification(pendingEntry)) {
                         extendLifetime(pendingEntry, extender);
                         lifetimeExtended = true;
+                        mNotifLog.log(
+                                NotifEvent.LIFETIME_EXTENDED,
+                                pendingEntry.sbn(),
+                                "pendingEntry extendedBy=" + extender.toString());
                     }
                 }
             }
         }
 
         if (!lifetimeExtended) {
-            abortExistingInflation(key);
+            abortExistingInflation(key, "removeNotification");
         }
 
         if (entry != null) {
@@ -310,6 +323,10 @@
                         mLatestRankingMap = ranking;
                         extendLifetime(entry, extender);
                         lifetimeExtended = true;
+                        mNotifLog.log(
+                                NotifEvent.LIFETIME_EXTENDED,
+                                entry.sbn(),
+                                "entry extendedBy=" + extender.toString());
                         break;
                     }
                 }
@@ -329,10 +346,12 @@
                 handleGroupSummaryRemoved(key);
 
                 mNotificationData.remove(key, ranking);
-                updateNotifications();
+                updateNotifications("removeNotificationInternal");
                 Dependency.get(LeakDetector.class).trackGarbage(entry);
                 removedByUser |= entryDismissed;
 
+                mNotifLog.log(NotifEvent.NOTIF_REMOVED, entry.sbn(),
+                        "removedByUser=" + removedByUser);
                 for (NotificationEntryListener listener : mNotificationEntryListeners) {
                     listener.onEntryRemoved(entry, visibility, removedByUser);
                 }
@@ -389,8 +408,8 @@
             Log.d(TAG, "addNotification key=" + key);
         }
 
-        mNotificationData.updateRanking(rankingMap);
-        NotificationListenerService.Ranking ranking = new NotificationListenerService.Ranking();
+        mNotificationData.updateRanking(rankingMap, "addNotificationInternal");
+        Ranking ranking = new Ranking();
         rankingMap.getRanking(key, ranking);
 
         NotificationEntry entry = new NotificationEntry(notification, ranking);
@@ -400,9 +419,9 @@
         requireBinder().inflateViews(entry, () -> performRemoveNotification(notification,
                 REASON_CANCEL));
 
-        abortExistingInflation(key);
-
+        abortExistingInflation(key, "addNotification");
         mPendingNotifications.put(key, entry);
+        mNotifLog.log(NotifEvent.NOTIF_ADDED, entry.sbn());
         for (NotificationEntryListener listener : mNotificationEntryListeners) {
             listener.onPendingEntryAdded(entry);
         }
@@ -423,7 +442,7 @@
         if (DEBUG) Log.d(TAG, "updateNotification(" + notification + ")");
 
         final String key = notification.getKey();
-        abortExistingInflation(key);
+        abortExistingInflation(key, "updateNotification");
         NotificationEntry entry = mNotificationData.get(key);
         if (entry == null) {
             return;
@@ -433,15 +452,15 @@
         // to keep its lifetime extended.
         cancelLifetimeExtension(entry);
 
-        mNotificationData.update(entry, ranking, notification);
-
+        mNotificationData.update(entry, ranking, notification, "updateNotificationInternal");
+        mNotifLog.log(NotifEvent.NOTIF_UPDATED, entry.sbn(), entry.ranking());
         for (NotificationEntryListener listener : mNotificationEntryListeners) {
             listener.onPreEntryUpdated(entry);
         }
 
         requireBinder().inflateViews(entry, () -> performRemoveNotification(notification,
                 REASON_CANCEL));
-        updateNotifications();
+        updateNotifications("updateNotificationInternal");
 
         if (DEBUG) {
             // Is this for you?
@@ -465,8 +484,12 @@
         }
     }
 
-    public void updateNotifications() {
-        mNotificationData.filterAndSort();
+    /**
+     * Update the notifications
+     * @param reason why the notifications are updating
+     */
+    public void updateNotifications(String reason) {
+        mNotificationData.filterAndSort(reason);
         if (mPresenter != null) {
             mPresenter.updateNotificationViews();
         }
@@ -489,7 +512,7 @@
         }
 
         // Populate notification entries from the new rankings.
-        mNotificationData.updateRanking(rankingMap);
+        mNotificationData.updateRanking(rankingMap, "updateNotificationRanking");
         updateRankingOfPendingNotifications(rankingMap);
 
         // By comparing the old and new UI adjustments, reinflate the view accordingly.
@@ -501,7 +524,7 @@
                     NotificationUiAdjustment.extractFromNotificationEntry(entry));
         }
 
-        updateNotifications();
+        updateNotifications("updateNotificationRanking");
 
         for (NotificationEntryListener listener : mNotificationEntryListeners) {
             listener.onNotificationRankingUpdated(rankingMap);
@@ -513,10 +536,11 @@
         if (rankingMap == null) {
             return;
         }
-        NotificationListenerService.Ranking ranking = new NotificationListenerService.Ranking();
         for (NotificationEntry pendingNotification : mPendingNotifications.values()) {
-            rankingMap.getRanking(pendingNotification.key, ranking);
-            pendingNotification.setRanking(ranking);
+            Ranking ranking = new Ranking();
+            if (rankingMap.getRanking(pendingNotification.key(), ranking)) {
+                pendingNotification.setRanking(ranking);
+            }
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationInterruptionStateProvider.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationInterruptionStateProvider.java
index 9362d2d..eadec6a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationInterruptionStateProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationInterruptionStateProvider.java
@@ -39,6 +39,7 @@
 import com.android.systemui.statusbar.NotificationPresenter;
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.HeadsUpManager;
 
 import javax.inject.Inject;
@@ -63,6 +64,7 @@
     private final Context mContext;
     private final PowerManager mPowerManager;
     private final IDreamManager mDreamManager;
+    private final BatteryController mBatteryController;
 
     private NotificationPresenter mPresenter;
     private HeadsUpManager mHeadsUpManager;
@@ -75,13 +77,14 @@
 
     @Inject
     public NotificationInterruptionStateProvider(Context context, NotificationFilter filter,
-            StatusBarStateController stateController) {
+            StatusBarStateController stateController, BatteryController batteryController) {
         this(context,
                 (PowerManager) context.getSystemService(Context.POWER_SERVICE),
                 IDreamManager.Stub.asInterface(
                         ServiceManager.checkService(DreamService.DREAM_SERVICE)),
                 new AmbientDisplayConfiguration(context),
                 filter,
+                batteryController,
                 stateController);
     }
 
@@ -92,10 +95,12 @@
             IDreamManager dreamManager,
             AmbientDisplayConfiguration ambientDisplayConfiguration,
             NotificationFilter notificationFilter,
+            BatteryController batteryController,
             StatusBarStateController statusBarStateController) {
         mContext = context;
         mPowerManager = powerManager;
         mDreamManager = dreamManager;
+        mBatteryController = batteryController;
         mAmbientDisplayConfiguration = ambientDisplayConfiguration;
         mNotificationFilter = notificationFilter;
         mStatusBarStateController = statusBarStateController;
@@ -293,6 +298,13 @@
             return false;
         }
 
+        if (mBatteryController.isAodPowerSave()) {
+            if (DEBUG_HEADS_UP) {
+                Log.d(TAG, "No pulsing: disabled by battery saver: " + sbn.getKey());
+            }
+            return false;
+        }
+
         if (!canAlertCommon(entry)) {
             if (DEBUG_HEADS_UP) {
                 Log.d(TAG, "No pulsing: notification shouldn't alert: " + sbn.getKey());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java
index 769cbb7..970cbf9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationListController.java
@@ -81,7 +81,7 @@
             new DeviceProvisionedListener() {
                 @Override
                 public void onDeviceProvisionedChanged() {
-                    mEntryManager.updateNotifications();
+                    mEntryManager.updateNotifications("device provisioned changed");
                 }
             };
 
@@ -106,7 +106,7 @@
         if (foregroundKey != null) {
             mEntryManager
                     .getNotificationData().updateAppOp(appOp, uid, pkg, foregroundKey, showIcon);
-            mEntryManager.updateNotifications();
+            mEntryManager.updateNotifications("app opp changed pkg=" + pkg);
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationSectionsFeatureManager.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationSectionsFeatureManager.kt
new file mode 100644
index 0000000..480cb78
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationSectionsFeatureManager.kt
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2019 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.statusbar.notification
+
+import android.content.Context
+import android.provider.DeviceConfig
+
+import com.android.internal.annotations.VisibleForTesting
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags.NOTIFICATIONS_USE_PEOPLE_FILTERING
+import com.android.systemui.statusbar.notification.stack.NotificationSectionsManager.BUCKET_ALERTING
+import com.android.systemui.statusbar.notification.stack.NotificationSectionsManager.BUCKET_PEOPLE
+import com.android.systemui.statusbar.notification.stack.NotificationSectionsManager.BUCKET_SILENT
+import com.android.systemui.util.DeviceConfigProxy
+
+import javax.inject.Inject
+
+private var sUsePeopleFiltering: Boolean? = null
+
+/**
+ * Feature controller for the NOTIFICATIONS_USE_PEOPLE_FILTERING config.
+ */
+class NotificationSectionsFeatureManager @Inject constructor(
+    val proxy: DeviceConfigProxy,
+    val context: Context
+) {
+
+    fun isFilteringEnabled(): Boolean {
+        return usePeopleFiltering(proxy)
+    }
+
+    fun getNotificationBuckets(): IntArray {
+        return when {
+            isFilteringEnabled() ->
+                intArrayOf(BUCKET_PEOPLE, BUCKET_ALERTING, BUCKET_SILENT)
+            NotificationUtils.useNewInterruptionModel(context) ->
+                intArrayOf(BUCKET_ALERTING, BUCKET_SILENT)
+            else ->
+                intArrayOf(BUCKET_ALERTING)
+        }
+    }
+
+    fun getNumberOfBuckets(): Int {
+        return getNotificationBuckets().size
+    }
+
+    @VisibleForTesting
+    fun clearCache() {
+        sUsePeopleFiltering = null
+    }
+}
+
+private fun usePeopleFiltering(proxy: DeviceConfigProxy): Boolean {
+    if (sUsePeopleFiltering == null) {
+        sUsePeopleFiltering = proxy.getBoolean(
+                DeviceConfig.NAMESPACE_SYSTEMUI, NOTIFICATIONS_USE_PEOPLE_FILTERING, false)
+    }
+
+    return sUsePeopleFiltering!!
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java
index dfbbf98..1af47dd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationUtils.java
@@ -36,7 +36,6 @@
     private static final int[] sLocationOffset = new int[2];
 
     @Nullable private static Boolean sUseNewInterruptionModel = null;
-    @Nullable private static Boolean sUsePeopleFiltering = null;
 
     public static boolean isGrayscale(ImageView v, ContrastColorUtil colorUtil) {
         Object isGrayscale = v.getTag(R.id.icon_is_grayscale);
@@ -88,17 +87,4 @@
         }
         return sUseNewInterruptionModel;
     }
-
-    /**
-     * Caches and returns the value of the people filtering setting. Cannot change except through
-     * process restarts.
-     */
-    public static boolean usePeopleFiltering(Context context) {
-        if (sUsePeopleFiltering == null) {
-            sUsePeopleFiltering = context.getResources().getBoolean(
-                    R.bool.config_usePeopleFiltering);
-        }
-
-        return sUsePeopleFiltering;
-    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationData.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationData.java
index aacb2dd..a98fa66 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationData.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationData.java
@@ -24,7 +24,6 @@
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.app.Person;
-import android.content.Context;
 import android.service.notification.NotificationListenerService.Ranking;
 import android.service.notification.NotificationListenerService.RankingMap;
 import android.service.notification.SnoozeCriterion;
@@ -35,7 +34,9 @@
 import com.android.systemui.Dependency;
 import com.android.systemui.statusbar.NotificationMediaManager;
 import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationUtils;
+import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
+import com.android.systemui.statusbar.notification.logging.NotifEvent;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.phone.NotificationGroupManager;
 import com.android.systemui.statusbar.policy.HeadsUpManager;
 
@@ -46,6 +47,8 @@
 import java.util.List;
 import java.util.Objects;
 
+import javax.inject.Inject;
+
 /**
  * The list of currently displaying notifications.
  */
@@ -72,9 +75,13 @@
     private RankingMap mRankingMap;
     private final Ranking mTmpRanking = new Ranking();
     private final boolean mUsePeopleFiltering;
+    private final NotifLog mNotifLog;
 
-    public NotificationData(Context context) {
-        mUsePeopleFiltering = NotificationUtils.usePeopleFiltering(context);
+    @Inject
+    public NotificationData(NotificationSectionsFeatureManager sectionsFeatureManager,
+            NotifLog notifLog) {
+        mUsePeopleFiltering = sectionsFeatureManager.isFilteringEnabled();
+        mNotifLog = notifLog;
     }
 
     public void setHeadsUpManager(HeadsUpManager headsUpManager) {
@@ -177,7 +184,7 @@
         }
         mGroupManager.onEntryAdded(entry);
 
-        updateRankingAndSort(mRankingMap);
+        updateRankingAndSort(mRankingMap, "addEntry=" + entry.sbn());
     }
 
     public NotificationEntry remove(String key, RankingMap ranking) {
@@ -187,7 +194,7 @@
         }
         if (removed == null) return null;
         mGroupManager.onEntryRemoved(removed);
-        updateRankingAndSort(ranking);
+        updateRankingAndSort(ranking, "removeEntry=" + removed.sbn());
         return removed;
     }
 
@@ -195,15 +202,19 @@
     public void update(
             NotificationEntry entry,
             RankingMap ranking,
-            StatusBarNotification notification) {
-        updateRanking(ranking);
+            StatusBarNotification notification,
+            String reason) {
+        updateRanking(ranking, reason);
         final StatusBarNotification oldNotification = entry.notification;
         entry.setNotification(notification);
         mGroupManager.onEntryUpdated(entry, oldNotification);
     }
 
-    public void updateRanking(RankingMap ranking) {
-        updateRankingAndSort(ranking);
+    /**
+     * Update ranking and trigger a re-sort
+     */
+    public void updateRanking(RankingMap ranking, String reason) {
+        updateRankingAndSort(ranking, reason);
     }
 
     public void updateAppOp(int appOp, int uid, String pkg, String key, boolean showIcon) {
@@ -350,7 +361,7 @@
         return false;
     }
 
-    private void updateRankingAndSort(RankingMap rankingMap) {
+    private void updateRankingAndSort(RankingMap rankingMap, String reason) {
         if (rankingMap != null) {
             mRankingMap = rankingMap;
             synchronized (mEntries) {
@@ -373,7 +384,7 @@
                 }
             }
         }
-        filterAndSort();
+        filterAndSort(reason);
     }
 
     /**
@@ -391,7 +402,11 @@
 
     // TODO: This should not be public. Instead the Environment should notify this class when
     // anything changed, and this class should call back the UI so it updates itself.
-    public void filterAndSort() {
+    /**
+     * Filters and sorts the list of notification entries
+     */
+    public void filterAndSort(String reason) {
+        mNotifLog.log(NotifEvent.FILTER_AND_SORT, reason);
         mSortedAndFiltered.clear();
 
         synchronized (mEntries) {
@@ -483,19 +498,6 @@
     }
 
     /**
-     * Get the current set of buckets for notification entries, as defined here
-     */
-    public static int[] getNotificationBuckets(Context context) {
-        if (NotificationUtils.usePeopleFiltering(context)) {
-            return new int[]{BUCKET_PEOPLE, BUCKET_ALERTING, BUCKET_SILENT};
-        } else if (NotificationUtils.useNewInterruptionModel(context)) {
-            return new int[]{BUCKET_ALERTING, BUCKET_SILENT};
-        } else {
-            return new int[]{BUCKET_ALERTING};
-        }
-    }
-
-    /**
      * Provides access to keyguard state and user settings dependent data.
      */
     public interface KeyguardEnvironment {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java
index 60cf995..e5571b6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java
@@ -41,6 +41,8 @@
 import com.android.systemui.statusbar.notification.InflationException;
 import com.android.systemui.statusbar.notification.NotificationClicker;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
+import com.android.systemui.statusbar.notification.logging.NotifEvent;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater;
@@ -72,6 +74,7 @@
     private final boolean mAllowLongPress;
     private final KeyguardBypassController mKeyguardBypassController;
     private final StatusBarStateController mStatusBarStateController;
+    private final NotifLog mNotifLog;
 
     private NotificationRemoteInputManager mRemoteInputManager;
     private NotificationPresenter mPresenter;
@@ -85,12 +88,14 @@
 
     public NotificationRowBinderImpl(Context context, boolean allowLongPress,
             KeyguardBypassController keyguardBypassController,
-            StatusBarStateController statusBarStateController) {
+            StatusBarStateController statusBarStateController,
+            NotifLog notifLog) {
         mContext = context;
         mMessagingUtil = new NotificationMessagingUtil(context);
         mAllowLongPress = allowLongPress;
         mKeyguardBypassController = keyguardBypassController;
         mStatusBarStateController = statusBarStateController;
+        mNotifLog = notifLog;
     }
 
     private NotificationRemoteInputManager getRemoteInputManager() {
@@ -143,6 +148,7 @@
                     row -> {
                         bindRow(entry, pmUser, sbn, row, onDismissRunnable);
                         updateNotification(entry, pmUser, sbn, row);
+                        mNotifLog.log(NotifEvent.INFLATED, sbn);
                     });
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java
new file mode 100644
index 0000000..7703cbd
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifEvent.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2019 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.statusbar.notification.logging;
+
+import android.annotation.IntDef;
+import android.service.notification.NotificationListenerService.Ranking;
+import android.service.notification.StatusBarNotification;
+
+import com.android.systemui.log.RichEvent;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * An event related to notifications. {@link NotifLog} stores and prints these events for debugging
+ * and triaging purposes.
+ */
+public class NotifEvent extends RichEvent {
+    public static final int TOTAL_EVENT_TYPES = 11;
+    private final StatusBarNotification mSbn;
+    private final Ranking mRanking;
+
+    /**
+     * Creates a NotifEvent with an event type that matches with an index in the array
+     * getSupportedEvents() and {@link EventType}.
+     *
+     * The status bar notification and ranking objects are stored as shallow copies of the current
+     * state of the event when this event occurred.
+     */
+    public NotifEvent(int logLevel, int type, String reason, StatusBarNotification sbn,
+            Ranking ranking) {
+        super(logLevel, type, reason);
+
+        if (sbn != null) {
+            mSbn = sbn.cloneLight();
+        } else {
+            mSbn = null;
+        }
+
+        if (ranking != null) {
+            mRanking = new Ranking();
+            mRanking.populate(ranking);
+        } else {
+            mRanking = null;
+        }
+
+        mMessage += getExtraInfo();
+    }
+
+    private String getExtraInfo() {
+        StringBuilder extraInfo = new StringBuilder();
+
+        if (mSbn != null) {
+            extraInfo.append(" Sbn=");
+            extraInfo.append(mSbn);
+        }
+
+        if (mRanking != null) {
+            extraInfo.append(" Ranking=");
+            extraInfo.append(mRanking);
+        }
+
+        return extraInfo.toString();
+    }
+
+    /**
+     * Event labels for NotifEvents
+     * Index corresponds to the {@link EventType}
+     */
+    @Override
+    public String[] getEventLabels() {
+        final String[] events = new String[]{
+                "NotifAdded",
+                "NotifRemoved",
+                "NotifUpdated",
+                "Filter",
+                "Sort",
+                "FilterAndSort",
+                "NotifVisibilityChanged",
+                "LifetimeExtended",
+                "RemoveIntercepted",
+                "InflationAborted",
+                "Inflated"
+        };
+
+        if (events.length != TOTAL_EVENT_TYPES) {
+            throw new IllegalStateException("NotifEvents events.length should match "
+                    + TOTAL_EVENT_TYPES
+                    + " events.length=" + events.length
+                    + " TOTAL_EVENT_LENGTH=" + TOTAL_EVENT_TYPES);
+        }
+        return events;
+    }
+
+    /**
+     * @return a copy of the status bar notification that changed with this event
+     */
+    public StatusBarNotification getSbn() {
+        return mSbn;
+    }
+
+    /**
+     * Builds a NotifEvent.
+     */
+    public static class NotifEventBuilder extends RichEvent.Builder<NotifEventBuilder> {
+        private StatusBarNotification mSbn;
+        private Ranking mRanking;
+
+        @Override
+        public NotifEventBuilder getBuilder() {
+            return this;
+        }
+
+        /**
+         * Stores the status bar notification object. A shallow copy is stored in the NotifEvent's
+         * constructor.
+         */
+        public NotifEventBuilder setSbn(StatusBarNotification sbn) {
+            mSbn = sbn;
+            return this;
+        }
+
+        /**
+         * Stores the ranking object. A shallow copy is stored in the NotifEvent's
+         * constructor.
+         */
+        public NotifEventBuilder setRanking(Ranking ranking) {
+            mRanking = ranking;
+            return this;
+        }
+
+        @Override
+        public RichEvent build() {
+            return new NotifEvent(mLogLevel, mType, mReason, mSbn, mRanking);
+        }
+    }
+
+    @IntDef({NOTIF_ADDED,
+            NOTIF_REMOVED,
+            NOTIF_UPDATED,
+            FILTER,
+            SORT,
+            FILTER_AND_SORT,
+            NOTIF_VISIBILITY_CHANGED,
+            LIFETIME_EXTENDED,
+            REMOVE_INTERCEPTED,
+            INFLATION_ABORTED,
+            INFLATED
+    })
+
+    /**
+     * Types of NotifEvents
+     */
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface EventType {}
+    public static final int NOTIF_ADDED = 0;
+    public static final int NOTIF_REMOVED = 1;
+    public static final int NOTIF_UPDATED = 2;
+    public static final int FILTER = 3;
+    public static final int SORT = 4;
+    public static final int FILTER_AND_SORT = 5;
+    public static final int NOTIF_VISIBILITY_CHANGED = 6;
+    public static final int LIFETIME_EXTENDED = 7;
+    // unable to remove notif - removal intercepted by {@link NotificationRemoveInterceptor}
+    public static final int REMOVE_INTERCEPTED = 8;
+    public static final int INFLATION_ABORTED = 9;
+    public static final int INFLATED = 10;
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java
new file mode 100644
index 0000000..8466d2e8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotifLog.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2019 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.statusbar.notification.logging;
+
+import android.service.notification.NotificationListenerService.Ranking;
+import android.service.notification.StatusBarNotification;
+
+import com.android.systemui.DumpController;
+import com.android.systemui.log.SysuiLog;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+/**
+ * Logs systemui notification events for debugging and triaging purposes. Logs are dumped in
+ * bugreports or on demand:
+ *      adb shell dumpsys activity service com.android.systemui/.SystemUIService \
+ *      dependency DumpController NotifLog
+ */
+@Singleton
+public class NotifLog extends SysuiLog {
+    private static final String TAG = "NotifLog";
+    private static final int MAX_DOZE_DEBUG_LOGS = 400;
+    private static final int MAX_DOZE_LOGS = 50;
+
+    @Inject
+    public NotifLog(DumpController dumpController) {
+        super(dumpController, TAG, MAX_DOZE_DEBUG_LOGS, MAX_DOZE_LOGS);
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a notification, ranking and message
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn,
+            Ranking ranking, String msg) {
+        return log(new NotifEvent.NotifEventBuilder()
+                .setType(eventType)
+                .setSbn(sbn)
+                .setRanking(ranking)
+                .setReason(msg)
+                .build());
+    }
+
+    /**
+     * Logs a {@link NotifEvent}
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType) {
+        return log(eventType, null, null, null);
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a message
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, String msg) {
+        return log(eventType, null, null, msg);
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a notification
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn) {
+        return log(eventType, sbn, null, "");
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a notification
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn, String msg) {
+        return log(eventType, sbn, null, msg);
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a ranking
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, Ranking ranking) {
+        return log(eventType, null, ranking, "");
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a notification and ranking
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, StatusBarNotification sbn,
+            Ranking ranking) {
+        return log(eventType, sbn, ranking, "");
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a notification entry
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, NotificationEntry entry) {
+        return log(eventType, entry.sbn(), entry.ranking(), "");
+    }
+
+    /**
+     * Logs a {@link NotifEvent} with a notification entry
+     * @return true if successfully logged, else false
+     */
+    public boolean log(@NotifEvent.EventType int eventType, NotificationEntry entry,
+            String msg) {
+        return log(eventType, entry.sbn(), entry.ranking(), msg);
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java
index 8d73251..a817f54 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java
@@ -180,6 +180,10 @@
         initDimens();
     }
 
+    public FalsingManager getFalsingManager() {
+        return mFalsingManager;
+    }
+
     private void updateColors() {
         mNormalColor = mContext.getColor(R.color.notification_material_background_color);
         mTintedRippleColor = mContext.getColor(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index 0f6ce21..924a347 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -74,7 +74,6 @@
 import com.android.systemui.Dependency;
 import com.android.systemui.Interpolators;
 import com.android.systemui.R;
-import com.android.systemui.plugins.FalsingManager;
 import com.android.systemui.plugins.PluginListener;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin.MenuItem;
@@ -221,7 +220,6 @@
     private ViewStub mGutsStub;
     private boolean mIsSystemChildExpanded;
     private boolean mIsPinned;
-    private FalsingManager mFalsingManager;
     private boolean mExpandAnimationRunning;
     private AboveShelfChangedListener mAboveShelfChangedListener;
     private HeadsUpManager mHeadsUpManager;
@@ -1449,6 +1447,7 @@
         }
         setDismissed(fromAccessibility);
         if (mEntry.isClearable()) {
+            // TODO: beverlyt, log dismissal
             // TODO: track dismiss sentiment
             if (mOnDismissRunnable != null) {
                 mOnDismissRunnable.run();
@@ -1636,7 +1635,6 @@
 
     public ExpandableNotificationRow(Context context, AttributeSet attrs) {
         super(context, attrs);
-        mFalsingManager = Dependency.get(FalsingManager.class);  // TODO: inject into a controller.
         mNotificationInflater = new NotificationContentInflater(this);
         mMenuRow = new NotificationMenuRow(mContext);
         mImageResolver = new NotificationInlineImageResolver(context,
@@ -2208,7 +2206,7 @@
      * @param allowChildExpansion whether a call to this method allows expanding children
      */
     public void setUserExpanded(boolean userExpanded, boolean allowChildExpansion) {
-        mFalsingManager.setNotificationExpanded();
+        getFalsingManager().setNotificationExpanded();
         if (mIsSummaryWithChildren && !shouldShowPublic() && allowChildExpansion
                 && !mChildrenContainer.showingAsLowPriority()) {
             final boolean wasExpanded = mGroupManager.isGroupExpanded(mStatusBarNotification);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManager.java
index 73093c6..37f63c9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManager.java
@@ -139,7 +139,8 @@
 
             mBlockingHelperRow.setBlockingHelperShowing(false);
             if (mBlockingHelperRow.isAttachedToWindow()) {
-                Dependency.get(NotificationEntryManager.class).updateNotifications();
+                Dependency.get(NotificationEntryManager.class).updateNotifications(
+                        "dismissCurrentBlockingHelper");
             }
             mBlockingHelperRow = null;
             return true;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGuts.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGuts.java
index 4700baa..18d436f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGuts.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGuts.java
@@ -421,7 +421,7 @@
     }
 
     /** Listener for animations executed in {@link #animateClose(int, int, boolean)}. */
-    private static class AnimateCloseListener extends AnimatorListenerAdapter {
+    private class AnimateCloseListener extends AnimatorListenerAdapter {
         final View mView;
         private final GutsContent mGutsContent;
 
@@ -433,8 +433,10 @@
         @Override
         public void onAnimationEnd(Animator animation) {
             super.onAnimationEnd(animation);
-            mView.setVisibility(View.GONE);
-            mGutsContent.onFinishedClosing();
+            if (!isExposed()) {
+                mView.setVisibility(View.GONE);
+                mGutsContent.onFinishedClosing();
+            }
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
index 9d0dd6b..2b7deec 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
@@ -100,6 +100,7 @@
     protected String mKeyToRemoveOnGutsClosed;
 
     private StatusBar mStatusBar;
+    private Runnable mOpenRunnable;
 
     @Inject
     public NotificationGutsManager(
@@ -343,6 +344,7 @@
     public void closeAndSaveGuts(boolean removeLeavebehinds, boolean force, boolean removeControls,
             int x, int y, boolean resetMenu) {
         if (mNotificationGutsExposed != null) {
+            mNotificationGutsExposed.removeCallbacks(mOpenRunnable);
             mNotificationGutsExposed.closeControls(removeLeavebehinds, removeControls, x, y, force);
         }
         if (resetMenu) {
@@ -445,7 +447,7 @@
         // ensure that it's laid but not visible until actually laid out
         guts.setVisibility(View.INVISIBLE);
         // Post to ensure the the guts are properly laid out.
-        guts.post(new Runnable() {
+        mOpenRunnable = new Runnable() {
             @Override
             public void run() {
                 if (row.getWindowToken() == null) {
@@ -470,7 +472,8 @@
                 mListContainer.onHeightChanged(row, true /* needsAnimation */);
                 mGutsMenuItem = menuItem;
             }
-        });
+        };
+        guts.post(mOpenRunnable);
         return true;
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManager.java
index ec0c634..b4f7b59 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManager.java
@@ -16,10 +16,9 @@
 
 package com.android.systemui.statusbar.notification.stack;
 
-import android.content.Context;
 import android.util.MathUtils;
 
-import com.android.systemui.statusbar.notification.collection.NotificationData;
+import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
@@ -52,8 +51,8 @@
     @Inject
     NotificationRoundnessManager(
             KeyguardBypassController keyguardBypassController,
-            Context context) {
-        int numberOfSections = NotificationData.getNotificationBuckets(context).length;
+            NotificationSectionsFeatureManager sectionsFeatureManager) {
+        int numberOfSections = sectionsFeatureManager.getNumberOfBuckets();
         mFirstInSectionViews = new ActivatableNotificationView[numberOfSections];
         mLastInSectionViews = new ActivatableNotificationView[numberOfSections];
         mTmpFirstInSectionViews = new ActivatableNotificationView[numberOfSections];
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
index a67018e..7bbe818 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
@@ -109,11 +109,11 @@
 import com.android.systemui.statusbar.notification.FakeShadowView;
 import com.android.systemui.statusbar.notification.NotificationEntryListener;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
 import com.android.systemui.statusbar.notification.NotificationUtils;
 import com.android.systemui.statusbar.notification.ShadeViewRefactor;
 import com.android.systemui.statusbar.notification.ShadeViewRefactor.RefactorComponent;
 import com.android.systemui.statusbar.notification.VisualStabilityManager;
-import com.android.systemui.statusbar.notification.collection.NotificationData;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
@@ -517,7 +517,8 @@
             StatusBarStateController statusBarStateController,
             HeadsUpManagerPhone headsUpManager,
             KeyguardBypassController keyguardBypassController,
-            FalsingManager falsingManager) {
+            FalsingManager falsingManager,
+            NotificationSectionsFeatureManager sectionsFeatureManager) {
         super(context, attrs, 0, 0);
         Resources res = getResources();
 
@@ -531,7 +532,7 @@
         mKeyguardBypassController = keyguardBypassController;
         mFalsingManager = falsingManager;
 
-        int[] buckets = NotificationData.getNotificationBuckets(context);
+        int[] buckets = sectionsFeatureManager.getNotificationBuckets();
         mSectionsManager =
                 new NotificationSectionsManager(
                         this,
@@ -5332,7 +5333,7 @@
         requestChildrenUpdate();
         onUpdateRowStates();
 
-        mEntryManager.updateNotifications();
+        mEntryManager.updateNotifications("StatusBar state changed");
         updateVisibility();
     }
 
@@ -6491,12 +6492,12 @@
 
         @Override
         public void onGroupCreatedFromChildren(NotificationGroupManager.NotificationGroup group) {
-            mStatusBar.requestNotificationUpdate();
+            mStatusBar.requestNotificationUpdate("onGroupCreatedFromChildren");
         }
 
         @Override
         public void onGroupsChanged() {
-            mStatusBar.requestNotificationUpdate();
+            mStatusBar.requestNotificationUpdate("onGroupsChanged");
         }
     };
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
index 2d012c9..7cbdfb0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BiometricUnlockController.java
@@ -38,6 +38,7 @@
 import com.android.systemui.keyguard.ScreenLifecycle;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.statusbar.NotificationMediaManager;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.io.PrintWriter;
 import java.lang.annotation.Retention;
@@ -127,7 +128,7 @@
     private final KeyguardBypassController mKeyguardBypassController;
     private PowerManager.WakeLock mWakeLock;
     private final KeyguardUpdateMonitor mUpdateMonitor;
-    private final UnlockMethodCache mUnlockMethodCache;
+    private final KeyguardStateController mKeyguardStateController;
     private final StatusBarWindowController mStatusBarWindowController;
     private final Context mContext;
     private final int mWakeUpDelay;
@@ -150,11 +151,11 @@
             KeyguardViewMediator keyguardViewMediator,
             ScrimController scrimController,
             StatusBar statusBar,
-            UnlockMethodCache unlockMethodCache, Handler handler,
+            KeyguardStateController keyguardStateController, Handler handler,
             KeyguardUpdateMonitor keyguardUpdateMonitor,
             KeyguardBypassController keyguardBypassController) {
         this(context, dozeScrimController, keyguardViewMediator, scrimController, statusBar,
-                unlockMethodCache, handler, keyguardUpdateMonitor,
+                keyguardStateController, handler, keyguardUpdateMonitor,
                 context.getResources()
                         .getInteger(com.android.internal.R.integer.config_wakeUpDelayDoze),
                 keyguardBypassController);
@@ -162,14 +163,11 @@
 
     @VisibleForTesting
     protected BiometricUnlockController(Context context,
-                                     DozeScrimController dozeScrimController,
-                                     KeyguardViewMediator keyguardViewMediator,
-                                     ScrimController scrimController,
-                                     StatusBar statusBar,
-                                     UnlockMethodCache unlockMethodCache, Handler handler,
-                                     KeyguardUpdateMonitor keyguardUpdateMonitor,
-                                     int wakeUpDelay,
-                                     KeyguardBypassController keyguardBypassController) {
+            DozeScrimController dozeScrimController, KeyguardViewMediator keyguardViewMediator,
+            ScrimController scrimController, StatusBar statusBar,
+            KeyguardStateController keyguardStateController, Handler handler,
+            KeyguardUpdateMonitor keyguardUpdateMonitor, int wakeUpDelay,
+            KeyguardBypassController keyguardBypassController) {
         mContext = context;
         mPowerManager = context.getSystemService(PowerManager.class);
         mUpdateMonitor = keyguardUpdateMonitor;
@@ -182,7 +180,7 @@
         mKeyguardViewMediator = keyguardViewMediator;
         mScrimController = scrimController;
         mStatusBar = statusBar;
-        mUnlockMethodCache = unlockMethodCache;
+        mKeyguardStateController = keyguardStateController;
         mHandler = handler;
         mWakeUpDelay = wakeUpDelay;
         mKeyguardBypassController = keyguardBypassController;
@@ -416,7 +414,7 @@
                 return MODE_ONLY_WAKE;
             } else if (mDozeScrimController.isPulsing() && unlockingAllowed) {
                 return MODE_WAKE_AND_UNLOCK_PULSING;
-            } else if (unlockingAllowed || !mUnlockMethodCache.isMethodSecure()) {
+            } else if (unlockingAllowed || !mKeyguardStateController.isMethodSecure()) {
                 return MODE_WAKE_AND_UNLOCK;
             } else {
                 return MODE_SHOW_BOUNCER;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragment.java
index d655b2f..e78b85e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragment.java
@@ -38,7 +38,7 @@
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.phone.StatusBarIconController.DarkIconManager;
 import com.android.systemui.statusbar.policy.EncryptionHelper;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.statusbar.policy.NetworkController.SignalCallback;
 
@@ -57,7 +57,7 @@
     public static final int FADE_IN_DELAY = 50;
     private PhoneStatusBarView mStatusBar;
     private StatusBarStateController mStatusBarStateController;
-    private KeyguardMonitor mKeyguardMonitor;
+    private KeyguardStateController mKeyguardStateController;
     private NetworkController mNetworkController;
     private LinearLayout mSystemIconArea;
     private View mClockView;
@@ -79,7 +79,7 @@
     @Override
     public void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
         mNetworkController = Dependency.get(NetworkController.class);
         mStatusBarStateController = Dependency.get(StatusBarStateController.class);
         mStatusBarComponent = SysUiServiceProvider.getComponent(getContext(), StatusBar.class);
@@ -207,8 +207,8 @@
             state |= DISABLE_CLOCK;
         }
 
-        if (!mKeyguardMonitor.isLaunchTransitionFadingAway()
-                && !mKeyguardMonitor.isKeyguardFadingAway()
+        if (!mKeyguardStateController.isLaunchTransitionFadingAway()
+                && !mKeyguardStateController.isKeyguardFadingAway()
                 && shouldHideNotificationIcons()
                 && !(mStatusBarStateController.getState() == StatusBarState.KEYGUARD
                         && headsUpVisible)) {
@@ -268,7 +268,7 @@
      * don't set the clock GONE otherwise it'll mess up the animation.
      */
     private int clockHiddenMode() {
-        if (!mStatusBar.isClosed() && !mKeyguardMonitor.isShowing()
+        if (!mStatusBar.isClosed() && !mKeyguardStateController.isShowing()
                 && !mStatusBarStateController.isDozing()) {
             return View.INVISIBLE;
         }
@@ -345,11 +345,11 @@
                 .withEndAction(null);
 
         // Synchronize the motion with the Keyguard fading if necessary.
-        if (mKeyguardMonitor.isKeyguardFadingAway()) {
+        if (mKeyguardStateController.isKeyguardFadingAway()) {
             v.animate()
-                    .setDuration(mKeyguardMonitor.getKeyguardFadingAwayDuration())
+                    .setDuration(mKeyguardStateController.getKeyguardFadingAwayDuration())
                     .setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN)
-                    .setStartDelay(mKeyguardMonitor.getKeyguardFadingAwayDelay())
+                    .setStartDelay(mKeyguardStateController.getKeyguardFadingAwayDelay())
                     .start();
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java
index 60e381a..fe3c04e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DozeScrimController.java
@@ -22,11 +22,14 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.systemui.Dependency;
+import com.android.systemui.doze.DozeEvent;
 import com.android.systemui.doze.DozeHost;
 import com.android.systemui.doze.DozeLog;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.plugins.statusbar.StatusBarStateController.StateListener;
 
+import javax.inject.Inject;
+
 /**
  * Controller which handles all the doze animations of the scrims.
  */
@@ -34,6 +37,7 @@
     private static final String TAG = "DozeScrimController";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
 
+    private final DozeLog mDozeLog;
     private final DozeParameters mDozeParameters;
     private final Handler mHandler = new Handler();
 
@@ -47,7 +51,7 @@
         public void onDisplayBlanked() {
             if (DEBUG) {
                 Log.d(TAG, "Pulse in, mDozing=" + mDozing + " mPulseReason="
-                        + DozeLog.reasonToString(mPulseReason));
+                        + DozeEvent.reasonToString(mPulseReason));
             }
             if (!mDozing) {
                 return;
@@ -68,8 +72,8 @@
             // Notifications should time out on their own.  Pulses due to notifications should
             // instead be managed externally based off the notification's lifetime.
             // Dock also controls the time out by self.
-            if (mPulseReason != DozeLog.PULSE_REASON_NOTIFICATION
-                    && mPulseReason != DozeLog.PULSE_REASON_DOCKING) {
+            if (mPulseReason != DozeEvent.PULSE_REASON_NOTIFICATION
+                    && mPulseReason != DozeEvent.PULSE_REASON_DOCKING) {
                 mHandler.postDelayed(mPulseOut, mDozeParameters.getPulseVisibleDuration());
                 mHandler.postDelayed(mPulseOutExtended,
                         mDozeParameters.getPulseVisibleDurationExtended());
@@ -90,14 +94,16 @@
          */
         @Override
         public boolean shouldTimeoutWallpaper() {
-            return mPulseReason == DozeLog.PULSE_REASON_DOCKING;
+            return mPulseReason == DozeEvent.PULSE_REASON_DOCKING;
         }
     };
 
-    public DozeScrimController(DozeParameters dozeParameters) {
+    @Inject
+    public DozeScrimController(DozeParameters dozeParameters, DozeLog dozeLog) {
         mDozeParameters = dozeParameters;
         //Never expected to be destroyed
         Dependency.get(StatusBarStateController.class).addCallback(this);
+        mDozeLog = dozeLog;
     }
 
     @VisibleForTesting
@@ -168,14 +174,14 @@
     }
 
     private void pulseStarted() {
-        DozeLog.tracePulseStart(mPulseReason);
+        mDozeLog.tracePulseStart(mPulseReason);
         if (mPulseCallback != null) {
             mPulseCallback.onPulseStarted();
         }
     }
 
     private void pulseFinished() {
-        DozeLog.tracePulseFinish();
+        mDozeLog.tracePulseFinish();
         if (mPulseCallback != null) {
             mPulseCallback.onPulseFinished();
             mPulseCallback = null;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
index f53c4e8..da62d9b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
@@ -39,7 +39,7 @@
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
 
 import java.util.function.BiConsumer;
@@ -89,7 +89,7 @@
             };
     private boolean mAnimationsEnabled = true;
     Point mPoint;
-    private KeyguardMonitor mKeyguardMonitor;
+    private KeyguardStateController mKeyguardStateController;
 
 
     public HeadsUpAppearanceController(
@@ -160,7 +160,7 @@
         mWakeUpCoordinator = wakeUpCoordinator;
         wakeUpCoordinator.addListener(this);
         mCommandQueue = getComponent(headsUpStatusBarView.getContext(), CommandQueue.class);
-        mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
     }
 
 
@@ -378,7 +378,7 @@
         boolean canShow = !mIsExpanded && notificationsShown;
         if (mBypassController.getBypassEnabled() &&
                 (mStatusBarStateController.getState() == StatusBarState.KEYGUARD
-                        || mKeyguardMonitor.isKeyguardGoingAway())
+                        || mKeyguardStateController.isKeyguardGoingAway())
                 && notificationsShown) {
             canShow = true;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
index 83ecb55..cac3304 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -80,6 +80,7 @@
 import com.android.systemui.statusbar.policy.ExtensionController;
 import com.android.systemui.statusbar.policy.ExtensionController.Extension;
 import com.android.systemui.statusbar.policy.FlashlightController;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.PreviewInflater;
 import com.android.systemui.tuner.LockscreenFragment.LockButtonFactory;
 import com.android.systemui.tuner.TunerService;
@@ -89,7 +90,7 @@
  * text.
  */
 public class KeyguardBottomAreaView extends FrameLayout implements View.OnClickListener,
-        UnlockMethodCache.OnUnlockMethodChangedListener,
+        KeyguardStateController.Callback,
         AccessibilityController.AccessibilityStateChangedCallback {
 
     final static String TAG = "StatusBar/KeyguardBottomAreaView";
@@ -116,7 +117,9 @@
     private static final int DOZE_ANIMATION_STAGGER_DELAY = 48;
     private static final int DOZE_ANIMATION_ELEMENT_DURATION = 250;
 
-    private final UnlockMethodCache mUnlockMethodCache;
+    private final boolean mShowLeftAffordance;
+    private final boolean mShowCameraAffordance;
+
     private KeyguardAffordanceView mRightAffordanceView;
     private KeyguardAffordanceView mLeftAffordanceView;
     private ViewGroup mIndicationArea;
@@ -128,6 +131,7 @@
     private View mCameraPreview;
 
     private ActivityStarter mActivityStarter;
+    private KeyguardStateController mKeyguardStateController;
     private LockPatternUtils mLockPatternUtils;
     private FlashlightController mFlashlightController;
     private PreviewInflater mPreviewInflater;
@@ -183,7 +187,9 @@
     public KeyguardBottomAreaView(Context context, AttributeSet attrs, int defStyleAttr,
             int defStyleRes) {
         super(context, attrs, defStyleAttr, defStyleRes);
-        mUnlockMethodCache = UnlockMethodCache.getInstance(getContext());
+        mShowLeftAffordance = getResources().getBoolean(R.bool.config_keyguardShowLeftAffordance);
+        mShowCameraAffordance = getResources()
+                .getBoolean(R.bool.config_keyguardShowCameraAffordance);
     }
 
     private AccessibilityDelegate mAccessibilityDelegate = new AccessibilityDelegate() {
@@ -239,6 +245,8 @@
         mBurnInYOffset = getResources().getDimensionPixelSize(
                 R.dimen.default_burn_in_prevention_offset);
         updateCameraVisibility();
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
+        mKeyguardStateController.addCallback(this);
         setClipChildren(false);
         setClipToPadding(false);
         inflateCameraPreview();
@@ -276,13 +284,13 @@
         getContext().registerReceiverAsUser(mDevicePolicyReceiver,
                 UserHandle.ALL, filter, null, null);
         Dependency.get(KeyguardUpdateMonitor.class).registerCallback(mUpdateMonitorCallback);
-        mUnlockMethodCache.addListener(this);
+        mKeyguardStateController.addCallback(this);
     }
 
     @Override
     protected void onDetachedFromWindow() {
         super.onDetachedFromWindow();
-        mUnlockMethodCache.removeListener(this);
+        mKeyguardStateController.removeCallback(this);
         mAccessibilityController.removeStateChangedCallback(this);
         mRightExtension.destroy();
         mLeftExtension.destroy();
@@ -369,8 +377,8 @@
             // Things are not set up yet; reply hazy, ask again later
             return;
         }
-        mRightAffordanceView.setVisibility(!mDozing && mRightButton.getIcon().isVisible
-                ? View.VISIBLE : View.GONE);
+        mRightAffordanceView.setVisibility(!mDozing && mShowCameraAffordance
+                && mRightButton.getIcon().isVisible ? View.VISIBLE : View.GONE);
     }
 
     /**
@@ -382,8 +390,12 @@
     }
 
     private void updateLeftAffordanceIcon() {
+        if (!mShowLeftAffordance || mDozing) {
+            mLeftAffordanceView.setVisibility(GONE);
+            return;
+        }
         IconState state = mLeftButton.getIcon();
-        mLeftAffordanceView.setVisibility(!mDozing && state.isVisible ? View.VISIBLE : View.GONE);
+        mLeftAffordanceView.setVisibility(state.isVisible ? View.VISIBLE : View.GONE);
         if (state.drawable != mLeftAffordanceView.getDrawable()
                 || state.tint != mLeftAffordanceView.shouldTint()) {
             mLeftAffordanceView.setImageDrawable(state.drawable, state.tint);
@@ -544,7 +556,7 @@
                 mAssistManager.launchVoiceAssistFromKeyguard();
             }
         };
-        if (mStatusBar.isKeyguardCurrentlySecure()) {
+        if (!mKeyguardStateController.canDismissLockScreen()) {
             AsyncTask.execute(runnable);
         } else {
             boolean dismissShade = !TextUtils.isEmpty(mRightButtonStr)
@@ -609,7 +621,7 @@
     }
 
     @Override
-    public void onUnlockMethodStateChanged() {
+    public void onUnlockedChanged() {
         updateCameraVisibility();
     }
 
@@ -765,10 +777,8 @@
         @Override
         public IconState getIcon() {
             mLeftIsVoiceAssist = canLaunchVoiceAssist();
-            final boolean showAffordance =
-                    getResources().getBoolean(R.bool.config_keyguardShowLeftAffordance);
             if (mLeftIsVoiceAssist) {
-                mIconState.isVisible = mUserSetupComplete && showAffordance;
+                mIconState.isVisible = mUserSetupComplete && mShowLeftAffordance;
                 if (mLeftAssistIcon == null) {
                     mIconState.drawable = mContext.getDrawable(R.drawable.ic_mic_26dp);
                 } else {
@@ -777,7 +787,8 @@
                 mIconState.contentDescription = mContext.getString(
                         R.string.accessibility_voice_assist_button);
             } else {
-                mIconState.isVisible = mUserSetupComplete && showAffordance && isPhoneVisible();
+                mIconState.isVisible = mUserSetupComplete && mShowLeftAffordance
+                        && isPhoneVisible();
                 mIconState.drawable = mContext.getDrawable(
                         com.android.internal.R.drawable.ic_phone);
                 mIconState.contentDescription = mContext.getString(
@@ -800,7 +811,7 @@
         public IconState getIcon() {
             boolean isCameraDisabled = (mStatusBar != null) && !mStatusBar.isCameraAllowedByAdmin();
             mIconState.isVisible = !isCameraDisabled
-                    && getResources().getBoolean(R.bool.config_keyguardShowCameraAffordance)
+                    && mShowCameraAffordance
                     && mUserSetupComplete
                     && resolveCameraIntent() != null;
             mIconState.drawable = mContext.getDrawable(R.drawable.ic_camera_alt_24dp);
@@ -811,11 +822,9 @@
 
         @Override
         public Intent getIntent() {
-            KeyguardUpdateMonitor updateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
-            boolean canSkipBouncer = updateMonitor.getUserCanSkipBouncer(
-                    KeyguardUpdateMonitor.getCurrentUser());
-            boolean secure = mUnlockMethodCache.isMethodSecure();
-            return (secure && !canSkipBouncer) ? SECURE_CAMERA_INTENT : INSECURE_CAMERA_INTENT;
+            boolean canDismissLs = mKeyguardStateController.canDismissLockScreen();
+            boolean secure = mKeyguardStateController.isMethodSecure();
+            return (secure && !canDismissLs) ? SECURE_CAMERA_INTENT : INSECURE_CAMERA_INTENT;
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
index d7f67ce..f34c15c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
@@ -17,7 +17,6 @@
 package com.android.systemui.statusbar.phone;
 
 import static com.android.keyguard.KeyguardSecurityModel.SecurityMode;
-import static com.android.systemui.DejankUtils.whitelistIpcs;
 import static com.android.systemui.plugins.ActivityStarter.OnDismissAction;
 
 import android.content.Context;
@@ -38,14 +37,17 @@
 
 import com.android.internal.widget.LockPatternUtils;
 import com.android.keyguard.KeyguardHostView;
+import com.android.keyguard.KeyguardSecurityModel;
 import com.android.keyguard.KeyguardSecurityView;
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.keyguard.KeyguardUpdateMonitorCallback;
 import com.android.keyguard.ViewMediatorCallback;
 import com.android.systemui.DejankUtils;
+import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.keyguard.DismissCallbackRegistry;
 import com.android.systemui.plugins.FalsingManager;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.io.PrintWriter;
 
@@ -69,7 +71,7 @@
     private final Handler mHandler;
     private final BouncerExpansionCallback mExpansionCallback;
     private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
-    private final UnlockMethodCache mUnlockMethodCache;
+    private final KeyguardStateController mKeyguardStateController;
     private final KeyguardUpdateMonitorCallback mUpdateMonitorCallback =
             new KeyguardUpdateMonitorCallback() {
                 @Override
@@ -97,7 +99,8 @@
     public KeyguardBouncer(Context context, ViewMediatorCallback callback,
             LockPatternUtils lockPatternUtils, ViewGroup container,
             DismissCallbackRegistry dismissCallbackRegistry, FalsingManager falsingManager,
-            BouncerExpansionCallback expansionCallback, UnlockMethodCache unlockMethodCache,
+            BouncerExpansionCallback expansionCallback,
+            KeyguardStateController keyguardStateController,
             KeyguardUpdateMonitor keyguardUpdateMonitor,
             KeyguardBypassController keyguardBypassController, Handler handler) {
         mContext = context;
@@ -109,7 +112,7 @@
         mDismissCallbackRegistry = dismissCallbackRegistry;
         mExpansionCallback = expansionCallback;
         mHandler = handler;
-        mUnlockMethodCache = unlockMethodCache;
+        mKeyguardStateController = keyguardStateController;
         mKeyguardUpdateMonitor.registerCallback(mUpdateMonitorCallback);
         mKeyguardBypassController = keyguardBypassController;
     }
@@ -173,7 +176,7 @@
 
         // Split up the work over multiple frames.
         DejankUtils.removeCallbacks(mResetRunnable);
-        if (mUnlockMethodCache.isFaceAuthEnabled() && !needsFullscreenBouncer()
+        if (mKeyguardStateController.isFaceAuthEnabled() && !needsFullscreenBouncer()
                 && !mKeyguardUpdateMonitor.userNeedsStrongAuth()
                 && !mKeyguardBypassController.getBypassEnabled()) {
             mHandler.postDelayed(mShowRunnable, BOUNCER_FACE_DELAY);
@@ -459,15 +462,9 @@
      * notifications on Keyguard, like SIM PIN/PUK.
      */
     public boolean needsFullscreenBouncer() {
-        // TODO(b/140059518)
-        return whitelistIpcs(() -> {
-            ensureView();
-            if (mKeyguardView != null) {
-                SecurityMode mode = mKeyguardView.getSecurityMode();
-                return mode == SecurityMode.SimPin || mode == SecurityMode.SimPuk;
-            }
-            return false;
-        });
+        SecurityMode mode = Dependency.get(KeyguardSecurityModel.class).getSecurityMode(
+                KeyguardUpdateMonitor.getCurrentUser());
+        return mode == SecurityMode.SimPin || mode == SecurityMode.SimPuk;
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBypassController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBypassController.kt
index 832ea9e..aca7f44 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBypassController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBypassController.kt
@@ -23,6 +23,7 @@
 import com.android.systemui.plugins.statusbar.StatusBarStateController
 import com.android.systemui.statusbar.NotificationLockscreenUserManager
 import com.android.systemui.statusbar.StatusBarState
+import com.android.systemui.statusbar.policy.KeyguardStateController
 import com.android.systemui.tuner.TunerService
 import java.io.PrintWriter
 import javax.inject.Inject
@@ -31,7 +32,7 @@
 @Singleton
 class KeyguardBypassController {
 
-    private val unlockMethodCache: UnlockMethodCache
+    private val mKeyguardStateController: KeyguardStateController
     private val statusBarStateController: StatusBarStateController
     private var hasFaceFeature: Boolean
 
@@ -47,7 +48,7 @@
      * If face unlock dismisses the lock screen or keeps user on keyguard for the current user.
      */
     var bypassEnabled: Boolean = false
-        get() = field && unlockMethodCache.isFaceAuthEnabled
+        get() = field && mKeyguardStateController.isFaceAuthEnabled
         private set
 
     var bouncerShowing: Boolean = false
@@ -66,9 +67,10 @@
         context: Context,
         tunerService: TunerService,
         statusBarStateController: StatusBarStateController,
-        lockscreenUserManager: NotificationLockscreenUserManager
+        lockscreenUserManager: NotificationLockscreenUserManager,
+        keyguardStateController: KeyguardStateController
     ) {
-        unlockMethodCache = UnlockMethodCache.getInstance(context)
+        this.mKeyguardStateController = keyguardStateController
         this.statusBarStateController = statusBarStateController
 
         hasFaceFeature = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardLiftController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardLiftController.kt
index 00b764b..d9de59e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardLiftController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardLiftController.kt
@@ -66,6 +66,9 @@
     }
 
     private fun updateListeningState() {
+        if (pickupSensor == null) {
+            return
+        }
         val onKeyguard = keyguardUpdateMonitor.isKeyguardVisible &&
                 !statusBarStateController.isDozing
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java
index d709730..de660ce 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarTransitionsController.java
@@ -31,7 +31,7 @@
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.CommandQueue.Callbacks;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -47,7 +47,7 @@
 
     private final Handler mHandler;
     private final DarkIntensityApplier mApplier;
-    private final KeyguardMonitor mKeyguardMonitor;
+    private final KeyguardStateController mKeyguardStateController;
     private final StatusBarStateController mStatusBarStateController;
 
     private boolean mTransitionDeferring;
@@ -73,7 +73,7 @@
     public LightBarTransitionsController(Context context, DarkIntensityApplier applier) {
         mApplier = applier;
         mHandler = new Handler();
-        mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
         mStatusBarStateController = Dependency.get(StatusBarStateController.class);
         SysUiServiceProvider.getComponent(context, CommandQueue.class)
                 .addCallback(this);
@@ -101,7 +101,7 @@
 
     @Override
     public void appTransitionPending(int displayId, boolean forced) {
-        if (mDisplayId != displayId || mKeyguardMonitor.isKeyguardGoingAway() && !forced) {
+        if (mDisplayId != displayId || mKeyguardStateController.isKeyguardGoingAway() && !forced) {
             return;
         }
         mTransitionPending = true;
@@ -123,7 +123,7 @@
     @Override
     public void appTransitionStarting(int displayId, long startTime, long duration,
             boolean forced) {
-        if (mDisplayId != displayId || mKeyguardMonitor.isKeyguardGoingAway() && !forced) {
+        if (mDisplayId != displayId || mKeyguardStateController.isKeyguardGoingAway() && !forced) {
             return;
         }
         if (mTransitionPending && mTintChangePending) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
index 6781073..4927ec8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
@@ -53,7 +53,7 @@
 import com.android.systemui.statusbar.phone.ScrimController.ScrimVisibility;
 import com.android.systemui.statusbar.policy.AccessibilityController;
 import com.android.systemui.statusbar.policy.ConfigurationController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
 import com.android.systemui.statusbar.policy.UserInfoController.OnUserInfoChangedListener;
 
@@ -68,9 +68,8 @@
  */
 public class LockIcon extends KeyguardAffordanceView implements OnUserInfoChangedListener,
         StatusBarStateController.StateListener, ConfigurationController.ConfigurationListener,
-        UnlockMethodCache.OnUnlockMethodChangedListener,
-        NotificationWakeUpCoordinator.WakeUpListener, ViewTreeObserver.OnPreDrawListener,
-        OnHeadsUpChangedListener {
+        KeyguardStateController.Callback, NotificationWakeUpCoordinator.WakeUpListener,
+        ViewTreeObserver.OnPreDrawListener, OnHeadsUpChangedListener {
 
     private static final int STATE_LOCKED = 0;
     private static final int STATE_LOCK_OPEN = 1;
@@ -78,11 +77,10 @@
     private static final int STATE_BIOMETRICS_ERROR = 3;
     private final ConfigurationController mConfigurationController;
     private final StatusBarStateController mStatusBarStateController;
-    private final UnlockMethodCache mUnlockMethodCache;
     private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
     private final AccessibilityController mAccessibilityController;
     private final DockManager mDockManager;
-    private final KeyguardMonitor mKeyguardMonitor;
+    private final KeyguardStateController mKeyguardStateController;
     private final KeyguardBypassController mBypassController;
     private final NotificationWakeUpCoordinator mWakeUpCoordinator;
     private final HeadsUpManagerPhone mHeadsUpManager;
@@ -107,13 +105,13 @@
     private boolean mUpdatePending;
     private boolean mBouncerPreHideAnimation;
 
-    private final KeyguardMonitor.Callback mKeyguardMonitorCallback =
-            new KeyguardMonitor.Callback() {
+    private final KeyguardStateController.Callback mKeyguardMonitorCallback =
+            new KeyguardStateController.Callback() {
                 @Override
                 public void onKeyguardShowingChanged() {
                     boolean force = false;
                     boolean wasShowing = mKeyguardShowing;
-                    mKeyguardShowing = mKeyguardMonitor.isShowing();
+                    mKeyguardShowing = mKeyguardStateController.isShowing();
                     if (!wasShowing && mKeyguardShowing && mBlockUpdates) {
                         mBlockUpdates = false;
                         force = true;
@@ -126,7 +124,7 @@
 
                 @Override
                 public void onKeyguardFadingAwayChanged() {
-                    if (!mKeyguardMonitor.isKeyguardFadingAway()) {
+                    if (!mKeyguardStateController.isKeyguardFadingAway()) {
                         mBouncerPreHideAnimation = false;
                         if (mBlockUpdates) {
                             mBlockUpdates = false;
@@ -134,6 +132,11 @@
                         }
                     }
                 }
+
+                @Override
+                public void onUnlockedChanged() {
+                    update();
+                }
             };
     private final DockManager.DockEventListener mDockEventListener =
             new DockManager.DockEventListener() {
@@ -181,19 +184,18 @@
             AccessibilityController accessibilityController,
             KeyguardBypassController bypassController,
             NotificationWakeUpCoordinator wakeUpCoordinator,
-            KeyguardMonitor keyguardMonitor,
+            KeyguardStateController keyguardStateController,
             @Nullable DockManager dockManager,
             HeadsUpManagerPhone headsUpManager) {
         super(context, attrs);
         mContext = context;
-        mUnlockMethodCache = UnlockMethodCache.getInstance(context);
         mKeyguardUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
         mAccessibilityController = accessibilityController;
         mConfigurationController = configurationController;
         mStatusBarStateController = statusBarStateController;
         mBypassController = bypassController;
         mWakeUpCoordinator = wakeUpCoordinator;
-        mKeyguardMonitor = keyguardMonitor;
+        mKeyguardStateController = keyguardStateController;
         mDockManager = dockManager;
         mHeadsUpManager = headsUpManager;
     }
@@ -203,9 +205,8 @@
         super.onAttachedToWindow();
         mStatusBarStateController.addCallback(this);
         mConfigurationController.addCallback(this);
-        mKeyguardMonitor.addCallback(mKeyguardMonitorCallback);
+        mKeyguardStateController.addCallback(mKeyguardMonitorCallback);
         mKeyguardUpdateMonitor.registerCallback(mUpdateMonitorCallback);
-        mUnlockMethodCache.addListener(this);
         mWakeUpCoordinator.addListener(this);
         mSimLocked = mKeyguardUpdateMonitor.isSimPinSecure();
         if (mDockManager != null) {
@@ -221,9 +222,8 @@
         mStatusBarStateController.removeCallback(this);
         mConfigurationController.removeCallback(this);
         mKeyguardUpdateMonitor.removeCallback(mUpdateMonitorCallback);
-        mKeyguardMonitor.removeCallback(mKeyguardMonitorCallback);
+        mKeyguardStateController.removeCallback(mKeyguardMonitorCallback);
         mWakeUpCoordinator.removeListener(this);
-        mUnlockMethodCache.removeListener(this);
         if (mDockManager != null) {
             mDockManager.removeListener(mDockEventListener);
         }
@@ -370,15 +370,15 @@
     }
 
     private boolean canBlockUpdates() {
-        return mKeyguardShowing || mKeyguardMonitor.isKeyguardFadingAway();
+        return mKeyguardShowing || mKeyguardStateController.isKeyguardFadingAway();
     }
 
     private void updateClickability() {
         if (mAccessibilityController == null) {
             return;
         }
-        boolean canLock = mUnlockMethodCache.isMethodSecure()
-                && mUnlockMethodCache.canSkipBouncer();
+        boolean canLock = mKeyguardStateController.isMethodSecure()
+                && mKeyguardStateController.canDismissLockScreen();
         boolean clickToUnlock = mAccessibilityController.isAccessibilityEnabled();
         setClickable(clickToUnlock);
         setLongClickable(canLock && !clickToUnlock);
@@ -523,8 +523,8 @@
 
     private int getState() {
         KeyguardUpdateMonitor updateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
-        if ((mUnlockMethodCache.canSkipBouncer() || !mKeyguardShowing || mBouncerPreHideAnimation
-                || mKeyguardMonitor.isKeyguardGoingAway()) && !mSimLocked) {
+        if ((mKeyguardStateController.canDismissLockScreen() || !mKeyguardShowing
+                || mKeyguardStateController.isKeyguardGoingAway()) && !mSimLocked) {
             return STATE_LOCK_OPEN;
         } else if (mTransientBiometricsError) {
             return STATE_BIOMETRICS_ERROR;
@@ -582,11 +582,6 @@
         update(true /* force */);
     }
 
-    @Override
-    public void onUnlockMethodStateChanged() {
-        update();
-    }
-
     /**
      * We need to hide the lock whenever there's a fingerprint unlock, otherwise you'll see the
      * icon on top of the black front scrim.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVPluginManager.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVPluginManager.kt
index 7dcc2fc..53601ba 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVPluginManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NPVPluginManager.kt
@@ -18,6 +18,7 @@
 
 import android.content.Context
 import android.view.View
+import android.view.ViewGroup.MarginLayoutParams
 import android.widget.FrameLayout
 import com.android.systemui.plugins.NPVPlugin
 import com.android.systemui.plugins.PluginListener
@@ -36,6 +37,7 @@
 
     private var plugin: NPVPlugin? = null
     private var animator = createAnimator()
+    private var yOffset = 0f
 
     private fun createAnimator() = TouchAnimator.Builder()
             .addFloat(parent, "alpha", 1f, 0f)
@@ -76,7 +78,7 @@
     }
 
     fun setExpansion(expansion: Float, headerTranslation: Float, heightDiff: Float) {
-        parent.setTranslationY(expansion * heightDiff + headerTranslation)
+        parent.setTranslationY(expansion * heightDiff + headerTranslation + yOffset)
         if (!expansion.isNaN()) animator.setPosition(expansion)
     }
 
@@ -88,5 +90,13 @@
         animator = createAnimator()
     }
 
-    fun getHeight() = if (plugin != null) parent.height else 0
+    fun getHeight() =
+        if (plugin != null) {
+            parent.height + (parent.getLayoutParams() as MarginLayoutParams).topMargin
+        } else 0
+
+    fun setYOffset(y: Float) {
+        yOffset = y
+        parent.setTranslationY(yOffset)
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
index 2b8c86b..6e61d7c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
@@ -86,9 +86,10 @@
 import com.android.internal.util.LatencyTracker;
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
-import com.android.systemui.ScreenDecorations;
 import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.assist.AssistHandleViewController;
 import com.android.systemui.assist.AssistManager;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.fragments.FragmentHostManager;
 import com.android.systemui.fragments.FragmentHostManager.FragmentListener;
 import com.android.systemui.model.SysUiState;
@@ -139,6 +140,7 @@
     private final MetricsLogger mMetricsLogger;
     private final DeviceProvisionedController mDeviceProvisionedController;
     private final StatusBarStateController mStatusBarStateController;
+    private final NavigationModeController mNavigationModeController;
 
     protected NavigationBarView mNavigationBarView = null;
 
@@ -170,11 +172,16 @@
 
     private OverviewProxyService mOverviewProxyService;
 
+    private final BroadcastDispatcher mBroadcastDispatcher;
+
     @VisibleForTesting
     public int mDisplayId;
     private boolean mIsOnDefaultDisplay;
     public boolean mHomeBlockedThisTouch;
-    private ScreenDecorations mScreenDecorations;
+
+    /** Only for default display */
+    @Nullable
+    private AssistHandleViewController mAssistHandlerViewController;
 
     private Handler mHandler = Dependency.get(Dependency.MAIN_HANDLER);
 
@@ -248,7 +255,8 @@
             AssistManager assistManager, OverviewProxyService overviewProxyService,
             NavigationModeController navigationModeController,
             StatusBarStateController statusBarStateController,
-            SysUiState sysUiFlagsContainer) {
+            SysUiState sysUiFlagsContainer,
+            BroadcastDispatcher broadcastDispatcher) {
         mAccessibilityManagerWrapper = accessibilityManagerWrapper;
         mDeviceProvisionedController = deviceProvisionedController;
         mStatusBarStateController = statusBarStateController;
@@ -257,7 +265,9 @@
         mSysUiFlagsContainer = sysUiFlagsContainer;
         mAssistantAvailable = mAssistManager.getAssistInfoForUser(UserHandle.USER_CURRENT) != null;
         mOverviewProxyService = overviewProxyService;
+        mNavigationModeController = navigationModeController;
         mNavBarMode = navigationModeController.addListener(this);
+        mBroadcastDispatcher = broadcastDispatcher;
     }
 
     // ----- Fragment Lifecycle Callbacks -----
@@ -296,6 +306,7 @@
     @Override
     public void onDestroy() {
         super.onDestroy();
+        mNavigationModeController.removeListener(this);
         mAccessibilityManagerWrapper.removeCallback(mAccessibilityListener);
         mContentResolver.unregisterContentObserver(mMagnificationObserver);
         mContentResolver.unregisterContentObserver(mAssistContentObserver);
@@ -334,7 +345,8 @@
         IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
         filter.addAction(Intent.ACTION_SCREEN_ON);
         filter.addAction(Intent.ACTION_USER_SWITCHED);
-        getContext().registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
+        mBroadcastDispatcher.registerReceiver(mBroadcastReceiver, filter, Handler.getMain(),
+                UserHandle.ALL);
         notifyNavigationBarScreenOn();
 
         mOverviewProxyService.addCallback(mOverviewProxyListener);
@@ -357,22 +369,27 @@
             mDisabledFlags2 |= StatusBarManager.DISABLE2_ROTATE_SUGGESTIONS;
         }
         setDisabled2Flags(mDisabledFlags2);
-
-        mScreenDecorations = SysUiServiceProvider.getComponent(getContext(),
-                ScreenDecorations.class);
-        getBarTransitions().addDarkIntensityListener(mScreenDecorations);
+        if (mIsOnDefaultDisplay) {
+            mAssistHandlerViewController =
+                new AssistHandleViewController(mHandler, mNavigationBarView);
+            getBarTransitions().addDarkIntensityListener(mAssistHandlerViewController);
+        }
     }
 
     @Override
     public void onDestroyView() {
         super.onDestroyView();
         if (mNavigationBarView != null) {
-            mNavigationBarView.getBarTransitions().removeDarkIntensityListener(mScreenDecorations);
+            if (mIsOnDefaultDisplay) {
+                mNavigationBarView.getBarTransitions()
+                        .removeDarkIntensityListener(mAssistHandlerViewController);
+                mAssistHandlerViewController = null;
+            }
             mNavigationBarView.getBarTransitions().destroy();
             mNavigationBarView.getLightTransitionsController().destroy(getContext());
         }
         mOverviewProxyService.removeCallback(mOverviewProxyListener);
-        getContext().unregisterReceiver(mBroadcastReceiver);
+        mBroadcastDispatcher.unregisterReceiver(mBroadcastReceiver);
     }
 
     @Override
@@ -1019,6 +1036,11 @@
                 delay + StackStateAnimator.ANIMATION_DURATION_GO_TO_FULL_SHADE);
     }
 
+    @Nullable
+    public AssistHandleViewController getAssistHandlerViewController() {
+        return mAssistHandlerViewController;
+    }
+
     /**
      * Performs transitions on navigation bar.
      *
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index fa4812d..2aae5b1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -67,6 +67,7 @@
 import com.android.systemui.Interpolators;
 import com.android.systemui.R;
 import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.assist.AssistHandleViewController;
 import com.android.systemui.assist.AssistManager;
 import com.android.systemui.model.SysUiState;
 import com.android.systemui.recents.OverviewProxyService;
@@ -75,6 +76,7 @@
 import com.android.systemui.shared.system.ActivityManagerWrapper;
 import com.android.systemui.shared.system.QuickStepContract;
 import com.android.systemui.shared.system.WindowManagerWrapper;
+import com.android.systemui.statusbar.NavigationBarController;
 import com.android.systemui.statusbar.policy.DeadZone;
 import com.android.systemui.statusbar.policy.KeyButtonDrawable;
 
@@ -829,7 +831,11 @@
         mRecentsOnboarding.onNavigationModeChanged(mNavBarMode);
         getRotateSuggestionButton().onNavigationModeChanged(mNavBarMode);
 
-        mRegionSamplingHelper.start(mSamplingBounds);
+        if (isGesturalMode(mNavBarMode)) {
+            mRegionSamplingHelper.start(mSamplingBounds);
+        } else {
+            mRegionSamplingHelper.stop();
+        }
     }
 
     public void setAccessibilityButtonState(final boolean visible, final boolean longClickable) {
@@ -1194,6 +1200,19 @@
         // we're passing the insets onto the gesture handler since the back arrow is only
         // conditionally added and doesn't always get all the insets.
         mEdgeBackGestureHandler.setInsets(leftInset, rightInset);
+
+        // this allows assist handle to be drawn outside its bound so that it can align screen
+        // bottom by translating its y position.
+        final boolean shouldClip =
+                !isGesturalMode(mNavBarMode) || insets.getSystemWindowInsetBottom() == 0;
+        setClipChildren(shouldClip);
+        setClipToPadding(shouldClip);
+
+        AssistHandleViewController controller = Dependency.get(NavigationBarController.class)
+                .getAssistHandlerViewController();
+        if (controller != null) {
+            controller.setBottomOffset(insets.getSystemWindowInsetBottom());
+        }
         return super.onApplyWindowInsets(insets);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index ea113df..00736b7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -68,6 +68,7 @@
 import com.android.systemui.Dependency;
 import com.android.systemui.Interpolators;
 import com.android.systemui.R;
+import com.android.systemui.doze.DozeLog;
 import com.android.systemui.fragments.FragmentHostManager;
 import com.android.systemui.fragments.FragmentHostManager.FragmentListener;
 import com.android.systemui.plugins.FalsingManager;
@@ -102,7 +103,7 @@
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
 import com.android.systemui.statusbar.notification.stack.StackStateAnimator;
 import com.android.systemui.statusbar.policy.ConfigurationController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
 import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
 import com.android.systemui.statusbar.policy.ZenModeController;
@@ -205,11 +206,11 @@
                     mDelayShowingKeyguardStatusBar = false;
                 }
             };
-    private final KeyguardMonitor.Callback mKeyguardMonitorCallback =
-            new KeyguardMonitor.Callback() {
+    private final KeyguardStateController.Callback mKeyguardMonitorCallback =
+            new KeyguardStateController.Callback() {
                 @Override
                 public void onKeyguardFadingAwayChanged() {
-                    if (!mKeyguardMonitor.isKeyguardFadingAway()) {
+                    if (!mKeyguardStateController.isKeyguardFadingAway()) {
                         mFirstBypassAttempt = false;
                         mDelayShowingKeyguardStatusBar = false;
                     }
@@ -407,14 +408,11 @@
             .setDuration(200)
             .setAnimationFinishListener(mAnimatorListenerAdapter)
             .setCustomInterpolator(PANEL_ALPHA.getProperty(), Interpolators.ALPHA_IN);
-    private final NotificationEntryManager mEntryManager =
-            Dependency.get(NotificationEntryManager.class);
+    private final NotificationEntryManager mEntryManager;
 
     private final CommandQueue mCommandQueue;
-    private final NotificationLockscreenUserManager mLockscreenUserManager =
-            Dependency.get(NotificationLockscreenUserManager.class);
-    private final ShadeController mShadeController =
-            Dependency.get(ShadeController.class);
+    private final NotificationLockscreenUserManager mLockscreenUserManager;
+    private final ShadeController mShadeController;
     private int mDisplayId;
 
     /**
@@ -459,8 +457,12 @@
             DynamicPrivacyController dynamicPrivacyController,
             KeyguardBypassController bypassController,
             FalsingManager falsingManager,
-            PluginManager pluginManager) {
-        super(context, attrs);
+            PluginManager pluginManager,
+            ShadeController shadeController,
+            NotificationLockscreenUserManager notificationLockscreenUserManager,
+            NotificationEntryManager notificationEntryManager,
+            DozeLog dozeLog) {
+        super(context, attrs, falsingManager, dozeLog);
         setWillNotDraw(!DEBUG);
         mInjectionInflationController = injectionInflationController;
         mFalsingManager = falsingManager;
@@ -482,7 +484,7 @@
         mKeyguardBypassController = bypassController;
         mUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
         mFirstBypassAttempt = mKeyguardBypassController.getBypassEnabled();
-        mKeyguardMonitor.addCallback(mKeyguardMonitorCallback);
+        mKeyguardStateController.addCallback(mKeyguardMonitorCallback);
         dynamicPrivacyController.addListener(this);
 
         mBottomAreaShadeAlphaAnimator = ValueAnimator.ofFloat(1f, 0);
@@ -493,6 +495,11 @@
         mBottomAreaShadeAlphaAnimator.setDuration(160);
         mBottomAreaShadeAlphaAnimator.setInterpolator(Interpolators.ALPHA_OUT);
         mPluginManager = pluginManager;
+        mShadeController = shadeController;
+        mLockscreenUserManager = notificationLockscreenUserManager;
+        mEntryManager = notificationEntryManager;
+
+        setBackgroundColor(Color.TRANSPARENT);
     }
 
     /**
@@ -507,9 +514,11 @@
         mKeyguardBottomArea.setStatusBar(mStatusBar);
     }
 
-    @Override
-    protected void onFinishInflate() {
-        super.onFinishInflate();
+    /**
+     * Call after this view has been fully inflated and had its children attached.
+     */
+    public void onChildrenAttached() {
+        loadDimens();
         mKeyguardStatusBar = findViewById(R.id.keyguard_header);
         mKeyguardStatusView = findViewById(R.id.keyguard_status_view);
 
@@ -552,7 +561,7 @@
             }
         });
 
-        Dependency.get(PluginManager.class).addPluginListener(
+        mPluginManager.addPluginListener(
                 new PluginListener<HomeControlsPlugin>() {
 
                     @Override
@@ -652,8 +661,7 @@
             mNotificationStackScroller.setLayoutParams(lp);
         }
         int sideMargin = res.getDimensionPixelOffset(R.dimen.notification_side_paddings);
-        int topMargin =
-                res.getDimensionPixelOffset(com.android.internal.R.dimen.quick_qs_total_height);
+        int topMargin = sideMargin;
         lp = (FrameLayout.LayoutParams) mPluginFrame.getLayoutParams();
         if (lp.width != qsWidth || lp.gravity != panelGravity || lp.leftMargin != sideMargin
                 || lp.rightMargin != sideMargin || lp.topMargin != topMargin) {
@@ -796,6 +804,7 @@
         int oldMaxHeight = mQsMaxExpansionHeight;
         if (mQs != null) {
             mQsMinExpansionHeight = mKeyguardShowing ? 0 : mQs.getQsMinExpansionHeight();
+            mNPVPluginManager.setYOffset(mQsMinExpansionHeight);
             mQsMinExpansionHeight += mNPVPluginManager.getHeight();
             mQsMaxExpansionHeight = mQs.getDesiredHeight();
             mNotificationStackScroller.setMaxTopPadding(
@@ -1683,7 +1692,7 @@
     @Override
     public void onStateChanged(int statusBarState) {
         boolean goingToFullShade = mStatusBarStateController.goingToFullShade();
-        boolean keyguardFadingAway = mKeyguardMonitor.isKeyguardFadingAway();
+        boolean keyguardFadingAway = mKeyguardStateController.isKeyguardFadingAway();
         int oldState = mBarState;
         boolean keyguardShowing = statusBarState == StatusBarState.KEYGUARD;
         setKeyguardStatusViewVisibility(statusBarState, keyguardFadingAway, goingToFullShade);
@@ -1701,7 +1710,7 @@
                 && (goingToFullShade || statusBarState == StatusBarState.SHADE_LOCKED)) {
             animateKeyguardStatusBarOut();
             long delay = mBarState == StatusBarState.SHADE_LOCKED
-                    ? 0 : mKeyguardMonitor.calculateGoingToFullShadeDelay();
+                    ? 0 : mKeyguardStateController.calculateGoingToFullShadeDelay();
             mQs.animateHeaderSlidingIn(delay);
         } else if (oldState == StatusBarState.SHADE_LOCKED
                 && statusBarState == StatusBarState.KEYGUARD) {
@@ -1778,13 +1787,13 @@
     private void animateKeyguardStatusBarOut() {
         ValueAnimator anim = ValueAnimator.ofFloat(mKeyguardStatusBar.getAlpha(), 0f);
         anim.addUpdateListener(mStatusBarAnimateAlphaListener);
-        anim.setStartDelay(mKeyguardMonitor.isKeyguardFadingAway()
-                ? mKeyguardMonitor.getKeyguardFadingAwayDelay()
+        anim.setStartDelay(mKeyguardStateController.isKeyguardFadingAway()
+                ? mKeyguardStateController.getKeyguardFadingAwayDelay()
                 : 0);
 
         long duration;
-        if (mKeyguardMonitor.isKeyguardFadingAway()) {
-            duration = mKeyguardMonitor.getShortenedFadingAwayDuration();
+        if (mKeyguardStateController.isKeyguardFadingAway()) {
+            duration = mKeyguardStateController.getShortenedFadingAwayDuration();
         } else {
             duration = StackStateAnimator.ANIMATION_DURATION_STANDARD;
         }
@@ -1831,8 +1840,8 @@
         if (goingToFullShade) {
             mKeyguardBottomArea.animate()
                     .alpha(0f)
-                    .setStartDelay(mKeyguardMonitor.getKeyguardFadingAwayDelay())
-                    .setDuration(mKeyguardMonitor.getShortenedFadingAwayDuration())
+                    .setStartDelay(mKeyguardStateController.getKeyguardFadingAwayDelay())
+                    .setDuration(mKeyguardStateController.getShortenedFadingAwayDuration())
                     .setInterpolator(Interpolators.ALPHA_OUT)
                     .withEndAction(mAnimateKeyguardBottomAreaInvisibleEndRunnable)
                     .start();
@@ -1860,8 +1869,8 @@
                     .withEndAction(mAnimateKeyguardStatusViewGoneEndRunnable);
             if (keyguardFadingAway) {
                 mKeyguardStatusView.animate()
-                        .setStartDelay(mKeyguardMonitor.getKeyguardFadingAwayDelay())
-                        .setDuration(mKeyguardMonitor.getShortenedFadingAwayDuration())
+                        .setStartDelay(mKeyguardStateController.getKeyguardFadingAwayDelay())
+                        .setDuration(mKeyguardStateController.getShortenedFadingAwayDuration())
                         .start();
             }
         } else if (mBarState == StatusBarState.SHADE_LOCKED
@@ -2556,7 +2565,7 @@
 
     @Override
     protected void onTrackingStarted() {
-        mFalsingManager.onTrackingStarted(mStatusBar.isKeyguardCurrentlySecure());
+        mFalsingManager.onTrackingStarted(!mKeyguardStateController.canDismissLockScreen());
         super.onTrackingStarted();
         if (mQsFullyExpanded) {
             mQsExpandImmediate = true;
@@ -2846,7 +2855,7 @@
     @Override
     protected boolean shouldUseDismissingAnimation() {
         return mBarState != StatusBarState.SHADE
-                && (!mStatusBar.isKeyguardCurrentlySecure() || !isTracking());
+                && (mKeyguardStateController.canDismissLockScreen() || !isTracking());
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index 31600e3..432d636 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -49,7 +49,7 @@
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.SysuiStatusBarStateController;
 import com.android.systemui.statusbar.VibratorHelper;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -111,6 +111,7 @@
     private FlingAnimationUtils mFlingAnimationUtilsClosing;
     private FlingAnimationUtils mFlingAnimationUtilsDismissing;
     private final FalsingManager mFalsingManager;
+    private final DozeLog mDozeLog;
     private final VibratorHelper mVibratorHelper;
 
     /**
@@ -143,7 +144,8 @@
     private boolean mGestureWaitForTouchSlop;
     private boolean mIgnoreXTouchSlop;
     private boolean mExpandLatencyTracking;
-    protected final KeyguardMonitor mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+    protected final KeyguardStateController mKeyguardStateController = Dependency.get(
+            KeyguardStateController.class);
     protected final SysuiStatusBarStateController mStatusBarStateController =
             (SysuiStatusBarStateController) Dependency.get(StatusBarStateController.class);
 
@@ -203,7 +205,8 @@
         mJustPeeked = true;
     }
 
-    public PanelView(Context context, AttributeSet attrs) {
+    public PanelView(Context context, AttributeSet attrs, FalsingManager falsingManager,
+            DozeLog dozeLog) {
         super(context, attrs);
         mFlingAnimationUtils = new FlingAnimationUtils(context, 0.6f /* maxLengthSeconds */,
                 0.6f /* speedUpFactor */);
@@ -213,7 +216,8 @@
                 0.5f /* maxLengthSeconds */, 0.2f /* speedUpFactor */, 0.6f /* x2 */,
                 0.84f /* y2 */);
         mBounceInterpolator = new BounceInterpolator();
-        mFalsingManager = Dependency.get(FalsingManager.class);  // TODO: inject into a controller.
+        mFalsingManager = falsingManager;
+        mDozeLog = dozeLog;
         mNotificationsDragEnabled =
                 getResources().getBoolean(R.bool.config_enableNotificationShadeDrag);
         mVibratorHelper = Dependency.get(VibratorHelper.class);
@@ -476,7 +480,7 @@
             boolean expand = flingExpands(vel, vectorVel, x, y)
                     || event.getActionMasked() == MotionEvent.ACTION_CANCEL
                     || forceCancel;
-            DozeLog.traceFling(expand, mTouchAboveFalsingThreshold,
+            mDozeLog.traceFling(expand, mTouchAboveFalsingThreshold,
                     mStatusBar.isFalsingThresholdNeeded(),
                     mStatusBar.isWakeUpComingFromTouch());
                     // Log collapse gesture if on lock screen.
@@ -495,7 +499,8 @@
                 mUpdateFlingVelocity = vel;
             }
         } else if (mPanelClosedOnDown && !mHeadsUpManager.hasPinnedHeadsUp() && !mTracking
-                && !mStatusBar.isBouncerShowing() && !mKeyguardMonitor.isKeyguardFadingAway()) {
+                && !mStatusBar.isBouncerShowing()
+                && !mKeyguardStateController.isKeyguardFadingAway()) {
             long timePassed = SystemClock.uptimeMillis() - mDownTime;
             if (timePassed < ViewConfiguration.getLongPressTimeout()) {
                 // Lets show the user that he can actually expand the panel
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
index ee43879..294111c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
@@ -57,7 +57,7 @@
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
 import com.android.systemui.statusbar.policy.HotspotController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.LocationController;
 import com.android.systemui.statusbar.policy.NextAlarmController;
 import com.android.systemui.statusbar.policy.RotationLockController;
@@ -82,7 +82,7 @@
                 Listener,
                 ZenModeController.Callback,
                 DeviceProvisionedListener,
-                KeyguardMonitor.Callback,
+                KeyguardStateController.Callback,
                 PrivacyItemController.Callback,
                 LocationController.LocationChangeCallback {
     private static final String TAG = "PhoneStatusBarPolicy";
@@ -119,7 +119,7 @@
     private final DataSaverController mDataSaver;
     private final ZenModeController mZenController;
     private final DeviceProvisionedController mProvisionedController;
-    private final KeyguardMonitor mKeyguardMonitor;
+    private final KeyguardStateController mKeyguardStateController;
     private final LocationController mLocationController;
     private final PrivacyItemController mPrivacyItemController;
     private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class);
@@ -152,7 +152,7 @@
         mDataSaver = Dependency.get(DataSaverController.class);
         mZenController = Dependency.get(ZenModeController.class);
         mProvisionedController = Dependency.get(DeviceProvisionedController.class);
-        mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+        mKeyguardStateController = Dependency.get(KeyguardStateController.class);
         mLocationController = Dependency.get(LocationController.class);
         mPrivacyItemController = Dependency.get(PrivacyItemController.class);
         mSensorPrivacyController = Dependency.get(SensorPrivacyController.class);
@@ -256,7 +256,7 @@
         mHotspot.addCallback(mHotspotCallback);
         mNextAlarmController.addCallback(mNextAlarmCallback);
         mDataSaver.addCallback(this);
-        mKeyguardMonitor.addCallback(this);
+        mKeyguardStateController.addCallback(this);
         mPrivacyItemController.addCallback(this);
         mSensorPrivacyController.addCallback(mSensorPrivacyListener);
         mLocationController.addCallback(this);
@@ -472,8 +472,8 @@
                 boolean isManagedProfile = mUserManager.isManagedProfile(userId);
                 mHandler.post(() -> {
                     final boolean showIcon;
-                    if (isManagedProfile &&
-                            (!mKeyguardMonitor.isShowing() || mKeyguardMonitor.isOccluded())) {
+                    if (isManagedProfile && (!mKeyguardStateController.isShowing()
+                            || mKeyguardStateController.isOccluded())) {
                         showIcon = true;
                         mIconController.setIcon(mSlotManagedProfile,
                                 R.drawable.stat_sys_managed_profile_status,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/RegionSamplingHelper.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/RegionSamplingHelper.java
index c1ff572..1a6b415 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/RegionSamplingHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/RegionSamplingHelper.java
@@ -127,6 +127,11 @@
         updateSamplingListener();
     }
 
+    void stopAndDestroy() {
+        stop();
+        mSamplingListener.destroy();
+    }
+
     @Override
     public void onViewAttachedToWindow(View view) {
         updateSamplingListener();
@@ -134,9 +139,7 @@
 
     @Override
     public void onViewDetachedFromWindow(View view) {
-        // isAttachedToWindow is only changed after this call to the listeners, so let's post it
-        // instead
-        postUpdateSamplingListener();
+        stopAndDestroy();
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
index 8c95b84..5ba19cc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -41,13 +41,14 @@
 import com.android.internal.util.function.TriConsumer;
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.keyguard.KeyguardUpdateMonitorCallback;
+import com.android.systemui.DejankUtils;
 import com.android.systemui.Dependency;
 import com.android.systemui.Dumpable;
 import com.android.systemui.R;
 import com.android.systemui.colorextraction.SysuiColorExtractor;
 import com.android.systemui.statusbar.ScrimView;
 import com.android.systemui.statusbar.notification.stack.ViewState;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.util.AlarmTimeout;
 import com.android.systemui.util.wakelock.DelayedWakeLock;
 import com.android.systemui.util.wakelock.WakeLock;
@@ -129,7 +130,7 @@
     protected final ScrimView mScrimBehind;
     protected final ScrimView mScrimForBubble;
 
-    private final UnlockMethodCache mUnlockMethodCache;
+    private final KeyguardStateController mKeyguardStateController;
     private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
     private final DozeParameters mDozeParameters;
     private final AlarmTimeout mTimeTicker;
@@ -187,7 +188,7 @@
     public ScrimController(ScrimView scrimBehind, ScrimView scrimInFront, ScrimView scrimForBubble,
             TriConsumer<ScrimState, Float, GradientColors> scrimStateListener,
             Consumer<Integer> scrimVisibleListener, DozeParameters dozeParameters,
-            AlarmManager alarmManager, KeyguardMonitor keyguardMonitor) {
+            AlarmManager alarmManager, KeyguardStateController keyguardStateController) {
         mScrimBehind = scrimBehind;
         mScrimInFront = scrimInFront;
         mScrimForBubble = scrimForBubble;
@@ -196,8 +197,8 @@
         mScrimVisibleListener = scrimVisibleListener;
 
         mContext = scrimBehind.getContext();
-        mUnlockMethodCache = UnlockMethodCache.getInstance(mContext);
-        mDarkenWhileDragging = !mUnlockMethodCache.canSkipBouncer();
+        mKeyguardStateController = keyguardStateController;
+        mDarkenWhileDragging = !mKeyguardStateController.canDismissLockScreen();
         mKeyguardUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
         mKeyguardVisibilityCallback = new KeyguardVisibilityCallback();
         mKeyguardUpdateMonitor.registerCallback(mKeyguardVisibilityCallback);
@@ -210,11 +211,11 @@
         // to make sure that text on top of it is legible.
         mScrimBehindAlpha = mScrimBehindAlphaResValue;
         mDozeParameters = dozeParameters;
-        keyguardMonitor.addCallback(new KeyguardMonitor.Callback() {
+        keyguardStateController.addCallback(new KeyguardStateController.Callback() {
             @Override
             public void onKeyguardFadingAwayChanged() {
-                setKeyguardFadingAway(keyguardMonitor.isKeyguardFadingAway(),
-                        keyguardMonitor.getKeyguardFadingAwayDuration());
+                setKeyguardFadingAway(keyguardStateController.isKeyguardFadingAway(),
+                        keyguardStateController.getKeyguardFadingAwayDuration());
             }
         });
 
@@ -311,10 +312,12 @@
         // Docking pulses may take a long time, wallpapers should also fade away after a while.
         mWallpaperVisibilityTimedOut = false;
         if (shouldFadeAwayWallpaper()) {
-            mTimeTicker.schedule(mDozeParameters.getWallpaperAodDuration(),
-                    AlarmTimeout.MODE_IGNORE_IF_SCHEDULED);
+            DejankUtils.postAfterTraversal(() -> {
+                mTimeTicker.schedule(mDozeParameters.getWallpaperAodDuration(),
+                        AlarmTimeout.MODE_IGNORE_IF_SCHEDULED);
+            });
         } else {
-            mTimeTicker.cancel();
+            DejankUtils.postAfterTraversal(mTimeTicker::cancel);
         }
 
         if (mKeyguardUpdateMonitor.needsSlowUnlockTransition() && mState == ScrimState.UNLOCKED) {
@@ -367,7 +370,7 @@
 
     public void onTrackingStarted() {
         mTracking = true;
-        mDarkenWhileDragging = !mUnlockMethodCache.canSkipBouncer();
+        mDarkenWhileDragging = !mKeyguardStateController.canDismissLockScreen();
     }
 
     public void onExpandingFinished() {
@@ -430,8 +433,10 @@
             // and docking.
             if (mWallpaperVisibilityTimedOut) {
                 mWallpaperVisibilityTimedOut = false;
-                mTimeTicker.schedule(mDozeParameters.getWallpaperAodDuration(),
-                        AlarmTimeout.MODE_IGNORE_IF_SCHEDULED);
+                DejankUtils.postAfterTraversal(() -> {
+                    mTimeTicker.schedule(mDozeParameters.getWallpaperAodDuration(),
+                            AlarmTimeout.MODE_IGNORE_IF_SCHEDULED);
+                });
             }
         }
     }
@@ -473,11 +478,11 @@
             if (mDarkenWhileDragging) {
                 mBehindAlpha = MathUtils.lerp(GRADIENT_SCRIM_ALPHA_BUSY, alphaBehind,
                         interpolatedFract);
-                mInFrontAlpha = 0;
+                mInFrontAlpha = mState.getFrontAlpha();
             } else {
                 mBehindAlpha = MathUtils.lerp(0 /* start */, alphaBehind,
                         interpolatedFract);
-                mInFrontAlpha = 0;
+                mInFrontAlpha = mState.getFrontAlpha();
             }
             mBehindTint = ColorUtils.blendARGB(ScrimState.BOUNCER.getBehindTint(),
                     mState.getBehindTint(), interpolatedFract);
@@ -503,13 +508,14 @@
      * device is dozing when the light sensor is on.
      */
     public void setAodFrontScrimAlpha(float alpha) {
-        if (mState == ScrimState.AOD && mDozeParameters.getAlwaysOn()
-                && mInFrontAlpha != alpha) {
+        if (((mState == ScrimState.AOD && mDozeParameters.getAlwaysOn())
+                || mState == ScrimState.PULSING) && mInFrontAlpha != alpha) {
             mInFrontAlpha = alpha;
             updateScrims();
         }
 
         mState.AOD.setAodFrontScrimAlpha(alpha);
+        mState.PULSING.setAodFrontScrimAlpha(alpha);
     }
 
     /**
@@ -753,6 +759,16 @@
     }
 
     private void onFinished(Callback callback) {
+        if (!hasReachedFinalState(mScrimBehind)
+            || !hasReachedFinalState(mScrimInFront)
+            || !hasReachedFinalState(mScrimForBubble)) {
+            if (callback != null && callback != mCallback) {
+                // Since we only notify the callback that we're finished once everything has
+                // finished, we need to make sure that any changing callbacks are also invoked
+                callback.onFinished();
+            }
+            return;
+        }
         if (mWakeLockHeld) {
             mWakeLock.release(TAG);
             mWakeLockHeld = false;
@@ -772,9 +788,17 @@
             mInFrontTint = Color.TRANSPARENT;
             mBehindTint = Color.TRANSPARENT;
             mBubbleTint = Color.TRANSPARENT;
+            updateScrimColor(mScrimInFront, mInFrontAlpha, mInFrontTint);
+            updateScrimColor(mScrimBehind, mBehindAlpha, mBehindTint);
+            updateScrimColor(mScrimForBubble, mBubbleAlpha, mBubbleTint);
         }
     }
 
+    private boolean hasReachedFinalState(ScrimView scrim) {
+        return scrim.getViewAlpha() == getCurrentScrimAlpha(scrim)
+                && scrim.getTint() == getCurrentScrimTint(scrim);
+    }
+
     private boolean isAnimating(View scrim) {
         return scrim.getTag(TAG_KEY_ANIM) != null;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
index c9acbad..7463c7c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
@@ -139,7 +139,7 @@
     PULSING(5) {
         @Override
         public void prepare(ScrimState previousState) {
-            mFrontAlpha = 0f;
+            mFrontAlpha = mAodFrontScrimAlpha;
             mBubbleAlpha = 0f;
             mBehindTint = Color.BLACK;
             mFrontTint = Color.BLACK;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 7bc849d..2b80d22 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -25,7 +25,6 @@
 import static android.app.StatusBarManager.windowStateToString;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY;
 
-import static com.android.systemui.DejankUtils.whitelistIpcs;
 import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME;
 import static com.android.systemui.Dependency.BG_HANDLER;
 import static com.android.systemui.Dependency.MAIN_HANDLER;
@@ -147,10 +146,12 @@
 import com.android.systemui.UiOffloadThread;
 import com.android.systemui.appops.AppOpsController;
 import com.android.systemui.assist.AssistManager;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.bubbles.BubbleController;
 import com.android.systemui.charging.WirelessChargingAnimation;
 import com.android.systemui.classifier.FalsingLog;
 import com.android.systemui.colorextraction.SysuiColorExtractor;
+import com.android.systemui.doze.DozeEvent;
 import com.android.systemui.doze.DozeHost;
 import com.android.systemui.doze.DozeLog;
 import com.android.systemui.doze.DozeReceiver;
@@ -197,6 +198,7 @@
 import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
 import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
 import com.android.systemui.statusbar.notification.DynamicPrivacyController;
+import com.android.systemui.statusbar.notification.NotifPipelineInitializer;
 import com.android.systemui.statusbar.notification.NotificationActivityStarter;
 import com.android.systemui.statusbar.notification.NotificationAlertingManager;
 import com.android.systemui.statusbar.notification.NotificationClicker;
@@ -208,11 +210,11 @@
 import com.android.systemui.statusbar.notification.VisualStabilityManager;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
-import com.android.systemui.statusbar.phone.UnlockMethodCache.OnUnlockMethodChangedListener;
 import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.BatteryController.BatteryStateChangeCallback;
 import com.android.systemui.statusbar.policy.BrightnessMirrorController;
@@ -222,7 +224,7 @@
 import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
 import com.android.systemui.statusbar.policy.ExtensionController;
 import com.android.systemui.statusbar.policy.HeadsUpManager;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
@@ -242,11 +244,13 @@
 
 import javax.inject.Inject;
 import javax.inject.Named;
+import javax.inject.Singleton;
 
 import dagger.Subcomponent;
 
+@Singleton
 public class StatusBar extends SystemUI implements DemoMode,
-        ActivityStarter, OnUnlockMethodChangedListener,
+        ActivityStarter, KeyguardStateController.Callback,
         OnHeadsUpChangedListener, CommandQueue.Callbacks, ZenModeController.Callback,
         ColorExtractor.OnColorsChangedListener, ConfigurationListener,
         StatusBarStateController.StateListener, ShadeController,
@@ -345,22 +349,20 @@
     private BrightnessMirrorController mBrightnessMirrorController;
     private boolean mBrightnessMirrorVisible;
     protected BiometricUnlockController mBiometricUnlockController;
-    private LightBarController mLightBarController;
+    private final LightBarController mLightBarController;
     protected LockscreenWallpaper mLockscreenWallpaper;
-    @VisibleForTesting
-    protected AutoHideController mAutoHideController;
+    private final AutoHideController mAutoHideController;
 
     private int mNaturalBarHeight = -1;
 
     private final Point mCurrentDisplaySize = new Point();
 
+    protected StatusBarWindowViewController mStatusBarWindowViewController;
     protected StatusBarWindowView mStatusBarWindow;
     protected PhoneStatusBarView mStatusBarView;
     private int mStatusBarWindowState = WINDOW_STATE_SHOWING;
     protected StatusBarWindowController mStatusBarWindowController;
-    protected UnlockMethodCache mUnlockMethodCache;
-    @VisibleForTesting
-    KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+    private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
     @VisibleForTesting
     DozeServiceHost mDozeServiceHost = new DozeServiceHost();
     private boolean mWakeUpComingFromTouch;
@@ -368,27 +370,23 @@
 
     private final Object mQueueLock = new Object();
 
-    protected StatusBarIconController mIconController;
-    @Inject
-    InjectionInflationController mInjectionInflater;
-    @Inject
-    PulseExpansionHandler mPulseExpansionHandler;
-    @Inject
-    NotificationWakeUpCoordinator mWakeUpCoordinator;
-    @Inject
-    KeyguardBypassController mKeyguardBypassController;
-    @Inject
-    protected HeadsUpManagerPhone mHeadsUpManager;
-    @Inject
-    DynamicPrivacyController mDynamicPrivacyController;
-    @Inject
-    BypassHeadsUpNotifier mBypassHeadsUpNotifier;
-    @Nullable
-    @Inject
-    protected KeyguardLiftController mKeyguardLiftController;
-    @Inject
-    @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME)
-    boolean mAllowNotificationLongPress;
+    private final StatusBarIconController mIconController;
+    private final DozeLog mDozeLog;
+    private final InjectionInflationController mInjectionInflater;
+    private final PulseExpansionHandler mPulseExpansionHandler;
+    private final NotificationWakeUpCoordinator mWakeUpCoordinator;
+    private final KeyguardBypassController mKeyguardBypassController;
+    private final KeyguardStateController mKeyguardStateController;
+    private final HeadsUpManagerPhone mHeadsUpManager;
+    private final DynamicPrivacyController mDynamicPrivacyController;
+    private final BypassHeadsUpNotifier mBypassHeadsUpNotifier;
+    private final boolean mAllowNotificationLongPress;
+    private final NotifPipelineInitializer mNotifPipelineInitializer;
+    private final FalsingManager mFalsingManager;
+    private final BroadcastDispatcher mBroadcastDispatcher;
+    private final ConfigurationController mConfigurationController;
+    private final StatusBarWindowViewController.Builder mStatusBarWindowViewControllerBuilder;
+    private final NotifLog mNotifLog;
 
     // expanded notifications
     protected NotificationPanelView mNotificationPanel; // the sliding/resizing panel within the notification window
@@ -401,8 +399,7 @@
     // RemoteInputView to be activated after unlock
     private View mPendingRemoteInputView;
 
-    private RemoteInputQuickSettingsDisabler mRemoteInputQuickSettingsDisabler =
-            Dependency.get(RemoteInputQuickSettingsDisabler.class);
+    private final RemoteInputQuickSettingsDisabler mRemoteInputQuickSettingsDisabler;
 
     private View mReportRejectedTouch;
 
@@ -411,18 +408,17 @@
     private final int[] mAbsPos = new int[2];
     private final ArrayList<Runnable> mPostCollapseRunnables = new ArrayList<>();
 
-    private NotificationGutsManager mGutsManager;
-    protected NotificationLogger mNotificationLogger;
-    protected NotificationEntryManager mEntryManager;
+    private final NotificationGutsManager mGutsManager;
+    private final NotificationLogger mNotificationLogger;
+    private final NotificationEntryManager mEntryManager;
     private NotificationListController mNotificationListController;
-    private NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
-    protected NotificationViewHierarchyManager mViewHierarchyManager;
-    protected ForegroundServiceController mForegroundServiceController;
-    protected AppOpsController mAppOpsController;
-    protected KeyguardViewMediator mKeyguardViewMediator;
-    private ZenModeController mZenController;
-    private final NotificationAlertingManager mNotificationAlertingManager =
-            Dependency.get(NotificationAlertingManager.class);
+    private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+    private final NotificationViewHierarchyManager mViewHierarchyManager;
+    private final ForegroundServiceController mForegroundServiceController;
+    private final AppOpsController mAppOpsController;
+    private final KeyguardViewMediator mKeyguardViewMediator;
+    private final ZenModeController mZenController;
+    private final NotificationAlertingManager mNotificationAlertingManager;
 
     // for disabling the status bar
     private int mDisabled1 = 0;
@@ -433,7 +429,7 @@
     private final Rect mLastFullscreenStackBounds = new Rect();
     private final Rect mLastDockedStackBounds = new Rect();
 
-    private final DisplayMetrics mDisplayMetrics = Dependency.get(DisplayMetrics.class);
+    private final DisplayMetrics mDisplayMetrics;
 
     // XXX: gesture research
     private final GestureRecorder mGestureRec = DEBUG_GESTURES
@@ -442,7 +438,7 @@
 
     private ScreenPinningRequest mScreenPinningRequest;
 
-    private final MetricsLogger mMetricsLogger = Dependency.get(MetricsLogger.class);
+    private final MetricsLogger mMetricsLogger;
 
     // ensure quick settings is disabled until the current user makes it through the setup wizard
     @VisibleForTesting
@@ -479,14 +475,14 @@
     private ViewMediatorCallback mKeyguardViewMediatorCallback;
     protected ScrimController mScrimController;
     protected DozeScrimController mDozeScrimController;
-    private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class);
+    private final UiOffloadThread mUiOffloadThread;
 
     protected boolean mDozing;
     private boolean mDozingRequested;
 
-    private NotificationMediaManager mMediaManager;
-    protected NotificationLockscreenUserManager mLockscreenUserManager;
-    protected NotificationRemoteInputManager mRemoteInputManager;
+    private final NotificationMediaManager mMediaManager;
+    private final NotificationLockscreenUserManager mLockscreenUserManager;
+    private final NotificationRemoteInputManager mRemoteInputManager;
     private boolean mWallpaperSupported;
 
     private final BroadcastReceiver mWallpaperChangedReceiver = new BroadcastReceiver() {
@@ -545,7 +541,7 @@
                         + "mStatusBarKeyguardViewManager was null");
                 return;
             }
-            if (mKeyguardMonitor.isKeyguardFadingAway()) {
+            if (mKeyguardStateController.isKeyguardFadingAway()) {
                 mStatusBarKeyguardViewManager.onKeyguardFadedAway();
             }
         }
@@ -557,19 +553,18 @@
     };
 
     private KeyguardUserSwitcher mKeyguardUserSwitcher;
-    protected UserSwitcherController mUserSwitcherController;
-    private NetworkController mNetworkController;
-    private KeyguardMonitor mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
-    private BatteryController mBatteryController;
+    private final UserSwitcherController mUserSwitcherController;
+    private final NetworkController mNetworkController;
+    private final BatteryController mBatteryController;
     protected boolean mPanelExpanded;
     private UiModeManager mUiModeManager;
     protected boolean mIsKeyguard;
     private LogMaker mStatusBarStateLog;
     protected NotificationIconAreaController mNotificationIconAreaController;
     @Nullable private View mAmbientIndicationContainer;
-    private SysuiColorExtractor mColorExtractor;
-    private ScreenLifecycle mScreenLifecycle;
-    @VisibleForTesting WakefulnessLifecycle mWakefulnessLifecycle;
+    private final SysuiColorExtractor mColorExtractor;
+    private final ScreenLifecycle mScreenLifecycle;
+    private final WakefulnessLifecycle mWakefulnessLifecycle;
 
     private final View.OnClickListener mGoToLockedShadeListener = v -> {
         if (mState == StatusBarState.KEYGUARD) {
@@ -578,9 +573,7 @@
         }
     };
     private boolean mNoAnimationOnNextBarModeChange;
-    protected FalsingManager mFalsingManager;
-    private final SysuiStatusBarStateController mStatusBarStateController =
-            (SysuiStatusBarStateController) Dependency.get(StatusBarStateController.class);
+    private final SysuiStatusBarStateController mStatusBarStateController;
 
     private final KeyguardUpdateMonitorCallback mUpdateCallback =
             new KeyguardUpdateMonitorCallback() {
@@ -594,26 +587,22 @@
                 @Override
                 public void onStrongAuthStateChanged(int userId) {
                     super.onStrongAuthStateChanged(userId);
-                    mEntryManager.updateNotifications();
+                    mEntryManager.updateNotifications("onStrongAuthStateChanged");
                 }
             };
     private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
 
     private HeadsUpAppearanceController mHeadsUpAppearanceController;
     private boolean mVibrateOnOpening;
-    private VibratorHelper mVibratorHelper;
+    private final VibratorHelper mVibratorHelper;
     private ActivityLaunchAnimator mActivityLaunchAnimator;
     protected StatusBarNotificationPresenter mPresenter;
     private NotificationActivityStarter mNotificationActivityStarter;
     private boolean mPulsing;
-    protected BubbleController mBubbleController;
-    private final BubbleController.BubbleExpandListener mBubbleExpandListener =
-            (isExpanding, key) -> {
-                mEntryManager.updateNotifications();
-                updateScrimController();
-            };
+    private final BubbleController mBubbleController;
+    private final BubbleController.BubbleExpandListener mBubbleExpandListener;
+
     private ActivityIntentHelper mActivityIntentHelper;
-    private ShadeController mShadeController;
 
     @Override
     public void onActiveStateChanged(int code, int uid, String packageName, boolean active) {
@@ -629,40 +618,131 @@
             AppOpsManager.OP_COARSE_LOCATION,
             AppOpsManager.OP_FINE_LOCATION};
 
+    @Inject
+    public StatusBar(
+            LightBarController lightBarController,
+            AutoHideController autoHideController,
+            KeyguardUpdateMonitor keyguardUpdateMonitor,
+            StatusBarIconController statusBarIconController,
+            DozeLog dozeLog,
+            InjectionInflationController injectionInflationController,
+            PulseExpansionHandler pulseExpansionHandler,
+            NotificationWakeUpCoordinator notificationWakeUpCoordinator,
+            KeyguardBypassController keyguardBypassController,
+            KeyguardStateController keyguardStateController,
+            HeadsUpManagerPhone headsUpManagerPhone,
+            DynamicPrivacyController dynamicPrivacyController,
+            BypassHeadsUpNotifier bypassHeadsUpNotifier,
+            @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowNotificationLongPress,
+            NotifPipelineInitializer notifPipelineInitializer,
+            FalsingManager falsingManager,
+            BroadcastDispatcher broadcastDispatcher,
+            RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler,
+            NotificationGutsManager notificationGutsManager,
+            NotificationLogger notificationLogger,
+            NotificationEntryManager notificationEntryManager,
+            NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+            NotificationViewHierarchyManager notificationViewHierarchyManager,
+            ForegroundServiceController foregroundServiceController,
+            AppOpsController appOpsController,
+            KeyguardViewMediator keyguardViewMediator,
+            ZenModeController zenModeController,
+            NotificationAlertingManager notificationAlertingManager,
+            DisplayMetrics displayMetrics,
+            MetricsLogger metricsLogger,
+            UiOffloadThread uiOffloadThread,
+            NotificationMediaManager notificationMediaManager,
+            NotificationLockscreenUserManager lockScreenUserManager,
+            NotificationRemoteInputManager remoteInputManager,
+            UserSwitcherController userSwitcherController,
+            NetworkController networkController,
+            BatteryController batteryController,
+            SysuiColorExtractor colorExtractor,
+            ScreenLifecycle screenLifecycle,
+            WakefulnessLifecycle wakefulnessLifecycle,
+            SysuiStatusBarStateController statusBarStateController,
+            VibratorHelper vibratorHelper,
+            BubbleController bubbleController,
+            NotificationGroupManager groupManager,
+            NotificationGroupAlertTransferHelper groupAlertTransferHelper,
+            VisualStabilityManager visualStabilityManager,
+            DeviceProvisionedController deviceProvisionedController,
+            NavigationBarController navigationBarController,
+            AssistManager assistManager,
+            NotificationListener notificationListener,
+            ConfigurationController configurationController,
+            StatusBarWindowController statusBarWindowController,
+            StatusBarWindowViewController.Builder statusBarWindowViewControllerBuilder,
+            NotifLog notifLog) {
+        mLightBarController = lightBarController;
+        mAutoHideController = autoHideController;
+        mKeyguardUpdateMonitor = keyguardUpdateMonitor;
+        mIconController = statusBarIconController;
+        mDozeLog = dozeLog;
+        mInjectionInflater = injectionInflationController;
+        mPulseExpansionHandler = pulseExpansionHandler;
+        mWakeUpCoordinator = notificationWakeUpCoordinator;
+        mKeyguardBypassController = keyguardBypassController;
+        mKeyguardStateController = keyguardStateController;
+        mHeadsUpManager = headsUpManagerPhone;
+        mDynamicPrivacyController = dynamicPrivacyController;
+        mBypassHeadsUpNotifier = bypassHeadsUpNotifier;
+        mAllowNotificationLongPress = allowNotificationLongPress;
+        mNotifPipelineInitializer = notifPipelineInitializer;
+        mFalsingManager = falsingManager;
+        mBroadcastDispatcher = broadcastDispatcher;
+        mRemoteInputQuickSettingsDisabler = remoteInputQuickSettingsDisabler;
+        mGutsManager = notificationGutsManager;
+        mNotificationLogger = notificationLogger;
+        mEntryManager = notificationEntryManager;
+        mNotificationInterruptionStateProvider = notificationInterruptionStateProvider;
+        mViewHierarchyManager = notificationViewHierarchyManager;
+        mForegroundServiceController = foregroundServiceController;
+        mAppOpsController = appOpsController;
+        mKeyguardViewMediator = keyguardViewMediator;
+        mZenController = zenModeController;
+        mNotificationAlertingManager = notificationAlertingManager;
+        mDisplayMetrics = displayMetrics;
+        mMetricsLogger = metricsLogger;
+        mUiOffloadThread = uiOffloadThread;
+        mMediaManager = notificationMediaManager;
+        mLockscreenUserManager = lockScreenUserManager;
+        mRemoteInputManager = remoteInputManager;
+        mUserSwitcherController = userSwitcherController;
+        mNetworkController = networkController;
+        mBatteryController = batteryController;
+        mColorExtractor = colorExtractor;
+        mScreenLifecycle = screenLifecycle;
+        mWakefulnessLifecycle = wakefulnessLifecycle;
+        mStatusBarStateController = statusBarStateController;
+        mVibratorHelper = vibratorHelper;
+        mBubbleController = bubbleController;
+        mGroupManager = groupManager;
+        mGroupAlertTransferHelper = groupAlertTransferHelper;
+        mVisualStabilityManager = visualStabilityManager;
+        mDeviceProvisionedController = deviceProvisionedController;
+        mNavigationBarController = navigationBarController;
+        mAssistManager = assistManager;
+        mNotificationListener = notificationListener;
+        mConfigurationController = configurationController;
+        mStatusBarWindowController = statusBarWindowController;
+        mStatusBarWindowViewControllerBuilder = statusBarWindowViewControllerBuilder;
+        mNotifLog = notifLog;
+
+        mBubbleExpandListener =
+                (isExpanding, key) -> {
+                    mEntryManager.updateNotifications("onBubbleExpandChanged");
+                    updateScrimController();
+                };
+    }
+
     @Override
     public void start() {
-        mGroupManager = Dependency.get(NotificationGroupManager.class);
-        mGroupAlertTransferHelper = Dependency.get(NotificationGroupAlertTransferHelper.class);
-        mVisualStabilityManager = Dependency.get(VisualStabilityManager.class);
-        mNotificationLogger = Dependency.get(NotificationLogger.class);
-        mRemoteInputManager = Dependency.get(NotificationRemoteInputManager.class);
-        mNotificationListener =  Dependency.get(NotificationListener.class);
         mNotificationListener.registerAsSystemService();
-        mNetworkController = Dependency.get(NetworkController.class);
-        mUserSwitcherController = Dependency.get(UserSwitcherController.class);
-        mScreenLifecycle = Dependency.get(ScreenLifecycle.class);
         mScreenLifecycle.addObserver(mScreenObserver);
-        mWakefulnessLifecycle = Dependency.get(WakefulnessLifecycle.class);
         mWakefulnessLifecycle.addObserver(mWakefulnessObserver);
-        mBatteryController = Dependency.get(BatteryController.class);
-        mAssistManager = Dependency.get(AssistManager.class);
         mUiModeManager = mContext.getSystemService(UiModeManager.class);
-        mLockscreenUserManager = Dependency.get(NotificationLockscreenUserManager.class);
-        mGutsManager = Dependency.get(NotificationGutsManager.class);
-        mMediaManager = Dependency.get(NotificationMediaManager.class);
-        mEntryManager = Dependency.get(NotificationEntryManager.class);
         mBypassHeadsUpNotifier.setUp(mEntryManager);
-        mNotificationInterruptionStateProvider =
-                Dependency.get(NotificationInterruptionStateProvider.class);
-        mViewHierarchyManager = Dependency.get(NotificationViewHierarchyManager.class);
-        mForegroundServiceController = Dependency.get(ForegroundServiceController.class);
-        mAppOpsController = Dependency.get(AppOpsController.class);
-        mZenController = Dependency.get(ZenModeController.class);
-        mKeyguardViewMediator = getComponent(KeyguardViewMediator.class);
-        mColorExtractor = Dependency.get(SysuiColorExtractor.class);
-        mDeviceProvisionedController = Dependency.get(DeviceProvisionedController.class);
-        mNavigationBarController = Dependency.get(NavigationBarController.class);
-        mBubbleController = Dependency.get(BubbleController.class);
         mBubbleController.setExpandListener(mBubbleExpandListener);
         mActivityIntentHelper = new ActivityIntentHelper(mContext);
         KeyguardSliceProvider sliceProvider = KeyguardSliceProvider.getAttachedInstance();
@@ -687,7 +767,6 @@
 
         mVibrateOnOpening = mContext.getResources().getBoolean(
                 R.bool.config_vibrateOnIconAnimation);
-        mVibratorHelper = Dependency.get(VibratorHelper.class);
 
         DateTimeView.setReceiverHandler(Dependency.get(Dependency.TIME_TICK_HANDLER));
         putComponent(StatusBar.class, this);
@@ -701,7 +780,6 @@
                 mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
 
         mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
-        mKeyguardUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
         mKeyguardUpdateMonitor.setKeyguardBypassController(mKeyguardBypassController);
         mBarService = IStatusBarService.Stub.asInterface(
                 ServiceManager.getService(Context.STATUS_BAR_SERVICE));
@@ -709,7 +787,6 @@
         mRecents = getComponent(Recents.class);
 
         mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
-        mFalsingManager = Dependency.get(FalsingManager.class);
 
         // Connect in to the status bar manager service
         mCommandQueue = getComponent(CommandQueue.class);
@@ -786,8 +863,7 @@
         mIconPolicy = new PhoneStatusBarPolicy(mContext, mIconController);
         mSignalPolicy = new StatusBarSignalPolicy(mContext, mIconController);
 
-        mUnlockMethodCache = UnlockMethodCache.getInstance(mContext);
-        mUnlockMethodCache.addListener(this);
+        mKeyguardStateController.addCallback(this);
         startKeyguard();
 
         mKeyguardUpdateMonitor.registerCallback(mUpdateCallback);
@@ -797,7 +873,7 @@
 
         Dependency.get(ActivityStarterDelegate.class).setActivityStarterImpl(this);
 
-        Dependency.get(ConfigurationController.class).addCallback(this);
+        mConfigurationController.addCallback(this);
 
         // set the initial view visibility
         Dependency.get(InitController.class).addPostInitTask(this::updateAreThereNotifications);
@@ -817,8 +893,7 @@
         updateTheme();
 
         inflateStatusBarWindow(context);
-        mStatusBarWindow.setService(this);
-        mStatusBarWindow.setBypassController(mKeyguardBypassController);
+        mStatusBarWindowViewController.setService(this);
         mStatusBarWindow.setOnTouchListener(getStatusBarWindowTouchListener());
 
         // TODO: Deal with the ugliness that comes from having some of the statusbar broken out
@@ -830,6 +905,8 @@
         NotificationListContainer notifListContainer = (NotificationListContainer) mStackScroller;
         mNotificationLogger.setUpWithContainer(notifListContainer);
 
+        // TODO: make this injectable. Currently that would create a circular dependency between
+        // NotificationIconAreaController and StatusBar.
         mNotificationIconAreaController = SystemUIFactory.getInstance()
                 .createNotificationIconAreaController(context, this,
                         mWakeUpCoordinator, mKeyguardBypassController,
@@ -884,7 +961,7 @@
                             mStatusBarStateController, mKeyguardBypassController,
                             mWakeUpCoordinator);
                     mHeadsUpAppearanceController.readFrom(oldController);
-                    mStatusBarWindow.setStatusBarView(mStatusBarView);
+                    mStatusBarWindowViewController.setStatusBarView(mStatusBarView);
                     updateAreThereNotifications();
                     checkBarModes();
                 }).getFragmentManager()
@@ -892,10 +969,9 @@
                 .replace(R.id.status_bar_container, new CollapsedStatusBarFragment(),
                         CollapsedStatusBarFragment.TAG)
                 .commit();
-        mIconController = Dependency.get(StatusBarIconController.class);
 
         mHeadsUpManager.setUp(mStatusBarWindow, mGroupManager, this, mVisualStabilityManager);
-        Dependency.get(ConfigurationController.class).addCallback(mHeadsUpManager);
+        mConfigurationController.addCallback(mHeadsUpManager);
         mHeadsUpManager.addListener(this);
         mHeadsUpManager.addListener(mNotificationPanel);
         mHeadsUpManager.addListener(mGroupManager);
@@ -938,11 +1014,8 @@
             }
         });
 
-        mAutoHideController = Dependency.get(AutoHideController.class);
         mAutoHideController.setStatusBar(this);
 
-        mLightBarController = Dependency.get(LightBarController.class);
-
         ScrimView scrimBehind = mStatusBarWindow.findViewById(R.id.scrim_behind);
         ScrimView scrimInFront = mStatusBarWindow.findViewById(R.id.scrim_in_front);
         ScrimView scrimForBubble = mStatusBarWindow.findViewById(R.id.scrim_for_bubble);
@@ -955,14 +1028,15 @@
                         mStatusBarWindowController.setScrimsVisibility(scrimsVisible);
                     }
                     if (mStatusBarWindow != null) {
-                        mStatusBarWindow.onScrimVisibilityChanged(scrimsVisible);
+                        mStatusBarWindowViewController.onScrimVisibilityChanged(scrimsVisible);
                     }
                 }, DozeParameters.getInstance(mContext),
                 mContext.getSystemService(AlarmManager.class),
-                mKeyguardMonitor);
+                mKeyguardStateController);
         mNotificationPanel.initDependencies(this, mGroupManager, mNotificationShelf,
                 mHeadsUpManager, mNotificationIconAreaController, mScrimController);
-        mDozeScrimController = new DozeScrimController(DozeParameters.getInstance(context));
+        mDozeScrimController = new DozeScrimController(DozeParameters.getInstance(context),
+                mDozeLog);
 
         BackDropView backdrop = mStatusBarWindow.findViewById(R.id.backdrop);
         mMediaManager.setup(backdrop, backdrop.findViewById(R.id.backdrop_front),
@@ -977,7 +1051,7 @@
         }
 
         mNotificationPanel.setLaunchAffordanceListener(
-                mStatusBarWindow::onShowingLaunchAffordanceChanged);
+                mStatusBarWindowViewController::onShowingLaunchAffordanceChanged);
 
         // Set up the quick settings tile panel
         View container = mStatusBarWindow.findViewById(R.id.qs_frame);
@@ -1032,11 +1106,10 @@
             });
         }
 
-        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
-        if (!pm.isScreenOn()) {
+        if (!mPowerManager.isScreenOn()) {
             mBroadcastReceiver.onReceive(mContext, new Intent(Intent.ACTION_SCREEN_OFF));
         }
-        mGestureWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
+        mGestureWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
                 "GestureWakeLock");
         mVibrator = mContext.getSystemService(Vibrator.class);
         int[] pattern = mContext.getResources().getIntArray(
@@ -1047,11 +1120,7 @@
         }
 
         // receive broadcasts
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
-        filter.addAction(Intent.ACTION_SCREEN_OFF);
-        filter.addAction(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
-        context.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
+        registerBroadcastReceiver();
 
         IntentFilter demoFilter = new IntentFilter();
         if (DEBUG_MEDIA_FAKE_ARTWORK) {
@@ -1072,6 +1141,15 @@
         ThreadedRenderer.overrideProperty("ambientRatio", String.valueOf(1.5f));
     }
 
+    @VisibleForTesting
+    protected void registerBroadcastReceiver() {
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
+        filter.addAction(Intent.ACTION_SCREEN_OFF);
+        filter.addAction(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
+        mBroadcastDispatcher.registerReceiver(mBroadcastReceiver, filter, null, UserHandle.ALL);
+    }
+
     protected QS createDefaultQSFragment() {
         return FragmentHostManager.get(mStatusBarWindow).create(QSFragment.class);
     }
@@ -1079,7 +1157,7 @@
     private void setUpPresenter() {
         // Set up the initial notification state.
         mActivityLaunchAnimator = new ActivityLaunchAnimator(
-                mStatusBarWindow, this, mNotificationPanel,
+                mStatusBarWindowViewController, this, mNotificationPanel,
                 (NotificationListContainer) mStackScroller);
 
         final NotificationRowBinderImpl rowBinder =
@@ -1087,7 +1165,8 @@
                         mContext,
                         mAllowNotificationLongPress,
                         mKeyguardBypassController,
-                        mStatusBarStateController);
+                        mStatusBarStateController,
+                        mNotifLog);
 
         mPresenter = new StatusBarNotificationPresenter(mContext, mNotificationPanel,
                 mHeadsUpManager, mStatusBarWindow, mStackScroller, mDozeScrimController,
@@ -1108,7 +1187,6 @@
         final StatusBarRemoteInputCallback mStatusBarRemoteInputCallback =
                 (StatusBarRemoteInputCallback) Dependency.get(
                         NotificationRemoteInputManager.Callback.class);
-        mShadeController = Dependency.get(ShadeController.class);
         final ActivityStarter activityStarter = Dependency.get(ActivityStarter.class);
 
         mNotificationActivityStarter = new StatusBarNotificationActivityStarter(mContext,
@@ -1116,7 +1194,7 @@
                 mHeadsUpManager, activityStarter, mActivityLaunchAnimator,
                 mBarService, mStatusBarStateController, mKeyguardManager, mDreamManager,
                 mRemoteInputManager, mStatusBarRemoteInputCallback, mGroupManager,
-                mLockscreenUserManager, mShadeController, mKeyguardMonitor,
+                mLockscreenUserManager, this, mKeyguardStateController,
                 mNotificationInterruptionStateProvider, mMetricsLogger,
                 new LockPatternUtils(mContext), Dependency.get(MAIN_HANDLER),
                 Dependency.get(BG_HANDLER), mActivityIntentHelper, mBubbleController);
@@ -1125,10 +1203,12 @@
 
         mEntryManager.setRowBinder(rowBinder);
         rowBinder.setNotificationClicker(new NotificationClicker(
-                this, Dependency.get(BubbleController.class), mNotificationActivityStarter));
+                this, mBubbleController, mNotificationActivityStarter));
 
         mGroupAlertTransferHelper.bind(mEntryManager, mGroupManager);
         mNotificationListController.bind();
+
+        mNotifPipelineInitializer.initialize(mNotificationListener);
     }
 
     /**
@@ -1153,8 +1233,8 @@
     @Override
     public void wakeUpIfDozing(long time, View where, String why) {
         if (mDozing) {
-            PowerManager pm = mContext.getSystemService(PowerManager.class);
-            pm.wakeUp(time, PowerManager.WAKE_REASON_GESTURE, "com.android.systemui:" + why);
+            mPowerManager.wakeUp(
+                    time, PowerManager.WAKE_REASON_GESTURE, "com.android.systemui:" + why);
             mWakeUpComingFromTouch = true;
             where.getLocationInWindow(mTmpInt2);
             mWakeUpTouchLocation = new PointF(mTmpInt2[0] + where.getWidth() / 2,
@@ -1250,17 +1330,20 @@
     protected void inflateStatusBarWindow(Context context) {
         mStatusBarWindow = (StatusBarWindowView) mInjectionInflater.injectable(
                 LayoutInflater.from(context)).inflate(R.layout.super_status_bar, null);
+        mStatusBarWindowViewController = mStatusBarWindowViewControllerBuilder
+                .setStatusBarWindowView(mStatusBarWindow)
+                .setShadeController(this)
+                .build();
     }
 
     protected void startKeyguard() {
         Trace.beginSection("StatusBar#startKeyguard");
-        KeyguardViewMediator keyguardViewMediator = getComponent(KeyguardViewMediator.class);
         mBiometricUnlockController = new BiometricUnlockController(mContext,
-                mDozeScrimController, keyguardViewMediator,
-                mScrimController, this, UnlockMethodCache.getInstance(mContext),
-                new Handler(), mKeyguardUpdateMonitor, mKeyguardBypassController);
+                mDozeScrimController, mKeyguardViewMediator,
+                mScrimController, this, mKeyguardStateController, new Handler(),
+                mKeyguardUpdateMonitor, mKeyguardBypassController);
         putComponent(BiometricUnlockController.class, mBiometricUnlockController);
-        mStatusBarKeyguardViewManager = keyguardViewMediator.registerStatusBar(this,
+        mStatusBarKeyguardViewManager = mKeyguardViewMediator.registerStatusBar(this,
                 getBouncerContainer(), mNotificationPanel, mBiometricUnlockController,
                 mStatusBarWindow.findViewById(R.id.lock_icon_container), mStackScroller,
                 mKeyguardBypassController);
@@ -1270,7 +1353,7 @@
         mRemoteInputManager.getController().addCallback(mStatusBarKeyguardViewManager);
         mDynamicPrivacyController.setStatusBarKeyguardViewManager(mStatusBarKeyguardViewManager);
 
-        mKeyguardViewMediatorCallback = keyguardViewMediator.getViewMediatorCallback();
+        mKeyguardViewMediatorCallback = mKeyguardViewMediator.getViewMediatorCallback();
         mLightBarController.setBiometricUnlockController(mBiometricUnlockController);
         mMediaManager.setBiometricUnlockController(mBiometricUnlockController);
         Dependency.get(KeyguardDismissUtil.class).setDismissHandler(this::executeWhenUnlocked);
@@ -1366,15 +1449,19 @@
         return mZenController.areNotificationsHiddenInShade();
     }
 
-    public void requestNotificationUpdate() {
-        mEntryManager.updateNotifications();
+    /**
+     * Request a notification update
+     * @param reason why we're requesting a notification update
+     */
+    public void requestNotificationUpdate(String reason) {
+        mEntryManager.updateNotifications(reason);
     }
 
     /**
      * Asks {@link KeyguardUpdateMonitor} to run face auth.
      */
     public void requestFaceAuth() {
-        if (!mUnlockMethodCache.canSkipBouncer()) {
+        if (!mKeyguardStateController.canDismissLockScreen()) {
             mKeyguardUpdateMonitor.requestFaceAuth();
         }
     }
@@ -1558,9 +1645,8 @@
         logStateToEventlog();
     }
 
-    @Override  // UnlockMethodCache.OnUnlockMethodChangedListener
-    public void onUnlockMethodStateChanged() {
-        // Unlock method state changed. Notify KeguardMonitor
+    @Override
+    public void onUnlockedChanged() {
         updateKeyguardState();
         logStateToEventlog();
     }
@@ -1609,7 +1695,7 @@
 
     @Override
     public void onHeadsUpStateChanged(NotificationEntry entry, boolean isHeadsUp) {
-        mEntryManager.updateNotifications();
+        mEntryManager.updateNotifications("onHeadsUpStateChanged");
         if (isDozing() && isHeadsUp) {
             entry.setPulseSuppressed(false);
             mDozeServiceHost.fireNotificationPulse(entry);
@@ -1623,10 +1709,6 @@
         }
     }
 
-    public boolean isKeyguardCurrentlySecure() {
-        return !mUnlockMethodCache.canSkipBouncer();
-    }
-
     public void setPanelExpanded(boolean isExpanded) {
         mPanelExpanded = isExpanded;
         updateHideIconsForBouncer(false /* animate */);
@@ -1761,6 +1843,16 @@
         return mPresenter;
     }
 
+    @VisibleForTesting
+    void setBarStateForTest(int state) {
+        mState = state;
+    }
+
+    @VisibleForTesting
+    void setUserSetupForTest(boolean userSetup) {
+        mUserSetup = userSetup;
+    }
+
     /**
      * All changes to the status bar and notifications funnel through here and are batched.
      */
@@ -1818,8 +1910,8 @@
     @Override
     public void handleSystemKey(int key) {
         if (SPEW) Log.d(TAG, "handleNavigationKey: " + key);
-        if (!mCommandQueue.panelsEnabled() || !mKeyguardMonitor.isDeviceInteractive()
-                || mKeyguardMonitor.isShowing() && !mKeyguardMonitor.isOccluded()) {
+        if (!mCommandQueue.panelsEnabled() || !mKeyguardUpdateMonitor.isDeviceInteractive()
+                || mKeyguardStateController.isShowing() && !mKeyguardStateController.isOccluded()) {
             return;
         }
 
@@ -1948,7 +2040,7 @@
             // release focus immediately to kick off focus change transition
             mStatusBarWindowController.setStatusBarFocusable(false);
 
-            mStatusBarWindow.cancelExpandHelper();
+            mStatusBarWindowViewController.cancelExpandHelper();
             mStatusBarView.collapsePanel(true /* animate */, delayed, speedUpFactor);
         } else {
             mBubbleController.collapseStack();
@@ -2339,8 +2431,8 @@
             dumpBarTransitions(pw, "mStatusBarView", mStatusBarView.getBarTransitions());
         }
         pw.println("  StatusBarWindowView: ");
-        if (mStatusBarWindow != null) {
-            mStatusBarWindow.dump(fd, pw, args);
+        if (mStatusBarWindowViewController != null) {
+            mStatusBarWindowViewController.dump(fd, pw, args);
         }
 
         pw.println("  mMediaManager: ");
@@ -2369,7 +2461,7 @@
         final boolean lightWpTheme = mContext.getThemeResId() == R.style.Theme_SystemUI_Light;
         pw.println("    light wallpaper theme: " + lightWpTheme);
 
-        DozeLog.dump(pw);
+        mDozeLog.dump(pw);
 
         if (mBiometricUnlockController != null) {
             mBiometricUnlockController.dump(pw);
@@ -2428,10 +2520,6 @@
             mLightBarController.dump(fd, pw, args);
         }
 
-        if (mUnlockMethodCache != null) {
-            mUnlockMethodCache.dump(pw);
-        }
-
         if (mKeyguardBypassController != null) {
             mKeyguardBypassController.dump(pw);
         }
@@ -2440,7 +2528,7 @@
             mKeyguardUpdateMonitor.dump(fd, pw, args);
         }
 
-        Dependency.get(FalsingManager.class).dump(pw);
+        mFalsingManager.dump(pw);
         FalsingLog.dump(pw);
 
         pw.println("SharedPreferences:");
@@ -2456,7 +2544,6 @@
 
     public void createAndAddWindows(@Nullable RegisterStatusBarResult result) {
         makeStatusBarView(result);
-        mStatusBarWindowController = Dependency.get(StatusBarWindowController.class);
         mStatusBarWindowController.add(mStatusBarWindow, getStatusBarHeight());
     }
 
@@ -2684,7 +2771,7 @@
     public void dismissKeyguardThenExecute(OnDismissAction action, Runnable cancelAction,
             boolean afterKeyguardGone) {
         if (mWakefulnessLifecycle.getWakefulness() == WAKEFULNESS_ASLEEP
-                && mUnlockMethodCache.canSkipBouncer()
+                && mKeyguardStateController.canDismissLockScreen()
                 && !mStatusBarStateController.leaveOpenOnKeyguardHide()
                 && isPulsing()) {
             // Reuse the biometric wake-and-unlock transition if we dismiss keyguard from a pulse.
@@ -2700,7 +2787,6 @@
         }
     }
 
-    // SystemUIService notifies SystemBars of configuration changes, which then calls down here
     @Override
     public void onConfigChanged(Configuration newConfig) {
         updateResources();
@@ -2827,14 +2913,14 @@
         boolean isShowing = mStatusBarKeyguardViewManager.isShowing();
         boolean isOccluded = mStatusBarKeyguardViewManager.isOccluded();
         boolean isBouncerShowing = mStatusBarKeyguardViewManager.isBouncerShowing();
-        boolean isSecure = mUnlockMethodCache.isMethodSecure();
-        boolean canSkipBouncer = mUnlockMethodCache.canSkipBouncer();
+        boolean isSecure = mKeyguardStateController.isMethodSecure();
+        boolean unlocked = mKeyguardStateController.canDismissLockScreen();
         int stateFingerprint = getLoggingFingerprint(mState,
                 isShowing,
                 isOccluded,
                 isBouncerShowing,
                 isSecure,
-                canSkipBouncer);
+                unlocked);
         if (stateFingerprint != mLastLoggedStateFingerprint) {
             if (mStatusBarStateLog == null) {
                 mStatusBarStateLog = new LogMaker(MetricsEvent.VIEW_UNKNOWN);
@@ -2848,7 +2934,7 @@
                     isOccluded ? 1 : 0,
                     isBouncerShowing ? 1 : 0,
                     isSecure ? 1 : 0,
-                    canSkipBouncer ? 1 : 0);
+                    unlocked ? 1 : 0);
             mLastLoggedStateFingerprint = stateFingerprint;
         }
     }
@@ -3048,7 +3134,7 @@
 
     public void showKeyguardImpl() {
         mIsKeyguard = true;
-        if (mKeyguardMonitor.isLaunchTransitionFadingAway()) {
+        if (mKeyguardStateController.isLaunchTransitionFadingAway()) {
             mNotificationPanel.animate().cancel();
             onLaunchTransitionFadingEnded();
         }
@@ -3080,7 +3166,7 @@
         mNotificationPanel.onAffordanceLaunchEnded();
         releaseGestureWakeLock();
         runLaunchTransitionEndRunnable();
-        mKeyguardMonitor.setLaunchTransitionFadingAway(false);
+        mKeyguardStateController.setLaunchTransitionFadingAway(false);
         mPresenter.updateMediaMetaData(true /* metaDataChanged */, true);
     }
 
@@ -3105,7 +3191,7 @@
         mHandler.removeMessages(MSG_LAUNCH_TRANSITION_TIMEOUT);
         mLaunchTransitionEndRunnable = endRunnable;
         Runnable hideRunnable = () -> {
-            mKeyguardMonitor.setLaunchTransitionFadingAway(true);
+            mKeyguardStateController.setLaunchTransitionFadingAway(true);
             if (beforeFading != null) {
                 beforeFading.run();
             }
@@ -3198,7 +3284,7 @@
             if (!mStatusBarStateController.isKeyguardRequested()) {
                 mStatusBarStateController.setLeaveOpenOnKeyguardHide(false);
             }
-            long delay = mKeyguardMonitor.calculateGoingToFullShadeDelay();
+            long delay = mKeyguardStateController.calculateGoingToFullShadeDelay();
             mNotificationPanel.animateToFullShade(delay);
             if (mDraggedDownEntry != null) {
                 mDraggedDownEntry.setUserLocked(false);
@@ -3240,7 +3326,7 @@
     public void keyguardGoingAway() {
         // Treat Keyguard exit animation as an app transition to achieve nice transition for status
         // bar.
-        mKeyguardMonitor.notifyKeyguardGoingAway(true);
+        mKeyguardStateController.notifyKeyguardGoingAway(true);
         mCommandQueue.appTransitionPending(mDisplayId, true /* forced */);
     }
 
@@ -3260,14 +3346,14 @@
         mCommandQueue.appTransitionStarting(mDisplayId,
                     startTime - LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION,
                     LightBarTransitionsController.DEFAULT_TINT_ANIMATION_DURATION, true);
-        mKeyguardMonitor.notifyKeyguardFadingAway(delay, fadeoutDuration, isBypassFading);
+        mKeyguardStateController.notifyKeyguardFadingAway(delay, fadeoutDuration, isBypassFading);
     }
 
     /**
      * Notifies that the Keyguard fading away animation is done.
      */
     public void finishKeyguardFadingAway() {
-        mKeyguardMonitor.notifyKeyguardDoneFading();
+        mKeyguardStateController.notifyKeyguardDoneFading();
         mScrimController.setExpansionAffectsAlpha(true);
     }
 
@@ -3282,7 +3368,7 @@
         final int themeResId = lockDarkText ? R.style.Theme_SystemUI_Light : R.style.Theme_SystemUI;
         if (mContext.getThemeResId() != themeResId) {
             mContext.setTheme(themeResId);
-            Dependency.get(ConfigurationController.class).notifyThemeChanged();
+            mConfigurationController.notifyThemeChanged();
         }
     }
 
@@ -3490,7 +3576,7 @@
         updateQsExpansionEnabled();
         mKeyguardViewMediator.setDozing(mDozing);
 
-        mEntryManager.updateNotifications();
+        mEntryManager.updateNotifications("onDozingChanged");
         updateDozingState();
         updateScrimController();
         updateReportRejectedTouchVisibility();
@@ -3513,8 +3599,8 @@
     }
 
     private void updateKeyguardState() {
-        mKeyguardMonitor.notifyKeyguardState(mStatusBarKeyguardViewManager.isShowing(),
-                mUnlockMethodCache.isMethodSecure(),
+        mKeyguardStateController.notifyKeyguardState(mStatusBarKeyguardViewManager.isShowing(),
+                mKeyguardStateController.isMethodSecure(),
                 mStatusBarKeyguardViewManager.isOccluded());
     }
 
@@ -3562,7 +3648,7 @@
 
     public void onTrackingStopped(boolean expand) {
         if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
-            if (!expand && !mUnlockMethodCache.canSkipBouncer()) {
+            if (!expand && !mKeyguardStateController.canDismissLockScreen()) {
                 showBouncer(false /* scrimmed */);
             }
         }
@@ -3640,7 +3726,7 @@
         mBouncerShowing = bouncerShowing;
         mKeyguardBypassController.setBouncerShowing(bouncerShowing);
         mPulseExpansionHandler.setBouncerShowing(bouncerShowing);
-        mStatusBarWindow.setBouncerShowingScrimmed(isBouncerShowingScrimmed());
+        mStatusBarWindowViewController.setBouncerShowingScrimmed(isBouncerShowingScrimmed());
         if (mStatusBarView != null) mStatusBarView.setBouncerShowing(bouncerShowing);
         updateHideIconsForBouncer(true /* animate */);
         mCommandQueue.recomputeDisableFlags(mDisplayId, true /* animate */);
@@ -3655,7 +3741,7 @@
      */
     public void collapseShade() {
         if (mNotificationPanel.isTracking()) {
-            mStatusBarWindow.cancelCurrentTouch();
+            mStatusBarWindowViewController.cancelCurrentTouch();
         }
         if (mPanelExpanded && mState == StatusBarState.SHADE) {
             animateCollapsePanels();
@@ -3676,7 +3762,7 @@
             updateVisibleToUser();
 
             updateNotificationPanelTouchState();
-            mStatusBarWindow.cancelCurrentTouch();
+            mStatusBarWindowViewController.cancelCurrentTouch();
             if (mLaunchCameraOnFinishedGoingToSleep) {
                 mLaunchCameraOnFinishedGoingToSleep = false;
 
@@ -3786,7 +3872,7 @@
 
     @Override
     public void showScreenPinningRequest(int taskId) {
-        if (mKeyguardMonitor.isShowing()) {
+        if (mKeyguardStateController.isShowing()) {
             // Don't allow apps to trigger this from keyguard.
             return;
         }
@@ -3829,8 +3915,7 @@
             return;
         }
         if (!mDeviceInteractive) {
-            PowerManager pm = mContext.getSystemService(PowerManager.class);
-            pm.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_CAMERA_LAUNCH,
+            mPowerManager.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_CAMERA_LAUNCH,
                     "com.android.systemui:CAMERA_GESTURE");
         }
         vibrateForCameraGesture();
@@ -3869,20 +3954,17 @@
     }
 
     boolean isCameraAllowedByAdmin() {
-        // TODO(b/140060745)
-        return whitelistIpcs(() -> {
-            if (mDevicePolicyManager.getCameraDisabled(null,
-                    mLockscreenUserManager.getCurrentUserId())) {
-                return false;
-            } else if (mStatusBarKeyguardViewManager == null
-                    || (isKeyguardShowing() && isKeyguardSecure())) {
-                // Check if the admin has disabled the camera specifically for the keyguard
-                return (mDevicePolicyManager.getKeyguardDisabledFeatures(null,
-                        mLockscreenUserManager.getCurrentUserId())
-                        & DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA) == 0;
-            }
-            return true;
-        });
+        if (mDevicePolicyManager.getCameraDisabled(null,
+                mLockscreenUserManager.getCurrentUserId())) {
+            return false;
+        } else if (mStatusBarKeyguardViewManager == null
+                || (isKeyguardShowing() && isKeyguardSecure())) {
+            // Check if the admin has disabled the camera specifically for the keyguard
+            return (mDevicePolicyManager.getKeyguardDisabledFeatures(null,
+                    mLockscreenUserManager.getCurrentUserId())
+                    & DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA) == 0;
+        }
+        return true;
     }
 
     private boolean isGoingToSleep() {
@@ -3898,7 +3980,8 @@
     public void notifyBiometricAuthModeChanged() {
         updateDozing();
         updateScrimController();
-        mStatusBarWindow.onBiometricAuthModeChanged(mBiometricUnlockController.isWakeAndUnlock(),
+        mStatusBarWindowViewController.onBiometricAuthModeChanged(
+                mBiometricUnlockController.isWakeAndUnlock(),
                 mBiometricUnlockController.isBiometricUnlock());
     }
 
@@ -3909,7 +3992,7 @@
         // We don't want to end up in KEYGUARD state when we're unlocking with
         // fingerprint from doze. We should cross fade directly from black.
         boolean unlocking = mBiometricUnlockController.isWakeAndUnlock()
-                || mKeyguardMonitor.isKeyguardFadingAway();
+                || mKeyguardStateController.isKeyguardFadingAway();
 
         // Do not animate the scrim expansion when triggered by the fingerprint sensor.
         mScrimController.setExpansionAffectsAlpha(
@@ -3999,7 +4082,7 @@
         public void startDozing() {
             if (!mDozingRequested) {
                 mDozingRequested = true;
-                DozeLog.traceDozing(mContext, mDozing);
+                mDozeLog.traceDozing(mDozing);
                 updateDozing();
                 updateIsKeyguard();
             }
@@ -4007,22 +4090,22 @@
 
         @Override
         public void pulseWhileDozing(@NonNull PulseCallback callback, int reason) {
-            if (reason == DozeLog.PULSE_REASON_SENSOR_LONG_PRESS) {
+            if (reason == DozeEvent.PULSE_REASON_SENSOR_LONG_PRESS) {
                 mPowerManager.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_GESTURE,
                         "com.android.systemui:LONG_PRESS");
                 startAssist(new Bundle());
                 return;
             }
 
-            if (reason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN) {
+            if (reason == DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN) {
                 mScrimController.setWakeLockScreenSensorActive(true);
             }
 
-            if (reason == DozeLog.PULSE_REASON_DOCKING && mStatusBarWindow != null) {
-                mStatusBarWindow.suppressWakeUpGesture(true);
+            if (reason == DozeEvent.PULSE_REASON_DOCKING && mStatusBarWindow != null) {
+                mStatusBarWindowViewController.suppressWakeUpGesture(true);
             }
 
-            boolean passiveAuthInterrupt = reason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN
+            boolean passiveAuthInterrupt = reason == DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN
                             && mWakeLockScreenPerformsAuth;
             // Set the state to pulsing, so ScrimController will know what to do once we ask it to
             // execute the transition. The pulse callback will then be invoked when the scrims
@@ -4043,7 +4126,7 @@
                     updateNotificationPanelTouchState();
                     mScrimController.setWakeLockScreenSensorActive(false);
                     if (mStatusBarWindow != null) {
-                        mStatusBarWindow.suppressWakeUpGesture(false);
+                        mStatusBarWindowViewController.suppressWakeUpGesture(false);
                     }
                     setPulsing(false);
                 }
@@ -4054,7 +4137,7 @@
                     mKeyguardViewMediator.setPulsing(pulsing);
                     mNotificationPanel.setPulsing(pulsing);
                     mVisualStabilityManager.setPulsing(pulsing);
-                    mStatusBarWindow.setPulsing(pulsing);
+                    mStatusBarWindowViewController.setPulsing(pulsing);
                     mIgnoreTouchWhilePulsing = false;
                     if (mKeyguardUpdateMonitor != null && passiveAuthInterrupt) {
                         mKeyguardUpdateMonitor.onAuthInterruptDetected(pulsing /* active */);
@@ -4073,7 +4156,7 @@
         public void stopDozing() {
             if (mDozingRequested) {
                 mDozingRequested = false;
-                DozeLog.traceDozing(mContext, mDozing);
+                mDozeLog.traceDozing(mDozing);
                 updateDozing();
             }
         }
@@ -4081,11 +4164,11 @@
         @Override
         public void onIgnoreTouchWhilePulsing(boolean ignore) {
             if (ignore != mIgnoreTouchWhilePulsing) {
-                DozeLog.tracePulseTouchDisabledByProx(mContext, ignore);
+                mDozeLog.tracePulseTouchDisabledByProx(ignore);
             }
             mIgnoreTouchWhilePulsing = ignore;
             if (isDozing() && ignore) {
-                mStatusBarWindow.cancelCurrentTouch();
+                mStatusBarWindowViewController.cancelCurrentTouch();
             }
         }
 
@@ -4125,7 +4208,7 @@
 
         @Override
         public void extendPulse(int reason) {
-            if (reason == DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN) {
+            if (reason == DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN) {
                 mScrimController.setWakeLockScreenSensorActive(true);
             }
             if (mDozeScrimController.isPulsing() && mHeadsUpManager.hasNotifications()) {
@@ -4219,12 +4302,11 @@
     // all notifications
     protected ViewGroup mStackScroller;
 
-    protected NotificationGroupManager mGroupManager;
-
-    protected NotificationGroupAlertTransferHelper mGroupAlertTransferHelper;
+    private final NotificationGroupManager mGroupManager;
+    private final NotificationGroupAlertTransferHelper mGroupAlertTransferHelper;
 
     // handling reordering
-    protected VisualStabilityManager mVisualStabilityManager;
+    private final VisualStabilityManager mVisualStabilityManager;
 
     protected AccessibilityManager mAccessibilityManager;
 
@@ -4240,10 +4322,9 @@
     protected StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
 
     protected KeyguardManager mKeyguardManager;
-    private DeviceProvisionedController mDeviceProvisionedController
-            = Dependency.get(DeviceProvisionedController.class);
+    private final DeviceProvisionedController mDeviceProvisionedController;
 
-    protected NavigationBarController mNavigationBarController;
+    private final NavigationBarController mNavigationBarController;
 
     // UI-specific methods
 
@@ -4259,7 +4340,7 @@
     protected NotificationShelf mNotificationShelf;
     protected EmptyShadeView mEmptyShadeView;
 
-    protected AssistManager mAssistManager;
+    private final AssistManager mAssistManager;
 
     public boolean isDeviceInteractive() {
         return mDeviceInteractive;
@@ -4318,7 +4399,7 @@
         }
     }
 
-    protected NotificationListener mNotificationListener;
+    private final NotificationListener mNotificationListener;
 
     public void setNotificationSnoozed(StatusBarNotification sbn, SnoozeOption snoozeOption) {
         if (snoozeOption.getSnoozeCriterion() != null) {
@@ -4454,8 +4535,7 @@
         executeActionDismissingKeyguard(() -> {
             try {
                 intent.send(null, 0, null, null, null, null, getActivityOptions(
-                        mActivityLaunchAnimator.getLaunchAnimation(associatedView,
-                                mShadeController.isOccluded())));
+                        mActivityLaunchAnimator.getLaunchAnimation(associatedView, isOccluded())));
             } catch (PendingIntent.CanceledException e) {
                 // the stack trace isn't very helpful here.
                 // Just log the exception message.
@@ -4543,7 +4623,7 @@
      */
     public void onBouncerPreHideAnimation() {
         mNotificationPanel.onBouncerPreHideAnimation();
-        mStatusBarWindow.onBouncerPreHideAnimation();
+        mStatusBarWindowViewController.onBouncerPreHideAnimation();
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index bb8ba05..75b0cdc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -56,12 +56,13 @@
 import com.android.systemui.statusbar.notification.ViewGroupFadeHelper;
 import com.android.systemui.statusbar.phone.KeyguardBouncer.BouncerExpansionCallback;
 import com.android.systemui.statusbar.policy.ConfigurationController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
-import com.android.systemui.statusbar.policy.KeyguardMonitorImpl;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
 
+import androidx.annotation.VisibleForTesting;
+
 /**
  * Manages creating, showing, hiding and resetting the keyguard within the status bar. Calls back
  * via {@link ViewMediatorCallback} to poke the wake lock and report that the keyguard is done,
@@ -161,12 +162,13 @@
     private boolean mLastLockVisible;
 
     private OnDismissAction mAfterKeyguardGoneAction;
+    private Runnable mKeyguardGoneCancelAction;
     private final ArrayList<Runnable> mAfterKeyguardGoneRunnables = new ArrayList<>();
 
     // Dismiss action to be launched when we stop dozing or the keyguard is gone.
     private DismissWithActionRequest mPendingWakeupAction;
-    private final KeyguardMonitorImpl mKeyguardMonitor =
-            (KeyguardMonitorImpl) Dependency.get(KeyguardMonitor.class);
+    private final KeyguardStateController mKeyguardStateController = Dependency.get(
+            KeyguardStateController.class);
     private final NotificationMediaManager mMediaManager =
             Dependency.get(NotificationMediaManager.class);
     private final SysuiStatusBarStateController mStatusBarStateController =
@@ -221,7 +223,7 @@
         mBiometricUnlockController = biometricUnlockController;
         mBouncer = SystemUIFactory.getInstance().createKeyguardBouncer(mContext,
                 mViewMediatorCallback, mLockPatternUtils, container, dismissCallbackRegistry,
-                mExpansionCallback, falsingManager, bypassController);
+                mExpansionCallback, mKeyguardStateController, falsingManager, bypassController);
         mNotificationPanelView = notificationPanelView;
         notificationPanelView.addExpansionListener(this);
         mBypassController = bypassController;
@@ -245,7 +247,7 @@
                 mBouncer.setExpansion(expansion);
             }
             if (expansion != KeyguardBouncer.EXPANSION_HIDDEN && tracking
-                    && mStatusBar.isKeyguardCurrentlySecure()
+                    && !mKeyguardStateController.canDismissLockScreen()
                     && !mBouncer.isShowing() && !mBouncer.isAnimatingAway()) {
                 mBouncer.show(false /* resetSecuritySelection */, false /* scrimmed */);
             }
@@ -269,7 +271,7 @@
         boolean keyguardWithoutQs = mStatusBarStateController.getState() == StatusBarState.KEYGUARD
                 && !mNotificationPanelView.isQsExpanded();
         boolean lockVisible = (mBouncer.isShowing() || keyguardWithoutQs)
-                && !mBouncer.isAnimatingAway() && !mKeyguardMonitor.isKeyguardFadingAway();
+                && !mBouncer.isAnimatingAway() && !mKeyguardStateController.isKeyguardFadingAway();
 
         if (mLastLockVisible != lockVisible) {
             mLastLockVisible = lockVisible;
@@ -299,8 +301,9 @@
     public void show(Bundle options) {
         mShowing = true;
         mStatusBarWindowController.setKeyguardShowing(true);
-        mKeyguardMonitor.notifyKeyguardState(
-                mShowing, mKeyguardMonitor.isSecure(), mKeyguardMonitor.isOccluded());
+        mKeyguardStateController.notifyKeyguardState(
+                mShowing, mKeyguardStateController.isMethodSecure(),
+                mKeyguardStateController.isOccluded());
         reset(true /* hideBouncerWhenShowing */);
         StatsLog.write(StatsLog.KEYGUARD_STATE_CHANGED,
             StatsLog.KEYGUARD_STATE_CHANGED__STATE__SHOWN);
@@ -329,10 +332,20 @@
         return false;
     }
 
-    private void hideBouncer(boolean destroyView) {
+    @VisibleForTesting
+    void hideBouncer(boolean destroyView) {
         if (mBouncer == null) {
             return;
         }
+        if (mShowing) {
+            // If we were showing the bouncer and then aborting, we need to also clear out any
+            // potential actions unless we actually unlocked.
+            mAfterKeyguardGoneAction = null;
+            if (mKeyguardGoneCancelAction != null) {
+                mKeyguardGoneCancelAction.run();
+                mKeyguardGoneCancelAction = null;
+            }
+        }
         mBouncer.hide(destroyView);
         cancelPendingWakeupAction();
     }
@@ -365,6 +378,7 @@
                 mBouncer.showWithDismissAction(r, cancelAction);
             } else {
                 mAfterKeyguardGoneAction = r;
+                mKeyguardGoneCancelAction = cancelAction;
                 mBouncer.show(false /* resetSecuritySelection */);
             }
         }
@@ -530,8 +544,8 @@
      */
     public void hide(long startTime, long fadeoutDuration) {
         mShowing = false;
-        mKeyguardMonitor.notifyKeyguardState(
-                mShowing, mKeyguardMonitor.isSecure(), mKeyguardMonitor.isOccluded());
+        mKeyguardStateController.notifyKeyguardState(mShowing,
+                mKeyguardStateController.isMethodSecure(), mKeyguardStateController.isOccluded());
         launchPendingWakeupAction();
 
         if (Dependency.get(KeyguardUpdateMonitor.class).needsSlowUnlockTransition()) {
@@ -672,6 +686,7 @@
             mAfterKeyguardGoneAction.onDismiss();
             mAfterKeyguardGoneAction = null;
         }
+        mKeyguardGoneCancelAction = null;
         for (int i = 0; i < mAfterKeyguardGoneRunnables.size(); i++) {
             mAfterKeyguardGoneRunnables.get(i).run();
         }
@@ -739,8 +754,8 @@
     }
 
     private long getNavBarShowDelay() {
-        if (mKeyguardMonitor.isKeyguardFadingAway()) {
-            return mKeyguardMonitor.getKeyguardFadingAwayDelay();
+        if (mKeyguardStateController.isKeyguardFadingAway()) {
+            return mKeyguardStateController.getKeyguardFadingAwayDelay();
         } else if (mBouncer.isShowing()) {
             return NAV_BAR_SHOW_DELAY_BOUNCER;
         } else {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
index 320243b..dfec195 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
@@ -68,7 +68,7 @@
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.policy.HeadsUpUtil;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 /**
  * Status bar implementation of {@link NotificationActivityStarter}.
@@ -84,7 +84,7 @@
     private final NotificationRemoteInputManager mRemoteInputManager;
     private final NotificationLockscreenUserManager mLockscreenUserManager;
     private final ShadeController mShadeController;
-    private final KeyguardMonitor mKeyguardMonitor;
+    private final KeyguardStateController mKeyguardStateController;
     private final ActivityStarter mActivityStarter;
     private final NotificationEntryManager mEntryManager;
     private final StatusBarStateController mStatusBarStateController;
@@ -125,7 +125,7 @@
             NotificationGroupManager groupManager,
             NotificationLockscreenUserManager lockscreenUserManager,
             ShadeController shadeController,
-            KeyguardMonitor keyguardMonitor,
+            KeyguardStateController keyguardStateController,
             NotificationInterruptionStateProvider notificationInterruptionStateProvider,
             MetricsLogger metricsLogger,
             LockPatternUtils lockPatternUtils,
@@ -145,7 +145,7 @@
         mRemoteInputManager = remoteInputManager;
         mLockscreenUserManager = lockscreenUserManager;
         mShadeController = shadeController;
-        mKeyguardMonitor = keyguardMonitor;
+        mKeyguardStateController = keyguardStateController;
         mActivityStarter = activityStarter;
         mEntryManager = entryManager;
         mStatusBarStateController = statusBarStateController;
@@ -204,7 +204,7 @@
                 && mActivityIntentHelper.wouldLaunchResolverActivity(intent.getIntent(),
                 mLockscreenUserManager.getCurrentUserId());
         final boolean wasOccluded = mShadeController.isOccluded();
-        boolean showOverLockscreen = mKeyguardMonitor.isShowing() && intent != null
+        boolean showOverLockscreen = mKeyguardStateController.isShowing() && intent != null
                 && mActivityIntentHelper.wouldShowOverLockscreen(intent.getIntent(),
                 mLockscreenUserManager.getCurrentUserId());
         ActivityStarter.OnDismissAction postKeyguardAction =
@@ -258,7 +258,7 @@
         if (showOverLockscreen) {
             mShadeController.addPostCollapseAction(runnable);
             mShadeController.collapsePanel(true /* animate */);
-        } else if (mKeyguardMonitor.isShowing()
+        } else if (mKeyguardStateController.isShowing()
                 && mShadeController.isOccluded()) {
             mShadeController.addAfterKeyguardGoneRunnable(runnable);
             mShadeController.collapsePanel();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
index 4732049..3e0c268 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
@@ -74,7 +74,7 @@
 import com.android.systemui.statusbar.notification.row.NotificationInfo.CheckSaveListener;
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
 import com.android.systemui.statusbar.policy.ConfigurationController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import java.util.ArrayList;
 
@@ -89,7 +89,8 @@
 
     private final ShadeController mShadeController = Dependency.get(ShadeController.class);
     private final ActivityStarter mActivityStarter = Dependency.get(ActivityStarter.class);
-    private final KeyguardMonitor mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+    private final KeyguardStateController mKeyguardStateController = Dependency.get(
+            KeyguardStateController.class);
     private final NotificationViewHierarchyManager mViewHierarchyManager =
             Dependency.get(NotificationViewHierarchyManager.class);
     private final NotificationLockscreenUserManager mLockscreenUserManager =
@@ -123,7 +124,6 @@
     private final DynamicPrivacyController mDynamicPrivacyController;
     private boolean mReinflateNotificationsOnUserSwitched;
     private boolean mDispatchUiModeChangeOnUserSwitched;
-    private final UnlockMethodCache mUnlockMethodCache;
     private TextView mNotificationPanelDebugText;
 
     protected boolean mVrMode;
@@ -152,7 +152,6 @@
         mAccessibilityManager = context.getSystemService(AccessibilityManager.class);
         mDozeScrimController = dozeScrimController;
         mScrimController = scrimController;
-        mUnlockMethodCache = UnlockMethodCache.getInstance(mContext);
         mKeyguardManager = context.getSystemService(KeyguardManager.class);
         mMaxAllowedKeyguardNotifications = context.getResources().getInteger(
                 R.integer.keyguard_max_notification_count);
@@ -366,7 +365,7 @@
                 return false;
             } else {
                 // we only allow head-up on the lockscreen if it doesn't have a fullscreen intent
-                return !mKeyguardMonitor.isShowing()
+                return !mKeyguardStateController.isShowing()
                         || mShadeController.isOccluded();
             }
         }
@@ -398,7 +397,7 @@
     public void onBindRow(NotificationEntry entry, PackageManager pmUser,
             StatusBarNotification sbn, ExpandableNotificationRow row) {
         row.setAboveShelfChangedListener(mAboveShelfObserver);
-        row.setSecureStateProvider(mUnlockMethodCache::canSkipBouncer);
+        row.setSecureStateProvider(mKeyguardStateController::canDismissLockScreen);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
index 13d4b8e..9a281ce 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java
@@ -47,8 +47,7 @@
 import com.android.systemui.statusbar.SysuiStatusBarStateController;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
-import com.android.systemui.statusbar.policy.RemoteInputView;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import javax.inject.Inject;
 import javax.inject.Singleton;
@@ -59,7 +58,8 @@
 public class StatusBarRemoteInputCallback implements Callback, Callbacks,
         StatusBarStateController.StateListener {
 
-    private final KeyguardMonitor mKeyguardMonitor = Dependency.get(KeyguardMonitor.class);
+    private final KeyguardStateController mKeyguardStateController = Dependency.get(
+            KeyguardStateController.class);
     private final SysuiStatusBarStateController mStatusBarStateController =
             (SysuiStatusBarStateController) Dependency.get(StatusBarStateController.class);
     private final NotificationLockscreenUserManager mLockscreenUserManager =
@@ -165,7 +165,7 @@
     @Override
     public void onMakeExpandedVisibleForRemoteInput(ExpandableNotificationRow row,
             View clickedView) {
-        if (mKeyguardMonitor.isShowing()) {
+        if (mKeyguardStateController.isShowing()) {
             onLockedRemoteInput(row, clickedView);
         } else {
             if (row.isChildInGroup() && !row.areChildrenExpanded()) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
index a9e818d..d04c7bd 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
@@ -19,29 +19,18 @@
 import android.annotation.ColorInt;
 import android.annotation.DrawableRes;
 import android.annotation.LayoutRes;
-import android.app.StatusBarManager;
 import android.content.Context;
 import android.content.res.Configuration;
 import android.content.res.TypedArray;
 import android.graphics.Canvas;
 import android.graphics.Paint;
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuffXfermode;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
-import android.hardware.display.AmbientDisplayConfiguration;
-import android.media.AudioManager;
-import android.media.session.MediaSessionLegacyHelper;
 import android.net.Uri;
 import android.os.Bundle;
-import android.os.SystemClock;
-import android.os.UserHandle;
-import android.provider.Settings;
 import android.util.AttributeSet;
 import android.view.ActionMode;
 import android.view.DisplayCutout;
-import android.view.GestureDetector;
-import android.view.InputDevice;
 import android.view.InputQueue;
 import android.view.KeyEvent;
 import android.view.LayoutInflater;
@@ -56,21 +45,9 @@
 import android.view.WindowInsetsController;
 import android.widget.FrameLayout;
 
-import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.view.FloatingActionMode;
 import com.android.internal.widget.FloatingToolbar;
-import com.android.systemui.Dependency;
-import com.android.systemui.ExpandHelper;
 import com.android.systemui.R;
-import com.android.systemui.plugins.FalsingManager;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.DragDownHelper;
-import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
-import com.android.systemui.statusbar.phone.ScrimController.ScrimVisibility;
-import com.android.systemui.tuner.TunerService;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
 
 /**
  * Combined status bar and notification panel view. Also holding backdrop and scrims.
@@ -79,87 +56,21 @@
     public static final String TAG = "StatusBarWindowView";
     public static final boolean DEBUG = StatusBar.DEBUG;
 
-    private final GestureDetector mGestureDetector;
-    private final StatusBarStateController mStatusBarStateController;
-    private boolean mDoubleTapEnabled;
-    private boolean mSingleTapEnabled;
-    private DragDownHelper mDragDownHelper;
-    private NotificationStackScrollLayout mStackScrollLayout;
-    private NotificationPanelView mNotificationPanel;
-    private View mBrightnessMirror;
-    private LockIcon mLockIcon;
-    private PhoneStatusBarView mStatusBarView;
-
     private int mRightInset = 0;
     private int mLeftInset = 0;
 
-    private StatusBar mService;
-    private final Paint mTransparentSrcPaint = new Paint();
-    private FalsingManager mFalsingManager;
-
     // Implements the floating action mode for TextView's Cut/Copy/Past menu. Normally provided by
     // DecorView, but since this is a special window we have to roll our own.
     private View mFloatingActionModeOriginatingView;
     private ActionMode mFloatingActionMode;
     private FloatingToolbar mFloatingToolbar;
     private ViewTreeObserver.OnPreDrawListener mFloatingToolbarPreDrawListener;
-    private boolean mTouchCancelled;
-    private boolean mTouchActive;
-    private boolean mExpandAnimationRunning;
-    private boolean mExpandAnimationPending;
-    private boolean mSuppressingWakeUpGesture;
 
-    private final GestureDetector.SimpleOnGestureListener mGestureListener =
-            new GestureDetector.SimpleOnGestureListener() {
-        @Override
-        public boolean onSingleTapConfirmed(MotionEvent e) {
-            if (mSingleTapEnabled && !mSuppressingWakeUpGesture) {
-                mService.wakeUpIfDozing(SystemClock.uptimeMillis(), StatusBarWindowView.this,
-                        "SINGLE_TAP");
-                return true;
-            }
-            return false;
-        }
-
-        @Override
-        public boolean onDoubleTap(MotionEvent e) {
-            if (mDoubleTapEnabled || mSingleTapEnabled) {
-                mService.wakeUpIfDozing(SystemClock.uptimeMillis(), StatusBarWindowView.this,
-                        "DOUBLE_TAP");
-                return true;
-            }
-            return false;
-        }
-    };
-    private final TunerService.Tunable mTunable = (key, newValue) -> {
-        AmbientDisplayConfiguration configuration = new AmbientDisplayConfiguration(mContext);
-        switch (key) {
-            case Settings.Secure.DOZE_DOUBLE_TAP_GESTURE:
-                mDoubleTapEnabled = configuration.doubleTapGestureEnabled(UserHandle.USER_CURRENT);
-                break;
-            case Settings.Secure.DOZE_TAP_SCREEN_GESTURE:
-                mSingleTapEnabled = configuration.tapGestureEnabled(UserHandle.USER_CURRENT);
-        }
-    };
-
-    /**
-     * If set to true, the current gesture started below the notch and we need to dispatch touch
-     * events manually as it's outside of the regular view bounds.
-     */
-    private boolean mExpandingBelowNotch;
-    private KeyguardBypassController mBypassController;
+    private InteractionEventHandler mInteractionEventHandler;
 
     public StatusBarWindowView(Context context, AttributeSet attrs) {
         super(context, attrs);
         setMotionEventSplittingEnabled(false);
-        mTransparentSrcPaint.setColor(0);
-        mTransparentSrcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
-        mFalsingManager = Dependency.get(FalsingManager.class);  // TODO: inject into a controller.
-        mGestureDetector = new GestureDetector(context, mGestureListener);
-        mStatusBarStateController = Dependency.get(StatusBarStateController.class);
-        Dependency.get(TunerService.class).addTunable(mTunable,
-                Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
-                Settings.Secure.DOZE_TAP_SCREEN_GESTURE);
     }
 
     @Override
@@ -226,11 +137,6 @@
         }
     }
 
-    @VisibleForTesting
-    protected NotificationStackScrollLayout getStackScrollLayout() {
-        return mStackScrollLayout;
-    }
-
     @Override
     public FrameLayout.LayoutParams generateLayoutParams(AttributeSet attrs) {
         return new LayoutParams(getContext(), attrs);
@@ -242,61 +148,6 @@
     }
 
     @Override
-    protected void onFinishInflate() {
-        super.onFinishInflate();
-        mStackScrollLayout = findViewById(R.id.notification_stack_scroller);
-        mNotificationPanel = findViewById(R.id.notification_panel);
-        mBrightnessMirror = findViewById(R.id.brightness_mirror);
-        mLockIcon = findViewById(R.id.lock_icon);
-    }
-
-    @Override
-    public void onViewAdded(View child) {
-        super.onViewAdded(child);
-        if (child.getId() == R.id.brightness_mirror) {
-            mBrightnessMirror = child;
-        }
-    }
-
-    /**
-     * Propagate {@link StatusBar} pulsing state.
-     */
-    public void setPulsing(boolean pulsing) {
-        if (mLockIcon != null) {
-            mLockIcon.setPulsing(pulsing);
-        }
-    }
-
-    /**
-     * Called when the biometric authentication mode changes.
-     * @param wakeAndUnlock If the type is {@link BiometricUnlockController#isWakeAndUnlock()}
-     * @param isUnlock If the type is {@link BiometricUnlockController#isBiometricUnlock()} ()
-     */
-    public void onBiometricAuthModeChanged(boolean wakeAndUnlock, boolean isUnlock) {
-        if (mLockIcon != null) {
-            mLockIcon.onBiometricAuthModeChanged(wakeAndUnlock, isUnlock);
-        }
-    }
-
-    public void setStatusBarView(PhoneStatusBarView statusBarView) {
-        mStatusBarView = statusBarView;
-    }
-
-    public void setService(StatusBar service) {
-        mService = service;
-        NotificationStackScrollLayout stackScrollLayout = getStackScrollLayout();
-        ExpandHelper.Callback expandHelperCallback = stackScrollLayout.getExpandHelperCallback();
-        DragDownHelper.DragDownCallback dragDownCallback = stackScrollLayout.getDragDownCallback();
-        setDragDownHelper(new DragDownHelper(getContext(), this, expandHelperCallback,
-                dragDownCallback, mFalsingManager));
-    }
-
-    @VisibleForTesting
-    void setDragDownHelper(DragDownHelper dragDownHelper) {
-        mDragDownHelper = dragDownHelper;
-    }
-
-    @Override
     protected void onAttachedToWindow () {
         super.onAttachedToWindow();
         setWillNotDraw(!DEBUG);
@@ -304,152 +155,53 @@
 
     @Override
     public boolean dispatchKeyEvent(KeyEvent event) {
-        if (mService.interceptMediaKey(event)) {
+        if (mInteractionEventHandler.interceptMediaKey(event)) {
             return true;
         }
+
         if (super.dispatchKeyEvent(event)) {
             return true;
         }
-        boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
-        switch (event.getKeyCode()) {
-            case KeyEvent.KEYCODE_BACK:
-                if (!down) {
-                    mService.onBackPressed();
-                }
-                return true;
-            case KeyEvent.KEYCODE_MENU:
-                if (!down) {
-                    return mService.onMenuPressed();
-                }
-            case KeyEvent.KEYCODE_SPACE:
-                if (!down) {
-                    return mService.onSpacePressed();
-                }
-                break;
-            case KeyEvent.KEYCODE_VOLUME_DOWN:
-            case KeyEvent.KEYCODE_VOLUME_UP:
-                if (mService.isDozing()) {
-                    MediaSessionLegacyHelper.getHelper(mContext).sendVolumeKeyEvent(
-                            event, AudioManager.USE_DEFAULT_STREAM_TYPE, true);
-                    return true;
-                }
-                break;
-        }
-        return false;
+
+        return mInteractionEventHandler.dispatchKeyEvent(event);
     }
 
-    public void setTouchActive(boolean touchActive) {
-        mTouchActive = touchActive;
-    }
-
-    void suppressWakeUpGesture(boolean suppress) {
-        mSuppressingWakeUpGesture = suppress;
+    protected void setInteractionEventHandler(InteractionEventHandler listener) {
+        mInteractionEventHandler = listener;
     }
 
     @Override
     public boolean dispatchTouchEvent(MotionEvent ev) {
-        boolean isDown = ev.getActionMasked() == MotionEvent.ACTION_DOWN;
-        boolean isUp = ev.getActionMasked() == MotionEvent.ACTION_UP;
-        boolean isCancel = ev.getActionMasked() == MotionEvent.ACTION_CANCEL;
+        Boolean result = mInteractionEventHandler.handleDispatchTouchEvent(ev);
 
-        // Reset manual touch dispatch state here but make sure the UP/CANCEL event still gets
-        // delivered.
-        boolean expandingBelowNotch = mExpandingBelowNotch;
-        if (isUp || isCancel) {
-            mExpandingBelowNotch = false;
-        }
-
-        if (!isCancel && mService.shouldIgnoreTouch()) {
-            return false;
-        }
-        if (isDown && mNotificationPanel.isFullyCollapsed()) {
-            mNotificationPanel.startExpandLatencyTracking();
-        }
-        if (isDown) {
-            setTouchActive(true);
-            mTouchCancelled = false;
-        } else if (ev.getActionMasked() == MotionEvent.ACTION_UP
-                || ev.getActionMasked() == MotionEvent.ACTION_CANCEL) {
-            setTouchActive(false);
-        }
-        if (mTouchCancelled || mExpandAnimationRunning || mExpandAnimationPending) {
-            return false;
-        }
-        mFalsingManager.onTouchEvent(ev, getWidth(), getHeight());
-        mGestureDetector.onTouchEvent(ev);
-        if (mBrightnessMirror != null && mBrightnessMirror.getVisibility() == VISIBLE) {
-            // Disallow new pointers while the brightness mirror is visible. This is so that you
-            // can't touch anything other than the brightness slider while the mirror is showing
-            // and the rest of the panel is transparent.
-            if (ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
-                return false;
-            }
-        }
-        if (isDown) {
-            getStackScrollLayout().closeControlsIfOutsideTouch(ev);
-        }
-        if (mService.isDozing()) {
-            mService.mDozeScrimController.extendPulse();
-        }
-
-        // In case we start outside of the view bounds (below the status bar), we need to dispatch
-        // the touch manually as the view system can't accomodate for touches outside of the
-        // regular view bounds.
-        if (isDown && ev.getY() >= mBottom) {
-            mExpandingBelowNotch = true;
-            expandingBelowNotch = true;
-        }
-        if (expandingBelowNotch) {
-            return mStatusBarView.dispatchTouchEvent(ev);
-        }
-
-        return super.dispatchTouchEvent(ev);
+        return result != null ? result : super.dispatchTouchEvent(ev);
     }
 
     @Override
     public boolean onInterceptTouchEvent(MotionEvent ev) {
-        NotificationStackScrollLayout stackScrollLayout = getStackScrollLayout();
-        if (mService.isDozing() && !mService.isPulsing()) {
-            // Capture all touch events in always-on.
-            return true;
-        }
-        boolean intercept = false;
-        if (mNotificationPanel.isFullyExpanded()
-                && mDragDownHelper.isDragDownEnabled()
-                && !mService.isBouncerShowing()
-                && !mService.isDozing()) {
-            intercept = mDragDownHelper.onInterceptTouchEvent(ev);
-        }
+        boolean intercept = mInteractionEventHandler.shouldInterceptTouchEvent(ev);
         if (!intercept) {
-            super.onInterceptTouchEvent(ev);
+            intercept = super.onInterceptTouchEvent(ev);
         }
         if (intercept) {
-            MotionEvent cancellation = MotionEvent.obtain(ev);
-            cancellation.setAction(MotionEvent.ACTION_CANCEL);
-            stackScrollLayout.onInterceptTouchEvent(cancellation);
-            mNotificationPanel.onInterceptTouchEvent(cancellation);
-            cancellation.recycle();
+            mInteractionEventHandler.didIntercept(ev);
         }
+
         return intercept;
     }
 
     @Override
     public boolean onTouchEvent(MotionEvent ev) {
-        boolean handled = false;
-        if (mService.isDozing()) {
-            handled = !mService.isPulsing();
-        }
-        if ((mDragDownHelper.isDragDownEnabled() && !handled) || mDragDownHelper.isDraggingDown()) {
-            // we still want to finish our drag down gesture when locking the screen
-            handled = mDragDownHelper.onTouchEvent(ev);
-        }
+        boolean handled = mInteractionEventHandler.handleTouchEvent(ev);
+
         if (!handled) {
             handled = super.onTouchEvent(ev);
         }
-        final int action = ev.getAction();
-        if (!handled && (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL)) {
-            mService.setInteracting(StatusBarManager.WINDOW_STATUS_BAR, false);
+
+        if (!handled) {
+            mInteractionEventHandler.didNotHandleTouchEvent(ev);
         }
+
         return handled;
     }
 
@@ -465,77 +217,6 @@
         }
     }
 
-    public void cancelExpandHelper() {
-        NotificationStackScrollLayout stackScrollLayout = getStackScrollLayout();
-        if (stackScrollLayout != null) {
-            stackScrollLayout.cancelExpandHelper();
-        }
-    }
-
-    public void cancelCurrentTouch() {
-        if (mTouchActive) {
-            final long now = SystemClock.uptimeMillis();
-            MotionEvent event = MotionEvent.obtain(now, now,
-                    MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
-            event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
-            dispatchTouchEvent(event);
-            event.recycle();
-            mTouchCancelled = true;
-        }
-    }
-
-    public void setExpandAnimationRunning(boolean expandAnimationRunning) {
-        mExpandAnimationRunning = expandAnimationRunning;
-    }
-
-    public void setExpandAnimationPending(boolean pending) {
-        mExpandAnimationPending = pending;
-    }
-
-    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
-        pw.print("  mExpandAnimationPending="); pw.println(mExpandAnimationPending);
-        pw.print("  mExpandAnimationRunning="); pw.println(mExpandAnimationRunning);
-        pw.print("  mTouchCancelled="); pw.println(mTouchCancelled);
-        pw.print("  mTouchActive="); pw.println(mTouchActive);
-    }
-
-    /**
-     * Called whenever the scrims become opaque, transparent or semi-transparent.
-     */
-    public void onScrimVisibilityChanged(@ScrimVisibility int scrimsVisible) {
-        if (mLockIcon != null) {
-            mLockIcon.onScrimVisibilityChanged(scrimsVisible);
-        }
-    }
-
-    /**
-     * When we're launching an affordance, like double pressing power to open camera.
-     */
-    public void onShowingLaunchAffordanceChanged(boolean showing) {
-        if (mLockIcon != null) {
-            mLockIcon.onShowingLaunchAffordanceChanged(showing);
-        }
-    }
-
-    public void setBypassController(KeyguardBypassController bypassController) {
-        mBypassController = bypassController;
-    }
-
-    public void setBouncerShowingScrimmed(boolean bouncerShowing) {
-        if (mLockIcon != null) {
-            mLockIcon.setBouncerShowingScrimmed(bouncerShowing);
-        }
-    }
-
-    /**
-     * When {@link KeyguardBouncer} starts to be dismissed and starts to play its animation.
-     */
-    public void onBouncerPreHideAnimation() {
-        if (mLockIcon != null) {
-            mLockIcon.onBouncerPreHideAnimation();
-        }
-    }
-
     public class LayoutParams extends FrameLayout.LayoutParams {
 
         public boolean ignoreRightInset;
@@ -657,6 +338,35 @@
         }
     }
 
+    interface InteractionEventHandler {
+        /**
+         * Returns a result for {@link ViewGroup#dispatchTouchEvent(MotionEvent)} or null to defer
+         * to the super method.
+         */
+        Boolean handleDispatchTouchEvent(MotionEvent ev);
+
+        /**
+         * Returns if the view should intercept the touch event.
+         *
+         * The touch event may still be interecepted if
+         * {@link ViewGroup#onInterceptTouchEvent(MotionEvent)} decides to do so.
+         */
+        boolean shouldInterceptTouchEvent(MotionEvent ev);
+
+        /**
+         * Called when the view decides to intercept the touch event.
+         */
+        void didIntercept(MotionEvent ev);
+
+        boolean handleTouchEvent(MotionEvent ev);
+
+        void didNotHandleTouchEvent(MotionEvent ev);
+
+        boolean interceptMediaKey(KeyEvent event);
+
+        boolean dispatchKeyEvent(KeyEvent event);
+    }
+
     /**
      * Minimal window to satisfy FloatingToolbar.
      */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java
new file mode 100644
index 0000000..f21085e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java
@@ -0,0 +1,543 @@
+/*
+ * Copyright (C) 2019 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.statusbar.phone;
+
+import android.app.StatusBarManager;
+import android.hardware.display.AmbientDisplayConfiguration;
+import android.media.AudioManager;
+import android.media.session.MediaSessionLegacyHelper;
+import android.os.SystemClock;
+import android.os.UserHandle;
+import android.provider.Settings;
+import android.view.GestureDetector;
+import android.view.InputDevice;
+import android.view.KeyEvent;
+import android.view.LayoutInflater;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewStub;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.systemui.ExpandHelper;
+import com.android.systemui.R;
+import com.android.systemui.doze.DozeLog;
+import com.android.systemui.plugins.FalsingManager;
+import com.android.systemui.shared.plugins.PluginManager;
+import com.android.systemui.statusbar.DragDownHelper;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
+import com.android.systemui.statusbar.PulseExpansionHandler;
+import com.android.systemui.statusbar.notification.DynamicPrivacyController;
+import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
+import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
+import com.android.systemui.tuner.TunerService;
+import com.android.systemui.util.InjectionInflationController;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+
+import javax.inject.Inject;
+
+/**
+ * Controller for {@link StatusBarWindowView}.
+ */
+public class StatusBarWindowViewController {
+    private final StatusBarWindowView mView;
+    private final FalsingManager mFalsingManager;
+    private final GestureDetector mGestureDetector;
+    private View mBrightnessMirror;
+    private boolean mTouchActive;
+    private boolean mTouchCancelled;
+    private boolean mExpandAnimationPending;
+    private boolean mExpandAnimationRunning;
+    private NotificationStackScrollLayout mStackScrollLayout;
+    private LockIcon mLockIcon;
+    private PhoneStatusBarView mStatusBarView;
+    private StatusBar mService;
+    private DragDownHelper mDragDownHelper;
+    private boolean mSuppressingWakeUpGesture;
+    private boolean mDoubleTapEnabled;
+    private boolean mSingleTapEnabled;
+    private boolean mExpandingBelowNotch;
+
+    private StatusBarWindowViewController(
+            StatusBarWindowView view,
+            InjectionInflationController injectionInflationController,
+            NotificationWakeUpCoordinator coordinator,
+            PulseExpansionHandler pulseExpansionHandler,
+            DynamicPrivacyController dynamicPrivacyController,
+            KeyguardBypassController bypassController,
+            FalsingManager falsingManager,
+            PluginManager pluginManager,
+            TunerService tunerService,
+            ShadeController shadeController,
+            NotificationLockscreenUserManager notificationLockscreenUserManager,
+            NotificationEntryManager notificationEntryManager,
+            DozeLog dozeLog) {
+        mView = view;
+        mFalsingManager = falsingManager;
+
+        // TODO: create controller for NotificationPanelView
+        NotificationPanelView notificationPanelView = new NotificationPanelView(
+                view.getContext(),
+                null,
+                injectionInflationController,
+                coordinator,
+                pulseExpansionHandler,
+                dynamicPrivacyController,
+                bypassController,
+                falsingManager,
+                pluginManager,
+                shadeController,
+                notificationLockscreenUserManager,
+                notificationEntryManager,
+                dozeLog);
+        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
+                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
+        notificationPanelView.setVisibility(View.INVISIBLE);
+        notificationPanelView.setId(R.id.notification_panel);
+        LayoutInflater li = injectionInflationController.injectable(
+                LayoutInflater.from(mView.getContext()));
+
+        li.inflate(R.layout.status_bar_expanded, notificationPanelView);
+        notificationPanelView.onChildrenAttached();
+
+        ViewStub statusBarExpanded = view.findViewById(R.id.status_bar_expanded);
+        mView.addView(notificationPanelView, mView.indexOfChild(statusBarExpanded), lp);
+        mView.removeView(statusBarExpanded);
+
+        mStackScrollLayout = mView.findViewById(R.id.notification_stack_scroller);
+        mLockIcon = mView.findViewById(R.id.lock_icon);
+        mBrightnessMirror = mView.findViewById(R.id.brightness_mirror);
+
+        TunerService.Tunable tunable = (key, newValue) -> {
+            AmbientDisplayConfiguration configuration =
+                    new AmbientDisplayConfiguration(mView.getContext());
+            switch (key) {
+                case Settings.Secure.DOZE_DOUBLE_TAP_GESTURE:
+                    mDoubleTapEnabled = configuration.doubleTapGestureEnabled(
+                            UserHandle.USER_CURRENT);
+                    break;
+                case Settings.Secure.DOZE_TAP_SCREEN_GESTURE:
+                    mSingleTapEnabled = configuration.tapGestureEnabled(UserHandle.USER_CURRENT);
+            }
+        };
+        tunerService.addTunable(tunable,
+                Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
+                Settings.Secure.DOZE_TAP_SCREEN_GESTURE);
+
+        GestureDetector.SimpleOnGestureListener gestureListener =
+                new GestureDetector.SimpleOnGestureListener() {
+                    @Override
+                    public boolean onSingleTapConfirmed(MotionEvent e) {
+                        if (mSingleTapEnabled && !mSuppressingWakeUpGesture) {
+                            mService.wakeUpIfDozing(
+                                    SystemClock.uptimeMillis(), mView, "SINGLE_TAP");
+                            return true;
+                        }
+                        return false;
+                    }
+
+                    @Override
+                    public boolean onDoubleTap(MotionEvent e) {
+                        if (mDoubleTapEnabled || mSingleTapEnabled) {
+                            mService.wakeUpIfDozing(
+                                    SystemClock.uptimeMillis(), mView, "DOUBLE_TAP");
+                            return true;
+                        }
+                        return false;
+                    }
+                };
+        mGestureDetector = new GestureDetector(mView.getContext(), gestureListener);
+
+        mView.setInteractionEventHandler(new StatusBarWindowView.InteractionEventHandler() {
+            @Override
+            public Boolean handleDispatchTouchEvent(MotionEvent ev) {
+                boolean isDown = ev.getActionMasked() == MotionEvent.ACTION_DOWN;
+                boolean isUp = ev.getActionMasked() == MotionEvent.ACTION_UP;
+                boolean isCancel = ev.getActionMasked() == MotionEvent.ACTION_CANCEL;
+
+                if (isUp || isCancel) {
+                    mExpandingBelowNotch = false;
+                }
+
+                // Reset manual touch dispatch state here but make sure the UP/CANCEL event still
+                // gets
+                // delivered.
+
+                if (!isCancel && mService.shouldIgnoreTouch()) {
+                    return false;
+                }
+                if (isDown && notificationPanelView.isFullyCollapsed()) {
+                    notificationPanelView.startExpandLatencyTracking();
+                }
+                if (isDown) {
+                    setTouchActive(true);
+                    mTouchCancelled = false;
+                } else if (ev.getActionMasked() == MotionEvent.ACTION_UP
+                        || ev.getActionMasked() == MotionEvent.ACTION_CANCEL) {
+                    setTouchActive(false);
+                }
+                if (mTouchCancelled || mExpandAnimationRunning || mExpandAnimationPending) {
+                    return false;
+                }
+                mFalsingManager.onTouchEvent(ev, mView.getWidth(), mView.getHeight());
+                mGestureDetector.onTouchEvent(ev);
+                if (mBrightnessMirror != null
+                        && mBrightnessMirror.getVisibility() == View.VISIBLE) {
+                    // Disallow new pointers while the brightness mirror is visible. This is so that
+                    // you can't touch anything other than the brightness slider while the mirror is
+                    // showing and the rest of the panel is transparent.
+                    if (ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
+                        return false;
+                    }
+                }
+                if (isDown) {
+                    getStackScrollLayout().closeControlsIfOutsideTouch(ev);
+                }
+                if (mService.isDozing()) {
+                    mService.mDozeScrimController.extendPulse();
+                }
+                // In case we start outside of the view bounds (below the status bar), we need to
+                // dispatch
+                // the touch manually as the view system can't accommodate for touches outside of
+                // the
+                // regular view bounds.
+                if (isDown && ev.getY() >= mView.getBottom()) {
+                    mExpandingBelowNotch = true;
+                }
+                if (mExpandingBelowNotch) {
+                    return mStatusBarView.dispatchTouchEvent(ev);
+                }
+
+                return null;
+            }
+
+            @Override
+            public boolean shouldInterceptTouchEvent(MotionEvent ev) {
+                if (mService.isDozing() && !mService.isPulsing()) {
+                    // Capture all touch events in always-on.
+                    return true;
+                }
+                boolean intercept = false;
+                if (notificationPanelView.isFullyExpanded()
+                        && mDragDownHelper.isDragDownEnabled()
+                        && !mService.isBouncerShowing()
+                        && !mService.isDozing()) {
+                    intercept = mDragDownHelper.onInterceptTouchEvent(ev);
+                }
+
+                return intercept;
+
+            }
+
+            @Override
+            public void didIntercept(MotionEvent ev) {
+                NotificationStackScrollLayout stackScrollLayout = getStackScrollLayout();
+                MotionEvent cancellation = MotionEvent.obtain(ev);
+                cancellation.setAction(MotionEvent.ACTION_CANCEL);
+                stackScrollLayout.onInterceptTouchEvent(cancellation);
+                notificationPanelView.onInterceptTouchEvent(cancellation);
+                cancellation.recycle();
+            }
+
+            @Override
+            public boolean handleTouchEvent(MotionEvent ev) {
+                boolean handled = false;
+                if (mService.isDozing()) {
+                    handled = !mService.isPulsing();
+                }
+                if ((mDragDownHelper.isDragDownEnabled() && !handled)
+                        || mDragDownHelper.isDraggingDown()) {
+                    // we still want to finish our drag down gesture when locking the screen
+                    handled = mDragDownHelper.onTouchEvent(ev);
+                }
+
+                return handled;
+            }
+
+            @Override
+            public void didNotHandleTouchEvent(MotionEvent ev) {
+                final int action = ev.getActionMasked();
+                if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
+                    mService.setInteracting(StatusBarManager.WINDOW_STATUS_BAR, false);
+                }
+            }
+
+            @Override
+            public boolean interceptMediaKey(KeyEvent event) {
+                return mService.interceptMediaKey(event);
+            }
+
+            @Override
+            public boolean dispatchKeyEvent(KeyEvent event) {
+                boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
+                switch (event.getKeyCode()) {
+                    case KeyEvent.KEYCODE_BACK:
+                        if (!down) {
+                            mService.onBackPressed();
+                        }
+                        return true;
+                    case KeyEvent.KEYCODE_MENU:
+                        if (!down) {
+                            return mService.onMenuPressed();
+                        }
+                        break;
+                    case KeyEvent.KEYCODE_SPACE:
+                        if (!down) {
+                            return mService.onSpacePressed();
+                        }
+                        break;
+                    case KeyEvent.KEYCODE_VOLUME_DOWN:
+                    case KeyEvent.KEYCODE_VOLUME_UP:
+                        if (mService.isDozing()) {
+                            MediaSessionLegacyHelper.getHelper(mView.getContext())
+                                    .sendVolumeKeyEvent(
+                                            event, AudioManager.USE_DEFAULT_STREAM_TYPE, true);
+                            return true;
+                        }
+                        break;
+                }
+                return false;
+            }
+        });
+
+        mView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
+            @Override
+            public void onChildViewAdded(View parent, View child) {
+                if (child.getId() == R.id.brightness_mirror) {
+                    mBrightnessMirror = child;
+                }
+            }
+
+            @Override
+            public void onChildViewRemoved(View parent, View child) {
+            }
+        });
+    }
+
+    public StatusBarWindowView getView() {
+        return mView;
+    }
+
+    public void setTouchActive(boolean touchActive) {
+        mTouchActive = touchActive;
+    }
+
+    public void cancelCurrentTouch() {
+        if (mTouchActive) {
+            final long now = SystemClock.uptimeMillis();
+            MotionEvent event = MotionEvent.obtain(now, now,
+                    MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
+            event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
+            mView.dispatchTouchEvent(event);
+            event.recycle();
+            mTouchCancelled = true;
+        }
+    }
+
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.print("  mExpandAnimationPending=");
+        pw.println(mExpandAnimationPending);
+        pw.print("  mExpandAnimationRunning=");
+        pw.println(mExpandAnimationRunning);
+        pw.print("  mTouchCancelled=");
+        pw.println(mTouchCancelled);
+        pw.print("  mTouchActive=");
+        pw.println(mTouchActive);
+    }
+
+    public void setExpandAnimationPending(boolean pending) {
+        mExpandAnimationPending = pending;
+    }
+
+    public void setExpandAnimationRunning(boolean running) {
+        mExpandAnimationRunning = running;
+    }
+
+    public void cancelExpandHelper() {
+        NotificationStackScrollLayout stackScrollLayout = getStackScrollLayout();
+        if (stackScrollLayout != null) {
+            stackScrollLayout.cancelExpandHelper();
+        }
+    }
+
+    @VisibleForTesting
+    protected NotificationStackScrollLayout getStackScrollLayout() {
+        return mStackScrollLayout;
+    }
+
+    /**
+     * Called whenever the scrims become opaque, transparent or semi-transparent.
+     */
+    public void onScrimVisibilityChanged(Integer scrimsVisible) {
+        if (mLockIcon != null) {
+            mLockIcon.onScrimVisibilityChanged(scrimsVisible);
+        }
+    }
+
+    /**
+     * Propagate {@link StatusBar} pulsing state.
+     */
+    public void setPulsing(boolean pulsing) {
+        if (mLockIcon != null) {
+            mLockIcon.setPulsing(pulsing);
+        }
+    }
+
+    /**
+     * Called when the biometric authentication mode changes.
+     *
+     * @param wakeAndUnlock If the type is {@link BiometricUnlockController#isWakeAndUnlock()}
+     * @param isUnlock      If the type is {@link BiometricUnlockController#isBiometricUnlock()} ()
+     */
+    public void onBiometricAuthModeChanged(boolean wakeAndUnlock, boolean isUnlock) {
+        if (mLockIcon != null) {
+            mLockIcon.onBiometricAuthModeChanged(wakeAndUnlock, isUnlock);
+        }
+    }
+
+    public void setStatusBarView(PhoneStatusBarView statusBarView) {
+        mStatusBarView = statusBarView;
+    }
+
+    public void setService(StatusBar statusBar) {
+        mService = statusBar;
+        NotificationStackScrollLayout stackScrollLayout = getStackScrollLayout();
+        ExpandHelper.Callback expandHelperCallback = stackScrollLayout.getExpandHelperCallback();
+        DragDownHelper.DragDownCallback dragDownCallback = stackScrollLayout.getDragDownCallback();
+        setDragDownHelper(
+                new DragDownHelper(
+                        mView.getContext(), mView, expandHelperCallback,
+                        dragDownCallback, mFalsingManager));
+    }
+
+    @VisibleForTesting
+    void setDragDownHelper(DragDownHelper dragDownHelper) {
+        mDragDownHelper = dragDownHelper;
+    }
+
+    public void suppressWakeUpGesture(boolean suppress) {
+        mSuppressingWakeUpGesture = suppress;
+    }
+
+    /**
+     * When we're launching an affordance, like double pressing power to open camera.
+     */
+    public void onShowingLaunchAffordanceChanged(Boolean showing) {
+        if (mLockIcon != null) {
+            mLockIcon.onShowingLaunchAffordanceChanged(showing);
+        }
+    }
+
+    public void setBouncerShowingScrimmed(boolean bouncerShowing) {
+        if (mLockIcon != null) {
+            mLockIcon.setBouncerShowingScrimmed(bouncerShowing);
+        }
+    }
+
+    /**
+     * When {@link KeyguardBouncer} starts to be dismissed and starts to play its animation.
+     */
+    public void onBouncerPreHideAnimation() {
+        if (mLockIcon != null) {
+            mLockIcon.onBouncerPreHideAnimation();
+        }
+    }
+
+    /**
+     * Builder for {@link StatusBarWindowViewController}.
+     */
+    public static class Builder {
+        private final InjectionInflationController mInjectionInflationController;
+        private final NotificationWakeUpCoordinator mCoordinator;
+        private final PulseExpansionHandler mPulseExpansionHandler;
+        private final DynamicPrivacyController mDynamicPrivacyController;
+        private final KeyguardBypassController mBypassController;
+        private final FalsingManager mFalsingManager;
+        private final PluginManager mPluginManager;
+        private final TunerService mTunerService;
+        private ShadeController mShadeController;
+        private final NotificationLockscreenUserManager mNotificationLockScreenUserManager;
+        private final NotificationEntryManager mNotificationEntryManager;
+        private final DozeLog mDozeLog;
+        private StatusBarWindowView mView;
+
+        @Inject
+        public Builder(
+                InjectionInflationController injectionInflationController,
+                NotificationWakeUpCoordinator coordinator,
+                PulseExpansionHandler pulseExpansionHandler,
+                DynamicPrivacyController dynamicPrivacyController,
+                KeyguardBypassController bypassController,
+                FalsingManager falsingManager,
+                PluginManager pluginManager,
+                TunerService tunerService,
+                NotificationLockscreenUserManager notificationLockscreenUserManager,
+                NotificationEntryManager notificationEntryManager,
+                DozeLog dozeLog) {
+            mInjectionInflationController = injectionInflationController;
+            mCoordinator = coordinator;
+            mPulseExpansionHandler = pulseExpansionHandler;
+            mDynamicPrivacyController = dynamicPrivacyController;
+            mBypassController = bypassController;
+            mFalsingManager = falsingManager;
+            mPluginManager = pluginManager;
+            mTunerService = tunerService;
+            mNotificationLockScreenUserManager = notificationLockscreenUserManager;
+            mNotificationEntryManager = notificationEntryManager;
+            mDozeLog = dozeLog;
+        }
+
+        /**
+         * Provide {@link StatusBarWindowView} to attach this controller to.
+         */
+        public Builder setStatusBarWindowView(StatusBarWindowView view) {
+            mView = view;
+            return this;
+        }
+
+        /**
+         * Provide {@link ShadeController} that this view needs.
+         */
+        public Builder setShadeController(ShadeController shadeController) {
+            mShadeController = shadeController;
+            return this;
+        }
+
+        /**
+         * Build a {@link StatusBarWindowView}.
+         */
+        public StatusBarWindowViewController build() {
+            return new StatusBarWindowViewController(
+                    mView,
+                    mInjectionInflationController,
+                    mCoordinator,
+                    mPulseExpansionHandler,
+                    mDynamicPrivacyController,
+                    mBypassController,
+                    mFalsingManager,
+                    mPluginManager,
+                    mTunerService,
+                    mShadeController,
+                    mNotificationLockScreenUserManager,
+                    mNotificationEntryManager,
+                    mDozeLog);
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
index e61a67c..ce929b7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
@@ -28,7 +28,8 @@
 
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.broadcast.BroadcastDispatcher;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 
 /**
@@ -100,7 +101,7 @@
     }
 
     public static void setWindowOnTop(Dialog dialog) {
-        if (Dependency.get(KeyguardMonitor.class).isShowing()) {
+        if (Dependency.get(KeyguardStateController.class).isShowing()) {
             dialog.getWindow().setType(LayoutParams.TYPE_STATUS_BAR_PANEL);
         } else {
             dialog.getWindow().setType(LayoutParams.TYPE_STATUS_BAR_SUB_PANEL);
@@ -138,20 +139,21 @@
 
         private final Dialog mDialog;
         private boolean mRegistered;
+        private final BroadcastDispatcher mBroadcastDispatcher;
 
         DismissReceiver(Dialog dialog) {
             mDialog = dialog;
+            mBroadcastDispatcher = Dependency.get(BroadcastDispatcher.class);
         }
 
         void register() {
-            mDialog.getContext()
-                    .registerReceiverAsUser(this, UserHandle.CURRENT, INTENT_FILTER, null, null);
+            mBroadcastDispatcher.registerReceiver(this, INTENT_FILTER, null, UserHandle.CURRENT);
             mRegistered = true;
         }
 
         void unregister() {
             if (mRegistered) {
-                mDialog.getContext().unregisterReceiver(this);
+                mBroadcastDispatcher.unregisterReceiver(this);
                 mRegistered = false;
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
deleted file mode 100644
index c76f93e..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2014 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.statusbar.phone;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.hardware.biometrics.BiometricSourceType;
-import android.os.Build;
-import android.os.Trace;
-
-import com.android.internal.widget.LockPatternUtils;
-import com.android.keyguard.KeyguardUpdateMonitor;
-import com.android.keyguard.KeyguardUpdateMonitorCallback;
-import com.android.systemui.DejankUtils;
-import com.android.systemui.Dependency;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-
-/**
- * Caches whether the current unlock method is insecure, taking trust into account. This information
- * might be a little bit out of date and should not be used for actual security decisions; it should
- * be only used for visual indications.
- */
-public class UnlockMethodCache {
-
-    private static UnlockMethodCache sInstance;
-    private static final boolean DEBUG_AUTH_WITH_ADB = false;
-    private static final String AUTH_BROADCAST_KEY = "debug_trigger_auth";
-
-    private final LockPatternUtils mLockPatternUtils;
-    private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
-    private final ArrayList<OnUnlockMethodChangedListener> mListeners = new ArrayList<>();
-    /** Whether the user configured a secure unlock method (PIN, password, etc.) */
-    private boolean mSecure;
-    /** Whether the unlock method is currently insecure (insecure method or trusted environment) */
-    private boolean mCanSkipBouncer;
-    private boolean mTrustManaged;
-    private boolean mTrusted;
-    private boolean mDebugUnlocked = false;
-    private boolean mFaceAuthEnabled;
-
-    private UnlockMethodCache(Context ctx) {
-        mLockPatternUtils = new LockPatternUtils(ctx);
-        mKeyguardUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
-        Dependency.get(KeyguardUpdateMonitor.class).registerCallback(mCallback);
-        update(true /* updateAlways */);
-        if (Build.IS_DEBUGGABLE && DEBUG_AUTH_WITH_ADB) {
-            // Watch for interesting updates
-            final IntentFilter filter = new IntentFilter();
-            filter.addAction(AUTH_BROADCAST_KEY);
-            ctx.registerReceiver(new BroadcastReceiver() {
-                @Override
-                public void onReceive(Context context, Intent intent) {
-                    if (DEBUG_AUTH_WITH_ADB && AUTH_BROADCAST_KEY.equals(intent.getAction())) {
-                        mDebugUnlocked = !mDebugUnlocked;
-                        update(true /* updateAlways */);
-                    }
-                }
-            }, filter, null, null);
-        }
-    }
-
-    public static UnlockMethodCache getInstance(Context context) {
-        if (sInstance == null) {
-            sInstance = new UnlockMethodCache(context);
-        }
-        return sInstance;
-    }
-
-    /**
-     * @return whether the user configured a secure unlock method like PIN, password, etc.
-     */
-    public boolean isMethodSecure() {
-        return mSecure;
-    }
-
-    public boolean isTrusted() {
-        return mTrusted;
-    }
-
-    /**
-     * @return whether the lockscreen is currently insecure, and the bouncer won't be shown
-     */
-    public boolean canSkipBouncer() {
-        return mCanSkipBouncer;
-    }
-
-    public void addListener(OnUnlockMethodChangedListener listener) {
-        mListeners.add(listener);
-    }
-
-    public void removeListener(OnUnlockMethodChangedListener listener) {
-        mListeners.remove(listener);
-    }
-
-    /**
-     * If there are faces enrolled and user enabled face auth on keyguard.
-     */
-    public boolean isFaceAuthEnabled() {
-        return mFaceAuthEnabled;
-    }
-
-    private void update(boolean updateAlways) {
-        Trace.beginSection("UnlockMethodCache#update");
-        int user = KeyguardUpdateMonitor.getCurrentUser();
-        boolean secure = mLockPatternUtils.isSecure(user);
-        boolean canSkipBouncer = !secure || mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)
-                || (Build.IS_DEBUGGABLE && DEBUG_AUTH_WITH_ADB && mDebugUnlocked);
-        boolean trustManaged = mKeyguardUpdateMonitor.getUserTrustIsManaged(user);
-        boolean trusted = mKeyguardUpdateMonitor.getUserHasTrust(user);
-        boolean faceAuthEnabled = mKeyguardUpdateMonitor.isFaceAuthEnabledForUser(user);
-        boolean changed = secure != mSecure || canSkipBouncer != mCanSkipBouncer
-                || trustManaged != mTrustManaged
-                || mFaceAuthEnabled != faceAuthEnabled;
-        if (changed || updateAlways) {
-            mSecure = secure;
-            mCanSkipBouncer = canSkipBouncer;
-            mTrusted = trusted;
-            mTrustManaged = trustManaged;
-            mFaceAuthEnabled = faceAuthEnabled;
-            Trace.endSection();
-            notifyListeners();
-        } else {
-            Trace.endSection();
-        }
-    }
-
-    private void notifyListeners() {
-        String tag = "UnlockMethodCache#notifyListeners";
-        DejankUtils.startDetectingBlockingIpcs(tag);
-        for (OnUnlockMethodChangedListener listener : mListeners) {
-            listener.onUnlockMethodStateChanged();
-        }
-        DejankUtils.stopDetectingBlockingIpcs(tag);
-    }
-
-    public void dump(PrintWriter pw) {
-        pw.println("UnlockMethodCache");
-        pw.println("  mSecure: " + mSecure);
-        pw.println("  mCanSkipBouncer: " + mCanSkipBouncer);
-        pw.println("  mTrustManaged: " + mTrustManaged);
-        pw.println("  mTrusted: " + mTrusted);
-        pw.println("  mDebugUnlocked: " + mDebugUnlocked);
-        pw.println("  mFaceAuthEnabled: " + mFaceAuthEnabled);
-    }
-
-    private final KeyguardUpdateMonitorCallback mCallback = new KeyguardUpdateMonitorCallback() {
-        @Override
-        public void onUserSwitchComplete(int userId) {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onTrustChanged(int userId) {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onTrustManagedChanged(int userId) {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onStartedWakingUp() {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onBiometricAuthenticated(int userId, BiometricSourceType biometricSourceType) {
-            Trace.beginSection("KeyguardUpdateMonitorCallback#onBiometricAuthenticated");
-            if (!mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed()) {
-                Trace.endSection();
-                return;
-            }
-            update(false /* updateAlways */);
-            Trace.endSection();
-        }
-
-        @Override
-        public void onFaceUnlockStateChanged(boolean running, int userId) {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onStrongAuthStateChanged(int userId) {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onScreenTurnedOff() {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onKeyguardVisibilityChanged(boolean showing) {
-            update(false /* updateAlways */);
-        }
-
-        @Override
-        public void onBiometricsCleared() {
-            update(false /* alwaysUpdate */);
-        }
-    };
-
-    public boolean isTrustManaged() {
-        return mTrustManaged;
-    }
-
-    public static interface OnUnlockMethodChangedListener {
-        void onUnlockMethodStateChanged();
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
index 111cdd2..738d076 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
@@ -45,9 +45,7 @@
     /**
      * Returns {@code true} if AOD was disabled by power saving policies.
      */
-    default boolean isAodPowerSave() {
-        return isPowerSave();
-    }
+    boolean isAodPowerSave();
 
     /**
      * A listener that will be notified whenever a change in battery level or power save mode has
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
index c2c3f81..b331fc3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
@@ -16,6 +16,8 @@
 
 package com.android.systemui.statusbar.policy;
 
+import static com.android.systemui.util.InjectionInflationController.VIEW_CONTEXT;
+
 import android.app.StatusBarManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -44,6 +46,7 @@
 import com.android.systemui.FontSizeUtils;
 import com.android.systemui.R;
 import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.plugins.DarkIconDispatcher;
 import com.android.systemui.plugins.DarkIconDispatcher.DarkReceiver;
 import com.android.systemui.settings.CurrentUserTracker;
@@ -60,6 +63,9 @@
 import java.util.Locale;
 import java.util.TimeZone;
 
+import javax.inject.Inject;
+import javax.inject.Named;
+
 /**
  * Digital clock for the status bar.
  */
@@ -107,15 +113,20 @@
      */
     private int mNonAdaptedColor;
 
-    public Clock(Context context) {
-        this(context, null);
-    }
+    private final BroadcastDispatcher mBroadcastDispatcher;
 
     public Clock(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
+        this(context, attrs, null);
     }
 
-    public Clock(Context context, AttributeSet attrs, int defStyle) {
+    @Inject
+    public Clock(@Named(VIEW_CONTEXT) Context context, AttributeSet attrs,
+            BroadcastDispatcher broadcastDispatcher) {
+        this(context, attrs, 0, broadcastDispatcher);
+    }
+
+    public Clock(Context context, AttributeSet attrs, int defStyle,
+            BroadcastDispatcher broadcastDispatcher) {
         super(context, attrs, defStyle);
         TypedArray a = context.getTheme().obtainStyledAttributes(
                 attrs,
@@ -134,6 +145,7 @@
                 mCurrentUserId = newUserId;
             }
         };
+        mBroadcastDispatcher = broadcastDispatcher;
     }
 
     @Override
@@ -358,11 +370,11 @@
                 }
                 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
                 filter.addAction(Intent.ACTION_SCREEN_ON);
-                mContext.registerReceiver(mScreenReceiver, filter);
+                mBroadcastDispatcher.registerReceiver(mScreenReceiver, filter);
             }
         } else {
             if (mSecondsHandler != null) {
-                mContext.unregisterReceiver(mScreenReceiver);
+                mBroadcastDispatcher.unregisterReceiver(mScreenReceiver);
                 mSecondsHandler.removeCallbacks(mSecondTick);
                 mSecondsHandler = null;
                 updateClock();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitor.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitor.java
deleted file mode 100644
index 6dc90b9..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitor.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2016 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.statusbar.policy;
-
-import com.android.systemui.statusbar.policy.KeyguardMonitor.Callback;
-
-public interface KeyguardMonitor extends CallbackController<Callback> {
-
-    boolean isSecure();
-    boolean isShowing();
-    boolean isOccluded();
-    boolean isKeyguardFadingAway();
-    boolean isKeyguardGoingAway();
-    boolean isLaunchTransitionFadingAway();
-    long getKeyguardFadingAwayDuration();
-    long getKeyguardFadingAwayDelay();
-    long calculateGoingToFullShadeDelay();
-
-    /**
-     * @return a shortened fading away duration similar to
-     * {{@link #getKeyguardFadingAwayDuration()}} which may only span half of the duration, unless
-     * we're bypassing
-     */
-    default long getShortenedFadingAwayDuration() {
-        if (isBypassFadingAnimation()) {
-            return getKeyguardFadingAwayDuration();
-        } else {
-            return getKeyguardFadingAwayDuration() / 2;
-        }
-    }
-
-    default boolean isDeviceInteractive() {
-        return false;
-    }
-
-    default void setLaunchTransitionFadingAway(boolean b) {
-    }
-
-    default void notifyKeyguardGoingAway(boolean b) {
-    }
-
-    /**
-     * @return {@code true} if the current fading away animation is the fast bypass fading.
-     */
-    default boolean isBypassFadingAnimation() {
-        return false;
-    }
-
-    /**
-     * Notifies that the Keyguard is fading away with the specified timings.
-     * @param delay the precalculated animation delay in milliseconds
-     * @param fadeoutDuration the duration of the exit animation, in milliseconds
-     * @param isBypassFading is this a fading away animation while bypassing
-     */
-    default void notifyKeyguardFadingAway(long delay, long fadeoutDuration,
-            boolean isBypassFading) {
-    }
-
-    default void notifyKeyguardDoneFading() {
-    }
-
-    default void notifyKeyguardState(boolean showing, boolean methodSecure, boolean occluded) {
-    }
-
-    interface Callback {
-        default void onKeyguardShowingChanged() {}
-        default void onKeyguardFadingAwayChanged() {}
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitorImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitorImpl.java
deleted file mode 100644
index e8b0f9b..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitorImpl.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2014 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.statusbar.policy;
-
-import android.annotation.NonNull;
-import android.content.Context;
-
-import com.android.internal.util.Preconditions;
-import com.android.keyguard.KeyguardUpdateMonitor;
-import com.android.keyguard.KeyguardUpdateMonitorCallback;
-import com.android.systemui.Dependency;
-
-import java.util.ArrayList;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-/**
- */
-@Singleton
-public class KeyguardMonitorImpl extends KeyguardUpdateMonitorCallback
-        implements KeyguardMonitor {
-
-    private final ArrayList<Callback> mCallbacks = new ArrayList<>();
-
-    private final Context mContext;
-    private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
-
-    private boolean mShowing;
-    private boolean mSecure;
-    private boolean mOccluded;
-
-    private boolean mListening;
-    private boolean mKeyguardFadingAway;
-    private long mKeyguardFadingAwayDelay;
-    private long mKeyguardFadingAwayDuration;
-    private boolean mKeyguardGoingAway;
-    private boolean mLaunchTransitionFadingAway;
-    private boolean mBypassFadingAnimation;
-
-    /**
-     */
-    @Inject
-    public KeyguardMonitorImpl(Context context) {
-        mContext = context;
-        mKeyguardUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
-    }
-
-    @Override
-    public void addCallback(@NonNull Callback callback) {
-        Preconditions.checkNotNull(callback, "Callback must not be null. b/128895449");
-        mCallbacks.add(callback);
-        if (mCallbacks.size() != 0 && !mListening) {
-            mListening = true;
-            mKeyguardUpdateMonitor.registerCallback(this);
-        }
-    }
-
-    @Override
-    public void removeCallback(@NonNull Callback callback) {
-        Preconditions.checkNotNull(callback, "Callback must not be null. b/128895449");
-        if (mCallbacks.remove(callback) && mCallbacks.size() == 0 && mListening) {
-            mListening = false;
-            mKeyguardUpdateMonitor.removeCallback(this);
-        }
-    }
-
-    @Override
-    public boolean isShowing() {
-        return mShowing;
-    }
-
-    @Override
-    public boolean isSecure() {
-        return mSecure;
-    }
-
-    @Override
-    public boolean isOccluded() {
-        return mOccluded;
-    }
-
-    public void notifyKeyguardState(boolean showing, boolean secure, boolean occluded) {
-        if (mShowing == showing && mSecure == secure && mOccluded == occluded) return;
-        mShowing = showing;
-        mSecure = secure;
-        mOccluded = occluded;
-        notifyKeyguardChanged();
-    }
-
-    @Override
-    public void onTrustChanged(int userId) {
-        notifyKeyguardChanged();
-    }
-
-    public boolean isDeviceInteractive() {
-        return mKeyguardUpdateMonitor.isDeviceInteractive();
-    }
-
-    private void notifyKeyguardChanged() {
-        // Copy the list to allow removal during callback.
-        new ArrayList<>(mCallbacks).forEach(Callback::onKeyguardShowingChanged);
-    }
-
-    public void notifyKeyguardFadingAway(long delay, long fadeoutDuration, boolean isBypassFading) {
-        mKeyguardFadingAwayDelay = delay;
-        mKeyguardFadingAwayDuration = fadeoutDuration;
-        mBypassFadingAnimation = isBypassFading;
-        setKeyguardFadingAway(true);
-    }
-
-    private void setKeyguardFadingAway(boolean keyguardFadingAway) {
-        if (mKeyguardFadingAway != keyguardFadingAway) {
-            mKeyguardFadingAway = keyguardFadingAway;
-            ArrayList<Callback> callbacks = new ArrayList<>(mCallbacks);
-            for (int i = 0; i < callbacks.size(); i++) {
-                callbacks.get(i).onKeyguardFadingAwayChanged();
-            }
-        }
-    }
-
-    public void notifyKeyguardDoneFading() {
-        mKeyguardGoingAway = false;
-        setKeyguardFadingAway(false);
-    }
-
-    @Override
-    public boolean isKeyguardFadingAway() {
-        return mKeyguardFadingAway;
-    }
-
-    @Override
-    public boolean isKeyguardGoingAway() {
-        return mKeyguardGoingAway;
-    }
-
-    @Override
-    public boolean isBypassFadingAnimation() {
-        return mBypassFadingAnimation;
-    }
-
-    @Override
-    public long getKeyguardFadingAwayDelay() {
-        return mKeyguardFadingAwayDelay;
-    }
-
-    @Override
-    public long getKeyguardFadingAwayDuration() {
-        return mKeyguardFadingAwayDuration;
-    }
-
-    @Override
-    public long calculateGoingToFullShadeDelay() {
-        return mKeyguardFadingAwayDelay + mKeyguardFadingAwayDuration;
-    }
-
-    public void notifyKeyguardGoingAway(boolean keyguardGoingAway) {
-        mKeyguardGoingAway = keyguardGoingAway;
-    }
-
-    public void setLaunchTransitionFadingAway(boolean fadingAway) {
-        mLaunchTransitionFadingAway = fadingAway;
-    }
-
-    @Override
-    public boolean isLaunchTransitionFadingAway() {
-        return mLaunchTransitionFadingAway;
-    }
-}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateController.java
new file mode 100644
index 0000000..aefe201
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateController.java
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2016 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.statusbar.policy;
+
+import com.android.systemui.statusbar.StatusBarState;
+import com.android.systemui.statusbar.policy.KeyguardStateController.Callback;
+
+/**
+ * Source of truth for keyguard state: If locked, occluded, has password, trusted etc.
+ */
+public interface KeyguardStateController extends CallbackController<Callback> {
+
+    /**
+     * If the device is locked or unlocked.
+     */
+    default boolean isUnlocked() {
+        return !isShowing() || canDismissLockScreen();
+    }
+
+    /**
+     * If the lock screen is visible.
+     * The keyguard is also visible when the device is asleep or in always on mode, except when
+     * the screen timed out and the user can unlock by quickly pressing power.
+     *
+     * This is unrelated to being locked or not.
+     *
+     * @see #isUnlocked()
+     * @see #canDismissLockScreen()
+     */
+    boolean isShowing();
+
+    /**
+     * If swiping up will unlock without asking for a password.
+     * @see #isUnlocked()
+     */
+    boolean canDismissLockScreen();
+
+    /**
+     * If the device has PIN/pattern/password or a lock screen at all.
+     */
+    boolean isMethodSecure();
+
+    /**
+     * When there's an {@link android.app.Activity} on top of the keyguard, where
+     * {@link android.app.Activity#setShowWhenLocked(boolean)} is true.
+     */
+    boolean isOccluded();
+
+    /**
+     * If a {@link android.service.trust.TrustAgentService} is keeping the device unlocked.
+     * {@link #canDismissLockScreen()} is better source of truth that also considers this state.
+     */
+    boolean isTrusted();
+
+    /**
+     * If the keyguard dismissal animation is running.
+     * @see #isKeyguardGoingAway()
+     */
+    boolean isKeyguardFadingAway();
+
+    /**
+     * When the keyguard challenge was successfully solved, and {@link android.app.ActivityManager}
+     * is launching the activity that will be revealed.
+     *
+     * This also includes the animation of the keyguard being dismissed, meaning that this will
+     * return {@code true} whenever {@link #isKeyguardFadingAway()} also returns {@code true}.
+     */
+    boolean isKeyguardGoingAway();
+
+    /**
+     * @return a shortened fading away duration similar to
+     * {{@link #getKeyguardFadingAwayDuration()}} which may only span half of the duration, unless
+     * we're bypassing
+     */
+    default long getShortenedFadingAwayDuration() {
+        if (isBypassFadingAnimation()) {
+            return getKeyguardFadingAwayDuration();
+        } else {
+            return getKeyguardFadingAwayDuration() / 2;
+        }
+    }
+
+    /**
+     * @return {@code true} if the current fading away animation is the fast bypass fading.
+     */
+    default boolean isBypassFadingAnimation() {
+        return false;
+    }
+
+    /**
+     * Notifies that the Keyguard is fading away with the specified timings.
+     * @param delay the precalculated animation delay in milliseconds
+     * @param fadeoutDuration the duration of the exit animation, in milliseconds
+     * @param isBypassFading is this a fading away animation while bypassing
+     */
+    default void notifyKeyguardFadingAway(long delay, long fadeoutDuration,
+            boolean isBypassFading) {
+    }
+
+    /**
+     * If there are faces enrolled and user enabled face auth on keyguard.
+     */
+    default boolean isFaceAuthEnabled() {
+        return false;
+    }
+
+    /**
+     * If the animation that morphs a notification into an app window is playing.
+     */
+    boolean isLaunchTransitionFadingAway();
+
+    /**
+     * How long the keyguard dismissal animation should take when unlocking.
+     */
+    long getKeyguardFadingAwayDuration();
+
+    /**
+     * Delay for {@link #getKeyguardFadingAwayDuration()}.
+     */
+    long getKeyguardFadingAwayDelay();
+
+    /**
+     * Delay when going from {@link StatusBarState#KEYGUARD} to {@link StatusBarState#SHADE} or
+     * {@link StatusBarState#SHADE_LOCKED}.
+     */
+    long calculateGoingToFullShadeDelay();
+
+    /** **/
+    default void setLaunchTransitionFadingAway(boolean b) {}
+    /** **/
+    default void notifyKeyguardGoingAway(boolean b) {}
+    /** **/
+    default void notifyKeyguardDoneFading() {}
+    /** **/
+    default void notifyKeyguardState(boolean showing, boolean methodSecure, boolean occluded) {}
+
+    /**
+     * Callback for authentication events.
+     */
+    interface Callback {
+        /**
+         * Called when the locked state of the device changes. The lock screen might still be
+         * showing on some cases, like when a {@link android.service.trust.TrustAgentService} is
+         * active, or face auth was triggered but the user didn't swipe up to dismiss the lock
+         * screen yet.
+         */
+        default void onUnlockedChanged() {}
+
+        /**
+         * If the lock screen is active or not. This is different from being locked, since the lock
+         * screen can be visible but unlocked by {@link android.service.trust.TrustAgentService} or
+         * face unlock.
+         *
+         * @see #isShowing()
+         */
+        default void onKeyguardShowingChanged() {}
+
+        /**
+         * Triggered when the device was just unlocked and the lock screen is being dismissed.
+         */
+        default void onKeyguardFadingAwayChanged() {}
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
new file mode 100644
index 0000000..392094d
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
@@ -0,0 +1,344 @@
+/*
+ * Copyright (C) 2014 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.statusbar.policy;
+
+import android.annotation.NonNull;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.hardware.biometrics.BiometricSourceType;
+import android.os.Build;
+import android.os.Trace;
+
+import com.android.internal.util.Preconditions;
+import com.android.internal.widget.LockPatternUtils;
+import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.keyguard.KeyguardUpdateMonitorCallback;
+import com.android.systemui.Dependency;
+import com.android.systemui.Dumpable;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+/**
+ */
+@Singleton
+public class KeyguardStateControllerImpl extends KeyguardUpdateMonitorCallback
+        implements KeyguardStateController, Dumpable {
+
+    private static final boolean DEBUG_AUTH_WITH_ADB = false;
+    private static final String AUTH_BROADCAST_KEY = "debug_trigger_auth";
+
+    private final ArrayList<Callback> mCallbacks = new ArrayList<>();
+    private final Context mContext;
+    private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+    private final LockPatternUtils mLockPatternUtils;
+    private final KeyguardUpdateMonitorCallback mKeyguardUpdateMonitorCallback =
+            new LockedStateInvalidator();
+
+    private boolean mCanDismissLockScreen;
+    private boolean mShowing;
+    private boolean mSecure;
+    private boolean mOccluded;
+
+    private boolean mListening;
+    private boolean mKeyguardFadingAway;
+    private long mKeyguardFadingAwayDelay;
+    private long mKeyguardFadingAwayDuration;
+    private boolean mKeyguardGoingAway;
+    private boolean mLaunchTransitionFadingAway;
+    private boolean mBypassFadingAnimation;
+    private boolean mTrustManaged;
+    private boolean mTrusted;
+    private boolean mDebugUnlocked = false;
+    private boolean mFaceAuthEnabled;
+
+    /**
+     */
+    @Inject
+    public KeyguardStateControllerImpl(Context context) {
+        mContext = context;
+        mKeyguardUpdateMonitor = Dependency.get(KeyguardUpdateMonitor.class);
+        mLockPatternUtils = new LockPatternUtils(context);
+        mKeyguardUpdateMonitor.registerCallback(mKeyguardUpdateMonitorCallback);
+
+        update(true /* updateAlways */);
+        if (Build.IS_DEBUGGABLE && DEBUG_AUTH_WITH_ADB) {
+            // Watch for interesting updates
+            final IntentFilter filter = new IntentFilter();
+            filter.addAction(AUTH_BROADCAST_KEY);
+            context.registerReceiver(new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    if (DEBUG_AUTH_WITH_ADB && AUTH_BROADCAST_KEY.equals(intent.getAction())) {
+                        mDebugUnlocked = !mDebugUnlocked;
+                        update(true /* updateAlways */);
+                    }
+                }
+            }, filter, null, null);
+        }
+    }
+
+    @Override
+    public void addCallback(@NonNull Callback callback) {
+        Preconditions.checkNotNull(callback, "Callback must not be null. b/128895449");
+        if (!mCallbacks.contains(callback)) {
+            mCallbacks.add(callback);
+        }
+        if (mCallbacks.size() != 0 && !mListening) {
+            mListening = true;
+            mKeyguardUpdateMonitor.registerCallback(this);
+        }
+    }
+
+    @Override
+    public void removeCallback(@NonNull Callback callback) {
+        Preconditions.checkNotNull(callback, "Callback must not be null. b/128895449");
+        if (mCallbacks.remove(callback) && mCallbacks.size() == 0 && mListening) {
+            mListening = false;
+            mKeyguardUpdateMonitor.removeCallback(this);
+        }
+    }
+
+    @Override
+    public boolean isShowing() {
+        return mShowing;
+    }
+
+    @Override
+    public boolean isMethodSecure() {
+        return mSecure;
+    }
+
+    @Override
+    public boolean isOccluded() {
+        return mOccluded;
+    }
+
+    @Override
+    public boolean isTrusted() {
+        return mTrusted;
+    }
+
+    @Override
+    public void notifyKeyguardState(boolean showing, boolean secure, boolean occluded) {
+        if (mShowing == showing && mSecure == secure && mOccluded == occluded) return;
+        mShowing = showing;
+        mSecure = secure;
+        mOccluded = occluded;
+        notifyKeyguardChanged();
+    }
+
+    @Override
+    public void onTrustChanged(int userId) {
+        notifyKeyguardChanged();
+    }
+
+    private void notifyKeyguardChanged() {
+        Trace.beginSection("KeyguardStateController#notifyKeyguardChanged");
+        // Copy the list to allow removal during callback.
+        new ArrayList<>(mCallbacks).forEach(Callback::onKeyguardShowingChanged);
+        Trace.endSection();
+    }
+
+    private void notifyUnlockedChanged() {
+        Trace.beginSection("KeyguardStateController#notifyUnlockedChanged");
+        // Copy the list to allow removal during callback.
+        new ArrayList<>(mCallbacks).forEach(Callback::onUnlockedChanged);
+        Trace.endSection();
+    }
+
+    @Override
+    public void notifyKeyguardFadingAway(long delay, long fadeoutDuration, boolean isBypassFading) {
+        mKeyguardFadingAwayDelay = delay;
+        mKeyguardFadingAwayDuration = fadeoutDuration;
+        mBypassFadingAnimation = isBypassFading;
+        setKeyguardFadingAway(true);
+    }
+
+    private void setKeyguardFadingAway(boolean keyguardFadingAway) {
+        if (mKeyguardFadingAway != keyguardFadingAway) {
+            mKeyguardFadingAway = keyguardFadingAway;
+            ArrayList<Callback> callbacks = new ArrayList<>(mCallbacks);
+            for (int i = 0; i < callbacks.size(); i++) {
+                callbacks.get(i).onKeyguardFadingAwayChanged();
+            }
+        }
+    }
+
+    @Override
+    public void notifyKeyguardDoneFading() {
+        mKeyguardGoingAway = false;
+        setKeyguardFadingAway(false);
+    }
+
+    private void update(boolean updateAlways) {
+        Trace.beginSection("KeyguardStateController#update");
+        int user = KeyguardUpdateMonitor.getCurrentUser();
+        boolean secure = mLockPatternUtils.isSecure(user);
+        boolean canDismissLockScreen = !secure || mKeyguardUpdateMonitor.getUserCanSkipBouncer(user)
+                || (Build.IS_DEBUGGABLE && DEBUG_AUTH_WITH_ADB && mDebugUnlocked);
+        boolean trustManaged = mKeyguardUpdateMonitor.getUserTrustIsManaged(user);
+        boolean trusted = mKeyguardUpdateMonitor.getUserHasTrust(user);
+        boolean faceAuthEnabled = mKeyguardUpdateMonitor.isFaceAuthEnabledForUser(user);
+        boolean changed = secure != mSecure || canDismissLockScreen != mCanDismissLockScreen
+                || trustManaged != mTrustManaged
+                || mFaceAuthEnabled != faceAuthEnabled;
+        if (changed || updateAlways) {
+            mSecure = secure;
+            mCanDismissLockScreen = canDismissLockScreen;
+            mTrusted = trusted;
+            mTrustManaged = trustManaged;
+            mFaceAuthEnabled = faceAuthEnabled;
+            notifyUnlockedChanged();
+        }
+        Trace.endSection();
+    }
+
+    @Override
+    public boolean canDismissLockScreen() {
+        return mCanDismissLockScreen;
+    }
+
+    @Override
+    public boolean isFaceAuthEnabled() {
+        return mFaceAuthEnabled;
+    }
+
+    @Override
+    public boolean isKeyguardFadingAway() {
+        return mKeyguardFadingAway;
+    }
+
+    @Override
+    public boolean isKeyguardGoingAway() {
+        return mKeyguardGoingAway;
+    }
+
+    @Override
+    public boolean isBypassFadingAnimation() {
+        return mBypassFadingAnimation;
+    }
+
+    @Override
+    public long getKeyguardFadingAwayDelay() {
+        return mKeyguardFadingAwayDelay;
+    }
+
+    @Override
+    public long getKeyguardFadingAwayDuration() {
+        return mKeyguardFadingAwayDuration;
+    }
+
+    @Override
+    public long calculateGoingToFullShadeDelay() {
+        return mKeyguardFadingAwayDelay + mKeyguardFadingAwayDuration;
+    }
+
+    @Override
+    public void notifyKeyguardGoingAway(boolean keyguardGoingAway) {
+        mKeyguardGoingAway = keyguardGoingAway;
+    }
+
+    @Override
+    public void setLaunchTransitionFadingAway(boolean fadingAway) {
+        mLaunchTransitionFadingAway = fadingAway;
+    }
+
+    @Override
+    public boolean isLaunchTransitionFadingAway() {
+        return mLaunchTransitionFadingAway;
+    }
+
+    /**
+     * Dumps internal state for debugging.
+     * @param pw Where to dump.
+     */
+    @Override
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.println("KeyguardStateController:");
+        pw.println("  mSecure: " + mSecure);
+        pw.println("  mCanDismissLockScreen: " + mCanDismissLockScreen);
+        pw.println("  mTrustManaged: " + mTrustManaged);
+        pw.println("  mTrusted: " + mTrusted);
+        pw.println("  mDebugUnlocked: " + mDebugUnlocked);
+        pw.println("  mFaceAuthEnabled: " + mFaceAuthEnabled);
+    }
+
+    private class LockedStateInvalidator extends KeyguardUpdateMonitorCallback {
+        @Override
+        public void onUserSwitchComplete(int userId) {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onTrustChanged(int userId) {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onTrustManagedChanged(int userId) {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onStartedWakingUp() {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onBiometricAuthenticated(int userId, BiometricSourceType biometricSourceType) {
+            Trace.beginSection("KeyguardUpdateMonitorCallback#onBiometricAuthenticated");
+            if (!mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed()) {
+                Trace.endSection();
+                return;
+            }
+            update(false /* updateAlways */);
+            Trace.endSection();
+        }
+
+        @Override
+        public void onFaceUnlockStateChanged(boolean running, int userId) {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onStrongAuthStateChanged(int userId) {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onScreenTurnedOff() {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onKeyguardVisibilityChanged(boolean showing) {
+            update(false /* updateAlways */);
+        }
+
+        @Override
+        public void onBiometricsCleared() {
+            update(false /* alwaysUpdate */);
+        }
+    };
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
index 4fa4b6c..95ae23c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
@@ -62,7 +62,6 @@
 import com.android.systemui.plugins.qs.DetailAdapter;
 import com.android.systemui.qs.tiles.UserDetailView;
 import com.android.systemui.statusbar.phone.SystemUIDialog;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -93,7 +92,7 @@
     private final ArrayList<WeakReference<BaseUserAdapter>> mAdapters = new ArrayList<>();
     private final GuestResumeSessionReceiver mGuestResumeSessionReceiver
             = new GuestResumeSessionReceiver();
-    private final KeyguardMonitor mKeyguardMonitor;
+    private final KeyguardStateController mKeyguardStateController;
     protected final Handler mHandler;
     private final ActivityStarter mActivityStarter;
 
@@ -110,13 +109,13 @@
     private SparseBooleanArray mForcePictureLoadForUserId = new SparseBooleanArray(2);
 
     @Inject
-    public UserSwitcherController(Context context, KeyguardMonitor keyguardMonitor,
+    public UserSwitcherController(Context context, KeyguardStateController keyguardStateController,
             @Named(MAIN_HANDLER_NAME) Handler handler, ActivityStarter activityStarter) {
         mContext = context;
         if (!UserManager.isGuestUserEphemeral()) {
             mGuestResumeSessionReceiver.register(context);
         }
-        mKeyguardMonitor = keyguardMonitor;
+        mKeyguardStateController = keyguardStateController;
         mHandler = handler;
         mActivityStarter = activityStarter;
         mUserManager = UserManager.get(context);
@@ -149,7 +148,7 @@
         // Fetch initial values.
         mSettingsObserver.onChange(false);
 
-        keyguardMonitor.addCallback(mCallback);
+        keyguardStateController.addCallback(mCallback);
         listenForCallState();
 
         refreshUsers(UserHandle.USER_NULL);
@@ -597,20 +596,18 @@
     public static abstract class BaseUserAdapter extends BaseAdapter {
 
         final UserSwitcherController mController;
-        private final KeyguardMonitor mKeyguardMonitor;
-        private final UnlockMethodCache mUnlockMethodCache;
+        private final KeyguardStateController mKeyguardStateController;
 
         protected BaseUserAdapter(UserSwitcherController controller) {
             mController = controller;
-            mKeyguardMonitor = controller.mKeyguardMonitor;
-            mUnlockMethodCache = UnlockMethodCache.getInstance(controller.mContext);
+            mKeyguardStateController = controller.mKeyguardStateController;
             controller.addAdapter(new WeakReference<>(this));
         }
 
         public int getUserCount() {
-            boolean secureKeyguardShowing = mKeyguardMonitor.isShowing()
-                    && mKeyguardMonitor.isSecure()
-                    && !mUnlockMethodCache.canSkipBouncer();
+            boolean secureKeyguardShowing = mKeyguardStateController.isShowing()
+                    && mKeyguardStateController.isMethodSecure()
+                    && !mKeyguardStateController.canDismissLockScreen();
             if (!secureKeyguardShowing) {
                 return mController.getUsers().size();
             }
@@ -630,9 +627,9 @@
 
         @Override
         public int getCount() {
-            boolean secureKeyguardShowing = mKeyguardMonitor.isShowing()
-                    && mKeyguardMonitor.isSecure()
-                    && !mUnlockMethodCache.canSkipBouncer();
+            boolean secureKeyguardShowing = mKeyguardStateController.isShowing()
+                    && mKeyguardStateController.isMethodSecure()
+                    && !mKeyguardStateController.canDismissLockScreen();
             if (!secureKeyguardShowing) {
                 return mController.getUsers().size();
             }
@@ -819,19 +816,21 @@
         }
     };
 
-    private final KeyguardMonitor.Callback mCallback = new KeyguardMonitor.Callback() {
-        @Override
-        public void onKeyguardShowingChanged() {
+    private final KeyguardStateController.Callback mCallback =
+            new KeyguardStateController.Callback() {
+                @Override
+                public void onKeyguardShowingChanged() {
 
-            // When Keyguard is going away, we don't need to update our items immediately which
-            // helps making the transition faster.
-            if (!mKeyguardMonitor.isShowing()) {
-                mHandler.post(UserSwitcherController.this::notifyAdapters);
-            } else {
-                notifyAdapters();
-            }
-        }
-    };
+                    // When Keyguard is going away, we don't need to update our items immediately
+                    // which
+                    // helps making the transition faster.
+                    if (!mKeyguardStateController.isShowing()) {
+                        mHandler.post(UserSwitcherController.this::notifyAdapters);
+                    } else {
+                        notifyAdapters();
+                    }
+                }
+            };
 
     private final class ExitGuestDialog extends SystemUIDialog implements
             DialogInterface.OnClickListener {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
new file mode 100644
index 0000000..d6d0a36
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
@@ -0,0 +1,203 @@
+/*
+ * Copyright (C) 2019 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.statusbar.tv;
+
+import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
+
+import android.app.AppOpsManager;
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.graphics.PixelFormat;
+import android.graphics.drawable.Drawable;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewTreeObserver;
+import android.view.WindowManager;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import com.android.systemui.R;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+class AudioRecordingDisclosureBar {
+    private static final String TAG = "AudioRecordingDisclosureBar";
+    private static final boolean DEBUG = false;
+
+    private static final String LAYOUT_PARAMS_TITLE = "AudioRecordingDisclosureBar";
+    private static final int ANIM_DURATION_MS = 150;
+
+    private final Context mContext;
+    private final List<String> mAudioRecordingApps = new ArrayList<>();
+    private View mView;
+    private ViewGroup mAppsInfoContainer;
+
+    AudioRecordingDisclosureBar(Context context) {
+        mContext = context;
+    }
+
+    void start() {
+        // Inflate and add audio recording disclosure bar
+        createView();
+
+        // Register AppOpsManager callback
+        final AppOpsManager appOpsManager = (AppOpsManager) mContext.getSystemService(
+                Context.APP_OPS_SERVICE);
+        appOpsManager.startWatchingActive(
+                new String[]{AppOpsManager.OPSTR_RECORD_AUDIO}, mContext.getMainExecutor(),
+                new OnActiveRecordingListener());
+    }
+
+    private void createView() {
+        mView = View.inflate(mContext,
+                R.layout.tv_status_bar_audio_recording, null);
+        mAppsInfoContainer = mView.findViewById(R.id.container);
+
+        final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
+                MATCH_PARENT,
+                WRAP_CONTENT,
+                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
+                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+                PixelFormat.TRANSLUCENT);
+        layoutParams.gravity = Gravity.BOTTOM;
+        layoutParams.setTitle(LAYOUT_PARAMS_TITLE);
+        layoutParams.packageName = mContext.getPackageName();
+
+        final WindowManager windowManager = (WindowManager) mContext.getSystemService(
+                Context.WINDOW_SERVICE);
+        windowManager.addView(mView, layoutParams);
+
+        // Set invisible first util it gains its actual size and we are able to hide it by moving
+        // off the screen
+        mView.setVisibility(View.INVISIBLE);
+        mView.getViewTreeObserver().addOnGlobalLayoutListener(
+                new ViewTreeObserver.OnGlobalLayoutListener() {
+                    @Override
+                    public void onGlobalLayout() {
+                        // Now that we get the height, we can move the bar off ("below") the screen
+                        final int height = mView.getHeight();
+                        mView.setTranslationY(height);
+                        // ... and make it visible
+                        mView.setVisibility(View.VISIBLE);
+                        // Remove the observer
+                        mView.getViewTreeObserver()
+                                .removeOnGlobalLayoutListener(this);
+                    }
+                });
+    }
+
+    private void showAudioRecordingDisclosureBar() {
+        mView.animate()
+                .translationY(0f)
+                .setDuration(ANIM_DURATION_MS)
+                .start();
+    }
+
+    private void addToAudioRecordingDisclosureBar(String packageName) {
+        final PackageManager pm = mContext.getPackageManager();
+        final ApplicationInfo appInfo;
+        try {
+            appInfo = pm.getApplicationInfo(packageName, 0);
+        } catch (PackageManager.NameNotFoundException e) {
+            return;
+        }
+        final CharSequence label = pm.getApplicationLabel(appInfo);
+        final Drawable icon = pm.getApplicationIcon(appInfo);
+
+        final View view = LayoutInflater.from(mContext).inflate(R.layout.tv_item_app_info,
+                mAppsInfoContainer, false);
+        ((TextView) view.findViewById(R.id.title)).setText(label);
+        ((ImageView) view.findViewById(R.id.icon)).setImageDrawable(icon);
+
+        mAppsInfoContainer.addView(view);
+    }
+
+    private void removeFromAudioRecordingDisclosureBar(int index) {
+        mAppsInfoContainer.removeViewAt(index);
+    }
+
+    private void hideAudioRecordingDisclosureBar() {
+        mView.animate()
+                .translationY(mView.getHeight())
+                .setDuration(ANIM_DURATION_MS)
+                .start();
+    }
+
+    private class OnActiveRecordingListener implements AppOpsManager.OnOpActiveChangedListener {
+        private final List<String> mExemptApps;
+
+        private OnActiveRecordingListener() {
+            mExemptApps = Arrays.asList(mContext.getResources().getStringArray(
+                    R.array.audio_recording_disclosure_exempt_apps));
+        }
+
+        @Override
+        public void onOpActiveChanged(String op, int uid, String packageName, boolean active) {
+            if (DEBUG) {
+                Log.d(TAG,
+                        "OP_RECORD_AUDIO active change, active" + active + ", app=" + packageName);
+            }
+
+            if (mExemptApps.contains(packageName)) {
+                if (DEBUG) {
+                    Log.d(TAG, "\t- exempt app");
+                }
+                return;
+            }
+
+            final boolean alreadyTracking = mAudioRecordingApps.contains(packageName);
+            if ((active && alreadyTracking) || (!active && !alreadyTracking)) {
+                if (DEBUG) {
+                    Log.d(TAG, "\t- nothing changed");
+                }
+                return;
+            }
+
+            if (active) {
+                if (DEBUG) {
+                    Log.d(TAG, "\t- new recording app");
+                }
+
+                if (mAudioRecordingApps.isEmpty()) {
+                    showAudioRecordingDisclosureBar();
+                }
+
+                mAudioRecordingApps.add(packageName);
+                addToAudioRecordingDisclosureBar(packageName);
+            } else {
+                if (DEBUG) {
+                    Log.d(TAG, "\t- not recording any more");
+                }
+
+                final int index = mAudioRecordingApps.indexOf(packageName);
+                removeFromAudioRecordingDisclosureBar(index);
+                mAudioRecordingApps.remove(index);
+
+                if (mAudioRecordingApps.isEmpty()) {
+                    hideAudioRecordingDisclosureBar();
+                }
+            }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
index 17d9cbe..b80b6d5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tv/TvStatusBar.java
@@ -23,28 +23,33 @@
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.systemui.SystemUI;
 import com.android.systemui.statusbar.CommandQueue;
-import com.android.systemui.statusbar.CommandQueue.Callbacks;
+
 
 /**
- * Status bar implementation for "large screen" products that mostly present no on-screen nav
+ * Status bar implementation for "large screen" products that mostly present no on-screen nav.
+ * Serves as a collection of UI components, rather than showing its own UI.
+ * The following is the list of elements that constitute the TV-specific status bar:
+ * <ul>
+ * <li> {@link AudioRecordingDisclosureBar} - shown whenever applications are conducting audio
+ * recording, discloses the responsible applications </li>
+ * </ul>
  */
-
-public class TvStatusBar extends SystemUI implements Callbacks {
-
-    private IStatusBarService mBarService;
+public class TvStatusBar extends SystemUI implements CommandQueue.Callbacks {
 
     @Override
     public void start() {
         putComponent(TvStatusBar.class, this);
-        CommandQueue commandQueue = getComponent(CommandQueue.class);
-        commandQueue.addCallback(this);
-        mBarService = IStatusBarService.Stub.asInterface(
+
+        final IStatusBarService barService = IStatusBarService.Stub.asInterface(
                 ServiceManager.getService(Context.STATUS_BAR_SERVICE));
+        final CommandQueue commandQueue = getComponent(CommandQueue.class);
+        commandQueue.addCallback(this);
         try {
-            mBarService.registerStatusBar(commandQueue);
+            barService.registerStatusBar(commandQueue);
         } catch (RemoteException ex) {
             // If the system process isn't there we're doomed anyway.
         }
-    }
 
+        new AudioRecordingDisclosureBar(mContext).start();
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java
index a46f018..47b56e0 100644
--- a/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbPermissionActivity.java
@@ -21,6 +21,7 @@
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
+import android.content.PermissionChecker;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.hardware.usb.IUsbManager;
@@ -84,14 +85,27 @@
         final AlertController.AlertParams ap = mAlertParams;
         ap.mTitle = appName;
         if (mDevice == null) {
+            // Accessory Case
+
             ap.mMessage = getString(R.string.usb_accessory_permission_prompt, appName,
                     mAccessory.getDescription());
             mDisconnectedReceiver = new UsbDisconnectedReceiver(this, mAccessory);
         } else {
-            ap.mMessage = getString(R.string.usb_device_permission_prompt, appName,
-                    mDevice.getProductName());
+            boolean hasRecordPermission =
+                    PermissionChecker.checkPermissionForPreflight(
+                            this, android.Manifest.permission.RECORD_AUDIO, -1, aInfo.uid,
+                            mPackageName)
+                            == android.content.pm.PackageManager.PERMISSION_GRANTED;
+            boolean isAudioCaptureDevice = mDevice.getHasAudioCapture();
+            boolean useRecordWarning = isAudioCaptureDevice && !hasRecordPermission;
+
+            int strID = useRecordWarning
+                    ? R.string.usb_device_permission_prompt_warn
+                    : R.string.usb_device_permission_prompt;
+            ap.mMessage = getString(strID, appName, mDevice.getProductName());
             mDisconnectedReceiver = new UsbDisconnectedReceiver(this, mDevice);
         }
+
         ap.mPositiveButtonText = getString(android.R.string.ok);
         ap.mNegativeButtonText = getString(android.R.string.cancel);
         ap.mPositiveButtonListener = this;
diff --git a/packages/SystemUI/src/com/android/systemui/util/InjectionInflationController.java b/packages/SystemUI/src/com/android/systemui/util/InjectionInflationController.java
index e44e58a..7e801da 100644
--- a/packages/SystemUI/src/com/android/systemui/util/InjectionInflationController.java
+++ b/packages/SystemUI/src/com/android/systemui/util/InjectionInflationController.java
@@ -37,6 +37,7 @@
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
 import com.android.systemui.statusbar.phone.LockIcon;
 import com.android.systemui.statusbar.phone.NotificationPanelView;
+import com.android.systemui.statusbar.policy.Clock;
 
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
@@ -178,6 +179,11 @@
          * Creates the QSCustomizer.
          */
         QSCustomizer createQSCustomizer();
+
+        /**
+         * Creates a Clock.
+         */
+        Clock createClock();
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/util/leak/DumpTruck.java b/packages/SystemUI/src/com/android/systemui/util/leak/DumpTruck.java
index fa7af0b..be5e0a0 100644
--- a/packages/SystemUI/src/com/android/systemui/util/leak/DumpTruck.java
+++ b/packages/SystemUI/src/com/android/systemui/util/leak/DumpTruck.java
@@ -36,6 +36,7 @@
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.List;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
@@ -53,7 +54,7 @@
 
     private final Context context;
     private Uri hprofUri;
-    private long pss;
+    private long rss;
     final StringBuilder body = new StringBuilder();
 
     public DumpTruck(Context context) {
@@ -66,7 +67,7 @@
      * @param pids
      * @return this, for chaining
      */
-    public DumpTruck captureHeaps(int[] pids) {
+    public DumpTruck captureHeaps(List<Long> pids) {
         final GarbageMonitor gm = Dependency.get(GarbageMonitor.class);
 
         final File dumpDir = new File(context.getCacheDir(), FILEPROVIDER_PATH);
@@ -79,8 +80,8 @@
         final ArrayList<String> paths = new ArrayList<String>();
         final int myPid = android.os.Process.myPid();
 
-        final int[] pids_copy = Arrays.copyOf(pids, pids.length);
-        for (int pid : pids_copy) {
+        for (Long pidL : pids) {
+            final int pid = pidL.intValue();
             body.append("  pid ").append(pid);
             if (gm != null) {
                 GarbageMonitor.ProcessMemInfo info = gm.getMemInfo(pid);
@@ -88,11 +89,9 @@
                     body.append(":")
                             .append(" up=")
                             .append(info.getUptime())
-                            .append(" pss=")
-                            .append(info.currentPss)
-                            .append(" uss=")
-                            .append(info.currentUss);
-                    pss = info.currentPss;
+                            .append(" rss=")
+                            .append(info.currentRss);
+                    rss = info.currentRss;
                 }
             }
             if (pid == myPid) {
@@ -147,7 +146,7 @@
         shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
         shareIntent.putExtra(Intent.EXTRA_SUBJECT,
-                String.format("SystemUI memory dump (pss=%dM)", pss / 1024));
+                String.format("SystemUI memory dump (rss=%dM)", rss / 1024));
 
         shareIntent.putExtra(Intent.EXTRA_TEXT, body.toString());
 
diff --git a/packages/SystemUI/src/com/android/systemui/util/leak/GarbageMonitor.java b/packages/SystemUI/src/com/android/systemui/util/leak/GarbageMonitor.java
index 583f6b3..2d5ebc4 100644
--- a/packages/SystemUI/src/com/android/systemui/util/leak/GarbageMonitor.java
+++ b/packages/SystemUI/src/com/android/systemui/util/leak/GarbageMonitor.java
@@ -35,7 +35,6 @@
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
 import android.os.Build;
-import android.os.Debug;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
@@ -49,7 +48,7 @@
 import com.android.systemui.Dumpable;
 import com.android.systemui.R;
 import com.android.systemui.SystemUI;
-import com.android.systemui.SystemUIFactory;
+import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.qs.QSTile;
 import com.android.systemui.qs.QSHost;
 import com.android.systemui.qs.tileimpl.QSTileImpl;
@@ -57,6 +56,7 @@
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.List;
 
 import javax.inject.Inject;
 import javax.inject.Named;
@@ -102,7 +102,6 @@
 
     private final LongSparseArray<ProcessMemInfo> mData = new LongSparseArray<>();
     private final ArrayList<Long> mPids = new ArrayList<>();
-    private int[] mPidsArray = new int[1];
 
     private long mHeapLimit;
 
@@ -164,8 +163,8 @@
         return mData.get(pid);
     }
 
-    public int[] getTrackedProcesses() {
-        return mPidsArray;
+    public List<Long> getTrackedProcesses() {
+        return mPids;
     }
 
     public void startTrackingProcess(long pid, String name, long start) {
@@ -173,43 +172,40 @@
             if (mPids.contains(pid)) return;
 
             mPids.add(pid);
-            updatePidsArrayL();
+            logPids();
 
             mData.put(pid, new ProcessMemInfo(pid, name, start));
         }
     }
 
-    private void updatePidsArrayL() {
-        final int N = mPids.size();
-        mPidsArray = new int[N];
-        StringBuffer sb = new StringBuffer("Now tracking processes: ");
-        for (int i = 0; i < N; i++) {
-            final int p = mPids.get(i).intValue();
-            mPidsArray[i] = p;
-            sb.append(p);
-            sb.append(" ");
+    private void logPids() {
+        if (DEBUG) {
+            StringBuffer sb = new StringBuffer("Now tracking processes: ");
+            for (int i = 0; i < mPids.size(); i++) {
+                final int p = mPids.get(i).intValue();
+                sb.append(" ");
+            }
+            Log.v(TAG, sb.toString());
         }
-        if (DEBUG) Log.v(TAG, sb.toString());
     }
 
     private void update() {
         synchronized (mPids) {
-            Debug.MemoryInfo[] dinfos = mAm.getProcessMemoryInfo(mPidsArray);
-            for (int i = 0; i < dinfos.length; i++) {
-                Debug.MemoryInfo dinfo = dinfos[i];
-                if (i > mPids.size()) {
-                    if (DEBUG) Log.e(TAG, "update: unknown process info received: " + dinfo);
+            for (int i = 0; i < mPids.size(); i++) {
+                final int pid = mPids.get(i).intValue();
+                // rssValues contains [VmRSS, RssFile, RssAnon, VmSwap].
+                long[] rssValues = Process.getRss(pid);
+                if (rssValues == null && rssValues.length == 0) {
+                    if (DEBUG) Log.e(TAG, "update: Process.getRss() didn't provide any values.");
                     break;
                 }
-                final long pid = mPids.get(i).intValue();
+                long rss = rssValues[0];
                 final ProcessMemInfo info = mData.get(pid);
-                info.pss[info.head] = info.currentPss = dinfo.getTotalPss();
-                info.uss[info.head] = info.currentUss = dinfo.getTotalPrivateDirty();
-                info.head = (info.head + 1) % info.pss.length;
-                if (info.currentPss > info.max) info.max = info.currentPss;
-                if (info.currentUss > info.max) info.max = info.currentUss;
-                if (info.currentPss == 0) {
-                    if (DEBUG) Log.v(TAG, "update: pid " + pid + " has pss=0, it probably died");
+                info.rss[info.head] = info.currentRss = rss;
+                info.head = (info.head + 1) % info.rss.length;
+                if (info.currentRss > info.max) info.max = info.currentRss;
+                if (info.currentRss == 0) {
+                    if (DEBUG) Log.v(TAG, "update: pid " + pid + " has rss=0, it probably died");
                     mData.remove(pid);
                 }
             }
@@ -217,7 +213,7 @@
                 final long pid = mPids.get(i).intValue();
                 if (mData.get(pid) == null) {
                     mPids.remove(i);
-                    updatePidsArrayL();
+                    logPids();
                 }
             }
         }
@@ -270,7 +266,7 @@
 
 
     private static class MemoryIconDrawable extends Drawable {
-        long pss, limit;
+        long rss, limit;
         final Drawable baseIcon;
         final Paint paint = new Paint();
         final float dp;
@@ -281,9 +277,9 @@
             paint.setColor(QSTileImpl.getColorForState(context, STATE_ACTIVE));
         }
 
-        public void setPss(long pss) {
-            if (pss != this.pss) {
-                this.pss = pss;
+        public void setRss(long rss) {
+            if (rss != this.rss) {
+                this.rss = rss;
                 invalidateSelf();
             }
         }
@@ -299,8 +295,8 @@
         public void draw(Canvas canvas) {
             baseIcon.draw(canvas);
 
-            if (limit > 0 && pss > 0) {
-                float frac = Math.min(1f, (float) pss / limit);
+            if (limit > 0 && rss > 0) {
+                float frac = Math.min(1f, (float) rss / limit);
 
                 final Rect bounds = getBounds();
                 canvas.translate(bounds.left + 8 * dp, bounds.top + 5 * dp);
@@ -361,10 +357,10 @@
     }
 
     private static class MemoryGraphIcon extends QSTile.Icon {
-        long pss, limit;
+        long rss, limit;
 
-        public void setPss(long pss) {
-            this.pss = pss;
+        public void setRss(long rss) {
+            this.rss = rss;
         }
 
         public void setHeapLimit(long limit) {
@@ -374,7 +370,7 @@
         @Override
         public Drawable getDrawable(Context context) {
             final MemoryIconDrawable drawable = new MemoryIconDrawable(context);
-            drawable.setPss(pss);
+            drawable.setRss(rss);
             drawable.setLimit(limit);
             return drawable;
         }
@@ -387,13 +383,15 @@
         public static final boolean ADD_TO_DEFAULT_ON_DEBUGGABLE_BUILDS = true;
 
         private final GarbageMonitor gm;
+        private final ActivityStarter mActivityStarter;
         private ProcessMemInfo pmi;
         private boolean dumpInProgress;
 
         @Inject
-        public MemoryTile(QSHost host) {
+        public MemoryTile(QSHost host, GarbageMonitor monitor, ActivityStarter starter) {
             super(host);
-            gm = SystemUIFactory.getInstance().getRootComponent().createGarbageMonitor();
+            gm = monitor;
+            mActivityStarter = starter;
         }
 
         @Override
@@ -424,7 +422,7 @@
                         dumpInProgress = false;
                         refreshState();
                         getHost().collapsePanels();
-                        mContext.startActivity(shareIntent);
+                        mActivityStarter.postStartActivityDismissingKeyguard(shareIntent, 0);
                     });
                 }
             }.start();
@@ -462,14 +460,14 @@
                     ? "Dumping..."
                     : mContext.getString(R.string.heap_dump_tile_name);
             if (pmi != null) {
-                icon.setPss(pmi.currentPss);
+                icon.setRss(pmi.currentRss);
                 state.secondaryLabel =
                         String.format(
-                                "pss: %s / %s",
-                                formatBytes(pmi.currentPss * 1024),
+                                "rss: %s / %s",
+                                formatBytes(pmi.currentRss * 1024),
                                 formatBytes(gm.mHeapLimit * 1024));
             } else {
-                icon.setPss(0);
+                icon.setRss(0);
                 state.secondaryLabel = null;
             }
             state.icon = icon;
@@ -479,8 +477,8 @@
             refreshState();
         }
 
-        public long getPss() {
-            return pmi != null ? pmi.currentPss : 0;
+        public long getRss() {
+            return pmi != null ? pmi.currentRss : 0;
         }
 
         public long getHeapLimit() {
@@ -493,9 +491,8 @@
         public long pid;
         public String name;
         public long startTime;
-        public long currentPss, currentUss;
-        public long[] pss = new long[HEAP_TRACK_HISTORY_LEN];
-        public long[] uss = new long[HEAP_TRACK_HISTORY_LEN];
+        public long currentRss;
+        public long[] rss = new long[HEAP_TRACK_HISTORY_LEN];
         public long max = 1;
         public int head = 0;
 
@@ -517,17 +514,12 @@
             pw.print(name.replace('"', '-'));
             pw.print("\", \"start\": ");
             pw.print(startTime);
-            pw.print(", \"pss\": [");
-            // write pss values starting from the oldest, which is pss[head], wrapping around to
-            // pss[(head-1) % pss.length]
-            for (int i = 0; i < pss.length; i++) {
+            pw.print(", \"rss\": [");
+            // write rss values starting from the oldest, which is rss[head], wrapping around to
+            // rss[(head-1) % rss.length]
+            for (int i = 0; i < rss.length; i++) {
                 if (i > 0) pw.print(",");
-                pw.print(pss[(head + i) % pss.length]);
-            }
-            pw.print("], \"uss\": [");
-            for (int i = 0; i < uss.length; i++) {
-                if (i > 0) pw.print(",");
-                pw.print(uss[(head + i) % uss.length]);
+                pw.print(rss[(head + i) % rss.length]);
             }
             pw.println("] }");
         }
@@ -535,7 +527,12 @@
 
     /** */
     public static class Service extends SystemUI implements Dumpable {
-        private GarbageMonitor mGarbageMonitor;
+        private final GarbageMonitor mGarbageMonitor;
+
+        @Inject
+        public Service(GarbageMonitor garbageMonitor) {
+            mGarbageMonitor = garbageMonitor;
+        }
 
         @Override
         public void start() {
@@ -543,8 +540,6 @@
                     Settings.Secure.getInt(
                                     mContext.getContentResolver(), FORCE_ENABLE_LEAK_REPORTING, 0)
                             != 0;
-            mGarbageMonitor = SystemUIFactory.getInstance().getRootComponent()
-                   .createGarbageMonitor();
             if (LEAK_REPORTING_ENABLED || forceEnable) {
                 mGarbageMonitor.startLeakMonitor();
             }
diff --git a/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java b/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java
index c48bdde..cce5bca 100644
--- a/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java
+++ b/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java
@@ -24,8 +24,8 @@
 import android.os.Handler;
 import android.util.Log;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.systemui.R;
-import com.android.systemui.shared.plugins.PluginManager;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -47,7 +47,7 @@
     private final float mMaxRange;
     private List<ProximitySensorListener> mListeners = new ArrayList<>();
     private String mTag = null;
-    private ProximityEvent mLastEvent;
+    @VisibleForTesting ProximityEvent mLastEvent;
     private int mSensorDelay = SensorManager.SENSOR_DELAY_NORMAL;
     private boolean mPaused;
     private boolean mRegistered;
@@ -64,8 +64,7 @@
     };
 
     @Inject
-    public ProximitySensor(
-            Context context, AsyncSensorManager sensorManager, PluginManager pluginManager) {
+    public ProximitySensor(Context context, AsyncSensorManager sensorManager) {
         mSensorManager = sensorManager;
         Sensor sensor = findBrightnessSensor(context);
 
@@ -146,17 +145,17 @@
             return false;
         }
 
-        logDebug("Using brightness sensor? " + mUsingBrightnessSensor);
         mListeners.add(listener);
         registerInternal();
 
         return true;
     }
 
-    private void registerInternal() {
+    protected void registerInternal() {
         if (mRegistered || mPaused || mListeners.isEmpty()) {
             return;
         }
+        logDebug("Using brightness sensor? " + mUsingBrightnessSensor);
         logDebug("Registering sensor listener");
         mRegistered = true;
         mSensorManager.registerListener(mSensorEventListener, mSensor, mSensorDelay);
@@ -175,7 +174,7 @@
         }
     }
 
-    private void unregisterInternal() {
+    protected void unregisterInternal() {
         if (!mRegistered) {
             return;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java
index a6b5b38..2c70fb4 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogControllerImpl.java
@@ -59,6 +59,7 @@
 import com.android.systemui.Dumpable;
 import com.android.systemui.R;
 import com.android.systemui.SysUiServiceProvider;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.VolumeDialogController;
 import com.android.systemui.qs.tiles.DndTile;
@@ -137,9 +138,10 @@
     private UserActivityListener mUserActivityListener;
 
     protected final VC mVolumeController = new VC();
+    protected final BroadcastDispatcher mBroadcastDispatcher;
 
     @Inject
-    public VolumeDialogControllerImpl(Context context) {
+    public VolumeDialogControllerImpl(Context context, BroadcastDispatcher broadcastDispatcher) {
         mContext = context.getApplicationContext();
         mNotificationManager = (NotificationManager) mContext.getSystemService(
                 Context.NOTIFICATION_SERVICE);
@@ -152,6 +154,7 @@
         mAudio = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
         mNoMan = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
         mObserver = new SettingObserver(mWorker);
+        mBroadcastDispatcher = broadcastDispatcher;
         mObserver.init();
         mReceiver.init();
         mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
@@ -618,7 +621,9 @@
                 .PRIORITY_CATEGORY_MEDIA) == 0;
         boolean disallowSystem = (policy.priorityCategories & NotificationManager.Policy
                 .PRIORITY_CATEGORY_SYSTEM) == 0;
-        boolean disallowRinger = ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(policy);
+        // ringer controls notifications, ringer and system sounds, so only disallow ringer changes
+        // if all relevant (notifications + ringer + system) sounds are not allowed to bypass DND
+        boolean disallowRinger = ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(policy);
         if (mState.disallowAlarms == disallowAlarms
                 && mState.disallowMedia == disallowMedia
                 && mState.disallowRinger == disallowRinger
@@ -1004,11 +1009,11 @@
             filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
             filter.addAction(Intent.ACTION_SCREEN_OFF);
             filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
-            mContext.registerReceiver(this, filter, null, mWorker);
+            mBroadcastDispatcher.registerReceiver(this, filter, mWorker);
         }
 
         public void destroy() {
-            mContext.unregisterReceiver(this);
+            mBroadcastDispatcher.unregisterReceiver(this);
         }
 
         @Override
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
index 2e94c7c..38537fd 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
@@ -26,20 +26,24 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
+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.verify;
 import static org.mockito.Mockito.when;
 
-import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.os.Process;
 import android.provider.Settings;
 import android.telephony.ServiceState;
 import android.telephony.SubscriptionInfo;
@@ -62,6 +66,7 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -105,6 +110,14 @@
     private CarrierTextController mCarrierTextController;
     private TestableLooper mTestableLooper;
 
+    private Void checkMainThread(InvocationOnMock inv) {
+        Looper mainLooper = Dependency.get(Dependency.MAIN_HANDLER).getLooper();
+        if (!mainLooper.isCurrentThread()) {
+            fail("This call should be done from the main thread");
+        }
+        return null;
+    }
+
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
@@ -112,6 +125,7 @@
 
         mContext.addMockSystemService(WifiManager.class, mWifiManager);
         mContext.addMockSystemService(ConnectivityManager.class, mConnectivityManager);
+        when(mConnectivityManager.isNetworkSupported(anyInt())).thenReturn(true);
         mContext.addMockSystemService(TelephonyManager.class, mTelephonyManager);
         mContext.addMockSystemService(SubscriptionManager.class, mSubscriptionManager);
         mContext.getOrCreateTestableResources().addOverride(
@@ -121,19 +135,43 @@
         mDependency.injectMockDependency(WakefulnessLifecycle.class);
         mDependency.injectTestDependency(Dependency.MAIN_HANDLER,
                 new Handler(mTestableLooper.getLooper()));
-        mDependency.injectMockDependency(KeyguardUpdateMonitor.class);
+        mDependency.injectTestDependency(KeyguardUpdateMonitor.class, mKeyguardUpdateMonitor);
+
+        doAnswer(this::checkMainThread).when(mKeyguardUpdateMonitor)
+                .registerCallback(any(KeyguardUpdateMonitorCallback.class));
+        doAnswer(this::checkMainThread).when(mKeyguardUpdateMonitor)
+                .removeCallback(any(KeyguardUpdateMonitorCallback.class));
 
         mCarrierTextCallbackInfo = new CarrierTextController.CarrierTextCallbackInfo("",
                 new CharSequence[]{}, false, new int[]{});
-        when(mTelephonyManager.getPhoneCount()).thenReturn(3);
+        when(mTelephonyManager.getMaxPhoneCount()).thenReturn(3);
 
-        mCarrierTextController = new TestCarrierTextController(mContext, SEPARATOR, true, true,
-                mKeyguardUpdateMonitor);
-        // This should not start listening on any of the real dependencies
+        mCarrierTextController = new CarrierTextController(mContext, SEPARATOR, true, true);
+        // This should not start listening on any of the real dependencies but will test that
+        // callbacks in mKeyguardUpdateMonitor are done in the mTestableLooper thread
         mCarrierTextController.setListening(mCarrierTextCallback);
     }
 
     @Test
+    public void testKeyguardUpdateMonitorCalledInMainThread() throws Exception {
+        // This test will run on the main looper (which is not the same as the looper set as MAIN
+        // for CarrierTextCallback. This will fail if calls to mKeyguardUpdateMonitor are not done
+        // through the looper set in the set up
+        HandlerThread thread = new HandlerThread("testThread",
+                Process.THREAD_PRIORITY_BACKGROUND);
+        thread.start();
+        TestableLooper testableLooper = new TestableLooper(thread.getLooper());
+        Handler h = new Handler(testableLooper.getLooper());
+        h.post(() -> {
+            mCarrierTextController.setListening(null);
+            mCarrierTextController.setListening(mCarrierTextCallback);
+        });
+        testableLooper.processAllMessages();
+        mTestableLooper.processAllMessages();
+        thread.quitSafely();
+    }
+
+    @Test
     public void testAirplaneMode() {
         Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 1);
         reset(mCarrierTextCallback);
@@ -466,20 +504,4 @@
         assertEquals(TEST_CARRIER + SEPARATOR + TEST_CARRIER,
                 captor.getValue().carrierText);
     }
-
-    public static class TestCarrierTextController extends CarrierTextController {
-        private KeyguardUpdateMonitor mKUM;
-
-        public TestCarrierTextController(Context context, CharSequence separator,
-                boolean showAirplaneMode, boolean showMissingSim, KeyguardUpdateMonitor kum) {
-            super(context, separator, showAirplaneMode, showMissingSim);
-            mKUM = kum;
-        }
-
-        @Override
-        public void setListening(CarrierTextCallback callback) {
-            super.setListening(callback);
-            mKeyguardUpdateMonitor = mKUM;
-        }
-    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
index ad7bba1..57b0987 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
@@ -25,6 +25,7 @@
 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.clearInvocations;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.never;
@@ -481,6 +482,25 @@
         assertThat(mKeyguardUpdateMonitor.isUserUnlocked(randomUser)).isFalse();
     }
 
+    @Test
+    public void testTrustUsuallyManaged_whenTrustChanges() {
+        int user = KeyguardUpdateMonitor.getCurrentUser();
+        when(mTrustManager.isTrustUsuallyManaged(eq(user))).thenReturn(true);
+        mKeyguardUpdateMonitor.onTrustManagedChanged(false /* managed */, user);
+        assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isTrue();
+    }
+
+    @Test
+    public void testTrustUsuallyManaged_resetWhenUserIsRemoved() {
+        int user = KeyguardUpdateMonitor.getCurrentUser();
+        when(mTrustManager.isTrustUsuallyManaged(eq(user))).thenReturn(true);
+        mKeyguardUpdateMonitor.onTrustManagedChanged(false /* managed */, user);
+        assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isTrue();
+
+        mKeyguardUpdateMonitor.handleUserRemoved(user);
+        assertThat(mKeyguardUpdateMonitor.isTrustUsuallyManaged(user)).isFalse();
+    }
+
     private Intent putPhoneInfo(Intent intent, Bundle data, Boolean simInited) {
         int subscription = simInited
                 ? 1/* mock subid=1 */ : SubscriptionManager.DUMMY_SUBSCRIPTION_ID_BASE;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
index 3b5e12c..64ab060 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
@@ -45,7 +45,6 @@
 import android.view.Display;
 import android.view.View;
 import android.view.WindowManager;
-import android.view.WindowManagerPolicyConstants;
 
 import androidx.test.filters.SmallTest;
 
@@ -53,7 +52,6 @@
 import com.android.systemui.ScreenDecorations.TunablePaddingTagListener;
 import com.android.systemui.fragments.FragmentHostManager;
 import com.android.systemui.fragments.FragmentService;
-import com.android.systemui.statusbar.phone.NavigationModeController;
 import com.android.systemui.statusbar.phone.StatusBar;
 import com.android.systemui.statusbar.phone.StatusBarWindowView;
 import com.android.systemui.tuner.TunablePadding;
@@ -80,7 +78,6 @@
     private TunerService mTunerService;
     private StatusBarWindowView mView;
     private TunablePaddingService mTunablePaddingService;
-    private NavigationModeController mNavigationModeController;
 
     @Before
     public void setup() {
@@ -90,8 +87,6 @@
         mTunablePaddingService = mDependency.injectMockDependency(TunablePaddingService.class);
         mTunerService = mDependency.injectMockDependency(TunerService.class);
         mFragmentService = mDependency.injectMockDependency(FragmentService.class);
-        mNavigationModeController = mDependency.injectMockDependency(
-                NavigationModeController.class);
 
         mStatusBar = mock(StatusBar.class);
         mWindowManager = mock(WindowManager.class);
@@ -213,54 +208,6 @@
     }
 
     @Test
-    public void testAssistHandles() {
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, false);
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.dimen.rounded_corner_radius, 0);
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.dimen.rounded_corner_radius_top, 0);
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
-        mContext.getOrCreateTestableResources()
-                .addOverride(dimen.rounded_corner_content_padding, 0);
-        when(mNavigationModeController.addListener(any())).thenReturn(
-                WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL);
-
-        mScreenDecorations.start();
-
-        // Add 2 windows for rounded corners (top and bottom).
-        verify(mWindowManager, times(2)).addView(any(), any());
-    }
-
-    @Test
-    public void testDelayedAssistHandles() {
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, false);
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.dimen.rounded_corner_radius, 0);
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.dimen.rounded_corner_radius_top, 0);
-        mContext.getOrCreateTestableResources().addOverride(
-                com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
-        mContext.getOrCreateTestableResources()
-                .addOverride(dimen.rounded_corner_content_padding, 0);
-        when(mNavigationModeController.addListener(any())).thenReturn(
-                WindowManagerPolicyConstants.NAV_BAR_MODE_3BUTTON);
-
-        mScreenDecorations.start();
-
-        // No handles and no corners
-        verify(mWindowManager, never()).addView(any(), any());
-
-        mScreenDecorations.handleNavigationModeChange(
-                WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL);
-
-        // Add 2 windows for rounded corners (top and bottom).
-        verify(mWindowManager, times(2)).addView(any(), any());
-    }
-
-    @Test
     public void hasRoundedCornerOverlayFlagSet() {
         assertThat(mScreenDecorations.getWindowLayoutParams().privateFlags
                         & PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java
index a245d41..cf77850 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/SysuiBaseFragmentTest.java
@@ -24,6 +24,7 @@
 
 import androidx.test.InstrumentationRegistry;
 
+import com.android.systemui.assist.AssistManager;
 import com.android.systemui.utils.leaks.LeakCheckedTest;
 import com.android.systemui.utils.leaks.LeakCheckedTest.SysuiLeakCheck;
 
@@ -64,6 +65,7 @@
         when(inst.getTargetContext()).thenThrow(new RuntimeException(
                 "SysUI Tests should use SysuiTestCase#getContext or SysuiTestCase#mContext"));
         InstrumentationRegistry.registerInstance(inst, InstrumentationRegistry.getArguments());
+        mDependency.injectMockDependency(AssistManager.class);
     }
 
     @After
diff --git a/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java
index 9c920f5..fbb8e0c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleBehaviorControllerTest.java
@@ -38,7 +38,6 @@
 import com.android.internal.app.AssistUtils;
 import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
 import com.android.systemui.DumpController;
-import com.android.systemui.ScreenDecorations;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.recents.OverviewProxyService;
@@ -64,7 +63,6 @@
 
     private AssistHandleBehaviorController mAssistHandleBehaviorController;
 
-    @Mock private ScreenDecorations mMockScreenDecorations;
     @Mock private AssistUtils mMockAssistUtils;
     @Mock private Handler mMockHandler;
     @Mock private PhenotypeHelper mMockPhenotypeHelper;
@@ -74,6 +72,7 @@
     @Mock private AssistHandleBehaviorController.BehaviorController mMockTestBehavior;
     @Mock private NavigationModeController mMockNavigationModeController;
     @Mock private DumpController mMockDumpController;
+    @Mock private AssistHandleViewController mMockAssistHandleViewController;
 
     @Before
     public void setup() {
@@ -97,7 +96,7 @@
                         mContext,
                         mMockAssistUtils,
                         mMockHandler,
-                        () -> mMockScreenDecorations,
+                        () -> mMockAssistHandleViewController,
                         mMockPhenotypeHelper,
                         behaviorMap,
                         mMockNavigationModeController,
@@ -114,14 +113,14 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.showAndStay();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.hide();
 
         // Assert
-        verify(mMockScreenDecorations).setAssistHintVisible(false);
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -129,13 +128,13 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.hide();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.hide();
 
         // Assert
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -143,14 +142,14 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.hide();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndStay();
 
         // Assert
-        verify(mMockScreenDecorations).setAssistHintVisible(true);
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -158,13 +157,13 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.showAndStay();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndStay();
 
         // Assert
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -172,13 +171,13 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(null);
         mAssistHandleBehaviorController.hide();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndStay();
 
         // Assert
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -186,15 +185,15 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.hide();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGo();
 
         // Assert
-        InOrder inOrder = inOrder(mMockScreenDecorations);
-        inOrder.verify(mMockScreenDecorations).setAssistHintVisible(true);
-        inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
+        InOrder inOrder = inOrder(mMockAssistHandleViewController);
+        inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+        inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
         inOrder.verifyNoMoreInteractions();
     }
 
@@ -203,14 +202,14 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.showAndStay();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGo();
 
         // Assert
-        verify(mMockScreenDecorations).setAssistHintVisible(false);
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -221,13 +220,13 @@
                 eq(SystemUiDeviceConfigFlags.ASSIST_HANDLES_SHOWN_FREQUENCY_THRESHOLD_MS),
                 anyLong())).thenReturn(10000L);
         mAssistHandleBehaviorController.showAndGo();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGo();
 
         // Assert
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -235,13 +234,13 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(null);
         mAssistHandleBehaviorController.hide();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGo();
 
         // Assert
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -249,15 +248,15 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.hide();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
 
         // Assert
-        InOrder inOrder = inOrder(mMockScreenDecorations);
-        inOrder.verify(mMockScreenDecorations).setAssistHintVisible(true);
-        inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
+        InOrder inOrder = inOrder(mMockAssistHandleViewController);
+        inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+        inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
         inOrder.verifyNoMoreInteractions();
     }
 
@@ -266,14 +265,14 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.showAndStay();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
 
         // Assert
-        verify(mMockScreenDecorations).setAssistHintVisible(false);
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -281,16 +280,16 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(COMPONENT_NAME);
         mAssistHandleBehaviorController.showAndStay();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGoDelayed(1000, true);
 
         // Assert
-        InOrder inOrder = inOrder(mMockScreenDecorations);
-        inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
-        inOrder.verify(mMockScreenDecorations).setAssistHintVisible(true);
-        inOrder.verify(mMockScreenDecorations).setAssistHintVisible(false);
+        InOrder inOrder = inOrder(mMockAssistHandleViewController);
+        inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
+        inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(true);
+        inOrder.verify(mMockAssistHandleViewController).setAssistHintVisible(false);
         inOrder.verifyNoMoreInteractions();
     }
 
@@ -302,13 +301,13 @@
                 eq(SystemUiDeviceConfigFlags.ASSIST_HANDLES_SHOWN_FREQUENCY_THRESHOLD_MS),
                 anyLong())).thenReturn(10000L);
         mAssistHandleBehaviorController.showAndGo();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
 
         // Assert
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
@@ -316,13 +315,13 @@
         // Arrange
         when(mMockAssistUtils.getAssistComponentForUser(anyInt())).thenReturn(null);
         mAssistHandleBehaviorController.hide();
-        reset(mMockScreenDecorations);
+        reset(mMockAssistHandleViewController);
 
         // Act
         mAssistHandleBehaviorController.showAndGoDelayed(1000, false);
 
         // Assert
-        verifyNoMoreInteractions(mMockScreenDecorations);
+        verifyNoMoreInteractions(mMockAssistHandleViewController);
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleViewControllerTest.java
new file mode 100644
index 0000000..6e21ae2
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/assist/AssistHandleViewControllerTest.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2019 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.assist;
+
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper.RunWithLooper;
+import android.view.View;
+import android.view.ViewPropertyAnimator;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.CornerHandleView;
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@RunWithLooper
+public class AssistHandleViewControllerTest extends SysuiTestCase {
+
+    private AssistHandleViewController mAssistHandleViewController;
+
+    @Mock private Handler mMockHandler;
+    @Mock private Looper mMockLooper;
+    @Mock private View mMockBarView;
+    @Mock private CornerHandleView mMockAssistHint;
+    @Mock private ViewPropertyAnimator mMockAnimator;
+
+    @Before
+    public void setup() {
+        MockitoAnnotations.initMocks(this);
+        when(mMockBarView.findViewById(anyInt())).thenReturn(mMockAssistHint);
+        when(mMockAssistHint.animate()).thenReturn(mMockAnimator);
+        when(mMockAnimator.setInterpolator(any())).thenReturn(mMockAnimator);
+        when(mMockAnimator.setDuration(anyLong())).thenReturn(mMockAnimator);
+        doNothing().when(mMockAnimator).cancel();
+        when(mMockHandler.getLooper()).thenReturn(mMockLooper);
+        when(mMockLooper.isCurrentThread()).thenReturn(true);
+
+        mAssistHandleViewController = new AssistHandleViewController(mMockHandler, mMockBarView);
+    }
+
+    @Test
+    public void testSetVisibleWithoutBlocked() {
+        // Act
+        mAssistHandleViewController.setAssistHintVisible(true);
+
+        // Assert
+        assertTrue(mAssistHandleViewController.mAssistHintVisible);
+    }
+
+    @Test
+    public void testSetInvisibleWithoutBlocked() {
+        // Arrange
+        mAssistHandleViewController.setAssistHintVisible(true);
+
+        // Act
+        mAssistHandleViewController.setAssistHintVisible(false);
+
+        // Assert
+        assertFalse(mAssistHandleViewController.mAssistHintVisible);
+    }
+
+    @Test
+    public void testSetVisibleWithBlocked() {
+        // Act
+        mAssistHandleViewController.setAssistHintBlocked(true);
+        mAssistHandleViewController.setAssistHintVisible(true);
+
+        // Assert
+        assertFalse(mAssistHandleViewController.mAssistHintVisible);
+        assertTrue(mAssistHandleViewController.mAssistHintBlocked);
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java
index 7a09137..2c85424 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthBiometricViewTest.java
@@ -24,6 +24,7 @@
 import static org.mockito.Mockito.verify;
 
 import android.content.Context;
+import android.hardware.biometrics.Authenticator;
 import android.hardware.biometrics.BiometricPrompt;
 import android.os.Bundle;
 import android.test.suitebuilder.annotation.SmallTest;
@@ -70,7 +71,7 @@
 
     @Test
     public void testOnAuthenticationSucceeded_noConfirmationRequired_sendsActionAuthenticated() {
-        initDialog(mContext, mCallback, new MockInjector());
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector());
 
         // The onAuthenticated runnable is posted when authentication succeeds.
         mBiometricView.onAuthenticationSucceeded();
@@ -81,7 +82,7 @@
 
     @Test
     public void testOnAuthenticationSucceeded_confirmationRequired_updatesDialogContents() {
-        initDialog(mContext, mCallback, new MockInjector());
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector());
 
         mBiometricView.setRequireConfirmation(true);
         mBiometricView.onAuthenticationSucceeded();
@@ -97,7 +98,7 @@
     @Test
     public void testPositiveButton_sendsActionAuthenticated() {
         Button button = new Button(mContext);
-        initDialog(mContext, mCallback, new MockInjector() {
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector() {
            @Override
             public Button getPositiveButton() {
                return button;
@@ -114,7 +115,7 @@
     @Test
     public void testNegativeButton_beforeAuthentication_sendsActionButtonNegative() {
         Button button = new Button(mContext);
-        initDialog(mContext, mCallback, new MockInjector() {
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector() {
             @Override
             public Button getNegativeButton() {
                 return button;
@@ -131,7 +132,7 @@
     @Test
     public void testNegativeButton_whenPendingConfirmation_sendsActionUserCanceled() {
         Button button = new Button(mContext);
-        initDialog(mContext, mCallback, new MockInjector() {
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector() {
             @Override
             public Button getNegativeButton() {
                 return button;
@@ -149,7 +150,7 @@
     @Test
     public void testTryAgainButton_sendsActionTryAgain() {
         Button button = new Button(mContext);
-        initDialog(mContext, mCallback, new MockInjector() {
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector() {
             @Override
             public Button getTryAgainButton() {
                 return button;
@@ -165,7 +166,7 @@
 
     @Test
     public void testError_sendsActionError() {
-        initDialog(mContext, mCallback, new MockInjector());
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector());
         final String testError = "testError";
         mBiometricView.onError(testError);
         waitForIdleSync();
@@ -176,7 +177,7 @@
 
     @Test
     public void testBackgroundClicked_sendsActionUserCanceled() {
-        initDialog(mContext, mCallback, new MockInjector());
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector());
 
         View view = new View(mContext);
         mBiometricView.setBackgroundView(view);
@@ -186,7 +187,7 @@
 
     @Test
     public void testBackgroundClicked_afterAuthenticated_neverSendsUserCanceled() {
-        initDialog(mContext, mCallback, new MockInjector());
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector());
 
         View view = new View(mContext);
         mBiometricView.setBackgroundView(view);
@@ -197,8 +198,7 @@
 
     @Test
     public void testBackgroundClicked_whenSmallDialog_neverSendsUserCanceled() {
-        initDialog(mContext, mCallback, new MockInjector());
-        mBiometricView.setPanelController(mPanelController);
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector());
         mBiometricView.updateSize(AuthDialog.SIZE_SMALL);
 
         View view = new View(mContext);
@@ -213,7 +213,7 @@
 
         Button tryAgainButton = new Button(mContext);
         TextView indicatorView = new TextView(mContext);
-        initDialog(mContext, mCallback, new MockInjector() {
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, new MockInjector() {
             @Override
             public Button getTryAgainButton() {
                 return tryAgainButton;
@@ -249,16 +249,18 @@
         // Create new dialog and restore the previous state into it
         Button tryAgainButton2 = new Button(mContext);
         TextView indicatorView2 = new TextView(mContext);
-        initDialog(mContext, mCallback, state, new MockInjector() {
-            @Override
-            public Button getTryAgainButton() {
-                return tryAgainButton2;
-            }
-            @Override
-            public TextView getIndicatorView() {
-                return indicatorView2;
-            }
-        });
+        initDialog(mContext, false /* allowDeviceCredential */, mCallback, state,
+                new MockInjector() {
+                    @Override
+                    public Button getTryAgainButton() {
+                        return tryAgainButton2;
+                    }
+
+                    @Override
+                    public TextView getIndicatorView() {
+                        return indicatorView2;
+                    }
+                });
         mBiometricView.setRequireConfirmation(requireConfirmation);
         waitForIdleSync();
 
@@ -271,26 +273,51 @@
         // dialog size is known.
     }
 
-    private Bundle buildBiometricPromptBundle() {
+    @Test
+    public void testNegativeButton_whenDeviceCredentialAllowed() throws InterruptedException {
+        Button negativeButton = new Button(mContext);
+        initDialog(mContext, true /* allowDeviceCredential */, mCallback, new MockInjector() {
+            @Override
+            public Button getNegativeButton() {
+                return negativeButton;
+            }
+        });
+
+        negativeButton.performClick();
+        waitForIdleSync();
+
+        verify(mCallback).onAction(AuthBiometricView.Callback.ACTION_USE_DEVICE_CREDENTIAL);
+    }
+
+    private Bundle buildBiometricPromptBundle(boolean allowDeviceCredential) {
         Bundle bundle = new Bundle();
         bundle.putCharSequence(BiometricPrompt.KEY_TITLE, "Title");
-        bundle.putCharSequence(BiometricPrompt.KEY_NEGATIVE_TEXT, "Negative");
+        int authenticators = Authenticator.TYPE_BIOMETRIC;
+        if (allowDeviceCredential) {
+            authenticators |= Authenticator.TYPE_CREDENTIAL;
+        } else {
+            bundle.putCharSequence(BiometricPrompt.KEY_NEGATIVE_TEXT, "Negative");
+        }
+        bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
         return bundle;
     }
 
-    private void initDialog(Context context, AuthBiometricView.Callback callback,
+    private void initDialog(Context context, boolean allowDeviceCredential,
+            AuthBiometricView.Callback callback,
             Bundle savedState, MockInjector injector) {
         mBiometricView = new TestableBiometricView(context, null, injector);
-        mBiometricView.setBiometricPromptBundle(buildBiometricPromptBundle());
+        mBiometricView.setBiometricPromptBundle(buildBiometricPromptBundle(allowDeviceCredential));
         mBiometricView.setCallback(callback);
         mBiometricView.restoreState(savedState);
         mBiometricView.onFinishInflateInternal();
         mBiometricView.onAttachedToWindowInternal();
+
+        mBiometricView.setPanelController(mPanelController);
     }
 
-    private void initDialog(Context context, AuthBiometricView.Callback callback,
-            MockInjector injector) {
-        initDialog(context, callback, null /* savedState */, injector);
+    private void initDialog(Context context, boolean allowDeviceCredential,
+            AuthBiometricView.Callback callback, MockInjector injector) {
+        initDialog(context, allowDeviceCredential, callback, null /* savedState */, injector);
     }
 
     private class MockInjector extends AuthBiometricView.Injector {
@@ -338,6 +365,16 @@
         public int getDelayAfterError() {
             return 0; // Keep this at 0 for tests to invoke callback immediately.
         }
+
+        @Override
+        public int getMediumToLargeAnimationDurationMs() {
+            return 0;
+        }
+
+        @Override
+        public int getAnimateCredentialStartDelayMs() {
+            return 0;
+        }
     }
 
     private class TestableBiometricView extends AuthBiometricView {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
index d4fc3f8..990f74a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
@@ -16,12 +16,30 @@
 
 package com.android.systemui.biometrics;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 
+import android.content.Context;
+import android.hardware.biometrics.Authenticator;
+import android.hardware.biometrics.BiometricAuthenticator;
+import android.hardware.biometrics.BiometricPrompt;
+import android.os.Bundle;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+import android.widget.ScrollView;
 
 import com.android.systemui.SysuiTestCase;
 
@@ -43,22 +61,21 @@
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
-
-        AuthContainerView.Config config = new AuthContainerView.Config();
-        config.mContext = mContext;
-        config.mCallback = mCallback;
-        mAuthContainer = new TestableAuthContainer(config);
     }
 
     @Test
     public void testActionAuthenticated_sendsDismissedAuthenticated() {
+        initializeContainer(Authenticator.TYPE_BIOMETRIC);
+
         mAuthContainer.mBiometricCallback.onAction(
                 AuthBiometricView.Callback.ACTION_AUTHENTICATED);
-        verify(mCallback).onDismissed(eq(AuthDialogCallback.DISMISSED_AUTHENTICATED));
+        verify(mCallback).onDismissed(eq(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED));
     }
 
     @Test
     public void testActionUserCanceled_sendsDismissedUserCanceled() {
+        initializeContainer(Authenticator.TYPE_BIOMETRIC);
+
         mAuthContainer.mBiometricCallback.onAction(
                 AuthBiometricView.Callback.ACTION_USER_CANCELED);
         verify(mCallback).onDismissed(eq(AuthDialogCallback.DISMISSED_USER_CANCELED));
@@ -66,6 +83,8 @@
 
     @Test
     public void testActionButtonNegative_sendsDismissedButtonNegative() {
+        initializeContainer(Authenticator.TYPE_BIOMETRIC);
+
         mAuthContainer.mBiometricCallback.onAction(
                 AuthBiometricView.Callback.ACTION_BUTTON_NEGATIVE);
         verify(mCallback).onDismissed(eq(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE));
@@ -73,6 +92,8 @@
 
     @Test
     public void testActionTryAgain_sendsTryAgain() {
+        initializeContainer(Authenticator.TYPE_BIOMETRIC);
+
         mAuthContainer.mBiometricCallback.onAction(
                 AuthBiometricView.Callback.ACTION_BUTTON_TRY_AGAIN);
         verify(mCallback).onTryAgainPressed();
@@ -80,14 +101,77 @@
 
     @Test
     public void testActionError_sendsDismissedError() {
+        initializeContainer(Authenticator.TYPE_BIOMETRIC);
+
         mAuthContainer.mBiometricCallback.onAction(
                 AuthBiometricView.Callback.ACTION_ERROR);
         verify(mCallback).onDismissed(AuthDialogCallback.DISMISSED_ERROR);
     }
 
+    @Test
+    public void testActionUseDeviceCredential_sendsOnDeviceCredentialPressed() {
+        initializeContainer(
+                Authenticator.TYPE_BIOMETRIC | Authenticator.TYPE_CREDENTIAL);
+
+        mAuthContainer.mBiometricCallback.onAction(
+                AuthBiometricView.Callback.ACTION_USE_DEVICE_CREDENTIAL);
+        verify(mCallback).onDeviceCredentialPressed();
+
+        // Credential view is attached to the frame layout
+        waitForIdleSync();
+        assertNotNull(mAuthContainer.mCredentialView);
+        verify(mAuthContainer.mFrameLayout).addView(eq(mAuthContainer.mCredentialView));
+    }
+
+    @Test
+    public void testAnimateToCredentialUI_invokesStartTransitionToCredentialUI() {
+        initializeContainer(
+                Authenticator.TYPE_BIOMETRIC | Authenticator.TYPE_CREDENTIAL);
+
+        mAuthContainer.mBiometricView = mock(AuthBiometricView.class);
+        mAuthContainer.animateToCredentialUI();
+        verify(mAuthContainer.mBiometricView).startTransitionToCredentialUI();
+    }
+
+    @Test
+    public void testShowBiometricUI() {
+        initializeContainer(Authenticator.TYPE_BIOMETRIC);
+
+        assertNotEquals(null, mAuthContainer.mBiometricView);
+
+        mAuthContainer.onAttachedToWindowInternal();
+        verify(mAuthContainer.mBiometricScrollView).addView(mAuthContainer.mBiometricView);
+        // Credential view is not added
+        verify(mAuthContainer.mFrameLayout, never()).addView(any());
+    }
+
+    @Test
+    public void testShowCredentialUI_doesNotInflateBiometricUI() {
+        initializeContainer(Authenticator.TYPE_CREDENTIAL);
+
+        mAuthContainer.onAttachedToWindowInternal();
+
+        assertNull(null, mAuthContainer.mBiometricView);
+        assertNotNull(mAuthContainer.mCredentialView);
+        verify(mAuthContainer.mFrameLayout).addView(mAuthContainer.mCredentialView);
+    }
+
+    private void initializeContainer(int authenticators) {
+        AuthContainerView.Config config = new AuthContainerView.Config();
+        config.mContext = mContext;
+        config.mCallback = mCallback;
+        config.mModalityMask |= BiometricAuthenticator.TYPE_FINGERPRINT;
+
+        Bundle bundle = new Bundle();
+        bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+        config.mBiometricPromptBundle = bundle;
+
+        mAuthContainer = new TestableAuthContainer(config);
+    }
+
     private class TestableAuthContainer extends AuthContainerView {
         TestableAuthContainer(AuthContainerView.Config config) {
-            super(config);
+            super(config, new MockInjector());
         }
 
         @Override
@@ -95,4 +179,32 @@
             mConfig.mCallback.onDismissed(reason);
         }
     }
+
+    private final class MockInjector extends AuthContainerView.Injector {
+        @Override
+        public ScrollView getBiometricScrollView(FrameLayout parent) {
+            return mock(ScrollView.class);
+        }
+
+        @Override
+        public FrameLayout inflateContainerView(LayoutInflater factory, ViewGroup root) {
+            return mock(FrameLayout.class);
+        }
+
+        @Override
+        public AuthPanelController getPanelController(Context context, View view,
+                boolean isManagedProfile) {
+            return mock(AuthPanelController.class);
+        }
+
+        @Override
+        public ImageView getBackgroundView(FrameLayout parent) {
+            return mock(ImageView.class);
+        }
+
+        @Override
+        public View getPanelView(FrameLayout parent) {
+            return mock(View.class);
+        }
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
index eb7be4f..dcdb5c3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
@@ -22,8 +22,11 @@
 
 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.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -33,6 +36,8 @@
 import android.content.ComponentName;
 import android.content.pm.PackageManager;
 import android.content.res.Configuration;
+import android.hardware.biometrics.Authenticator;
+import android.hardware.biometrics.BiometricConstants;
 import android.hardware.biometrics.BiometricPrompt;
 import android.hardware.biometrics.IBiometricServiceReceiverInternal;
 import android.os.Bundle;
@@ -69,7 +74,7 @@
     @Mock
     private AuthDialog mDialog2;
 
-    private TestableBiometricDialogImpl mBiometricDialogImpl;
+    private TestableAuthController mAuthController;
 
 
     @Before
@@ -90,78 +95,90 @@
         when(mDialog1.getOpPackageName()).thenReturn("Dialog1");
         when(mDialog2.getOpPackageName()).thenReturn("Dialog2");
 
-        mBiometricDialogImpl = new TestableBiometricDialogImpl(new MockInjector());
-        mBiometricDialogImpl.mContext = context;
-        mBiometricDialogImpl.mComponents = mContext.getComponents();
+        when(mDialog1.isAllowDeviceCredentials()).thenReturn(false);
+        when(mDialog2.isAllowDeviceCredentials()).thenReturn(false);
 
-        mBiometricDialogImpl.start();
+        mAuthController = new TestableAuthController(new MockInjector());
+        mAuthController.mContext = context;
+        mAuthController.mComponents = mContext.getComponents();
+
+        mAuthController.start();
     }
 
     // Callback tests
 
     @Test
     public void testSendsReasonUserCanceled_whenDismissedByUserCancel() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
         verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
     }
 
     @Test
     public void testSendsReasonNegative_whenDismissedByButtonNegative() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE);
         verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_NEGATIVE);
     }
 
     @Test
     public void testSendsReasonConfirmed_whenDismissedByButtonPositive() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_POSITIVE);
-        verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_CONFIRMED);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_POSITIVE);
+        verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED);
     }
 
     @Test
     public void testSendsReasonConfirmNotRequired_whenDismissedByAuthenticated() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.onDismissed(AuthDialogCallback.DISMISSED_AUTHENTICATED);
-        verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_CONFIRM_NOT_REQUIRED);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED);
+        verify(mReceiver).onDialogDismissed(
+                BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED);
     }
 
     @Test
     public void testSendsReasonError_whenDismissedByError() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.onDismissed(AuthDialogCallback.DISMISSED_ERROR);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onDismissed(AuthDialogCallback.DISMISSED_ERROR);
         verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_ERROR);
     }
 
     @Test
-    public void testSendsReasonDismissedBySystemServer_whenDismissedByServer() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.onDismissed(AuthDialogCallback.DISMISSED_BY_SYSTEM_SERVER);
+    public void testSendsReasonServerRequested_whenDismissedByServer() throws Exception {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BY_SYSTEM_SERVER);
         verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED);
     }
 
+    @Test
+    public void testSendsReasonCredentialConfirmed_whenDeviceCredentialAuthenticated()
+            throws Exception {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onDismissed(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED);
+        verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED);
+    }
+
     // Statusbar tests
 
     @Test
     public void testShowInvoked_whenSystemRequested()
             throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
         verify(mDialog1).show(any(), any());
     }
 
     @Test
-    public void testOnAuthenticationSucceededInvoked_whenSystemRequested() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.onBiometricAuthenticated(true, null /* failureReason */);
+    public void testOnAuthenticationSucceededInvoked_whenSystemRequested() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.onBiometricAuthenticated(true, null /* failureReason */);
         verify(mDialog1).onAuthenticationSucceeded();
     }
 
     @Test
-    public void testOnAuthenticationFailedInvoked_whenSystemRequested() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
+    public void testOnAuthenticationFailedInvoked_whenSystemRequested() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
         final String failureReason = "failure reason";
-        mBiometricDialogImpl.onBiometricAuthenticated(false, failureReason);
+        mAuthController.onBiometricAuthenticated(false, failureReason);
 
         ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
         verify(mDialog1).onAuthenticationFailed(captor.capture());
@@ -170,10 +187,10 @@
     }
 
     @Test
-    public void testOnHelpInvoked_whenSystemRequested() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
+    public void testOnHelpInvoked_whenSystemRequested() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
         final String helpMessage = "help";
-        mBiometricDialogImpl.onBiometricHelp(helpMessage);
+        mAuthController.onBiometricHelp(helpMessage);
 
         ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
         verify(mDialog1).onHelp(captor.capture());
@@ -182,10 +199,11 @@
     }
 
     @Test
-    public void testOnErrorInvoked_whenSystemRequested() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
+    public void testOnErrorInvoked_whenSystemRequested() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        final int error = 1;
         final String errMessage = "error message";
-        mBiometricDialogImpl.onBiometricError(errMessage);
+        mAuthController.onBiometricError(error, errMessage);
 
         ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
         verify(mDialog1).onError(captor.capture());
@@ -194,30 +212,82 @@
     }
 
     @Test
-    public void testDismissWithoutCallbackInvoked_whenSystemRequested() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.hideBiometricDialog();
+    public void testErrorLockout_whenCredentialAllowed_AnimatesToCredentialUI() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT;
+        final String errorString = "lockout";
+
+        when(mDialog1.isAllowDeviceCredentials()).thenReturn(true);
+
+        mAuthController.onBiometricError(error, errorString);
+        verify(mDialog1, never()).onError(anyString());
+        verify(mDialog1).animateToCredentialUI();
+    }
+
+    @Test
+    public void testErrorLockoutPermanent_whenCredentialAllowed_AnimatesToCredentialUI() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
+        final String errorString = "lockout_permanent";
+
+        when(mDialog1.isAllowDeviceCredentials()).thenReturn(true);
+
+        mAuthController.onBiometricError(error, errorString);
+        verify(mDialog1, never()).onError(anyString());
+        verify(mDialog1).animateToCredentialUI();
+    }
+
+    @Test
+    public void testErrorLockout_whenCredentialNotAllowed_sendsOnError() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT;
+        final String errorString = "lockout";
+
+        when(mDialog1.isAllowDeviceCredentials()).thenReturn(false);
+
+        mAuthController.onBiometricError(error, errorString);
+        verify(mDialog1).onError(eq(errorString));
+        verify(mDialog1, never()).animateToCredentialUI();
+    }
+
+    @Test
+    public void testErrorLockoutPermanent_whenCredentialNotAllowed_sendsOnError() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        final int error = BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
+        final String errorString = "lockout_permanent";
+
+        when(mDialog1.isAllowDeviceCredentials()).thenReturn(false);
+
+        mAuthController.onBiometricError(error, errorString);
+        verify(mDialog1).onError(eq(errorString));
+        verify(mDialog1, never()).animateToCredentialUI();
+    }
+
+    @Test
+    public void testDismissWithoutCallbackInvoked_whenSystemRequested() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.hideAuthenticationDialog();
         verify(mDialog1).dismissFromSystemServer();
     }
 
     @Test
-    public void testClientNotified_whenDismissedBySystemServer() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
-        mBiometricDialogImpl.hideBiometricDialog();
+    public void testClientNotified_whenDismissedBySystemServer() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
+        mAuthController.hideAuthenticationDialog();
         verify(mDialog1).dismissFromSystemServer();
 
-        assertNotNull(mBiometricDialogImpl.mCurrentDialog);
-        assertNotNull(mBiometricDialogImpl.mReceiver);
+        assertNotNull(mAuthController.mCurrentDialog);
+        assertNotNull(mAuthController.mReceiver);
     }
 
     // Corner case tests
 
     @Test
-    public void testShowNewDialog_beforeOldDialogDismissed_SkipsAnimations() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
+    public void testShowNewDialog_beforeOldDialogDismissed_SkipsAnimations() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
         verify(mDialog1).show(any(), any());
 
-        showDialog(BiometricPrompt.TYPE_FACE);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
 
         // First dialog should be dismissed without animation
         verify(mDialog1).dismissWithoutCallback(eq(false) /* animate */);
@@ -227,11 +297,20 @@
     }
 
     @Test
-    public void testConfigurationPersists_whenOnConfigurationChanged() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
+    public void testConfigurationPersists_whenOnConfigurationChanged() {
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
         verify(mDialog1).show(any(), any());
 
-        mBiometricDialogImpl.onConfigurationChanged(new Configuration());
+        // Return that the UI is in "showing" state
+        doAnswer(invocation -> {
+            Object[] args = invocation.getArguments();
+            Bundle savedState = (Bundle) args[0];
+            savedState.putInt(
+                    AuthDialog.KEY_CONTAINER_STATE, AuthContainerView.STATE_SHOWING);
+            return null; // onSaveState returns void
+        }).when(mDialog1).onSaveState(any());
+
+        mAuthController.onConfigurationChanged(new Configuration());
 
         ArgumentCaptor<Bundle> captor = ArgumentCaptor.forClass(Bundle.class);
         verify(mDialog1).onSaveState(captor.capture());
@@ -248,37 +327,63 @@
     }
 
     @Test
+    public void testConfigurationPersists_whenBiometricFallbackToCredential() {
+        showDialog(Authenticator.TYPE_CREDENTIAL | Authenticator.TYPE_BIOMETRIC,
+                BiometricPrompt.TYPE_FACE);
+        verify(mDialog1).show(any(), any());
+
+        // Pretend that the UI is now showing device credential UI.
+        doAnswer(invocation -> {
+            Object[] args = invocation.getArguments();
+            Bundle savedState = (Bundle) args[0];
+            savedState.putInt(
+                    AuthDialog.KEY_CONTAINER_STATE, AuthContainerView.STATE_SHOWING);
+            savedState.putBoolean(AuthDialog.KEY_CREDENTIAL_SHOWING, true);
+            return null; // onSaveState returns void
+        }).when(mDialog1).onSaveState(any());
+
+        mAuthController.onConfigurationChanged(new Configuration());
+
+        // Check that the new dialog was initialized to the credential UI.
+        ArgumentCaptor<Bundle> captor = ArgumentCaptor.forClass(Bundle.class);
+        verify(mDialog2).show(any(), captor.capture());
+        assertEquals(Authenticator.TYPE_CREDENTIAL,
+                mAuthController.mLastBiometricPromptBundle
+                        .getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+    }
+
+    @Test
     public void testClientNotified_whenTaskStackChangesDuringAuthentication() throws Exception {
-        showDialog(BiometricPrompt.TYPE_FACE);
+        showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE);
 
         List<ActivityManager.RunningTaskInfo> tasks = new ArrayList<>();
         ActivityManager.RunningTaskInfo taskInfo = mock(ActivityManager.RunningTaskInfo.class);
         taskInfo.topActivity = mock(ComponentName.class);
         when(taskInfo.topActivity.getPackageName()).thenReturn("other_package");
         tasks.add(taskInfo);
-        when(mBiometricDialogImpl.mActivityTaskManager.getTasks(anyInt())).thenReturn(tasks);
+        when(mAuthController.mActivityTaskManager.getTasks(anyInt())).thenReturn(tasks);
 
-        mBiometricDialogImpl.mTaskStackListener.onTaskStackChanged();
+        mAuthController.mTaskStackListener.onTaskStackChanged();
         waitForIdleSync();
 
-        assertNull(mBiometricDialogImpl.mCurrentDialog);
-        assertNull(mBiometricDialogImpl.mReceiver);
+        assertNull(mAuthController.mCurrentDialog);
+        assertNull(mAuthController.mReceiver);
         verify(mDialog1).dismissWithoutCallback(true /* animate */);
         verify(mReceiver).onDialogDismissed(eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL));
     }
 
     // Helpers
 
-    private void showDialog(int type) {
-        mBiometricDialogImpl.showBiometricDialog(createTestDialogBundle(),
+    private void showDialog(int authenticators, int biometricModality) {
+        mAuthController.showAuthenticationDialog(createTestDialogBundle(authenticators),
                 mReceiver /* receiver */,
-                type,
+                biometricModality,
                 true /* requireConfirmation */,
                 0 /* userId */,
                 "testPackage");
     }
 
-    private Bundle createTestDialogBundle() {
+    private Bundle createTestDialogBundle(int authenticators) {
         Bundle bundle = new Bundle();
 
         bundle.putCharSequence(BiometricPrompt.KEY_TITLE, "Title");
@@ -290,13 +395,16 @@
         // by user settings, and should be tested in BiometricService.
         bundle.putBoolean(BiometricPrompt.KEY_REQUIRE_CONFIRMATION, true);
 
+        bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+
         return bundle;
     }
 
-    private final class TestableBiometricDialogImpl extends AuthController {
+    private final class TestableAuthController extends AuthController {
         private int mBuildCount = 0;
+        private Bundle mLastBiometricPromptBundle;
 
-        public TestableBiometricDialogImpl(Injector injector) {
+        public TestableAuthController(Injector injector) {
             super(injector);
         }
 
@@ -304,6 +412,9 @@
         protected AuthDialog buildDialog(Bundle biometricPromptBundle,
                 boolean requireConfirmation, int userId, int type, String opPackageName,
                 boolean skipIntro) {
+
+            mLastBiometricPromptBundle = biometricPromptBundle;
+
             AuthDialog dialog;
             if (mBuildCount == 0) {
                 dialog = mDialog1;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/broadcast/UserBroadcastDispatcherTest.kt b/packages/SystemUI/tests/src/com/android/systemui/broadcast/UserBroadcastDispatcherTest.kt
index 011c2cd..e838d9e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/broadcast/UserBroadcastDispatcherTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/broadcast/UserBroadcastDispatcherTest.kt
@@ -70,6 +70,8 @@
     private lateinit var mockContext: Context
     @Mock
     private lateinit var mockHandler: Handler
+    @Mock
+    private lateinit var mPendingResult: BroadcastReceiver.PendingResult
 
     @Captor
     private lateinit var argumentCaptor: ArgumentCaptor<IntentFilter>
@@ -88,6 +90,7 @@
 
         universalBroadcastReceiver = UserBroadcastDispatcher(
                 mockContext, USER_ID, handler, testableLooper.looper)
+        universalBroadcastReceiver.pendingResult = mPendingResult
     }
 
     @Test
@@ -227,4 +230,19 @@
         verify(broadcastReceiver).onReceive(mockContext, intent)
         verify(broadcastReceiverOther).onReceive(mockContext, intent)
     }
+
+    @Test
+    fun testPendingResult() {
+        intentFilter = IntentFilter(ACTION_1)
+        universalBroadcastReceiver.registerReceiver(
+                ReceiverData(broadcastReceiver, intentFilter, handler, USER_HANDLE))
+
+        val intent = Intent(ACTION_1)
+        universalBroadcastReceiver.onReceive(mockContext, intent)
+
+        testableLooper.processAllMessages()
+
+        verify(broadcastReceiver).onReceive(mockContext, intent)
+        verify(broadcastReceiver).pendingResult = mPendingResult
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index 448c80e..5a2b5e3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -33,6 +33,7 @@
 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.Mockito.atLeastOnce;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
@@ -74,6 +75,7 @@
 import com.android.systemui.statusbar.phone.KeyguardBypassController;
 import com.android.systemui.statusbar.phone.NotificationGroupManager;
 import com.android.systemui.statusbar.phone.StatusBarWindowController;
+import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.ConfigurationController;
 import com.android.systemui.statusbar.policy.HeadsUpManager;
 import com.android.systemui.statusbar.policy.ZenModeController;
@@ -90,7 +92,6 @@
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper(setAsMainLooper = true)
 public class BubbleControllerTest extends SysuiTestCase {
-
     @Mock
     private NotificationEntryManager mNotificationEntryManager;
     @Mock
@@ -174,7 +175,8 @@
         TestableNotificationInterruptionStateProvider interruptionStateProvider =
                 new TestableNotificationInterruptionStateProvider(mContext,
                         mock(NotificationFilter.class),
-                        mock(StatusBarStateController.class));
+                        mock(StatusBarStateController.class),
+                        mock(BatteryController.class));
         interruptionStateProvider.setUpWithPresenter(
                 mock(NotificationPresenter.class),
                 mock(HeadsUpManager.class),
@@ -221,13 +223,13 @@
         mBubbleController.updateBubble(mRow.getEntry());
         assertNotNull(mBubbleData.getBubbleWithKey(mRow.getEntry().key));
         assertTrue(mBubbleController.hasBubbles());
-        verify(mNotificationEntryManager).updateNotifications();
+        verify(mNotificationEntryManager).updateNotifications(any());
         verify(mBubbleStateChangeListener).onHasBubblesChanged(true);
 
         mBubbleController.removeBubble(mRow.getEntry().key, BubbleController.DISMISS_USER_GESTURE);
         assertFalse(mStatusBarWindowController.getBubblesShowing());
         assertNull(mBubbleData.getBubbleWithKey(mRow.getEntry().key));
-        verify(mNotificationEntryManager, times(2)).updateNotifications();
+        verify(mNotificationEntryManager, times(2)).updateNotifications(anyString());
         verify(mBubbleStateChangeListener).onHasBubblesChanged(false);
     }
 
@@ -255,16 +257,16 @@
     @Test
     public void testDismissStack() {
         mBubbleController.updateBubble(mRow.getEntry());
-        verify(mNotificationEntryManager, times(1)).updateNotifications();
+        verify(mNotificationEntryManager, times(1)).updateNotifications(any());
         assertNotNull(mBubbleData.getBubbleWithKey(mRow.getEntry().key));
         mBubbleController.updateBubble(mRow2.getEntry());
-        verify(mNotificationEntryManager, times(2)).updateNotifications();
+        verify(mNotificationEntryManager, times(2)).updateNotifications(any());
         assertNotNull(mBubbleData.getBubbleWithKey(mRow2.getEntry().key));
         assertTrue(mBubbleController.hasBubbles());
 
         mBubbleController.dismissStack(BubbleController.DISMISS_USER_GESTURE);
         assertFalse(mStatusBarWindowController.getBubblesShowing());
-        verify(mNotificationEntryManager, times(3)).updateNotifications();
+        verify(mNotificationEntryManager, times(3)).updateNotifications(any());
         assertNull(mBubbleData.getBubbleWithKey(mRow.getEntry().key));
         assertNull(mBubbleData.getBubbleWithKey(mRow2.getEntry().key));
     }
@@ -660,8 +662,9 @@
             NotificationInterruptionStateProvider {
 
         TestableNotificationInterruptionStateProvider(Context context,
-                NotificationFilter filter, StatusBarStateController controller) {
-            super(context, filter, controller);
+                NotificationFilter filter, StatusBarStateController controller,
+                BatteryController batteryController) {
+            super(context, filter, controller, batteryController);
             mUseHeadsUp = true;
         }
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java
index af2de1b..1ce0172 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeDockHandlerTest.java
@@ -43,7 +43,6 @@
 import com.android.systemui.doze.DozeMachine.State;
 
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -58,12 +57,6 @@
     private Instrumentation mInstrumentation;
     private DockManagerFake mDockManagerFake;
 
-    @BeforeClass
-    public static void setupSuite() {
-        // We can't use KeyguardUpdateMonitor from tests.
-        DozeLog.setRegisterKeyguardCallback(false);
-    }
-
     @Before
     public void setUp() throws Exception {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
@@ -95,7 +88,7 @@
 
         mDockManagerFake.setDockEvent(DockManager.STATE_DOCKED);
 
-        verify(mMachine).requestPulse(eq(DozeLog.PULSE_REASON_DOCKING));
+        verify(mMachine).requestPulse(eq(DozeEvent.PULSE_REASON_DOCKING));
     }
 
     @Test
@@ -105,14 +98,14 @@
 
         mDockManagerFake.setDockEvent(DockManager.STATE_DOCKED);
 
-        verify(mMachine).requestPulse(eq(DozeLog.PULSE_REASON_DOCKING));
+        verify(mMachine).requestPulse(eq(DozeEvent.PULSE_REASON_DOCKING));
     }
 
     @Test
     public void testOnEvent_dockedHideWhenPulsing_requestPulseOut() {
         mDockHandler.transitionTo(DozeMachine.State.UNINITIALIZED, DozeMachine.State.INITIALIZED);
         when(mMachine.getState()).thenReturn(State.DOZE_PULSING);
-        when(mMachine.getPulseReason()).thenReturn(DozeLog.PULSE_REASON_DOCKING);
+        when(mMachine.getPulseReason()).thenReturn(DozeEvent.PULSE_REASON_DOCKING);
 
         mDockManagerFake.setDockEvent(DockManager.STATE_DOCKED_HIDE);
 
@@ -123,7 +116,7 @@
     public void testOnEvent_undockedWhenPulsing_requestPulseOut() {
         mDockHandler.transitionTo(DozeMachine.State.UNINITIALIZED, DozeMachine.State.INITIALIZED);
         when(mMachine.getState()).thenReturn(DozeMachine.State.DOZE_PULSING);
-        when(mMachine.getPulseReason()).thenReturn(DozeLog.PULSE_REASON_DOCKING);
+        when(mMachine.getPulseReason()).thenReturn(DozeEvent.PULSE_REASON_DOCKING);
 
         mDockManagerFake.setDockEvent(DockManager.STATE_NONE);
 
@@ -161,7 +154,7 @@
 
         TestableLooper.get(this).processAllMessages();
 
-        verify(mMachine).requestPulse(eq(DozeLog.PULSE_REASON_DOCKING));
+        verify(mMachine).requestPulse(eq(DozeEvent.PULSE_REASON_DOCKING));
     }
 
     @Test
@@ -174,7 +167,7 @@
 
         TestableLooper.get(this).processAllMessages();
 
-        verify(mMachine).requestPulse(eq(DozeLog.PULSE_REASON_DOCKING));
+        verify(mMachine).requestPulse(eq(DozeEvent.PULSE_REASON_DOCKING));
     }
 
     @Test
@@ -186,7 +179,7 @@
 
         mDockHandler.transitionTo(DozeMachine.State.INITIALIZED, DozeMachine.State.DOZE);
 
-        verify(mMachine, never()).requestPulse(eq(DozeLog.PULSE_REASON_DOCKING));
+        verify(mMachine, never()).requestPulse(eq(DozeEvent.PULSE_REASON_DOCKING));
     }
 
     @Test
@@ -205,7 +198,7 @@
     public void testTransitionToPulsing_whenDockedHide_requestPulseOut() {
         mDockHandler.transitionTo(DozeMachine.State.UNINITIALIZED, DozeMachine.State.INITIALIZED);
         when(mMachine.getState()).thenReturn(DozeMachine.State.DOZE_PULSING);
-        when(mMachine.getPulseReason()).thenReturn(DozeLog.PULSE_REASON_DOCKING);
+        when(mMachine.getPulseReason()).thenReturn(DozeEvent.PULSE_REASON_DOCKING);
         mDockManagerFake.setDockEvent(DockManager.STATE_DOCKED_HIDE);
 
         mDockHandler.transitionTo(DozeMachine.State.INITIALIZED, State.DOZE_PULSING);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
index 1e18e51..bbd2ab1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeMachineTest.java
@@ -46,6 +46,7 @@
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
+import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.util.wakelock.WakeLockFake;
 
 import org.junit.Before;
@@ -63,6 +64,8 @@
 
     @Mock
     private WakefulnessLifecycle mWakefulnessLifecycle;
+    @Mock
+    private DozeLog mDozeLog;
     private DozeServiceFake mServiceFake;
     private WakeLockFake mWakeLockFake;
     private AmbientDisplayConfiguration mConfigMock;
@@ -76,8 +79,8 @@
         mConfigMock = mock(AmbientDisplayConfiguration.class);
         mPartMock = mock(DozeMachine.Part.class);
 
-        mMachine = new DozeMachine(mServiceFake, mConfigMock, mWakeLockFake, mWakefulnessLifecycle);
-
+        mMachine = new DozeMachine(mServiceFake, mConfigMock, mWakeLockFake,
+                mWakefulnessLifecycle, mock(BatteryController.class), mDozeLog);
         mMachine.setParts(new DozeMachine.Part[]{mPartMock});
     }
 
@@ -112,7 +115,7 @@
     public void testPulseDone_goesToDoze() {
         when(mConfigMock.alwaysOnEnabled(anyInt())).thenReturn(false);
         mMachine.requestState(INITIALIZED);
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         mMachine.requestState(DOZE_PULSING);
 
         mMachine.requestState(DOZE_PULSE_DONE);
@@ -125,7 +128,7 @@
     public void testPulseDone_goesToAoD() {
         when(mConfigMock.alwaysOnEnabled(anyInt())).thenReturn(true);
         mMachine.requestState(INITIALIZED);
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         mMachine.requestState(DOZE_PULSING);
 
         mMachine.requestState(DOZE_PULSE_DONE);
@@ -169,7 +172,7 @@
     public void testWakeLock_heldInPulseStates() {
         mMachine.requestState(INITIALIZED);
 
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         assertTrue(mWakeLockFake.isHeld());
 
         mMachine.requestState(DOZE_PULSING);
@@ -192,7 +195,7 @@
         mMachine.requestState(INITIALIZED);
 
         mMachine.requestState(DOZE);
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         mMachine.requestState(DOZE_PULSING);
         mMachine.requestState(DOZE_PULSE_DONE);
 
@@ -204,9 +207,9 @@
         mMachine.requestState(INITIALIZED);
 
         mMachine.requestState(DOZE);
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         mMachine.requestState(DOZE_PULSING);
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         mMachine.requestState(DOZE_PULSE_DONE);
     }
 
@@ -215,7 +218,7 @@
         mMachine.requestState(INITIALIZED);
 
         mMachine.requestState(DOZE);
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         mMachine.requestState(DOZE_PULSE_DONE);
     }
 
@@ -228,7 +231,7 @@
             return null;
         }).when(mPartMock).transitionTo(any(), eq(DOZE_REQUEST_PULSE));
 
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
 
         assertEquals(DOZE_PULSING, mMachine.getState());
     }
@@ -237,9 +240,9 @@
     public void testPulseReason_getMatchesRequest() {
         mMachine.requestState(INITIALIZED);
         mMachine.requestState(DOZE);
-        mMachine.requestPulse(DozeLog.REASON_SENSOR_DOUBLE_TAP);
+        mMachine.requestPulse(DozeEvent.REASON_SENSOR_DOUBLE_TAP);
 
-        assertEquals(DozeLog.REASON_SENSOR_DOUBLE_TAP, mMachine.getPulseReason());
+        assertEquals(DozeEvent.REASON_SENSOR_DOUBLE_TAP, mMachine.getPulseReason());
     }
 
     @Test
@@ -251,7 +254,7 @@
             if (newState == DOZE_REQUEST_PULSE
                     || newState == DOZE_PULSING
                     || newState == DOZE_PULSE_DONE) {
-                assertEquals(DozeLog.PULSE_REASON_NOTIFICATION, mMachine.getPulseReason());
+                assertEquals(DozeEvent.PULSE_REASON_NOTIFICATION, mMachine.getPulseReason());
             } else {
                 assertTrue("unexpected state " + newState,
                         newState == DOZE || newState == DOZE_AOD);
@@ -259,7 +262,7 @@
             return null;
         }).when(mPartMock).transitionTo(any(), any());
 
-        mMachine.requestPulse(DozeLog.PULSE_REASON_NOTIFICATION);
+        mMachine.requestPulse(DozeEvent.PULSE_REASON_NOTIFICATION);
         mMachine.requestState(DOZE_PULSING);
         mMachine.requestState(DOZE_PULSE_DONE);
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
index ddd1685..f2665ef 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeSensorsTest.java
@@ -78,6 +78,8 @@
     private AlwaysOnDisplayPolicy mAlwaysOnDisplayPolicy;
     @Mock
     private TriggerSensor mTriggerSensor;
+    @Mock
+    private DozeLog mDozeLog;
     private SensorManagerPlugin.SensorEventListener mWakeLockScreenListener;
     private TestableLooper mTestableLooper;
     private DozeSensors mDozeSensors;
@@ -101,14 +103,14 @@
 
         mWakeLockScreenListener.onSensorChanged(mock(SensorManagerPlugin.SensorEvent.class));
         mTestableLooper.processAllMessages();
-        verify(mCallback).onSensorPulse(eq(DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN),
+        verify(mCallback).onSensorPulse(eq(DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN),
                 anyFloat(), anyFloat(), eq(null));
 
         mDozeSensors.requestTemporaryDisable();
         reset(mCallback);
         mWakeLockScreenListener.onSensorChanged(mock(SensorManagerPlugin.SensorEvent.class));
         mTestableLooper.processAllMessages();
-        verify(mCallback, never()).onSensorPulse(eq(DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN),
+        verify(mCallback, never()).onSensorPulse(eq(DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN),
                 anyFloat(), anyFloat(), eq(null));
     }
 
@@ -146,7 +148,7 @@
         TestableDozeSensors() {
             super(getContext(), mAlarmManager, mSensorManager, mDozeParameters,
                     mAmbientDisplayConfiguration, mWakeLock, mCallback, mProxCallback,
-                    mAlwaysOnDisplayPolicy);
+                    mAlwaysOnDisplayPolicy, mDozeLog);
             for (TriggerSensor sensor : mSensors) {
                 if (sensor instanceof PluginSensor
                         && ((PluginSensor) sensor).mPluginSensor.getType()
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
index f7cd696..e5ae6d5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java
@@ -41,12 +41,13 @@
 import com.android.systemui.dock.DockManager;
 import com.android.systemui.statusbar.phone.DozeParameters;
 import com.android.systemui.util.sensors.AsyncSensorManager;
+import com.android.systemui.util.sensors.FakeProximitySensor;
 import com.android.systemui.util.sensors.FakeSensorManager;
+import com.android.systemui.util.sensors.ProximitySensor;
 import com.android.systemui.util.wakelock.WakeLock;
 import com.android.systemui.util.wakelock.WakeLockFake;
 
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -60,12 +61,7 @@
     private FakeSensorManager mSensors;
     private Sensor mTapSensor;
     private DockManager mDockManagerFake;
-
-    @BeforeClass
-    public static void setupSuite() {
-        // We can't use KeyguardUpdateMonitor from tests.
-        DozeLog.setRegisterKeyguardCallback(false);
-    }
+    private FakeProximitySensor mProximitySensor;
 
     @Before
     public void setUp() throws Exception {
@@ -80,10 +76,11 @@
         mDockManagerFake = mock(DockManager.class);
         AsyncSensorManager asyncSensorManager =
                 new AsyncSensorManager(mSensors, null, new Handler());
+        mProximitySensor = new FakeProximitySensor(getContext(), asyncSensorManager);
 
         mTriggers = new DozeTriggers(mContext, mMachine, mHost, alarmManager, config, parameters,
                 asyncSensorManager, Handler.createAsync(Looper.myLooper()), wakeLock, true,
-                mDockManagerFake);
+                mDockManagerFake, mProximitySensor, mock(DozeLog.class));
         waitForSensorManager();
     }
 
@@ -95,15 +92,17 @@
         mTriggers.transitionTo(DozeMachine.State.INITIALIZED, DozeMachine.State.DOZE);
         clearInvocations(mMachine);
 
+        mProximitySensor.setLastEvent(new ProximitySensor.ProximityEvent(true, 1));
         mHost.callback.onNotificationAlerted(null /* pulseSuppressedListener */);
-        mSensors.getFakeProximitySensor().sendProximityResult(false); /* Near */
+        mProximitySensor.alertListeners();
 
         verify(mMachine, never()).requestState(any());
         verify(mMachine, never()).requestPulse(anyInt());
 
         mHost.callback.onNotificationAlerted(null /* pulseSuppressedListener */);
         waitForSensorManager();
-        mSensors.getFakeProximitySensor().sendProximityResult(true); /* Far */
+        mProximitySensor.setLastEvent(new ProximitySensor.ProximityEvent(false, 2));
+        mProximitySensor.alertListeners();
 
         verify(mMachine).requestPulse(anyInt());
     }
@@ -139,6 +138,15 @@
         verify(mDockManagerFake).removeListener(any());
     }
 
+    @Test
+    public void testProximitySensorNotAvailablel() {
+        mProximitySensor.setSensorAvailable(false);
+        mTriggers.onSensor(DozeEvent.PULSE_REASON_SENSOR_LONG_PRESS, 100, 100, null);
+        mTriggers.onSensor(DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN, 100, 100,
+                new float[]{1});
+        mTriggers.onSensor(DozeEvent.REASON_SENSOR_TAP, 100, 100, null);
+    }
+
     private void waitForSensorManager() {
         TestableLooper.get(this).processAllMessages();
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
index 25231bc..c5bddc1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeUiTest.java
@@ -65,6 +65,8 @@
     private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
     @Mock
     private DozeHost mHost;
+    @Mock
+    private DozeLog mDozeLog;
     private WakeLockFake mWakeLock;
     private Handler mHandler;
     private HandlerThread mHandlerThread;
@@ -80,7 +82,7 @@
         mHandler = mHandlerThread.getThreadHandler();
 
         mDozeUi = new DozeUi(mContext, mAlarmManager, mMachine, mWakeLock, mHost, mHandler,
-                mDozeParameters, mKeyguardUpdateMonitor);
+                mDozeParameters, mKeyguardUpdateMonitor, mDozeLog);
     }
 
     @After
@@ -135,7 +137,7 @@
         reset(mHost);
         when(mDozeParameters.getDisplayNeedsBlanking()).thenReturn(true);
         mDozeUi = new DozeUi(mContext, mAlarmManager, mMachine, mWakeLock, mHost, mHandler,
-                mDozeParameters, mKeyguardUpdateMonitor);
+                mDozeParameters, mKeyguardUpdateMonitor, mDozeLog);
 
         // Never animate if display doesn't support it.
         mDozeUi.getKeyguardCallback().onKeyguardVisibilityChanged(true);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java b/packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java
new file mode 100644
index 0000000..2f90641
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/log/RichEventTest.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2019 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.log;
+
+import static junit.framework.Assert.assertEquals;
+
+import android.testing.AndroidTestingRunner;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+
+import junit.framework.Assert;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+public class RichEventTest extends SysuiTestCase {
+
+    private static final int TOTAL_EVENT_TYPES = 1;
+
+    @Test
+    public void testCreateRichEvent_invalidType() {
+        try {
+            // indexing for events starts at 0, so TOTAL_EVENT_TYPES is an invalid type
+            new TestableRichEvent(Event.DEBUG, TOTAL_EVENT_TYPES, "msg");
+        } catch (IllegalArgumentException e) {
+            // expected
+            return;
+        }
+
+        Assert.fail("Expected an invalidArgumentException since the event type was invalid.");
+    }
+
+    @Test
+    public void testCreateRichEvent() {
+        final int eventType = 0;
+        RichEvent e = new TestableRichEvent(Event.DEBUG, eventType, "msg");
+        assertEquals(e.getType(), eventType);
+    }
+
+    class TestableRichEvent extends RichEvent {
+        TestableRichEvent(int logLevel, int type, String reason) {
+            super(logLevel, type, reason);
+        }
+
+        @Override
+        public String[] getEventLabels() {
+            return new String[]{"ACTION_NAME"};
+        }
+    }
+
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java b/packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java
new file mode 100644
index 0000000..378bba1
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/log/SysuiLogTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2019 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.log;
+
+import static junit.framework.Assert.assertEquals;
+
+import android.testing.AndroidTestingRunner;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.DumpController;
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+public class SysuiLogTest extends SysuiTestCase {
+    private static final String TEST_ID = "TestLogger";
+    private static final int MAX_LOGS = 5;
+
+    @Mock
+    private DumpController mDumpController;
+    private SysuiLog mSysuiLog;
+
+    @Before
+    public void setup() {
+        MockitoAnnotations.initMocks(this);
+    }
+
+    @Test
+    public void testLogDisabled_noLogsWritten() {
+        mSysuiLog = new SysuiLog(mDumpController, TEST_ID, MAX_LOGS, false);
+        assertEquals(mSysuiLog.mTimeline, null);
+
+        mSysuiLog.log(new Event("msg"));
+        assertEquals(mSysuiLog.mTimeline, null);
+    }
+
+    @Test
+    public void testLogEnabled_logWritten() {
+        mSysuiLog = new SysuiLog(mDumpController, TEST_ID, MAX_LOGS, true);
+        assertEquals(mSysuiLog.mTimeline.size(), 0);
+
+        mSysuiLog.log(new Event("msg"));
+        assertEquals(mSysuiLog.mTimeline.size(), 1);
+    }
+
+    @Test
+    public void testMaxLogs() {
+        mSysuiLog = new SysuiLog(mDumpController, TEST_ID, MAX_LOGS, true);
+        assertEquals(mSysuiLog.mTimeline.size(), 0);
+
+        final String msg = "msg";
+        for (int i = 0; i < MAX_LOGS + 1; i++) {
+            mSysuiLog.log(new Event(msg + i));
+        }
+
+        assertEquals(mSysuiLog.mTimeline.size(), MAX_LOGS);
+
+        // check the first message (msg0) is deleted:
+        assertEquals(mSysuiLog.mTimeline.getFirst().getMessage(), msg + "1");
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java b/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java
index 4d95f3f..4958c64 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java
@@ -19,6 +19,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.anyObject;
 import static org.mockito.Mockito.mock;
@@ -27,8 +28,11 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.IntentFilter;
 import android.os.BatteryManager;
+import android.os.Handler;
 import android.os.IThermalEventListener;
 import android.os.IThermalService;
 import android.os.PowerManager;
@@ -43,6 +47,7 @@
 import com.android.settingslib.fuelgauge.Estimate;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.power.PowerUI.WarningsUI;
 import com.android.systemui.statusbar.phone.StatusBar;
 
@@ -80,6 +85,7 @@
     @Mock private IThermalService mThermalServiceMock;
     private IThermalEventListener mUsbThermalEventListener;
     private IThermalEventListener mSkinThermalEventListener;
+    @Mock private BroadcastDispatcher mBroadcastDispatcher;
 
     @Before
     public void setup() {
@@ -96,6 +102,15 @@
     }
 
     @Test
+    public void testReceiverIsRegisteredToDispatcherOnStart() {
+        mPowerUI.start();
+        verify(mBroadcastDispatcher).registerReceiver(
+                any(BroadcastReceiver.class),
+                any(IntentFilter.class),
+                any(Handler.class)); //PowerUI does not call with User
+    }
+
+    @Test
     public void testSkinWarning_throttlingCritical() throws Exception {
         mPowerUI.start();
 
@@ -667,7 +682,7 @@
     }
 
     private void createPowerUi() {
-        mPowerUI = new PowerUI();
+        mPowerUI = new PowerUI(mBroadcastDispatcher);
         mPowerUI.mContext = mContext;
         mPowerUI.mComponents = mContext.getComponents();
         mPowerUI.mThermalService = mThermalServiceMock;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java
index f29392b..a2a20a95 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSCarrierGroupTest.java
@@ -20,6 +20,7 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import android.os.Handler;
 import android.telephony.SubscriptionManager;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
@@ -28,6 +29,7 @@
 import androidx.test.filters.SmallTest;
 
 import com.android.keyguard.CarrierTextController;
+import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.utils.leaks.LeakCheckedTest;
@@ -45,13 +47,20 @@
 public class QSCarrierGroupTest extends LeakCheckedTest {
 
     private QSCarrierGroup mCarrierGroup;
+    private CarrierTextController.CarrierTextCallback mCallback;
+    private TestableLooper mTestableLooper;
 
     @Before
     public void setup() throws Exception {
         injectLeakCheckedDependencies(ALL_SUPPORTED_CLASSES);
-        TestableLooper.get(this).runWithLooper(
+        mTestableLooper = TestableLooper.get(this);
+        mDependency.injectTestDependency(
+                Dependency.BG_HANDLER, new Handler(mTestableLooper.getLooper()));
+        mDependency.injectTestDependency(Dependency.MAIN_LOOPER, mTestableLooper.getLooper());
+        mTestableLooper.runWithLooper(
                 () -> mCarrierGroup = (QSCarrierGroup) LayoutInflater.from(mContext).inflate(
                         R.layout.qs_carrier_group, null));
+        mCallback = mCarrierGroup.getCallback();
     }
 
     @Test // throws no Exception
@@ -72,7 +81,7 @@
                 new CharSequence[]{""},
                 false,
                 new int[]{0});
-        spiedCarrierGroup.updateCarrierInfo(c1);
+        mCallback.updateCarrierInfo(c1);
 
         // listOfCarriers length 1, subscriptionIds length 1, anySims true
         CarrierTextController.CarrierTextCallbackInfo
@@ -81,7 +90,7 @@
                 new CharSequence[]{""},
                 true,
                 new int[]{0});
-        spiedCarrierGroup.updateCarrierInfo(c2);
+        mCallback.updateCarrierInfo(c2);
 
         // listOfCarriers length 2, subscriptionIds length 2, anySims false
         CarrierTextController.CarrierTextCallbackInfo
@@ -90,7 +99,7 @@
                 new CharSequence[]{"", ""},
                 false,
                 new int[]{0, 1});
-        spiedCarrierGroup.updateCarrierInfo(c3);
+        mCallback.updateCarrierInfo(c3);
 
         // listOfCarriers length 2, subscriptionIds length 2, anySims true
         CarrierTextController.CarrierTextCallbackInfo
@@ -99,7 +108,9 @@
                 new CharSequence[]{"", ""},
                 true,
                 new int[]{0, 1});
-        spiedCarrierGroup.updateCarrierInfo(c4);
+        mCallback.updateCarrierInfo(c4);
+
+        mTestableLooper.processAllMessages();
     }
 
     @Test // throws no Exception
@@ -120,7 +131,7 @@
                 new CharSequence[]{"", ""},
                 false,
                 new int[]{0});
-        spiedCarrierGroup.updateCarrierInfo(c1);
+        mCallback.updateCarrierInfo(c1);
 
         // listOfCarriers length 2, subscriptionIds length 1, anySims true
         CarrierTextController.CarrierTextCallbackInfo
@@ -129,7 +140,7 @@
                 new CharSequence[]{"", ""},
                 true,
                 new int[]{0});
-        spiedCarrierGroup.updateCarrierInfo(c2);
+        mCallback.updateCarrierInfo(c2);
 
         // listOfCarriers length 1, subscriptionIds length 2, anySims false
         CarrierTextController.CarrierTextCallbackInfo
@@ -138,7 +149,7 @@
                 new CharSequence[]{""},
                 false,
                 new int[]{0, 1});
-        spiedCarrierGroup.updateCarrierInfo(c3);
+        mCallback.updateCarrierInfo(c3);
 
         // listOfCarriers length 1, subscriptionIds length 2, anySims true
         CarrierTextController.CarrierTextCallbackInfo
@@ -147,7 +158,8 @@
                 new CharSequence[]{""},
                 true,
                 new int[]{0, 1});
-        spiedCarrierGroup.updateCarrierInfo(c4);
+        mCallback.updateCarrierInfo(c4);
+        mTestableLooper.processAllMessages();
     }
 
     @Test // throws no Exception
@@ -161,7 +173,8 @@
                 new CharSequence[]{"", ""},
                 true,
                 new int[]{0, 1});
-        spiedCarrierGroup.updateCarrierInfo(c4);
+        mCallback.updateCarrierInfo(c4);
+        mTestableLooper.processAllMessages();
     }
 
     @Test // throws no Exception
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
index 07fbbcf..7752014 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
@@ -60,6 +60,7 @@
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.util.List;
+import java.util.Objects;
 
 import javax.inject.Provider;
 
@@ -190,8 +191,7 @@
             // changed
             String newSetting = Settings.Secure.getStringForUser(getContext().getContentResolver(),
                     TILES_SETTING, ActivityManager.getCurrentUser());
-            // newSetting is not null, as it has just been set.
-            if (!newSetting.equals(previousSetting)) {
+            if (!Objects.equals(newSetting, previousSetting)) {
                 onTuningChanged(TILES_SETTING, newSetting);
             }
         }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java
index 818db87..853b2db 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/CastTileTest.java
@@ -40,7 +40,7 @@
 import com.android.systemui.qs.QSTileHost;
 import com.android.systemui.statusbar.policy.CastController;
 import com.android.systemui.statusbar.policy.CastController.CastDevice;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.NetworkController;
 
 import org.junit.Before;
@@ -64,7 +64,7 @@
     @Mock
     private ActivityStarter mActivityStarter;
     @Mock
-    private KeyguardMonitor mKeyguard;
+    private KeyguardStateController mKeyguard;
     @Mock
     private NetworkController mNetworkController;
     @Mock
@@ -83,7 +83,7 @@
         mDependency.injectTestDependency(Dependency.BG_LOOPER, mTestableLooper.getLooper());
         mController = mDependency.injectMockDependency(CastController.class);
         mActivityStarter = mDependency.injectMockDependency(ActivityStarter.class);
-        mKeyguard = mDependency.injectMockDependency(KeyguardMonitor.class);
+        mKeyguard = mDependency.injectMockDependency(KeyguardStateController.class);
         mNetworkController = mDependency.injectMockDependency(NetworkController.class);
 
         when(mHost.getContext()).thenReturn(mContext);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
index b252a0d..1bd01e1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
@@ -367,12 +367,13 @@
     }
 
     @Test
-    public void testShowBiometricDialog() {
+    public void testShowAuthenticationDialog() {
         Bundle bundle = new Bundle();
         String packageName = "test";
-        mCommandQueue.showBiometricDialog(bundle, null /* receiver */, 1, true, 3, packageName);
+        mCommandQueue.showAuthenticationDialog(bundle, null /* receiver */, 1, true, 3,
+                packageName);
         waitForIdleSync();
-        verify(mCallbacks).showBiometricDialog(eq(bundle), eq(null), eq(1), eq(true), eq(3),
+        verify(mCallbacks).showAuthenticationDialog(eq(bundle), eq(null), eq(1), eq(true), eq(3),
                 eq(packageName));
     }
 
@@ -394,16 +395,17 @@
 
     @Test
     public void testOnBiometricError() {
+        final int errorCode = 1;
         String errorMessage = "test_error_message";
-        mCommandQueue.onBiometricError(errorMessage);
+        mCommandQueue.onBiometricError(errorCode, errorMessage);
         waitForIdleSync();
-        verify(mCallbacks).onBiometricError(eq(errorMessage));
+        verify(mCallbacks).onBiometricError(eq(errorCode), eq(errorMessage));
     }
 
     @Test
-    public void testHideBiometricDialog() {
-        mCommandQueue.hideBiometricDialog();
+    public void testHideAuthenticationDialog() {
+        mCommandQueue.hideAuthenticationDialog();
         waitForIdleSync();
-        verify(mCallbacks).hideBiometricDialog();
+        verify(mCallbacks).hideAuthenticationDialog();
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
index 0817ee9..cf6fd4a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/KeyguardIndicationControllerTest.java
@@ -51,8 +51,8 @@
 import com.android.systemui.statusbar.phone.KeyguardIndicationTextView;
 import com.android.systemui.statusbar.phone.LockIcon;
 import com.android.systemui.statusbar.phone.ShadeController;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
 import com.android.systemui.statusbar.policy.AccessibilityController;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.util.wakelock.WakeLockFake;
 
 import org.junit.Before;
@@ -79,7 +79,7 @@
     @Mock
     private AccessibilityController mAccessibilityController;
     @Mock
-    private UnlockMethodCache mUnlockMethodCache;
+    private KeyguardStateController mKeyguardStateController;
     @Mock
     private StatusBarStateController mStatusBarStateController;
     @Mock
@@ -111,7 +111,7 @@
         }
         mController = new KeyguardIndicationController(mContext, mIndicationArea, mLockIcon,
                 mLockPatternUtils, mWakeLock, mShadeController, mAccessibilityController,
-                mUnlockMethodCache, mStatusBarStateController, mKeyguardUpdateMonitor);
+                mKeyguardStateController, mStatusBarStateController, mKeyguardUpdateMonitor);
     }
 
     @Test
@@ -187,7 +187,7 @@
     }
 
     @Test
-    public void unlockMethodCache_listenerUpdatesIndication() {
+    public void updateMonitor_listenerUpdatesIndication() {
         createController();
         String restingIndication = "Resting indication";
 
@@ -203,14 +203,14 @@
         reset(mKeyguardUpdateMonitor);
         when(mKeyguardUpdateMonitor.isUserUnlocked(anyInt())).thenReturn(true);
         when(mKeyguardUpdateMonitor.getUserHasTrust(anyInt())).thenReturn(false);
-        mController.onUnlockMethodStateChanged();
+        mController.onUnlockedChanged();
         assertThat(mTextView.getText()).isEqualTo(restingIndication);
     }
 
     @Test
-    public void unlockMethodCache_listener() {
+    public void updateMonitor_listener() {
         createController();
-        verify(mUnlockMethodCache).addListener(eq(mController));
+        verify(mKeyguardStateController).addCallback(eq(mController));
         verify(mStatusBarStateController).addCallback(eq(mController));
         verify(mKeyguardUpdateMonitor, times(2)).registerCallback(any());
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NavigationBarControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NavigationBarControllerTest.java
index 7d2ccdc..cfa4065a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NavigationBarControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NavigationBarControllerTest.java
@@ -23,22 +23,19 @@
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
 
-import android.content.Context;
-import android.hardware.display.DisplayManager;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
 import android.util.SparseArray;
-import android.view.Display;
-import android.view.WindowManager;
 
 import androidx.test.filters.SmallTest;
 
@@ -58,7 +55,6 @@
 public class NavigationBarControllerTest extends SysuiTestCase {
 
     private NavigationBarController mNavigationBarController;
-    private Display mDisplay;
     private NavigationBarFragment mDefaultNavBar;
     private NavigationBarFragment mSecondaryNavBar;
 
@@ -88,37 +84,28 @@
     @After
     public void tearDown() {
         mNavigationBarController = null;
-        mDisplay = null;
         mDefaultNavBar = null;
         mSecondaryNavBar = null;
     }
 
     @Test
     public void testCreateNavigationBarsIncludeDefaultTrue() {
-        initializeDisplayManager();
         doNothing().when(mNavigationBarController).createNavigationBar(any(), any());
 
         mNavigationBarController.createNavigationBars(true, null);
 
-        verify(mNavigationBarController).createNavigationBar(any(Display.class), any());
+        verify(mNavigationBarController).createNavigationBar(
+                argThat(display -> display.getDisplayId() == DEFAULT_DISPLAY), any());
     }
 
     @Test
     public void testCreateNavigationBarsIncludeDefaultFalse() {
-        initializeDisplayManager();
         doNothing().when(mNavigationBarController).createNavigationBar(any(), any());
 
         mNavigationBarController.createNavigationBars(false, null);
 
-        verify(mNavigationBarController, never()).createNavigationBar(any(), any());
-    }
-
-    private void initializeDisplayManager() {
-        DisplayManager displayManager = mock(DisplayManager.class);
-        mDisplay = mContext.getSystemService(WindowManager.class).getDefaultDisplay();
-        Display[] displays = {mDisplay};
-        when(displayManager.getDisplays()).thenReturn(displays);
-        mContext.addMockSystemService(Context.DISPLAY_SERVICE, displayManager);
+        verify(mNavigationBarController, never()).createNavigationBar(
+                argThat(display -> display.getDisplayId() == DEFAULT_DISPLAY), any());
     }
 
     // Tests if NPE occurs when call checkNavBarModes() with invalid display.
@@ -240,4 +227,10 @@
 
         verify(mSecondaryNavBar).disableAnimationsDuringHide(eq(500L));
     }
+
+    @Test
+    public void testGetAssistHandlerViewController_noCrash() {
+        reset(mNavigationBarController.mNavigationBars);
+        mNavigationBarController.getAssistHandlerViewController();
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
index 350ab5a..28a7e40 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
@@ -52,6 +52,7 @@
 import com.android.systemui.statusbar.notification.NotificationFilter;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.HeadsUpManager;
 
 import org.junit.Before;
@@ -84,6 +85,8 @@
     HeadsUpManager mHeadsUpManager;
     @Mock
     NotificationInterruptionStateProvider.HeadsUpSuppressor mHeadsUpSuppressor;
+    @Mock
+    BatteryController mBatteryController;
 
     private NotificationInterruptionStateProvider mNotifInterruptionStateProvider;
 
@@ -97,7 +100,8 @@
                         mDreamManager,
                         mAmbientDisplayConfiguration,
                         mNotificationFilter,
-                        mStatusBarStateController);
+                        mStatusBarStateController,
+                        mBatteryController);
 
         mNotifInterruptionStateProvider.setUpWithPresenter(
                 mPresenter,
@@ -590,17 +594,17 @@
     /**
      * Testable class overriding constructor.
      */
-    public class TestableNotificationInterruptionStateProvider extends
+    public static class TestableNotificationInterruptionStateProvider extends
             NotificationInterruptionStateProvider {
 
         TestableNotificationInterruptionStateProvider(Context context,
                 PowerManager powerManager, IDreamManager dreamManager,
                 AmbientDisplayConfiguration ambientDisplayConfiguration,
                 NotificationFilter notificationFilter,
-                StatusBarStateController statusBarStateController) {
+                StatusBarStateController statusBarStateController,
+                BatteryController batteryController) {
             super(context, powerManager, dreamManager, ambientDisplayConfiguration,
-                    notificationFilter,
-                    statusBarStateController);
+                    notificationFilter, batteryController, statusBarStateController);
         }
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
index a027643..0569c55 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerTest.java
@@ -25,6 +25,7 @@
 import static junit.framework.Assert.assertTrue;
 
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -99,7 +100,7 @@
     @Test
     public void testLockScreenShowNotificationsChangeUpdatesNotifications() {
         mLockscreenUserManager.getLockscreenSettingsObserverForTest().onChange(false);
-        verify(mEntryManager, times(1)).updateNotifications();
+        verify(mEntryManager, times(1)).updateNotifications(anyString());
     }
 
     @Test
@@ -138,7 +139,7 @@
     public void testSettingsObserverUpdatesNotifications() {
         when(mDeviceProvisionedController.isDeviceProvisioned()).thenReturn(true);
         mLockscreenUserManager.getSettingsObserverForTest().onChange(false);
-        verify(mEntryManager, times(1)).updateNotifications();
+        verify(mEntryManager, times(1)).updateNotifications(anyString());
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimatorTest.java
index 5558393..145a25c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimatorTest.java
@@ -17,11 +17,8 @@
 package com.android.systemui.statusbar.notification;
 
 import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.anyObject;
 import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -30,23 +27,20 @@
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
-import android.testing.TestableLooper.RunWithLooper;
 import android.view.RemoteAnimationAdapter;
 import android.view.View;
-import android.widget.FrameLayout;
 
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.NotificationTestHelper;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
 import com.android.systemui.statusbar.phone.NotificationPanelView;
 import com.android.systemui.statusbar.phone.StatusBarWindowView;
+import com.android.systemui.statusbar.phone.StatusBarWindowViewController;
 
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.stubbing.Answer;
 
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
@@ -55,6 +49,8 @@
 
     private ActivityLaunchAnimator mLaunchAnimator;
     private ActivityLaunchAnimator.Callback mCallback = mock(ActivityLaunchAnimator.Callback.class);
+    private StatusBarWindowViewController mStatusBarWindowViewController = mock(
+            StatusBarWindowViewController.class);
     private StatusBarWindowView mStatusBarWindowView = mock(StatusBarWindowView.class);
     private NotificationListContainer mNotificationContainer
             = mock(NotificationListContainer.class);
@@ -62,10 +58,11 @@
 
     @Before
     public void setUp() throws Exception {
+        when(mStatusBarWindowViewController.getView()).thenReturn(mStatusBarWindowView);
         when(mStatusBarWindowView.getResources()).thenReturn(mContext.getResources());
         when(mCallback.areLaunchAnimationsEnabled()).thenReturn(true);
         mLaunchAnimator = new ActivityLaunchAnimator(
-                mStatusBarWindowView,
+                mStatusBarWindowViewController,
                 mCallback,
                 mock(NotificationPanelView.class),
                 mNotificationContainer);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java
index d804b6f..99dc895 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicPrivacyControllerTest.java
@@ -26,22 +26,17 @@
 import android.test.suitebuilder.annotation.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
-import android.testing.TestableLooper.RunWithLooper;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.NotificationLockscreenUserManager;
-import com.android.systemui.statusbar.NotificationViewHierarchyManager;
 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
-import com.android.systemui.statusbar.phone.UnlockMethodCache;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-import dagger.Lazy;
-
 
 @SmallTest
 @org.junit.runner.RunWith(AndroidTestingRunner.class)
@@ -49,19 +44,17 @@
 public class DynamicPrivacyControllerTest extends SysuiTestCase {
 
     private DynamicPrivacyController mDynamicPrivacyController;
-    private UnlockMethodCache mCache = mock(UnlockMethodCache.class);
     private NotificationLockscreenUserManager mLockScreenUserManager
             = mock(NotificationLockscreenUserManager.class);
     private DynamicPrivacyController.Listener mListener
             = mock(DynamicPrivacyController.Listener.class);
-    private KeyguardMonitor mKeyguardMonitor = mock(KeyguardMonitor.class);
+    private KeyguardStateController mKeyguardStateController = mock(KeyguardStateController.class);
 
     @Before
     public void setUp() throws Exception {
-        when(mCache.canSkipBouncer()).thenReturn(false);
-        when(mKeyguardMonitor.isShowing()).thenReturn(true);
+        when(mKeyguardStateController.isShowing()).thenReturn(true);
         mDynamicPrivacyController = new DynamicPrivacyController(
-                mLockScreenUserManager, mKeyguardMonitor, mCache,
+                mLockScreenUserManager, mKeyguardStateController,
                 mock(StatusBarStateController.class));
         mDynamicPrivacyController.setStatusBarKeyguardViewManager(
                 mock(StatusBarKeyguardViewManager.class));
@@ -71,7 +64,7 @@
     @Test
     public void testDynamicFalseWhenCannotSkipBouncer() {
         enableDynamicPrivacy();
-        when(mCache.canSkipBouncer()).thenReturn(false);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(false);
         Assert.assertFalse("can't skip bouncer but is dynamically unlocked",
                 mDynamicPrivacyController.isDynamicallyUnlocked());
     }
@@ -79,16 +72,16 @@
     @Test
     public void testDynamicTrueWhenCanSkipBouncer() {
         enableDynamicPrivacy();
-        when(mCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         Assert.assertTrue("Isn't dynamically unlocked even though we can skip bouncer",
                 mDynamicPrivacyController.isDynamicallyUnlocked());
     }
 
     @Test
     public void testNotifiedWhenEnabled() {
-        when(mCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         enableDynamicPrivacy();
-        mDynamicPrivacyController.onUnlockMethodStateChanged();
+        mDynamicPrivacyController.onUnlockedChanged();
         verify(mListener).onDynamicPrivacyChanged();
     }
 
@@ -99,10 +92,10 @@
 
     @Test
     public void testNotNotifiedWithoutNotifications() {
-        when(mCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         when(mLockScreenUserManager.shouldHideNotifications(anyInt())).thenReturn(
                 true);
-        mDynamicPrivacyController.onUnlockMethodStateChanged();
+        mDynamicPrivacyController.onUnlockedChanged();
         verifyNoMoreInteractions(mListener);
     }
 }
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
index 30e02e6..e52a258 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
@@ -28,6 +28,7 @@
 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.doAnswer;
@@ -41,7 +42,6 @@
 import android.app.Notification;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
-import android.content.Context;
 import android.content.Intent;
 import android.graphics.drawable.Icon;
 import android.os.Handler;
@@ -69,6 +69,7 @@
 import com.android.systemui.statusbar.NotificationLifetimeExtender;
 import com.android.systemui.statusbar.NotificationListener;
 import com.android.systemui.statusbar.NotificationLockscreenUserManager;
+import com.android.systemui.statusbar.NotificationMediaManager;
 import com.android.systemui.statusbar.NotificationPresenter;
 import com.android.systemui.statusbar.NotificationRemoteInputManager;
 import com.android.systemui.statusbar.NotificationRemoveInterceptor;
@@ -80,6 +81,7 @@
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.collection.NotificationRowBinder;
 import com.android.systemui.statusbar.notification.collection.NotificationRowBinderImpl;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.NotificationContentInflater.InflationFlag;
 import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -145,8 +147,9 @@
     private class TestableNotificationEntryManager extends NotificationEntryManager {
         private final CountDownLatch mCountDownLatch;
 
-        TestableNotificationEntryManager(Context context) {
-            super(context);
+        TestableNotificationEntryManager() {
+            super(new NotificationData(mock(NotificationSectionsFeatureManager.class),
+                    mock(NotifLog.class)), mock(NotifLog.class));
             mCountDownLatch = new CountDownLatch(1);
         }
 
@@ -225,6 +228,7 @@
         mDependency.injectTestDependency(MetricsLogger.class, mMetricsLogger);
         mDependency.injectTestDependency(SmartReplyController.class, mSmartReplyController);
         mDependency.injectTestDependency(KeyguardEnvironment.class, mEnvironment);
+        mDependency.injectMockDependency(NotificationMediaManager.class);
 
         mCountDownLatch = new CountDownLatch(1);
 
@@ -250,7 +254,7 @@
 
         mEntry.expandedIcon = mock(StatusBarIconView.class);
 
-        mEntryManager = new TestableNotificationEntryManager(mContext);
+        mEntryManager = new TestableNotificationEntryManager();
         Dependency.get(InitController.class).executePostInitTasks();
         mEntryManager.setUpWithPresenter(mPresenter, mListContainer, mHeadsUpManager);
         mEntryManager.addNotificationEntryListener(mEntryListener);
@@ -258,7 +262,9 @@
 
         NotificationRowBinderImpl notificationRowBinder =
                 new NotificationRowBinderImpl(mContext, true, /* allowLongPress */
-                        mock(KeyguardBypassController.class), mock(StatusBarStateController.class));
+                        mock(KeyguardBypassController.class),
+                        mock(StatusBarStateController.class),
+                        mock(NotifLog.class));
         notificationRowBinder.setUpWithPresenter(
                 mPresenter, mListContainer, mHeadsUpManager, mEntryManager, mBindCallback);
         notificationRowBinder.setNotificationClicker(mock(NotificationClicker.class));
@@ -349,7 +355,7 @@
         // Ensure that update callbacks happen in correct order
         InOrder order = inOrder(mEntryListener, notifData, mPresenter, mEntryListener);
         order.verify(mEntryListener).onPreEntryUpdated(mEntry);
-        order.verify(notifData).filterAndSort();
+        order.verify(notifData).filterAndSort(anyString());
         order.verify(mPresenter).updateNotificationViews();
         order.verify(mEntryListener).onPostEntryUpdated(mEntry);
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
index 8d496a7..8207a04 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationListControllerTest.java
@@ -21,6 +21,7 @@
 
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -43,9 +44,11 @@
 import com.android.systemui.statusbar.NotificationEntryBuilder;
 import com.android.systemui.statusbar.notification.collection.NotificationData;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
+import com.android.systemui.util.DeviceConfigProxyFake;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -73,7 +76,9 @@
     private DeviceProvisionedListener mProvisionedListener;
 
     // TODO: Remove this once EntryManager no longer needs to be mocked
-    private NotificationData mNotificationData = new NotificationData(mContext);
+    private NotificationData mNotificationData =
+            new NotificationData(new NotificationSectionsFeatureManager(
+                    new DeviceConfigProxyFake(), mContext), mock(NotifLog.class));
 
     private int mNextNotifId = 0;
 
@@ -110,7 +115,7 @@
     @Test
     public void testCallUpdateNotificationsOnDeviceProvisionedChange() {
         mProvisionedListener.onDeviceProvisionedChanged();
-        verify(mEntryManager).updateNotifications();
+        verify(mEntryManager).updateNotifications(anyString());
     }
 
     @Test
@@ -130,8 +135,8 @@
 
         // THEN the app op is added to the entry
         assertTrue(entry.mActiveAppOps.contains(AppOpsManager.OP_CAMERA));
-        // THEN updateNotifications() is called
-        verify(mEntryManager, times(1)).updateNotifications();
+        // THEN updateNotifications(TEST) is called
+        verify(mEntryManager, times(1)).updateNotifications(anyString());
     }
 
     @Test
@@ -143,8 +148,8 @@
         // WHEN An unrelated notification gets a new app op
         mController.updateNotificationsForAppOp(AppOpsManager.OP_CAMERA, 1000, "pkg", true);
 
-        // THEN We never call updateNotifications()
-        verify(mEntryManager, never()).updateNotifications();
+        // THEN We never call updateNotifications(TEST)
+        verify(mEntryManager, never()).updateNotifications(anyString());
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationSectionsFeatureManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationSectionsFeatureManagerTest.kt
new file mode 100644
index 0000000..b3d0d22
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationSectionsFeatureManagerTest.kt
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2019 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.statusbar.notification
+
+import android.provider.DeviceConfig
+import android.provider.Settings
+import android.provider.Settings.Secure.NOTIFICATION_NEW_INTERRUPTION_MODEL
+import android.testing.AndroidTestingRunner
+
+import androidx.test.filters.SmallTest
+
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags.NOTIFICATIONS_USE_PEOPLE_FILTERING
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.util.DeviceConfigProxyFake
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidTestingRunner::class)
+@SmallTest
+class NotificationSectionsFeatureManagerTest : SysuiTestCase() {
+    var manager: NotificationSectionsFeatureManager? = null
+    val proxyFake = DeviceConfigProxyFake()
+
+    @Before
+    public fun setup() {
+        Settings.Secure.putInt(mContext.getContentResolver(),
+        NOTIFICATION_NEW_INTERRUPTION_MODEL, 1)
+        manager = NotificationSectionsFeatureManager(proxyFake, mContext)
+        manager!!.clearCache()
+    }
+
+    @Test
+    public fun testPeopleFilteringOff_newInterruptionModelOn() {
+        proxyFake.setProperty(
+                DeviceConfig.NAMESPACE_SYSTEMUI, NOTIFICATIONS_USE_PEOPLE_FILTERING, "false", false)
+
+        assertFalse("People filtering should be disabled", manager!!.isFilteringEnabled())
+        assertTrue("Expecting 2 buckets when people filtering is disabled",
+                manager!!.getNumberOfBuckets() == 2)
+    }
+
+    @Test
+    public fun testPeopleFilteringOn_newInterruptionModelOn() {
+        proxyFake.setProperty(
+                DeviceConfig.NAMESPACE_SYSTEMUI, NOTIFICATIONS_USE_PEOPLE_FILTERING, "true", false)
+
+        assertTrue("People filtering should be enabled", manager!!.isFilteringEnabled())
+        assertTrue("Expecting 3 buckets when people filtering is enabled",
+                manager!!.getNumberOfBuckets() == 3)
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java
index 657ec61d..59c76a8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationDataTest.java
@@ -50,7 +50,6 @@
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Person;
-import android.content.Context;
 import android.content.Intent;
 import android.content.pm.IPackageManager;
 import android.content.pm.PackageManager;
@@ -78,7 +77,9 @@
 import com.android.systemui.statusbar.NotificationTestHelper;
 import com.android.systemui.statusbar.RankingBuilder;
 import com.android.systemui.statusbar.SbnBuilder;
+import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
 import com.android.systemui.statusbar.notification.collection.NotificationData.KeyguardEnvironment;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.phone.NotificationGroupManager;
 import com.android.systemui.statusbar.phone.ShadeController;
@@ -139,8 +140,9 @@
         mDependency.injectTestDependency(KeyguardEnvironment.class, mEnvironment);
         when(mEnvironment.isDeviceProvisioned()).thenReturn(true);
         when(mEnvironment.isNotificationForCurrentProfiles(any())).thenReturn(true);
-        mNotificationData = new TestableNotificationData(mContext);
-        mNotificationData.updateRanking(mock(NotificationListenerService.RankingMap.class));
+        mNotificationData = new TestableNotificationData(
+                mock(NotificationSectionsFeatureManager.class));
+        mNotificationData.updateRanking(mock(NotificationListenerService.RankingMap.class), "");
         mRow = new NotificationTestHelper(getContext()).createRow();
         Dependency.get(InitController.class).executePostInitTasks();
     }
@@ -631,8 +633,8 @@
     }
 
     public static class TestableNotificationData extends NotificationData {
-        public TestableNotificationData(Context context) {
-            super(context);
+        public TestableNotificationData(NotificationSectionsFeatureManager sectionsFeatureManager) {
+            super(sectionsFeatureManager, mock(NotifLog.class));
         }
 
         public static final String OVERRIDE_RANK = "r";
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java
index 6d64395..cc89504 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationBlockingHelperManagerTest.java
@@ -27,6 +27,7 @@
 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.Mockito.never;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
@@ -62,7 +63,6 @@
 @org.junit.runner.RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
 public class NotificationBlockingHelperManagerTest extends SysuiTestCase {
-
     private NotificationBlockingHelperManager mBlockingHelperManager;
 
     private NotificationTestHelper mHelper;
@@ -112,7 +112,7 @@
         assertTrue(mBlockingHelperManager.dismissCurrentBlockingHelper());
         assertTrue(mBlockingHelperManager.isBlockingHelperRowNull());
 
-        verify(mEntryManager, times(0)).updateNotifications();
+        verify(mEntryManager, times(0)).updateNotifications(anyString());
     }
 
     @Test
@@ -125,7 +125,7 @@
         assertTrue(mBlockingHelperManager.dismissCurrentBlockingHelper());
         assertTrue(mBlockingHelperManager.isBlockingHelperRowNull());
 
-        verify(mEntryManager).updateNotifications();
+        verify(mEntryManager).updateNotifications(anyString());
     }
 
     @Test
@@ -267,7 +267,7 @@
         assertTrue(mBlockingHelperManager.dismissCurrentBlockingHelper());
         assertTrue(mBlockingHelperManager.isBlockingHelperRowNull());
 
-        verify(mEntryManager).updateNotifications();
+        verify(mEntryManager).updateNotifications(anyString());
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java
index addceb5..3f467ea 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationRoundnessManagerTest.java
@@ -32,10 +32,12 @@
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.NotificationTestHelper;
+import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
 import com.android.systemui.statusbar.notification.row.ExpandableView;
 import com.android.systemui.statusbar.phone.KeyguardBypassController;
+import com.android.systemui.util.DeviceConfigProxy;
 
 import org.junit.Assert;
 import org.junit.Before;
@@ -64,7 +66,9 @@
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        mRoundnessManager = new NotificationRoundnessManager(mBypassController, mContext);
+        mRoundnessManager = new NotificationRoundnessManager(
+                mBypassController,
+                new NotificationSectionsFeatureManager(new DeviceConfigProxy(), mContext));
         com.android.systemui.util.Assert.sMainLooper = TestableLooper.get(this).getLooper();
         NotificationTestHelper testHelper = new NotificationTestHelper(getContext());
         mFirst = testHelper.createRow();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
index 31054260..11ae0cc 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
@@ -55,7 +55,6 @@
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.classifier.FalsingManagerFake;
 import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.EmptyShadeView;
 import com.android.systemui.statusbar.NotificationPresenter;
 import com.android.systemui.statusbar.NotificationRemoteInputManager;
@@ -65,6 +64,7 @@
 import com.android.systemui.statusbar.SysuiStatusBarStateController;
 import com.android.systemui.statusbar.notification.DynamicPrivacyController;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
 import com.android.systemui.statusbar.notification.collection.NotificationData;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
@@ -79,6 +79,7 @@
 import com.android.systemui.statusbar.phone.StatusBar;
 import com.android.systemui.statusbar.phone.StatusBarTest.TestableNotificationEntryManager;
 import com.android.systemui.statusbar.policy.ConfigurationController;
+import com.android.systemui.util.DeviceConfigProxyFake;
 
 import org.junit.After;
 import org.junit.Before;
@@ -144,11 +145,10 @@
         mDependency.injectMockDependency(ShadeController.class);
         when(mRemoteInputManager.getController()).thenReturn(mRemoteInputController);
 
-        mEntryManager = new TestableNotificationEntryManager(mContext);
+        mEntryManager = new TestableNotificationEntryManager(mNotificationData);
         mDependency.injectTestDependency(NotificationEntryManager.class, mEntryManager);
         Dependency.get(InitController.class).executePostInitTasks();
-        mEntryManager.setUpForTest(mock(NotificationPresenter.class), null, mHeadsUpManager,
-                mNotificationData);
+        mEntryManager.setUpForTest(mock(NotificationPresenter.class), null, mHeadsUpManager);
 
 
         NotificationShelf notificationShelf = mock(NotificationShelf.class);
@@ -166,7 +166,8 @@
                 mock(SysuiStatusBarStateController.class),
                 mHeadsUpManager,
                 mKeyguardBypassController,
-                new FalsingManagerFake());
+                new FalsingManagerFake(),
+                new NotificationSectionsFeatureManager(new DeviceConfigProxyFake(), mContext));
         mStackScroller = spy(mStackScrollerInternal);
         mStackScroller.setShelf(notificationShelf);
         mStackScroller.setStatusBar(mBar);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
index fd67611..ff9aae7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/BiometricsUnlockControllerTest.java
@@ -39,6 +39,7 @@
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.keyguard.KeyguardViewMediator;
 import com.android.systemui.statusbar.NotificationMediaManager;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -70,7 +71,7 @@
     @Mock
     private StatusBar mStatusBar;
     @Mock
-    private UnlockMethodCache mUnlockMethodCache;
+    private KeyguardStateController mKeyguardStateController;
     @Mock
     private Handler mHandler;
     @Mock
@@ -82,7 +83,7 @@
         MockitoAnnotations.initMocks(this);
         when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(true);
         when(mUpdateMonitor.isDeviceInteractive()).thenReturn(true);
-        when(mUnlockMethodCache.isFaceAuthEnabled()).thenReturn(true);
+        when(mKeyguardStateController.isFaceAuthEnabled()).thenReturn(true);
         when(mKeyguardBypassController.onBiometricAuthenticated(any())).thenReturn(true);
         when(mKeyguardBypassController.canPlaySubtleWindowAnimations()).thenReturn(true);
         mContext.addMockSystemService(PowerManager.class, mPowerManager);
@@ -90,7 +91,7 @@
         mDependency.injectTestDependency(StatusBarWindowController.class,
                 mStatusBarWindowController);
         mBiometricUnlockController = new BiometricUnlockController(mContext, mDozeScrimController,
-                mKeyguardViewMediator, mScrimController, mStatusBar, mUnlockMethodCache,
+                mKeyguardViewMediator, mScrimController, mStatusBar, mKeyguardStateController,
                 mHandler, mUpdateMonitor, 0 /* wakeUpDelay */, mKeyguardBypassController);
         mBiometricUnlockController.setStatusBarKeyguardViewManager(mStatusBarKeyguardViewManager);
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java
index 20c739f..1ce336e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/DozeScrimControllerTest.java
@@ -27,6 +27,7 @@
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.doze.DozeHost;
+import com.android.systemui.doze.DozeLog;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -41,12 +42,14 @@
 
     @Mock
     private DozeParameters mDozeParameters;
+    @Mock
+    private DozeLog mDozeLog;
     private DozeScrimController mDozeScrimController;
 
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
-        mDozeScrimController = new DozeScrimController(mDozeParameters);
+        mDozeScrimController = new DozeScrimController(mDozeParameters, mDozeLog);
         mDozeScrimController.setDozing(true);
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
index c51263f..cb87d7d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardBouncerTest.java
@@ -52,6 +52,7 @@
 import com.android.systemui.keyguard.DismissCallbackRegistry;
 import com.android.systemui.plugins.ActivityStarter.OnDismissAction;
 import com.android.systemui.plugins.FalsingManager;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import org.junit.Assert;
 import org.junit.Before;
@@ -83,11 +84,13 @@
     @Mock
     private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
     @Mock
-    private UnlockMethodCache mUnlockMethodCache;
+    private KeyguardStateController mKeyguardStateController;
     @Mock
     private KeyguardBypassController mKeyguardBypassController;
     @Mock
     private Handler mHandler;
+    @Mock
+    private KeyguardSecurityModel mKeyguardSecurityModel;
 
     private KeyguardBouncer mBouncer;
 
@@ -96,13 +99,16 @@
         com.android.systemui.util.Assert.sMainLooper = TestableLooper.get(this).getLooper();
         MockitoAnnotations.initMocks(this);
         mDependency.injectTestDependency(KeyguardUpdateMonitor.class, mKeyguardUpdateMonitor);
+        mDependency.injectTestDependency(KeyguardSecurityModel.class, mKeyguardSecurityModel);
+        when(mKeyguardSecurityModel.getSecurityMode(anyInt()))
+                .thenReturn(KeyguardSecurityModel.SecurityMode.None);
         DejankUtils.setImmediate(true);
         final ViewGroup container = new FrameLayout(getContext());
         when(mKeyguardHostView.getViewTreeObserver()).thenReturn(mViewTreeObserver);
         when(mKeyguardHostView.getHeight()).thenReturn(500);
         mBouncer = new KeyguardBouncer(getContext(), mViewMediatorCallback,
                 mLockPatternUtils, container, mDismissCallbackRegistry, mFalsingManager,
-                mExpansionCallback, mUnlockMethodCache, mKeyguardUpdateMonitor,
+                mExpansionCallback, mKeyguardStateController, mKeyguardUpdateMonitor,
                 mKeyguardBypassController, mHandler) {
             @Override
             protected void inflateView() {
@@ -305,14 +311,6 @@
     }
 
     @Test
-    public void testNeedsFullscreenBouncer_asksKeyguardView() {
-        mBouncer.ensureView();
-        mBouncer.needsFullscreenBouncer();
-        verify(mKeyguardHostView).getSecurityMode();
-        verify(mKeyguardHostView, never()).getCurrentSecurityMode();
-    }
-
-    @Test
     public void testIsFullscreenBouncer_asksKeyguardView() {
         mBouncer.ensureView();
         mBouncer.isFullscreenBouncer();
@@ -384,7 +382,7 @@
 
     @Test
     public void testShow_delaysIfFaceAuthIsRunning() {
-        when(mUnlockMethodCache.isFaceAuthEnabled()).thenReturn(true);
+        when(mKeyguardStateController.isFaceAuthEnabled()).thenReturn(true);
         mBouncer.show(true /* reset */);
 
         ArgumentCaptor<Runnable> showRunnable = ArgumentCaptor.forClass(Runnable.class);
@@ -397,7 +395,7 @@
 
     @Test
     public void testShow_delaysIfFaceAuthIsRunning_unlessBypass() {
-        when(mUnlockMethodCache.isFaceAuthEnabled()).thenReturn(true);
+        when(mKeyguardStateController.isFaceAuthEnabled()).thenReturn(true);
         when(mKeyguardBypassController.getBypassEnabled()).thenReturn(true);
         mBouncer.show(true /* reset */);
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
index 33d3ac8..237f6ac 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarFragmentTest.java
@@ -24,9 +24,11 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.annotation.LayoutRes;
@@ -34,11 +36,14 @@
 import android.app.Fragment;
 import android.app.FragmentController;
 import android.app.FragmentHostCallback;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.IntentFilter;
 import android.hardware.display.DisplayManagerGlobal;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Looper;
+import android.os.UserHandle;
 import android.testing.AndroidTestingRunner;
 import android.testing.LeakCheck.Tracker;
 import android.testing.TestableLooper;
@@ -58,6 +63,7 @@
 import com.android.systemui.SysuiBaseFragmentTest;
 import com.android.systemui.SysuiTestableContext;
 import com.android.systemui.assist.AssistManager;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.model.SysUiState;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.recents.OverviewProxyService;
@@ -70,9 +76,11 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
 @RunWith(AndroidTestingRunner.class)
-@RunWithLooper()
+@RunWithLooper(setAsMainLooper = true)
 @SmallTest
 public class NavigationBarFragmentTest extends SysuiBaseFragmentTest {
     private static final int EXTERNAL_DISPLAY_ID = 2;
@@ -85,6 +93,8 @@
     private OverviewProxyService mOverviewProxyService;
     private CommandQueue mCommandQueue;
     private SysUiState mMockSysUiState;
+    @Mock
+    private BroadcastDispatcher mBroadcastDispatcher;
 
     private AccessibilityManagerWrapper mAccessibilityWrapper =
             new AccessibilityManagerWrapper(mContext) {
@@ -112,6 +122,8 @@
 
     @Before
     public void setupFragment() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
         setupSysuiDependency();
         createRootView();
         mOverviewProxyService =
@@ -177,6 +189,18 @@
     }
 
     @Test
+    public void testRegisteredWithDispatcher() {
+        mFragments.dispatchResume();
+        processAllMessages();
+
+        verify(mBroadcastDispatcher).registerReceiver(
+                any(BroadcastReceiver.class),
+                any(IntentFilter.class),
+                any(Handler.class),
+                any(UserHandle.class));
+    }
+
+    @Test
     public void testSetImeWindowStatusWhenImeSwitchOnDisplay() {
         // Create default & external NavBar fragment.
         NavigationBarFragment defaultNavBar = (NavigationBarFragment) mFragment;
@@ -193,7 +217,7 @@
         // Set IME window status for default NavBar.
         mCommandQueue.setImeWindowStatus(DEFAULT_DISPLAY, null, IME_VISIBLE,
                 BACK_DISPOSITION_DEFAULT, true, false);
-        Handler.getMain().runWithScissors(() -> { }, 500);
+        processAllMessages();
 
         // Verify IME window state will be updated in default NavBar & external NavBar state reset.
         assertEquals(NAVIGATION_HINT_BACK_ALT | NAVIGATION_HINT_IME_SHOWN,
@@ -204,7 +228,7 @@
         // Set IME window status for external NavBar.
         mCommandQueue.setImeWindowStatus(EXTERNAL_DISPLAY_ID, null,
                 IME_VISIBLE, BACK_DISPOSITION_DEFAULT, true, false);
-        Handler.getMain().runWithScissors(() -> { }, 500);
+        processAllMessages();
 
         // Verify IME window state will be updated in external NavBar & default NavBar state reset.
         assertEquals(NAVIGATION_HINT_BACK_ALT | NAVIGATION_HINT_IME_SHOWN,
@@ -227,7 +251,8 @@
                 mOverviewProxyService,
                 mock(NavigationModeController.class),
                 mock(StatusBarStateController.class),
-                mMockSysUiState);
+                mMockSysUiState,
+                mBroadcastDispatcher);
     }
 
     private class HostCallbacksForExternalDisplay extends
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java
index 219aef1..95e9e67 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationPanelViewTest.java
@@ -40,6 +40,8 @@
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.systemui.SystemUIFactory;
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.classifier.FalsingManagerFake;
+import com.android.systemui.doze.DozeLog;
 import com.android.systemui.plugins.FalsingManager;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.shared.plugins.PluginManager;
@@ -50,7 +52,11 @@
 import com.android.systemui.statusbar.StatusBarStateControllerImpl;
 import com.android.systemui.statusbar.SysuiStatusBarStateController;
 import com.android.systemui.statusbar.notification.DynamicPrivacyController;
+import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
 import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
+import com.android.systemui.statusbar.notification.collection.NotificationData;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.stack.NotificationRoundnessManager;
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
 import com.android.systemui.statusbar.policy.ConfigurationController;
@@ -120,8 +126,6 @@
         mDependency.injectTestDependency(StatusBarStateController.class,
                 mStatusBarStateController);
         mDependency.injectTestDependency(KeyguardUpdateMonitor.class, mUpdateMonitor);
-        mDependency.injectMockDependency(ShadeController.class);
-        mDependency.injectMockDependency(NotificationLockscreenUserManager.class);
         mDependency.injectMockDependency(ConfigurationController.class);
         mDependency.injectMockDependency(ZenModeController.class);
         NotificationWakeUpCoordinator coordinator =
@@ -129,9 +133,13 @@
                         mock(HeadsUpManagerPhone.class),
                         new StatusBarStateControllerImpl(),
                         mKeyguardBypassController);
-        PulseExpansionHandler expansionHandler = new PulseExpansionHandler(mContext, coordinator,
+        PulseExpansionHandler expansionHandler = new PulseExpansionHandler(
+                mContext,
+                coordinator,
                 mKeyguardBypassController, mHeadsUpManager,
-                mock(NotificationRoundnessManager.class), mStatusBarStateController);
+                mock(NotificationRoundnessManager.class),
+                mStatusBarStateController,
+                new FalsingManagerFake());
         mNotificationPanelView = new TestableNotificationPanelView(coordinator, expansionHandler,
                 mKeyguardBypassController);
         mNotificationPanelView.setHeadsUpManager(mHeadsUpManager);
@@ -211,12 +219,23 @@
         TestableNotificationPanelView(NotificationWakeUpCoordinator coordinator,
                 PulseExpansionHandler expansionHandler,
                 KeyguardBypassController bypassController) {
-            super(NotificationPanelViewTest.this.mContext, null,
+            super(
+                    NotificationPanelViewTest.this.mContext,
+                    null,
                     new InjectionInflationController(
                             SystemUIFactory.getInstance().getRootComponent()),
-                    coordinator, expansionHandler, mock(DynamicPrivacyController.class),
+                    coordinator,
+                    expansionHandler,
+                    mock(DynamicPrivacyController.class),
                     bypassController,
-                    mFalsingManager, mock(PluginManager.class));
+                    mFalsingManager,
+                    mock(PluginManager.class),
+                    mock(ShadeController.class),
+                    mock(NotificationLockscreenUserManager.class),
+                    new NotificationEntryManager(new NotificationData(mock(
+                            NotificationSectionsFeatureManager.class), mock(NotifLog.class)),
+                            mock(NotifLog.class)),
+                    mock(DozeLog.class));
             mNotificationStackScroller = mNotificationStackScrollLayout;
             mKeyguardStatusView = NotificationPanelViewTest.this.mKeyguardStatusView;
             mKeyguardStatusBar = NotificationPanelViewTest.this.mKeyguardStatusBar;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
index 2623b46..214e26a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
@@ -46,9 +46,10 @@
 import com.android.internal.colorextraction.ColorExtractor.GradientColors;
 import com.android.internal.util.function.TriConsumer;
 import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.systemui.DejankUtils;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.ScrimView;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.util.wakelock.WakeLock;
 import com.android.systemui.utils.os.FakeHandler;
 
@@ -95,6 +96,7 @@
         mDependency.injectMockDependency(KeyguardUpdateMonitor.class);
         when(mDozeParamenters.getAlwaysOn()).thenAnswer(invocation -> mAlwaysOnEnabled);
         when(mDozeParamenters.getDisplayNeedsBlanking()).thenReturn(true);
+        DejankUtils.setImmediate(true);
         mScrimController = new SynchronousScrimController(mScrimBehind, mScrimInFront,
                 mScrimForBubble,
                 (scrimState, scrimBehindAlpha, scrimInFrontColor) -> {
@@ -103,7 +105,7 @@
                     mScrimInFrontColor = scrimInFrontColor;
                 },
                 visible -> mScrimVisibility = visible, mDozeParamenters, mAlarmManager,
-                mock(KeyguardMonitor.class));
+                mock(KeyguardStateController.class));
         mScrimController.setHasBackdrop(false);
         mScrimController.setWallpaperSupportsAmbientMode(false);
         mScrimController.transitionTo(ScrimState.KEYGUARD);
@@ -113,6 +115,7 @@
     @After
     public void tearDown() {
         mScrimController.finishAnimationsImmediately();
+        DejankUtils.setImmediate(false);
     }
 
     @Test
@@ -243,7 +246,7 @@
     }
 
     @Test
-    public void transitionToPulsing() {
+    public void transitionToPulsing_withFrontAlphaUpdates() {
         // Pre-condition
         // Need to go to AoD first because PULSING doesn't change
         // the back scrim opacity - otherwise it would hide AoD wallpapers.
@@ -267,11 +270,22 @@
                 true /* behind */,
                 false /* bubble */);
 
+        // ... and when ambient goes dark, front scrim should be semi-transparent
+        mScrimController.setAodFrontScrimAlpha(0.5f);
+        mScrimController.finishAnimationsImmediately();
+        // Front scrim should be semi-transparent
+        assertScrimAlpha(SEMI_TRANSPARENT /* front */,
+                OPAQUE /* back */,
+                TRANSPARENT /* bubble */);
+
         mScrimController.setWakeLockScreenSensorActive(true);
         mScrimController.finishAnimationsImmediately();
-        assertScrimAlpha(TRANSPARENT /* front */,
+        assertScrimAlpha(SEMI_TRANSPARENT /* front */,
                 SEMI_TRANSPARENT /* back */,
                 TRANSPARENT /* bubble */);
+
+        // Reset value since enums are static.
+        mScrimController.setAodFrontScrimAlpha(0f);
     }
 
     @Test
@@ -422,6 +436,7 @@
                 TRANSPARENT /* behind */,
                 TRANSPARENT /* bubble */);
 
+        // Make sure at the very end of the animation, we're reset to transparent
         assertScrimTint(false /* front */,
                 false /* behind */,
                 false  /* bubble */);
@@ -790,9 +805,9 @@
                 ScrimView scrimForBubble,
                 TriConsumer<ScrimState, Float, GradientColors> scrimStateListener,
                 Consumer<Integer> scrimVisibleListener, DozeParameters dozeParameters,
-                AlarmManager alarmManager, KeyguardMonitor keyguardMonitor) {
+                AlarmManager alarmManager, KeyguardStateController keyguardStateController) {
             super(scrimBehind, scrimInFront, scrimForBubble, scrimStateListener,
-                    scrimVisibleListener, dozeParameters, alarmManager, keyguardMonitor);
+                    scrimVisibleListener, dozeParameters, alarmManager, keyguardStateController);
         }
 
         @Override
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
index 3c445c8..aafcdd0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java
@@ -46,6 +46,7 @@
 import com.android.systemui.plugins.FalsingManager;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.SysuiStatusBarStateController;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -65,6 +66,8 @@
     @Mock
     private KeyguardBouncer mBouncer;
     @Mock
+    private KeyguardStateController mKeyguardStateController;
+    @Mock
     private StatusBar mStatusBar;
     @Mock
     private ViewGroup mContainer;
@@ -90,6 +93,7 @@
         mDependency.injectMockDependency(StatusBarWindowController.class);
         mDependency.injectMockDependency(KeyguardUpdateMonitor.class);
         mDependency.injectTestDependency(StatusBarStateController.class, mStatusBarStateController);
+        mDependency.injectTestDependency(KeyguardStateController.class, mKeyguardStateController);
         when(mLockIconContainer.getParent()).thenReturn(mock(ViewGroup.class));
         when(mLockIconContainer.animate()).thenReturn(mock(ViewPropertyAnimator.class,
                 RETURNS_DEEP_STUBS));
@@ -169,7 +173,7 @@
 
     @Test
     public void onPanelExpansionChanged_showsBouncerWhenSwiping() {
-        when(mStatusBar.isKeyguardCurrentlySecure()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(false);
         mStatusBarKeyguardViewManager.onPanelExpansionChanged(0.5f /* expansion */,
                 true /* tracking */);
         verify(mBouncer).show(eq(false), eq(false));
@@ -223,6 +227,31 @@
         verify(mStatusBar, never()).animateKeyguardUnoccluding();
     }
 
+    @Test
+    public void testHiding_cancelsGoneRunnable() {
+        OnDismissAction action = mock(OnDismissAction.class);
+        Runnable cancelAction = mock(Runnable.class);
+        mStatusBarKeyguardViewManager.dismissWithAction(action, cancelAction,
+                true /* afterKeyguardGone */);
+
+        mStatusBarKeyguardViewManager.hideBouncer(true);
+        mStatusBarKeyguardViewManager.hide(0, 30);
+        verify(action, never()).onDismiss();
+        verify(cancelAction).run();
+    }
+
+    @Test
+    public void testHiding_doesntCancelWhenShowing() {
+        OnDismissAction action = mock(OnDismissAction.class);
+        Runnable cancelAction = mock(Runnable.class);
+        mStatusBarKeyguardViewManager.dismissWithAction(action, cancelAction,
+                true /* afterKeyguardGone */);
+
+        mStatusBarKeyguardViewManager.hide(0, 30);
+        verify(action).onDismiss();
+        verify(cancelAction, never()).run();
+    }
+
     private class TestableStatusBarKeyguardViewManager extends StatusBarKeyguardViewManager {
 
         public TestableStatusBarKeyguardViewManager(Context context,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
index 5a6f27d..266abcf 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
@@ -71,7 +71,7 @@
 import com.android.systemui.statusbar.notification.collection.NotificationData;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
 import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -104,7 +104,7 @@
     @Mock
     private ShadeController mShadeController;
     @Mock
-    private KeyguardMonitor mKeyguardMonitor;
+    private KeyguardStateController mKeyguardStateController;
     @Mock
     private Handler mHandler;
     @Mock
@@ -167,7 +167,8 @@
                 mock(StatusBarStateController.class), mock(KeyguardManager.class),
                 mock(IDreamManager.class), mRemoteInputManager,
                 mock(StatusBarRemoteInputCallback.class), mock(NotificationGroupManager.class),
-                mock(NotificationLockscreenUserManager.class), mShadeController, mKeyguardMonitor,
+                mock(NotificationLockscreenUserManager.class), mShadeController,
+                mKeyguardStateController,
                 mock(NotificationInterruptionStateProvider.class), mock(MetricsLogger.class),
                 mock(LockPatternUtils.class), mHandler, mHandler, mActivityIntentHelper,
                 mBubbleController);
@@ -200,7 +201,7 @@
         sbn.getNotification().contentIntent = mContentIntent;
         sbn.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
 
-        when(mKeyguardMonitor.isShowing()).thenReturn(true);
+        when(mKeyguardStateController.isShowing()).thenReturn(true);
         when(mShadeController.isOccluded()).thenReturn(true);
 
         // When
@@ -263,7 +264,7 @@
 
         // Given
         sbn.getNotification().contentIntent = null;
-        when(mKeyguardMonitor.isShowing()).thenReturn(true);
+        when(mKeyguardStateController.isShowing()).thenReturn(true);
         when(mShadeController.isOccluded()).thenReturn(true);
 
         // When
@@ -293,7 +294,7 @@
 
         // Given
         sbn.getNotification().contentIntent = mContentIntent;
-        when(mKeyguardMonitor.isShowing()).thenReturn(true);
+        when(mKeyguardStateController.isShowing()).thenReturn(true);
         when(mShadeController.isOccluded()).thenReturn(true);
 
         // When
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
index 4eb9a31..12e9be1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
@@ -41,7 +41,9 @@
 import android.app.Notification;
 import android.app.StatusBarManager;
 import android.app.trust.TrustManager;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.IntentFilter;
 import android.hardware.display.AmbientDisplayConfiguration;
 import android.hardware.fingerprint.FingerprintManager;
 import android.metrics.LogMaker;
@@ -51,17 +53,19 @@
 import android.os.Looper;
 import android.os.PowerManager;
 import android.os.RemoteException;
+import android.os.UserHandle;
 import android.service.dreams.IDreamManager;
 import android.support.test.metricshelper.MetricsAsserts;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
+import android.util.DisplayMetrics;
 import android.util.SparseArray;
 import android.view.ViewGroup.LayoutParams;
 
 import androidx.test.filters.SmallTest;
 
-import com.android.internal.logging.MetricsLogger;
+import com.android.internal.colorextraction.ColorExtractor;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.logging.testing.FakeMetricsLogger;
 import com.android.internal.statusbar.IStatusBarService;
@@ -70,18 +74,21 @@
 import com.android.systemui.ForegroundServiceController;
 import com.android.systemui.InitController;
 import com.android.systemui.R;
-import com.android.systemui.SystemUIFactory;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.UiOffloadThread;
 import com.android.systemui.appops.AppOpsController;
 import com.android.systemui.assist.AssistManager;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.bubbles.BubbleController;
+import com.android.systemui.classifier.FalsingManagerFake;
+import com.android.systemui.colorextraction.SysuiColorExtractor;
+import com.android.systemui.doze.DozeEvent;
 import com.android.systemui.doze.DozeHost;
 import com.android.systemui.doze.DozeLog;
 import com.android.systemui.keyguard.KeyguardViewMediator;
+import com.android.systemui.keyguard.ScreenLifecycle;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.plugins.ActivityStarter.OnDismissAction;
-import com.android.systemui.plugins.FalsingManager;
 import com.android.systemui.plugins.statusbar.StatusBarStateController;
 import com.android.systemui.statusbar.CommandQueue;
 import com.android.systemui.statusbar.KeyguardIndicationController;
@@ -92,26 +99,38 @@
 import com.android.systemui.statusbar.NotificationMediaManager;
 import com.android.systemui.statusbar.NotificationPresenter;
 import com.android.systemui.statusbar.NotificationRemoteInputManager;
-import com.android.systemui.statusbar.NotificationShelf;
 import com.android.systemui.statusbar.NotificationViewHierarchyManager;
+import com.android.systemui.statusbar.PulseExpansionHandler;
 import com.android.systemui.statusbar.RemoteInputController;
 import com.android.systemui.statusbar.StatusBarState;
 import com.android.systemui.statusbar.StatusBarStateControllerImpl;
+import com.android.systemui.statusbar.VibratorHelper;
+import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
+import com.android.systemui.statusbar.notification.DynamicPrivacyController;
+import com.android.systemui.statusbar.notification.NotifPipelineInitializer;
 import com.android.systemui.statusbar.notification.NotificationAlertingManager;
 import com.android.systemui.statusbar.notification.NotificationEntryListener;
 import com.android.systemui.statusbar.notification.NotificationEntryManager;
 import com.android.systemui.statusbar.notification.NotificationFilter;
 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
 import com.android.systemui.statusbar.notification.VisualStabilityManager;
 import com.android.systemui.statusbar.notification.collection.NotificationData;
 import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.logging.NotifLog;
 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
 import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
 import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
 import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
+import com.android.systemui.statusbar.policy.BatteryController;
+import com.android.systemui.statusbar.policy.ConfigurationController;
 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
+import com.android.systemui.statusbar.policy.NetworkController;
+import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler;
 import com.android.systemui.statusbar.policy.UserSwitcherController;
+import com.android.systemui.statusbar.policy.ZenModeController;
+import com.android.systemui.util.InjectionInflationController;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -128,10 +147,19 @@
 
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
-@RunWithLooper
+@RunWithLooper(setAsMainLooper = true)
 public class StatusBarTest extends SysuiTestCase {
+
+    private StatusBar mStatusBar;
+    private FakeMetricsLogger mMetricsLogger;
+    private PowerManager mPowerManager;
+    private TestableNotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+    private CommandQueue mCommandQueue;
+
+    @Mock private LightBarController mLightBarController;
+    @Mock private StatusBarIconController mStatusBarIconController;
     @Mock private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
-    @Mock private UnlockMethodCache mUnlockMethodCache;
+    @Mock private KeyguardStateController mKeyguardStateController;
     @Mock private KeyguardIndicationController mKeyguardIndicationController;
     @Mock private NotificationStackScrollLayout mStackScroller;
     @Mock private HeadsUpManagerPhone mHeadsUpManager;
@@ -143,11 +171,7 @@
     @Mock private ArrayList<NotificationEntry> mNotificationList;
     @Mock private BiometricUnlockController mBiometricUnlockController;
     @Mock private NotificationData mNotificationData;
-    @Mock
-    private NotificationInterruptionStateProvider.HeadsUpSuppressor mHeadsUpSuppressor;
-
-    // Mock dependencies:
-    @Mock private NotificationViewHierarchyManager mViewHierarchyManager;
+    @Mock private NotificationInterruptionStateProvider.HeadsUpSuppressor mHeadsUpSuppressor;
     @Mock private VisualStabilityManager mVisualStabilityManager;
     @Mock private NotificationListener mNotificationListener;
     @Mock private KeyguardViewMediator mKeyguardViewMediator;
@@ -155,51 +179,52 @@
     @Mock private NotificationRemoteInputManager mRemoteInputManager;
     @Mock private RemoteInputController mRemoteInputController;
     @Mock private StatusBarStateControllerImpl mStatusBarStateController;
+    @Mock private BatteryController mBatteryController;
     @Mock private DeviceProvisionedController mDeviceProvisionedController;
     @Mock private StatusBarNotificationPresenter mNotificationPresenter;
-    @Mock
-    private NotificationEntryListener mEntryListener;
-    @Mock
-    private NotificationFilter mNotificationFilter;
-    @Mock
-    private NotificationAlertingManager mNotificationAlertingManager;
-    @Mock
-    private NotificationLogger.ExpansionStateLogger mExpansionStateLogger;
-    @Mock
-    private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
-    @Mock
-    private AmbientDisplayConfiguration mAmbientDisplayConfiguration;
-    @Mock
-    private StatusBarWindowView mStatusBarWindowView;
-
-    private TestableStatusBar mStatusBar;
-    private FakeMetricsLogger mMetricsLogger;
-    private PowerManager mPowerManager;
-    private TestableNotificationEntryManager mEntryManager;
-    private TestableNotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
-    private NotificationLogger mNotificationLogger;
-    private CommandQueue mCommandQueue;
+    @Mock private NotificationEntryListener mEntryListener;
+    @Mock private NotificationFilter mNotificationFilter;
+    @Mock private NotificationAlertingManager mNotificationAlertingManager;
+    @Mock private NotificationLogger.ExpansionStateLogger mExpansionStateLogger;
+    @Mock private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
+    @Mock private AmbientDisplayConfiguration mAmbientDisplayConfiguration;
+    @Mock private StatusBarWindowView mStatusBarWindowView;
+    @Mock private BroadcastDispatcher mBroadcastDispatcher;
+    @Mock private AssistManager mAssistManager;
+    @Mock private NotificationGutsManager mNotificationGutsManager;
+    @Mock private NotificationMediaManager mNotificationMediaManager;
+    @Mock private ForegroundServiceController mForegroundServiceController;
+    @Mock private AppOpsController mAppOpsController;
+    @Mock private NavigationBarController mNavigationBarController;
+    @Mock private BypassHeadsUpNotifier mBypassHeadsUpNotifier;
+    @Mock private SysuiColorExtractor mColorExtractor;
+    @Mock private ColorExtractor.GradientColors mGradientColors;
+    @Mock private DozeLog mDozeLog;
+    @Mock private PulseExpansionHandler mPulseExpansionHandler;
+    @Mock private NotificationWakeUpCoordinator mNotificationWakeUpCoordinator;
+    @Mock private KeyguardBypassController mKeyguardBypassController;
+    @Mock private InjectionInflationController mInjectionInflationController;
+    @Mock private DynamicPrivacyController mDynamicPrivacyController;
+    @Mock private NotifPipelineInitializer mNotifPipelineInitializer;
+    @Mock private ZenModeController mZenModeController;
+    @Mock private AutoHideController mAutoHideController;
+    @Mock private NotificationViewHierarchyManager mNotificationViewHierarchyManager;
+    @Mock private UserSwitcherController mUserSwitcherController;
+    @Mock private NetworkController mNetworkController;
+    @Mock private VibratorHelper mVibratorHelper;
+    @Mock private BubbleController mBubbleController;
+    @Mock private NotificationGroupManager mGroupManager;
+    @Mock private NotificationGroupAlertTransferHelper mGroupAlertTransferHelper;
+    @Mock private StatusBarWindowController mStatusBarWindowController;
+    @Mock private NotificationIconAreaController mNotificationIconAreaController;
+    @Mock private StatusBarWindowViewController.Builder mStatusBarWindowViewControllerBuilder;
+    @Mock private StatusBarWindowViewController mStatusBarWindowViewController;
+    @Mock private NotifLog mNotifLog;
 
     @Before
     public void setup() throws Exception {
         MockitoAnnotations.initMocks(this);
-        mDependency.injectMockDependency(AssistManager.class);
-        mDependency.injectMockDependency(NotificationGutsManager.class);
-        mDependency.injectMockDependency(NotificationMediaManager.class);
-        mDependency.injectMockDependency(ForegroundServiceController.class);
-        mDependency.injectTestDependency(NotificationViewHierarchyManager.class,
-                mViewHierarchyManager);
-        mDependency.injectTestDependency(VisualStabilityManager.class, mVisualStabilityManager);
-        mDependency.injectTestDependency(NotificationListener.class, mNotificationListener);
-        mDependency.injectTestDependency(KeyguardMonitor.class, mock(KeyguardMonitor.class));
-        mDependency.injectTestDependency(AppOpsController.class, mock(AppOpsController.class));
-        mDependency.injectTestDependency(StatusBarStateController.class, mStatusBarStateController);
-        mDependency.injectTestDependency(DeviceProvisionedController.class,
-                mDeviceProvisionedController);
-        mDependency.injectMockDependency(BubbleController.class);
         mDependency.injectTestDependency(NotificationFilter.class, mNotificationFilter);
-        mDependency.injectTestDependency(NotificationAlertingManager.class,
-                mNotificationAlertingManager);
 
         IPowerManager powerManagerService = mock(IPowerManager.class);
         mPowerManager = new PowerManager(mContext, powerManagerService,
@@ -208,23 +233,18 @@
         mNotificationInterruptionStateProvider =
                 new TestableNotificationInterruptionStateProvider(mContext, mPowerManager,
                         mDreamManager, mAmbientDisplayConfiguration, mNotificationFilter,
-                        mStatusBarStateController);
-        mDependency.injectTestDependency(NotificationInterruptionStateProvider.class,
-                mNotificationInterruptionStateProvider);
-        mDependency.injectMockDependency(NavigationBarController.class);
+                        mStatusBarStateController, mBatteryController);
 
         mContext.addMockSystemService(TrustManager.class, mock(TrustManager.class));
         mContext.addMockSystemService(FingerprintManager.class, mock(FingerprintManager.class));
 
         mMetricsLogger = new FakeMetricsLogger();
-        mDependency.injectTestDependency(MetricsLogger.class, mMetricsLogger);
-        mEntryManager = new TestableNotificationEntryManager(mContext);
-        mNotificationLogger = new NotificationLogger(mNotificationListener,
-                Dependency.get(UiOffloadThread.class), mEntryManager, mStatusBarStateController,
+        TestableNotificationEntryManager entryManager = new TestableNotificationEntryManager(
+                mNotificationData);
+        NotificationLogger notificationLogger = new NotificationLogger(mNotificationListener,
+                Dependency.get(UiOffloadThread.class), entryManager, mStatusBarStateController,
                 mExpansionStateLogger);
-        mNotificationLogger.setVisibilityReporter(mock(Runnable.class));
-        mDependency.injectTestDependency(NotificationLogger.class, mNotificationLogger);
-        DozeLog.traceDozing(mContext, false /* dozing */);
+        notificationLogger.setVisibilityReporter(mock(Runnable.class));
 
         mCommandQueue = mock(CommandQueue.class);
         when(mCommandQueue.asBinder()).thenReturn(new Binder());
@@ -253,30 +273,100 @@
                 mHeadsUpManager, mHeadsUpSuppressor);
 
         when(mRemoteInputManager.getController()).thenReturn(mRemoteInputController);
-        mStatusBar = new TestableStatusBar(mStatusBarKeyguardViewManager, mUnlockMethodCache,
-                mKeyguardIndicationController, mStackScroller,
-                mPowerManager, mNotificationPanelView, mBarService, mNotificationListener,
-                mNotificationLogger, mVisualStabilityManager, mViewHierarchyManager,
-                mEntryManager, mScrimController, mBiometricUnlockController,
-                mKeyguardViewMediator, mRemoteInputManager, mock(NotificationGroupManager.class),
-                mock(NotificationGroupAlertTransferHelper.class), mock(FalsingManager.class),
-                mock(StatusBarWindowController.class), mock(NotificationIconAreaController.class),
-                mDozeScrimController, mock(NotificationShelf.class),
-                mLockscreenUserManager, mCommandQueue, mNotificationPresenter,
-                mock(BubbleController.class), mock(NavigationBarController.class),
-                mock(AutoHideController.class), mKeyguardUpdateMonitor, mStatusBarWindowView);
+
+        WakefulnessLifecycle wakefulnessLifecycle = new WakefulnessLifecycle();
+        wakefulnessLifecycle.dispatchStartedWakingUp();
+        wakefulnessLifecycle.dispatchFinishedWakingUp();
+
+        when(mGradientColors.supportsDarkText()).thenReturn(true);
+        when(mColorExtractor.getNeutralColors()).thenReturn(mGradientColors);
+        ConfigurationController configurationController = new ConfigurationControllerImpl(mContext);
+
+        when(mStatusBarWindowViewControllerBuilder.build())
+                .thenReturn(mStatusBarWindowViewController);
+
+        mStatusBar = new StatusBar(
+                mLightBarController,
+                mAutoHideController,
+                mKeyguardUpdateMonitor,
+                mStatusBarIconController,
+                mDozeLog,
+                mInjectionInflationController,
+                mPulseExpansionHandler,
+                mNotificationWakeUpCoordinator,
+                mKeyguardBypassController,
+                mKeyguardStateController,
+                mHeadsUpManager,
+                mDynamicPrivacyController,
+                mBypassHeadsUpNotifier,
+                true,
+                mNotifPipelineInitializer,
+                new FalsingManagerFake(),
+                mBroadcastDispatcher,
+                new RemoteInputQuickSettingsDisabler(
+                        mContext,
+                        configurationController
+                ),
+                mNotificationGutsManager,
+                notificationLogger,
+                entryManager,
+                mNotificationInterruptionStateProvider,
+                mNotificationViewHierarchyManager,
+                mForegroundServiceController,
+                mAppOpsController,
+                mKeyguardViewMediator,
+                mZenModeController,
+                mNotificationAlertingManager,
+                new DisplayMetrics(),
+                mMetricsLogger,
+                Dependency.get(UiOffloadThread.class),
+                mNotificationMediaManager,
+                mLockscreenUserManager,
+                mRemoteInputManager,
+                mUserSwitcherController,
+                mNetworkController,
+                mBatteryController,
+                mColorExtractor,
+                new ScreenLifecycle(),
+                wakefulnessLifecycle,
+                mStatusBarStateController,
+                mVibratorHelper,
+                mBubbleController,
+                mGroupManager,
+                mGroupAlertTransferHelper,
+                mVisualStabilityManager,
+                mDeviceProvisionedController,
+                mNavigationBarController,
+                mAssistManager,
+                mNotificationListener,
+                configurationController,
+                mStatusBarWindowController,
+                mStatusBarWindowViewControllerBuilder,
+                mNotifLog);
+        // TODO: we should be able to call mStatusBar.start() and have all the below values
+        // initialized automatically.
         mStatusBar.mContext = mContext;
         mStatusBar.mComponents = mContext.getComponents();
-        SystemUIFactory.getInstance().getRootComponent()
-                .getStatusBarInjector()
-                .createStatusBar(mStatusBar);
-        mStatusBar.setHeadsUpManager(mHeadsUpManager);
+        mStatusBar.mStatusBarKeyguardViewManager = mStatusBarKeyguardViewManager;
+        mStatusBar.mStatusBarWindow = mStatusBarWindowView;
+        mStatusBar.mBiometricUnlockController = mBiometricUnlockController;
+        mStatusBar.mScrimController = mScrimController;
+        mStatusBar.mNotificationPanel = mNotificationPanelView;
+        mStatusBar.mCommandQueue = mCommandQueue;
+        mStatusBar.mDozeScrimController = mDozeScrimController;
+        mStatusBar.mNotificationIconAreaController = mNotificationIconAreaController;
+        mStatusBar.mPresenter = mNotificationPresenter;
+        mStatusBar.mKeyguardIndicationController = mKeyguardIndicationController;
+        mStatusBar.mPowerManager = mPowerManager;
+        mStatusBar.mBarService = mBarService;
+        mStatusBar.mStackScroller = mStackScroller;
+        mStatusBar.mStatusBarWindowViewController = mStatusBarWindowViewController;
         mStatusBar.putComponent(StatusBar.class, mStatusBar);
         Dependency.get(InitController.class).executePostInitTasks();
-        mEntryManager.setUpForTest(mock(NotificationPresenter.class), mStackScroller,
-                mHeadsUpManager, mNotificationData);
-        mEntryManager.addNotificationEntryListener(mEntryListener);
-        mNotificationLogger.setUpWithContainer(mStackScroller);
+        entryManager.setUpForTest(mock(NotificationPresenter.class), mStackScroller,
+                mHeadsUpManager);
+        entryManager.addNotificationEntryListener(mEntryListener);
+        notificationLogger.setUpWithContainer(mStackScroller);
     }
 
     @Test
@@ -313,11 +403,11 @@
     public void lockscreenStateMetrics_notShowing() {
         // uninteresting state, except that fingerprint must be non-zero
         when(mStatusBarKeyguardViewManager.isOccluded()).thenReturn(false);
-        when(mUnlockMethodCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         // interesting state
         when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(false);
         when(mStatusBarKeyguardViewManager.isBouncerShowing()).thenReturn(false);
-        when(mUnlockMethodCache.isMethodSecure()).thenReturn(false);
+        when(mKeyguardStateController.isMethodSecure()).thenReturn(false);
         mStatusBar.onKeyguardViewManagerStatesUpdated();
 
         MetricsAsserts.assertHasLog("missing hidden insecure lockscreen log",
@@ -331,11 +421,11 @@
     public void lockscreenStateMetrics_notShowing_secure() {
         // uninteresting state, except that fingerprint must be non-zero
         when(mStatusBarKeyguardViewManager.isOccluded()).thenReturn(false);
-        when(mUnlockMethodCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         // interesting state
         when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(false);
         when(mStatusBarKeyguardViewManager.isBouncerShowing()).thenReturn(false);
-        when(mUnlockMethodCache.isMethodSecure()).thenReturn(true);
+        when(mKeyguardStateController.isMethodSecure()).thenReturn(true);
 
         mStatusBar.onKeyguardViewManagerStatesUpdated();
 
@@ -350,11 +440,11 @@
     public void lockscreenStateMetrics_isShowing() {
         // uninteresting state, except that fingerprint must be non-zero
         when(mStatusBarKeyguardViewManager.isOccluded()).thenReturn(false);
-        when(mUnlockMethodCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         // interesting state
         when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(true);
         when(mStatusBarKeyguardViewManager.isBouncerShowing()).thenReturn(false);
-        when(mUnlockMethodCache.isMethodSecure()).thenReturn(false);
+        when(mKeyguardStateController.isMethodSecure()).thenReturn(false);
 
         mStatusBar.onKeyguardViewManagerStatesUpdated();
 
@@ -369,11 +459,11 @@
     public void lockscreenStateMetrics_isShowing_secure() {
         // uninteresting state, except that fingerprint must be non-zero
         when(mStatusBarKeyguardViewManager.isOccluded()).thenReturn(false);
-        when(mUnlockMethodCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         // interesting state
         when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(true);
         when(mStatusBarKeyguardViewManager.isBouncerShowing()).thenReturn(false);
-        when(mUnlockMethodCache.isMethodSecure()).thenReturn(true);
+        when(mKeyguardStateController.isMethodSecure()).thenReturn(true);
 
         mStatusBar.onKeyguardViewManagerStatesUpdated();
 
@@ -388,11 +478,11 @@
     public void lockscreenStateMetrics_isShowingBouncer() {
         // uninteresting state, except that fingerprint must be non-zero
         when(mStatusBarKeyguardViewManager.isOccluded()).thenReturn(false);
-        when(mUnlockMethodCache.canSkipBouncer()).thenReturn(true);
+        when(mKeyguardStateController.canDismissLockScreen()).thenReturn(true);
         // interesting state
         when(mStatusBarKeyguardViewManager.isShowing()).thenReturn(true);
         when(mStatusBarKeyguardViewManager.isBouncerShowing()).thenReturn(true);
-        when(mUnlockMethodCache.isMethodSecure()).thenReturn(true);
+        when(mKeyguardStateController.isMethodSecure()).thenReturn(true);
 
         mStatusBar.onKeyguardViewManagerStatesUpdated();
 
@@ -599,8 +689,8 @@
     @Test
     @RunWithLooper(setAsMainLooper = true)
     public void testUpdateKeyguardState_DoesNotCrash() {
-        mStatusBar.mState = StatusBarState.KEYGUARD;
-        when(mStatusBar.mLockscreenUserManager.getCurrentProfiles()).thenReturn(
+        mStatusBar.setBarStateForTest(StatusBarState.KEYGUARD);
+        when(mLockscreenUserManager.getCurrentProfiles()).thenReturn(
                 new SparseArray<>());
         mStatusBar.onStateChanged(StatusBarState.SHADE);
     }
@@ -644,7 +734,7 @@
 
         // Starting a pulse should change the scrim controller to the pulsing state
         mStatusBar.mDozeServiceHost.pulseWhileDozing(mock(DozeHost.PulseCallback.class),
-                DozeLog.PULSE_REASON_NOTIFICATION);
+                DozeEvent.PULSE_REASON_NOTIFICATION);
         verify(mScrimController).transitionTo(eq(ScrimState.PULSING), any());
 
         // Ending a pulse should take it back to keyguard state
@@ -655,21 +745,21 @@
     @Test
     public void testPulseWhileDozing_notifyAuthInterrupt() {
         HashSet<Integer> reasonsWantingAuth = new HashSet<>(
-                Collections.singletonList(DozeLog.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN));
+                Collections.singletonList(DozeEvent.PULSE_REASON_SENSOR_WAKE_LOCK_SCREEN));
         HashSet<Integer> reasonsSkippingAuth = new HashSet<>(
-                Arrays.asList(DozeLog.PULSE_REASON_INTENT,
-                        DozeLog.PULSE_REASON_NOTIFICATION,
-                        DozeLog.PULSE_REASON_SENSOR_SIGMOTION,
-                        DozeLog.REASON_SENSOR_PICKUP,
-                        DozeLog.REASON_SENSOR_DOUBLE_TAP,
-                        DozeLog.PULSE_REASON_SENSOR_LONG_PRESS,
-                        DozeLog.PULSE_REASON_DOCKING,
-                        DozeLog.REASON_SENSOR_WAKE_UP,
-                        DozeLog.REASON_SENSOR_TAP));
+                Arrays.asList(DozeEvent.PULSE_REASON_INTENT,
+                        DozeEvent.PULSE_REASON_NOTIFICATION,
+                        DozeEvent.PULSE_REASON_SENSOR_SIGMOTION,
+                        DozeEvent.REASON_SENSOR_PICKUP,
+                        DozeEvent.REASON_SENSOR_DOUBLE_TAP,
+                        DozeEvent.PULSE_REASON_SENSOR_LONG_PRESS,
+                        DozeEvent.PULSE_REASON_DOCKING,
+                        DozeEvent.REASON_SENSOR_WAKE_UP,
+                        DozeEvent.REASON_SENSOR_TAP));
         HashSet<Integer> reasonsThatDontPulse = new HashSet<>(
-                Arrays.asList(DozeLog.REASON_SENSOR_PICKUP,
-                        DozeLog.REASON_SENSOR_DOUBLE_TAP,
-                        DozeLog.REASON_SENSOR_TAP));
+                Arrays.asList(DozeEvent.REASON_SENSOR_PICKUP,
+                        DozeEvent.REASON_SENSOR_DOUBLE_TAP,
+                        DozeEvent.REASON_SENSOR_TAP));
 
         doAnswer(invocation -> {
             DozeHost.PulseCallback callback = invocation.getArgument(0);
@@ -678,7 +768,7 @@
         }).when(mDozeScrimController).pulse(any(), anyInt());
 
         mStatusBar.mDozeServiceHost.mWakeLockScreenPerformsAuth = true;
-        for (int i = 0; i < DozeLog.REASONS; i++) {
+        for (int i = 0; i < DozeEvent.TOTAL_REASONS; i++) {
             reset(mKeyguardUpdateMonitor);
             mStatusBar.mDozeServiceHost.pulseWhileDozing(mock(DozeHost.PulseCallback.class), i);
             if (reasonsWantingAuth.contains(i)) {
@@ -703,12 +793,12 @@
 
         // Starting a pulse while docking should suppress wakeup gesture
         mStatusBar.mDozeServiceHost.pulseWhileDozing(mock(DozeHost.PulseCallback.class),
-                DozeLog.PULSE_REASON_DOCKING);
-        verify(mStatusBarWindowView).suppressWakeUpGesture(eq(true));
+                DozeEvent.PULSE_REASON_DOCKING);
+        verify(mStatusBarWindowViewController).suppressWakeUpGesture(eq(true));
 
         // Ending a pulse should restore wakeup gesture
         pulseCallback[0].onPulseFinished();
-        verify(mStatusBarWindowView).suppressWakeUpGesture(eq(false));
+        verify(mStatusBarWindowViewController).suppressWakeUpGesture(eq(false));
     }
 
     @Test
@@ -731,8 +821,7 @@
         verify(mStatusBarStateController).setState(eq(StatusBarState.KEYGUARD));
 
         // If useFullscreenUserSwitcher is true, state is set to FULLSCREEN_USER_SWITCHER.
-        mStatusBar.mUserSwitcherController = mock(UserSwitcherController.class);
-        when(mStatusBar.mUserSwitcherController.useFullscreenUserSwitcher()).thenReturn(true);
+        when(mUserSwitcherController.useFullscreenUserSwitcher()).thenReturn(true);
         mStatusBar.showKeyguardImpl();
         verify(mStatusBarStateController).setState(eq(StatusBarState.FULLSCREEN_USER_SWITCHER));
     }
@@ -774,123 +863,42 @@
         verify(mNotificationPanelView, never()).expand(anyBoolean());
     }
 
-    static class TestableStatusBar extends StatusBar {
-        public TestableStatusBar(StatusBarKeyguardViewManager man,
-                UnlockMethodCache unlock, KeyguardIndicationController key,
-                NotificationStackScrollLayout stack,
-                PowerManager pm, NotificationPanelView panelView,
-                IStatusBarService barService, NotificationListener notificationListener,
-                NotificationLogger notificationLogger,
-                VisualStabilityManager visualStabilityManager,
-                NotificationViewHierarchyManager viewHierarchyManager,
-                TestableNotificationEntryManager entryManager, ScrimController scrimController,
-                BiometricUnlockController biometricUnlockController,
-                KeyguardViewMediator keyguardViewMediator,
-                NotificationRemoteInputManager notificationRemoteInputManager,
-                NotificationGroupManager notificationGroupManager,
-                NotificationGroupAlertTransferHelper notificationGroupAlertTransferHelper,
-                FalsingManager falsingManager,
-                StatusBarWindowController statusBarWindowController,
-                NotificationIconAreaController notificationIconAreaController,
-                DozeScrimController dozeScrimController,
-                NotificationShelf notificationShelf,
-                NotificationLockscreenUserManager notificationLockscreenUserManager,
-                CommandQueue commandQueue,
-                StatusBarNotificationPresenter notificationPresenter,
-                BubbleController bubbleController,
-                NavigationBarController navBarController,
-                AutoHideController autoHideController,
-                KeyguardUpdateMonitor keyguardUpdateMonitor,
-                StatusBarWindowView statusBarWindow) {
-            mStatusBarKeyguardViewManager = man;
-            mUnlockMethodCache = unlock;
-            mKeyguardIndicationController = key;
-            mStackScroller = stack;
-            mPowerManager = pm;
-            mNotificationPanel = panelView;
-            mBarService = barService;
-            mNotificationListener = notificationListener;
-            mNotificationLogger = notificationLogger;
-            mWakefulnessLifecycle = createAwakeWakefulnessLifecycle();
-            mVisualStabilityManager = visualStabilityManager;
-            mViewHierarchyManager = viewHierarchyManager;
-            mEntryManager = entryManager;
-            mScrimController = scrimController;
-            mBiometricUnlockController = biometricUnlockController;
-            mKeyguardViewMediator = keyguardViewMediator;
-            mRemoteInputManager = notificationRemoteInputManager;
-            mGroupManager = notificationGroupManager;
-            mGroupAlertTransferHelper = notificationGroupAlertTransferHelper;
-            mFalsingManager = falsingManager;
-            mStatusBarWindowController = statusBarWindowController;
-            mNotificationIconAreaController = notificationIconAreaController;
-            mDozeScrimController = dozeScrimController;
-            mNotificationShelf = notificationShelf;
-            mLockscreenUserManager = notificationLockscreenUserManager;
-            mCommandQueue = commandQueue;
-            mPresenter = notificationPresenter;
-            mGestureWakeLock = mock(PowerManager.WakeLock.class);
-            mBubbleController = bubbleController;
-            mNavigationBarController = navBarController;
-            mAutoHideController = autoHideController;
-            mKeyguardUpdateMonitor = keyguardUpdateMonitor;
-            mStatusBarWindow = statusBarWindow;
-            mDozeServiceHost.mWakeLockScreenPerformsAuth = false;
-        }
-
-        private WakefulnessLifecycle createAwakeWakefulnessLifecycle() {
-            WakefulnessLifecycle wakefulnessLifecycle = new WakefulnessLifecycle();
-            wakefulnessLifecycle.dispatchStartedWakingUp();
-            wakefulnessLifecycle.dispatchFinishedWakingUp();
-            return wakefulnessLifecycle;
-        }
-
-        @Override
-        protected void updateTheme() {
-            // Do nothing for now, until we have more mocking and StatusBar is smaller.
-        }
-
-        public void setBarStateForTest(int state) {
-            mState = state;
-        }
-
-        void setHeadsUpManager(HeadsUpManagerPhone headsUpManager) {
-            mHeadsUpManager = headsUpManager;
-        }
-
-        public void setUserSetupForTest(boolean userSetup) {
-            mUserSetup = userSetup;
-        }
-
+    @Test
+    public void testRegisterBroadcastsonDispatcher() {
+        mStatusBar.registerBroadcastReceiver();
+        verify(mBroadcastDispatcher).registerReceiver(
+                any(BroadcastReceiver.class),
+                any(IntentFilter.class),
+                eq(null),
+                any(UserHandle.class));
     }
 
     public static class TestableNotificationEntryManager extends NotificationEntryManager {
 
-        public TestableNotificationEntryManager(Context context) {
-            super(context);
+        public TestableNotificationEntryManager(NotificationData notificationData) {
+            super(notificationData, mock(NotifLog.class));
         }
 
         public void setUpForTest(NotificationPresenter presenter,
                 NotificationListContainer listContainer,
-                HeadsUpManagerPhone headsUpManager,
-                NotificationData notificationData) {
+                HeadsUpManagerPhone headsUpManager) {
             super.setUpWithPresenter(presenter, listContainer, headsUpManager);
-            mNotificationData = notificationData;
         }
     }
 
     public static class TestableNotificationInterruptionStateProvider extends
             NotificationInterruptionStateProvider {
 
-        public TestableNotificationInterruptionStateProvider(
+        TestableNotificationInterruptionStateProvider(
                 Context context,
                 PowerManager powerManager,
                 IDreamManager dreamManager,
                 AmbientDisplayConfiguration ambientDisplayConfiguration,
                 NotificationFilter filter,
-                StatusBarStateController controller) {
+                StatusBarStateController controller,
+                BatteryController batteryController) {
             super(context, powerManager, dreamManager, ambientDisplayConfiguration, filter,
-                    controller);
+                    batteryController, controller);
             mUseHeadsUp = true;
         }
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
index 00d87c3..9f4dfb4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java
@@ -16,55 +16,89 @@
 
 package com.android.systemui.statusbar.phone;
 
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.os.SystemClock;
+import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper;
 import android.view.MotionEvent;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
-import com.android.systemui.Dependency;
+import com.android.systemui.SystemUIFactory;
 import com.android.systemui.SysuiTestCase;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.classifier.FalsingManagerFake;
+import com.android.systemui.doze.DozeLog;
+import com.android.systemui.shared.plugins.PluginManager;
 import com.android.systemui.statusbar.DragDownHelper;
-import com.android.systemui.statusbar.StatusBarState;
-import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
+import com.android.systemui.statusbar.PulseExpansionHandler;
+import com.android.systemui.statusbar.notification.DynamicPrivacyController;
+import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
+import com.android.systemui.tuner.TunerService;
+import com.android.systemui.util.InjectionInflationController;
 
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
-@RunWith(AndroidJUnit4.class)
-@TestableLooper.RunWithLooper
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
 @SmallTest
 public class StatusBarWindowViewTest extends SysuiTestCase {
 
     private StatusBarWindowView mView;
-    private StatusBar mStatusBar;
-    private DragDownHelper mDragDownHelper;
-    private NotificationStackScrollLayout mStackScrollLayout;
+    private StatusBarWindowViewController mController;
+
+    @Mock private NotificationWakeUpCoordinator mCoordinator;
+    @Mock private PulseExpansionHandler mPulseExpansionHandler;
+    @Mock private DynamicPrivacyController mDynamicPrivacyController;
+    @Mock private KeyguardBypassController mBypassController;
+    @Mock private PluginManager mPluginManager;
+    @Mock private TunerService mTunerService;
+    @Mock private DragDownHelper mDragDownHelper;
+    @Mock private ShadeController mShadeController;
+    @Mock private NotificationLockscreenUserManager mNotificationLockScreenUserManager;
+    @Mock private NotificationEntryManager mNotificationEntryManager;
+    @Mock private StatusBar mStatusBar;
+    @Mock private DozeLog mDozeLog;
 
     @Before
     public void setUp() {
-        mDependency.injectMockDependency(StatusBarStateController.class);
-        mView = spy(new StatusBarWindowView(getContext(), null));
-        mStackScrollLayout = mock(NotificationStackScrollLayout.class);
-        when(mView.getStackScrollLayout()).thenReturn(mStackScrollLayout);
-        mStatusBar = mock(StatusBar.class);
-        mView.setService(mStatusBar);
-        mDragDownHelper = mock(DragDownHelper.class);
-        mView.setDragDownHelper(mDragDownHelper);
+        MockitoAnnotations.initMocks(this);
+
+        mView = new StatusBarWindowView(getContext(), null);
+        mContext.putComponent(StatusBar.class, mStatusBar);
+        when(mStatusBar.isDozing()).thenReturn(false);
+        mDependency.injectTestDependency(ShadeController.class, mShadeController);
+
+        mController = new StatusBarWindowViewController.Builder(
+                new InjectionInflationController(
+                        SystemUIFactory.getInstance().getRootComponent()),
+                mCoordinator,
+                mPulseExpansionHandler,
+                mDynamicPrivacyController,
+                mBypassController,
+                new FalsingManagerFake(),
+                mPluginManager,
+                mTunerService,
+                mNotificationLockScreenUserManager,
+                mNotificationEntryManager,
+                mDozeLog)
+                .setShadeController(mShadeController)
+                .setStatusBarWindowView(mView)
+                .build();
+        mController.setService(mStatusBar);
+        mController.setDragDownHelper(mDragDownHelper);
+
     }
 
     @Test
-    public void testDragDownHelperCalledWhenDraggingDown() throws Exception {
-        when(Dependency.get(StatusBarStateController.class).getState())
-                .thenReturn(StatusBarState.SHADE);
+    public void testDragDownHelperCalledWhenDraggingDown() {
         when(mDragDownHelper.isDraggingDown()).thenReturn(true);
         long now = SystemClock.elapsedRealtime();
         MotionEvent ev = MotionEvent.obtain(now, now, MotionEvent.ACTION_UP, 0 /* x */, 0 /* y */,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java
index a9a1392..589aa03 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/SystemUIDialogTest.java
@@ -18,11 +18,9 @@
 
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 
 import android.content.BroadcastReceiver;
-import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.testing.AndroidTestingRunner;
@@ -31,11 +29,14 @@
 import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
 @RunWith(AndroidTestingRunner.class)
 @RunWithLooper
@@ -43,13 +44,16 @@
 public class SystemUIDialogTest extends SysuiTestCase {
 
     private SystemUIDialog mDialog;
-
-    Context mContextSpy;
+    @Mock
+    private BroadcastDispatcher mBroadcastDispatcher;
 
     @Before
     public void setup() {
-        mContextSpy = spy(mContext);
-        mDialog = new SystemUIDialog(mContextSpy);
+        MockitoAnnotations.initMocks(this);
+
+        mDependency.injectTestDependency(BroadcastDispatcher.class, mBroadcastDispatcher);
+
+        mDialog = new SystemUIDialog(mContext);
     }
 
     @Test
@@ -60,12 +64,12 @@
                 ArgumentCaptor.forClass(IntentFilter.class);
 
         mDialog.show();
-        verify(mContextSpy).registerReceiverAsUser(broadcastReceiverCaptor.capture(), any(),
-                intentFilterCaptor.capture(), any(), any());
+        verify(mBroadcastDispatcher).registerReceiver(broadcastReceiverCaptor.capture(),
+                intentFilterCaptor.capture(), eq(null), any());
 
         assertTrue(intentFilterCaptor.getValue().hasAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
 
         mDialog.dismiss();
-        verify(mContextSpy).unregisterReceiver(eq(broadcastReceiverCaptor.getValue()));
+        verify(mBroadcastDispatcher).unregisterReceiver(eq(broadcastReceiverCaptor.getValue()));
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/sensors/FakeProximitySensor.java b/packages/SystemUI/tests/src/com/android/systemui/util/sensors/FakeProximitySensor.java
new file mode 100644
index 0000000..d7df96d
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/sensors/FakeProximitySensor.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2019 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.util.sensors;
+
+import android.content.Context;
+
+public class FakeProximitySensor extends ProximitySensor {
+    private boolean mAvailable;
+    private boolean mPaused;
+
+    public FakeProximitySensor(Context context, AsyncSensorManager sensorManager) {
+        super(context, sensorManager);
+
+        mAvailable = true;
+    }
+
+    public void setSensorAvailable(boolean available) {
+        mAvailable = available;
+    }
+
+    public void setLastEvent(ProximityEvent event) {
+        mLastEvent = event;
+    }
+
+    @Override
+    public boolean getSensorAvailable() {
+        return mAvailable;
+    }
+
+    @Override
+    protected void registerInternal() {
+        // no-op
+    }
+
+    @Override
+    protected void unregisterInternal() {
+        // no-op
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java
index 6d13408..fa943e3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java
@@ -47,7 +47,7 @@
         AsyncSensorManager asyncSensorManager = new AsyncSensorManager(
                 sensorManager, null, new Handler());
         mFakeProximitySensor = sensorManager.getFakeProximitySensor();
-        mProximitySensor = new ProximitySensor(getContext(), asyncSensorManager, null);
+        mProximitySensor = new ProximitySensor(getContext(), asyncSensorManager);
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBatteryController.java b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBatteryController.java
index a843cca..df76f01 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBatteryController.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeBatteryController.java
@@ -48,4 +48,9 @@
     public boolean isPowerSave() {
         return false;
     }
+
+    @Override
+    public boolean isAodPowerSave() {
+        return false;
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeKeyguardMonitor.java b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeKeyguardMonitor.java
deleted file mode 100644
index 2fb0e0e..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeKeyguardMonitor.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2016 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.utils.leaks;
-
-import android.testing.LeakCheck;
-
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
-
-public class FakeKeyguardMonitor implements KeyguardMonitor {
-
-    private final BaseLeakChecker<Callback> mCallbackController;
-
-    public FakeKeyguardMonitor(LeakCheck test) {
-        mCallbackController = new BaseLeakChecker<Callback>(test, "keyguard");
-    }
-
-    @Override
-    public void addCallback(Callback callback) {
-        mCallbackController.addCallback(callback);
-    }
-
-    @Override
-    public void removeCallback(Callback callback) {
-        mCallbackController.removeCallback(callback);
-    }
-
-    @Override
-    public boolean isSecure() {
-        return false;
-    }
-
-    @Override
-    public boolean isShowing() {
-        return false;
-    }
-
-    @Override
-    public boolean isOccluded() {
-        return false;
-    }
-
-    @Override
-    public boolean isKeyguardFadingAway() {
-        return false;
-    }
-
-    @Override
-    public boolean isKeyguardGoingAway() {
-        return false;
-    }
-
-    @Override
-    public boolean isLaunchTransitionFadingAway() {
-        return false;
-    }
-
-    @Override
-    public long getKeyguardFadingAwayDuration() {
-        return 0;
-    }
-
-    @Override
-    public long getKeyguardFadingAwayDelay() {
-        return 0;
-    }
-
-    @Override
-    public long calculateGoingToFullShadeDelay() {
-        return 0;
-    }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeKeyguardStateController.java b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeKeyguardStateController.java
new file mode 100644
index 0000000..26cac29
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakeKeyguardStateController.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2016 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.utils.leaks;
+
+import android.testing.LeakCheck;
+
+import com.android.systemui.statusbar.policy.KeyguardStateController;
+
+public class FakeKeyguardStateController implements KeyguardStateController {
+
+    private final BaseLeakChecker<Callback> mCallbackController;
+
+    public FakeKeyguardStateController(LeakCheck test) {
+        mCallbackController = new BaseLeakChecker<Callback>(test, "keyguard");
+    }
+
+    @Override
+    public void addCallback(Callback callback) {
+        mCallbackController.addCallback(callback);
+    }
+
+    @Override
+    public void removeCallback(Callback callback) {
+        mCallbackController.removeCallback(callback);
+    }
+
+    @Override
+    public boolean isMethodSecure() {
+        return false;
+    }
+
+    @Override
+    public boolean isShowing() {
+        return false;
+    }
+
+    @Override
+    public boolean canDismissLockScreen() {
+        return false;
+    }
+
+    @Override
+    public boolean isOccluded() {
+        return false;
+    }
+
+    @Override
+    public boolean isTrusted() {
+        return false;
+    }
+
+    @Override
+    public boolean isKeyguardFadingAway() {
+        return false;
+    }
+
+    @Override
+    public boolean isKeyguardGoingAway() {
+        return false;
+    }
+
+    @Override
+    public boolean isLaunchTransitionFadingAway() {
+        return false;
+    }
+
+    @Override
+    public long getKeyguardFadingAwayDuration() {
+        return 0;
+    }
+
+    @Override
+    public long getKeyguardFadingAwayDelay() {
+        return 0;
+    }
+
+    @Override
+    public long calculateGoingToFullShadeDelay() {
+        return 0;
+    }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/LeakCheckedTest.java b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/LeakCheckedTest.java
index f479126..fedc08d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/LeakCheckedTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/LeakCheckedTest.java
@@ -14,8 +14,6 @@
 
 package com.android.systemui.utils.leaks;
 
-import static org.mockito.Matchers.any;
-
 import android.testing.LeakCheck;
 import android.util.ArrayMap;
 
@@ -29,7 +27,7 @@
 import com.android.systemui.statusbar.policy.ConfigurationController;
 import com.android.systemui.statusbar.policy.FlashlightController;
 import com.android.systemui.statusbar.policy.HotspotController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
+import com.android.systemui.statusbar.policy.KeyguardStateController;
 import com.android.systemui.statusbar.policy.LocationController;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.statusbar.policy.NextAlarmController;
@@ -60,7 +58,7 @@
             HotspotController.class,
             FlashlightController.class,
             UserInfoController.class,
-            KeyguardMonitor.class,
+            KeyguardStateController.class,
             BatteryController.class,
             SecurityController.class,
             ManagedProfileController.class,
@@ -118,8 +116,8 @@
                     obj = new FakeFlashlightController(this);
                 } else if (cls == UserInfoController.class) {
                     obj = new FakeUserInfoController(this);
-                } else if (cls == KeyguardMonitor.class) {
-                    obj = new FakeKeyguardMonitor(this);
+                } else if (cls == KeyguardStateController.class) {
+                    obj = new FakeKeyguardStateController(this);
                 } else if (cls == BatteryController.class) {
                     obj = new FakeBatteryController(this);
                 } else if (cls == SecurityController.class) {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
index f4d0854..2e945f2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogControllerImplTest.java
@@ -16,41 +16,64 @@
 
 package com.android.systemui.volume;
 
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.IntentFilter;
 import android.media.AudioManager;
 import android.media.session.MediaSession;
+import android.os.Handler;
+import android.testing.AndroidTestingRunner;
 
 import androidx.test.filters.SmallTest;
 
 import com.android.systemui.SysuiTestCase;
+import com.android.systemui.broadcast.BroadcastDispatcher;
 import com.android.systemui.keyguard.WakefulnessLifecycle;
 import com.android.systemui.statusbar.phone.StatusBar;
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
+@RunWith(AndroidTestingRunner.class)
 @SmallTest
 public class VolumeDialogControllerImplTest extends SysuiTestCase {
 
     TestableVolumeDialogControllerImpl mVolumeController;
     VolumeDialogControllerImpl.C mCallback;
     StatusBar mStatusBar;
+    @Mock
+    private BroadcastDispatcher mBroadcastDispatcher;
 
     @Before
     public void setup() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
         mCallback = mock(VolumeDialogControllerImpl.C.class);
         mStatusBar = mock(StatusBar.class);
-        mVolumeController = new TestableVolumeDialogControllerImpl(mContext, mCallback, mStatusBar);
+        mVolumeController = new TestableVolumeDialogControllerImpl(mContext, mCallback, mStatusBar,
+                mBroadcastDispatcher);
         mVolumeController.setEnableDialogs(true, true);
     }
 
     @Test
+    public void testRegisteredWithDispatcher() {
+        verify(mBroadcastDispatcher).registerReceiver(
+                any(BroadcastReceiver.class),
+                any(IntentFilter.class),
+                any(Handler.class)); // VolumeDialogControllerImpl does not call with user
+    }
+
+    @Test
     public void testVolumeChangeW_deviceNotInteractiveAOD() {
         when(mStatusBar.isDeviceInteractive()).thenReturn(false);
         when(mStatusBar.getWakefulnessState()).thenReturn(WakefulnessLifecycle.WAKEFULNESS_AWAKE);
@@ -81,7 +104,7 @@
     public void testVolumeChangeW_nullStatusBar() {
         VolumeDialogControllerImpl.C callback = mock(VolumeDialogControllerImpl.C.class);
         TestableVolumeDialogControllerImpl nullStatusBarTestableDialog =  new
-                TestableVolumeDialogControllerImpl(mContext, callback, null);
+                TestableVolumeDialogControllerImpl(mContext, callback, null, mBroadcastDispatcher);
         nullStatusBarTestableDialog.setEnableDialogs(true, true);
         nullStatusBarTestableDialog.onVolumeChangedW(0, AudioManager.FLAG_SHOW_UI);
         verify(callback, times(1)).onShowRequested(Events.SHOW_REASON_VOLUME_CHANGED);
@@ -100,8 +123,9 @@
     }
 
     static class TestableVolumeDialogControllerImpl extends VolumeDialogControllerImpl {
-        public TestableVolumeDialogControllerImpl(Context context, C callback, StatusBar s) {
-            super(context);
+        TestableVolumeDialogControllerImpl(Context context, C callback, StatusBar s,
+                BroadcastDispatcher broadcastDispatcher) {
+            super(context, broadcastDispatcher);
             mCallbacks = callback;
             mStatusBar = s;
         }
diff --git a/proto/src/system_messages.proto b/proto/src/system_messages.proto
index ffbf1ae..5d6d1c9 100644
--- a/proto/src/system_messages.proto
+++ b/proto/src/system_messages.proto
@@ -230,6 +230,10 @@
     // Package: android
     NOTE_TEST_HARNESS_MODE_ENABLED = 54;
 
+    // Inform the user that Serial Console is active.
+    // Package: android
+    NOTE_SERIAL_CONSOLE_ENABLED = 55;
+
     // ADD_NEW_IDS_ABOVE_THIS_LINE
     // Legacy IDs with arbitrary values appear below
     // Legacy IDs existed as stable non-conflicting constants prior to the O release
diff --git a/services/Android.bp b/services/Android.bp
index 6953e86..60dd895 100644
--- a/services/Android.bp
+++ b/services/Android.bp
@@ -47,6 +47,11 @@
         "compat-changeid-annotation-processor",
     ],
 
+    required: [
+      // Required by services.backup
+      "BackupEncryption",
+    ],
+
     // Uncomment to enable output of certain warnings (deprecated, unchecked)
     //javacflags: ["-Xlint"],
 
diff --git a/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java b/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java
index 4f021ad..514eb77 100644
--- a/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java
+++ b/services/accessibility/java/com/android/server/accessibility/AbstractAccessibilityServiceConnection.java
@@ -350,9 +350,9 @@
 
     protected abstract boolean hasRightsToCurrentUserLocked();
 
+    @Nullable
     @Override
-    public List<AccessibilityWindowInfo> getWindows() {
-        ensureWindowsAvailableTimed(Display.DEFAULT_DISPLAY);
+    public AccessibilityWindowInfo.WindowListSparseArray getWindows() {
         synchronized (mLock) {
             if (!hasRightsToCurrentUserLocked()) {
                 return null;
@@ -362,38 +362,39 @@
             if (!permissionGranted) {
                 return null;
             }
-            List<AccessibilityWindowInfo> internalWindowList =
-                    mA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY);
-            if (internalWindowList == null) {
-                return null;
-            }
             if (!mSecurityPolicy.checkAccessibilityAccess(this)) {
                 return null;
             }
-            List<AccessibilityWindowInfo> returnedWindowList = new ArrayList<>();
-            final int windowCount = internalWindowList.size();
-            for (int i = 0; i < windowCount; i++) {
-                AccessibilityWindowInfo window = internalWindowList.get(i);
-                AccessibilityWindowInfo windowClone =
-                        AccessibilityWindowInfo.obtain(window);
-                windowClone.setConnectionId(mId);
-                returnedWindowList.add(windowClone);
+            final AccessibilityWindowInfo.WindowListSparseArray allWindows =
+                    new AccessibilityWindowInfo.WindowListSparseArray();
+            final ArrayList<Integer> displayList = mA11yWindowManager.getDisplayListLocked();
+            final int displayListCounts = displayList.size();
+            if (displayListCounts > 0) {
+                for (int i = 0; i < displayListCounts; i++) {
+                    final int displayId = displayList.get(i);
+                    ensureWindowsAvailableTimedLocked(displayId);
+
+                    final List<AccessibilityWindowInfo> windowList = getWindowsByDisplayLocked(
+                            displayId);
+                    if (windowList != null) {
+                        allWindows.put(displayId, windowList);
+                    }
+                }
             }
-            return returnedWindowList;
+            return allWindows;
         }
     }
 
     @Override
     public AccessibilityWindowInfo getWindow(int windowId) {
-        int displayId = Display.INVALID_DISPLAY;
         synchronized (mLock) {
+            int displayId = Display.INVALID_DISPLAY;
             if (windowId != AccessibilityWindowInfo.UNDEFINED_WINDOW_ID) {
                 displayId = mA11yWindowManager.getDisplayIdByUserIdAndWindowIdLocked(
                         mSystemSupport.getCurrentUserIdLocked(), windowId);
             }
-        }
-        ensureWindowsAvailableTimed(displayId);
-        synchronized (mLock) {
+            ensureWindowsAvailableTimedLocked(displayId);
+
             if (!hasRightsToCurrentUserLocked()) {
                 return null;
             }
@@ -1316,35 +1317,33 @@
      *
      * @param displayId The logical display id.
      */
-    private void ensureWindowsAvailableTimed(int displayId) {
-        synchronized (mLock) {
-            if (mA11yWindowManager.getWindowListLocked(displayId) != null) {
-                return;
-            }
-            // If we have no registered callback, update the state we
-            // we may have to register one but it didn't happen yet.
-            if (!mA11yWindowManager.isTrackingWindowsLocked(displayId)) {
-                // Invokes client change to make sure tracking window enabled.
-                mSystemSupport.onClientChangeLocked(false);
-            }
-            // We have no windows but do not care about them, done.
-            if (!mA11yWindowManager.isTrackingWindowsLocked(displayId)) {
-                return;
-            }
+    private void ensureWindowsAvailableTimedLocked(int displayId) {
+        if (mA11yWindowManager.getWindowListLocked(displayId) != null) {
+            return;
+        }
+        // If we have no registered callback, update the state we
+        // we may have to register one but it didn't happen yet.
+        if (!mA11yWindowManager.isTrackingWindowsLocked(displayId)) {
+            // Invokes client change to make sure tracking window enabled.
+            mSystemSupport.onClientChangeLocked(false);
+        }
+        // We have no windows but do not care about them, done.
+        if (!mA11yWindowManager.isTrackingWindowsLocked(displayId)) {
+            return;
+        }
 
-            // Wait for the windows with a timeout.
-            final long startMillis = SystemClock.uptimeMillis();
-            while (mA11yWindowManager.getWindowListLocked(displayId) == null) {
-                final long elapsedMillis = SystemClock.uptimeMillis() - startMillis;
-                final long remainMillis = WAIT_WINDOWS_TIMEOUT_MILLIS - elapsedMillis;
-                if (remainMillis <= 0) {
-                    return;
-                }
-                try {
-                    mLock.wait(remainMillis);
-                } catch (InterruptedException ie) {
-                    /* ignore */
-                }
+        // Wait for the windows with a timeout.
+        final long startMillis = SystemClock.uptimeMillis();
+        while (mA11yWindowManager.getWindowListLocked(displayId) == null) {
+            final long elapsedMillis = SystemClock.uptimeMillis() - startMillis;
+            final long remainMillis = WAIT_WINDOWS_TIMEOUT_MILLIS - elapsedMillis;
+            if (remainMillis <= 0) {
+                return;
+            }
+            try {
+                mLock.wait(remainMillis);
+            } catch (InterruptedException ie) {
+                /* ignore */
             }
         }
     }
@@ -1442,6 +1441,24 @@
                 interrogatingPid, interrogatingTid);
     }
 
+    private List<AccessibilityWindowInfo> getWindowsByDisplayLocked(int displayId) {
+        final List<AccessibilityWindowInfo> internalWindowList =
+                mA11yWindowManager.getWindowListLocked(displayId);
+        if (internalWindowList == null) {
+            return null;
+        }
+        final List<AccessibilityWindowInfo> returnedWindowList = new ArrayList<>();
+        final int windowCount = internalWindowList.size();
+        for (int i = 0; i < windowCount; i++) {
+            AccessibilityWindowInfo window = internalWindowList.get(i);
+            AccessibilityWindowInfo windowClone =
+                    AccessibilityWindowInfo.obtain(window);
+            windowClone.setConnectionId(mId);
+            returnedWindowList.add(windowClone);
+        }
+        return returnedWindowList;
+    }
+
     public ComponentName getComponentName() {
         return mComponentName;
     }
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
index 1f11059..3b105ad 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -30,6 +30,7 @@
 import android.accessibilityservice.AccessibilityGestureEvent;
 import android.accessibilityservice.AccessibilityService;
 import android.accessibilityservice.AccessibilityServiceInfo;
+import android.accessibilityservice.AccessibilityShortcutInfo;
 import android.accessibilityservice.IAccessibilityServiceClient;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -1208,6 +1209,18 @@
         return false;
     }
 
+    private boolean readInstalledAccessibilityShortcutLocked(UserState userState) {
+        final List<AccessibilityShortcutInfo> shortcutInfos = AccessibilityManager
+                .getInstance(mContext).getInstalledAccessibilityShortcutListAsUser(
+                        mContext, mCurrentUserId);
+        if (!shortcutInfos.equals(userState.mInstalledShortcuts)) {
+            userState.mInstalledShortcuts.clear();
+            userState.mInstalledShortcuts.addAll(shortcutInfos);
+            return true;
+        }
+        return false;
+    }
+
     private boolean readEnabledAccessibilityServicesLocked(UserState userState) {
         mTempComponentNameSet.clear();
         readComponentNamesFromSettingLocked(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
@@ -1741,6 +1754,7 @@
 
     private boolean readConfigurationForUserStateLocked(UserState userState) {
         boolean somethingChanged = readInstalledAccessibilityServiceLocked(userState);
+        somethingChanged |= readInstalledAccessibilityShortcutLocked(userState);
         somethingChanged |= readEnabledAccessibilityServicesLocked(userState);
         somethingChanged |= readTouchExplorationGrantedAccessibilityServicesLocked(userState);
         somethingChanged |= readTouchExplorationEnabledSettingLocked(userState);
@@ -2671,6 +2685,8 @@
         public final List<AccessibilityServiceInfo> mInstalledServices =
                 new ArrayList<>();
 
+        public final List<AccessibilityShortcutInfo> mInstalledShortcuts = new ArrayList<>();
+
         private final Set<ComponentName> mBindingServices = new HashSet<>();
 
         public final Set<ComponentName> mEnabledServices = new HashSet<>();
@@ -3083,6 +3099,8 @@
                         || mUserInteractiveUiTimeoutUri.equals(uri)) {
                     readUserRecommendedUiTimeoutSettingsLocked(userState);
                 }
+                // TODO(a11y shortcut): Monitor new setting keys, when user adds shortcut, and
+                //  remove from the list of enabled targets anything that's been uninstalled.
             }
         }
     }
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
index 0038a27..cb858ac 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
@@ -1472,11 +1472,27 @@
     public int getDisplayIdByUserIdAndWindowIdLocked(int userId, int windowId) {
         final IBinder windowToken = getWindowTokenForUserAndWindowIdLocked(userId, windowId);
         final int displayId = mWindowManagerInternal.getDisplayIdForWindow(windowToken);
-
         return displayId;
     }
 
     /**
+     * Returns the display list including all displays which are tracking windows.
+     *
+     * @return The display list.
+     */
+    public ArrayList<Integer> getDisplayListLocked() {
+        final ArrayList<Integer> displayList = new ArrayList<>();
+        final int count = mDisplayWindowsObservers.size();
+        for (int i = 0; i < count; i++) {
+            final DisplayWindowsObserver observer = mDisplayWindowsObservers.valueAt(i);
+            if (observer != null) {
+                displayList.add(observer.mDisplayId);
+            }
+        }
+        return displayList;
+    }
+
+    /**
      * Gets current input focused window token from window manager, and returns its windowId.
      *
      * @param userId The userId
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java b/services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java
index 7e8fb29..3dfe59e 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/AccessibilityGestureDetector.java
@@ -408,9 +408,6 @@
         cancelGesture();
     }
 
-    public boolean firstTapDetected() {
-        return mFirstTapDetected;
-    }
 
     @Override
     public void onLongPress(MotionEvent e) {
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/EventDispatcher.java b/services/accessibility/java/com/android/server/accessibility/gestures/EventDispatcher.java
index dc7a9aa..5ac3b69 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/EventDispatcher.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/EventDispatcher.java
@@ -72,10 +72,16 @@
      *
      * @param prototype The prototype from which to create the injected events.
      * @param action The action of the event.
+     * @param rawEvent The original event prior to magnification or other transformations.
      * @param pointerIdBits The bits of the pointers to send.
      * @param policyFlags The policy flags associated with the event.
      */
-    void sendMotionEvent(MotionEvent prototype, int action, int pointerIdBits, int policyFlags) {
+    void sendMotionEvent(
+            MotionEvent prototype,
+            int action,
+            MotionEvent rawEvent,
+            int pointerIdBits,
+            int policyFlags) {
         prototype.setAction(action);
 
         MotionEvent event = null;
@@ -105,11 +111,8 @@
 
         // Make sure that the user will see the event.
         policyFlags |= WindowManagerPolicy.FLAG_PASS_TO_USER;
-        // TODO: For now pass null for the raw event since the touch
-        //       explorer is the last event transformation and it does
-        //       not care about the raw event.
         if (mReceiver != null) {
-            mReceiver.onMotionEvent(event, null, policyFlags);
+            mReceiver.onMotionEvent(event, rawEvent, policyFlags);
         } else {
             Slog.e(LOG_TAG, "Error sending event: no receiver specified.");
         }
@@ -280,7 +283,12 @@
             if (!isInjectedPointerDown(pointerId)) {
                 pointerIdBits |= (1 << pointerId);
                 final int action = computeInjectionAction(MotionEvent.ACTION_DOWN, i);
-                sendMotionEvent(prototype, action, pointerIdBits, policyFlags);
+                sendMotionEvent(
+                        prototype,
+                        action,
+                        mState.getLastReceivedEvent(),
+                        pointerIdBits,
+                        policyFlags);
             }
         }
     }
@@ -303,7 +311,8 @@
             }
             pointerIdBits |= (1 << pointerId);
             final int action = computeInjectionAction(MotionEvent.ACTION_UP, i);
-            sendMotionEvent(prototype, action, pointerIdBits, policyFlags);
+            sendMotionEvent(
+                    prototype, action, mState.getLastReceivedEvent(), pointerIdBits, policyFlags);
         }
     }
 }
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java b/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
index f4ac821..b62e260 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
@@ -183,9 +183,9 @@
     private void clear() {
         // If we have not received an event then we are in initial
         // state. Therefore, there is not need to clean anything.
-        MotionEvent event = mReceivedPointerTracker.getLastReceivedEvent();
+        MotionEvent event = mState.getLastReceivedEvent();
         if (event != null) {
-            clear(mReceivedPointerTracker.getLastReceivedEvent(), WindowManagerPolicy.FLAG_TRUSTED);
+            clear(event, WindowManagerPolicy.FLAG_TRUSTED);
         }
     }
 
@@ -229,7 +229,7 @@
             Slog.d(LOG_TAG, mState.toString());
         }
 
-        mReceivedPointerTracker.onMotionEvent(rawEvent);
+        mState.onReceivedMotionEvent(rawEvent);
 
         if (mGestureDetector.onMotionEvent(event, rawEvent, policyFlags)) {
             // Event was handled by the gesture detector.
@@ -250,9 +250,9 @@
         } else if (mState.isTouchExploring()) {
             handleMotionEventStateTouchExploring(event, rawEvent, policyFlags);
         } else if (mState.isDragging()) {
-            handleMotionEventStateDragging(event, policyFlags);
+            handleMotionEventStateDragging(event, rawEvent, policyFlags);
         } else if (mState.isDelegating()) {
-            handleMotionEventStateDelegating(event, policyFlags);
+            handleMotionEventStateDelegating(event, rawEvent, policyFlags);
         } else if (mState.isGestureDetecting()) {
             // Already handled.
         } else {
@@ -292,7 +292,7 @@
         }
 
         // Pointers should not be zero when running this command.
-        if (mReceivedPointerTracker.getLastReceivedEvent().getPointerCount() == 0) {
+        if (mState.getLastReceivedEvent().getPointerCount() == 0) {
             return;
         }
         // Try to use the standard accessibility API to long click
@@ -368,11 +368,15 @@
 
                 // We have just decided that the user is touch,
                 // exploring so start sending events.
-                mSendHoverEnterAndMoveDelayed.addEvent(event);
+                mSendHoverEnterAndMoveDelayed.addEvent(event, mState.getLastReceivedEvent());
                 mSendHoverEnterAndMoveDelayed.forceSendAndRemove();
                 mSendHoverExitDelayed.cancel();
                 mDispatcher.sendMotionEvent(
-                        event, MotionEvent.ACTION_HOVER_MOVE, pointerIdBits, policyFlags);
+                        event,
+                        MotionEvent.ACTION_HOVER_MOVE,
+                        mState.getLastReceivedEvent(),
+                        pointerIdBits,
+                        policyFlags);
                 return true;
             }
         }
@@ -387,7 +391,7 @@
         switch (event.getActionMasked()) {
             // The only way to leave the clear state is for a pointer to go down.
             case MotionEvent.ACTION_DOWN:
-                handleActionDown(event, policyFlags);
+                handleActionDown(event, rawEvent, policyFlags);
                 break;
             default:
                 // Some other nonsensical event.
@@ -399,7 +403,7 @@
      * Handles ACTION_DOWN while in the clear or touch interacting states. This event represents the
      * first finger touching the screen.
      */
-    private void handleActionDown(MotionEvent event, int policyFlags) {
+    private void handleActionDown(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
         mAms.onTouchInteractionStart();
 
         // If we still have not notified the user for the last
@@ -407,24 +411,12 @@
         // we resent the delayed callback and wait again.
         mSendHoverEnterAndMoveDelayed.cancel();
         mSendHoverExitDelayed.cancel();
-
         // If a touch exploration gesture is in progress send events for its end.
         if (mState.isTouchExploring()) {
             sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
         }
 
-        // Avoid duplicated TYPE_TOUCH_INTERACTION_START event when 2nd tap of double
-        // tap.
-        if (!mGestureDetector.firstTapDetected() && mState.isClear()) {
-            mSendTouchExplorationEndDelayed.forceSendAndRemove();
-            mSendTouchInteractionEndDelayed.forceSendAndRemove();
-            mDispatcher.sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_START);
-        } else {
-            // Let gesture to handle to avoid duplicated TYPE_TOUCH_INTERACTION_END event.
-            mSendTouchInteractionEndDelayed.cancel();
-        }
-
-        if (!mGestureDetector.firstTapDetected() && !mState.isTouchExploring()) {
+        if (mState.isClear()) {
             if (!mSendHoverEnterAndMoveDelayed.isPending()) {
                 // Queue a delayed transition to STATE_TOUCH_EXPLORING.
                 // If we do not detect that this is a gesture, delegation or drag the transition
@@ -432,11 +424,17 @@
                 // The idea is to avoid getting stuck in STATE_TOUCH_INTERACTING
                 final int pointerId = mReceivedPointerTracker.getPrimaryPointerId();
                 final int pointerIdBits = (1 << pointerId);
-                mSendHoverEnterAndMoveDelayed.post(event, pointerIdBits, policyFlags);
+                mSendHoverEnterAndMoveDelayed.post(event, rawEvent, pointerIdBits, policyFlags);
             } else {
                 // Cache the event until we discern exploration from gesturing.
-                mSendHoverEnterAndMoveDelayed.addEvent(event);
+                mSendHoverEnterAndMoveDelayed.addEvent(event, rawEvent);
             }
+            mSendTouchExplorationEndDelayed.forceSendAndRemove();
+            mSendTouchInteractionEndDelayed.forceSendAndRemove();
+            mDispatcher.sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_START);
+        } else {
+            // Avoid duplicated TYPE_TOUCH_INTERACTION_START event when 2nd tap of double tap.
+            mSendTouchInteractionEndDelayed.cancel();
         }
     }
 
@@ -453,7 +451,7 @@
             case MotionEvent.ACTION_DOWN:
                 // Continue the previous interaction.
                 mSendTouchInteractionEndDelayed.cancel();
-                handleActionDown(event, policyFlags);
+                handleActionDown(event, rawEvent, policyFlags);
                 break;
             case MotionEvent.ACTION_POINTER_DOWN:
                 handleActionPointerDown();
@@ -462,7 +460,7 @@
                 handleActionMoveStateTouchInteracting(event, rawEvent, policyFlags);
                 break;
             case MotionEvent.ACTION_UP:
-                handleActionUp(event, policyFlags);
+                handleActionUp(event, rawEvent, policyFlags);
                 break;
         }
     }
@@ -487,7 +485,7 @@
                 handleActionMoveStateTouchExploring(event, rawEvent, policyFlags);
                 break;
             case MotionEvent.ACTION_UP:
-                handleActionUp(event, policyFlags);
+                handleActionUp(event, rawEvent, policyFlags);
                 break;
             default:
                 break;
@@ -520,7 +518,7 @@
                 // figure out what the user is doing.
                 if (mSendHoverEnterAndMoveDelayed.isPending()) {
                     // Cache the event until we discern exploration from gesturing.
-                    mSendHoverEnterAndMoveDelayed.addEvent(event);
+                    mSendHoverEnterAndMoveDelayed.addEvent(event, rawEvent);
                 }
                 break;
             case 2:
@@ -538,7 +536,7 @@
                     mDraggingPointerId = pointerId;
                     event.setEdgeFlags(mReceivedPointerTracker.getLastReceivedDownEdgeFlags());
                     mDispatcher.sendMotionEvent(
-                            event, MotionEvent.ACTION_DOWN, pointerIdBits, policyFlags);
+                            event, MotionEvent.ACTION_DOWN, rawEvent, pointerIdBits, policyFlags);
                 } else {
                     // Two pointers moving arbitrary are delegated to the view hierarchy.
                     mState.startDelegating();
@@ -558,13 +556,13 @@
      * Handles ACTION_UP while in the touch interacting state. This event represents all fingers
      * being lifted from the screen.
      */
-    private void handleActionUp(MotionEvent event, int policyFlags) {
+    private void handleActionUp(MotionEvent event,  MotionEvent rawEvent, int policyFlags) {
         mAms.onTouchInteractionEnd();
         final int pointerId = event.getPointerId(event.getActionIndex());
         final int pointerIdBits = (1 << pointerId);
         if (mSendHoverEnterAndMoveDelayed.isPending()) {
             // If we have not delivered the enter schedule an exit.
-            mSendHoverExitDelayed.post(event, pointerIdBits, policyFlags);
+            mSendHoverExitDelayed.post(event, rawEvent, pointerIdBits, policyFlags);
         } else {
             // The user is touch exploring so we send events for end.
             sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
@@ -588,7 +586,7 @@
             // Touch exploration.
                 sendTouchExplorationGestureStartAndHoverEnterIfNeeded(policyFlags);
                 mDispatcher.sendMotionEvent(
-                        event, MotionEvent.ACTION_HOVER_MOVE, pointerIdBits, policyFlags);
+                        event, MotionEvent.ACTION_HOVER_MOVE, rawEvent, pointerIdBits, policyFlags);
                 break;
             case 2:
                 if (mSendHoverEnterAndMoveDelayed.isPending()) {
@@ -638,7 +636,8 @@
      * @param event The event to be handled.
      * @param policyFlags The policy flags associated with the event.
      */
-    private void handleMotionEventStateDragging(MotionEvent event, int policyFlags) {
+    private void handleMotionEventStateDragging(
+            MotionEvent event, MotionEvent rawEvent, int policyFlags) {
         int pointerIdBits = 0;
         // Clear the dragging pointer id if it's no longer valid.
         if (event.findPointerIndex(mDraggingPointerId) == -1) {
@@ -662,7 +661,7 @@
                 mState.startDelegating();
                 if (mDraggingPointerId != INVALID_POINTER_ID) {
                     mDispatcher.sendMotionEvent(
-                            event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
+                            event, MotionEvent.ACTION_UP, rawEvent, pointerIdBits, policyFlags);
                 }
                 mDispatcher.sendDownForAllNotInjectedPointers(event, policyFlags);
             } break;
@@ -681,6 +680,7 @@
                             mDispatcher.sendMotionEvent(
                                     event,
                                     MotionEvent.ACTION_MOVE,
+                                    rawEvent,
                                     pointerIdBits,
                                     policyFlags);
                         } else {
@@ -690,7 +690,11 @@
                             // Remove move history before send injected non-move events
                             event = MotionEvent.obtainNoHistory(event);
                             // Send an event to the end of the drag gesture.
-                            mDispatcher.sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits,
+                            mDispatcher.sendMotionEvent(
+                                    event,
+                                    MotionEvent.ACTION_UP,
+                                    rawEvent,
+                                    pointerIdBits,
                                     policyFlags);
                             // Deliver all pointers to the view hierarchy.
                             mDispatcher.sendDownForAllNotInjectedPointers(event, policyFlags);
@@ -700,7 +704,11 @@
                         mState.startDelegating();
                         event = MotionEvent.obtainNoHistory(event);
                         // Send an event to the end of the drag gesture.
-                        mDispatcher.sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits,
+                        mDispatcher.sendMotionEvent(
+                                event,
+                                MotionEvent.ACTION_UP,
+                                rawEvent,
+                                pointerIdBits,
                                 policyFlags);
                         // Deliver all pointers to the view hierarchy.
                         mDispatcher.sendDownForAllNotInjectedPointers(event, policyFlags);
@@ -713,7 +721,7 @@
                     mDraggingPointerId = INVALID_POINTER_ID;
                         // Send an event to the end of the drag gesture.
                     mDispatcher.sendMotionEvent(
-                            event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
+                            event, MotionEvent.ACTION_UP, rawEvent, pointerIdBits, policyFlags);
                  }
             } break;
             case MotionEvent.ACTION_UP: {
@@ -726,7 +734,7 @@
                     mDraggingPointerId = INVALID_POINTER_ID;
                     // Send an event to the end of the drag gesture.
                     mDispatcher.sendMotionEvent(
-                            event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
+                            event, MotionEvent.ACTION_UP, rawEvent, pointerIdBits, policyFlags);
                 }
             } break;
         }
@@ -738,7 +746,8 @@
      * @param event The event to be handled.
      * @param policyFlags The policy flags associated with the event.
      */
-    private void handleMotionEventStateDelegating(MotionEvent event, int policyFlags) {
+    private void handleMotionEventStateDelegating(
+            MotionEvent event, MotionEvent rawEvent, int policyFlags) {
         switch (event.getActionMasked()) {
             case MotionEvent.ACTION_DOWN: {
                 Slog.e(LOG_TAG, "Delegating state can only be reached if "
@@ -749,7 +758,7 @@
             case MotionEvent.ACTION_UP: {
                 // Deliver the event.
                 mDispatcher.sendMotionEvent(
-                        event, event.getAction(), ALL_POINTER_ID_BITS, policyFlags);
+                        event, event.getAction(), rawEvent, ALL_POINTER_ID_BITS, policyFlags);
 
                 // Announce the end of a the touch interaction.
                 mAms.onTouchInteractionEnd();
@@ -759,7 +768,7 @@
             default: {
                     // Deliver the event.
                 mDispatcher.sendMotionEvent(
-                        event, event.getAction(), ALL_POINTER_ID_BITS, policyFlags);
+                        event, event.getAction(), rawEvent, ALL_POINTER_ID_BITS, policyFlags);
             }
         }
     }
@@ -792,7 +801,11 @@
                 mSendTouchExplorationEndDelayed.post();
             }
             mDispatcher.sendMotionEvent(
-                    event, MotionEvent.ACTION_HOVER_EXIT, pointerIdBits, policyFlags);
+                    event,
+                    MotionEvent.ACTION_HOVER_EXIT,
+                    mState.getLastReceivedEvent(),
+                    pointerIdBits,
+                    policyFlags);
         }
     }
 
@@ -807,7 +820,11 @@
         if (event != null && event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
             final int pointerIdBits = event.getPointerIdBits();
             mDispatcher.sendMotionEvent(
-                    event, MotionEvent.ACTION_HOVER_ENTER, pointerIdBits, policyFlags);
+                    event,
+                    MotionEvent.ACTION_HOVER_ENTER,
+                    mState.getLastReceivedEvent(),
+                    pointerIdBits,
+                    policyFlags);
         }
     }
 
@@ -891,20 +908,23 @@
         private final String LOG_TAG_SEND_HOVER_DELAYED = "SendHoverEnterAndMoveDelayed";
 
         private final List<MotionEvent> mEvents = new ArrayList<MotionEvent>();
+        private final List<MotionEvent> mRawEvents = new ArrayList<MotionEvent>();
 
         private int mPointerIdBits;
         private int mPolicyFlags;
 
-        public void post(MotionEvent event, int pointerIdBits, int policyFlags) {
+        public void post(
+                MotionEvent event, MotionEvent rawEvent, int pointerIdBits, int policyFlags) {
             cancel();
-            addEvent(event);
+            addEvent(event, rawEvent);
             mPointerIdBits = pointerIdBits;
             mPolicyFlags = policyFlags;
             mHandler.postDelayed(this, mDetermineUserIntentTimeout);
         }
 
-        public void addEvent(MotionEvent event) {
+        public void addEvent(MotionEvent event, MotionEvent rawEvent) {
             mEvents.add(MotionEvent.obtain(event));
+            mRawEvents.add(MotionEvent.obtain(rawEvent));
         }
 
         public void cancel() {
@@ -925,6 +945,10 @@
             for (int i = eventCount - 1; i >= 0; i--) {
                 mEvents.remove(i).recycle();
             }
+            final int rawEventcount = mRawEvents.size();
+            for (int i = rawEventcount - 1; i >= 0; i--) {
+                mRawEvents.remove(i).recycle();
+            }
         }
 
         public void forceSendAndRemove() {
@@ -939,10 +963,10 @@
             mDispatcher.sendAccessibilityEvent(
                     AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START);
 
-            if (!mEvents.isEmpty()) {
+            if (!mEvents.isEmpty() && !mRawEvents.isEmpty()) {
                 // Deliver a down event.
                 mDispatcher.sendMotionEvent(mEvents.get(0), MotionEvent.ACTION_HOVER_ENTER,
-                        mPointerIdBits, mPolicyFlags);
+                        mRawEvents.get(0), mPointerIdBits, mPolicyFlags);
                 if (DEBUG) {
                     Slog.d(LOG_TAG_SEND_HOVER_DELAYED,
                             "Injecting motion event: ACTION_HOVER_ENTER");
@@ -952,7 +976,7 @@
                 final int eventCount = mEvents.size();
                 for (int i = 1; i < eventCount; i++) {
                     mDispatcher.sendMotionEvent(mEvents.get(i), MotionEvent.ACTION_HOVER_MOVE,
-                            mPointerIdBits, mPolicyFlags);
+                            mRawEvents.get(i), mPointerIdBits, mPolicyFlags);
                     if (DEBUG) {
                         Slog.d(LOG_TAG_SEND_HOVER_DELAYED,
                                 "Injecting motion event: ACTION_HOVER_MOVE");
@@ -970,12 +994,15 @@
         private final String LOG_TAG_SEND_HOVER_DELAYED = "SendHoverExitDelayed";
 
         private MotionEvent mPrototype;
+        private MotionEvent mRawEvent;
         private int mPointerIdBits;
         private int mPolicyFlags;
 
-        public void post(MotionEvent prototype, int pointerIdBits, int policyFlags) {
+        public void post(
+                MotionEvent prototype, MotionEvent rawEvent, int pointerIdBits, int policyFlags) {
             cancel();
             mPrototype = MotionEvent.obtain(prototype);
+            mRawEvent = MotionEvent.obtain(rawEvent);
             mPointerIdBits = pointerIdBits;
             mPolicyFlags = policyFlags;
             mHandler.postDelayed(this, mDetermineUserIntentTimeout);
@@ -993,8 +1020,14 @@
         }
 
         private void clear() {
-            mPrototype.recycle();
+            if (mPrototype != null) {
+                mPrototype.recycle();
+            }
+            if (mRawEvent != null) {
+                mRawEvent.recycle();
+            }
             mPrototype = null;
+            mRawEvent = null;
             mPointerIdBits = -1;
             mPolicyFlags = 0;
         }
@@ -1011,8 +1044,12 @@
                 Slog.d(LOG_TAG_SEND_HOVER_DELAYED, "Injecting motion event:"
                         + " ACTION_HOVER_EXIT");
             }
-            mDispatcher.sendMotionEvent(mPrototype, MotionEvent.ACTION_HOVER_EXIT,
-                    mPointerIdBits, mPolicyFlags);
+            mDispatcher.sendMotionEvent(
+                    mPrototype,
+                    MotionEvent.ACTION_HOVER_EXIT,
+                    mRawEvent,
+                    mPointerIdBits,
+                    mPolicyFlags);
             if (!mSendTouchExplorationEndDelayed.isPending()) {
                 mSendTouchExplorationEndDelayed.cancel();
                 mSendTouchExplorationEndDelayed.post();
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java b/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java
index 49938fa..f463260 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/TouchState.java
@@ -71,6 +71,7 @@
     // Helper class to track received pointers.
     // Todo: collapse or hide this class so multiple classes don't modify it.
     private final ReceivedPointerTracker mReceivedPointerTracker;
+    private MotionEvent mLastReceivedEvent;
 
     public TouchState() {
         mReceivedPointerTracker = new ReceivedPointerTracker();
@@ -80,6 +81,10 @@
     public void clear() {
         setState(STATE_CLEAR);
         // Reset the pointer trackers.
+        if (mLastReceivedEvent != null) {
+            mLastReceivedEvent.recycle();
+            mLastReceivedEvent = null;
+        }
         mReceivedPointerTracker.clear();
     }
 
@@ -89,6 +94,10 @@
      * @param rawEvent The raw touch event.
      */
     public void onReceivedMotionEvent(MotionEvent rawEvent) {
+        if (mLastReceivedEvent != null) {
+            mLastReceivedEvent.recycle();
+        }
+        mLastReceivedEvent = MotionEvent.obtain(rawEvent);
         mReceivedPointerTracker.onMotionEvent(rawEvent);
     }
 
@@ -216,6 +225,11 @@
         return mReceivedPointerTracker;
     }
 
+    /** @return The last received event. */
+    public MotionEvent getLastReceivedEvent() {
+        return mLastReceivedEvent;
+    }
+
     /** This class tracks where and when a pointer went down. It does not track its movement. */
     class ReceivedPointerTracker {
         private static final String LOG_TAG_RECEIVED_POINTER_TRACKER = "ReceivedPointerTracker";
@@ -232,8 +246,6 @@
         // or if it goes up the next one that most recently went down.
         private int mPrimaryPointerId;
 
-        // Keep track of the last up pointer data.
-        private MotionEvent mLastReceivedEvent;
 
         ReceivedPointerTracker() {
             clear();
@@ -254,11 +266,6 @@
          * @param event The event to process.
          */
         public void onMotionEvent(MotionEvent event) {
-            if (mLastReceivedEvent != null) {
-                mLastReceivedEvent.recycle();
-            }
-            mLastReceivedEvent = MotionEvent.obtain(event);
-
             final int action = event.getActionMasked();
             switch (action) {
                 case MotionEvent.ACTION_DOWN:
@@ -279,11 +286,6 @@
             }
         }
 
-        /** @return The last received event. */
-        public MotionEvent getLastReceivedEvent() {
-            return mLastReceivedEvent;
-        }
-
         /** @return The number of received pointers that are down. */
         public int getReceivedPointerDownCount() {
             return Integer.bitCount(mReceivedPointersDown);
diff --git a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
index fea4e90..81ce359 100644
--- a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
+++ b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
@@ -631,8 +631,9 @@
                     onClickIntent = mDevicePolicyManagerInternal.createShowAdminSupportIntent(
                             providerUserId, true);
                 } else {
-                    final SuspendDialogInfo dialogInfo = mPackageManagerInternal
-                            .getSuspendedDialogInfo(providerPackage, providerUserId);
+                    final SuspendDialogInfo dialogInfo =
+                            mPackageManagerInternal.getSuspendedDialogInfo(providerPackage,
+                                    suspendingPackage, providerUserId);
                     onClickIntent = SuspendedAppActivity.createSuspendedAppInterceptIntent(
                             providerPackage, suspendingPackage, dialogInfo, providerUserId);
                 }
diff --git a/services/autofill/java/com/android/server/autofill/ui/SaveUi.java b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
index 8e20019..b35300c 100644
--- a/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
+++ b/services/autofill/java/com/android/server/autofill/ui/SaveUi.java
@@ -78,6 +78,8 @@
     private static final int THEME_ID_DARK =
             com.android.internal.R.style.Theme_DeviceDefault_Autofill_Save;
 
+    private static final int SCROLL_BAR_DEFAULT_DELAY_BEFORE_FADE_MS = 500;
+
     public interface OnSaveListener {
         void onSave();
         void onCancel(IntentSender listener);
@@ -252,6 +254,8 @@
                         new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                 ViewGroup.LayoutParams.WRAP_CONTENT));
                 subtitleContainer.setVisibility(View.VISIBLE);
+                subtitleContainer.setScrollBarDefaultDelayBeforeFade(
+                        SCROLL_BAR_DEFAULT_DELAY_BEFORE_FADE_MS);
             }
             if (sDebug) Slog.d(TAG, "on constructor: title=" + mTitle + ", subTitle=" + mSubTitle);
         }
@@ -429,6 +433,9 @@
                     saveUiView.findViewById(R.id.autofill_save_custom_subtitle);
             subtitleContainer.addView(customSubtitleView);
             subtitleContainer.setVisibility(View.VISIBLE);
+            subtitleContainer.setScrollBarDefaultDelayBeforeFade(
+                    SCROLL_BAR_DEFAULT_DELAY_BEFORE_FADE_MS);
+
             return true;
         } catch (Exception e) {
             Slog.e(TAG, "Error applying custom description. ", e);
diff --git a/services/backup/Android.bp b/services/backup/Android.bp
index ef03d83..a3b0c89 100644
--- a/services/backup/Android.bp
+++ b/services/backup/Android.bp
@@ -2,4 +2,5 @@
     name: "services.backup",
     srcs: ["java/**/*.java"],
     libs: ["services.core"],
+    static_libs: ["backuplib"],
 }
diff --git a/services/backup/backuplib/Android.bp b/services/backup/backuplib/Android.bp
new file mode 100644
index 0000000..7b194a092
--- /dev/null
+++ b/services/backup/backuplib/Android.bp
@@ -0,0 +1,5 @@
+java_library {
+    name: "backuplib",
+    srcs: ["java/**/*.java"],
+    libs: ["services.core"],
+}
diff --git a/services/backup/backuplib/java/com/android/server/backup/TransportManager.java b/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
new file mode 100644
index 0000000..de48f4b
--- /dev/null
+++ b/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
@@ -0,0 +1,728 @@
+/*
+ * 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.backup;
+
+import android.annotation.Nullable;
+import android.annotation.UserIdInt;
+import android.annotation.WorkerThread;
+import android.app.backup.BackupManager;
+import android.app.backup.BackupTransport;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.Bundle;
+import android.os.RemoteException;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.util.Slog;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.backup.IBackupTransport;
+import com.android.internal.util.Preconditions;
+import com.android.server.backup.transport.OnTransportRegisteredListener;
+import com.android.server.backup.transport.TransportClient;
+import com.android.server.backup.transport.TransportClientManager;
+import com.android.server.backup.transport.TransportConnectionListener;
+import com.android.server.backup.transport.TransportNotAvailableException;
+import com.android.server.backup.transport.TransportNotRegisteredException;
+import com.android.server.backup.transport.TransportStats;
+
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.function.Predicate;
+
+/** Handles in-memory bookkeeping of all BackupTransport objects. */
+public class TransportManager {
+    private static final String TAG = "BackupTransportManager";
+
+    @VisibleForTesting
+    public static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
+
+    private final Intent mTransportServiceIntent = new Intent(SERVICE_ACTION_TRANSPORT_HOST);
+    private final @UserIdInt int mUserId;
+    private final PackageManager mPackageManager;
+    private final Set<ComponentName> mTransportWhitelist;
+    private final TransportClientManager mTransportClientManager;
+    private final TransportStats mTransportStats;
+    private OnTransportRegisteredListener mOnTransportRegisteredListener = (c, n) -> {};
+
+    /**
+     * Lock for registered transports and currently selected transport.
+     *
+     * <p><b>Warning:</b> No calls to {@link IBackupTransport} or calls that result in transport
+     * code being executed such as {@link TransportClient#connect(String)}} and its variants should
+     * be made with this lock held, risk of deadlock.
+     */
+    private final Object mTransportLock = new Object();
+
+    /** @see #getRegisteredTransportNames() */
+    @GuardedBy("mTransportLock")
+    private final Map<ComponentName, TransportDescription> mRegisteredTransportsDescriptionMap =
+            new ArrayMap<>();
+
+    @GuardedBy("mTransportLock")
+    @Nullable
+    private volatile String mCurrentTransportName;
+
+    TransportManager(@UserIdInt int userId, Context context, Set<ComponentName> whitelist,
+            String selectedTransport) {
+        mUserId = userId;
+        mPackageManager = context.getPackageManager();
+        mTransportWhitelist = Preconditions.checkNotNull(whitelist);
+        mCurrentTransportName = selectedTransport;
+        mTransportStats = new TransportStats();
+        mTransportClientManager = TransportClientManager.createEncryptingClientManager(mUserId,
+                context, mTransportStats);
+    }
+
+    @VisibleForTesting
+    TransportManager(
+            @UserIdInt int userId,
+            Context context,
+            Set<ComponentName> whitelist,
+            String selectedTransport,
+            TransportClientManager transportClientManager) {
+        mUserId = userId;
+        mPackageManager = context.getPackageManager();
+        mTransportWhitelist = Preconditions.checkNotNull(whitelist);
+        mCurrentTransportName = selectedTransport;
+        mTransportStats = new TransportStats();
+        mTransportClientManager = transportClientManager;
+    }
+
+    /* Sets a listener to be called whenever a transport is registered. */
+    public void setOnTransportRegisteredListener(OnTransportRegisteredListener listener) {
+        mOnTransportRegisteredListener = listener;
+    }
+
+    @WorkerThread
+    void onPackageAdded(String packageName) {
+        registerTransportsFromPackage(packageName, transportComponent -> true);
+    }
+
+    void onPackageRemoved(String packageName) {
+        synchronized (mTransportLock) {
+            mRegisteredTransportsDescriptionMap.keySet().removeIf(fromPackageFilter(packageName));
+        }
+    }
+
+    @WorkerThread
+    void onPackageChanged(String packageName, String... components) {
+        // Unfortunately this can't be atomic because we risk a deadlock if
+        // registerTransportsFromPackage() is put inside the synchronized block
+        Set<ComponentName> transportComponents = new ArraySet<>(components.length);
+        for (String componentName : components) {
+            transportComponents.add(new ComponentName(packageName, componentName));
+        }
+        synchronized (mTransportLock) {
+            mRegisteredTransportsDescriptionMap.keySet().removeIf(transportComponents::contains);
+        }
+        registerTransportsFromPackage(packageName, transportComponents::contains);
+    }
+
+    /**
+     * Returns the {@link ComponentName}s of the registered transports.
+     *
+     * <p>A *registered* transport is a transport that satisfies intent with action
+     * android.backup.TRANSPORT_HOST, returns true for {@link #isTransportTrusted(ComponentName)}
+     * and that we have successfully connected to once.
+     */
+    ComponentName[] getRegisteredTransportComponents() {
+        synchronized (mTransportLock) {
+            return mRegisteredTransportsDescriptionMap
+                    .keySet()
+                    .toArray(new ComponentName[mRegisteredTransportsDescriptionMap.size()]);
+        }
+    }
+
+    /**
+     * Returns the names of the registered transports.
+     *
+     * @see #getRegisteredTransportComponents()
+     */
+    String[] getRegisteredTransportNames() {
+        synchronized (mTransportLock) {
+            String[] transportNames = new String[mRegisteredTransportsDescriptionMap.size()];
+            int i = 0;
+            for (TransportDescription description : mRegisteredTransportsDescriptionMap.values()) {
+                transportNames[i] = description.name;
+                i++;
+            }
+            return transportNames;
+        }
+    }
+
+    /** Returns a set with the whitelisted transports. */
+    Set<ComponentName> getTransportWhitelist() {
+        return mTransportWhitelist;
+    }
+
+    /** Returns the name of the selected transport or {@code null} if no transport selected. */
+    @Nullable
+    public String getCurrentTransportName() {
+        return mCurrentTransportName;
+    }
+
+    /**
+     * Returns the {@link ComponentName} of the host service of the selected transport or
+     * {@code null} if no transport selected.
+     *
+     * @throws TransportNotRegisteredException if the selected transport is not registered.
+     */
+    @Nullable
+    public ComponentName getCurrentTransportComponent()
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            if (mCurrentTransportName == null) {
+                return null;
+            }
+            return getRegisteredTransportComponentOrThrowLocked(mCurrentTransportName);
+        }
+    }
+
+    /**
+     * Returns the transport name associated with {@code transportComponent}.
+     *
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    public String getTransportName(ComponentName transportComponent)
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportDescriptionOrThrowLocked(transportComponent).name;
+        }
+    }
+
+    /**
+     * Retrieves the transport dir name of {@code transportComponent}.
+     *
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    public String getTransportDirName(ComponentName transportComponent)
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportDescriptionOrThrowLocked(transportComponent)
+                    .transportDirName;
+        }
+    }
+
+    /**
+     * Retrieves the transport dir name of {@code transportName}.
+     *
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    public String getTransportDirName(String transportName) throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportDescriptionOrThrowLocked(transportName).transportDirName;
+        }
+    }
+
+    /**
+     * Retrieves the configuration intent of {@code transportName}.
+     *
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    @Nullable
+    public Intent getTransportConfigurationIntent(String transportName)
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
+                    .configurationIntent;
+        }
+    }
+
+    /**
+     * Retrieves the current destination string of {@code transportName}.
+     *
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    public String getTransportCurrentDestinationString(String transportName)
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
+                    .currentDestinationString;
+        }
+    }
+
+    /**
+     * Retrieves the data management intent of {@code transportName}.
+     *
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    @Nullable
+    public Intent getTransportDataManagementIntent(String transportName)
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
+                    .dataManagementIntent;
+        }
+    }
+
+    /**
+     * Retrieves the data management label of {@code transportName}.
+     *
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    @Nullable
+    public CharSequence getTransportDataManagementLabel(String transportName)
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
+                    .dataManagementLabel;
+        }
+    }
+
+    /* Returns true if the transport identified by {@code transportName} is registered. */
+    public boolean isTransportRegistered(String transportName) {
+        synchronized (mTransportLock) {
+            return getRegisteredTransportEntryLocked(transportName) != null;
+        }
+    }
+
+    /**
+     * Execute {@code transportConsumer} for each registered transport passing the transport name.
+     * This is called with an internal lock held, ensuring that the transport will remain registered
+     * while {@code transportConsumer} is being executed. Don't do heavy operations in {@code
+     * transportConsumer}.
+     *
+     * <p><b>Warning:</b> Do NOT make any calls to {@link IBackupTransport} or call any variants of
+     * {@link TransportClient#connect(String)} here, otherwise you risk deadlock.
+     */
+    public void forEachRegisteredTransport(Consumer<String> transportConsumer) {
+        synchronized (mTransportLock) {
+            for (TransportDescription transportDescription :
+                    mRegisteredTransportsDescriptionMap.values()) {
+                transportConsumer.accept(transportDescription.name);
+            }
+        }
+    }
+
+    /**
+     * Updates given values for the transport already registered and identified with {@param
+     * transportComponent}. If the transport is not registered it will log and return.
+     */
+    public void updateTransportAttributes(
+            ComponentName transportComponent,
+            String name,
+            @Nullable Intent configurationIntent,
+            String currentDestinationString,
+            @Nullable Intent dataManagementIntent,
+            @Nullable CharSequence dataManagementLabel) {
+        synchronized (mTransportLock) {
+            TransportDescription description =
+                    mRegisteredTransportsDescriptionMap.get(transportComponent);
+            if (description == null) {
+                Slog.e(TAG, "Transport " + name + " not registered tried to change description");
+                return;
+            }
+            description.name = name;
+            description.configurationIntent = configurationIntent;
+            description.currentDestinationString = currentDestinationString;
+            description.dataManagementIntent = dataManagementIntent;
+            description.dataManagementLabel = dataManagementLabel;
+            Slog.d(TAG, "Transport " + name + " updated its attributes");
+        }
+    }
+
+    @GuardedBy("mTransportLock")
+    private ComponentName getRegisteredTransportComponentOrThrowLocked(String transportName)
+            throws TransportNotRegisteredException {
+        ComponentName transportComponent = getRegisteredTransportComponentLocked(transportName);
+        if (transportComponent == null) {
+            throw new TransportNotRegisteredException(transportName);
+        }
+        return transportComponent;
+    }
+
+    @GuardedBy("mTransportLock")
+    private TransportDescription getRegisteredTransportDescriptionOrThrowLocked(
+            ComponentName transportComponent) throws TransportNotRegisteredException {
+        TransportDescription description =
+                mRegisteredTransportsDescriptionMap.get(transportComponent);
+        if (description == null) {
+            throw new TransportNotRegisteredException(transportComponent);
+        }
+        return description;
+    }
+
+    @GuardedBy("mTransportLock")
+    private TransportDescription getRegisteredTransportDescriptionOrThrowLocked(
+            String transportName) throws TransportNotRegisteredException {
+        TransportDescription description = getRegisteredTransportDescriptionLocked(transportName);
+        if (description == null) {
+            throw new TransportNotRegisteredException(transportName);
+        }
+        return description;
+    }
+
+    @GuardedBy("mTransportLock")
+    @Nullable
+    private ComponentName getRegisteredTransportComponentLocked(String transportName) {
+        Map.Entry<ComponentName, TransportDescription> entry =
+                getRegisteredTransportEntryLocked(transportName);
+        return (entry == null) ? null : entry.getKey();
+    }
+
+    @GuardedBy("mTransportLock")
+    @Nullable
+    private TransportDescription getRegisteredTransportDescriptionLocked(String transportName) {
+        Map.Entry<ComponentName, TransportDescription> entry =
+                getRegisteredTransportEntryLocked(transportName);
+        return (entry == null) ? null : entry.getValue();
+    }
+
+    @GuardedBy("mTransportLock")
+    @Nullable
+    private Map.Entry<ComponentName, TransportDescription> getRegisteredTransportEntryLocked(
+            String transportName) {
+        for (Map.Entry<ComponentName, TransportDescription> entry :
+                mRegisteredTransportsDescriptionMap.entrySet()) {
+            TransportDescription description = entry.getValue();
+            if (transportName.equals(description.name)) {
+                return entry;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Returns a {@link TransportClient} for {@code transportName} or {@code null} if not
+     * registered.
+     *
+     * @param transportName The name of the transport.
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     * @return A {@link TransportClient} or null if not registered.
+     */
+    @Nullable
+    public TransportClient getTransportClient(String transportName, String caller) {
+        try {
+            return getTransportClientOrThrow(transportName, caller);
+        } catch (TransportNotRegisteredException e) {
+            Slog.w(TAG, "Transport " + transportName + " not registered");
+            return null;
+        }
+    }
+
+    /**
+     * Returns a {@link TransportClient} for {@code transportName} or throws if not registered.
+     *
+     * @param transportName The name of the transport.
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     * @return A {@link TransportClient}.
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     */
+    public TransportClient getTransportClientOrThrow(String transportName, String caller)
+            throws TransportNotRegisteredException {
+        synchronized (mTransportLock) {
+            ComponentName component = getRegisteredTransportComponentLocked(transportName);
+            if (component == null) {
+                throw new TransportNotRegisteredException(transportName);
+            }
+            return mTransportClientManager.getTransportClient(component, caller);
+        }
+    }
+
+    /**
+     * Returns a {@link TransportClient} for the current transport or {@code null} if not
+     * registered.
+     *
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     * @return A {@link TransportClient} or null if not registered.
+     * @throws IllegalStateException if no transport is selected.
+     */
+    @Nullable
+    public TransportClient getCurrentTransportClient(String caller) {
+        if (mCurrentTransportName == null) {
+            throw new IllegalStateException("No transport selected");
+        }
+        synchronized (mTransportLock) {
+            return getTransportClient(mCurrentTransportName, caller);
+        }
+    }
+
+    /**
+     * Returns a {@link TransportClient} for the current transport or throws if not registered.
+     *
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     * @return A {@link TransportClient}.
+     * @throws TransportNotRegisteredException if the transport is not registered.
+     * @throws IllegalStateException if no transport is selected.
+     */
+    public TransportClient getCurrentTransportClientOrThrow(String caller)
+            throws TransportNotRegisteredException {
+        if (mCurrentTransportName == null) {
+            throw new IllegalStateException("No transport selected");
+        }
+        synchronized (mTransportLock) {
+            return getTransportClientOrThrow(mCurrentTransportName, caller);
+        }
+    }
+
+    /**
+     * Disposes of the {@link TransportClient}.
+     *
+     * @param transportClient The {@link TransportClient} to be disposed of.
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     */
+    public void disposeOfTransportClient(TransportClient transportClient, String caller) {
+        mTransportClientManager.disposeOfTransportClient(transportClient, caller);
+    }
+
+    /**
+     * Sets {@code transportName} as selected transport and returns previously selected transport
+     * name. If there was no previous transport it returns null.
+     *
+     * <p>You should NOT call this method in new code. This won't make any checks against {@code
+     * transportName}, putting any operation at risk of a {@link TransportNotRegisteredException} or
+     * another error at the time it's being executed.
+     *
+     * <p>{@link Deprecated} as public, this method can be used as private.
+     */
+    @Deprecated
+    @Nullable
+    String selectTransport(String transportName) {
+        synchronized (mTransportLock) {
+            String prevTransport = mCurrentTransportName;
+            mCurrentTransportName = transportName;
+            return prevTransport;
+        }
+    }
+
+    /**
+     * Tries to register the transport if not registered. If successful also selects the transport.
+     *
+     * @param transportComponent Host of the transport.
+     * @return One of {@link BackupManager#SUCCESS}, {@link BackupManager#ERROR_TRANSPORT_INVALID}
+     *     or {@link BackupManager#ERROR_TRANSPORT_UNAVAILABLE}.
+     */
+    @WorkerThread
+    public int registerAndSelectTransport(ComponentName transportComponent) {
+        // If it's already registered we select and return
+        synchronized (mTransportLock) {
+            try {
+                selectTransport(getTransportName(transportComponent));
+                return BackupManager.SUCCESS;
+            } catch (TransportNotRegisteredException e) {
+                // Fall through and release lock
+            }
+        }
+
+        // We can't call registerTransport() with the transport lock held
+        int result = registerTransport(transportComponent);
+        if (result != BackupManager.SUCCESS) {
+            return result;
+        }
+        synchronized (mTransportLock) {
+            try {
+                selectTransport(getTransportName(transportComponent));
+                return BackupManager.SUCCESS;
+            } catch (TransportNotRegisteredException e) {
+                Slog.wtf(TAG, "Transport got unregistered");
+                return BackupManager.ERROR_TRANSPORT_UNAVAILABLE;
+            }
+        }
+    }
+
+    @WorkerThread
+    public void registerTransports() {
+        registerTransportsForIntent(mTransportServiceIntent, transportComponent -> true);
+    }
+
+    @WorkerThread
+    private void registerTransportsFromPackage(
+            String packageName, Predicate<ComponentName> transportComponentFilter) {
+        try {
+            mPackageManager.getPackageInfoAsUser(packageName, 0, mUserId);
+        } catch (PackageManager.NameNotFoundException e) {
+            Slog.e(TAG, "Trying to register transports from package not found " + packageName);
+            return;
+        }
+
+        registerTransportsForIntent(
+                new Intent(mTransportServiceIntent).setPackage(packageName),
+                transportComponentFilter.and(fromPackageFilter(packageName)));
+    }
+
+    @WorkerThread
+    private void registerTransportsForIntent(
+            Intent intent, Predicate<ComponentName> transportComponentFilter) {
+        List<ResolveInfo> hosts =
+                mPackageManager.queryIntentServicesAsUser(intent, 0, mUserId);
+        if (hosts == null) {
+            return;
+        }
+        for (ResolveInfo host : hosts) {
+            ComponentName transportComponent = host.serviceInfo.getComponentName();
+            if (transportComponentFilter.test(transportComponent)
+                    && isTransportTrusted(transportComponent)) {
+                registerTransport(transportComponent);
+            }
+        }
+    }
+
+    /** Transport has to be whitelisted and privileged. */
+    private boolean isTransportTrusted(ComponentName transport) {
+        if (!mTransportWhitelist.contains(transport)) {
+            Slog.w(
+                    TAG,
+                    "BackupTransport " + transport.flattenToShortString() + " not whitelisted.");
+            return false;
+        }
+        try {
+            PackageInfo packInfo =
+                    mPackageManager.getPackageInfoAsUser(transport.getPackageName(), 0, mUserId);
+            if ((packInfo.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
+                    == 0) {
+                Slog.w(TAG, "Transport package " + transport.getPackageName() + " not privileged");
+                return false;
+            }
+        } catch (PackageManager.NameNotFoundException e) {
+            Slog.w(TAG, "Package not found.", e);
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Tries to register transport represented by {@code transportComponent}.
+     *
+     * <p><b>Warning:</b> Don't call this with the transport lock held.
+     *
+     * @param transportComponent Host of the transport that we want to register.
+     * @return One of {@link BackupManager#SUCCESS}, {@link BackupManager#ERROR_TRANSPORT_INVALID}
+     *     or {@link BackupManager#ERROR_TRANSPORT_UNAVAILABLE}.
+     */
+    @WorkerThread
+    private int registerTransport(ComponentName transportComponent) {
+        checkCanUseTransport();
+
+        if (!isTransportTrusted(transportComponent)) {
+            return BackupManager.ERROR_TRANSPORT_INVALID;
+        }
+
+        String transportString = transportComponent.flattenToShortString();
+        String callerLogString = "TransportManager.registerTransport()";
+
+        Bundle extras = new Bundle();
+        extras.putBoolean(BackupTransport.EXTRA_TRANSPORT_REGISTRATION, true);
+
+        TransportClient transportClient =
+                mTransportClientManager.getTransportClient(
+                        transportComponent, extras, callerLogString);
+        final IBackupTransport transport;
+        try {
+            transport = transportClient.connectOrThrow(callerLogString);
+        } catch (TransportNotAvailableException e) {
+            Slog.e(TAG, "Couldn't connect to transport " + transportString + " for registration");
+            mTransportClientManager.disposeOfTransportClient(transportClient, callerLogString);
+            return BackupManager.ERROR_TRANSPORT_UNAVAILABLE;
+        }
+
+        int result;
+        try {
+            String transportName = transport.name();
+            String transportDirName = transport.transportDirName();
+            registerTransport(transportComponent, transport);
+            // If registerTransport() hasn't thrown...
+            Slog.d(TAG, "Transport " + transportString + " registered");
+            mOnTransportRegisteredListener.onTransportRegistered(transportName, transportDirName);
+            result = BackupManager.SUCCESS;
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Transport " + transportString + " died while registering");
+            result = BackupManager.ERROR_TRANSPORT_UNAVAILABLE;
+        }
+
+        mTransportClientManager.disposeOfTransportClient(transportClient, callerLogString);
+        return result;
+    }
+
+    /** If {@link RemoteException} is thrown the transport is guaranteed to not be registered. */
+    private void registerTransport(ComponentName transportComponent, IBackupTransport transport)
+            throws RemoteException {
+        checkCanUseTransport();
+
+        TransportDescription description =
+                new TransportDescription(
+                        transport.name(),
+                        transport.transportDirName(),
+                        transport.configurationIntent(),
+                        transport.currentDestinationString(),
+                        transport.dataManagementIntent(),
+                        transport.dataManagementIntentLabel());
+        synchronized (mTransportLock) {
+            mRegisteredTransportsDescriptionMap.put(transportComponent, description);
+        }
+    }
+
+    private void checkCanUseTransport() {
+        Preconditions.checkState(
+                !Thread.holdsLock(mTransportLock), "Can't call transport with transport lock held");
+    }
+
+    public void dumpTransportClients(PrintWriter pw) {
+        mTransportClientManager.dump(pw);
+    }
+
+    public void dumpTransportStats(PrintWriter pw) {
+        mTransportStats.dump(pw);
+    }
+
+    private static Predicate<ComponentName> fromPackageFilter(String packageName) {
+        return transportComponent -> packageName.equals(transportComponent.getPackageName());
+    }
+
+    private static class TransportDescription {
+        private String name;
+        private final String transportDirName;
+        @Nullable private Intent configurationIntent;
+        private String currentDestinationString;
+        @Nullable private Intent dataManagementIntent;
+        @Nullable private CharSequence dataManagementLabel;
+
+        private TransportDescription(
+                String name,
+                String transportDirName,
+                @Nullable Intent configurationIntent,
+                String currentDestinationString,
+                @Nullable Intent dataManagementIntent,
+                @Nullable CharSequence dataManagementLabel) {
+            this.name = name;
+            this.transportDirName = transportDirName;
+            this.configurationIntent = configurationIntent;
+            this.currentDestinationString = currentDestinationString;
+            this.dataManagementIntent = dataManagementIntent;
+            this.dataManagementLabel = dataManagementLabel;
+        }
+    }
+}
diff --git a/services/backup/backuplib/java/com/android/server/backup/transport/DelegatingTransport.java b/services/backup/backuplib/java/com/android/server/backup/transport/DelegatingTransport.java
new file mode 100644
index 0000000..ab87080
--- /dev/null
+++ b/services/backup/backuplib/java/com/android/server/backup/transport/DelegatingTransport.java
@@ -0,0 +1,414 @@
+/*
+ * Copyright (C) 2019 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.backup.transport;
+
+import android.app.backup.BackupAgent;
+import android.app.backup.BackupTransport;
+import android.app.backup.RestoreDescription;
+import android.app.backup.RestoreSet;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+
+import com.android.internal.backup.IBackupTransport;
+
+/**
+ * Delegates all transport methods to the delegate() implemented in the derived class.
+ */
+public abstract class DelegatingTransport extends IBackupTransport.Stub {
+    protected abstract IBackupTransport getDelegate() throws RemoteException;
+
+    /**
+     * Ask the transport for the name under which it should be registered.  This will
+     * typically be its host service's component name, but need not be.
+     */
+    @Override
+    public String name() throws RemoteException {
+        return getDelegate().name();
+    }
+
+    /**
+     * Ask the transport for an Intent that can be used to launch any internal
+     * configuration Activity that it wishes to present.  For example, the transport
+     * may offer a UI for allowing the user to supply login credentials for the
+     * transport's off-device backend.
+     *
+     * If the transport does not supply any user-facing configuration UI, it should
+     * return null from this method.
+     *
+     * @return An Intent that can be passed to Context.startActivity() in order to
+     * launch the transport's configuration UI.  This method will return null
+     * if the transport does not offer any user-facing configuration UI.
+     */
+    @Override
+    public Intent configurationIntent() throws RemoteException {
+        return getDelegate().configurationIntent();
+    }
+
+    /**
+     * On demand, supply a one-line string that can be shown to the user that
+     * describes the current backend destination.  For example, a transport that
+     * can potentially associate backup data with arbitrary user accounts should
+     * include the name of the currently-active account here.
+     *
+     * @return A string describing the destination to which the transport is currently
+     * sending data.  This method should not return null.
+     */
+    @Override
+    public String currentDestinationString() throws RemoteException {
+        return getDelegate().currentDestinationString();
+    }
+
+    /**
+     * Ask the transport for an Intent that can be used to launch a more detailed
+     * secondary data management activity.  For example, the configuration intent might
+     * be one for allowing the user to select which account they wish to associate
+     * their backups with, and the management intent might be one which presents a
+     * UI for managing the data on the backend.
+     *
+     * <p>In the Settings UI, the configuration intent will typically be invoked
+     * when the user taps on the preferences item labeled with the current
+     * destination string, and the management intent will be placed in an overflow
+     * menu labelled with the management label string.
+     *
+     * <p>If the transport does not supply any user-facing data management
+     * UI, then it should return {@code null} from this method.
+     *
+     * @return An intent that can be passed to Context.startActivity() in order to
+     * launch the transport's data-management UI.  This method will return
+     * {@code null} if the transport does not offer any user-facing data
+     * management UI.
+     */
+    @Override
+    public Intent dataManagementIntent() throws RemoteException {
+        return getDelegate().dataManagementIntent();
+    }
+
+    /**
+     * On demand, supply a short {@link CharSequence} that can be shown to the user as the
+     * label on
+     * an overflow menu item used to invoke the data management UI.
+     *
+     * @return A {@link CharSequence} to be used as the label for the transport's data management
+     *         affordance.  If the transport supplies a data management intent, this
+     *         method must not return {@code null}.
+     */
+    @Override
+    public CharSequence dataManagementIntentLabel() throws RemoteException {
+        return getDelegate().dataManagementIntentLabel();
+    }
+
+    /**
+     * Ask the transport where, on local device storage, to keep backup state blobs.
+     * This is per-transport so that mock transports used for testing can coexist with
+     * "live" backup services without interfering with the live bookkeeping.  The
+     * returned string should be a name that is expected to be unambiguous among all
+     * available backup transports; the name of the class implementing the transport
+     * is a good choice.  This MUST be constant.
+     *
+     * @return A unique name, suitable for use as a file or directory name, that the
+     *         Backup Manager could use to disambiguate state files associated with
+     *         different backup transports.
+     */
+    @Override
+    public String transportDirName() throws RemoteException {
+        return getDelegate().transportDirName();
+    }
+
+    /**
+     * Verify that this is a suitable time for a backup pass.  This should return zero
+     * if a backup is reasonable right now, some positive value otherwise.  This method
+     * will be called outside of the {@link #startSession}/{@link #endSession} pair.
+     *
+     * <p>If this is not a suitable time for a backup, the transport should return a
+     * backoff delay, in milliseconds, after which the Backup Manager should try again.
+     *
+     * @return Zero if this is a suitable time for a backup pass, or a positive time delay
+     *   in milliseconds to suggest deferring the backup pass for a while.
+     */
+    @Override
+    public long requestBackupTime() throws RemoteException {
+        return getDelegate().requestBackupTime();
+    }
+
+    /**
+     * Initialize the server side storage for this device, erasing all stored data.
+     * The transport may send the request immediately, or may buffer it.  After
+     * this is called, {@link #finishBackup} must be called to ensure the request
+     * is sent and received successfully.
+     *
+     * @return One of {@link BackupConstants#TRANSPORT_OK} (OK so far) or
+     *   {@link BackupConstants#TRANSPORT_ERROR} (on network error or other failure).
+     */
+    @Override
+    public int initializeDevice() throws RemoteException {
+        return getDelegate().initializeDevice();
+    }
+
+    /**
+     * Send one application's data to the backup destination.  The transport may send
+     * the data immediately, or may buffer it.  After this is called, {@link #finishBackup}
+     * must be called to ensure the data is sent and recorded successfully.
+     *
+     * @param packageInfo The identity of the application whose data is being backed up.
+     *   This specifically includes the signature list for the package.
+     * @param inFd Descriptor of file with data that resulted from invoking the application's
+     *   BackupService.doBackup() method.  This may be a pipe rather than a file on
+     *   persistent media, so it may not be seekable.
+     * @param flags Some of {@link BackupTransport#FLAG_USER_INITIATED}.
+     * @return one of {@link BackupConstants#TRANSPORT_OK} (OK so far),
+     *  {@link BackupConstants#TRANSPORT_ERROR} (on network error or other failure), or
+     *  {@link BackupConstants#TRANSPORT_NOT_INITIALIZED} (if the backend dataset has
+     *  become lost due to inactive expiry or some other reason and needs re-initializing)
+     */
+    @Override
+    public int performBackup(PackageInfo packageInfo,
+            ParcelFileDescriptor inFd, int flags) throws RemoteException {
+        return getDelegate().performBackup(packageInfo, inFd, flags);
+    }
+
+    /**
+     * Erase the give application's data from the backup destination.  This clears
+     * out the given package's data from the current backup set, making it as though
+     * the app had never yet been backed up.  After this is called, {@link finishBackup}
+     * must be called to ensure that the operation is recorded successfully.
+     *
+     * @return the same error codes as {@link #performBackup}.
+     * @param packageInfo
+     */
+    @Override
+    public int clearBackupData(PackageInfo packageInfo) throws RemoteException {
+        return getDelegate().clearBackupData(packageInfo);
+    }
+
+    /**
+     * Finish sending application data to the backup destination.  This must be
+     * called after {@link #performBackup} or {@link clearBackupData} to ensure that
+     * all data is sent.  Only when this method returns true can a backup be assumed
+     * to have succeeded.
+     *
+     * @return the same error codes as {@link #performBackup}.
+     */
+    @Override
+    public int finishBackup() throws RemoteException {
+        return getDelegate().finishBackup();
+    }
+
+    /**
+     * Get the set of all backups currently available over this transport.
+     *
+     * @return Descriptions of the set of restore images available for this device,
+     *   or null if an error occurred (the attempt should be rescheduled).
+     **/
+    @Override
+    public RestoreSet[] getAvailableRestoreSets() throws RemoteException {
+        return getDelegate().getAvailableRestoreSets();
+    }
+
+    /**
+     * Get the identifying token of the backup set currently being stored from
+     * this device.  This is used in the case of applications wishing to restore
+     * their last-known-good data.
+     *
+     * @return A token that can be passed to {@link #startRestore}, or 0 if there
+     *   is no backup set available corresponding to the current device state.
+     */
+    @Override
+    public long getCurrentRestoreSet() throws RemoteException {
+        return getDelegate().getCurrentRestoreSet();
+    }
+
+    /**
+     * Start restoring application data from backup.  After calling this function,
+     * alternate calls to {@link #nextRestorePackage} and {@link #nextRestoreData}
+     * to walk through the actual application data.
+     *
+     * @param token A backup token as returned by {@link #getAvailableRestoreSets}
+     *   or {@link #getCurrentRestoreSet}.
+     * @param packages List of applications to restore (if data is available).
+     *   Application data will be restored in the order given.
+     * @return One of {@link BackupConstants#TRANSPORT_OK} (OK so far, call
+     *   {@link #nextRestorePackage}) or {@link BackupConstants#TRANSPORT_ERROR}
+     *   (an error occurred, the restore should be aborted and rescheduled).
+     */
+    @Override
+    public int startRestore(long token, PackageInfo[] packages) throws RemoteException {
+        return getDelegate().startRestore(token, packages);
+    }
+
+    /**
+     * Get the package name of the next application with data in the backup store, plus
+     * a description of the structure of the restored archive: either TYPE_KEY_VALUE for
+     * an original-API key/value dataset, or TYPE_FULL_STREAM for a tarball-type archive stream.
+     *
+     * <p>If the package name in the returned RestoreDescription object is the singleton
+     * {@link RestoreDescription#NO_MORE_PACKAGES}, it indicates that no further data is available
+     * in the current restore session: all packages described in startRestore() have been
+     * processed.
+     *
+     * <p>If this method returns {@code null}, it means that a transport-level error has
+     * occurred and the entire restore operation should be abandoned.
+     *
+     * @return A RestoreDescription object containing the name of one of the packages
+     *   supplied to {@link #startRestore} plus an indicator of the data type of that
+     *   restore data; or {@link RestoreDescription#NO_MORE_PACKAGES} to indicate that
+     *   no more packages can be restored in this session; or {@code null} to indicate
+     *   a transport-level error.
+     */
+    @Override
+    public RestoreDescription nextRestorePackage() throws RemoteException {
+        return getDelegate().nextRestorePackage();
+    }
+
+    /**
+     * Get the data for the application returned by {@link #nextRestorePackage}.
+     *
+     * @param outFd An open, writable file into which the backup data should be stored.
+     * @return the same error codes as {@link #startRestore}.
+     */
+    @Override
+    public int getRestoreData(ParcelFileDescriptor outFd) throws RemoteException {
+        return getDelegate().getRestoreData(outFd);
+    }
+
+    /**
+     * End a restore session (aborting any in-process data transfer as necessary),
+     * freeing any resources and connections used during the restore process.
+     */
+    @Override
+    public void finishRestore() throws RemoteException {
+        getDelegate().finishRestore();
+    }
+
+    @Override
+    public long requestFullBackupTime() throws RemoteException {
+        return getDelegate().requestFullBackupTime();
+    }
+
+    @Override
+    public int performFullBackup(PackageInfo targetPackage,
+            ParcelFileDescriptor socket, int flags) throws RemoteException {
+        return getDelegate().performFullBackup(targetPackage, socket, flags);
+    }
+
+    @Override
+    public int checkFullBackupSize(long size) throws RemoteException {
+        return getDelegate().checkFullBackupSize(size);
+    }
+
+    @Override
+    public int sendBackupData(int numBytes) throws RemoteException {
+        return getDelegate().sendBackupData(numBytes);
+    }
+
+    @Override
+    public void cancelFullBackup() throws RemoteException {
+        getDelegate().cancelFullBackup();
+    }
+
+    /**
+     * Ask the transport whether this app is eligible for backup.
+     *
+     * @param targetPackage The identity of the application.
+     * @param isFullBackup If set, transport should check if app is eligible for full data backup,
+     *   otherwise to check if eligible for key-value backup.
+     * @return Whether this app is eligible for backup.
+     */
+    @Override
+    public boolean isAppEligibleForBackup(PackageInfo targetPackage,
+            boolean isFullBackup) throws RemoteException {
+        return getDelegate().isAppEligibleForBackup(targetPackage, isFullBackup);
+    }
+
+    /**
+     * Ask the transport about current quota for backup size of the package.
+     *
+     * @param packageName  ID of package to provide the quota.
+     * @param isFullBackup If set, transport should return limit for full data backup, otherwise
+     *                     for key-value backup.
+     * @return Current limit on full data backup size in bytes.
+     */
+    @Override
+    public long getBackupQuota(String packageName, boolean isFullBackup) throws RemoteException {
+        return getDelegate().getBackupQuota(packageName, isFullBackup);
+    }
+
+    /**
+     * Ask the transport to provide data for the "current" package being restored.  This
+     * is the package that was just reported by {@link #nextRestorePackage()} as having
+     * {@link RestoreDescription#TYPE_FULL_STREAM} data.
+     *
+     * The transport writes some data to the socket supplied to this call, and returns
+     * the number of bytes written.  The system will then read that many bytes and
+     * stream them to the application's agent for restore, then will call this method again
+     * to receive the next chunk of the archive.  This sequence will be repeated until the
+     * transport returns zero indicating that all of the package's data has been delivered
+     * (or returns a negative value indicating some sort of hard error condition at the
+     * transport level).
+     *
+     * <p>After this method returns zero, the system will then call
+     * {@link #getNextFullRestorePackage()} to begin the restore process for the next
+     * application, and the sequence begins again.
+     *
+     * <p>The transport should always close this socket when returning from this method.
+     * Do not cache this socket across multiple calls or you may leak file descriptors.
+     *
+     * @param socket The file descriptor that the transport will use for delivering the
+     *    streamed archive.  The transport must close this socket in all cases when returning
+     *    from this method.
+     * @return 0 when no more data for the current package is available.  A positive value
+     *    indicates the presence of that many bytes to be delivered to the app.  Any negative
+     *    return value is treated as equivalent to {@link BackupTransport#TRANSPORT_ERROR},
+     *    indicating a fatal error condition that precludes further restore operations
+     *    on the current dataset.
+     */
+    @Override
+    public int getNextFullRestoreDataChunk(ParcelFileDescriptor socket) throws RemoteException {
+        return getDelegate().getNextFullRestoreDataChunk(socket);
+    }
+
+    /**
+     * If the OS encounters an error while processing {@link RestoreDescription#TYPE_FULL_STREAM}
+     * data for restore, it will invoke this method to tell the transport that it should
+     * abandon the data download for the current package.  The OS will then either call
+     * {@link #nextRestorePackage()} again to move on to restoring the next package in the
+     * set being iterated over, or will call {@link #finishRestore()} to shut down the restore
+     * operation.
+     *
+     * @return {@link #TRANSPORT_OK} if the transport was successful in shutting down the
+     *    current stream cleanly, or {@link #TRANSPORT_ERROR} to indicate a serious
+     *    transport-level failure.  If the transport reports an error here, the entire restore
+     *    operation will immediately be finished with no further attempts to restore app data.
+     */
+    @Override
+    public int abortFullRestore() throws RemoteException {
+        return getDelegate().abortFullRestore();
+    }
+
+    /**
+     * Returns flags with additional information about the transport, which is accessible to the
+     * {@link BackupAgent}. This allows the agent to decide what to backup or
+     * restore based on properties of the transport.
+     *
+     * <p>For supported flags see {@link BackupAgent}.
+     */
+    @Override
+    public int getTransportFlags() throws RemoteException {
+        return getDelegate().getTransportFlags();
+    }
+}
diff --git a/services/backup/java/com/android/server/backup/transport/OnTransportRegisteredListener.java b/services/backup/backuplib/java/com/android/server/backup/transport/OnTransportRegisteredListener.java
similarity index 100%
rename from services/backup/java/com/android/server/backup/transport/OnTransportRegisteredListener.java
rename to services/backup/backuplib/java/com/android/server/backup/transport/OnTransportRegisteredListener.java
diff --git a/services/backup/java/com/android/server/backup/transport/TransportClient.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportClient.java
similarity index 100%
rename from services/backup/java/com/android/server/backup/transport/TransportClient.java
rename to services/backup/backuplib/java/com/android/server/backup/transport/TransportClient.java
diff --git a/services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java
new file mode 100644
index 0000000..72b1ee7
--- /dev/null
+++ b/services/backup/backuplib/java/com/android/server/backup/transport/TransportClientManager.java
@@ -0,0 +1,206 @@
+/*
+ * 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.backup.transport;
+
+import static com.android.server.backup.TransportManager.SERVICE_ACTION_TRANSPORT_HOST;
+import static com.android.server.backup.transport.TransportUtils.formatMessage;
+
+import android.annotation.Nullable;
+import android.annotation.UserIdInt;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+
+import com.android.internal.backup.IBackupTransport;
+import com.android.server.backup.TransportManager;
+import com.android.server.backup.transport.TransportUtils.Priority;
+
+import java.io.PrintWriter;
+import java.util.Map;
+import java.util.WeakHashMap;
+import java.util.function.Function;
+
+/**
+ * Manages the creation and disposal of {@link TransportClient}s. The only class that should use
+ * this is {@link TransportManager}, all the other usages should go to {@link TransportManager}.
+ */
+public class TransportClientManager {
+    private static final String TAG = "TransportClientManager";
+    private static final String SERVICE_ACTION_ENCRYPTING_TRANSPORT =
+            "android.encryption.BACKUP_ENCRYPTION";
+    private static final ComponentName ENCRYPTING_TRANSPORT = new ComponentName(
+            "com.android.server.backup.encryption",
+            "com.android.server.backup.encryption.BackupEncryptionService");
+    private static final String ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY = "transport";
+
+    private final @UserIdInt int mUserId;
+    private final Context mContext;
+    private final TransportStats mTransportStats;
+    private final Object mTransportClientsLock = new Object();
+    private int mTransportClientsCreated = 0;
+    private Map<TransportClient, String> mTransportClientsCallerMap = new WeakHashMap<>();
+    private final Function<ComponentName, Intent> mIntentFunction;
+
+    /**
+     * Return an {@link Intent} which resolves to an intermediate {@link IBackupTransport} that
+     * encrypts (or decrypts) the data when sending it (or receiving it) from the {@link
+     * IBackupTransport} for the given {@link ComponentName}.
+     */
+    public static Intent getEncryptingTransportIntent(ComponentName tranportComponent) {
+        return new Intent(SERVICE_ACTION_ENCRYPTING_TRANSPORT)
+                .setComponent(ENCRYPTING_TRANSPORT)
+                .putExtra(ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY, tranportComponent);
+    }
+
+    /**
+     * Return an {@link Intent} which resolves to the {@link IBackupTransport} for the {@link
+     * ComponentName}.
+     */
+    private static Intent getRealTransportIntent(ComponentName transportComponent) {
+        return new Intent(SERVICE_ACTION_TRANSPORT_HOST).setComponent(transportComponent);
+    }
+
+    /**
+     * Given a {@link Intent} originally created by {@link
+     * #getEncryptingTransportIntent(ComponentName)}, returns the {@link Intent} which resolves to
+     * the {@link IBackupTransport} for that {@link ComponentName}.
+     */
+    public static Intent getRealTransportIntent(Intent encryptingTransportIntent) {
+        ComponentName transportComponent = encryptingTransportIntent.getParcelableExtra(
+                ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY);
+        Intent intent = getRealTransportIntent(transportComponent)
+                .putExtras(encryptingTransportIntent.getExtras());
+        intent.removeExtra(ENCRYPTING_TRANSPORT_REAL_TRANSPORT_KEY);
+        return intent;
+    }
+
+    /**
+     * Create a {@link TransportClientManager} such that {@link #getTransportClient(ComponentName,
+     * Bundle, String)} returns a {@link TransportClient} which connects to an intermediate {@link
+     * IBackupTransport} that encrypts (or decrypts) the data when sending it (or receiving it) from
+     * the {@link IBackupTransport} for the given {@link ComponentName}.
+     */
+    public static TransportClientManager createEncryptingClientManager(@UserIdInt int userId,
+            Context context, TransportStats transportStats) {
+        return new TransportClientManager(userId, context, transportStats,
+                TransportClientManager::getEncryptingTransportIntent);
+    }
+
+    public TransportClientManager(@UserIdInt int userId, Context context,
+            TransportStats transportStats) {
+        this(userId, context, transportStats, TransportClientManager::getRealTransportIntent);
+    }
+
+    private TransportClientManager(@UserIdInt int userId, Context context,
+            TransportStats transportStats, Function<ComponentName, Intent> intentFunction) {
+        mUserId = userId;
+        mContext = context;
+        mTransportStats = transportStats;
+        mIntentFunction = intentFunction;
+    }
+
+    /**
+     * Retrieves a {@link TransportClient} for the transport identified by {@param
+     * transportComponent}.
+     *
+     * @param transportComponent The {@link ComponentName} of the transport.
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     * @return A {@link TransportClient}.
+     */
+    public TransportClient getTransportClient(ComponentName transportComponent, String caller) {
+        return getTransportClient(transportComponent, null, caller);
+    }
+
+    /**
+     * Retrieves a {@link TransportClient} for the transport identified by {@param
+     * transportComponent} whose binding intent will have the {@param extras} extras.
+     *
+     * @param transportComponent The {@link ComponentName} of the transport.
+     * @param extras A {@link Bundle} of extras to pass to the binding intent.
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     * @return A {@link TransportClient}.
+     */
+    public TransportClient getTransportClient(
+            ComponentName transportComponent, @Nullable Bundle extras, String caller) {
+        Intent bindIntent = mIntentFunction.apply(transportComponent);
+        if (extras != null) {
+            bindIntent.putExtras(extras);
+        }
+        return getTransportClient(transportComponent, caller, bindIntent);
+    }
+
+    private TransportClient getTransportClient(
+            ComponentName transportComponent, String caller, Intent bindIntent) {
+        synchronized (mTransportClientsLock) {
+            TransportClient transportClient =
+                    new TransportClient(
+                            mUserId,
+                            mContext,
+                            mTransportStats,
+                            bindIntent,
+                            transportComponent,
+                            Integer.toString(mTransportClientsCreated),
+                            caller);
+            mTransportClientsCallerMap.put(transportClient, caller);
+            mTransportClientsCreated++;
+            TransportUtils.log(
+                    Priority.DEBUG,
+                    TAG,
+                    formatMessage(null, caller, "Retrieving " + transportClient));
+            return transportClient;
+        }
+    }
+
+    /**
+     * Disposes of the {@link TransportClient}.
+     *
+     * @param transportClient The {@link TransportClient} to be disposed of.
+     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
+     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
+     *     details.
+     */
+    public void disposeOfTransportClient(TransportClient transportClient, String caller) {
+        transportClient.unbind(caller);
+        transportClient.markAsDisposed();
+        synchronized (mTransportClientsLock) {
+            TransportUtils.log(
+                    Priority.DEBUG,
+                    TAG,
+                    formatMessage(null, caller, "Disposing of " + transportClient));
+            mTransportClientsCallerMap.remove(transportClient);
+        }
+    }
+
+    public void dump(PrintWriter pw) {
+        pw.println("Transport clients created: " + mTransportClientsCreated);
+        synchronized (mTransportClientsLock) {
+            pw.println("Current transport clients: " + mTransportClientsCallerMap.size());
+            for (TransportClient transportClient : mTransportClientsCallerMap.keySet()) {
+                String caller = mTransportClientsCallerMap.get(transportClient);
+                pw.println("    " + transportClient + " [" + caller + "]");
+                for (String logEntry : transportClient.getLogBuffer()) {
+                    pw.println("        " + logEntry);
+                }
+            }
+        }
+    }
+}
diff --git a/services/backup/java/com/android/server/backup/transport/TransportConnectionListener.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportConnectionListener.java
similarity index 100%
rename from services/backup/java/com/android/server/backup/transport/TransportConnectionListener.java
rename to services/backup/backuplib/java/com/android/server/backup/transport/TransportConnectionListener.java
diff --git a/services/backup/java/com/android/server/backup/transport/TransportNotAvailableException.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportNotAvailableException.java
similarity index 100%
rename from services/backup/java/com/android/server/backup/transport/TransportNotAvailableException.java
rename to services/backup/backuplib/java/com/android/server/backup/transport/TransportNotAvailableException.java
diff --git a/services/backup/java/com/android/server/backup/transport/TransportNotRegisteredException.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportNotRegisteredException.java
similarity index 100%
rename from services/backup/java/com/android/server/backup/transport/TransportNotRegisteredException.java
rename to services/backup/backuplib/java/com/android/server/backup/transport/TransportNotRegisteredException.java
diff --git a/services/backup/java/com/android/server/backup/transport/TransportStats.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportStats.java
similarity index 100%
rename from services/backup/java/com/android/server/backup/transport/TransportStats.java
rename to services/backup/backuplib/java/com/android/server/backup/transport/TransportStats.java
diff --git a/services/backup/java/com/android/server/backup/transport/TransportUtils.java b/services/backup/backuplib/java/com/android/server/backup/transport/TransportUtils.java
similarity index 100%
rename from services/backup/java/com/android/server/backup/transport/TransportUtils.java
rename to services/backup/backuplib/java/com/android/server/backup/transport/TransportUtils.java
diff --git a/services/backup/java/com/android/server/backup/TransportManager.java b/services/backup/java/com/android/server/backup/TransportManager.java
deleted file mode 100644
index 30ce4cf..0000000
--- a/services/backup/java/com/android/server/backup/TransportManager.java
+++ /dev/null
@@ -1,727 +0,0 @@
-/*
- * 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.backup;
-
-import android.annotation.Nullable;
-import android.annotation.UserIdInt;
-import android.annotation.WorkerThread;
-import android.app.backup.BackupManager;
-import android.app.backup.BackupTransport;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.os.Bundle;
-import android.os.RemoteException;
-import android.util.ArrayMap;
-import android.util.ArraySet;
-import android.util.Slog;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.backup.IBackupTransport;
-import com.android.internal.util.Preconditions;
-import com.android.server.backup.transport.OnTransportRegisteredListener;
-import com.android.server.backup.transport.TransportClient;
-import com.android.server.backup.transport.TransportClientManager;
-import com.android.server.backup.transport.TransportConnectionListener;
-import com.android.server.backup.transport.TransportNotAvailableException;
-import com.android.server.backup.transport.TransportNotRegisteredException;
-import com.android.server.backup.transport.TransportStats;
-
-import java.io.PrintWriter;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Consumer;
-import java.util.function.Predicate;
-
-/** Handles in-memory bookkeeping of all BackupTransport objects. */
-public class TransportManager {
-    private static final String TAG = "BackupTransportManager";
-
-    @VisibleForTesting
-    public static final String SERVICE_ACTION_TRANSPORT_HOST = "android.backup.TRANSPORT_HOST";
-
-    private final Intent mTransportServiceIntent = new Intent(SERVICE_ACTION_TRANSPORT_HOST);
-    private final @UserIdInt int mUserId;
-    private final PackageManager mPackageManager;
-    private final Set<ComponentName> mTransportWhitelist;
-    private final TransportClientManager mTransportClientManager;
-    private final TransportStats mTransportStats;
-    private OnTransportRegisteredListener mOnTransportRegisteredListener = (c, n) -> {};
-
-    /**
-     * Lock for registered transports and currently selected transport.
-     *
-     * <p><b>Warning:</b> No calls to {@link IBackupTransport} or calls that result in transport
-     * code being executed such as {@link TransportClient#connect(String)}} and its variants should
-     * be made with this lock held, risk of deadlock.
-     */
-    private final Object mTransportLock = new Object();
-
-    /** @see #getRegisteredTransportNames() */
-    @GuardedBy("mTransportLock")
-    private final Map<ComponentName, TransportDescription> mRegisteredTransportsDescriptionMap =
-            new ArrayMap<>();
-
-    @GuardedBy("mTransportLock")
-    @Nullable
-    private volatile String mCurrentTransportName;
-
-    TransportManager(@UserIdInt int userId, Context context, Set<ComponentName> whitelist,
-            String selectedTransport) {
-        mUserId = userId;
-        mPackageManager = context.getPackageManager();
-        mTransportWhitelist = Preconditions.checkNotNull(whitelist);
-        mCurrentTransportName = selectedTransport;
-        mTransportStats = new TransportStats();
-        mTransportClientManager = new TransportClientManager(mUserId, context, mTransportStats);
-    }
-
-    @VisibleForTesting
-    TransportManager(
-            @UserIdInt int userId,
-            Context context,
-            Set<ComponentName> whitelist,
-            String selectedTransport,
-            TransportClientManager transportClientManager) {
-        mUserId = userId;
-        mPackageManager = context.getPackageManager();
-        mTransportWhitelist = Preconditions.checkNotNull(whitelist);
-        mCurrentTransportName = selectedTransport;
-        mTransportStats = new TransportStats();
-        mTransportClientManager = transportClientManager;
-    }
-
-    /* Sets a listener to be called whenever a transport is registered. */
-    public void setOnTransportRegisteredListener(OnTransportRegisteredListener listener) {
-        mOnTransportRegisteredListener = listener;
-    }
-
-    @WorkerThread
-    void onPackageAdded(String packageName) {
-        registerTransportsFromPackage(packageName, transportComponent -> true);
-    }
-
-    void onPackageRemoved(String packageName) {
-        synchronized (mTransportLock) {
-            mRegisteredTransportsDescriptionMap.keySet().removeIf(fromPackageFilter(packageName));
-        }
-    }
-
-    @WorkerThread
-    void onPackageChanged(String packageName, String... components) {
-        // Unfortunately this can't be atomic because we risk a deadlock if
-        // registerTransportsFromPackage() is put inside the synchronized block
-        Set<ComponentName> transportComponents = new ArraySet<>(components.length);
-        for (String componentName : components) {
-            transportComponents.add(new ComponentName(packageName, componentName));
-        }
-        synchronized (mTransportLock) {
-            mRegisteredTransportsDescriptionMap.keySet().removeIf(transportComponents::contains);
-        }
-        registerTransportsFromPackage(packageName, transportComponents::contains);
-    }
-
-    /**
-     * Returns the {@link ComponentName}s of the registered transports.
-     *
-     * <p>A *registered* transport is a transport that satisfies intent with action
-     * android.backup.TRANSPORT_HOST, returns true for {@link #isTransportTrusted(ComponentName)}
-     * and that we have successfully connected to once.
-     */
-    ComponentName[] getRegisteredTransportComponents() {
-        synchronized (mTransportLock) {
-            return mRegisteredTransportsDescriptionMap
-                    .keySet()
-                    .toArray(new ComponentName[mRegisteredTransportsDescriptionMap.size()]);
-        }
-    }
-
-    /**
-     * Returns the names of the registered transports.
-     *
-     * @see #getRegisteredTransportComponents()
-     */
-    String[] getRegisteredTransportNames() {
-        synchronized (mTransportLock) {
-            String[] transportNames = new String[mRegisteredTransportsDescriptionMap.size()];
-            int i = 0;
-            for (TransportDescription description : mRegisteredTransportsDescriptionMap.values()) {
-                transportNames[i] = description.name;
-                i++;
-            }
-            return transportNames;
-        }
-    }
-
-    /** Returns a set with the whitelisted transports. */
-    Set<ComponentName> getTransportWhitelist() {
-        return mTransportWhitelist;
-    }
-
-    /** Returns the name of the selected transport or {@code null} if no transport selected. */
-    @Nullable
-    public String getCurrentTransportName() {
-        return mCurrentTransportName;
-    }
-
-    /**
-     * Returns the {@link ComponentName} of the host service of the selected transport or
-     * {@code null} if no transport selected.
-     *
-     * @throws TransportNotRegisteredException if the selected transport is not registered.
-     */
-    @Nullable
-    public ComponentName getCurrentTransportComponent()
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            if (mCurrentTransportName == null) {
-                return null;
-            }
-            return getRegisteredTransportComponentOrThrowLocked(mCurrentTransportName);
-        }
-    }
-
-    /**
-     * Returns the transport name associated with {@code transportComponent}.
-     *
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    public String getTransportName(ComponentName transportComponent)
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportDescriptionOrThrowLocked(transportComponent).name;
-        }
-    }
-
-    /**
-     * Retrieves the transport dir name of {@code transportComponent}.
-     *
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    public String getTransportDirName(ComponentName transportComponent)
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportDescriptionOrThrowLocked(transportComponent)
-                    .transportDirName;
-        }
-    }
-
-    /**
-     * Retrieves the transport dir name of {@code transportName}.
-     *
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    public String getTransportDirName(String transportName) throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportDescriptionOrThrowLocked(transportName).transportDirName;
-        }
-    }
-
-    /**
-     * Retrieves the configuration intent of {@code transportName}.
-     *
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    @Nullable
-    public Intent getTransportConfigurationIntent(String transportName)
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
-                    .configurationIntent;
-        }
-    }
-
-    /**
-     * Retrieves the current destination string of {@code transportName}.
-     *
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    public String getTransportCurrentDestinationString(String transportName)
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
-                    .currentDestinationString;
-        }
-    }
-
-    /**
-     * Retrieves the data management intent of {@code transportName}.
-     *
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    @Nullable
-    public Intent getTransportDataManagementIntent(String transportName)
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
-                    .dataManagementIntent;
-        }
-    }
-
-    /**
-     * Retrieves the data management label of {@code transportName}.
-     *
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    @Nullable
-    public CharSequence getTransportDataManagementLabel(String transportName)
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportDescriptionOrThrowLocked(transportName)
-                    .dataManagementLabel;
-        }
-    }
-
-    /* Returns true if the transport identified by {@code transportName} is registered. */
-    public boolean isTransportRegistered(String transportName) {
-        synchronized (mTransportLock) {
-            return getRegisteredTransportEntryLocked(transportName) != null;
-        }
-    }
-
-    /**
-     * Execute {@code transportConsumer} for each registered transport passing the transport name.
-     * This is called with an internal lock held, ensuring that the transport will remain registered
-     * while {@code transportConsumer} is being executed. Don't do heavy operations in {@code
-     * transportConsumer}.
-     *
-     * <p><b>Warning:</b> Do NOT make any calls to {@link IBackupTransport} or call any variants of
-     * {@link TransportClient#connect(String)} here, otherwise you risk deadlock.
-     */
-    public void forEachRegisteredTransport(Consumer<String> transportConsumer) {
-        synchronized (mTransportLock) {
-            for (TransportDescription transportDescription :
-                    mRegisteredTransportsDescriptionMap.values()) {
-                transportConsumer.accept(transportDescription.name);
-            }
-        }
-    }
-
-    /**
-     * Updates given values for the transport already registered and identified with {@param
-     * transportComponent}. If the transport is not registered it will log and return.
-     */
-    public void updateTransportAttributes(
-            ComponentName transportComponent,
-            String name,
-            @Nullable Intent configurationIntent,
-            String currentDestinationString,
-            @Nullable Intent dataManagementIntent,
-            @Nullable CharSequence dataManagementLabel) {
-        synchronized (mTransportLock) {
-            TransportDescription description =
-                    mRegisteredTransportsDescriptionMap.get(transportComponent);
-            if (description == null) {
-                Slog.e(TAG, "Transport " + name + " not registered tried to change description");
-                return;
-            }
-            description.name = name;
-            description.configurationIntent = configurationIntent;
-            description.currentDestinationString = currentDestinationString;
-            description.dataManagementIntent = dataManagementIntent;
-            description.dataManagementLabel = dataManagementLabel;
-            Slog.d(TAG, "Transport " + name + " updated its attributes");
-        }
-    }
-
-    @GuardedBy("mTransportLock")
-    private ComponentName getRegisteredTransportComponentOrThrowLocked(String transportName)
-            throws TransportNotRegisteredException {
-        ComponentName transportComponent = getRegisteredTransportComponentLocked(transportName);
-        if (transportComponent == null) {
-            throw new TransportNotRegisteredException(transportName);
-        }
-        return transportComponent;
-    }
-
-    @GuardedBy("mTransportLock")
-    private TransportDescription getRegisteredTransportDescriptionOrThrowLocked(
-            ComponentName transportComponent) throws TransportNotRegisteredException {
-        TransportDescription description =
-                mRegisteredTransportsDescriptionMap.get(transportComponent);
-        if (description == null) {
-            throw new TransportNotRegisteredException(transportComponent);
-        }
-        return description;
-    }
-
-    @GuardedBy("mTransportLock")
-    private TransportDescription getRegisteredTransportDescriptionOrThrowLocked(
-            String transportName) throws TransportNotRegisteredException {
-        TransportDescription description = getRegisteredTransportDescriptionLocked(transportName);
-        if (description == null) {
-            throw new TransportNotRegisteredException(transportName);
-        }
-        return description;
-    }
-
-    @GuardedBy("mTransportLock")
-    @Nullable
-    private ComponentName getRegisteredTransportComponentLocked(String transportName) {
-        Map.Entry<ComponentName, TransportDescription> entry =
-                getRegisteredTransportEntryLocked(transportName);
-        return (entry == null) ? null : entry.getKey();
-    }
-
-    @GuardedBy("mTransportLock")
-    @Nullable
-    private TransportDescription getRegisteredTransportDescriptionLocked(String transportName) {
-        Map.Entry<ComponentName, TransportDescription> entry =
-                getRegisteredTransportEntryLocked(transportName);
-        return (entry == null) ? null : entry.getValue();
-    }
-
-    @GuardedBy("mTransportLock")
-    @Nullable
-    private Map.Entry<ComponentName, TransportDescription> getRegisteredTransportEntryLocked(
-            String transportName) {
-        for (Map.Entry<ComponentName, TransportDescription> entry :
-                mRegisteredTransportsDescriptionMap.entrySet()) {
-            TransportDescription description = entry.getValue();
-            if (transportName.equals(description.name)) {
-                return entry;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Returns a {@link TransportClient} for {@code transportName} or {@code null} if not
-     * registered.
-     *
-     * @param transportName The name of the transport.
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     * @return A {@link TransportClient} or null if not registered.
-     */
-    @Nullable
-    public TransportClient getTransportClient(String transportName, String caller) {
-        try {
-            return getTransportClientOrThrow(transportName, caller);
-        } catch (TransportNotRegisteredException e) {
-            Slog.w(TAG, "Transport " + transportName + " not registered");
-            return null;
-        }
-    }
-
-    /**
-     * Returns a {@link TransportClient} for {@code transportName} or throws if not registered.
-     *
-     * @param transportName The name of the transport.
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     * @return A {@link TransportClient}.
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     */
-    public TransportClient getTransportClientOrThrow(String transportName, String caller)
-            throws TransportNotRegisteredException {
-        synchronized (mTransportLock) {
-            ComponentName component = getRegisteredTransportComponentLocked(transportName);
-            if (component == null) {
-                throw new TransportNotRegisteredException(transportName);
-            }
-            return mTransportClientManager.getTransportClient(component, caller);
-        }
-    }
-
-    /**
-     * Returns a {@link TransportClient} for the current transport or {@code null} if not
-     * registered.
-     *
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     * @return A {@link TransportClient} or null if not registered.
-     * @throws IllegalStateException if no transport is selected.
-     */
-    @Nullable
-    public TransportClient getCurrentTransportClient(String caller) {
-        if (mCurrentTransportName == null) {
-            throw new IllegalStateException("No transport selected");
-        }
-        synchronized (mTransportLock) {
-            return getTransportClient(mCurrentTransportName, caller);
-        }
-    }
-
-    /**
-     * Returns a {@link TransportClient} for the current transport or throws if not registered.
-     *
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     * @return A {@link TransportClient}.
-     * @throws TransportNotRegisteredException if the transport is not registered.
-     * @throws IllegalStateException if no transport is selected.
-     */
-    public TransportClient getCurrentTransportClientOrThrow(String caller)
-            throws TransportNotRegisteredException {
-        if (mCurrentTransportName == null) {
-            throw new IllegalStateException("No transport selected");
-        }
-        synchronized (mTransportLock) {
-            return getTransportClientOrThrow(mCurrentTransportName, caller);
-        }
-    }
-
-    /**
-     * Disposes of the {@link TransportClient}.
-     *
-     * @param transportClient The {@link TransportClient} to be disposed of.
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     */
-    public void disposeOfTransportClient(TransportClient transportClient, String caller) {
-        mTransportClientManager.disposeOfTransportClient(transportClient, caller);
-    }
-
-    /**
-     * Sets {@code transportName} as selected transport and returns previously selected transport
-     * name. If there was no previous transport it returns null.
-     *
-     * <p>You should NOT call this method in new code. This won't make any checks against {@code
-     * transportName}, putting any operation at risk of a {@link TransportNotRegisteredException} or
-     * another error at the time it's being executed.
-     *
-     * <p>{@link Deprecated} as public, this method can be used as private.
-     */
-    @Deprecated
-    @Nullable
-    String selectTransport(String transportName) {
-        synchronized (mTransportLock) {
-            String prevTransport = mCurrentTransportName;
-            mCurrentTransportName = transportName;
-            return prevTransport;
-        }
-    }
-
-    /**
-     * Tries to register the transport if not registered. If successful also selects the transport.
-     *
-     * @param transportComponent Host of the transport.
-     * @return One of {@link BackupManager#SUCCESS}, {@link BackupManager#ERROR_TRANSPORT_INVALID}
-     *     or {@link BackupManager#ERROR_TRANSPORT_UNAVAILABLE}.
-     */
-    @WorkerThread
-    public int registerAndSelectTransport(ComponentName transportComponent) {
-        // If it's already registered we select and return
-        synchronized (mTransportLock) {
-            try {
-                selectTransport(getTransportName(transportComponent));
-                return BackupManager.SUCCESS;
-            } catch (TransportNotRegisteredException e) {
-                // Fall through and release lock
-            }
-        }
-
-        // We can't call registerTransport() with the transport lock held
-        int result = registerTransport(transportComponent);
-        if (result != BackupManager.SUCCESS) {
-            return result;
-        }
-        synchronized (mTransportLock) {
-            try {
-                selectTransport(getTransportName(transportComponent));
-                return BackupManager.SUCCESS;
-            } catch (TransportNotRegisteredException e) {
-                Slog.wtf(TAG, "Transport got unregistered");
-                return BackupManager.ERROR_TRANSPORT_UNAVAILABLE;
-            }
-        }
-    }
-
-    @WorkerThread
-    public void registerTransports() {
-        registerTransportsForIntent(mTransportServiceIntent, transportComponent -> true);
-    }
-
-    @WorkerThread
-    private void registerTransportsFromPackage(
-            String packageName, Predicate<ComponentName> transportComponentFilter) {
-        try {
-            mPackageManager.getPackageInfoAsUser(packageName, 0, mUserId);
-        } catch (PackageManager.NameNotFoundException e) {
-            Slog.e(TAG, "Trying to register transports from package not found " + packageName);
-            return;
-        }
-
-        registerTransportsForIntent(
-                new Intent(mTransportServiceIntent).setPackage(packageName),
-                transportComponentFilter.and(fromPackageFilter(packageName)));
-    }
-
-    @WorkerThread
-    private void registerTransportsForIntent(
-            Intent intent, Predicate<ComponentName> transportComponentFilter) {
-        List<ResolveInfo> hosts =
-                mPackageManager.queryIntentServicesAsUser(intent, 0, mUserId);
-        if (hosts == null) {
-            return;
-        }
-        for (ResolveInfo host : hosts) {
-            ComponentName transportComponent = host.serviceInfo.getComponentName();
-            if (transportComponentFilter.test(transportComponent)
-                    && isTransportTrusted(transportComponent)) {
-                registerTransport(transportComponent);
-            }
-        }
-    }
-
-    /** Transport has to be whitelisted and privileged. */
-    private boolean isTransportTrusted(ComponentName transport) {
-        if (!mTransportWhitelist.contains(transport)) {
-            Slog.w(
-                    TAG,
-                    "BackupTransport " + transport.flattenToShortString() + " not whitelisted.");
-            return false;
-        }
-        try {
-            PackageInfo packInfo =
-                    mPackageManager.getPackageInfoAsUser(transport.getPackageName(), 0, mUserId);
-            if ((packInfo.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
-                    == 0) {
-                Slog.w(TAG, "Transport package " + transport.getPackageName() + " not privileged");
-                return false;
-            }
-        } catch (PackageManager.NameNotFoundException e) {
-            Slog.w(TAG, "Package not found.", e);
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * Tries to register transport represented by {@code transportComponent}.
-     *
-     * <p><b>Warning:</b> Don't call this with the transport lock held.
-     *
-     * @param transportComponent Host of the transport that we want to register.
-     * @return One of {@link BackupManager#SUCCESS}, {@link BackupManager#ERROR_TRANSPORT_INVALID}
-     *     or {@link BackupManager#ERROR_TRANSPORT_UNAVAILABLE}.
-     */
-    @WorkerThread
-    private int registerTransport(ComponentName transportComponent) {
-        checkCanUseTransport();
-
-        if (!isTransportTrusted(transportComponent)) {
-            return BackupManager.ERROR_TRANSPORT_INVALID;
-        }
-
-        String transportString = transportComponent.flattenToShortString();
-        String callerLogString = "TransportManager.registerTransport()";
-
-        Bundle extras = new Bundle();
-        extras.putBoolean(BackupTransport.EXTRA_TRANSPORT_REGISTRATION, true);
-
-        TransportClient transportClient =
-                mTransportClientManager.getTransportClient(
-                        transportComponent, extras, callerLogString);
-        final IBackupTransport transport;
-        try {
-            transport = transportClient.connectOrThrow(callerLogString);
-        } catch (TransportNotAvailableException e) {
-            Slog.e(TAG, "Couldn't connect to transport " + transportString + " for registration");
-            mTransportClientManager.disposeOfTransportClient(transportClient, callerLogString);
-            return BackupManager.ERROR_TRANSPORT_UNAVAILABLE;
-        }
-
-        int result;
-        try {
-            String transportName = transport.name();
-            String transportDirName = transport.transportDirName();
-            registerTransport(transportComponent, transport);
-            // If registerTransport() hasn't thrown...
-            Slog.d(TAG, "Transport " + transportString + " registered");
-            mOnTransportRegisteredListener.onTransportRegistered(transportName, transportDirName);
-            result = BackupManager.SUCCESS;
-        } catch (RemoteException e) {
-            Slog.e(TAG, "Transport " + transportString + " died while registering");
-            result = BackupManager.ERROR_TRANSPORT_UNAVAILABLE;
-        }
-
-        mTransportClientManager.disposeOfTransportClient(transportClient, callerLogString);
-        return result;
-    }
-
-    /** If {@link RemoteException} is thrown the transport is guaranteed to not be registered. */
-    private void registerTransport(ComponentName transportComponent, IBackupTransport transport)
-            throws RemoteException {
-        checkCanUseTransport();
-
-        TransportDescription description =
-                new TransportDescription(
-                        transport.name(),
-                        transport.transportDirName(),
-                        transport.configurationIntent(),
-                        transport.currentDestinationString(),
-                        transport.dataManagementIntent(),
-                        transport.dataManagementIntentLabel());
-        synchronized (mTransportLock) {
-            mRegisteredTransportsDescriptionMap.put(transportComponent, description);
-        }
-    }
-
-    private void checkCanUseTransport() {
-        Preconditions.checkState(
-                !Thread.holdsLock(mTransportLock), "Can't call transport with transport lock held");
-    }
-
-    public void dumpTransportClients(PrintWriter pw) {
-        mTransportClientManager.dump(pw);
-    }
-
-    public void dumpTransportStats(PrintWriter pw) {
-        mTransportStats.dump(pw);
-    }
-
-    private static Predicate<ComponentName> fromPackageFilter(String packageName) {
-        return transportComponent -> packageName.equals(transportComponent.getPackageName());
-    }
-
-    private static class TransportDescription {
-        private String name;
-        private final String transportDirName;
-        @Nullable private Intent configurationIntent;
-        private String currentDestinationString;
-        @Nullable private Intent dataManagementIntent;
-        @Nullable private CharSequence dataManagementLabel;
-
-        private TransportDescription(
-                String name,
-                String transportDirName,
-                @Nullable Intent configurationIntent,
-                String currentDestinationString,
-                @Nullable Intent dataManagementIntent,
-                @Nullable CharSequence dataManagementLabel) {
-            this.name = name;
-            this.transportDirName = transportDirName;
-            this.configurationIntent = configurationIntent;
-            this.currentDestinationString = currentDestinationString;
-            this.dataManagementIntent = dataManagementIntent;
-            this.dataManagementLabel = dataManagementLabel;
-        }
-    }
-}
diff --git a/services/backup/java/com/android/server/backup/transport/TransportClientManager.java b/services/backup/java/com/android/server/backup/transport/TransportClientManager.java
deleted file mode 100644
index a4e9b10..0000000
--- a/services/backup/java/com/android/server/backup/transport/TransportClientManager.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * 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.backup.transport;
-
-import static com.android.server.backup.TransportManager.SERVICE_ACTION_TRANSPORT_HOST;
-import static com.android.server.backup.transport.TransportUtils.formatMessage;
-
-import android.annotation.UserIdInt;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-
-import com.android.server.backup.TransportManager;
-import com.android.server.backup.transport.TransportUtils.Priority;
-
-import java.io.PrintWriter;
-import java.util.Map;
-import java.util.WeakHashMap;
-
-/**
- * Manages the creation and disposal of {@link TransportClient}s. The only class that should use
- * this is {@link TransportManager}, all the other usages should go to {@link TransportManager}.
- */
-public class TransportClientManager {
-    private static final String TAG = "TransportClientManager";
-
-    private final @UserIdInt int mUserId;
-    private final Context mContext;
-    private final TransportStats mTransportStats;
-    private final Object mTransportClientsLock = new Object();
-    private int mTransportClientsCreated = 0;
-    private Map<TransportClient, String> mTransportClientsCallerMap = new WeakHashMap<>();
-
-    public TransportClientManager(@UserIdInt int userId, Context context,
-            TransportStats transportStats) {
-        mUserId = userId;
-        mContext = context;
-        mTransportStats = transportStats;
-    }
-
-    /**
-     * Retrieves a {@link TransportClient} for the transport identified by {@param
-     * transportComponent}.
-     *
-     * @param transportComponent The {@link ComponentName} of the transport.
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     * @return A {@link TransportClient}.
-     */
-    public TransportClient getTransportClient(ComponentName transportComponent, String caller) {
-        Intent bindIntent =
-                new Intent(SERVICE_ACTION_TRANSPORT_HOST).setComponent(transportComponent);
-
-        return getTransportClient(transportComponent, caller, bindIntent);
-    }
-
-    /**
-     * Retrieves a {@link TransportClient} for the transport identified by {@param
-     * transportComponent} whose binding intent will have the {@param extras} extras.
-     *
-     * @param transportComponent The {@link ComponentName} of the transport.
-     * @param extras A {@link Bundle} of extras to pass to the binding intent.
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     * @return A {@link TransportClient}.
-     */
-    public TransportClient getTransportClient(
-            ComponentName transportComponent, Bundle extras, String caller) {
-        Intent bindIntent =
-                new Intent(SERVICE_ACTION_TRANSPORT_HOST).setComponent(transportComponent);
-        bindIntent.putExtras(extras);
-
-        return getTransportClient(transportComponent, caller, bindIntent);
-    }
-
-    private TransportClient getTransportClient(
-            ComponentName transportComponent, String caller, Intent bindIntent) {
-        synchronized (mTransportClientsLock) {
-            TransportClient transportClient =
-                    new TransportClient(
-                            mUserId,
-                            mContext,
-                            mTransportStats,
-                            bindIntent,
-                            transportComponent,
-                            Integer.toString(mTransportClientsCreated),
-                            caller);
-            mTransportClientsCallerMap.put(transportClient, caller);
-            mTransportClientsCreated++;
-            TransportUtils.log(
-                    Priority.DEBUG,
-                    TAG,
-                    formatMessage(null, caller, "Retrieving " + transportClient));
-            return transportClient;
-        }
-    }
-
-    /**
-     * Disposes of the {@link TransportClient}.
-     *
-     * @param transportClient The {@link TransportClient} to be disposed of.
-     * @param caller A {@link String} identifying the caller for logging/debugging purposes. Check
-     *     {@link TransportClient#connectAsync(TransportConnectionListener, String)} for more
-     *     details.
-     */
-    public void disposeOfTransportClient(TransportClient transportClient, String caller) {
-        transportClient.unbind(caller);
-        transportClient.markAsDisposed();
-        synchronized (mTransportClientsLock) {
-            TransportUtils.log(
-                    Priority.DEBUG,
-                    TAG,
-                    formatMessage(null, caller, "Disposing of " + transportClient));
-            mTransportClientsCallerMap.remove(transportClient);
-        }
-    }
-
-    public void dump(PrintWriter pw) {
-        pw.println("Transport clients created: " + mTransportClientsCreated);
-        synchronized (mTransportClientsLock) {
-            pw.println("Current transport clients: " + mTransportClientsCallerMap.size());
-            for (TransportClient transportClient : mTransportClientsCallerMap.keySet()) {
-                String caller = mTransportClientsCallerMap.get(transportClient);
-                pw.println("    " + transportClient + " [" + caller + "]");
-                for (String logEntry : transportClient.getLogBuffer()) {
-                    pw.println("        " + logEntry);
-                }
-            }
-        }
-    }
-}
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 1643221..4e80977 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -1,3 +1,62 @@
+java_library {
+    name: "protolog-common",
+    srcs: [
+        "java/com/android/server/protolog/common/**/*.java",
+    ],
+    host_supported: true,
+}
+
+java_library {
+    name: "services.core.wm.protologgroups",
+    srcs: [
+        "java/com/android/server/wm/ProtoLogGroup.java",
+    ],
+    static_libs: ["protolog-common"],
+}
+
+genrule {
+    name: "services.core.protologsrc",
+    srcs: [":services.core.wm.protologgroups", "java/**/*.java"],
+    tools: ["protologtool"],
+    cmd: "$(location protologtool) transform-protolog-calls " +
+      "--protolog-class com.android.server.protolog.common.ProtoLog " +
+      "--protolog-impl-class com.android.server.protolog.ProtoLogImpl " +
+      "--loggroups-class com.android.server.wm.ProtoLogGroup " +
+      "--loggroups-jar $(location :services.core.wm.protologgroups) " +
+      "--output-srcjar $(out) " +
+      "$(locations java/**/*.java)",
+    out: ["services.core.protolog.srcjar"],
+}
+
+genrule {
+    name: "generate-protolog.json",
+    srcs: [":services.core.wm.protologgroups", "java/**/*.java"],
+    tools: ["protologtool"],
+    cmd: "$(location protologtool) generate-viewer-config " +
+      "--protolog-class com.android.server.protolog.common.ProtoLog " +
+      "--loggroups-class com.android.server.wm.ProtoLogGroup " +
+      "--loggroups-jar $(location :services.core.wm.protologgroups) " +
+      "--viewer-conf $(out) " +
+      "$(locations java/**/*.java)",
+    out: ["services.core.protolog.json"],
+}
+
+genrule {
+    name: "checked-protolog.json",
+    srcs: [
+        ":generate-protolog.json",
+        ":services.core.protolog.json",
+    ],
+    cmd: "cp $(location :generate-protolog.json) $(out) && " +
+      "{ ! (diff $(out) $(location :services.core.protolog.json) | grep -q '^<') || " +
+      "{ echo -e '\\n\\n################################################################\\n#\\n" +
+      "#  ERROR: ProtoLog viewer config is stale.  To update it, run:\\n#\\n" +
+      "#  cp $(location :generate-protolog.json) " +
+      "$(location :services.core.protolog.json)\\n#\\n" +
+      "################################################################\\n\\n' >&2 && false; } }",
+    out: ["services.core.protolog.json"],
+}
+
 java_library_static {
     name: "services.core.unboosted",
 
@@ -12,7 +71,7 @@
         ],
     },
     srcs: [
-        "java/**/*.java",
+        ":services.core.protologsrc",
         ":dumpstate_aidl",
         ":idmap2_aidl",
         ":installd_aidl",
@@ -34,6 +93,7 @@
 
     required: [
         "gps_debug.conf",
+        "protolog.conf.json.gz",
     ],
 
     static_libs: [
@@ -48,7 +108,7 @@
         "android.hardware.biometrics.fingerprint-V2.1-java",
         "android.hardware.oemlock-V1.0-java",
         "android.hardware.tetheroffload.control-V1.0-java",
-        "android.hardware.vibrator-V1.0-java",
+        "android.hardware.vibrator-V1.4-java",
         "android.hardware.configstore-V1.0-java",
         "android.hardware.contexthub-V1.0-java",
         "android.hidl.manager-V1.2-java",
@@ -81,3 +141,15 @@
     name: "gps_debug.conf",
     src: "java/com/android/server/location/gps_debug.conf",
 }
+
+genrule {
+    name: "services.core.json.gz",
+    srcs: [":checked-protolog.json"],
+    out: ["services.core.protolog.json.gz"],
+    cmd: "gzip < $(in) > $(out)",
+}
+
+prebuilt_etc {
+    name: "protolog.conf.json.gz",
+    src: ":services.core.json.gz",
+}
diff --git a/services/core/java/android/content/pm/PackageManagerInternal.java b/services/core/java/android/content/pm/PackageManagerInternal.java
new file mode 100644
index 0000000..1d666ad
--- /dev/null
+++ b/services/core/java/android/content/pm/PackageManagerInternal.java
@@ -0,0 +1,807 @@
+/*
+ * Copyright (C) 2015 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.content.pm;
+
+import android.annotation.AppIdInt;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.UserIdInt;
+import android.content.ComponentName;
+import android.content.Intent;
+import android.content.IntentSender;
+import android.content.pm.PackageManager.ApplicationInfoFlags;
+import android.content.pm.PackageManager.ComponentInfoFlags;
+import android.content.pm.PackageManager.PackageInfoFlags;
+import android.content.pm.PackageManager.ResolveInfoFlags;
+import android.os.Bundle;
+import android.os.PersistableBundle;
+import android.util.ArraySet;
+import android.util.SparseArray;
+
+import com.android.server.pm.PackageList;
+
+import java.io.IOException;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.List;
+import java.util.function.Consumer;
+
+/**
+ * Package manager local system service interface.
+ *
+ * @hide Only for use within the system server.
+ */
+public abstract class PackageManagerInternal {
+    public static final int PACKAGE_SYSTEM = 0;
+    public static final int PACKAGE_SETUP_WIZARD = 1;
+    public static final int PACKAGE_INSTALLER = 2;
+    public static final int PACKAGE_VERIFIER = 3;
+    public static final int PACKAGE_BROWSER = 4;
+    public static final int PACKAGE_SYSTEM_TEXT_CLASSIFIER = 5;
+    public static final int PACKAGE_PERMISSION_CONTROLLER = 6;
+    public static final int PACKAGE_WELLBEING = 7;
+    public static final int PACKAGE_DOCUMENTER = 8;
+    public static final int PACKAGE_CONFIGURATOR = 9;
+    public static final int PACKAGE_INCIDENT_REPORT_APPROVER = 10;
+    public static final int PACKAGE_APP_PREDICTOR = 11;
+    @IntDef(value = {
+        PACKAGE_SYSTEM,
+        PACKAGE_SETUP_WIZARD,
+        PACKAGE_INSTALLER,
+        PACKAGE_VERIFIER,
+        PACKAGE_BROWSER,
+        PACKAGE_SYSTEM_TEXT_CLASSIFIER,
+        PACKAGE_PERMISSION_CONTROLLER,
+        PACKAGE_WELLBEING,
+        PACKAGE_DOCUMENTER,
+        PACKAGE_CONFIGURATOR,
+        PACKAGE_INCIDENT_REPORT_APPROVER,
+        PACKAGE_APP_PREDICTOR,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface KnownPackage {}
+
+    /** Observer called whenever the list of packages changes */
+    public interface PackageListObserver {
+        /** A package was added to the system. */
+        void onPackageAdded(@NonNull String packageName, int uid);
+        /** A package was changed - either installed for a specific user or updated. */
+        default void onPackageChanged(@NonNull String packageName, int uid) {}
+        /** A package was removed from the system. */
+        void onPackageRemoved(@NonNull String packageName, int uid);
+    }
+
+    /**
+     * Called when the package for the default SMS handler changed
+     *
+     * @param packageName the new sms package
+     * @param userId user for which the change was made
+     */
+    public void onDefaultSmsAppChanged(String packageName, int userId) {}
+
+    /**
+     * Called when the package for the default sim call manager changed
+     *
+     * @param packageName the new sms package
+     * @param userId user for which the change was made
+     */
+    public void onDefaultSimCallManagerAppChanged(String packageName, int userId) {}
+
+    /**
+     * Sets a list of apps to keep in PM's internal data structures and as APKs even if no user has
+     * currently installed it. The apps are not preloaded.
+     * @param packageList List of package names to keep cached.
+     */
+    public abstract void setKeepUninstalledPackages(List<String> packageList);
+
+    /**
+     * Gets whether some of the permissions used by this package require a user
+     * review before any of the app components can run.
+     * @param packageName The package name for which to check.
+     * @param userId The user under which to check.
+     * @return True a permissions review is required.
+     */
+    public abstract boolean isPermissionsReviewRequired(String packageName, int userId);
+
+    /**
+     * Retrieve all of the information we know about a particular package/application.
+     * @param filterCallingUid The results will be filtered in the context of this UID instead
+     * of the calling UID.
+     * @see PackageManager#getPackageInfo(String, int)
+     */
+    public abstract PackageInfo getPackageInfo(String packageName,
+            @PackageInfoFlags int flags, int filterCallingUid, int userId);
+
+    /**
+     * Return a List of all application packages that are installed on the
+     * device, for a specific user. If flag GET_UNINSTALLED_PACKAGES has been
+     * set, a list of all applications including those deleted with
+     * {@code DONT_DELETE_DATA} (partially installed apps with data directory)
+     * will be returned.
+     *
+     * @param flags Additional option flags to modify the data returned.
+     * @param userId The user for whom the installed applications are to be
+     *            listed
+     * @param callingUid The uid of the original caller app
+     * @return A List of ApplicationInfo objects, one for each installed
+     *         application. In the unlikely case there are no installed
+     *         packages, an empty list is returned. If flag
+     *         {@code MATCH_UNINSTALLED_PACKAGES} is set, the application
+     *         information is retrieved from the list of uninstalled
+     *         applications (which includes installed applications as well as
+     *         applications with data directory i.e. applications which had been
+     *         deleted with {@code DONT_DELETE_DATA} flag set).
+     */
+    public abstract List<ApplicationInfo> getInstalledApplications(
+            @ApplicationInfoFlags int flags, @UserIdInt int userId, int callingUid);
+
+    /**
+     * Retrieve launcher extras for a suspended package provided to the system in
+     * {@link PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
+     * PersistableBundle, String)}.
+     *
+     * @param packageName The package for which to return launcher extras.
+     * @param userId The user for which to check.
+     * @return The launcher extras.
+     *
+     * @see PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
+     * PersistableBundle, String)
+     * @see PackageManager#isPackageSuspended()
+     */
+    public abstract Bundle getSuspendedPackageLauncherExtras(String packageName,
+            int userId);
+
+    /**
+     * Internal api to query the suspended state of a package.
+     * @param packageName The package to check.
+     * @param userId The user id to check for.
+     * @return {@code true} if the package is suspended, {@code false} otherwise.
+     * @see PackageManager#isPackageSuspended(String)
+     */
+    public abstract boolean isPackageSuspended(String packageName, int userId);
+
+    /**
+     * Get the name of the package that suspended the given package. Packages can be suspended by
+     * device administrators or apps holding {@link android.Manifest.permission#MANAGE_USERS} or
+     * {@link android.Manifest.permission#SUSPEND_APPS}.
+     *
+     * @param suspendedPackage The package that has been suspended.
+     * @param userId The user for which to check.
+     * @return Name of the package that suspended the given package. Returns {@code null} if the
+     * given package is not currently suspended and the platform package name - i.e.
+     * {@code "android"} - if the package was suspended by a device admin.
+     */
+    public abstract String getSuspendingPackage(String suspendedPackage, int userId);
+
+    /**
+     * Get the information describing the dialog to be shown to the user when they try to launch a
+     * suspended application.
+     *
+     * @param suspendedPackage The package that has been suspended.
+     * @param suspendingPackage
+     * @param userId The user for which to check.
+     * @return A {@link SuspendDialogInfo} object describing the dialog to be shown.
+     */
+    @Nullable
+    public abstract SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage,
+            String suspendingPackage, int userId);
+
+    /**
+     * Gets any distraction flags set via
+     * {@link PackageManager#setDistractingPackageRestrictions(String[], int)}
+     *
+     * @param packageName
+     * @param userId
+     * @return A bitwise OR of any of the {@link PackageManager.DistractionRestriction}
+     */
+    public abstract @PackageManager.DistractionRestriction int getDistractingPackageRestrictions(
+            String packageName, int userId);
+
+    /**
+     * Do a straight uid lookup for the given package/application in the given user.
+     * @see PackageManager#getPackageUidAsUser(String, int, int)
+     * @return The app's uid, or < 0 if the package was not found in that user
+     */
+    public abstract int getPackageUid(String packageName,
+            @PackageInfoFlags int flags, int userId);
+
+    /**
+     * Retrieve all of the information we know about a particular package/application.
+     * @param filterCallingUid The results will be filtered in the context of this UID instead
+     * of the calling UID.
+     * @see PackageManager#getApplicationInfo(String, int)
+     */
+    public abstract ApplicationInfo getApplicationInfo(String packageName,
+            @ApplicationInfoFlags int flags, int filterCallingUid, int userId);
+
+    /**
+     * Retrieve all of the information we know about a particular activity class.
+     * @param filterCallingUid The results will be filtered in the context of this UID instead
+     * of the calling UID.
+     * @see PackageManager#getActivityInfo(ComponentName, int)
+     */
+    public abstract ActivityInfo getActivityInfo(ComponentName component,
+            @ComponentInfoFlags int flags, int filterCallingUid, int userId);
+
+    /**
+     * Retrieve all activities that can be performed for the given intent.
+     * @param filterCallingUid The results will be filtered in the context of this UID instead
+     * of the calling UID.
+     * @see PackageManager#queryIntentActivities(Intent, int)
+     */
+    public abstract List<ResolveInfo> queryIntentActivities(Intent intent,
+            @ResolveInfoFlags int flags, int filterCallingUid, int userId);
+
+    /**
+     * Retrieve all services that can be performed for the given intent.
+     * @see PackageManager#queryIntentServices(Intent, int)
+     */
+    public abstract List<ResolveInfo> queryIntentServices(
+            Intent intent, int flags, int callingUid, int userId);
+
+    /**
+     * Interface to {@link com.android.server.pm.PackageManagerService#getHomeActivitiesAsUser}.
+     */
+    public abstract ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
+            int userId);
+
+    /**
+     * @return The default home activity component name.
+     */
+    public abstract ComponentName getDefaultHomeActivity(int userId);
+
+    /**
+     * Called by DeviceOwnerManagerService to set the package names of device owner and profile
+     * owners.
+     */
+    public abstract void setDeviceAndProfileOwnerPackages(
+            int deviceOwnerUserId, String deviceOwner, SparseArray<String> profileOwners);
+
+    /**
+     * Returns {@code true} if a given package can't be wiped. Otherwise, returns {@code false}.
+     */
+    public abstract boolean isPackageDataProtected(int userId, String packageName);
+
+    /**
+     * Returns {@code true} if a given package's state is protected, e.g. it cannot be force
+     * stopped, suspended, disabled or hidden. Otherwise, returns {@code false}.
+     */
+    public abstract boolean isPackageStateProtected(String packageName, int userId);
+
+    /**
+     * Returns {@code true} if a given package is installed as ephemeral. Otherwise, returns
+     * {@code false}.
+     */
+    public abstract boolean isPackageEphemeral(int userId, String packageName);
+
+    /**
+     * Gets whether the package was ever launched.
+     * @param packageName The package name.
+     * @param userId The user for which to check.
+     * @return Whether was launched.
+     * @throws IllegalArgumentException if the package is not found
+     */
+    public abstract boolean wasPackageEverLaunched(String packageName, int userId);
+
+    /**
+     * Retrieve the official name associated with a uid. This name is
+     * guaranteed to never change, though it is possible for the underlying
+     * uid to be changed. That is, if you are storing information about
+     * uids in persistent storage, you should use the string returned
+     * by this function instead of the raw uid.
+     *
+     * @param uid The uid for which you would like to retrieve a name.
+     * @return Returns a unique name for the given uid, or null if the
+     * uid is not currently assigned.
+     */
+    public abstract String getNameForUid(int uid);
+
+    /**
+     * Marks a package as installed (or not installed) for a given user.
+     *
+     * @param pkg the package whose installation is to be set
+     * @param userId the user for whom to set it
+     * @param installed the new installed state
+     * @return true if the installed state changed as a result
+     */
+    public abstract boolean setInstalled(PackageParser.Package pkg,
+            @UserIdInt int userId, boolean installed);
+
+    /**
+     * Request to perform the second phase of ephemeral resolution.
+     * @param responseObj The response of the first phase of ephemeral resolution
+     * @param origIntent The original intent that triggered ephemeral resolution
+     * @param resolvedType The resolved type of the intent
+     * @param callingPackage The name of the package requesting the ephemeral application
+     * @param verificationBundle Optional bundle to pass to the installer for additional
+     * verification
+     * @param userId The ID of the user that triggered ephemeral resolution
+     */
+    public abstract void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
+            Intent origIntent, String resolvedType, String callingPackage,
+            Bundle verificationBundle, int userId);
+
+    /**
+     * Grants implicit access based on an interaction between two apps. This grants the target app
+     * access to the calling application's package metadata.
+     * <p>
+     * When an application explicitly tries to interact with another application [via an
+     * activity, service or provider that is either declared in the caller's
+     * manifest via the {@code <queries>} tag or has been exposed via the target apps manifest using
+     * the {@code visibleToInstantApp} attribute], the target application must be able to see
+     * metadata about the calling app. If the calling application uses an implicit intent [ie
+     * action VIEW, category BROWSABLE], it remains hidden from the launched app.
+     * <p>
+     * @param userId the user
+     * @param intent the intent that triggered the grant
+     * @param callingUid The uid of the calling application
+     * @param targetAppId The app ID of the target application
+     */
+    public abstract void grantImplicitAccess(
+            @UserIdInt int userId, Intent intent, int callingUid,
+            @AppIdInt int targetAppId);
+
+    public abstract boolean isInstantAppInstallerComponent(ComponentName component);
+    /**
+     * Prunes instant apps and state associated with uninstalled
+     * instant apps according to the current platform policy.
+     */
+    public abstract void pruneInstantApps();
+
+    /**
+     * @return The SetupWizard package name.
+     */
+    public abstract String getSetupWizardPackageName();
+
+    public interface ExternalSourcesPolicy {
+
+        int USER_TRUSTED = 0;   // User has trusted the package to install apps
+        int USER_BLOCKED = 1;   // User has blocked the package to install apps
+        int USER_DEFAULT = 2;   // Default code to use when user response is unavailable
+
+        /**
+         * Checks the user preference for whether a package is trusted to request installs through
+         * package installer
+         *
+         * @param packageName The package to check for
+         * @param uid the uid in which the package is running
+         * @return {@link #USER_TRUSTED} if the user has trusted the package, {@link #USER_BLOCKED}
+         * if user has blocked requests from the package, {@link #USER_DEFAULT} if the user response
+         * is not yet available
+         */
+        int getPackageTrustedToInstallApps(String packageName, int uid);
+    }
+
+    public abstract void setExternalSourcesPolicy(ExternalSourcesPolicy policy);
+
+    /**
+     * Return true if the given package is a persistent app process.
+     */
+    public abstract boolean isPackagePersistent(String packageName);
+
+    /**
+     * Returns whether or not the given package represents a legacy system application released
+     * prior to runtime permissions.
+     */
+    public abstract boolean isLegacySystemApp(PackageParser.Package pkg);
+
+    /**
+     * Get all overlay packages for a user.
+     * @param userId The user for which to get the overlays.
+     * @return A list of overlay packages. An empty list is returned if the
+     *         user has no installed overlay packages.
+     */
+    public abstract List<PackageInfo> getOverlayPackages(int userId);
+
+    /**
+     * Get the names of all target packages for a user.
+     * @param userId The user for which to get the package names.
+     * @return A list of target package names. This list includes the "android" package.
+     */
+    public abstract List<String> getTargetPackageNames(int userId);
+
+    /**
+     * Set which overlay to use for a package.
+     * @param userId The user for which to update the overlays.
+     * @param targetPackageName The package name of the package for which to update the overlays.
+     * @param overlayPackageNames The complete list of overlay packages that should be enabled for
+     *                            the target. Previously enabled overlays not specified in the list
+     *                            will be disabled. Pass in null or an empty list to disable
+     *                            all overlays. The order of the items is significant if several
+     *                            overlays modify the same resource.
+     * @return true if all packages names were known by the package manager, false otherwise
+     */
+    public abstract boolean setEnabledOverlayPackages(int userId, String targetPackageName,
+            List<String> overlayPackageNames);
+
+    /**
+     * Resolves an activity intent, allowing instant apps to be resolved.
+     */
+    public abstract ResolveInfo resolveIntent(Intent intent, String resolvedType,
+            int flags, int userId, boolean resolveForStart, int filterCallingUid);
+
+    /**
+    * Resolves a service intent, allowing instant apps to be resolved.
+    */
+    public abstract ResolveInfo resolveService(Intent intent, String resolvedType,
+           int flags, int userId, int callingUid);
+
+   /**
+    * Resolves a content provider intent.
+    */
+    public abstract ProviderInfo resolveContentProvider(String name, int flags, int userId);
+
+    /**
+     * Track the creator of a new isolated uid.
+     * @param isolatedUid The newly created isolated uid.
+     * @param ownerUid The uid of the app that created the isolated process.
+     */
+    public abstract void addIsolatedUid(int isolatedUid, int ownerUid);
+
+    /**
+     * Track removal of an isolated uid.
+     * @param isolatedUid isolated uid that is no longer being used.
+     */
+    public abstract void removeIsolatedUid(int isolatedUid);
+
+    /**
+     * Return the taget SDK version for the app with the given UID.
+     */
+    public abstract int getUidTargetSdkVersion(int uid);
+
+    /**
+     * Return the taget SDK version for the app with the given package name.
+     */
+    public abstract int getPackageTargetSdkVersion(String packageName);
+
+    /** Whether the binder caller can access instant apps. */
+    public abstract boolean canAccessInstantApps(int callingUid, int userId);
+
+    /** Whether the binder caller can access the given component. */
+    public abstract boolean canAccessComponent(int callingUid, ComponentName component, int userId);
+
+    /**
+     * Returns {@code true} if a given package has instant application meta-data.
+     * Otherwise, returns {@code false}. Meta-data is state (eg. cookie, app icon, etc)
+     * associated with an instant app. It may be kept after the instant app has been uninstalled.
+     */
+    public abstract boolean hasInstantApplicationMetadata(String packageName, int userId);
+
+    /**
+     * Updates a package last used time.
+     */
+    public abstract void notifyPackageUse(String packageName, int reason);
+
+    /**
+     * Returns a package object for the given package name.
+     */
+    public abstract @Nullable PackageParser.Package getPackage(@NonNull String packageName);
+
+    /**
+     * Returns a package for the given UID. If the UID is part of a shared user ID, one
+     * of the packages will be chosen to be returned.
+     */
+    public abstract @Nullable PackageParser.Package getPackage(int uid);
+
+    /**
+     * Returns a list without a change observer.
+     *
+     * @see #getPackageList(PackageListObserver)
+     */
+    public @NonNull PackageList getPackageList() {
+        return getPackageList(null);
+    }
+
+    /**
+     * Returns the list of packages installed at the time of the method call.
+     * <p>The given observer is notified when the list of installed packages
+     * changes [eg. a package was installed or uninstalled]. It will not be
+     * notified if a package is updated.
+     * <p>The package list will not be updated automatically as packages are
+     * installed / uninstalled. Any changes must be handled within the observer.
+     */
+    public abstract @NonNull PackageList getPackageList(@Nullable PackageListObserver observer);
+
+    /**
+     * Removes the observer.
+     * <p>Generally not needed. {@link #getPackageList(PackageListObserver)} will automatically
+     * remove the observer.
+     * <p>Does nothing if the observer isn't currently registered.
+     * <p>Observers are notified asynchronously and it's possible for an observer to be
+     * invoked after its been removed.
+     */
+    public abstract void removePackageListObserver(@NonNull PackageListObserver observer);
+
+    /**
+     * Returns a package object for the disabled system package name.
+     */
+    public abstract @Nullable PackageParser.Package getDisabledSystemPackage(
+            @NonNull String packageName);
+
+    /**
+     * Returns the package name for the disabled system package.
+     *
+     * This is equivalent to
+     * {@link #getDisabledSystemPackage(String)}.{@link PackageParser.Package#packageName}
+     */
+    public abstract @Nullable String getDisabledSystemPackageName(@NonNull String packageName);
+
+    /**
+     * Returns whether or not the component is the resolver activity.
+     */
+    public abstract boolean isResolveActivityComponent(@NonNull ComponentInfo component);
+
+    /**
+     * Returns the package name for a known package.
+     */
+    public abstract @Nullable String getKnownPackageName(
+            @KnownPackage int knownPackage, int userId);
+
+    /**
+     * Returns whether the package is an instant app.
+     */
+    public abstract boolean isInstantApp(String packageName, int userId);
+
+    /**
+     * Returns whether the package is an instant app.
+     */
+    public abstract @Nullable String getInstantAppPackageName(int uid);
+
+    /**
+     * Returns whether or not access to the application should be filtered.
+     * <p>
+     * Access may be limited based upon whether the calling or target applications
+     * are instant applications.
+     *
+     * @see #canAccessInstantApps
+     */
+    public abstract boolean filterAppAccess(
+            @NonNull PackageParser.Package pkg, int callingUid, int userId);
+
+    /**
+     * Returns whether or not access to the application should be filtered.
+     *
+     * @see #filterAppAccess(android.content.pm.PackageParser.Package, int, int)
+     */
+    public abstract boolean filterAppAccess(
+            @NonNull String packageName, int callingUid, int userId);
+
+    /** Returns whether the given package was signed by the platform */
+    public abstract boolean isPlatformSigned(String pkg);
+
+    /**
+     * Returns true if it's still safe to restore data backed up from this app's version
+     * that was signed with restoringFromSigHash.
+     */
+    public abstract boolean isDataRestoreSafe(@NonNull byte[] restoringFromSigHash,
+            @NonNull String packageName);
+
+    /**
+     * Returns true if it's still safe to restore data backed up from this app's version
+     * that was signed with restoringFromSig.
+     */
+    public abstract boolean isDataRestoreSafe(@NonNull Signature restoringFromSig,
+            @NonNull String packageName);
+
+    /**
+     * Returns {@code true} if the the signing information for {@code clientUid} is sufficient
+     * to gain access gated by {@code capability}.  This can happen if the two UIDs have the
+     * same signing information, if the signing information {@code clientUid} indicates that
+     * it has the signing certificate for {@code serverUid} in its signing history (if it was
+     * previously signed by it), or if the signing certificate for {@code clientUid} is in the
+     * signing history for {@code serverUid} and with the {@code capability} specified.
+     */
+    public abstract boolean hasSignatureCapability(int serverUid, int clientUid,
+            @PackageParser.SigningDetails.CertCapabilities int capability);
+
+    /**
+     * Get appIds of all available apps which specified android:sharedUserId in the manifest.
+     *
+     * @return a SparseArray mapping from appId to it's sharedUserId.
+     */
+    public abstract SparseArray<String> getAppsWithSharedUserIds();
+
+    /**
+     * Get the value of attribute android:sharedUserId for the given packageName if specified,
+     * otherwise {@code null}.
+     */
+    public abstract String getSharedUserIdForPackage(@NonNull String packageName);
+
+    /**
+     * Get all packages which specified the given sharedUserId as android:sharedUserId attribute
+     * or an empty array if no package specified it.
+     */
+    public abstract String[] getPackagesForSharedUserId(@NonNull String sharedUserId, int userId);
+
+    /**
+     * Return if device is currently in a "core" boot environment, typically
+     * used to support full-disk encryption. Only apps marked with
+     * {@code coreApp} attribute are available.
+     */
+    public abstract boolean isOnlyCoreApps();
+
+    /**
+     * Make a best-effort attempt to provide the requested free disk space by
+     * deleting cached files.
+     *
+     * @throws IOException if the request was unable to be fulfilled.
+     */
+    public abstract void freeStorage(String volumeUuid, long bytes, int storageFlags)
+            throws IOException;
+
+    /** Returns {@code true} if the specified component is enabled and matches the given flags. */
+    public abstract boolean isEnabledAndMatches(@NonNull ComponentInfo info, int flags, int userId);
+
+    /** Returns {@code true} if the given user requires extra badging for icons. */
+    public abstract boolean userNeedsBadging(int userId);
+
+    /**
+     * Perform the given action for each package.
+     * Note that packages lock will be held while performin the actions.
+     *
+     * @param actionLocked action to be performed
+     */
+    public abstract void forEachPackage(Consumer<PackageParser.Package> actionLocked);
+
+    /**
+     * Perform the given action for each installed package for a user.
+     * Note that packages lock will be held while performin the actions.
+     */
+    public abstract void forEachInstalledPackage(
+            @NonNull Consumer<PackageParser.Package> actionLocked, @UserIdInt int userId);
+
+    /** Returns the list of enabled components */
+    public abstract ArraySet<String> getEnabledComponents(String packageName, int userId);
+
+    /** Returns the list of disabled components */
+    public abstract ArraySet<String> getDisabledComponents(String packageName, int userId);
+
+    /** Returns whether the given package is enabled for the given user */
+    public abstract @PackageManager.EnabledState int getApplicationEnabledState(
+            String packageName, int userId);
+
+    /**
+     * Extra field name for the token of a request to enable rollback for a
+     * package.
+     */
+    public static final String EXTRA_ENABLE_ROLLBACK_TOKEN =
+            "android.content.pm.extra.ENABLE_ROLLBACK_TOKEN";
+
+    /**
+     * Extra field name for the installFlags of a request to enable rollback
+     * for a package.
+     */
+    public static final String EXTRA_ENABLE_ROLLBACK_INSTALL_FLAGS =
+            "android.content.pm.extra.ENABLE_ROLLBACK_INSTALL_FLAGS";
+
+    /**
+     * Extra field name for the user id an install is associated with when
+     * enabling rollback.
+     */
+    public static final String EXTRA_ENABLE_ROLLBACK_USER =
+            "android.content.pm.extra.ENABLE_ROLLBACK_USER";
+
+    /**
+     * Used as the {@code enableRollbackCode} argument for
+     * {@link PackageManagerInternal#setEnableRollbackCode} to indicate that
+     * enabling rollback succeeded.
+     */
+    public static final int ENABLE_ROLLBACK_SUCCEEDED = 1;
+
+    /**
+     * Used as the {@code enableRollbackCode} argument for
+     * {@link PackageManagerInternal#setEnableRollbackCode} to indicate that
+     * enabling rollback failed.
+     */
+    public static final int ENABLE_ROLLBACK_FAILED = -1;
+
+    /**
+     * Allows the rollback manager listening to the
+     * {@link Intent#ACTION_PACKAGE_ENABLE_ROLLBACK enable rollback broadcast}
+     * to respond to the package manager. The response must include the
+     * {@code enableRollbackCode} which is one of
+     * {@link PackageManager#ENABLE_ROLLBACK_SUCCEEDED} or
+     * {@link PackageManager#ENABLE_ROLLBACK_FAILED}.
+     *
+     * @param token pending package identifier as passed via the
+     *            {@link PackageManager#EXTRA_ENABLE_ROLLBACK_TOKEN} Intent extra.
+     * @param enableRollbackCode the status code result of enabling rollback
+     * @throws SecurityException if the caller does not have the
+     *            PACKAGE_ROLLBACK_AGENT permission.
+     */
+    public abstract void setEnableRollbackCode(int token, int enableRollbackCode);
+
+    /**
+     * Ask the package manager to compile layouts in the given package.
+     */
+    public abstract boolean compileLayouts(String packageName);
+
+    /*
+     * Inform the package manager that the pending package install identified by
+     * {@code token} can be completed.
+     */
+    public abstract void finishPackageInstall(int token, boolean didLaunch);
+
+    /**
+     * Remove the default browser stored in the legacy package settings.
+     *
+     * @param userId the user id
+     *
+     * @return the package name of the default browser, or {@code null} if none
+     */
+    @Nullable
+    public abstract String removeLegacyDefaultBrowserPackageName(int userId);
+
+    /**
+     * Returns {@code true} if given {@code packageName} is an apex package.
+     */
+    public abstract boolean isApexPackage(String packageName);
+
+    /**
+     * Uninstalls given {@code packageName}.
+     *
+     * @param packageName apex package to uninstall.
+     * @param versionCode version of a package to uninstall.
+     * @param userId user to uninstall apex package for. Must be
+     *               {@link android.os.UserHandle#USER_ALL}, otherwise failure will be reported.
+     * @param intentSender a {@link IntentSender} to send result of an uninstall to.
+     */
+    public abstract void uninstallApex(String packageName, long versionCode, int userId,
+            IntentSender intentSender);
+
+    /**
+     * Get fingerprint of build that updated the runtime permissions for a user.
+     *
+     * @param userId The user to update
+     * @param fingerPrint The fingerprint to set
+     */
+    public abstract void setRuntimePermissionsFingerPrint(@NonNull String fingerPrint,
+            @UserIdInt int userId);
+
+    /**
+     * Migrates legacy obb data to its new location.
+     */
+    public abstract void migrateLegacyObbData();
+
+    /**
+     * Writes all package manager settings to disk. If {@code async} is {@code true}, the
+     * settings are written at some point in the future. Otherwise, the call blocks until
+     * the settings have been written.
+     */
+    public abstract void writeSettings(boolean async);
+
+    /**
+     * Writes all permission settings for the given set of users to disk. If {@code async}
+     * is {@code true}, the settings are written at some point in the future. Otherwise,
+     * the call blocks until the settings have been written.
+     */
+    public abstract void writePermissionSettings(@NonNull @UserIdInt int[] userIds, boolean async);
+
+    /**
+     * Returns {@code true} if the caller is the installer of record for the given package.
+     * Otherwise, {@code false}.
+     */
+    public abstract boolean isCallerInstallerOfRecord(
+            @NonNull PackageParser.Package pkg, int callingUid);
+
+    /** Returns whether or not default runtime permissions are granted for the given user */
+    public abstract boolean areDefaultRuntimePermissionsGranted(@UserIdInt int userId);
+
+    /** Sets the enforcement of reading external storage */
+    public abstract void setReadExternalStorageEnforced(boolean enforced);
+}
diff --git a/services/core/java/com/android/server/AnimationThread.java b/services/core/java/com/android/server/AnimationThread.java
index c607b1e..fad743e 100644
--- a/services/core/java/com/android/server/AnimationThread.java
+++ b/services/core/java/com/android/server/AnimationThread.java
@@ -64,7 +64,7 @@
      */
     @VisibleForTesting
     public static void dispose() {
-        synchronized (DisplayThread.class) {
+        synchronized (AnimationThread.class) {
             if (sInstance == null) {
                 return;
             }
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 18a8148..e0f60b4 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -495,7 +495,7 @@
       * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
       * arg2 = NetID.
       */
-    public static final int EVENT_NETWORK_TESTED = 41;
+    private static final int EVENT_NETWORK_TESTED = 41;
 
     /**
      * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
@@ -503,7 +503,7 @@
      * obj = PrivateDnsConfig
      * arg2 = netid
      */
-    public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
+    private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
 
     /**
      * Request ConnectivityService display provisioning notification.
@@ -511,12 +511,12 @@
      * arg2    = NetID.
      * obj     = Intent to be launched when notification selected by user, null if !arg1.
      */
-    public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
+    private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
 
     /**
      * This event can handle dismissing notification by given network id.
      */
-    public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
+    private static final int EVENT_TIMEOUT_NOTIFICATION = 44;
 
     /**
      * Used to specify whether a network should be used even if connectivity is partial.
@@ -531,13 +531,13 @@
      * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
      * should be shown.
      */
-    public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
+    private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
 
     /**
      * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
      * should be hidden.
      */
-    public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
+    private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
 
     private static String eventName(int what) {
         return sMagicDecoderRing.get(what, Integer.toString(what));
@@ -579,6 +579,8 @@
     // the set of network types that can only be enabled by system/sig apps
     private List mProtectedNetworks;
 
+    private Set<String> mWolSupportedInterfaces;
+
     private TelephonyManager mTelephonyManager;
 
     private KeepaliveTracker mKeepaliveTracker;
@@ -1055,6 +1057,10 @@
             }
         }
 
+        mWolSupportedInterfaces = new ArraySet(
+                mContext.getResources().getStringArray(
+                        com.android.internal.R.array.config_wakeonlan_supported_interfaces));
+
         mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
 
         mTethering = deps.makeTethering(mContext, mNMS, mStatsService, mPolicyManager,
@@ -1938,7 +1944,7 @@
             }
         }
 
-        return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
+        return NetworkPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
                 isNetworkMetered, isBackgroundRestricted);
     }
 
@@ -2204,7 +2210,7 @@
         final String iface = networkAgent.linkProperties.getInterfaceName();
 
         final int timeout;
-        int type = ConnectivityManager.TYPE_NONE;
+        final int type;
 
         if (networkAgent.networkCapabilities.hasTransport(
                 NetworkCapabilities.TRANSPORT_CELLULAR)) {
@@ -2219,11 +2225,10 @@
                                              15);
             type = ConnectivityManager.TYPE_WIFI;
         } else {
-            // do not track any other networks
-            timeout = 0;
+            return; // do not track any other networks
         }
 
-        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
+        if (timeout > 0 && iface != null) {
             try {
                 mNMS.addIdleTimer(iface, timeout, type);
             } catch (Exception e) {
@@ -2299,7 +2304,6 @@
 
     @VisibleForTesting
     protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
-    private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
 
     private void updateTcpBufferSizes(String tcpBufferSizes) {
         String[] values = null;
@@ -2375,7 +2379,8 @@
     }
 
     @Override
-    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
+    protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
+            @Nullable String[] args) {
         PriorityDump.dump(mPriorityDumper, fd, writer, args);
     }
 
@@ -2837,7 +2842,7 @@
 
         private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
             mNetId = nai.network.netId;
-            mNai = new AutodestructReference(nai);
+            mNai = new AutodestructReference<>(nai);
         }
 
         @Override
@@ -3269,7 +3274,8 @@
         final NetworkRequestInfo nri = mNetworkRequests.get(request);
 
         if (nri != null) {
-            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
+            if (Process.SYSTEM_UID != callingUid && Process.NETWORK_STACK_UID != callingUid
+                    && nri.mUid != callingUid) {
                 log(String.format("UID %d attempted to %s for unowned request %s",
                         callingUid, requestedOperation, nri));
                 return null;
@@ -4292,7 +4298,7 @@
         public void onChange(boolean selfChange, Uri uri) {
             final Integer what = mUriEventMap.get(uri);
             if (what != null) {
-                mHandler.obtainMessage(what.intValue()).sendToTarget();
+                mHandler.obtainMessage(what).sendToTarget();
             } else {
                 loge("No matching event to send for URI=" + uri);
             }
@@ -4729,12 +4735,10 @@
     private static final String ATTR_MNC = "mnc";
 
     private String getProvisioningUrlBaseFromFile() {
-        FileReader fileReader = null;
-        XmlPullParser parser = null;
+        XmlPullParser parser;
         Configuration config = mContext.getResources().getConfiguration();
 
-        try {
-            fileReader = new FileReader(mProvisioningUrlFile);
+        try (FileReader fileReader = new FileReader(mProvisioningUrlFile)) {
             parser = Xml.newPullParser();
             parser.setInput(fileReader);
             XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
@@ -4769,12 +4773,6 @@
             loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
         } catch (IOException e) {
             loge("I/O exception reading Carrier Provisioning Urls file: " + e);
-        } finally {
-            if (fileReader != null) {
-                try {
-                    fileReader.close();
-                } catch (IOException e) {}
-            }
         }
         return null;
     }
@@ -5104,8 +5102,8 @@
         }
     }
 
-    // This checks that the passed capabilities either do not request a specific SSID/SignalStrength
-    // , or the calling app has permission to do so.
+    // This checks that the passed capabilities either do not request a
+    // specific SSID/SignalStrength, or the calling app has permission to do so.
     private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
             int callerPid, int callerUid) {
         if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
@@ -5238,7 +5236,7 @@
                 final int uid = Binder.getCallingUid();
                 Integer uidReqs = mBandwidthRequests.get(uid);
                 if (uidReqs == null) {
-                    uidReqs = new Integer(0);
+                    uidReqs = 0;
                 }
                 mBandwidthRequests.put(uid, ++uidReqs);
             }
@@ -5572,7 +5570,7 @@
     }
 
     private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
-            LinkProperties oldLp) {
+            @NonNull LinkProperties oldLp) {
         int netId = networkAgent.network.netId;
 
         // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
@@ -5608,6 +5606,9 @@
         } else {
             updateProxy(newLp, oldLp);
         }
+
+        updateWakeOnLan(newLp);
+
         // TODO - move this check to cover the whole function
         if (!Objects.equals(newLp, oldLp)) {
             synchronized (networkAgent) {
@@ -5687,7 +5688,7 @@
      */
     private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
         // Compare the route diff to determine which routes should be added and removed.
-        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
+        CompareResult<RouteInfo> routeDiff = new CompareResult<>(
                 oldLp != null ? oldLp.getAllRoutes() : null,
                 newLp != null ? newLp.getAllRoutes() : null);
 
@@ -5706,7 +5707,7 @@
             }
         }
         for (RouteInfo route : routeDiff.added) {
-            if (route.hasGateway() == false) continue;
+            if (!route.hasGateway()) continue;
             if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
             try {
                 mNMS.addRoute(netId, route);
@@ -5778,6 +5779,10 @@
         }
     }
 
+    private void updateWakeOnLan(@NonNull LinkProperties lp) {
+        lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
+    }
+
     private int getNetworkPermission(NetworkCapabilities nc) {
         if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
             return INetd.PERMISSION_SYSTEM;
@@ -5935,8 +5940,8 @@
      *  3. the VPN is fully-routed
      *  4. the VPN interface is non-null
      *
-     * @See INetd#firewallAddUidInterfaceRules
-     * @See INetd#firewallRemoveUidInterfaceRules
+     * @see INetd#firewallAddUidInterfaceRules
+     * @see INetd#firewallRemoveUidInterfaceRules
      */
     private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
             LinkProperties lp) {
@@ -7051,9 +7056,9 @@
     }
 
     @Override
-    public void onShellCommand(FileDescriptor in, FileDescriptor out,
-            FileDescriptor err, String[] args, ShellCallback callback,
-            ResultReceiver resultReceiver) {
+    public void onShellCommand(@NonNull FileDescriptor in, @NonNull FileDescriptor out,
+            FileDescriptor err, @NonNull String[] args, ShellCallback callback,
+            @NonNull ResultReceiver resultReceiver) {
         (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
     }
 
diff --git a/services/core/java/com/android/server/GnssManagerService.java b/services/core/java/com/android/server/GnssManagerService.java
new file mode 100644
index 0000000..b6e619e
--- /dev/null
+++ b/services/core/java/com/android/server/GnssManagerService.java
@@ -0,0 +1,800 @@
+/*
+ * Copyright (C) 2019 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;
+
+import android.Manifest;
+import android.app.ActivityManager;
+import android.app.AppOpsManager;
+import android.content.Context;
+import android.location.GnssCapabilities;
+import android.location.GnssMeasurementCorrections;
+import android.location.IBatchedLocationCallback;
+import android.location.IGnssMeasurementsListener;
+import android.location.IGnssNavigationMessageListener;
+import android.location.IGnssStatusListener;
+import android.location.IGpsGeofenceHardware;
+import android.location.INetInitiatedListener;
+import android.location.Location;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.IInterface;
+import android.os.Process;
+import android.os.RemoteException;
+import android.stats.location.LocationStatsEnums;
+import android.util.ArrayMap;
+import android.util.Log;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.DumpUtils;
+import com.android.internal.util.IndentingPrintWriter;
+import com.android.server.LocationManagerServiceUtils.LinkedListener;
+import com.android.server.LocationManagerServiceUtils.LinkedListenerBase;
+import com.android.server.location.AbstractLocationProvider;
+import com.android.server.location.CallerIdentity;
+import com.android.server.location.GnssBatchingProvider;
+import com.android.server.location.GnssCapabilitiesProvider;
+import com.android.server.location.GnssLocationProvider;
+import com.android.server.location.GnssMeasurementCorrectionsProvider;
+import com.android.server.location.GnssMeasurementsProvider;
+import com.android.server.location.GnssNavigationMessageProvider;
+import com.android.server.location.GnssStatusListenerHelper;
+import com.android.server.location.RemoteListenerHelper;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+/** Manages Gnss providers and related Gnss functions for LocationManagerService. */
+public class GnssManagerService {
+    private static final String TAG = "LocationManagerService";
+    private static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
+
+    // Providers
+    private final GnssLocationProvider mGnssLocationProvider;
+    private final GnssStatusListenerHelper mGnssStatusProvider;
+    private final GnssMeasurementsProvider mGnssMeasurementsProvider;
+    private final GnssMeasurementCorrectionsProvider mGnssMeasurementCorrectionsProvider;
+    private final GnssNavigationMessageProvider mGnssNavigationMessageProvider;
+    private final GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
+    private final GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
+    private final GnssCapabilitiesProvider mGnssCapabilitiesProvider;
+    private final GnssBatchingProvider mGnssBatchingProvider;
+
+    private final INetInitiatedListener mNetInitiatedListener;
+    private final IGpsGeofenceHardware mGpsGeofenceProxy;
+    private final LocationManagerService mLocationManagerService;
+    private final LocationUsageLogger mLocationUsageLogger;
+
+    @GuardedBy("mGnssMeasurementsListeners")
+    private final ArrayMap<IBinder,
+            LinkedListener<IGnssMeasurementsListener>>
+            mGnssMeasurementsListeners = new ArrayMap<>();
+
+    @GuardedBy("mGnssNavigationMessageListeners")
+    private final ArrayMap<
+            IBinder, LinkedListener<IGnssNavigationMessageListener>>
+            mGnssNavigationMessageListeners = new ArrayMap<>();
+
+    @GuardedBy("mGnssStatusListeners")
+    private final ArrayMap<IBinder, LinkedListener<IGnssStatusListener>>
+            mGnssStatusListeners = new ArrayMap<>();
+
+    @GuardedBy("mGnssBatchingLock")
+    private IBatchedLocationCallback mGnssBatchingCallback;
+
+    @GuardedBy("mGnssBatchingLock")
+    private LinkedListener<IBatchedLocationCallback>
+            mGnssBatchingDeathCallback;
+
+    @GuardedBy("mGnssBatchingLock")
+    private boolean mGnssBatchingInProgress = false;
+
+    private final Object mGnssBatchingLock = new Object();
+    private final Context mContext;
+    private final Handler mHandler;
+
+    public GnssManagerService(LocationManagerService locationManagerService,
+            Context context,
+            AbstractLocationProvider.LocationProviderManager gnssProviderManager,
+            LocationUsageLogger locationUsageLogger) {
+        this(locationManagerService, context, new GnssLocationProvider(context, gnssProviderManager,
+                FgThread.getHandler().getLooper()), locationUsageLogger);
+    }
+
+    // Can use this constructor to inject GnssLocationProvider for testing
+    @VisibleForTesting
+    GnssManagerService(LocationManagerService locationManagerService,
+            Context context,
+            GnssLocationProvider gnssLocationProvider,
+            LocationUsageLogger locationUsageLogger) {
+        mContext = context;
+        mHandler = FgThread.getHandler();
+
+        mGnssLocationProvider =
+                gnssLocationProvider;
+
+        mGnssStatusProvider = mGnssLocationProvider.getGnssStatusProvider();
+        mGnssMeasurementsProvider = mGnssLocationProvider.getGnssMeasurementsProvider();
+        mGnssMeasurementCorrectionsProvider =
+                mGnssLocationProvider.getGnssMeasurementCorrectionsProvider();
+        mGnssNavigationMessageProvider = mGnssLocationProvider.getGnssNavigationMessageProvider();
+        mGnssSystemInfoProvider = mGnssLocationProvider.getGnssSystemInfoProvider();
+        mGnssMetricsProvider = mGnssLocationProvider.getGnssMetricsProvider();
+        mGnssCapabilitiesProvider = mGnssLocationProvider.getGnssCapabilitiesProvider();
+        mGnssBatchingProvider = mGnssLocationProvider.getGnssBatchingProvider();
+
+        mNetInitiatedListener = mGnssLocationProvider.getNetInitiatedListener();
+        mGpsGeofenceProxy = mGnssLocationProvider.getGpsGeofenceProxy();
+        mLocationManagerService = locationManagerService;
+        mLocationUsageLogger = locationUsageLogger;
+
+        registerUidListener();
+    }
+
+    public static boolean isGnssSupported() {
+        return GnssLocationProvider.isSupported();
+    }
+
+    private boolean hasGnssPermissions(String packageName) {
+        mContext.enforceCallingPermission(
+                Manifest.permission.ACCESS_FINE_LOCATION,
+                "Fine location permission not granted.");
+
+        int uid = Binder.getCallingUid();
+        long identity = Binder.clearCallingIdentity();
+        try {
+            return mContext.getSystemService(
+                    AppOpsManager.class).checkOp(AppOpsManager.OP_FINE_LOCATION, uid, packageName)
+                    == AppOpsManager.MODE_ALLOWED;
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
+    public GnssLocationProvider getGnssLocationProvider() {
+        return mGnssLocationProvider;
+    }
+
+    public IGpsGeofenceHardware getGpsGeofenceProxy() {
+        return mGpsGeofenceProxy;
+    }
+
+    /**
+     * Get year of GNSS hardware.
+     *
+     * @return year of GNSS hardware as an int if possible, otherwise zero
+     */
+    public int getGnssYearOfHardware() {
+        if (mGnssSystemInfoProvider != null) {
+            return mGnssSystemInfoProvider.getGnssYearOfHardware();
+        } else {
+            return 0;
+        }
+    }
+
+    /**
+     * Get model name of GNSS hardware.
+     *
+     * @return GNSS hardware model name as a string if possible, otherwise null
+     */
+    public String getGnssHardwareModelName() {
+        if (mGnssSystemInfoProvider != null) {
+            return mGnssSystemInfoProvider.getGnssHardwareModelName();
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Get GNSS hardware capabilities. The capabilities are described in {@link
+     * android.location.GnssCapabilities} and their integer values correspond to the
+     * bit positions in the returned {@code long} value.
+     *
+     * @param packageName name of requesting package
+     * @return capabilities supported by the GNSS chipset
+     */
+    public long getGnssCapabilities(String packageName) {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to obtain GNSS chipset capabilities.");
+        if (!hasGnssPermissions(packageName) || mGnssCapabilitiesProvider == null) {
+            return GnssCapabilities.INVALID_CAPABILITIES;
+        }
+        return mGnssCapabilitiesProvider.getGnssCapabilities();
+    }
+
+    /**
+     * Get size of GNSS batch (GNSS location results are batched together for power savings).
+     * Requires LOCATION_HARDWARE and GNSS permissions.
+     *
+     * @param packageName name of requesting package
+     * @return size of the GNSS batch collection
+     */
+    public int getGnssBatchSize(String packageName) {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to access hardware batching");
+
+        if (!hasGnssPermissions(packageName)) {
+            Log.e(TAG, "getGnssBatchSize called without GNSS permissions");
+            return 0;
+        }
+        if (mGnssBatchingProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not get GNSS batch size. GNSS batching provider "
+                            + "not available.");
+            return 0;
+        }
+
+        synchronized (mGnssBatchingLock) {
+            return mGnssBatchingProvider.getBatchSize();
+        }
+    }
+
+    /**
+     * Starts GNSS batch collection. GNSS positions are collected in a batch before being delivered
+     * as a collection.
+     *
+     * @param periodNanos    duration over which to collect GPS positions before delivering as a
+     *                       batch
+     * @param wakeOnFifoFull specifying whether to wake on full queue
+     * @param packageName    name of requesting package
+     * @return true of batch started successfully, false otherwise
+     */
+    public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to access hardware batching");
+
+        if (!hasGnssPermissions(packageName)) {
+            Log.e(TAG, "startGnssBatch called without GNSS permissions");
+            return false;
+        }
+        if (mGnssBatchingProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not start GNSS batching. GNSS batching provider "
+                            + "not available.");
+            return false;
+        }
+
+        synchronized (mGnssBatchingLock) {
+            if (mGnssBatchingInProgress) {
+                // Current design does not expect multiple starts to be called repeatedly
+                Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
+                // Try to clean up anyway, and continue
+                stopGnssBatch();
+            }
+
+            mGnssBatchingInProgress = true;
+            return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
+        }
+    }
+
+    /**
+     * Adds a GNSS batching callback for delivering GNSS location batch results.
+     *
+     * @param callback    called when batching operation is complete to deliver GPS positions
+     * @param packageName name of requesting package
+     * @return true if callback is successfully added, false otherwise
+     */
+    public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to access hardware batching");
+
+        if (!hasGnssPermissions(packageName)) {
+            Log.e(TAG, "addGnssBatchingCallback called without GNSS permissions");
+            return false;
+        }
+        if (mGnssBatchingProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not add GNSS batching callback. GNSS batching provider "
+                            + "not available.");
+            return false;
+        }
+
+        CallerIdentity callerIdentity =
+                new CallerIdentity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
+        synchronized (mGnssBatchingLock) {
+            mGnssBatchingCallback = callback;
+            mGnssBatchingDeathCallback =
+                    new LocationManagerServiceUtils.LinkedListener<>(
+                            callback,
+                            "BatchedLocationCallback",
+                            callerIdentity,
+                            (IBatchedLocationCallback listener) -> {
+                                stopGnssBatch();
+                                removeGnssBatchingCallback();
+                            });
+            if (!mGnssBatchingDeathCallback.linkToListenerDeathNotificationLocked(
+                    callback.asBinder())) {
+                return false;
+            }
+            return true;
+        }
+    }
+
+    /**
+     * Force flush GNSS location results from batch.
+     *
+     * @param packageName name of requesting package
+     */
+    public void flushGnssBatch(String packageName) {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to access hardware batching");
+
+        if (!hasGnssPermissions(packageName)) {
+            Log.e(TAG, "flushGnssBatch called without GNSS permissions");
+            return;
+        }
+
+        if (mGnssBatchingProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not flush GNSS batch. GNSS batching provider "
+                            + "not available.");
+            return;
+        }
+
+        synchronized (mGnssBatchingLock) {
+            if (!mGnssBatchingInProgress) {
+                Log.w(TAG, "flushGnssBatch called with no batch in progress");
+            }
+            mGnssBatchingProvider.flush();
+        }
+    }
+
+    /**
+     * Removes GNSS batching callback.
+     */
+    public void removeGnssBatchingCallback() {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to access hardware batching");
+
+        if (mGnssBatchingProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not add GNSS batching callback. GNSS batching provider "
+                            + "not available.");
+            return;
+        }
+
+        synchronized (mGnssBatchingLock) {
+            mGnssBatchingDeathCallback.unlinkFromListenerDeathNotificationLocked(
+                    mGnssBatchingCallback.asBinder());
+            mGnssBatchingCallback = null;
+            mGnssBatchingDeathCallback = null;
+        }
+    }
+
+    /**
+     * Stop GNSS batch collection.
+     *
+     * @return true if GNSS batch successfully stopped, false otherwise
+     */
+    public boolean stopGnssBatch() {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to access hardware batching");
+
+        if (mGnssBatchingProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not stop GNSS batch. GNSS batching provider "
+                            + "not available.");
+            return false;
+        }
+        synchronized (mGnssBatchingLock) {
+            mGnssBatchingInProgress = false;
+            return mGnssBatchingProvider.stop();
+        }
+    }
+
+    private void registerUidListener() {
+        mContext.getSystemService(
+                ActivityManager.class).addOnUidImportanceListener(
+                    (uid, importance) -> {
+                        // listener invoked on ui thread, move to our thread to reduce risk
+                        // of blocking ui thread
+                        mHandler.post(
+                                () -> {
+                                    onForegroundChanged(uid,
+                                            LocationManagerServiceUtils.isImportanceForeground(
+                                                    importance));
+                                });
+                    },
+                ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE);
+    }
+
+    private void onForegroundChanged(int uid, boolean foreground) {
+        synchronized (mGnssMeasurementsListeners) {
+            updateListenersOnForegroundChangedLocked(
+                    mGnssMeasurementsListeners,
+                    mGnssMeasurementsProvider,
+                    IGnssMeasurementsListener.Stub::asInterface,
+                    uid,
+                    foreground);
+        }
+        synchronized (mGnssNavigationMessageListeners) {
+            updateListenersOnForegroundChangedLocked(
+                    mGnssNavigationMessageListeners,
+                    mGnssNavigationMessageProvider,
+                    IGnssNavigationMessageListener.Stub::asInterface,
+                    uid,
+                    foreground);
+        }
+        synchronized (mGnssStatusListeners) {
+            updateListenersOnForegroundChangedLocked(
+                    mGnssStatusListeners,
+                    mGnssStatusProvider,
+                    IGnssStatusListener.Stub::asInterface,
+                    uid,
+                    foreground);
+        }
+    }
+
+    private <TListener extends IInterface> void updateListenersOnForegroundChangedLocked(
+            ArrayMap<IBinder, ? extends LinkedListenerBase>
+                    gnssDataListeners,
+            RemoteListenerHelper<TListener> gnssDataProvider,
+            Function<IBinder, TListener> mapBinderToListener,
+            int uid,
+            boolean foreground) {
+        for (Map.Entry<IBinder, ? extends LinkedListenerBase> entry :
+                gnssDataListeners.entrySet()) {
+            LinkedListenerBase linkedListener = entry.getValue();
+            CallerIdentity callerIdentity = linkedListener.getCallerIdentity();
+            if (callerIdentity.mUid != uid) {
+                continue;
+            }
+
+            if (D) {
+                Log.d(
+                        TAG,
+                        linkedListener.getListenerName()
+                                + " from uid "
+                                + uid
+                                + " is now "
+                                + LocationManagerServiceUtils.foregroundAsString(foreground));
+            }
+
+            TListener listener = mapBinderToListener.apply(entry.getKey());
+            if (foreground || mLocationManagerService.isThrottlingExemptLocked(callerIdentity)) {
+                gnssDataProvider.addListener(listener, callerIdentity);
+            } else {
+                gnssDataProvider.removeListener(listener);
+            }
+        }
+    }
+
+    private <TListener extends IInterface> boolean addGnssDataListenerLocked(
+            TListener listener,
+            String packageName,
+            String listenerName,
+            RemoteListenerHelper<TListener> gnssDataProvider,
+            ArrayMap<IBinder,
+                    LinkedListener<TListener>> gnssDataListeners,
+            Consumer<TListener> binderDeathCallback) {
+        if (!hasGnssPermissions(packageName)) {
+            Log.e(TAG, "addGnssDataListenerLocked called without GNSS permissions");
+            return false;
+        }
+
+        if (gnssDataProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not add GNSS data listener. GNSS data provider "
+                            + "not available.");
+            return false;
+        }
+
+        CallerIdentity callerIdentity =
+                new CallerIdentity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
+        LinkedListener<TListener> linkedListener =
+                new LocationManagerServiceUtils.LinkedListener<>(
+                        listener, listenerName, callerIdentity, binderDeathCallback);
+        IBinder binder = listener.asBinder();
+        if (!linkedListener.linkToListenerDeathNotificationLocked(binder)) {
+            return false;
+        }
+
+        gnssDataListeners.put(binder, linkedListener);
+        long identity = Binder.clearCallingIdentity();
+        try {
+            if (gnssDataProvider == mGnssMeasurementsProvider
+                    || gnssDataProvider == mGnssStatusProvider) {
+                mLocationUsageLogger.logLocationApiUsage(
+                        LocationStatsEnums.USAGE_STARTED,
+                        gnssDataProvider == mGnssMeasurementsProvider
+                                ? LocationStatsEnums.API_ADD_GNSS_MEASUREMENTS_LISTENER
+                                : LocationStatsEnums.API_REGISTER_GNSS_STATUS_CALLBACK,
+                        packageName,
+                        /* LocationRequest= */ null,
+                        /* hasListener= */ true,
+                        /* hasIntent= */ false,
+                        /* geofence= */ null,
+                        LocationManagerServiceUtils.getPackageImportance(packageName,
+                                mContext));
+            }
+            if (mLocationManagerService.isThrottlingExemptLocked(callerIdentity)
+                    || LocationManagerServiceUtils.isImportanceForeground(
+                    LocationManagerServiceUtils.getPackageImportance(packageName, mContext))) {
+                gnssDataProvider.addListener(listener, callerIdentity);
+            }
+            return true;
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
+    private <TListener extends IInterface> void removeGnssDataListener(
+            TListener listener,
+            RemoteListenerHelper<TListener> gnssDataProvider,
+            ArrayMap<IBinder,
+                    LinkedListener<TListener>> gnssDataListeners) {
+        if (gnssDataProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not remove GNSS data listener. GNSS data provider "
+                            + "not available.");
+            return;
+        }
+
+        IBinder binder = listener.asBinder();
+        LinkedListener<TListener> linkedListener =
+                gnssDataListeners.remove(binder);
+        if (linkedListener == null) {
+            return;
+        }
+        long identity = Binder.clearCallingIdentity();
+        try {
+            if (gnssDataProvider == mGnssMeasurementsProvider
+                    || gnssDataProvider == mGnssStatusProvider) {
+                mLocationUsageLogger.logLocationApiUsage(
+                        LocationStatsEnums.USAGE_ENDED,
+                        gnssDataProvider == mGnssMeasurementsProvider
+                                ? LocationStatsEnums.API_ADD_GNSS_MEASUREMENTS_LISTENER
+                                : LocationStatsEnums.API_REGISTER_GNSS_STATUS_CALLBACK,
+                        linkedListener.getCallerIdentity().mPackageName,
+                        /* LocationRequest= */ null,
+                        /* hasListener= */ true,
+                        /* hasIntent= */ false,
+                        /* geofence= */ null,
+                        LocationManagerServiceUtils.getPackageImportance(
+                                linkedListener.getCallerIdentity().mPackageName, mContext));
+            }
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+        linkedListener.unlinkFromListenerDeathNotificationLocked(binder);
+        gnssDataProvider.removeListener(listener);
+    }
+
+    /**
+     * Registers listener for GNSS status changes.
+     *
+     * @param listener    called when GNSS status changes
+     * @param packageName name of requesting package
+     * @return true if listener is successfully registered, false otherwise
+     */
+    public boolean registerGnssStatusCallback(IGnssStatusListener listener, String packageName) {
+        synchronized (mGnssStatusListeners) {
+            return addGnssDataListenerLocked(
+                    listener,
+                    packageName,
+                    "GnssStatusListener",
+                    mGnssStatusProvider,
+                    mGnssStatusListeners,
+                    this::unregisterGnssStatusCallback);
+        }
+    }
+
+    /**
+     * Unregisters listener for GNSS status changes.
+     *
+     * @param listener called when GNSS status changes
+     */
+    public void unregisterGnssStatusCallback(IGnssStatusListener listener) {
+        synchronized (mGnssStatusListeners) {
+            removeGnssDataListener(listener, mGnssStatusProvider, mGnssStatusListeners);
+        }
+    }
+
+    /**
+     * Adds a GNSS measurements listener.
+     *
+     * @param listener    called when GNSS measurements are received
+     * @param packageName name of requesting package
+     * @return true if listener is successfully added, false otherwise
+     */
+    public boolean addGnssMeasurementsListener(
+            IGnssMeasurementsListener listener, String packageName) {
+        synchronized (mGnssMeasurementsListeners) {
+            return addGnssDataListenerLocked(
+                    listener,
+                    packageName,
+                    "GnssMeasurementsListener",
+                    mGnssMeasurementsProvider,
+                    mGnssMeasurementsListeners,
+                    this::removeGnssMeasurementsListener);
+        }
+    }
+
+    /**
+     * Injects GNSS measurement corrections.
+     *
+     * @param measurementCorrections GNSS measurement corrections
+     * @param packageName            name of requesting package
+     */
+    public void injectGnssMeasurementCorrections(
+            GnssMeasurementCorrections measurementCorrections, String packageName) {
+        mContext.enforceCallingPermission(
+                android.Manifest.permission.LOCATION_HARDWARE,
+                "Location Hardware permission not granted to inject GNSS measurement corrections.");
+        if (!hasGnssPermissions(packageName)) {
+            Log.e(TAG, "Can not inject GNSS corrections due to no permission.");
+            return;
+        }
+        if (mGnssMeasurementCorrectionsProvider == null) {
+            Log.e(
+                    TAG,
+                    "Can not inject GNSS corrections. GNSS measurement corrections provider "
+                            + "not available.");
+            return;
+        }
+        mGnssMeasurementCorrectionsProvider.injectGnssMeasurementCorrections(
+                measurementCorrections);
+    }
+
+    /**
+     * Removes a GNSS measurements listener.
+     *
+     * @param listener called when GNSS measurements are received
+     */
+    public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
+        synchronized (mGnssMeasurementsListeners) {
+            removeGnssDataListener(listener, mGnssMeasurementsProvider, mGnssMeasurementsListeners);
+        }
+    }
+
+    /**
+     * Adds a GNSS navigation message listener.
+     *
+     * @param listener    called when navigation message is received
+     * @param packageName name of requesting package
+     * @return true if listener is successfully added, false otherwise
+     */
+    public boolean addGnssNavigationMessageListener(
+            IGnssNavigationMessageListener listener, String packageName) {
+        synchronized (mGnssNavigationMessageListeners) {
+            return addGnssDataListenerLocked(
+                    listener,
+                    packageName,
+                    "GnssNavigationMessageListener",
+                    mGnssNavigationMessageProvider,
+                    mGnssNavigationMessageListeners,
+                    this::removeGnssNavigationMessageListener);
+        }
+    }
+
+    /**
+     * Removes a GNSS navigation message listener.
+     *
+     * @param listener called when navigation message is received
+     */
+    public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
+        removeGnssDataListener(
+                listener, mGnssNavigationMessageProvider, mGnssNavigationMessageListeners);
+    }
+
+    /**
+     * Send Ni Response, indicating a location request initiated by a network carrier.
+     */
+    public boolean sendNiResponse(int notifId, int userResponse) {
+        if (Binder.getCallingUid() != Process.myUid()) {
+            throw new SecurityException(
+                    "calling sendNiResponse from outside of the system is not allowed");
+        }
+        try {
+            return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
+            return false;
+        }
+    }
+
+    /**
+     * Report location results to GNSS batching listener.
+     *
+     * @param locations batch of locations to report to GNSS batching callback
+     */
+    public void onReportLocation(List<Location> locations) {
+        if (mGnssBatchingCallback == null) {
+            Log.e(TAG, "reportLocationBatch() called without active Callback");
+            return;
+        }
+
+        try {
+            mGnssBatchingCallback.onLocationBatch(locations);
+        } catch (RemoteException e) {
+            Log.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
+        }
+    }
+
+    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
+
+        IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
+
+        if (args.length > 0 && args[0].equals("--gnssmetrics")) {
+            if (mGnssMetricsProvider != null) {
+                pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
+            }
+            return;
+        }
+
+        ipw.println("GnssMeasurement Listeners:");
+        ipw.increaseIndent();
+        synchronized (mGnssMeasurementsListeners) {
+            for (LinkedListenerBase listener :
+                    mGnssMeasurementsListeners
+                            .values()) {
+                ipw.println(listener + ": " + mLocationManagerService.isThrottlingExemptLocked(
+                        listener.mCallerIdentity));
+            }
+        }
+        ipw.decreaseIndent();
+
+        ipw.println("GnssNavigationMessage Listeners:");
+        ipw.increaseIndent();
+        synchronized (mGnssNavigationMessageListeners) {
+            for (LinkedListenerBase listener :
+                    mGnssNavigationMessageListeners.values()) {
+                ipw.println(listener + ": " + mLocationManagerService.isThrottlingExemptLocked(
+                        listener.mCallerIdentity));
+            }
+        }
+        ipw.decreaseIndent();
+
+        ipw.println("GnssStatus Listeners:");
+        ipw.increaseIndent();
+        synchronized (mGnssStatusListeners) {
+            for (LinkedListenerBase listener :
+                    mGnssStatusListeners.values()) {
+                ipw.println(listener + ": " + mLocationManagerService.isThrottlingExemptLocked(
+                        listener.mCallerIdentity));
+            }
+        }
+        ipw.decreaseIndent();
+
+        synchronized (mGnssBatchingLock) {
+            if (mGnssBatchingInProgress) {
+                ipw.println("GNSS batching in progress");
+            }
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index 69f226f6..09f62ff 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -49,16 +49,13 @@
 import android.location.Criteria;
 import android.location.GeocoderParams;
 import android.location.Geofence;
-import android.location.GnssCapabilities;
 import android.location.GnssMeasurementCorrections;
 import android.location.IBatchedLocationCallback;
 import android.location.IGnssMeasurementsListener;
 import android.location.IGnssNavigationMessageListener;
 import android.location.IGnssStatusListener;
-import android.location.IGpsGeofenceHardware;
 import android.location.ILocationListener;
 import android.location.ILocationManager;
-import android.location.INetInitiatedListener;
 import android.location.Location;
 import android.location.LocationManager;
 import android.location.LocationRequest;
@@ -67,7 +64,6 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
-import android.os.IInterface;
 import android.os.PowerManager;
 import android.os.PowerManager.ServiceType;
 import android.os.PowerManagerInternal;
@@ -81,7 +77,6 @@
 import android.provider.Settings;
 import android.stats.location.LocationStatsEnums;
 import android.text.TextUtils;
-import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.EventLog;
 import android.util.Log;
@@ -102,13 +97,6 @@
 import com.android.server.location.GeocoderProxy;
 import com.android.server.location.GeofenceManager;
 import com.android.server.location.GeofenceProxy;
-import com.android.server.location.GnssBatchingProvider;
-import com.android.server.location.GnssCapabilitiesProvider;
-import com.android.server.location.GnssLocationProvider;
-import com.android.server.location.GnssMeasurementCorrectionsProvider;
-import com.android.server.location.GnssMeasurementsProvider;
-import com.android.server.location.GnssNavigationMessageProvider;
-import com.android.server.location.GnssStatusListenerHelper;
 import com.android.server.location.LocationBlacklist;
 import com.android.server.location.LocationFudger;
 import com.android.server.location.LocationProviderProxy;
@@ -117,7 +105,6 @@
 import com.android.server.location.LocationRequestStatistics.PackageStatistics;
 import com.android.server.location.MockProvider;
 import com.android.server.location.PassiveProvider;
-import com.android.server.location.RemoteListenerHelper;
 import com.android.server.pm.permission.PermissionManagerServiceInternal;
 
 import java.io.ByteArrayOutputStream;
@@ -132,9 +119,6 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-import java.util.NoSuchElementException;
-import java.util.function.Consumer;
-import java.util.function.Function;
 
 /**
  * The service class that manages LocationProviders and issues location
@@ -197,17 +181,13 @@
     private GeofenceManager mGeofenceManager;
     private LocationFudger mLocationFudger;
     private GeocoderProxy mGeocodeProvider;
-    private GnssStatusListenerHelper mGnssStatusProvider;
-    private INetInitiatedListener mNetInitiatedListener;
-    private PassiveProvider mPassiveProvider;  // track passive provider for special cases
+    @Nullable
+    private GnssManagerService mGnssManagerService;
+    private PassiveProvider mPassiveProvider; // track passive provider for special cases
     private LocationBlacklist mBlacklist;
-    private GnssMeasurementsProvider mGnssMeasurementsProvider;
-    private GnssMeasurementCorrectionsProvider mGnssMeasurementCorrectionsProvider;
-    private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
     @GuardedBy("mLock")
     private String mExtraLocationControllerPackage;
     private boolean mExtraLocationControllerPackageEnabled;
-    private IGpsGeofenceHardware mGpsGeofenceProxy;
 
     // list of currently active providers
     @GuardedBy("mLock")
@@ -239,32 +219,10 @@
 
     private final ArraySet<String> mIgnoreSettingsPackageWhitelist = new ArraySet<>();
 
-    @GuardedBy("mLock")
-    private final ArrayMap<IBinder, LinkedListener<IGnssMeasurementsListener>>
-            mGnssMeasurementsListeners = new ArrayMap<>();
-    @GuardedBy("mLock")
-    private final ArrayMap<IBinder, LinkedListener<IGnssNavigationMessageListener>>
-            mGnssNavigationMessageListeners = new ArrayMap<>();
-    @GuardedBy("mLock")
-    private final ArrayMap<IBinder, LinkedListener<IGnssStatusListener>>
-            mGnssStatusListeners = new ArrayMap<>();
-
     // current active user on the device - other users are denied location data
     private int mCurrentUserId = UserHandle.USER_SYSTEM;
     private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM};
 
-    private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
-    private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
-    private GnssCapabilitiesProvider mGnssCapabilitiesProvider;
-
-    private GnssBatchingProvider mGnssBatchingProvider;
-    @GuardedBy("mLock")
-    private IBatchedLocationCallback mGnssBatchingCallback;
-    @GuardedBy("mLock")
-    private LinkedListener<IBatchedLocationCallback> mGnssBatchingDeathCallback;
-    @GuardedBy("mLock")
-    private boolean mGnssBatchingInProgress = false;
-
     @GuardedBy("mLock")
     @PowerManager.LocationPowerSaveMode
     private int mBatterySaverMode;
@@ -287,7 +245,7 @@
                         com.android.internal.R.array.config_locationProviderPackageNames));
         permissionManagerInternal.setLocationExtraPackagesProvider(
                 userId -> mContext.getResources().getStringArray(
-                      com.android.internal.R.array.config_locationExtraPackageNames));
+                        com.android.internal.R.array.config_locationExtraPackageNames));
 
         // most startup is deferred until systemRunning()
     }
@@ -567,7 +525,7 @@
 
     @GuardedBy("mLock")
     private void onUidImportanceChangedLocked(int uid, int importance) {
-        boolean foreground = isImportanceForeground(importance);
+        boolean foreground = LocationManagerServiceUtils.isImportanceForeground(importance);
         HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
         for (Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
             String provider = entry.getKey();
@@ -576,7 +534,8 @@
                         && record.mIsForegroundUid != foreground) {
                     if (D) {
                         Log.d(TAG, "request from uid " + uid + " is now "
-                                + foregroundAsString(foreground));
+                                + LocationManagerServiceUtils.foregroundAsString(
+                                foreground));
                     }
                     record.updateForeground(foreground);
 
@@ -589,51 +548,6 @@
         for (String provider : affectedProviders) {
             applyRequirementsLocked(provider);
         }
-
-        updateGnssDataProviderOnUidImportanceChangedLocked(mGnssMeasurementsListeners,
-                mGnssMeasurementsProvider, IGnssMeasurementsListener.Stub::asInterface,
-                uid, foreground);
-
-        updateGnssDataProviderOnUidImportanceChangedLocked(mGnssNavigationMessageListeners,
-                mGnssNavigationMessageProvider, IGnssNavigationMessageListener.Stub::asInterface,
-                uid, foreground);
-
-        updateGnssDataProviderOnUidImportanceChangedLocked(mGnssStatusListeners,
-                mGnssStatusProvider, IGnssStatusListener.Stub::asInterface, uid, foreground);
-    }
-
-    @GuardedBy("mLock")
-    private <TListener extends IInterface> void updateGnssDataProviderOnUidImportanceChangedLocked(
-            ArrayMap<IBinder, ? extends LinkedListenerBase> gnssDataListeners,
-            RemoteListenerHelper<TListener> gnssDataProvider,
-            Function<IBinder, TListener> mapBinderToListener, int uid, boolean foreground) {
-        for (Entry<IBinder, ? extends LinkedListenerBase> entry : gnssDataListeners.entrySet()) {
-            LinkedListenerBase linkedListener = entry.getValue();
-            CallerIdentity callerIdentity = linkedListener.mCallerIdentity;
-            if (callerIdentity.mUid != uid) {
-                continue;
-            }
-
-            if (D) {
-                Log.d(TAG, linkedListener.mListenerName + " from uid "
-                        + uid + " is now " + foregroundAsString(foreground));
-            }
-
-            TListener listener = mapBinderToListener.apply(entry.getKey());
-            if (foreground || isThrottlingExemptLocked(callerIdentity)) {
-                gnssDataProvider.addListener(listener, callerIdentity);
-            } else {
-                gnssDataProvider.removeListener(listener);
-            }
-        }
-    }
-
-    private static String foregroundAsString(boolean foreground) {
-        return foreground ? "foreground" : "background";
-    }
-
-    private static boolean isImportanceForeground(int importance) {
-        return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
     }
 
     @GuardedBy("mLock")
@@ -768,28 +682,15 @@
         mPassiveProvider = new PassiveProvider(mContext, passiveProviderManager);
         passiveProviderManager.attachLocked(mPassiveProvider);
 
-        if (GnssLocationProvider.isSupported()) {
-            // Create a gps location provider
+        if (GnssManagerService.isGnssSupported()) {
+            // Create a gps location provider manager
             LocationProvider gnssProviderManager = new LocationProvider(GPS_PROVIDER, true);
             mRealProviders.add(gnssProviderManager);
             addProviderLocked(gnssProviderManager);
 
-            GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext,
-                    gnssProviderManager,
-                    mHandler.getLooper());
-            gnssProviderManager.attachLocked(gnssProvider);
-
-            mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
-            mGnssBatchingProvider = gnssProvider.getGnssBatchingProvider();
-            mGnssMetricsProvider = gnssProvider.getGnssMetricsProvider();
-            mGnssCapabilitiesProvider = gnssProvider.getGnssCapabilitiesProvider();
-            mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
-            mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
-            mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
-            mGnssMeasurementCorrectionsProvider =
-                    gnssProvider.getGnssMeasurementCorrectionsProvider();
-            mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
-            mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
+            mGnssManagerService = new GnssManagerService(this, mContext, gnssProviderManager,
+                    mLocationUsageLogger);
+            gnssProviderManager.attachLocked(mGnssManagerService.getGnssLocationProvider());
         }
 
         /*
@@ -857,15 +758,17 @@
             Slog.e(TAG, "no geocoder provider found");
         }
 
-        // bind to geofence provider
-        GeofenceProxy provider = GeofenceProxy.createAndBind(
-                mContext, com.android.internal.R.bool.config_enableGeofenceOverlay,
-                com.android.internal.R.string.config_geofenceProviderPackageName,
-                com.android.internal.R.array.config_locationProviderPackageNames,
-                mGpsGeofenceProxy,
-                null);
-        if (provider == null) {
-            Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
+        if (mGnssManagerService != null) {
+            // bind to geofence provider
+            GeofenceProxy provider = GeofenceProxy.createAndBind(
+                    mContext, com.android.internal.R.bool.config_enableGeofenceOverlay,
+                    com.android.internal.R.string.config_geofenceProviderPackageName,
+                    com.android.internal.R.array.config_locationProviderPackageNames,
+                    mGnssManagerService.getGpsGeofenceProxy(),
+                    null);
+            if (provider == null) {
+                Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
+            }
         }
 
         // bind to hardware activity recognition
@@ -939,7 +842,10 @@
         }
     }
 
-    private class LocationProvider implements AbstractLocationProvider.LocationProviderManager {
+    /**
+     * Location provider manager, manages a LocationProvider.
+     */
+    class LocationProvider implements AbstractLocationProvider.LocationProviderManager {
 
         private final String mName;
 
@@ -948,7 +854,8 @@
 
         // remember to clear binder identity before invoking any provider operation
         @GuardedBy("mLock")
-        @Nullable protected AbstractLocationProvider mProvider;
+        @Nullable
+        protected AbstractLocationProvider mProvider;
 
         @GuardedBy("mLock")
         private boolean mUseable;  // combined state
@@ -958,7 +865,8 @@
         private boolean mEnabled;  // state of provider
 
         @GuardedBy("mLock")
-        @Nullable private ProviderProperties mProperties;
+        @Nullable
+        private ProviderProperties mProperties;
 
         private LocationProvider(String name) {
             this(name, false);
@@ -1095,6 +1003,9 @@
 
         @Override
         public void onReportLocation(List<Location> locations) {
+            if (mGnssManagerService == null) {
+                return;
+            }
             synchronized (mLock) {
                 LocationProvider gpsProvider = getLocationProviderLocked(GPS_PROVIDER);
                 if (gpsProvider == null || !gpsProvider.isUseableLocked()) {
@@ -1102,16 +1013,7 @@
                     return;
                 }
 
-                if (mGnssBatchingCallback == null) {
-                    Slog.e(TAG, "reportLocationBatch() called without active Callback");
-                    return;
-                }
-
-                try {
-                    mGnssBatchingCallback.onLocationBatch(locations);
-                } catch (RemoteException e) {
-                    Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
-                }
+                mGnssManagerService.onReportLocation(locations);
             }
         }
 
@@ -1300,7 +1202,8 @@
      * A wrapper class holding either an ILocationListener or a PendingIntent to receive
      * location updates.
      */
-    private final class Receiver extends LinkedListenerBase implements PendingIntent.OnFinished {
+    private final class Receiver extends LocationManagerServiceUtils.LinkedListenerBase implements
+            PendingIntent.OnFinished {
         private static final long WAKELOCK_TIMEOUT_MILLIS = 60 * 1000;
         private final int mAllowedResolutionLevel;  // resolution level allowed to receiver
 
@@ -1614,146 +1517,45 @@
 
     @Override
     public int getGnssYearOfHardware() {
-        if (mGnssSystemInfoProvider != null) {
-            return mGnssSystemInfoProvider.getGnssYearOfHardware();
-        } else {
-            return 0;
-        }
+        return mGnssManagerService == null ? 0 : mGnssManagerService.getGnssYearOfHardware();
     }
 
     @Override
     @Nullable
     public String getGnssHardwareModelName() {
-        if (mGnssSystemInfoProvider != null) {
-            return mGnssSystemInfoProvider.getGnssHardwareModelName();
-        } else {
-            return null;
-        }
-    }
-
-    private boolean hasGnssPermissions(String packageName) {
-        synchronized (mLock) {
-            int allowedResolutionLevel = getCallerAllowedResolutionLevel();
-            checkResolutionLevelIsSufficientForProviderUseLocked(
-                    allowedResolutionLevel,
-                    GPS_PROVIDER);
-
-            int pid = Binder.getCallingPid();
-            int uid = Binder.getCallingUid();
-            long identity = Binder.clearCallingIdentity();
-            try {
-                return checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
-            } finally {
-                Binder.restoreCallingIdentity(identity);
-            }
-        }
+        return mGnssManagerService == null ? "" : mGnssManagerService.getGnssHardwareModelName();
     }
 
     @Override
     public int getGnssBatchSize(String packageName) {
-        mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
-                "Location Hardware permission not granted to access hardware batching");
-
-        if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
-            return mGnssBatchingProvider.getBatchSize();
-        } else {
-            return 0;
-        }
+        return mGnssManagerService == null ? 0 : mGnssManagerService.getGnssBatchSize(packageName);
     }
 
     @Override
     public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
-        mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
-                "Location Hardware permission not granted to access hardware batching");
-
-        if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
-            return false;
-        }
-
-        CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
-                Binder.getCallingPid(), packageName);
-        synchronized (mLock) {
-            mGnssBatchingCallback = callback;
-            mGnssBatchingDeathCallback =  new LinkedListener<>(callback,
-                    "BatchedLocationCallback", callerIdentity,
-                    (IBatchedLocationCallback listener) -> {
-                        stopGnssBatch();
-                        removeGnssBatchingCallback();
-                    });
-            if (!linkToListenerDeathNotificationLocked(callback.asBinder(),
-                    mGnssBatchingDeathCallback)) {
-                return false;
-            }
-            return true;
-        }
+        return mGnssManagerService == null ? false : mGnssManagerService.addGnssBatchingCallback(
+                callback, packageName);
     }
 
     @Override
     public void removeGnssBatchingCallback() {
-        synchronized (mLock) {
-            unlinkFromListenerDeathNotificationLocked(mGnssBatchingCallback.asBinder(),
-                    mGnssBatchingDeathCallback);
-            mGnssBatchingCallback = null;
-            mGnssBatchingDeathCallback = null;
-        }
+        if (mGnssManagerService != null) mGnssManagerService.removeGnssBatchingCallback();
     }
 
     @Override
     public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
-        mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
-                "Location Hardware permission not granted to access hardware batching");
-
-        if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
-            return false;
-        }
-
-        synchronized (mLock) {
-            if (mGnssBatchingInProgress) {
-                // Current design does not expect multiple starts to be called repeatedly
-                Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
-                // Try to clean up anyway, and continue
-                stopGnssBatch();
-            }
-
-            mGnssBatchingInProgress = true;
-            return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
-        }
+        return mGnssManagerService == null ? false : mGnssManagerService.startGnssBatch(periodNanos,
+                wakeOnFifoFull, packageName);
     }
 
     @Override
     public void flushGnssBatch(String packageName) {
-        mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
-                "Location Hardware permission not granted to access hardware batching");
-
-        if (!hasGnssPermissions(packageName)) {
-            Log.e(TAG, "flushGnssBatch called without GNSS permissions");
-            return;
-        }
-
-        synchronized (mLock) {
-            if (!mGnssBatchingInProgress) {
-                Log.w(TAG, "flushGnssBatch called with no batch in progress");
-            }
-
-            if (mGnssBatchingProvider != null) {
-                mGnssBatchingProvider.flush();
-            }
-        }
+        if (mGnssManagerService != null) mGnssManagerService.flushGnssBatch(packageName);
     }
 
     @Override
     public boolean stopGnssBatch() {
-        mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
-                "Location Hardware permission not granted to access hardware batching");
-
-        synchronized (mLock) {
-            if (mGnssBatchingProvider != null) {
-                mGnssBatchingInProgress = false;
-                return mGnssBatchingProvider.stop();
-            } else {
-                return false;
-            }
-        }
+        return mGnssManagerService == null ? false : mGnssManagerService.stopGnssBatch();
     }
 
     @GuardedBy("mLock")
@@ -2191,7 +1993,7 @@
     }
 
     @GuardedBy("mLock")
-    private boolean isThrottlingExemptLocked(CallerIdentity callerIdentity) {
+    public boolean isThrottlingExemptLocked(CallerIdentity callerIdentity) {
         if (callerIdentity.mUid == Process.SYSTEM_UID) {
             return true;
         }
@@ -2236,8 +2038,10 @@
             mRealRequest = request;
             mRequest = request;
             mReceiver = receiver;
-            mIsForegroundUid = isImportanceForeground(
-                    mActivityManager.getPackageImportance(mReceiver.mCallerIdentity.mPackageName));
+            mIsForegroundUid =
+                    LocationManagerServiceUtils.isImportanceForeground(
+                            mActivityManager.getPackageImportance(
+                                    mReceiver.mCallerIdentity.mPackageName));
 
             if (D && receiver.mCallerIdentity.mPid == Process.myPid()) {
                 mStackTrace = new Throwable();
@@ -2335,8 +2139,8 @@
         if (receiver == null) {
             receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
                     hideFromAppOps);
-            if (!linkToListenerDeathNotificationLocked(receiver.getListener().asBinder(),
-                    receiver)) {
+            if (!receiver.linkToListenerDeathNotificationLocked(
+                    receiver.getListener().asBinder())) {
                 return null;
             }
             mReceivers.put(binder, receiver);
@@ -2558,8 +2362,8 @@
         if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
 
         if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
-            unlinkFromListenerDeathNotificationLocked(receiver.getListener().asBinder(),
-                    receiver);
+            receiver.unlinkFromListenerDeathNotificationLocked(
+                    receiver.getListener().asBinder());
             receiver.clearPendingBroadcastsLocked();
         }
 
@@ -2606,7 +2410,6 @@
                     return null;
                 }
 
-
                 // Figure out the provider. Either its explicitly request (deprecated API's),
                 // or use the fused provider
                 String name = request.getProvider();
@@ -2666,7 +2469,7 @@
                         if (D) {
                             Log.d(TAG, "not returning last loc for no op app: " + packageName);
                         }
-                        lastLocation =  null;
+                        lastLocation = null;
                     }
                 }
                 return lastLocation;
@@ -2696,13 +2499,6 @@
         mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
                 "Access Fine Location permission not granted to inject Location");
 
-        if (location == null) {
-            if (D) {
-                Log.d(TAG, "injectLocation(): called with null location");
-            }
-            return false;
-        }
-
         synchronized (mLock) {
             LocationProvider provider = getLocationProviderLocked(location.getProvider());
             if (provider == null || !provider.isUseableLocked()) {
@@ -2807,219 +2603,58 @@
 
     @Override
     public boolean registerGnssStatusCallback(IGnssStatusListener listener, String packageName) {
-        return addGnssDataListener(listener, packageName, "GnssStatusListener",
-                mGnssStatusProvider, mGnssStatusListeners,
-                this::unregisterGnssStatusCallback);
+        return mGnssManagerService == null ? false : mGnssManagerService.registerGnssStatusCallback(
+                listener, packageName);
     }
 
     @Override
     public void unregisterGnssStatusCallback(IGnssStatusListener listener) {
-        removeGnssDataListener(listener, mGnssStatusProvider, mGnssStatusListeners);
+        if (mGnssManagerService != null) mGnssManagerService.unregisterGnssStatusCallback(listener);
     }
 
     @Override
     public boolean addGnssMeasurementsListener(
             IGnssMeasurementsListener listener, String packageName) {
-        return addGnssDataListener(listener, packageName, "GnssMeasurementsListener",
-                mGnssMeasurementsProvider, mGnssMeasurementsListeners,
-                this::removeGnssMeasurementsListener);
+        return mGnssManagerService == null ? false
+                : mGnssManagerService.addGnssMeasurementsListener(listener, packageName);
     }
 
     @Override
     public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
-        removeGnssDataListener(listener, mGnssMeasurementsProvider, mGnssMeasurementsListeners);
-    }
-
-    private abstract static class LinkedListenerBase implements IBinder.DeathRecipient {
-        protected final CallerIdentity mCallerIdentity;
-        protected final String mListenerName;
-
-        private LinkedListenerBase(@NonNull CallerIdentity callerIdentity,
-                @NonNull String listenerName) {
-            mCallerIdentity = callerIdentity;
-            mListenerName = listenerName;
-        }
-
-        @Override
-        public String toString() {
-            return mListenerName + "[" + mCallerIdentity.mPackageName + "(" + mCallerIdentity.mPid
-                    + ")]";
-        }
-    }
-
-    private static class LinkedListener<TListener> extends LinkedListenerBase {
-        private final TListener mListener;
-        private final Consumer<TListener> mBinderDeathCallback;
-
-        private LinkedListener(@NonNull TListener listener, String listenerName,
-                @NonNull CallerIdentity callerIdentity,
-                @NonNull Consumer<TListener> binderDeathCallback) {
-            super(callerIdentity, listenerName);
-            mListener = listener;
-            mBinderDeathCallback = binderDeathCallback;
-        }
-
-        @Override
-        public void binderDied() {
-            if (D) Log.d(TAG, "Remote " + mListenerName + " died.");
-            mBinderDeathCallback.accept(mListener);
-        }
-    }
-
-    private <TListener extends IInterface> boolean addGnssDataListener(
-            TListener listener, String packageName, String listenerName,
-            RemoteListenerHelper<TListener> gnssDataProvider,
-            ArrayMap<IBinder, LinkedListener<TListener>> gnssDataListeners,
-            Consumer<TListener> binderDeathCallback) {
-        if (!hasGnssPermissions(packageName) || gnssDataProvider == null) {
-            return false;
-        }
-
-        CallerIdentity callerIdentity = new CallerIdentity(Binder.getCallingUid(),
-                Binder.getCallingPid(), packageName);
-        LinkedListener<TListener> linkedListener = new LinkedListener<>(listener,
-                listenerName, callerIdentity, binderDeathCallback);
-        IBinder binder = listener.asBinder();
-        synchronized (mLock) {
-            if (!linkToListenerDeathNotificationLocked(binder, linkedListener)) {
-                return false;
-            }
-
-            gnssDataListeners.put(binder, linkedListener);
-            long identity = Binder.clearCallingIdentity();
-            try {
-                if (gnssDataProvider == mGnssMeasurementsProvider
-                        || gnssDataProvider == mGnssStatusProvider) {
-                    mLocationUsageLogger.logLocationApiUsage(
-                            LocationStatsEnums.USAGE_STARTED,
-                            gnssDataProvider == mGnssMeasurementsProvider
-                                ? LocationStatsEnums.API_ADD_GNSS_MEASUREMENTS_LISTENER
-                                : LocationStatsEnums.API_REGISTER_GNSS_STATUS_CALLBACK,
-                            packageName,
-                            /* LocationRequest= */ null,
-                            /* hasListener= */ true,
-                            /* hasIntent= */ false,
-                            /* geofence= */ null,
-                            mActivityManager.getPackageImportance(packageName));
-                }
-                if (isThrottlingExemptLocked(callerIdentity)
-                        || isImportanceForeground(
-                        mActivityManager.getPackageImportance(packageName))) {
-                    gnssDataProvider.addListener(listener, callerIdentity);
-                }
-                return true;
-            } finally {
-                Binder.restoreCallingIdentity(identity);
-            }
-        }
-    }
-
-    private <TListener extends IInterface> void removeGnssDataListener(
-            TListener listener, RemoteListenerHelper<TListener> gnssDataProvider,
-            ArrayMap<IBinder, LinkedListener<TListener>> gnssDataListeners) {
-        if (gnssDataProvider == null) {
-            return;
-        }
-
-        IBinder binder = listener.asBinder();
-        synchronized (mLock) {
-            LinkedListener<TListener> linkedListener = gnssDataListeners.remove(binder);
-            if (linkedListener == null) {
-                return;
-            }
-            long identity = Binder.clearCallingIdentity();
-            try {
-                if (gnssDataProvider == mGnssMeasurementsProvider
-                        || gnssDataProvider == mGnssStatusProvider) {
-                    mLocationUsageLogger.logLocationApiUsage(
-                            LocationStatsEnums.USAGE_ENDED,
-                            gnssDataProvider == mGnssMeasurementsProvider
-                                ? LocationStatsEnums.API_ADD_GNSS_MEASUREMENTS_LISTENER
-                                : LocationStatsEnums.API_REGISTER_GNSS_STATUS_CALLBACK,
-                            linkedListener.mCallerIdentity.mPackageName,
-                            /* LocationRequest= */ null,
-                            /* hasListener= */ true,
-                            /* hasIntent= */ false,
-                            /* geofence= */ null,
-                            mActivityManager.getPackageImportance(
-                                    linkedListener.mCallerIdentity.mPackageName));
-                }
-            } finally {
-                Binder.restoreCallingIdentity(identity);
-            }
-            unlinkFromListenerDeathNotificationLocked(binder, linkedListener);
-            gnssDataProvider.removeListener(listener);
-        }
-    }
-
-    private boolean linkToListenerDeathNotificationLocked(IBinder binder,
-            LinkedListenerBase linkedListener) {
-        try {
-            binder.linkToDeath(linkedListener, 0 /* flags */);
-            return true;
-        } catch (RemoteException e) {
-            // if the remote process registering the listener is already dead, just swallow the
-            // exception and return
-            Log.w(TAG, "Could not link " + linkedListener.mListenerName + " death callback.", e);
-            return false;
-        }
-    }
-
-    private boolean unlinkFromListenerDeathNotificationLocked(IBinder binder,
-            LinkedListenerBase linkedListener) {
-        try {
-            binder.unlinkToDeath(linkedListener, 0 /* flags */);
-            return true;
-        } catch (NoSuchElementException e) {
-            // if the death callback isn't connected (it should be...), log error,
-            // swallow the exception and return
-            Log.w(TAG, "Could not unlink " + linkedListener.mListenerName + " death callback.", e);
-            return false;
+        if (mGnssManagerService != null) {
+            mGnssManagerService.removeGnssMeasurementsListener(
+                    listener);
         }
     }
 
     @Override
     public void injectGnssMeasurementCorrections(
             GnssMeasurementCorrections measurementCorrections, String packageName) {
-        mContext.enforceCallingPermission(
-                android.Manifest.permission.LOCATION_HARDWARE,
-                "Location Hardware permission not granted to inject GNSS measurement corrections.");
-        if (!hasGnssPermissions(packageName)) {
-            Slog.e(TAG, "Can not inject GNSS corrections due to no permission.");
-            return;
+        if (mGnssManagerService != null) {
+            mGnssManagerService.injectGnssMeasurementCorrections(
+                    measurementCorrections, packageName);
         }
-        if (mGnssMeasurementCorrectionsProvider == null) {
-            Slog.e(TAG, "Can not inject GNSS corrections. GNSS measurement corrections provider "
-                    + "not available.");
-            return;
-        }
-        mGnssMeasurementCorrectionsProvider.injectGnssMeasurementCorrections(
-                measurementCorrections);
     }
 
     @Override
     public long getGnssCapabilities(String packageName) {
-        mContext.enforceCallingPermission(
-                android.Manifest.permission.LOCATION_HARDWARE,
-                "Location Hardware permission not granted to obtain GNSS chipset capabilities.");
-        if (!hasGnssPermissions(packageName) || mGnssCapabilitiesProvider == null) {
-            return GnssCapabilities.INVALID_CAPABILITIES;
-        }
-        return mGnssCapabilitiesProvider.getGnssCapabilities();
+        return mGnssManagerService == null ? 0L : mGnssManagerService.getGnssCapabilities(
+                packageName);
     }
 
     @Override
     public boolean addGnssNavigationMessageListener(
             IGnssNavigationMessageListener listener, String packageName) {
-        return addGnssDataListener(listener, packageName, "GnssNavigationMessageListener",
-                mGnssNavigationMessageProvider, mGnssNavigationMessageListeners,
-                this::removeGnssNavigationMessageListener);
+        return mGnssManagerService == null ? false
+                : mGnssManagerService.addGnssNavigationMessageListener(listener, packageName);
     }
 
     @Override
     public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
-        removeGnssDataListener(listener, mGnssNavigationMessageProvider,
-                mGnssNavigationMessageListeners);
+        if (mGnssManagerService != null) {
+            mGnssManagerService.removeGnssNavigationMessageListener(
+                    listener);
+        }
     }
 
     @Override
@@ -3059,24 +2694,13 @@
 
     @Override
     public boolean sendNiResponse(int notifId, int userResponse) {
-        if (Binder.getCallingUid() != Process.myUid()) {
-            throw new SecurityException(
-                    "calling sendNiResponse from outside of the system is not allowed");
-        }
-        try {
-            return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
-            return false;
-        }
+        return mGnssManagerService == null ? false : mGnssManagerService.sendNiResponse(notifId,
+                userResponse);
     }
 
     @Override
     public ProviderProperties getProviderProperties(String providerName) {
         synchronized (mLock) {
-            checkResolutionLevelIsSufficientForProviderUseLocked(getCallerAllowedResolutionLevel(),
-                    providerName);
-
             LocationProvider provider = getLocationProviderLocked(providerName);
             if (provider == null) {
                 return null;
@@ -3149,10 +2773,10 @@
         long identity = Binder.clearCallingIdentity();
         try {
             return Settings.Secure.getIntForUser(
-                        mContext.getContentResolver(),
-                        Settings.Secure.LOCATION_MODE,
-                        Settings.Secure.LOCATION_MODE_OFF,
-                        userId) != Settings.Secure.LOCATION_MODE_OFF;
+                    mContext.getContentResolver(),
+                    Settings.Secure.LOCATION_MODE,
+                    Settings.Secure.LOCATION_MODE_OFF,
+                    userId) != Settings.Secure.LOCATION_MODE_OFF;
         } finally {
             Binder.restoreCallingIdentity(identity);
         }
@@ -3440,11 +3064,6 @@
             try {
                 LocationProvider oldProvider = getLocationProviderLocked(name);
                 if (oldProvider != null) {
-                    if (oldProvider.isMock()) {
-                        throw new IllegalArgumentException(
-                                "Provider \"" + name + "\" already exists");
-                    }
-
                     removeProviderLocked(oldProvider);
                 }
 
@@ -3469,7 +3088,7 @@
             try {
                 LocationProvider testProvider = getLocationProviderLocked(name);
                 if (testProvider == null || !testProvider.isMock()) {
-                    throw new IllegalArgumentException("Provider \"" + name + "\" unknown");
+                    return;
                 }
 
                 removeProviderLocked(testProvider);
@@ -3566,11 +3185,8 @@
         IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
 
         synchronized (mLock) {
-            if (args.length > 0 && args[0].equals("--gnssmetrics")) {
-                if (mGnssMetricsProvider != null) {
-                    pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
-                }
-                return;
+            if (mGnssManagerService != null && args.length > 0 && args[0].equals("--gnssmetrics")) {
+                mGnssManagerService.dump(fd, pw, args);
             }
 
             ipw.println("Location Manager State:");
@@ -3604,27 +3220,6 @@
             }
             ipw.decreaseIndent();
 
-            ipw.println("GnssMeasurement Listeners:");
-            ipw.increaseIndent();
-            for (LinkedListenerBase listener : mGnssMeasurementsListeners.values()) {
-                ipw.println(listener + ": " + isThrottlingExemptLocked(listener.mCallerIdentity));
-            }
-            ipw.decreaseIndent();
-
-            ipw.println("GnssNavigationMessage Listeners:");
-            ipw.increaseIndent();
-            for (LinkedListenerBase listener : mGnssNavigationMessageListeners.values()) {
-                ipw.println(listener + ": " + isThrottlingExemptLocked(listener.mCallerIdentity));
-            }
-            ipw.decreaseIndent();
-
-            ipw.println("GnssStatus Listeners:");
-            ipw.increaseIndent();
-            for (LinkedListenerBase listener : mGnssStatusListeners.values()) {
-                ipw.println(listener + ": " + isThrottlingExemptLocked(listener.mCallerIdentity));
-            }
-            ipw.decreaseIndent();
-
             ipw.println("Historical Records by Provider:");
             ipw.increaseIndent();
             for (Map.Entry<PackageProviderKey, PackageStatistics> entry
@@ -3654,7 +3249,7 @@
                 mGeofenceManager.dump(ipw);
                 ipw.decreaseIndent();
             }
-          
+
             if (mBlacklist != null) {
                 mBlacklist.dump(ipw);
             }
@@ -3694,11 +3289,11 @@
             for (LocationProvider provider : mProviders) {
                 provider.dumpLocked(fd, ipw, args);
             }
-            ipw.decreaseIndent();
+        }
 
-            if (mGnssBatchingInProgress) {
-                ipw.println("GNSS batching in progress");
-            }
+        if (mGnssManagerService != null) {
+            ipw.decreaseIndent();
+            mGnssManagerService.dump(fd, pw, args);
         }
     }
 }
diff --git a/services/core/java/com/android/server/LocationManagerServiceUtils.java b/services/core/java/com/android/server/LocationManagerServiceUtils.java
new file mode 100644
index 0000000..9c8ac19
--- /dev/null
+++ b/services/core/java/com/android/server/LocationManagerServiceUtils.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2019 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;
+
+import android.annotation.NonNull;
+import android.app.ActivityManager;
+import android.content.Context;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.util.Log;
+
+import com.android.server.location.CallerIdentity;
+
+import java.util.NoSuchElementException;
+import java.util.function.Consumer;
+
+/**
+ * Shared utilities for LocationManagerService and GnssManager.
+ */
+public class LocationManagerServiceUtils {
+
+    private static final String TAG = "LocManagerServiceUtils";
+    private static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
+
+    /**
+     * Listener that can be linked to a binder.
+     * @param <TListener> listener type
+     */
+    public static class LinkedListener<TListener> extends
+            LinkedListenerBase {
+        private final TListener mListener;
+        private final Consumer<TListener> mBinderDeathCallback;
+
+        public LinkedListener(
+                @NonNull TListener listener,
+                String listenerName,
+                @NonNull CallerIdentity callerIdentity,
+                @NonNull Consumer<TListener> binderDeathCallback) {
+            super(callerIdentity, listenerName);
+            mListener = listener;
+            mBinderDeathCallback = binderDeathCallback;
+        }
+
+        @Override
+        public void binderDied() {
+            if (D) Log.d(TAG, "Remote " + mListenerName + " died.");
+            mBinderDeathCallback.accept(mListener);
+        }
+    }
+
+    /**
+     * Skeleton class of listener that can be linked to a binder.
+     */
+    public abstract static class LinkedListenerBase implements IBinder.DeathRecipient {
+        protected final CallerIdentity mCallerIdentity;
+        protected final String mListenerName;
+
+        LinkedListenerBase(
+                @NonNull CallerIdentity callerIdentity, @NonNull String listenerName) {
+            mCallerIdentity = callerIdentity;
+            mListenerName = listenerName;
+        }
+
+        @Override
+        public String toString() {
+            return mListenerName + "[" + mCallerIdentity.mPackageName + "(" + mCallerIdentity.mPid
+                    + ")]";
+        }
+
+        public CallerIdentity getCallerIdentity() {
+            return mCallerIdentity;
+        }
+
+        public String getListenerName() {
+            return mListenerName;
+        }
+
+        /**
+         * Link listener (i.e. callback) to a binder, so that it will be called upon binder's death.
+         *
+         * @param binder that calls listener upon death
+         * @return true if listener is successfully linked to binder, false otherwise
+         */
+        public boolean linkToListenerDeathNotificationLocked(
+                IBinder binder) {
+            try {
+                binder.linkToDeath(this, 0 /* flags */);
+                return true;
+            } catch (RemoteException e) {
+                // if the remote process registering the listener is already dead, just swallow the
+                // exception and return
+                Log.w(TAG, "Could not link " + mListenerName + " death callback.", e);
+                return false;
+            }
+        }
+
+        /**
+         * Unlink death listener (i.e. callback) from binder.
+         *
+         * @param binder that calls listener upon death
+         * @return true if binder is successfully unlinked from binder, false otherwise
+         */
+        public boolean unlinkFromListenerDeathNotificationLocked(
+                IBinder binder) {
+            try {
+                binder.unlinkToDeath(this, 0 /* flags */);
+                return true;
+            } catch (NoSuchElementException e) {
+                // if the death callback isn't connected (it should be...), log error,
+                // swallow the exception and return
+                Log.w(TAG, "Could not unlink " + mListenerName + " death callback.", e);
+                return false;
+            }
+        }
+
+    }
+
+    /**
+     * Convert boolean foreground into "foreground" or "background" string.
+     *
+     * @param foreground boolean indicating foreground
+     * @return "foreground" string if true, false otherwise
+     */
+    public static String foregroundAsString(boolean foreground) {
+        return foreground ? "foreground" : "background";
+    }
+
+
+    /**
+     * Classifies importance level as foreground or not.
+     *
+     * @param importance level as int
+     * @return boolean indicating if importance level is foreground or greater
+     */
+    public static boolean isImportanceForeground(int importance) {
+        return importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
+    }
+
+    /**
+     * Get package importance level.
+     *
+     * @param packageName package name
+     * @return package importance level as int
+     */
+    public static int getPackageImportance(String packageName, Context context) {
+        return ((ActivityManager) context.getSystemService(
+                Context.ACTIVITY_SERVICE)).getPackageImportance(packageName);
+    }
+}
diff --git a/services/core/java/com/android/server/MasterClearReceiver.java b/services/core/java/com/android/server/MasterClearReceiver.java
index fa1653d..793e342 100644
--- a/services/core/java/com/android/server/MasterClearReceiver.java
+++ b/services/core/java/com/android/server/MasterClearReceiver.java
@@ -88,7 +88,7 @@
             }
         };
 
-        if (mWipeExternalStorage || mWipeEsims) {
+        if (mWipeExternalStorage) {
             // thr will be started at the end of this task.
             new WipeDataTask(context, thr).execute();
         } else {
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 8367e89..3916f0d 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -196,6 +196,9 @@
     private static final String ZRAM_ENABLED_PROPERTY =
             "persist.sys.zram_enabled";
 
+    private static final boolean IS_FUSE_ENABLED =
+            SystemProperties.getBoolean(StorageManager.PROP_FUSE, false);
+
     private static final boolean ENABLE_ISOLATED_STORAGE = StorageManager.hasIsolatedStorage();
 
     /**
@@ -205,6 +208,12 @@
      */
     private static final String ISOLATED_STORAGE_ENABLED = "isolated_storage_enabled";
 
+    /**
+     * If {@code 1}, enables FuseDaemon to intercept file system ops. If {@code -1},
+     * disables FuseDaemon. If {@code 0}, uses the default value from the build system.
+     */
+    private static final String FUSE_ENABLED = "fuse_enabled";
+
     public static class Lifecycle extends SystemService {
         private StorageManagerService mStorageManagerService;
 
@@ -346,6 +355,9 @@
     @GuardedBy("mLock")
     private String mMoveTargetUuid;
 
+    @Nullable
+    private volatile String mMediaStoreAuthorityPackageName = null;
+
     private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
 
     /** Holding lock for AppFuse business */
@@ -808,11 +820,13 @@
                 }
             });
         // For now, simply clone property when it changes
-        DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_STORAGE,
+        DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
                 mContext.getMainExecutor(), (properties) -> {
                     refreshIsolatedStorageSettings();
+                    refreshFuseSettings();
                 });
         refreshIsolatedStorageSettings();
+        refreshFuseSettings();
     }
 
     /**
@@ -848,7 +862,8 @@
         // Always copy value from newer DeviceConfig location
         Settings.Global.putString(mResolver,
                 Settings.Global.ISOLATED_STORAGE_REMOTE,
-                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_STORAGE, ISOLATED_STORAGE_ENABLED));
+                DeviceConfig.getProperty(DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
+                        ISOLATED_STORAGE_ENABLED));
 
         final int local = Settings.Global.getInt(mContext.getContentResolver(),
                 Settings.Global.ISOLATED_STORAGE_LOCAL, 0);
@@ -875,6 +890,18 @@
         SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE, Boolean.toString(res));
     }
 
+    private void refreshFuseSettings() {
+        int isFuseEnabled = DeviceConfig.getInt(DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
+                FUSE_ENABLED, 0);
+        if (isFuseEnabled == 1) {
+            SystemProperties.set(StorageManager.PROP_FUSE, "true");
+        } else if (isFuseEnabled == -1) {
+            SystemProperties.set(StorageManager.PROP_FUSE, "false");
+        }
+        // else, keep the build config.
+        // This can be overridden be direct adjustment of persist.sys.prop
+    }
+
     /**
      * MediaProvider has a ton of code that makes assumptions about storage
      * paths never changing, so we outright kill them to pick up new state.
@@ -1520,6 +1547,9 @@
         SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT, Boolean.toString(
                 SystemProperties.getBoolean(StorageManager.PROP_ISOLATED_STORAGE, true)));
 
+        SystemProperties.set(StorageManager.PROP_FUSE_SNAPSHOT, Boolean.toString(
+                SystemProperties.getBoolean(StorageManager.PROP_FUSE, false)));
+
         mContext = context;
         mResolver = mContext.getContentResolver();
 
@@ -1661,6 +1691,15 @@
                 ServiceManager.getService("package"));
         mIAppOpsService = IAppOpsService.Stub.asInterface(
                 ServiceManager.getService(Context.APP_OPS_SERVICE));
+
+        ProviderInfo provider = mPmInternal.resolveContentProvider(
+                MediaStore.AUTHORITY, PackageManager.MATCH_DIRECT_BOOT_AWARE
+                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+                UserHandle.getUserId(UserHandle.USER_SYSTEM));
+        if (provider != null) {
+            mMediaStoreAuthorityPackageName = provider.packageName;
+        }
+
         try {
             mIAppOpsService.startWatchingMode(OP_REQUEST_INSTALL_PACKAGES, null, mAppOpsCallback);
             mIAppOpsService.startWatchingMode(OP_LEGACY_STORAGE, null, mAppOpsCallback);
@@ -1843,7 +1882,7 @@
             // This means the mountUserId on such volumes is USER_NULL. This breaks fuse which
             // requires a valid user to mount a volume. Create individual volumes per user in vold
             // and remove this property check
-            int userId = SystemProperties.getBoolean("persist.sys.fuse", false)
+            int userId = SystemProperties.getBoolean(StorageManager.PROP_FUSE_SNAPSHOT, false)
                     ? mCurrentUserId : vol.mountUserId;
             return mVold.mount(vol.id, vol.mountFlags, userId);
         } catch (Exception e) {
@@ -3672,6 +3711,11 @@
                 return Zygote.MOUNT_EXTERNAL_NONE;
             }
 
+            if (IS_FUSE_ENABLED && packageName.equals(mMediaStoreAuthorityPackageName)) {
+                // Determine if caller requires pass_through mount
+                return Zygote.MOUNT_EXTERNAL_PASS_THROUGH;
+            }
+
             // Determine if caller is holding runtime permission
             final boolean hasRead = StorageManager.checkPermissionAndCheckOp(mContext, false, 0,
                     uid, packageName, READ_EXTERNAL_STORAGE, OP_READ_EXTERNAL_STORAGE);
diff --git a/services/core/java/com/android/server/SystemServerInitThreadPool.java b/services/core/java/com/android/server/SystemServerInitThreadPool.java
index ff6a537..19f4089 100644
--- a/services/core/java/com/android/server/SystemServerInitThreadPool.java
+++ b/services/core/java/com/android/server/SystemServerInitThreadPool.java
@@ -16,10 +16,12 @@
 
 package com.android.server;
 
+import android.annotation.NonNull;
 import android.os.Build;
 import android.os.Process;
 import android.util.Slog;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.ConcurrentUtils;
 import com.android.internal.util.Preconditions;
 import com.android.server.am.ActivityManagerService;
@@ -32,9 +34,11 @@
 
 /**
  * Thread pool used during initialization of system server.
+ *
  * <p>System services can {@link #submit(Runnable)} tasks for execution during boot.
  * The pool will be shut down after {@link SystemService#PHASE_BOOT_COMPLETED}.
- * New tasks <em>should not</em> be submitted afterwards.
+ *
+ * <p>New tasks <em>should not</em> be submitted afterwards.
  *
  * @hide
  */
@@ -42,26 +46,46 @@
     private static final String TAG = SystemServerInitThreadPool.class.getSimpleName();
     private static final int SHUTDOWN_TIMEOUT_MILLIS = 20000;
     private static final boolean IS_DEBUGGABLE = Build.IS_DEBUGGABLE;
+    private static final Object LOCK = new Object();
 
+    @GuardedBy("LOCK")
     private static SystemServerInitThreadPool sInstance;
 
-    private ExecutorService mService = ConcurrentUtils.newFixedThreadPool(
-            Runtime.getRuntime().availableProcessors(),
-            "system-server-init-thread", Process.THREAD_PRIORITY_FOREGROUND);
+    private final ExecutorService mService;
 
-    private List<String> mPendingTasks = new ArrayList<>();
+    @GuardedBy("mPendingTasks")
+    private final List<String> mPendingTasks = new ArrayList<>();
 
-    public static synchronized SystemServerInitThreadPool get() {
-        if (sInstance == null) {
-            sInstance = new SystemServerInitThreadPool();
-        }
-        Preconditions.checkState(sInstance.mService != null, "Cannot get " + TAG
-                + " - it has been shut down");
-        return sInstance;
+    @GuardedBy("mPendingTasks")
+    private boolean mShutDown;
+
+    private SystemServerInitThreadPool() {
+        final int size = Runtime.getRuntime().availableProcessors();
+        Slog.i(TAG, "Creating instance with " + size + " threads");
+        mService = ConcurrentUtils.newFixedThreadPool(size,
+                "system-server-init-thread", Process.THREAD_PRIORITY_FOREGROUND);
     }
 
-    public Future<?> submit(Runnable runnable, String description) {
+    /**
+     * Gets the singleton.
+     *
+     * @throws IllegalStateException if it hasn't been started or has been shut down already.
+     */
+    public static SystemServerInitThreadPool get() {
+        synchronized (LOCK) {
+            Preconditions.checkState(sInstance != null, "Cannot get " + TAG
+                    + " - it has been shut down");
+            return sInstance;
+        }
+    }
+
+    /**
+     * Submits a task for execution.
+     */
+    public @NonNull Future<?> submit(@NonNull Runnable runnable, @NonNull String description) {
+        Preconditions.checkNotNull(description, "description cannot be null");
         synchronized (mPendingTasks) {
+            Preconditions.checkState(!mShutDown, TAG + " already shut down");
             mPendingTasks.add(description);
         }
         return mService.submit(() -> {
@@ -83,10 +107,36 @@
         });
     }
 
-    static synchronized void shutdown() {
-        if (sInstance != null && sInstance.mService != null) {
+    /**
+     * Starts it.
+     *
+     * <p>Note:</p> should only be called by {@link SystemServer}.
+     *
+     * @throws IllegalStateException if it has been started already without being shut down yet.
+     */
+    static void start() {
+        synchronized (LOCK) {
+            Preconditions.checkState(sInstance == null, TAG + " already started");
+            sInstance = new SystemServerInitThreadPool();
+        }
+    }
+
+    /**
+     * Shuts it down.
+     *
+     * <p>Note:</p> should only be called by {@link SystemServer}.
+     */
+    static void shutdown() {
+        synchronized (LOCK) {
+            if (sInstance == null) {
+                Slog.wtf(TAG, "Already shutdown", new Exception());
+                return;
+            }
+            synchronized (sInstance.mPendingTasks) {
+                sInstance.mShutDown = true;
+            }
             sInstance.mService.shutdown();
-            boolean terminated;
+            final boolean terminated;
             try {
                 terminated = sInstance.mService.awaitTermination(SHUTDOWN_TIMEOUT_MILLIS,
                         TimeUnit.MILLISECONDS);
@@ -100,7 +150,7 @@
                 // in the thread pool.
                 dumpStackTraces();
             }
-            List<Runnable> unstartedRunnables = sInstance.mService.shutdownNow();
+            final List<Runnable> unstartedRunnables = sInstance.mService.shutdownNow();
             if (!terminated) {
                 final List<String> copy = new ArrayList<>();
                 synchronized (sInstance.mPendingTasks) {
@@ -109,8 +159,7 @@
                 throw new IllegalStateException("Cannot shutdown. Unstarted tasks "
                         + unstartedRunnables + " Unfinished tasks " + copy);
             }
-            sInstance.mService = null; // Make mService eligible for GC
-            sInstance.mPendingTasks = null;
+            sInstance = null; // Make eligible for GC
             Slog.d(TAG, "Shutdown successful");
         }
     }
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index eb2723a..0f8a3b5 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -33,6 +33,9 @@
 import android.os.Message;
 import android.os.RemoteException;
 import android.os.UserHandle;
+import android.telephony.Annotation.DataFailureCause;
+import android.telephony.Annotation.RadioPowerState;
+import android.telephony.Annotation.SrvccState;
 import android.telephony.CallAttributes;
 import android.telephony.CallQuality;
 import android.telephony.CellInfo;
@@ -208,6 +211,10 @@
 
     private Map<Integer, List<EmergencyNumber>> mEmergencyNumberList;
 
+    private EmergencyNumber[] mOutgoingSmsEmergencyNumber;
+
+    private EmergencyNumber[] mOutgoingCallEmergencyNumber;
+
     private CallQuality[] mCallQuality;
 
     private CallAttributes[] mCallAttributes;
@@ -241,7 +248,7 @@
 
     private int mActiveDataSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
 
-    @TelephonyManager.RadioPowerState
+    @RadioPowerState
     private int mRadioPowerState = TelephonyManager.RADIO_POWER_UNAVAILABLE;
 
     private final LocalLog mLocalLog = new LocalLog(100);
@@ -266,6 +273,10 @@
                 PhoneStateListener.LISTEN_PRECISE_CALL_STATE |
                 PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE;
 
+    static final int READ_ACTIVE_EMERGENCY_SESSION_PERMISSION_MASK =
+            PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_CALL
+                    | PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_SMS;
+
     private static final int MSG_USER_SWITCHED = 1;
     private static final int MSG_UPDATE_DEFAULT_SUB = 2;
 
@@ -284,11 +295,12 @@
                 }
                 case MSG_UPDATE_DEFAULT_SUB: {
                     int newDefaultPhoneId = msg.arg1;
-                    int newDefaultSubId = (Integer)(msg.obj);
+                    int newDefaultSubId = msg.arg2;
                     if (VDBG) {
                         log("MSG_UPDATE_DEFAULT_SUB:current mDefaultSubId=" + mDefaultSubId
-                            + " current mDefaultPhoneId=" + mDefaultPhoneId + " newDefaultSubId= "
-                            + newDefaultSubId + " newDefaultPhoneId=" + newDefaultPhoneId);
+                                + " current mDefaultPhoneId=" + mDefaultPhoneId
+                                + " newDefaultSubId=" + newDefaultSubId
+                                + " newDefaultPhoneId=" + newDefaultPhoneId);
                     }
 
                     //Due to possible risk condition,(notify call back using the new
@@ -305,7 +317,7 @@
                     mDefaultSubId = newDefaultSubId;
                     mDefaultPhoneId = newDefaultPhoneId;
                     mLocalLog.log("Default subscription updated: mDefaultPhoneId="
-                            + mDefaultPhoneId + ", mDefaultSubId" + mDefaultSubId);
+                            + mDefaultPhoneId + ", mDefaultSubId=" + mDefaultSubId);
                 }
             }
         }
@@ -335,22 +347,25 @@
                 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
                 if (DBG) log("onReceive: userHandle=" + userHandle);
                 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHED, userHandle, 0));
-            } else if (action.equals(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED)) {
-                Integer newDefaultSubIdObj = new Integer(intent.getIntExtra(
-                        PhoneConstants.SUBSCRIPTION_KEY,
-                        SubscriptionManager.getDefaultSubscriptionId()));
-                int newDefaultPhoneId = intent.getIntExtra(PhoneConstants.PHONE_KEY,
-                    SubscriptionManager.getPhoneId(mDefaultSubId));
+            } else if (action.equals(SubscriptionManager.ACTION_DEFAULT_SUBSCRIPTION_CHANGED)) {
+                int newDefaultSubId = intent.getIntExtra(
+                        SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
+                        SubscriptionManager.getDefaultSubscriptionId());
+                int newDefaultPhoneId = intent.getIntExtra(
+                        PhoneConstants.PHONE_KEY,
+                        SubscriptionManager.getPhoneId(newDefaultSubId));
                 if (DBG) {
                     log("onReceive:current mDefaultSubId=" + mDefaultSubId
-                        + " current mDefaultPhoneId=" + mDefaultPhoneId + " newDefaultSubId= "
-                        + newDefaultSubIdObj + " newDefaultPhoneId=" + newDefaultPhoneId);
+                            + " current mDefaultPhoneId=" + mDefaultPhoneId
+                            + " newDefaultSubId=" + newDefaultSubId
+                            + " newDefaultPhoneId=" + newDefaultPhoneId);
                 }
 
-                if(validatePhoneId(newDefaultPhoneId) && (!newDefaultSubIdObj.equals(mDefaultSubId)
-                        || (newDefaultPhoneId != mDefaultPhoneId))) {
+                if (validatePhoneId(newDefaultPhoneId)
+                        && (newDefaultSubId != mDefaultSubId
+                                || newDefaultPhoneId != mDefaultPhoneId)) {
                     mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_DEFAULT_SUB,
-                            newDefaultPhoneId, 0, newDefaultSubIdObj));
+                            newDefaultPhoneId, newDefaultSubId));
                 }
             }
         }
@@ -370,7 +385,7 @@
         mContext = context;
         mBatteryStats = BatteryStatsService.getService();
 
-        int numPhones = TelephonyManager.getDefault().getPhoneCount();
+        int numPhones = TelephonyManager.getDefault().getMaxPhoneCount();
         if (DBG) log("TelephonyRegistry: ctor numPhones=" + numPhones);
         mNumPhones = numPhones;
         mCallState = new int[numPhones];
@@ -402,6 +417,8 @@
         mImsReasonInfo = new ArrayList<>();
         mPhysicalChannelConfigs = new ArrayList<>();
         mEmergencyNumberList = new HashMap<>();
+        mOutgoingCallEmergencyNumber = new EmergencyNumber[numPhones];
+        mOutgoingSmsEmergencyNumber = new EmergencyNumber[numPhones];
         for (int i = 0; i < numPhones; i++) {
             mCallState[i] =  TelephonyManager.CALL_STATE_IDLE;
             mDataActivity[i] = TelephonyManager.DATA_ACTIVITY_NONE;
@@ -449,7 +466,7 @@
         final IntentFilter filter = new IntentFilter();
         filter.addAction(Intent.ACTION_USER_SWITCHED);
         filter.addAction(Intent.ACTION_USER_REMOVED);
-        filter.addAction(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED);
+        filter.addAction(SubscriptionManager.ACTION_DEFAULT_SUBSCRIPTION_CHANGED);
         log("systemRunning register for intents");
         mContext.registerReceiver(mBroadcastReceiver, filter);
     }
@@ -947,13 +964,13 @@
         }
     }
 
-    public void notifyCallState(int state, String phoneNumber) {
+    public void notifyCallStateForAllSubs(int state, String phoneNumber) {
         if (!checkNotifyPermission("notifyCallState()")) {
             return;
         }
 
         if (VDBG) {
-            log("notifyCallState: state=" + state + " phoneNumber=" + phoneNumber);
+            log("notifyCallStateForAllSubs: state=" + state + " phoneNumber=" + phoneNumber);
         }
 
         synchronized (mRecords) {
@@ -980,13 +997,12 @@
                 SubscriptionManager.INVALID_SUBSCRIPTION_ID);
     }
 
-    public void notifyCallStateForPhoneId(int phoneId, int subId, int state,
-                String incomingNumber) {
+    public void notifyCallState(int phoneId, int subId, int state, String incomingNumber) {
         if (!checkNotifyPermission("notifyCallState()")) {
             return;
         }
         if (VDBG) {
-            log("notifyCallStateForPhoneId: subId=" + subId
+            log("notifyCallState: subId=" + subId
                 + " state=" + state + " incomingNumber=" + incomingNumber);
         }
         synchronized (mRecords) {
@@ -1080,10 +1096,10 @@
         synchronized (mRecords) {
             if (validatePhoneId(phoneId)) {
                 switch (activationType) {
-                    case PhoneConstants.SIM_ACTIVATION_TYPE_VOICE:
+                    case TelephonyManager.SIM_ACTIVATION_TYPE_VOICE:
                         mVoiceActivationState[phoneId] = activationState;
                         break;
-                    case PhoneConstants.SIM_ACTIVATION_TYPE_DATA:
+                    case TelephonyManager.SIM_ACTIVATION_TYPE_DATA:
                         mDataActivationState[phoneId] = activationState;
                         break;
                     default:
@@ -1096,7 +1112,7 @@
                                 + " state=" + activationState);
                     }
                     try {
-                        if ((activationType == PhoneConstants.SIM_ACTIVATION_TYPE_VOICE) &&
+                        if ((activationType == TelephonyManager.SIM_ACTIVATION_TYPE_VOICE) &&
                                 r.matchPhoneStateListenerEvent(
                                         PhoneStateListener.LISTEN_VOICE_ACTIVATION_STATE) &&
                                 idMatch(r.subId, subId, phoneId)) {
@@ -1107,7 +1123,7 @@
                             }
                             r.callback.onVoiceActivationStateChanged(activationState);
                         }
-                        if ((activationType == PhoneConstants.SIM_ACTIVATION_TYPE_DATA) &&
+                        if ((activationType == TelephonyManager.SIM_ACTIVATION_TYPE_DATA) &&
                                 r.matchPhoneStateListenerEvent(
                                         PhoneStateListener.LISTEN_DATA_ACTIVATION_STATE) &&
                                 idMatch(r.subId, subId, phoneId)) {
@@ -1190,7 +1206,7 @@
     public void notifyCarrierNetworkChange(boolean active) {
         // only CarrierService with carrier privilege rule should have the permission
         int[] subIds = Arrays.stream(SubscriptionManager.from(mContext)
-                    .getActiveSubscriptionIdList())
+                    .getActiveSubscriptionIdList(false))
                     .filter(i -> TelephonyPermissions.checkCarrierPrivilegeForSubId(i)).toArray();
         if (ArrayUtils.isEmpty(subIds)) {
             loge("notifyCarrierNetworkChange without carrier privilege");
@@ -1227,7 +1243,7 @@
     }
 
     public void notifyCellInfoForSubscriber(int subId, List<CellInfo> cellInfo) {
-        if (!checkNotifyPermission("notifyCellInfo()")) {
+        if (!checkNotifyPermission("notifyCellInfoForSubscriber()")) {
             return;
         }
         if (VDBG) {
@@ -1244,7 +1260,8 @@
                             checkFineLocationAccess(r, Build.VERSION_CODES.Q)) {
                         try {
                             if (DBG_LOC) {
-                                log("notifyCellInfo: mCellInfo=" + cellInfo + " r=" + r);
+                                log("notifyCellInfoForSubscriber: mCellInfo=" + cellInfo
+                                    + " r=" + r);
                             }
                             r.callback.onCellInfoChanged(cellInfo);
                         } catch (RemoteException ex) {
@@ -1704,7 +1721,7 @@
     }
 
     public void notifyPreciseDataConnectionFailed(int phoneId, int subId, String apnType,
-            String apn, @DataFailCause.FailCause int failCause) {
+            String apn, @DataFailureCause int failCause) {
         if (!checkNotifyPermission("notifyPreciseDataConnectionFailed()")) {
             return;
         }
@@ -1734,7 +1751,7 @@
     }
 
     @Override
-    public void notifySrvccStateChanged(int subId, @TelephonyManager.SrvccState int state) {
+    public void notifySrvccStateChanged(int subId, @SrvccState int state) {
         if (!checkNotifyPermission("notifySrvccStateChanged()")) {
             return;
         }
@@ -1841,8 +1858,7 @@
         }
     }
 
-    public void notifyRadioPowerStateChanged(int phoneId, int subId,
-                                             @TelephonyManager.RadioPowerState int state) {
+    public void notifyRadioPowerStateChanged(int phoneId, int subId, @RadioPowerState int state) {
         if (!checkNotifyPermission("notifyRadioPowerStateChanged()")) {
             return;
         }
@@ -1906,6 +1922,56 @@
     }
 
     @Override
+    public void notifyOutgoingEmergencyCall(int phoneId, int subId,
+            EmergencyNumber emergencyNumber) {
+        if (!checkNotifyPermission("notifyOutgoingEmergencyCall()")) {
+            return;
+        }
+        synchronized (mRecords) {
+            if (validatePhoneId(phoneId)) {
+                mOutgoingCallEmergencyNumber[phoneId] = emergencyNumber;
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_CALL)
+                                    && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onOutgoingEmergencyCall(emergencyNumber);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
+                    }
+                }
+            }
+            handleRemoveListLocked();
+        }
+    }
+
+    @Override
+    public void notifyOutgoingEmergencySms(int phoneId, int subId,
+            EmergencyNumber emergencyNumber) {
+        if (!checkNotifyPermission("notifyOutgoingEmergencySms()")) {
+            return;
+        }
+        synchronized (mRecords) {
+            if (validatePhoneId(phoneId)) {
+                mOutgoingSmsEmergencyNumber[phoneId] = emergencyNumber;
+                for (Record r : mRecords) {
+                    if (r.matchPhoneStateListenerEvent(
+                            PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_SMS)
+                                    && idMatch(r.subId, subId, phoneId)) {
+                        try {
+                            r.callback.onOutgoingEmergencySms(emergencyNumber);
+                        } catch (RemoteException ex) {
+                            mRemoveList.add(r.binder);
+                        }
+                    }
+                }
+            }
+            handleRemoveListLocked();
+        }
+    }
+
+    @Override
     public void notifyCallQualityChanged(CallQuality callQuality, int phoneId, int subId,
             int callNetworkType) {
         if (!checkNotifyPermission("notifyCallQualityChanged()")) {
@@ -1977,6 +2043,8 @@
                 pw.println("mCallAttributes=" + mCallAttributes[i]);
                 pw.println("mCallNetworkType=" + mCallNetworkType[i]);
                 pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState[i]);
+                pw.println("mOutgoingCallEmergencyNumber=" + mOutgoingCallEmergencyNumber[i]);
+                pw.println("mOutgoingSmsEmergencyNumber=" + mOutgoingSmsEmergencyNumber[i]);
                 pw.decreaseIndent();
             }
             pw.println("mCarrierNetworkChangeState=" + mCarrierNetworkChangeState);
@@ -2161,7 +2229,7 @@
 
     private void broadcastPreciseDataConnectionStateChanged(int state, int networkType,
             String apnType, String apn, LinkProperties linkProperties,
-            @DataFailCause.FailCause int failCause) {
+            @DataFailureCause int failCause) {
         Intent intent = new Intent(TelephonyManager.ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED);
         intent.putExtra(PhoneConstants.STATE_KEY, state);
         intent.putExtra(PhoneConstants.DATA_NETWORK_TYPE_KEY, networkType);
@@ -2246,6 +2314,11 @@
                     android.Manifest.permission.READ_PRECISE_PHONE_STATE, null);
         }
 
+        if ((events & READ_ACTIVE_EMERGENCY_SESSION_PERMISSION_MASK) != 0) {
+            mContext.enforceCallingOrSelfPermission(
+                    android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION, null);
+        }
+
         if ((events & PhoneStateListener.LISTEN_OEM_HOOK_RAW_EVENT) != 0) {
             mContext.enforceCallingOrSelfPermission(
                     android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, null);
diff --git a/services/core/java/com/android/server/UiThread.java b/services/core/java/com/android/server/UiThread.java
index b2fa684..34fc9ab 100644
--- a/services/core/java/com/android/server/UiThread.java
+++ b/services/core/java/com/android/server/UiThread.java
@@ -21,6 +21,8 @@
 import android.os.Process;
 import android.os.Trace;
 
+import com.android.internal.annotations.VisibleForTesting;
+
 /**
  * Shared singleton thread for showing UI.  This is a foreground thread, and in
  * additional should not have operations that can take more than a few ms scheduled
@@ -68,4 +70,20 @@
             return sHandler;
         }
     }
+
+    /**
+     * Disposes current ui thread if it's initialized. Should only be used in tests to set up a
+     * new environment.
+     */
+    @VisibleForTesting
+    public static void dispose() {
+        synchronized (UiThread.class) {
+            if (sInstance == null) {
+                return;
+            }
+
+            getHandler().runWithScissors(sInstance::quit, 0 /* timeout */);
+            sInstance = null;
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/VibratorService.java b/services/core/java/com/android/server/VibratorService.java
index 9936d73..d622fb4 100644
--- a/services/core/java/com/android/server/VibratorService.java
+++ b/services/core/java/com/android/server/VibratorService.java
@@ -29,6 +29,7 @@
 import android.database.ContentObserver;
 import android.hardware.input.InputManager;
 import android.hardware.vibrator.V1_0.EffectStrength;
+import android.hardware.vibrator.V1_4.Capabilities;
 import android.icu.text.DateFormat;
 import android.media.AudioAttributes;
 import android.media.AudioManager;
@@ -108,6 +109,9 @@
     // If a vibration is playing for longer than 5s, it's probably not haptic feedback.
     private static final long MAX_HAPTIC_FEEDBACK_DURATION = 5000;
 
+    // If HAL supports callbacks set the timeout to ASYNC_TIMEOUT_MULTIPLIER * duration.
+    private static final long ASYNC_TIMEOUT_MULTIPLIER = 2;
+
 
     // A mapping from the intensity adjustment to the scaling to apply, where the intensity
     // adjustment is defined as the delta between the default intensity level and the user selected
@@ -123,6 +127,7 @@
     private final boolean mAllowPriorityVibrationsInLowPowerMode;
     private final boolean mSupportsAmplitudeControl;
     private final boolean mSupportsExternalControl;
+    private final long mCapabilities;
     private final int mDefaultVibrationAmplitude;
     private final SparseArray<VibrationEffect> mFallbackEffects;
     private final SparseArray<Integer> mProcStatesCache = new SparseArray();
@@ -163,9 +168,10 @@
     static native void vibratorOff();
     static native boolean vibratorSupportsAmplitudeControl();
     static native void vibratorSetAmplitude(int amplitude);
-    static native long vibratorPerformEffect(long effect, long strength);
+    static native long vibratorPerformEffect(long effect, long strength, Vibration vibration);
     static native boolean vibratorSupportsExternalControl();
     static native void vibratorSetExternalControl(boolean enabled);
+    static native long vibratorGetCapabilities();
 
     private final IUidObserver mUidObserver = new IUidObserver.Stub() {
         @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
@@ -226,6 +232,14 @@
             }
         }
 
+        private void onComplete() {
+            synchronized (mLock) {
+                if (this == mCurrentVibration) {
+                    doCancelVibrateLocked();
+                }
+            }
+        }
+
         public boolean hasTimeoutLongerThan(long millis) {
             final long duration = effect.getDuration();
             return duration >= 0 && duration > millis;
@@ -347,6 +361,7 @@
 
         mSupportsAmplitudeControl = vibratorSupportsAmplitudeControl();
         mSupportsExternalControl = vibratorSupportsExternalControl();
+        mCapabilities = vibratorGetCapabilities();
 
         mContext = context;
         PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
@@ -1135,10 +1150,14 @@
             }
             // Input devices don't support prebaked effect, so skip trying it with them.
             if (!usingInputDeviceVibrators) {
-                long timeout = vibratorPerformEffect(prebaked.getId(),
-                        prebaked.getEffectStrength());
+                long duration = vibratorPerformEffect(prebaked.getId(),
+                        prebaked.getEffectStrength(), vib);
+                long timeout = duration;
+                if ((mCapabilities & Capabilities.PERFORM_COMPLETION_CALLBACK) != 0) {
+                    timeout *= ASYNC_TIMEOUT_MULTIPLIER;
+                }
                 if (timeout > 0) {
-                    noteVibratorOnLocked(vib.uid, timeout);
+                    noteVibratorOnLocked(vib.uid, duration);
                     return timeout;
                 }
             }
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index e7569be..9209a21 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -192,34 +192,38 @@
         @Override
         public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
             synchronized (mAm) {
-                final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
-                final int N = smap.mServicesByInstanceName.size();
-                final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
-                for (int i = 0; i < N; i++) {
-                    final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
-                    if (uid == r.serviceInfo.applicationInfo.uid
-                            || packageName.equals(r.serviceInfo.packageName)) {
-                        if (r.isForeground) {
-                            toStop.add(r);
-                        }
-                    }
-                }
+                stopAllForegroundServicesLocked(uid, packageName);
+            }
+        }
+    }
 
-                // Now stop them all
-                final int numToStop = toStop.size();
-                if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
-                    Slog.i(TAG, "Package " + packageName + "/" + uid
-                            + " entering FAS with foreground services");
-                }
-                for (int i = 0; i < numToStop; i++) {
-                    final ServiceRecord r = toStop.get(i);
-                    if (DEBUG_FOREGROUND_SERVICE) {
-                        Slog.i(TAG, "  Stopping fg for service " + r);
-                    }
-                    setServiceForegroundInnerLocked(r, 0, null, 0, 0);
+    void stopAllForegroundServicesLocked(final int uid, final String packageName) {
+        final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
+        final int N = smap.mServicesByInstanceName.size();
+        final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
+        for (int i = 0; i < N; i++) {
+            final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
+            if (uid == r.serviceInfo.applicationInfo.uid
+                    || packageName.equals(r.serviceInfo.packageName)) {
+                if (r.isForeground) {
+                    toStop.add(r);
                 }
             }
         }
+
+        // Now stop them all
+        final int numToStop = toStop.size();
+        if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
+            Slog.i(TAG, "Package " + packageName + "/" + uid
+                    + " in FAS with foreground services");
+        }
+        for (int i = 0; i < numToStop; i++) {
+            final ServiceRecord r = toStop.get(i);
+            if (DEBUG_FOREGROUND_SERVICE) {
+                Slog.i(TAG, "  Stopping fg for service " + r);
+            }
+            setServiceForegroundInnerLocked(r, 0, null, 0, 0);
+        }
     }
 
     /**
@@ -1019,12 +1023,23 @@
                         }
                     }
                     if (!aa.mAppOnTop) {
-                        if (active == null) {
-                            active = new ArrayList<>();
+                        // Transitioning a fg-service host app out of top: if it's bg restricted,
+                        // it loses the fg service state now.
+                        if (!appRestrictedAnyInBackground(aa.mUid, aa.mPackageName)) {
+                            if (active == null) {
+                                active = new ArrayList<>();
+                            }
+                            if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
+                                    + aa.mPackageName + ", uid=" + aa.mUid);
+                            active.add(aa);
+                        } else {
+                            if (DEBUG_FOREGROUND_SERVICE) {
+                                Slog.d(TAG, "bg-restricted app "
+                                        + aa.mPackageName + "/" + aa.mUid
+                                        + " exiting top; demoting fg services ");
+                            }
+                            stopAllForegroundServicesLocked(aa.mUid, aa.mPackageName);
                         }
-                        if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
-                                + aa.mPackageName + ", uid=" + aa.mUid);
-                        active.add(aa);
                     }
                 }
                 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
@@ -1749,7 +1764,7 @@
             // Once the apps have become associated, if one of them is caller is ephemeral
             // the target app should now be able to see the calling app
             mAm.grantImplicitAccess(callerApp.userId, service,
-                    UserHandle.getAppId(callerApp.uid), UserHandle.getAppId(s.appInfo.uid));
+                    callerApp.uid, UserHandle.getAppId(s.appInfo.uid));
 
             AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
             ConnectionRecord c = new ConnectionRecord(b, activity,
@@ -2802,7 +2817,7 @@
                 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
                         si.getUriPermissionsLocked());
             }
-            mAm.grantImplicitAccess(r.userId, si.intent, UserHandle.getAppId(si.callingId),
+            mAm.grantImplicitAccess(r.userId, si.intent, si.callingId,
                     UserHandle.getAppId(r.appInfo.uid)
             );
             bumpServiceExecutingLocked(r, execInFg, "start");
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 3c7cb88..4bca7a1 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -233,6 +233,7 @@
 import android.os.BatteryStats;
 import android.os.Binder;
 import android.os.BinderProxy;
+import android.os.BugreportParams;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Debug;
@@ -2404,7 +2405,8 @@
         final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
         mProcessList.init(this, activeUids);
         mLowMemDetector = null;
-        mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids, handlerThread);
+        mOomAdjuster = hasHandlerThread
+                ? new OomAdjuster(this, mProcessList, activeUids, handlerThread) : null;
 
         mIntentFirewall = hasHandlerThread
                 ? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null;
@@ -5013,7 +5015,9 @@
             if (preBindAgent != null) {
                 thread.attachAgent(preBindAgent);
             }
-
+            if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
+                thread.attachStartupAgents(app.info.dataDir);
+            }
 
             // Figure out whether the app needs to run in autofill compat mode.
             AutofillOptions autofillOptions = null;
@@ -5320,10 +5324,42 @@
                     });
             mUserController.scheduleStartProfiles();
         }
+        // UART is on if init's console service is running, send a warning notification.
+        showConsoleNotificationIfActive();
 
         t.traceEnd();
     }
 
+    private void showConsoleNotificationIfActive() {
+        if (!SystemProperties.get("init.svc.console").equals("running")) {
+            return;
+        }
+        String title = mContext
+                .getString(com.android.internal.R.string.console_running_notification_title);
+        String message = mContext
+                .getString(com.android.internal.R.string.console_running_notification_message);
+        Notification notification =
+                new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
+                        .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
+                        .setWhen(0)
+                        .setOngoing(true)
+                        .setTicker(title)
+                        .setDefaults(0)  // please be quiet
+                        .setColor(mContext.getColor(
+                                com.android.internal.R.color
+                                        .system_notification_accent_color))
+                        .setContentTitle(title)
+                        .setContentText(message)
+                        .setVisibility(Notification.VISIBILITY_PUBLIC)
+                        .build();
+
+        NotificationManager notificationManager =
+                mContext.getSystemService(NotificationManager.class);
+        notificationManager.notifyAsUser(
+                null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL);
+
+    }
+
     @Override
     public void bootAnimationComplete() {
         final boolean callFinishBooting;
@@ -6118,9 +6154,9 @@
     }
 
     @VisibleForTesting
-    public void grantImplicitAccess(int userId, Intent intent, int callingAppId, int targetAppId) {
+    public void grantImplicitAccess(int userId, Intent intent, int callingUid, int targetAppId) {
         getPackageManagerInternalLocked().
-                grantImplicitAccess(userId, intent, callingAppId, targetAppId);
+                grantImplicitAccess(userId, intent, callingUid, targetAppId);
     }
 
     /**
@@ -7407,6 +7443,7 @@
                         dst.setProcess(r);
                         dst.notifyAll();
                     }
+                    dst.mRestartCount = 0;
                     updateOomAdjLocked(r, true, OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
                     maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
                             src.info.authority);
@@ -8223,22 +8260,22 @@
             @Nullable String shareDescription, int bugreportType) {
         String type = null;
         switch (bugreportType) {
-            case ActivityManager.BUGREPORT_OPTION_FULL:
+            case BugreportParams.BUGREPORT_MODE_FULL:
                 type = "bugreportfull";
                 break;
-            case ActivityManager.BUGREPORT_OPTION_INTERACTIVE:
+            case BugreportParams.BUGREPORT_MODE_INTERACTIVE:
                 type = "bugreportplus";
                 break;
-            case ActivityManager.BUGREPORT_OPTION_REMOTE:
+            case BugreportParams.BUGREPORT_MODE_REMOTE:
                 type = "bugreportremote";
                 break;
-            case ActivityManager.BUGREPORT_OPTION_WEAR:
+            case BugreportParams.BUGREPORT_MODE_WEAR:
                 type = "bugreportwear";
                 break;
-            case ActivityManager.BUGREPORT_OPTION_TELEPHONY:
+            case BugreportParams.BUGREPORT_MODE_TELEPHONY:
                 type = "bugreporttelephony";
                 break;
-            case ActivityManager.BUGREPORT_OPTION_WIFI:
+            case BugreportParams.BUGREPORT_MODE_WIFI:
                 type = "bugreportwifi";
                 break;
             default:
@@ -8273,12 +8310,14 @@
         final boolean useApi = FeatureFlagUtils.isEnabled(mContext,
                 FeatureFlagUtils.USE_BUGREPORT_API);
 
-        if (useApi && bugreportType == ActivityManager.BUGREPORT_OPTION_INTERACTIVE) {
+        if (useApi) {
             // Create intent to trigger Bugreport API via Shell
             Intent triggerShellBugreport = new Intent();
             triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED);
             triggerShellBugreport.setPackage(SHELL_APP_PACKAGE);
             triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType);
+            triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+            triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
             if (shareTitle != null) {
                 triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle);
             }
@@ -8307,7 +8346,7 @@
     @Override
     public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
         requestBugReportWithDescription(shareTitle, shareDescription,
-                ActivityManager.BUGREPORT_OPTION_TELEPHONY);
+                BugreportParams.BUGREPORT_MODE_TELEPHONY);
     }
 
     /**
@@ -8319,7 +8358,7 @@
     @Override
     public void requestWifiBugReport(String shareTitle, String shareDescription) {
         requestBugReportWithDescription(shareTitle, shareDescription,
-                ActivityManager.BUGREPORT_OPTION_WIFI);
+                BugreportParams.BUGREPORT_MODE_WIFI);
     }
 
     /**
@@ -8327,7 +8366,7 @@
      */
     @Override
     public void requestInteractiveBugReport() {
-        requestBugReportWithDescription(null, null, ActivityManager.BUGREPORT_OPTION_INTERACTIVE);
+        requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE);
     }
 
     /**
@@ -8338,7 +8377,7 @@
     public void requestInteractiveBugReportWithDescription(String shareTitle,
             String shareDescription) {
         requestBugReportWithDescription(shareTitle, shareDescription,
-                ActivityManager.BUGREPORT_OPTION_INTERACTIVE);
+                BugreportParams.BUGREPORT_MODE_INTERACTIVE);
     }
 
     /**
@@ -8346,7 +8385,7 @@
      */
     @Override
     public void requestFullBugReport() {
-        requestBugReportWithDescription(null, null, ActivityManager.BUGREPORT_OPTION_FULL);
+        requestBugReportWithDescription(null, null,  BugreportParams.BUGREPORT_MODE_FULL);
     }
 
     /**
@@ -8354,7 +8393,7 @@
      */
     @Override
     public void requestRemoteBugReport() {
-        requestBugReportWithDescription(null, null, ActivityManager.BUGREPORT_OPTION_REMOTE);
+        requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE);
     }
 
     public void registerProcessObserver(IProcessObserver observer) {
@@ -9699,6 +9738,10 @@
             sb.append("Foreground: ")
                     .append(process.isInterestingToUserLocked() ? "Yes" : "No")
                     .append("\n");
+            if (process.startTime > 0) {
+                long runtimeMillis = SystemClock.elapsedRealtime() - process.startTime;
+                sb.append("Process-Runtime: ").append(runtimeMillis).append("\n");
+            }
         }
         if (activityShortComponentName != null) {
             sb.append("Activity: ").append(activityShortComponentName).append("\n");
@@ -13848,9 +13891,20 @@
         return false;
     }
 
+    /**
+     * Remove the dying provider from known provider map and launching provider map.
+     * @param proc The dying process recoder
+     * @param cpr The provider to be removed.
+     * @param always If true, remove the provider from launching map always, no more restart attempt
+     * @return true if the given provider is in launching
+     */
     private final boolean removeDyingProviderLocked(ProcessRecord proc,
             ContentProviderRecord cpr, boolean always) {
-        final boolean inLaunching = mLaunchingProviders.contains(cpr);
+        boolean inLaunching = mLaunchingProviders.contains(cpr);
+        if (inLaunching && !always && ++cpr.mRestartCount > ContentProviderRecord.MAX_RETRY_COUNT) {
+            // It's being launched but we've reached maximum attempts, force the removal
+            always = true;
+        }
 
         if (!inLaunching || always) {
             synchronized (cpr) {
@@ -13902,6 +13956,8 @@
 
         if (inLaunching && always) {
             mLaunchingProviders.remove(cpr);
+            cpr.mRestartCount = 0;
+            inLaunching = false;
         }
         return inLaunching;
     }
@@ -14117,6 +14173,10 @@
         for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
             ContentProviderRecord cpr = mLaunchingProviders.get(i);
             if (cpr.launchingApp == app) {
+                if (++cpr.mRestartCount > ContentProviderRecord.MAX_RETRY_COUNT) {
+                    // It's being launched but we've reached maximum attempts, mark it as bad
+                    alwaysBad = true;
+                }
                 if (!alwaysBad && !app.bad && cpr.hasConnectionOrHandle()) {
                     restart = true;
                 } else {
@@ -15267,7 +15327,7 @@
                                 mBatteryStatsService.removeUid(uid);
                                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
                                     mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
-                                            intent.getData().getSchemeSpecificPart());
+                                            intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
                                 } else {
                                     mAppOpsService.uidRemoved(uid);
                                 }
@@ -18295,7 +18355,7 @@
 
         @Override
         public int getCurrentUserId() {
-            return mUserController.getCurrentUserIdLU();
+            return mUserController.getCurrentUserId();
         }
 
         @Override
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index d46c626..8be2438 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -1016,18 +1016,23 @@
 
     int runBugReport(PrintWriter pw) throws RemoteException {
         String opt;
-        int bugreportType = ActivityManager.BUGREPORT_OPTION_FULL;
+        boolean fullBugreport = true;
         while ((opt=getNextOption()) != null) {
             if (opt.equals("--progress")) {
-                bugreportType = ActivityManager.BUGREPORT_OPTION_INTERACTIVE;
+                fullBugreport = false;
+                mInterface.requestInteractiveBugReport();
             } else if (opt.equals("--telephony")) {
-                bugreportType = ActivityManager.BUGREPORT_OPTION_TELEPHONY;
+                fullBugreport = false;
+                // no title and description specified
+                mInterface.requestTelephonyBugReport("" /* no title */, "" /* no descriptions */);
             } else {
                 getErrPrintWriter().println("Error: Unknown option: " + opt);
                 return -1;
             }
         }
-        mInterface.requestBugReport(bugreportType);
+        if (fullBugreport) {
+            mInterface.requestFullBugReport();
+        }
         pw.println("Your lovely bug report is being created; please be patient.");
         return 0;
     }
@@ -2854,7 +2859,21 @@
         return 0;
     }
 
-    private int runCompat(PrintWriter pw) {
+    private void killPackage(String packageName, PrintWriter pw) throws RemoteException {
+        int uid = mPm.getPackageUid(packageName, 0, mUserId);
+        if (uid < 0) {
+            // uid is negative if the package wasn't found.
+            pw.println("Didn't find package " + packageName + " on device.");
+        } else {
+            pw.println("Killing package " + packageName + " (UID " + uid + ").");
+            final long origId = Binder.clearCallingIdentity();
+            mInterface.killUid(UserHandle.getAppId(uid),
+                    UserHandle.USER_ALL, "killPackage");
+            Binder.restoreCallingIdentity(origId);
+        }
+    }
+
+    private int runCompat(PrintWriter pw) throws RemoteException {
         final CompatConfig config = CompatConfig.get();
         String toggleValue = getNextArgRequired();
         long changeId;
@@ -2868,13 +2887,14 @@
             pw.println("Unknown or invalid change: '" + changeIdString + "'.");
         }
         String packageName = getNextArgRequired();
-        switch(toggleValue) {
+        switch (toggleValue) {
             case "enable":
                 if (!config.addOverride(changeId, packageName, true)) {
                     pw.println("Warning! Change " + changeId + " is not known yet. Enabling it"
                             + " could have no effect.");
                 }
                 pw.println("Enabled change " + changeId + " for " + packageName + ".");
+                killPackage(packageName, pw);
                 return 0;
             case "disable":
                 if (!config.addOverride(changeId, packageName, false)) {
@@ -2882,11 +2902,13 @@
                             + " could have no effect.");
                 }
                 pw.println("Disabled change " + changeId + " for " + packageName + ".");
+                killPackage(packageName, pw);
                 return 0;
             case "reset":
                 if (config.removeOverride(changeId, packageName)) {
                     pw.println("Reset change " + changeId + " for " + packageName
                             + " to default value.");
+                    killPackage(packageName, pw);
                 } else {
                     pw.println("No override exists for changeId " + changeId + ".");
                 }
@@ -3205,6 +3227,7 @@
             pw.println("      Write all pending state to storage.");
             pw.println("  compat enable|disable|reset <CHANGE_ID|CHANGE_NAME> <PACKAGE_NAME>");
             pw.println("      Toggles a change either by id or by name for <PACKAGE_NAME>.");
+            pw.println("      It kills <PACKAGE_NAME> (to allow the toggle to take effect).");
             pw.println();
             Intent.printIntentArgsHelp(pw, "");
         }
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index 56208a95..59c2326 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -446,7 +446,9 @@
         mHandler.removeCallbacksAndMessages(msgToken);
         // ...then schedule the removal of the token after the extended timeout
         mHandler.postAtTime(() -> {
-            app.removeAllowBackgroundActivityStartsToken(r);
+            synchronized (mService) {
+                app.removeAllowBackgroundActivityStartsToken(r);
+            }
         }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
     }
 
diff --git a/services/core/java/com/android/server/am/ContentProviderRecord.java b/services/core/java/com/android/server/am/ContentProviderRecord.java
index 46dfc7c..d8d8ccc 100644
--- a/services/core/java/com/android/server/am/ContentProviderRecord.java
+++ b/services/core/java/com/android/server/am/ContentProviderRecord.java
@@ -38,6 +38,9 @@
 import java.util.ArrayList;
 
 final class ContentProviderRecord implements ComponentName.WithComponentName {
+    // Maximum attempts to bring up the content provider before giving up.
+    static final int MAX_RETRY_COUNT = 3;
+
     final ActivityManagerService service;
     public final ProviderInfo info;
     final int uid;
@@ -54,6 +57,7 @@
     ArrayMap<IBinder, ExternalProcessHandle> externalProcessTokenToHandle;
     // Count for external process for which we have no handles.
     int externalProcessNoHandleCount;
+    int mRestartCount; // number of times we tried before bringing up it successfully.
     ProcessRecord proc; // if non-null, hosting process.
     ProcessRecord launchingApp; // if non-null, waiting for this app to be launched.
     String stringName;
diff --git a/services/core/java/com/android/server/am/MemoryStatUtil.java b/services/core/java/com/android/server/am/MemoryStatUtil.java
index fd64df9..2081b17 100644
--- a/services/core/java/com/android/server/am/MemoryStatUtil.java
+++ b/services/core/java/com/android/server/am/MemoryStatUtil.java
@@ -39,8 +39,7 @@
  * Static utility methods related to {@link MemoryStat}.
  */
 public final class MemoryStatUtil {
-    static final int BYTES_IN_KILOBYTE = 1024;
-    static final long JIFFY_NANOS = 1_000_000_000 / Os.sysconf(OsConstants._SC_CLK_TCK);
+    static final int PAGE_SIZE = (int) Os.sysconf(OsConstants._SC_PAGESIZE);
 
     private static final String TAG = TAG_WITH_CLASS_NAME ? "MemoryStatUtil" : TAG_AM;
 
@@ -52,10 +51,6 @@
     private static final String MEMORY_STAT_FILE_FMT = "/dev/memcg/apps/uid_%d/pid_%d/memory.stat";
     /** Path to procfs stat file for logging app start memory state */
     private static final String PROC_STAT_FILE_FMT = "/proc/%d/stat";
-    /** Path to procfs status file for logging app memory state */
-    private static final String PROC_STATUS_FILE_FMT = "/proc/%d/status";
-    /** Path to procfs cmdline file. Used with pid: /proc/pid/cmdline. */
-    private static final String PROC_CMDLINE_FILE_FMT = "/proc/%d/cmdline";
 
     private static final Pattern PGFAULT = Pattern.compile("total_pgfault (\\d+)");
     private static final Pattern PGMAJFAULT = Pattern.compile("total_pgmajfault (\\d+)");
@@ -63,16 +58,9 @@
     private static final Pattern CACHE_IN_BYTES = Pattern.compile("total_cache (\\d+)");
     private static final Pattern SWAP_IN_BYTES = Pattern.compile("total_swap (\\d+)");
 
-    private static final Pattern PROCFS_RSS_IN_KILOBYTES =
-            Pattern.compile("VmRSS:\\s*(\\d+)\\s*kB");
-    private static final Pattern PROCFS_ANON_RSS_IN_KILOBYTES =
-            Pattern.compile("RssAnon:\\s*(\\d+)\\s*kB");
-    private static final Pattern PROCFS_SWAP_IN_KILOBYTES =
-            Pattern.compile("VmSwap:\\s*(\\d+)\\s*kB");
-
     private static final int PGFAULT_INDEX = 9;
     private static final int PGMAJFAULT_INDEX = 11;
-    private static final int START_TIME_INDEX = 21;
+    private static final int RSS_IN_PAGES_INDEX = 23;
 
     private MemoryStatUtil() {}
 
@@ -106,19 +94,7 @@
     @Nullable
     public static MemoryStat readMemoryStatFromProcfs(int pid) {
         final String statPath = String.format(Locale.US, PROC_STAT_FILE_FMT, pid);
-        final String statusPath = String.format(Locale.US, PROC_STATUS_FILE_FMT, pid);
-        return parseMemoryStatFromProcfs(readFileContents(statPath), readFileContents(statusPath));
-    }
-
-    /**
-     * Reads cmdline of a process from procfs.
-     *
-     * Returns content of /proc/pid/cmdline (e.g. /system/bin/statsd) or an empty string
-     * if the file is not available.
-     */
-    public static String readCmdlineFromProcfs(int pid) {
-        final String path = String.format(Locale.US, PROC_CMDLINE_FILE_FMT, pid);
-        return parseCmdlineFromProcfs(readFileContents(path));
+        return parseMemoryStatFromProcfs(readFileContents(statPath));
     }
 
     private static String readFileContents(String path) {
@@ -160,31 +136,19 @@
      */
     @VisibleForTesting
     @Nullable
-    static MemoryStat parseMemoryStatFromProcfs(
-            String procStatContents, String procStatusContents) {
+    static MemoryStat parseMemoryStatFromProcfs(String procStatContents) {
         if (procStatContents == null || procStatContents.isEmpty()) {
             return null;
         }
-        if (procStatusContents == null || procStatusContents.isEmpty()) {
-            return null;
-        }
-
         final String[] splits = procStatContents.split(" ");
         if (splits.length < 24) {
             return null;
         }
-
         try {
             final MemoryStat memoryStat = new MemoryStat();
             memoryStat.pgfault = Long.parseLong(splits[PGFAULT_INDEX]);
             memoryStat.pgmajfault = Long.parseLong(splits[PGMAJFAULT_INDEX]);
-            memoryStat.rssInBytes =
-                tryParseLong(PROCFS_RSS_IN_KILOBYTES, procStatusContents) * BYTES_IN_KILOBYTE;
-            memoryStat.anonRssInBytes =
-                tryParseLong(PROCFS_ANON_RSS_IN_KILOBYTES, procStatusContents) * BYTES_IN_KILOBYTE;
-            memoryStat.swapInBytes =
-                tryParseLong(PROCFS_SWAP_IN_KILOBYTES, procStatusContents) * BYTES_IN_KILOBYTE;
-            memoryStat.startTimeNanos = Long.parseLong(splits[START_TIME_INDEX]) * JIFFY_NANOS;
+            memoryStat.rssInBytes = Long.parseLong(splits[RSS_IN_PAGES_INDEX]) * PAGE_SIZE;
             return memoryStat;
         } catch (NumberFormatException e) {
             Slog.e(TAG, "Failed to parse value", e);
@@ -193,23 +157,6 @@
     }
 
     /**
-     * Parses cmdline out of the contents of the /proc/pid/cmdline file in procfs.
-     *
-     * Parsing is required to strip anything after first null byte.
-     */
-    @VisibleForTesting
-    static String parseCmdlineFromProcfs(String cmdline) {
-        if (cmdline == null) {
-            return "";
-        }
-        int firstNullByte = cmdline.indexOf("\0");
-        if (firstNullByte == -1) {
-            return cmdline;
-        }
-        return cmdline.substring(0, firstNullByte);
-    }
-
-    /**
      * Returns whether per-app memcg is available on device.
      */
     static boolean hasMemcg() {
@@ -237,13 +184,9 @@
         public long pgmajfault;
         /** For memcg stats, the anon rss + swap cache size. Otherwise total RSS. */
         public long rssInBytes;
-        /** Number of bytes of the anonymous RSS. Only present for non-memcg stats. */
-        public long anonRssInBytes;
         /** Number of bytes of page cache memory. Only present for memcg stats. */
         public long cacheInBytes;
         /** Number of bytes of swap usage */
         public long swapInBytes;
-        /** Device time when the processes started. */
-        public long startTimeNanos;
     }
 }
diff --git a/services/core/java/com/android/server/am/OomAdjuster.java b/services/core/java/com/android/server/am/OomAdjuster.java
index 3c2aee4..bb214bd 100644
--- a/services/core/java/com/android/server/am/OomAdjuster.java
+++ b/services/core/java/com/android/server/am/OomAdjuster.java
@@ -30,7 +30,7 @@
 import static android.app.ActivityManager.PROCESS_STATE_TOP;
 import static android.app.ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND;
 import static android.os.Process.SCHED_OTHER;
-import static android.os.Process.THREAD_GROUP_BG_NONINTERACTIVE;
+import static android.os.Process.THREAD_GROUP_BACKGROUND;
 import static android.os.Process.THREAD_GROUP_DEFAULT;
 import static android.os.Process.THREAD_GROUP_RESTRICTED;
 import static android.os.Process.THREAD_GROUP_TOP_APP;
@@ -1759,7 +1759,7 @@
                 int processGroup;
                 switch (curSchedGroup) {
                     case ProcessList.SCHED_GROUP_BACKGROUND:
-                        processGroup = THREAD_GROUP_BG_NONINTERACTIVE;
+                        processGroup = THREAD_GROUP_BACKGROUND;
                         break;
                     case ProcessList.SCHED_GROUP_TOP_APP:
                     case ProcessList.SCHED_GROUP_TOP_APP_BOUND:
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index c0af814..af126f2 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -215,7 +215,7 @@
     // Memory pages are 4K.
     static final int PAGE_SIZE = 4 * 1024;
 
-    // Activity manager's version of Process.THREAD_GROUP_BG_NONINTERACTIVE
+    // Activity manager's version of Process.THREAD_GROUP_BACKGROUND
     static final int SCHED_GROUP_BACKGROUND = 0;
       // Activity manager's version of Process.THREAD_GROUP_RESTRICTED
     static final int SCHED_GROUP_RESTRICTED = 1;
diff --git a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
index 64f4a35..4a6e63f 100644
--- a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
+++ b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
@@ -86,6 +86,7 @@
         DeviceConfig.NAMESPACE_NETD_NATIVE,
         DeviceConfig.NAMESPACE_RUNTIME_NATIVE,
         DeviceConfig.NAMESPACE_RUNTIME_NATIVE_BOOT,
+        DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
     };
 
     private final String[] mGlobalSettings;
@@ -276,4 +277,4 @@
         String settingValue = Settings.Global.getString(mContentResolver, settingName);
         setProperty(propName, settingValue);
     }
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/am/TEST_MAPPING b/services/core/java/com/android/server/am/TEST_MAPPING
index 21d4925..bc4707f 100644
--- a/services/core/java/com/android/server/am/TEST_MAPPING
+++ b/services/core/java/com/android/server/am/TEST_MAPPING
@@ -33,7 +33,6 @@
     },
     {
       "name": "FrameworksMockingServicesTests",
-      "file_patterns": ["AppCompactor\\.java"],
       "options": [
         {
           "include-filter": "com.android.server.am."
diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java
index 5c8e530..17541911 100644
--- a/services/core/java/com/android/server/am/UserController.java
+++ b/services/core/java/com/android/server/am/UserController.java
@@ -133,12 +133,12 @@
     static final int CONTINUE_USER_SWITCH_MSG = 20;
     static final int USER_SWITCH_TIMEOUT_MSG = 30;
     static final int START_PROFILES_MSG = 40;
-    static final int SYSTEM_USER_START_MSG = 50;
-    static final int SYSTEM_USER_CURRENT_MSG = 60;
+    static final int USER_START_MSG = 50;
+    static final int USER_CURRENT_MSG = 60;
     static final int FOREGROUND_PROFILE_CHANGED_MSG = 70;
     static final int REPORT_USER_SWITCH_COMPLETE_MSG = 80;
     static final int USER_SWITCH_CALLBACKS_TIMEOUT_MSG = 90;
-    static final int SYSTEM_USER_UNLOCK_MSG = 100;
+    static final int USER_UNLOCK_MSG = 100;
     static final int REPORT_LOCKED_BOOT_COMPLETE_MSG = 110;
     static final int START_USER_SWITCH_FG_MSG = 120;
 
@@ -368,16 +368,18 @@
                 }
             }
 
-            mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
-                    userId, 0));
-            Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
-            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
-            intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
-                    | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
-            mInjector.broadcastIntent(intent, null, resultTo, 0, null, null,
-                    new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
-                    AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID,
-                    Binder.getCallingUid(), Binder.getCallingPid(), userId);
+            if (!mInjector.getUserManager().isPreCreated(userId)) {
+                mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
+                        userId, 0));
+                Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
+                intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
+                intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
+                        | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
+                mInjector.broadcastIntent(intent, null, resultTo, 0, null, null,
+                        new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
+                        AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID,
+                        Binder.getCallingUid(), Binder.getCallingPid(), userId);
+            }
         }
 
         // We need to delay unlocking managed profiles until the parent user
@@ -438,8 +440,7 @@
 
             // Dispatch unlocked to system services; when fully dispatched,
             // that calls through to the next "unlocked" phase
-            mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
-                    .sendToTarget();
+            mHandler.obtainMessage(USER_UNLOCK_MSG, userId, 0, uss).sendToTarget();
         });
         return true;
     }
@@ -555,6 +556,17 @@
             }
         }
 
+        if (userInfo.preCreated) {
+            Slog.i(TAG, "Stopping pre-created user " + userInfo.toFullString());
+            // Pre-created user was started right after creation so services could properly
+            // intialize it; it should be stopped right away as it's not really a "real" user.
+            // TODO(b/140750212): in the long-term, we should add a onCreateUser() callback
+            // on SystemService instead.
+            stopUser(userInfo.id, /* force= */ true, /* stopUserCallback= */ null,
+                    /* keyEvictedCallback= */ null);
+            return;
+        }
+
         // Spin up app widgets prior to boot-complete, so they can be ready promptly
         mInjector.startUserWidgets(userId);
 
@@ -799,7 +811,8 @@
             mInjector.systemServiceManagerCleanupUser(userId);
             mInjector.stackSupervisorRemoveUser(userId);
             // Remove the user if it is ephemeral.
-            if (getUserInfo(userId).isEphemeral()) {
+            UserInfo userInfo = getUserInfo(userId);
+            if (userInfo.isEphemeral() && !userInfo.preCreated) {
                 mInjector.getUserManager().removeUserEvenWhenDisallowed(userId);
             }
 
@@ -1069,6 +1082,11 @@
                 return false;
             }
 
+            if (foreground && userInfo.preCreated) {
+                Slog.w(TAG, "Cannot start pre-created user #" + userId + " as foreground");
+                return false;
+            }
+
             if (foreground && mUserSwitchUiEnabled) {
                 t.traceBegin("startFreezingScreen");
                 mInjector.getWindowManager().startFreezingScreen(
@@ -1166,7 +1184,7 @@
                     updateStartedUserArrayLU();
                 }
                 needStart = true;
-                t.traceBegin("updateStateStopping");
+                t.traceEnd();
             }
 
             if (uss.state == UserState.STATE_BOOTING) {
@@ -1178,15 +1196,13 @@
                 // Booting up a new user, need to tell system services about it.
                 // Note that this is on the same handler as scheduling of broadcasts,
                 // which is important because it needs to go first.
-                mHandler.sendMessage(
-                        mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
+                mHandler.sendMessage(mHandler.obtainMessage(USER_START_MSG, userId, 0));
                 t.traceEnd();
             }
 
             t.traceBegin("sendMessages");
             if (foreground) {
-                mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
-                        oldUserId));
+                mHandler.sendMessage(mHandler.obtainMessage(USER_CURRENT_MSG, userId, oldUserId));
                 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
                 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
                 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
@@ -1195,6 +1211,10 @@
                         oldUserId, userId, uss), USER_SWITCH_TIMEOUT_MS);
             }
 
+            if (userInfo.preCreated) {
+                needStart = false;
+            }
+
             if (needStart) {
                 // Send USER_STARTED broadcast
                 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
@@ -2168,14 +2188,14 @@
             case START_PROFILES_MSG:
                 startProfiles();
                 break;
-            case SYSTEM_USER_START_MSG:
+            case USER_START_MSG:
                 mInjector.batteryStatsServiceNoteEvent(
                         BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
                         Integer.toString(msg.arg1), msg.arg1);
                 mInjector.getSystemServiceManager().startUser(TimingsTraceAndSlog.newAsyncLog(),
                         msg.arg1);
                 break;
-            case SYSTEM_USER_UNLOCK_MSG:
+            case USER_UNLOCK_MSG:
                 final int userId = msg.arg1;
                 mInjector.getSystemServiceManager().unlockUser(userId);
                 // Loads recents on a worker thread that allows disk I/O
@@ -2184,7 +2204,7 @@
                 });
                 finishUserUnlocked((UserState) msg.obj);
                 break;
-            case SYSTEM_USER_CURRENT_MSG:
+            case USER_CURRENT_MSG:
                 mInjector.batteryStatsServiceNoteEvent(
                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
                         Integer.toString(msg.arg2), msg.arg2);
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 159e5b8..6c4cc2d 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -108,6 +108,7 @@
 import com.android.internal.app.IAppOpsService;
 import com.android.internal.os.Zygote;
 import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.CollectionUtils;
 import com.android.internal.util.DumpUtils;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.Preconditions;
@@ -256,6 +257,9 @@
     @GuardedBy("this")
     private CheckOpsDelegate mCheckOpsDelegate;
 
+    @GuardedBy("this")
+    private SparseArray<List<Integer>> mSwitchOpToOps;
+
     /**
      * All times are in milliseconds. These constants are kept synchronized with the system
      * global Settings. Any access to this class or its fields should be done while
@@ -360,7 +364,7 @@
 
         public int startNesting;
         public ArrayMap<String, Ops> pkgOps;
-        private SparseIntArray opModes;
+        public SparseIntArray opModes;
 
         // true indicates there is an interested observer, false there isn't but it has such an op
         public SparseBooleanArray foregroundOps;
@@ -382,64 +386,6 @@
                     && (pendingState == UID_STATE_CACHED));
         }
 
-        public int getOpModeCount() {
-            return opModes != null ? opModes.size() : 0;
-        }
-
-        public int getOpCodeAt(int index) {
-            return opModes.keyAt(index);
-        }
-
-        public boolean hasOpMode(int code) {
-            return opModes != null && opModes.indexOfKey(code) >= 0;
-        }
-
-        public int getOpMode(int code) {
-            return opModes.get(code);
-        }
-
-        public boolean putOpMode(int code, int mode) {
-            if (mode == AppOpsManager.opToDefaultMode(code)) {
-                return removeOpMode(code);
-            }
-            if (opModes == null) {
-                opModes = new SparseIntArray();
-            }
-            int index = opModes.indexOfKey(code);
-            if (index < 0) {
-                opModes.put(code, mode);
-                return true;
-            }
-            if (opModes.valueAt(index) == mode) {
-                return false;
-            }
-            opModes.setValueAt(index, mode);
-            return true;
-        }
-
-        public boolean removeOpMode(int code) {
-            if (opModes == null) {
-                return false;
-            }
-            int index = opModes.indexOfKey(code);
-            if (index < 0) {
-                return false;
-            }
-            opModes.removeAt(index);
-            if (opModes.size() == 0) {
-                opModes = null;
-            }
-            return true;
-        }
-
-        @Nullable
-        public SparseIntArray cloneOpModes() {
-            if (opModes == null) {
-                return null;
-            }
-            return opModes.clone();
-        }
-
         int evalMode(int op, int mode) {
             if (mode == AppOpsManager.MODE_FOREGROUND) {
                 return state <= AppOpsManager.resolveFirstUnrestrictedUidState(op)
@@ -467,13 +413,14 @@
         public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
             SparseBooleanArray which = null;
             hasForegroundWatchers = false;
-            for (int i = getOpModeCount() - 1; i >= 0; i--) {
-                int code = getOpCodeAt(i);
-                if (getOpMode(code) == AppOpsManager.MODE_FOREGROUND) {
-                    if (which == null) {
-                        which = new SparseBooleanArray();
+            if (opModes != null) {
+                for (int i = opModes.size() - 1; i >= 0; i--) {
+                    if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
+                        if (which == null) {
+                            which = new SparseBooleanArray();
+                        }
+                        evalForegroundWatchers(opModes.keyAt(i), watchers, which);
                     }
-                    evalForegroundWatchers(code, watchers, which);
                 }
             }
             if (pkgOps != null) {
@@ -807,7 +754,12 @@
         public void binderDied() {
             synchronized (AppOpsService.this) {
                 for (int i=mStartedOps.size()-1; i>=0; i--) {
-                    finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
+                    final Op op = mStartedOps.get(i);
+                    finishOperationLocked(op, /*finishNested*/ true);
+                    if (op.startNesting <= 0) {
+                        scheduleOpActiveChangedIfNeededLocked(op.op, op.uidState.uid,
+                                op.packageName, false);
+                    }
                 }
                 mClients.remove(mAppToken);
             }
@@ -1116,28 +1068,24 @@
         return resOps;
     }
 
-    @Nullable
-    private ArrayList<AppOpsManager.OpEntry> collectOps(@NonNull UidState uidState,
-            @Nullable int[] ops) {
-        int opModeCount = uidState.getOpModeCount();
-        if (opModeCount == 0) {
+    private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
+        if (uidOps == null) {
             return null;
         }
         ArrayList<AppOpsManager.OpEntry> resOps = null;
         if (ops == null) {
             resOps = new ArrayList<>();
-            for (int i = 0; i < opModeCount; i++) {
-                int code = uidState.getOpCodeAt(i);
-                resOps.add(new OpEntry(code, uidState.getOpMode(code)));
+            for (int j=0; j<uidOps.size(); j++) {
+                resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
             }
         } else {
-            for (int i = 0; i < ops.length; i++) {
-                int code = ops[i];
-                if (uidState.hasOpMode(code)) {
+            for (int j=0; j<ops.length; j++) {
+                int index = uidOps.indexOfKey(ops[j]);
+                if (index >= 0) {
                     if (resOps == null) {
                         resOps = new ArrayList<>();
                     }
-                    resOps.add(new OpEntry(code, uidState.getOpMode(code)));
+                    resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
                 }
             }
         }
@@ -1283,11 +1231,11 @@
             if (uidState == null) {
                 return null;
             }
-            ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState, ops);
+            ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
             if (resOps == null) {
                 return null;
             }
-            ArrayList<AppOpsManager.PackageOps> res = new ArrayList<>();
+            ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
             AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
                     null, uidState.uid, resOps);
             res.add(resPackage);
@@ -1346,6 +1294,8 @@
         verifyIncomingOp(code);
         code = AppOpsManager.opToSwitch(code);
 
+        updatePermissionRevokedCompat(uid, code, mode);
+
         synchronized (this) {
             final int defaultMode = AppOpsManager.opToDefaultMode(code);
 
@@ -1355,14 +1305,29 @@
                     return;
                 }
                 uidState = new UidState(uid);
-                uidState.putOpMode(code, mode);
+                uidState.opModes = new SparseIntArray();
+                uidState.opModes.put(code, mode);
                 mUidStates.put(uid, uidState);
                 scheduleWriteLocked();
-            } else {
-                boolean changed = uidState.putOpMode(code, mode);
-                if (changed) {
+            } else if (uidState.opModes == null) {
+                if (mode != defaultMode) {
+                    uidState.opModes = new SparseIntArray();
+                    uidState.opModes.put(code, mode);
                     scheduleWriteLocked();
                 }
+            } else {
+                if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
+                    return;
+                }
+                if (mode == defaultMode) {
+                    uidState.opModes.delete(code);
+                    if (uidState.opModes.size() <= 0) {
+                        uidState.opModes = null;
+                    }
+                } else {
+                    uidState.opModes.put(code, mode);
+                }
+                scheduleWriteLocked();
             }
             uidState.evalForegroundOps(mOpModeWatchers);
         }
@@ -1432,6 +1397,86 @@
         notifyOpChangedSync(code, uid, null, mode);
     }
 
+    private void updatePermissionRevokedCompat(int uid, int switchCode, int mode) {
+        PackageManager packageManager = mContext.getPackageManager();
+        String[] packageNames = packageManager.getPackagesForUid(uid);
+        if (ArrayUtils.isEmpty(packageNames)) {
+            return;
+        }
+        String packageName = packageNames[0];
+
+        List<Integer> ops = getSwitchOpToOps().get(switchCode);
+        int opsSize = CollectionUtils.size(ops);
+        for (int i = 0; i < opsSize; i++) {
+            int code = ops.get(i);
+
+            String permissionName = AppOpsManager.opToPermission(code);
+            if (permissionName == null) {
+                continue;
+            }
+
+            PermissionInfo permissionInfo;
+            try {
+                permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
+            } catch (PackageManager.NameNotFoundException e) {
+                e.printStackTrace();
+                continue;
+            }
+
+            if (!permissionInfo.isRuntime()) {
+                continue;
+            }
+
+            UserHandle user = UserHandle.getUserHandleForUid(uid);
+            boolean isRevokedCompat;
+            if (permissionInfo.backgroundPermission != null) {
+                boolean isBackgroundRevokedCompat = mode != AppOpsManager.MODE_ALLOWED;
+                long identity = Binder.clearCallingIdentity();
+                try {
+                    packageManager.updatePermissionFlags(permissionInfo.backgroundPermission,
+                            packageName, PackageManager.FLAG_PERMISSION_REVOKED_COMPAT,
+                            isBackgroundRevokedCompat
+                                    ? PackageManager.FLAG_PERMISSION_REVOKED_COMPAT : 0, user);
+                } finally {
+                    Binder.restoreCallingIdentity(identity);
+                }
+
+                isRevokedCompat = mode != AppOpsManager.MODE_ALLOWED
+                        && mode != AppOpsManager.MODE_FOREGROUND;
+            } else {
+                isRevokedCompat = mode != AppOpsManager.MODE_ALLOWED;
+            }
+
+            long identity = Binder.clearCallingIdentity();
+            try {
+                packageManager.updatePermissionFlags(permissionName, packageName,
+                        PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, isRevokedCompat
+                                ? PackageManager.FLAG_PERMISSION_REVOKED_COMPAT : 0, user);
+            } finally {
+                Binder.restoreCallingIdentity(identity);
+            }
+        }
+    }
+
+    @NonNull
+    private SparseArray<List<Integer>> getSwitchOpToOps() {
+        synchronized (this) {
+            if (mSwitchOpToOps == null) {
+                mSwitchOpToOps = new SparseArray<>();
+                for (int op = 0; op < _NUM_OP; op++) {
+                    int switchOp = AppOpsManager.opToSwitch(op);
+                    List<Integer> ops = mSwitchOpToOps.get(switchOp);
+                    if (ops == null) {
+                        ops = new ArrayList<>();
+                        mSwitchOpToOps.put(switchOp, ops);
+                    }
+                    ops.add(op);
+                }
+            }
+            return mSwitchOpToOps;
+        }
+    }
+
     private void notifyOpChangedSync(int code, int uid, @NonNull String packageName, int mode) {
         final StorageManagerInternal storageManagerInternal =
                 LocalServices.getService(StorageManagerInternal.class);
@@ -1601,13 +1646,16 @@
             for (int i = mUidStates.size() - 1; i >= 0; i--) {
                 UidState uidState = mUidStates.valueAt(i);
 
-                if (uidState.uid == reqUid || reqUid == -1) {
-                    for (int opModeIndex = uidState.getOpModeCount() - 1; opModeIndex >= 0;
-                            opModeIndex--) {
-                        final int code = uidState.getOpCodeAt(opModeIndex);
-
+                SparseIntArray opModes = uidState.opModes;
+                if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
+                    final int uidOpCount = opModes.size();
+                    for (int j = uidOpCount - 1; j >= 0; j--) {
+                        final int code = opModes.keyAt(j);
                         if (AppOpsManager.opAllowsReset(code)) {
-                            uidState.removeOpMode(code);
+                            opModes.removeAt(j);
+                            if (opModes.size() <= 0) {
+                                uidState.opModes = null;
+                            }
                             for (String packageName : getPackagesForUid(uidState.uid)) {
                                 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
                                         mOpModeWatchers.get(code));
@@ -1857,8 +1905,9 @@
             }
             code = AppOpsManager.opToSwitch(code);
             UidState uidState = getUidStateLocked(uid, false);
-            if (uidState != null && uidState.hasOpMode(code)) {
-                final int rawMode = uidState.getOpMode(code);
+            if (uidState != null && uidState.opModes != null
+                    && uidState.opModes.indexOfKey(code) >= 0) {
+                final int rawMode = uidState.opModes.get(code);
                 return raw ? rawMode : uidState.evalMode(code, rawMode);
             }
             Op op = getOpLocked(code, uid, packageName, false, false);
@@ -2027,8 +2076,8 @@
             final int switchCode = AppOpsManager.opToSwitch(code);
             // If there is a non-default per UID policy (we set UID op mode only if
             // non-default) it takes over, otherwise use the per package policy.
-            if (uidState.hasOpMode(switchCode)) {
-                final int uidMode = uidState.evalMode(code, uidState.getOpMode(switchCode));
+            if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
+                final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
                 if (uidMode != AppOpsManager.MODE_ALLOWED) {
                     if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
                             + switchCode + " (" + code + ") uid " + uid + " package "
@@ -2329,8 +2378,8 @@
             // If there is a non-default per UID policy (we set UID op mode only if
             // non-default) it takes over, otherwise use the per package policy.
             final int opCode = op.op;
-            if (uidState.hasOpMode(switchCode)) {
-                final int uidMode = uidState.evalMode(code, uidState.getOpMode(switchCode));
+            if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
+                final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
                 if (uidMode != AppOpsManager.MODE_ALLOWED
                         && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
                     if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
@@ -2649,8 +2698,9 @@
                                 || !callback.isWatchingUid(uidState.uid)) {
                             continue;
                         }
-                        boolean doAllPackages = uidState.hasOpMode(code)
-                                && uidState.getOpMode(code) == AppOpsManager.MODE_FOREGROUND;
+                        boolean doAllPackages = uidState.opModes != null
+                                && uidState.opModes.indexOfKey(code) >= 0
+                                && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
                         if (uidState.pkgOps != null) {
                             for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
                                 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
@@ -2973,9 +3023,12 @@
             if (uidState == null) {
                 continue;
             }
-            if (uidState.hasOpMode(AppOpsManager.OP_RUN_IN_BACKGROUND)) {
-                uidState.putOpMode(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uidState.getOpMode(
-                        AppOpsManager.OP_RUN_IN_BACKGROUND));
+            if (uidState.opModes != null) {
+                final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
+                if (idx >= 0) {
+                    uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
+                        uidState.opModes.valueAt(idx));
+                }
             }
             if (uidState.pkgOps == null) {
                 continue;
@@ -3031,7 +3084,10 @@
                 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
                 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
                 UidState uidState = getUidStateLocked(uid, true);
-                uidState.putOpMode(code, mode);
+                if (uidState.opModes == null) {
+                    uidState.opModes = new SparseIntArray();
+                }
+                uidState.opModes.put(code, mode);
             } else {
                 Slog.w(TAG, "Unknown element under <uid-ops>: "
                         + parser.getName());
@@ -3183,38 +3239,47 @@
                 out.startTag(null, "app-ops");
                 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
 
-                final SparseArray<SparseIntArray> uidOpModes = new SparseArray<>();
+                SparseArray<SparseIntArray> uidStatesClone;
                 synchronized (this) {
-                    final int uidStatesSize = mUidStates.size();
-                    for (int i = 0; i < uidStatesSize; i++) {
-                        final SparseIntArray opModes = mUidStates.valueAt(i).cloneOpModes();
-                        if (opModes != null) {
-                            final int uid = mUidStates.keyAt(i);
-                            uidOpModes.put(uid, opModes);
+                    uidStatesClone = new SparseArray<>(mUidStates.size());
+
+                    final int uidStateCount = mUidStates.size();
+                    for (int uidStateNum = 0; uidStateNum < uidStateCount; uidStateNum++) {
+                        UidState uidState = mUidStates.valueAt(uidStateNum);
+                        int uid = mUidStates.keyAt(uidStateNum);
+
+                        SparseIntArray opModes = uidState.opModes;
+                        if (opModes != null && opModes.size() > 0) {
+                            uidStatesClone.put(uid, new SparseIntArray(opModes.size()));
+
+                            final int opCount = opModes.size();
+                            for (int opCountNum = 0; opCountNum < opCount; opCountNum++) {
+                                uidStatesClone.get(uid).put(
+                                        opModes.keyAt(opCountNum),
+                                        opModes.valueAt(opCountNum));
+                            }
                         }
                     }
                 }
 
-                final int uidOpModesSize = uidOpModes.size();
-                for (int uidOpModesIndex = 0; uidOpModesIndex < uidOpModesSize; uidOpModesIndex++) {
-                    final int uid = uidOpModes.keyAt(uidOpModesIndex);
-                    final SparseIntArray opModes = uidOpModes.valueAt(uidOpModesIndex);
-
-                    out.startTag(null, "uid");
-                    out.attribute(null, "n", Integer.toString(uid));
-
-                    final int opModesSize = opModes.size();
-                    for (int opModesIndex = 0; opModesIndex < opModesSize; opModesIndex++) {
-                        final int code = opModes.keyAt(opModesIndex);
-                        final int mode = opModes.valueAt(opModesIndex);
-
-                        out.startTag(null, "op");
-                        out.attribute(null, "n", Integer.toString(code));
-                        out.attribute(null, "m", Integer.toString(mode));
-                        out.endTag(null, "op");
+                final int uidStateCount = uidStatesClone.size();
+                for (int uidStateNum = 0; uidStateNum < uidStateCount; uidStateNum++) {
+                    SparseIntArray opModes = uidStatesClone.valueAt(uidStateNum);
+                    if (opModes != null && opModes.size() > 0) {
+                        out.startTag(null, "uid");
+                        out.attribute(null, "n",
+                                Integer.toString(uidStatesClone.keyAt(uidStateNum)));
+                        final int opCount = opModes.size();
+                        for (int opCountNum = 0; opCountNum < opCount; opCountNum++) {
+                            final int op = opModes.keyAt(opCountNum);
+                            final int mode = opModes.valueAt(opCountNum);
+                            out.startTag(null, "op");
+                            out.attribute(null, "n", Integer.toString(op));
+                            out.attribute(null, "m", Integer.toString(mode));
+                            out.endTag(null, "op");
+                        }
+                        out.endTag(null, "uid");
                     }
-
-                    out.endTag(null, "uid");
                 }
 
                 if (allOps != null) {
@@ -4159,22 +4224,21 @@
             }
             for (int i=0; i<mUidStates.size(); i++) {
                 UidState uidState = mUidStates.valueAt(i);
+                final SparseIntArray opModes = uidState.opModes;
                 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
 
                 if (dumpWatchers || dumpHistory) {
                     continue;
                 }
                 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
-                    boolean hasOp = dumpOp < 0 || uidState.hasOpMode(dumpOp);
+                    boolean hasOp = dumpOp < 0 || (uidState.opModes != null
+                            && uidState.opModes.indexOfKey(dumpOp) >= 0);
                     boolean hasPackage = dumpPackage == null;
                     boolean hasMode = dumpMode < 0;
-                    if (!hasMode) {
-                        int opModeCount = uidState.getOpModeCount();
-                        for (int opModeIndex = 0; opModeIndex < opModeCount; opModeIndex++) {
-                            int code = uidState.getOpCodeAt(opModeIndex);
-                            if (uidState.getOpMode(code) == dumpMode) {
+                    if (!hasMode && opModes != null) {
+                        for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
+                            if (opModes.valueAt(opi) == dumpMode) {
                                 hasMode = true;
-                                break;
                             }
                         }
                     }
@@ -4241,18 +4305,20 @@
                 }
                 needSep = true;
 
-                final int opModeCount = uidState.getOpModeCount();
-                for (int opModeIndex = 0; opModeIndex < opModeCount; opModeIndex++) {
-                    final int code = uidState.getOpCodeAt(opModeIndex);
-                    final int mode = uidState.getOpMode(code);
-                    if (dumpOp >= 0 && dumpOp != code) {
-                        continue;
+                if (opModes != null) {
+                    final int opModeCount = opModes.size();
+                    for (int j = 0; j < opModeCount; j++) {
+                        final int code = opModes.keyAt(j);
+                        final int mode = opModes.valueAt(j);
+                        if (dumpOp >= 0 && dumpOp != code) {
+                            continue;
+                        }
+                        if (dumpMode >= 0 && dumpMode != mode) {
+                            continue;
+                        }
+                        pw.print("      "); pw.print(AppOpsManager.opToName(code));
+                        pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
                     }
-                    if (dumpMode >= 0 && dumpMode != mode) {
-                        continue;
-                    }
-                    pw.print("      "); pw.print(AppOpsManager.opToName(code));
-                    pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
                 }
 
                 if (pkgOps == null) {
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 77b3fee..a6ac17d 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -59,6 +59,7 @@
 import android.hardware.hdmi.HdmiControlManager;
 import android.hardware.hdmi.HdmiPlaybackClient;
 import android.hardware.hdmi.HdmiTvClient;
+import android.hardware.input.InputManager;
 import android.hardware.usb.UsbManager;
 import android.media.AudioAttributes;
 import android.media.AudioFocusInfo;
@@ -545,6 +546,10 @@
     private String mEnabledSurroundFormats;
     private boolean mSurroundModeChanged;
 
+    private boolean mMicMuteFromSwitch;
+    private boolean mMicMuteFromApi;
+    private boolean mMicMuteFromRestrictions;
+
     @GuardedBy("mSettingsLock")
     private int mAssistantUid;
 
@@ -882,6 +887,8 @@
         mRoleObserver.register();
 
         onIndicateSystemReady();
+
+        setMicMuteFromSwitchInput();
     }
 
     RoleObserver mRoleObserver;
@@ -1021,6 +1028,8 @@
 
         sendMsg(mAudioHandler, MSG_DISPATCH_AUDIO_SERVER_STATE,
                 SENDMSG_QUEUE, 1, 0, null, 0);
+
+        setMicMuteFromSwitchInput();
     }
 
     private void onDispatchAudioServerStateChange(boolean state) {
@@ -1557,12 +1566,13 @@
         AudioSystem.setMasterMute(masterMute);
         broadcastMasterMuteStatus(masterMute);
 
-        boolean microphoneMute = mUserManagerInternal.getUserRestriction(
+        mMicMuteFromRestrictions = mUserManagerInternal.getUserRestriction(
                 currentUser, UserManager.DISALLOW_UNMUTE_MICROPHONE);
         if (DEBUG_VOL) {
-            Log.d(TAG, String.format("Mic mute %s, user=%d", microphoneMute, currentUser));
+            Log.d(TAG, String.format("Mic mute %b, user=%d", mMicMuteFromRestrictions,
+                    currentUser));
         }
-        AudioSystem.muteMicrophone(microphoneMute);
+        setMicrophoneMuteNoCallerCheck(currentUser);
     }
 
     private int rescaleIndex(int index, int srcStream, int dstStream) {
@@ -2837,20 +2847,45 @@
                 != PackageManager.PERMISSION_GRANTED) {
             return;
         }
-        setMicrophoneMuteNoCallerCheck(on, userId);
+        mMicMuteFromApi = on;
+        setMicrophoneMuteNoCallerCheck(userId);
     }
 
-    private void setMicrophoneMuteNoCallerCheck(boolean on, int userId) {
+    /** @see AudioManager#setMicrophoneMuteFromSwitch(boolean) */
+    public void setMicrophoneMuteFromSwitch(boolean on) {
+        int userId = Binder.getCallingUid();
+        if (userId != android.os.Process.SYSTEM_UID) {
+            Log.e(TAG, "setMicrophoneMuteFromSwitch() called from non system user!");
+            return;
+        }
+        mMicMuteFromSwitch = on;
+        setMicrophoneMuteNoCallerCheck(userId);
+    }
+
+    private void setMicMuteFromSwitchInput() {
+        InputManager im = mContext.getSystemService(InputManager.class);
+        final int isMicMuted = im.isMicMuted();
+        if (isMicMuted != InputManager.SWITCH_STATE_UNKNOWN) {
+            setMicrophoneMuteFromSwitch(im.isMicMuted() != InputManager.SWITCH_STATE_OFF);
+        }
+    }
+
+    public boolean isMicrophoneMuted() {
+        return mMicMuteFromSwitch || mMicMuteFromRestrictions || mMicMuteFromApi;
+    }
+
+    private void setMicrophoneMuteNoCallerCheck(int userId) {
+        final boolean muted = isMicrophoneMuted();
         if (DEBUG_VOL) {
-            Log.d(TAG, String.format("Mic mute %s, user=%d", on, userId));
+            Log.d(TAG, String.format("Mic mute %b, user=%d", muted, userId));
         }
         // only mute for the current user
-        if (getCurrentUserId() == userId) {
+        if (getCurrentUserId() == userId || userId == android.os.Process.SYSTEM_UID) {
             final boolean currentMute = AudioSystem.isMicrophoneMuted();
             final long identity = Binder.clearCallingIdentity();
-            AudioSystem.muteMicrophone(on);
+            AudioSystem.muteMicrophone(muted);
             Binder.restoreCallingIdentity(identity);
-            if (on != currentMute) {
+            if (muted != currentMute) {
                 mContext.sendBroadcastAsUser(
                         new Intent(AudioManager.ACTION_MICROPHONE_MUTE_CHANGED)
                                 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY), UserHandle.ALL);
@@ -3854,7 +3889,7 @@
         final boolean muteSystem = (zenPolicy.priorityCategories
                 & NotificationManager.Policy.PRIORITY_CATEGORY_SYSTEM) == 0;
         final boolean muteNotificationAndRing = ZenModeConfig
-                .areAllPriorityOnlyNotificationZenSoundsMuted(
+                .areAllPriorityOnlyRingerSoundsMuted(
                         mNm.getConsolidatedNotificationPolicy());
         return muteAlarms && isAlarm(streamType)
                 || muteMedia && isMedia(streamType)
@@ -3867,16 +3902,26 @@
     }
 
     /**
-     * DND total silence: media and alarms streams are tied to the muted ringer
+     * Notifications, ringer and system sounds are controlled by the ringer:
      * {@link ZenModeHelper.RingerModeDelegate#getRingerModeAffectedStreams(int)}
-     * DND alarms only: notification, ringer + system muted (by default tied to muted ringer mode)
-     * DND priority only: alarms, media, system streams can be muted separate from ringer based on
+     * DND total silence: media and alarms streams can be muted by DND
+     * DND alarms only: no streams additionally controlled by DND
+     * DND priority only: alarms, media, system streams can be muted by DND based on
      * zenPolicy (this method determines which streams)
      * @return true if changed, else false
      */
     private boolean updateZenModeAffectedStreams() {
+        if (!mSystemReady) {
+            return false;
+        }
+
         int zenModeAffectedStreams = 0;
-        if (mSystemReady && mNm.getZenMode() == Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS) {
+        final int zenMode = mNm.getZenMode();
+
+        if (zenMode == Settings.Global.ZEN_MODE_NO_INTERRUPTIONS) {
+            zenModeAffectedStreams |= 1 << AudioManager.STREAM_ALARM;
+            zenModeAffectedStreams |= 1 << AudioManager.STREAM_MUSIC;
+        } else if (zenMode == Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS) {
             NotificationManager.Policy zenPolicy = mNm.getConsolidatedNotificationPolicy();
             if ((zenPolicy.priorityCategories
                     & NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS) == 0) {
@@ -3888,6 +3933,8 @@
                 zenModeAffectedStreams |= 1 << AudioManager.STREAM_MUSIC;
             }
 
+            // even if zen isn't muting the system stream, the ringer mode can still mute
+            // the system stream
             if ((zenPolicy.priorityCategories
                     & NotificationManager.Policy.PRIORITY_CATEGORY_SYSTEM) == 0) {
                 zenModeAffectedStreams |= 1 << AudioManager.STREAM_SYSTEM;
@@ -5378,7 +5425,8 @@
                 final boolean isRestricted =
                         newRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE);
                 if (wasRestricted != isRestricted) {
-                    setMicrophoneMuteNoCallerCheck(isRestricted, userId);
+                    mMicMuteFromRestrictions = isRestricted;
+                    setMicrophoneMuteNoCallerCheck(userId);
                 }
             }
 
diff --git a/services/core/java/com/android/server/biometrics/BiometricService.java b/services/core/java/com/android/server/biometrics/BiometricService.java
index 7302b98..4f1db3c 100644
--- a/services/core/java/com/android/server/biometrics/BiometricService.java
+++ b/services/core/java/com/android/server/biometrics/BiometricService.java
@@ -25,21 +25,18 @@
 import static android.hardware.biometrics.BiometricAuthenticator.TYPE_NONE;
 
 import android.app.ActivityManager;
-import android.app.AppOpsManager;
 import android.app.IActivityManager;
-import android.app.KeyguardManager;
 import android.app.UserSwitchObserver;
 import android.content.ContentResolver;
 import android.content.Context;
-import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.database.ContentObserver;
+import android.hardware.biometrics.Authenticator;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
 import android.hardware.biometrics.BiometricPrompt;
 import android.hardware.biometrics.BiometricSourceType;
 import android.hardware.biometrics.BiometricsProtoEnums;
-import android.hardware.biometrics.IBiometricConfirmDeviceCredentialCallback;
 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
 import android.hardware.biometrics.IBiometricService;
 import android.hardware.biometrics.IBiometricServiceReceiver;
@@ -96,11 +93,8 @@
     private static final int MSG_ON_READY_FOR_AUTHENTICATION = 8;
     private static final int MSG_AUTHENTICATE = 9;
     private static final int MSG_CANCEL_AUTHENTICATION = 10;
-    private static final int MSG_ON_CONFIRM_DEVICE_CREDENTIAL_SUCCESS = 11;
-    private static final int MSG_ON_CONFIRM_DEVICE_CREDENTIAL_ERROR = 12;
-    private static final int MSG_REGISTER_CANCELLATION_CALLBACK = 13;
-    private static final int MSG_ON_AUTHENTICATION_TIMED_OUT = 14;
-
+    private static final int MSG_ON_AUTHENTICATION_TIMED_OUT = 11;
+    private static final int MSG_ON_DEVICE_CREDENTIAL_PRESSED = 12;
     private static final int[] FEATURE_ID = {
         TYPE_FINGERPRINT,
         TYPE_IRIS,
@@ -133,19 +127,19 @@
      */
     static final int STATE_AUTH_PENDING_CONFIRM = 5;
     /**
-     * Biometric authentication was canceled, but the device is now showing ConfirmDeviceCredential
-     */
-    static final int STATE_BIOMETRIC_AUTH_CANCELED_SHOWING_CDC = 6;
-    /**
      * Biometric authenticated, waiting for SysUI to finish animation
      */
-    static final int STATE_AUTHENTICATED_PENDING_SYSUI = 7;
+    static final int STATE_AUTHENTICATED_PENDING_SYSUI = 6;
     /**
      * Biometric error, waiting for SysUI to finish animation
      */
-    static final int STATE_ERROR_PENDING_SYSUI = 8;
+    static final int STATE_ERROR_PENDING_SYSUI = 7;
+    /**
+     * Device credential in AuthController is showing
+     */
+    static final int STATE_SHOWING_DEVICE_CREDENTIAL = 8;
 
-    final class AuthSession implements IBinder.DeathRecipient {
+    final class AuthSession {
         // Map of Authenticator/Cookie pairs. We expect to receive the cookies back from
         // <Biometric>Services before we can start authenticating. Pairs that have been returned
         // are moved to mModalitiesMatched.
@@ -185,14 +179,10 @@
         // Timestamp when hardware authentication occurred
         private long mAuthenticatedTimeMs;
 
-        // TODO(b/123378871): Remove when moved.
-        private IBiometricConfirmDeviceCredentialCallback mConfirmDeviceCredentialCallback;
-
         AuthSession(HashMap<Integer, Integer> modalities, IBinder token, long sessionId,
                 int userId, IBiometricServiceReceiver receiver, String opPackageName,
                 Bundle bundle, int callingUid, int callingPid, int callingUserId,
-                int modality, boolean requireConfirmation,
-                IBiometricConfirmDeviceCredentialCallback callback) {
+                int modality, boolean requireConfirmation) {
             mModalitiesWaiting = modalities;
             mToken = token;
             mSessionId = sessionId;
@@ -205,25 +195,12 @@
             mCallingUserId = callingUserId;
             mModality = modality;
             mRequireConfirmation = requireConfirmation;
-            mConfirmDeviceCredentialCallback = callback;
-
-            if (isFromConfirmDeviceCredential()) {
-                try {
-                    token.linkToDeath(this, 0 /* flags */);
-                } catch (RemoteException e) {
-                    Slog.e(TAG, "Unable to link to death", e);
-                }
-            }
         }
 
         boolean isCrypto() {
             return mSessionId != 0;
         }
 
-        boolean isFromConfirmDeviceCredential() {
-            return mBundle.getBoolean(BiometricPrompt.KEY_FROM_CONFIRM_DEVICE_CREDENTIAL, false);
-        }
-
         boolean containsCookie(int cookie) {
             if (mModalitiesWaiting != null && mModalitiesWaiting.containsValue(cookie)) {
                 return true;
@@ -234,35 +211,19 @@
             return false;
         }
 
-        // TODO(b/123378871): Remove when moved.
-        @Override
-        public void binderDied() {
-            mHandler.post(() -> {
-                Slog.e(TAG, "Binder died, killing ConfirmDeviceCredential");
-                if (mConfirmDeviceCredentialCallback == null) {
-                    Slog.e(TAG, "Callback is null");
-                    return;
-                }
-
-                try {
-                    mConfirmDeviceCredentialCallback.cancel();
-                    mConfirmDeviceCredentialCallback = null;
-                } catch (RemoteException e) {
-                    Slog.e(TAG, "Unable to send cancel", e);
-                }
-            });
+        boolean isAllowDeviceCredential() {
+            return Utils.isDeviceCredentialAllowed(mBundle);
         }
     }
 
     private final Injector mInjector;
     @VisibleForTesting
     final IBiometricService.Stub mImpl;
-    private final AppOpsManager mAppOps;
     private final boolean mHasFeatureFingerprint;
     private final boolean mHasFeatureIris;
     private final boolean mHasFeatureFace;
     @VisibleForTesting
-    SettingObserver mSettingObserver;
+    final SettingObserver mSettingObserver;
     private final List<EnabledOnKeyguardCallback> mEnabledOnKeyguardCallbacks;
     private final Random mRandom = new Random();
 
@@ -277,7 +238,7 @@
 
     // Get and cache the available authenticator (manager) classes. Used since aidl doesn't support
     // polymorphism :/
-    final ArrayList<Authenticator> mAuthenticators = new ArrayList<>();
+    final ArrayList<AuthenticatorWrapper> mAuthenticators = new ArrayList<>();
 
     // The current authentication session, null if idle/done. We need to track both the current
     // and pending sessions since errors may be sent to either.
@@ -286,14 +247,6 @@
     @VisibleForTesting
     AuthSession mPendingAuthSession;
 
-    // TODO(b/123378871): Remove when moved.
-    // When BiometricPrompt#setAllowDeviceCredentials is set to true, we need to store the
-    // client (app) receiver. BiometricService internally launches CDCA which invokes
-    // BiometricService to start authentication (normal path). When auth is success/rejected,
-    // CDCA will use an aidl method to poke BiometricService - the result will then be forwarded
-    // to this receiver.
-    private IBiometricServiceReceiver mConfirmDeviceCredentialReceiver;
-
     @VisibleForTesting
     final Handler mHandler = new Handler(Looper.getMainLooper()) {
         @Override
@@ -363,8 +316,7 @@
                             (Bundle) args.arg5 /* bundle */,
                             args.argi2 /* callingUid */,
                             args.argi3 /* callingPid */,
-                            args.argi4 /* callingUserId */,
-                            (IBiometricConfirmDeviceCredentialCallback) args.arg6 /* callback */);
+                            args.argi4 /* callingUserId */);
                     args.recycle();
                     break;
                 }
@@ -378,31 +330,16 @@
                     break;
                 }
 
-                case MSG_ON_CONFIRM_DEVICE_CREDENTIAL_SUCCESS: {
-                    handleOnConfirmDeviceCredentialSuccess();
-                    break;
-                }
-
-                case MSG_ON_CONFIRM_DEVICE_CREDENTIAL_ERROR: {
-                    SomeArgs args = (SomeArgs) msg.obj;
-                    handleOnConfirmDeviceCredentialError(
-                            args.argi1 /* error */,
-                            (String) args.arg1 /* errorMsg */);
-                    args.recycle();
-                    break;
-                }
-
-                case MSG_REGISTER_CANCELLATION_CALLBACK: {
-                    handleRegisterCancellationCallback(
-                            (IBiometricConfirmDeviceCredentialCallback) msg.obj /* callback */);
-                    break;
-                }
-
                 case MSG_ON_AUTHENTICATION_TIMED_OUT: {
                     handleAuthenticationTimedOut((String) msg.obj /* errorMessage */);
                     break;
                 }
 
+                case MSG_ON_DEVICE_CREDENTIAL_PRESSED: {
+                    handleOnDeviceCredentialPressed();
+                    break;
+                }
+
                 default:
                     Slog.e(TAG, "Unknown message: " + msg);
                     break;
@@ -410,11 +347,11 @@
         }
     };
 
-    private final class Authenticator {
-        int mType;
-        BiometricAuthenticator mAuthenticator;
+    private final class AuthenticatorWrapper {
+        final int mType;
+        final BiometricAuthenticator mAuthenticator;
 
-        Authenticator(int type, BiometricAuthenticator authenticator) {
+        AuthenticatorWrapper(int type, BiometricAuthenticator authenticator) {
             mType = type;
             mAuthenticator = authenticator;
         }
@@ -445,9 +382,9 @@
         private final ContentResolver mContentResolver;
         private final List<BiometricService.EnabledOnKeyguardCallback> mCallbacks;
 
-        private Map<Integer, Boolean> mFaceEnabledOnKeyguard = new HashMap<>();
-        private Map<Integer, Boolean> mFaceEnabledForApps = new HashMap<>();
-        private Map<Integer, Boolean> mFaceAlwaysRequireConfirmation = new HashMap<>();
+        private final Map<Integer, Boolean> mFaceEnabledOnKeyguard = new HashMap<>();
+        private final Map<Integer, Boolean> mFaceEnabledForApps = new HashMap<>();
+        private final Map<Integer, Boolean> mFaceAlwaysRequireConfirmation = new HashMap<>();
 
         /**
          * Creates a content observer.
@@ -622,6 +559,11 @@
         public void onTryAgainPressed() {
             mHandler.sendEmptyMessage(MSG_ON_TRY_AGAIN_PRESSED);
         }
+
+        @Override
+        public void onDeviceCredentialPressed() {
+            mHandler.sendEmptyMessage(MSG_ON_DEVICE_CREDENTIAL_PRESSED);
+        }
     };
 
 
@@ -644,18 +586,12 @@
 
         @Override // Binder call
         public void authenticate(IBinder token, long sessionId, int userId,
-                IBiometricServiceReceiver receiver, String opPackageName, Bundle bundle,
-                IBiometricConfirmDeviceCredentialCallback callback)
+                IBiometricServiceReceiver receiver, String opPackageName, Bundle bundle)
                 throws RemoteException {
             final int callingUid = Binder.getCallingUid();
             final int callingPid = Binder.getCallingPid();
             final int callingUserId = UserHandle.getCallingUserId();
 
-            // TODO(b/123378871): Remove when moved.
-            if (callback != null) {
-                checkInternalPermission();
-            }
-
             // In the BiometricServiceBase, check do the AppOps and foreground check.
             if (userId == callingUserId) {
                 // Check the USE_BIOMETRIC permission here.
@@ -672,12 +608,12 @@
                 return;
             }
 
-            final boolean isFromConfirmDeviceCredential =
-                    bundle.getBoolean(BiometricPrompt.KEY_FROM_CONFIRM_DEVICE_CREDENTIAL, false);
-            if (isFromConfirmDeviceCredential) {
+            if (bundle.get(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED) != null) {
                 checkInternalPermission();
             }
 
+            Utils.combineAuthenticatorBundles(bundle);
+
             // Check the usage of this in system server. Need to remove this check if it becomes
             // a public API.
             final boolean useDefaultTitle =
@@ -691,39 +627,6 @@
                 }
             }
 
-            // Launch CDC instead if necessary. CDC will return results through an AIDL call, since
-            // we can't get activity results. Store the receiver somewhere so we can forward the
-            // result back to the client.
-            // TODO(b/123378871): Remove when moved.
-            if (bundle.getBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL)) {
-                mHandler.post(() -> {
-                    final KeyguardManager kgm = getContext().getSystemService(
-                            KeyguardManager.class);
-                    if (!kgm.isDeviceSecure()) {
-                        try {
-                            receiver.onError(
-                                    BiometricConstants.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL,
-                                    getContext().getString(
-                                            R.string.biometric_error_device_not_secured));
-                        } catch (RemoteException e) {
-                            Slog.e(TAG, "Remote exception", e);
-                        }
-                        return;
-                    }
-                    mConfirmDeviceCredentialReceiver = receiver;
-                    // Use this so we don't need to duplicate logic..
-                    final Intent intent = kgm.createConfirmDeviceCredentialIntent(null /* title */,
-                            null /* description */, userId);
-                    // Then give it the bundle to do magic behavior..
-                    intent.putExtra(KeyguardManager.EXTRA_BIOMETRIC_PROMPT_BUNDLE, bundle);
-                    // Create a new task with this activity located at the root.
-                    intent.setFlags(
-                            Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
-                    getContext().startActivityAsUser(intent, UserHandle.CURRENT);
-                });
-                return;
-            }
-
             SomeArgs args = SomeArgs.obtain();
             args.arg1 = token;
             args.arg2 = sessionId;
@@ -734,41 +637,11 @@
             args.argi2 = callingUid;
             args.argi3 = callingPid;
             args.argi4 = callingUserId;
-            args.arg6 = callback;
 
             mHandler.obtainMessage(MSG_AUTHENTICATE, args).sendToTarget();
         }
 
         @Override // Binder call
-        public void onConfirmDeviceCredentialSuccess() {
-            checkInternalPermission();
-
-            mHandler.sendEmptyMessage(MSG_ON_CONFIRM_DEVICE_CREDENTIAL_SUCCESS);
-        }
-
-        @Override // Binder call
-        public void onConfirmDeviceCredentialError(int error, String message) {
-            checkInternalPermission();
-
-            SomeArgs args = SomeArgs.obtain();
-            args.argi1 = error;
-            args.arg1 = message;
-            mHandler.obtainMessage(MSG_ON_CONFIRM_DEVICE_CREDENTIAL_ERROR, args).sendToTarget();
-        }
-
-        @Override // Binder call
-        public void registerCancellationCallback(
-                IBiometricConfirmDeviceCredentialCallback callback) {
-            // TODO(b/123378871): Remove when moved.
-            // This callback replaces the one stored in the current session. If the session is null
-            // we can ignore this, since it means ConfirmDeviceCredential was launched by something
-            // else (not BiometricPrompt)
-            checkInternalPermission();
-
-            mHandler.obtainMessage(MSG_REGISTER_CANCELLATION_CALLBACK, callback).sendToTarget();
-        }
-
-        @Override // Binder call
         public void cancelAuthentication(IBinder token, String opPackageName)
                 throws RemoteException {
             checkPermission();
@@ -864,14 +737,6 @@
         }
     }
 
-    private void checkAppOp(String opPackageName, int callingUid) {
-        if (mAppOps.noteOp(AppOpsManager.OP_USE_BIOMETRIC, callingUid,
-                opPackageName) != AppOpsManager.MODE_ALLOWED) {
-            Slog.w(TAG, "Rejecting " + opPackageName + "; permission denied");
-            throw new SecurityException("Permission denied");
-        }
-    }
-
     private void checkInternalPermission() {
         getContext().enforceCallingOrSelfPermission(USE_BIOMETRIC_INTERNAL,
                 "Must have USE_BIOMETRIC_INTERNAL permission");
@@ -942,7 +807,6 @@
 
         mInjector = injector;
         mImpl = new BiometricServiceWrapper();
-        mAppOps = context.getSystemService(AppOpsManager.class);
         mEnabledOnKeyguardCallbacks = new ArrayList<>();
         mSettingObserver = mInjector.getSettingObserver(context, mHandler,
                 mEnabledOnKeyguardCallbacks);
@@ -983,8 +847,8 @@
         // Cache the authenticators
         for (int featureId : FEATURE_ID) {
             if (hasFeature(featureId)) {
-                Authenticator authenticator =
-                        new Authenticator(featureId, getAuthenticator(featureId));
+                AuthenticatorWrapper authenticator =
+                        new AuthenticatorWrapper(featureId, getAuthenticator(featureId));
                 mAuthenticators.add(authenticator);
             }
         }
@@ -1022,7 +886,7 @@
 
         int modality = TYPE_NONE;
         int firstHwAvailable = TYPE_NONE;
-        for (Authenticator authenticatorWrapper : mAuthenticators) {
+        for (AuthenticatorWrapper authenticatorWrapper : mAuthenticators) {
             modality = authenticatorWrapper.getType();
             BiometricAuthenticator authenticator = authenticatorWrapper.getAuthenticator();
             if (authenticator.isHardwareDetected()) {
@@ -1119,7 +983,7 @@
     }
 
     private void logDialogDismissed(int reason) {
-        if (reason == BiometricPrompt.DISMISSED_REASON_CONFIRMED) {
+        if (reason == BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED) {
             // Explicit auth, authentication confirmed.
             // Latency in this case is authenticated -> confirmed. <Biometric>Service
             // should have the first half (first acquired -> authenticated).
@@ -1265,49 +1129,6 @@
         }
     }
 
-    private void handleOnConfirmDeviceCredentialSuccess() {
-        if (mConfirmDeviceCredentialReceiver == null) {
-            Slog.w(TAG, "handleOnConfirmDeviceCredentialSuccess null!");
-            return;
-        }
-        try {
-            mConfirmDeviceCredentialReceiver.onAuthenticationSucceeded();
-            if (mCurrentAuthSession != null) {
-                mCurrentAuthSession = null;
-            }
-        } catch (RemoteException e) {
-            Slog.e(TAG, "RemoteException", e);
-        }
-        mConfirmDeviceCredentialReceiver = null;
-    }
-
-    private void handleOnConfirmDeviceCredentialError(int error, String message) {
-        if (mConfirmDeviceCredentialReceiver == null) {
-            Slog.w(TAG, "handleOnConfirmDeviceCredentialError null! Error: "
-                    + error + " " + message);
-            return;
-        }
-        try {
-            mConfirmDeviceCredentialReceiver.onError(error, message);
-            if (mCurrentAuthSession != null) {
-                mCurrentAuthSession = null;
-            }
-        } catch (RemoteException e) {
-            Slog.e(TAG, "RemoteException", e);
-        }
-        mConfirmDeviceCredentialReceiver = null;
-    }
-
-    private void handleRegisterCancellationCallback(
-            IBiometricConfirmDeviceCredentialCallback callback) {
-        if (mCurrentAuthSession == null) {
-            Slog.d(TAG, "Current auth session null");
-            return;
-        }
-        Slog.d(TAG, "Updating cancel callback");
-        mCurrentAuthSession.mConfirmDeviceCredentialCallback = callback;
-    }
-
     private void handleOnError(int cookie, int error, String message) {
         Slog.d(TAG, "handleOnError: " + error + " cookie: " + cookie);
         // Errors can either be from the current auth session or the pending auth session.
@@ -1318,34 +1139,34 @@
         // of their intended receivers.
         try {
             if (mCurrentAuthSession != null && mCurrentAuthSession.containsCookie(cookie)) {
-
                 mCurrentAuthSession.mErrorEscrow = error;
                 mCurrentAuthSession.mErrorStringEscrow = message;
 
-                if (mCurrentAuthSession.isFromConfirmDeviceCredential()) {
-                    // If we were invoked by ConfirmDeviceCredential, do not delete the current
-                    // auth session since we still need to respond to cancel signal while
-                    if (DEBUG) Slog.d(TAG, "From CDC, transition to CANCELED_SHOWING_CDC state");
-
-                    // Send the error to ConfirmDeviceCredential so that it goes to Pin/Pattern/Pass
-                    // screen
-                    mCurrentAuthSession.mClientReceiver.onError(error, message);
-                    mCurrentAuthSession.mState = STATE_BIOMETRIC_AUTH_CANCELED_SHOWING_CDC;
-                    mStatusBarService.hideBiometricDialog();
-                } else if (mCurrentAuthSession.mState == STATE_AUTH_STARTED) {
-                    mCurrentAuthSession.mState = STATE_ERROR_PENDING_SYSUI;
-                    if (error == BiometricConstants.BIOMETRIC_ERROR_CANCELED) {
-                        mStatusBarService.hideBiometricDialog();
+                if (mCurrentAuthSession.mState == STATE_AUTH_STARTED) {
+                    final boolean errorLockout = error == BiometricConstants.BIOMETRIC_ERROR_LOCKOUT
+                            || error == BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
+                    if (mCurrentAuthSession.isAllowDeviceCredential() && errorLockout) {
+                        // SystemUI handles transition from biometric to device credential.
+                        mCurrentAuthSession.mState = STATE_SHOWING_DEVICE_CREDENTIAL;
+                        mStatusBarService.onBiometricError(error, message);
                     } else {
-                        mStatusBarService.onBiometricError(message);
+                        mCurrentAuthSession.mState = STATE_ERROR_PENDING_SYSUI;
+                        if (error == BiometricConstants.BIOMETRIC_ERROR_CANCELED) {
+                            mStatusBarService.hideAuthenticationDialog();
+                        } else {
+                            mStatusBarService.onBiometricError(error, message);
+                        }
                     }
                 } else if (mCurrentAuthSession.mState == STATE_AUTH_PAUSED) {
                     // In the "try again" state, we should forward canceled errors to
                     // the client and and clean up. The only error we should get here is
                     // ERROR_CANCELED due to another client kicking us out.
                     mCurrentAuthSession.mClientReceiver.onError(error, message);
-                    mStatusBarService.hideBiometricDialog();
+                    mStatusBarService.hideAuthenticationDialog();
                     mCurrentAuthSession = null;
+                } else if (mCurrentAuthSession.mState == STATE_SHOWING_DEVICE_CREDENTIAL) {
+                    Slog.d(TAG, "Biometric canceled, ignoring from state: "
+                            + mCurrentAuthSession.mState);
                 } else {
                     Slog.e(TAG, "Impossible session error state: "
                             + mCurrentAuthSession.mState);
@@ -1353,12 +1174,38 @@
             } else if (mPendingAuthSession != null
                     && mPendingAuthSession.containsCookie(cookie)) {
                 if (mPendingAuthSession.mState == STATE_AUTH_CALLED) {
-                    mPendingAuthSession.mClientReceiver.onError(error, message);
-                    mPendingAuthSession = null;
+                    // If any error is received while preparing the auth session (lockout, etc),
+                    // and if device credential is allowed, just show the credential UI.
+                    if (mPendingAuthSession.isAllowDeviceCredential()) {
+                        int authenticators = mPendingAuthSession.mBundle
+                                .getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, 0);
+                        // Disallow biometric and notify SystemUI to show the authentication prompt.
+                        authenticators &= ~Authenticator.TYPE_BIOMETRIC;
+                        mPendingAuthSession.mBundle.putInt(
+                                BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED,
+                                authenticators);
+
+                        mCurrentAuthSession = mPendingAuthSession;
+                        mCurrentAuthSession.mState = STATE_SHOWING_DEVICE_CREDENTIAL;
+                        mPendingAuthSession = null;
+
+                        mStatusBarService.showAuthenticationDialog(
+                                mCurrentAuthSession.mBundle,
+                                mInternalReceiver,
+                                0 /* biometricModality */,
+                                false /* requireConfirmation */,
+                                mCurrentAuthSession.mUserId,
+                                mCurrentAuthSession.mOpPackageName);
+                    } else {
+                        mPendingAuthSession.mClientReceiver.onError(error, message);
+                        mPendingAuthSession = null;
+                    }
                 } else {
                     Slog.e(TAG, "Impossible pending session error state: "
                             + mPendingAuthSession.mState);
                 }
+            } else {
+                Slog.e(TAG, "Unknown cookie: " + cookie);
             }
         } catch (RemoteException e) {
             Slog.e(TAG, "Remote exception", e);
@@ -1396,9 +1243,12 @@
 
         try {
             switch (reason) {
-                case BiometricPrompt.DISMISSED_REASON_CONFIRMED:
-                case BiometricPrompt.DISMISSED_REASON_CONFIRM_NOT_REQUIRED:
-                    mKeyStore.addAuthToken(mCurrentAuthSession.mTokenEscrow);
+                case BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED:
+                case BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED:
+                case BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED:
+                    if (mCurrentAuthSession.mTokenEscrow != null) {
+                        mKeyStore.addAuthToken(mCurrentAuthSession.mTokenEscrow);
+                    }
                     mCurrentAuthSession.mClientReceiver.onAuthenticationSucceeded();
                     break;
 
@@ -1450,12 +1300,37 @@
                 mCurrentAuthSession.mCallingUid,
                 mCurrentAuthSession.mCallingPid,
                 mCurrentAuthSession.mCallingUserId,
-                mCurrentAuthSession.mModality,
-                mCurrentAuthSession.mConfirmDeviceCredentialCallback);
+                mCurrentAuthSession.mModality);
     }
 
+    private void handleOnDeviceCredentialPressed() {
+        Slog.d(TAG, "onDeviceCredentialPressed");
+        if (mCurrentAuthSession == null) {
+            Slog.e(TAG, "Auth session null");
+            return;
+        }
+
+        // Cancel authentication. Skip the token/package check since we are cancelling
+        // from system server. The interface is permission protected so this is fine.
+        cancelInternal(null /* token */, null /* package */, false /* fromClient */);
+
+        mCurrentAuthSession.mState = STATE_SHOWING_DEVICE_CREDENTIAL;
+    }
+
+    /**
+     * Invoked when each service has notified that its client is ready to be started. When
+     * all biometrics are ready, this invokes the SystemUI dialog through StatusBar.
+     */
     private void handleOnReadyForAuthentication(int cookie, boolean requireConfirmation,
             int userId) {
+        if (mPendingAuthSession == null) {
+            // Only should happen if a biometric was locked out when authenticate() was invoked.
+            // In that case, if device credentials are allowed, the UI is already showing. If not
+            // allowed, the error has already been returned to the caller.
+            Slog.w(TAG, "Pending auth session null");
+            return;
+        }
+
         Iterator it = mPendingAuthSession.mModalitiesWaiting.entrySet().iterator();
         while (it.hasNext()) {
             Map.Entry<Integer, Integer> pair = (Map.Entry) it.next();
@@ -1497,7 +1372,7 @@
                 }
 
                 if (!continuing) {
-                    mStatusBarService.showBiometricDialog(mCurrentAuthSession.mBundle,
+                    mStatusBarService.showAuthenticationDialog(mCurrentAuthSession.mBundle,
                             mInternalReceiver, modality, requireConfirmation, userId,
                             mCurrentAuthSession.mOpPackageName);
                 }
@@ -1509,16 +1384,21 @@
 
     private void handleAuthenticate(IBinder token, long sessionId, int userId,
             IBiometricServiceReceiver receiver, String opPackageName, Bundle bundle,
-            int callingUid, int callingPid, int callingUserId,
-            IBiometricConfirmDeviceCredentialCallback callback) {
+            int callingUid, int callingPid, int callingUserId) {
 
         mHandler.post(() -> {
             final Pair<Integer, Integer> result = checkAndGetBiometricModality(userId);
             final int modality = result.first;
             final int error = result.second;
 
-            // Check for errors, notify callback, and return
-            if (error != BiometricConstants.BIOMETRIC_SUCCESS) {
+            final boolean credentialAllowed = Utils.isDeviceCredentialAllowed(bundle);
+
+            if (error != BiometricConstants.BIOMETRIC_SUCCESS && credentialAllowed) {
+                // If there's a problem but device credential is allowed, only show credential UI.
+                bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED,
+                        Authenticator.TYPE_CREDENTIAL);
+            } else if (error != BiometricConstants.BIOMETRIC_SUCCESS) {
+                // Check for errors, notify callback, and return
                 try {
                     final String hardwareUnavailable =
                             getContext().getString(R.string.biometric_error_hw_unavailable);
@@ -1546,7 +1426,7 @@
             // Start preparing for authentication. Authentication starts when
             // all modalities requested have invoked onReadyForAuthentication.
             authenticateInternal(token, sessionId, userId, receiver, opPackageName, bundle,
-                    callingUid, callingPid, callingUserId, modality, callback);
+                    callingUid, callingPid, callingUserId, modality);
         });
     }
 
@@ -1561,8 +1441,7 @@
      */
     private void authenticateInternal(IBinder token, long sessionId, int userId,
             IBiometricServiceReceiver receiver, String opPackageName, Bundle bundle,
-            int callingUid, int callingPid, int callingUserId, int modality,
-            IBiometricConfirmDeviceCredentialCallback callback) {
+            int callingUid, int callingPid, int callingUserId, int modality) {
         try {
             boolean requireConfirmation = bundle.getBoolean(
                     BiometricPrompt.KEY_REQUIRE_CONFIRMATION, true /* default */);
@@ -1576,27 +1455,49 @@
             // with the cookie. Once all cookies are received, we can show the prompt
             // and let the services start authenticating. The cookie should be non-zero.
             final int cookie = mRandom.nextInt(Integer.MAX_VALUE - 1) + 1;
+            final int authenticators = bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED);
             Slog.d(TAG, "Creating auth session. Modality: " + modality
-                    + ", cookie: " + cookie);
-            final HashMap<Integer, Integer> authenticators = new HashMap<>();
-            authenticators.put(modality, cookie);
-            mPendingAuthSession = new AuthSession(authenticators, token, sessionId, userId,
+                    + ", cookie: " + cookie
+                    + ", authenticators: " + authenticators);
+            final HashMap<Integer, Integer> modalities = new HashMap<>();
+
+            // If it's only device credential, we don't need to wait - LockSettingsService is
+            // always ready to check credential (SystemUI invokes that path).
+            if ((authenticators & ~Authenticator.TYPE_CREDENTIAL) != 0) {
+                modalities.put(modality, cookie);
+            }
+            mPendingAuthSession = new AuthSession(modalities, token, sessionId, userId,
                     receiver, opPackageName, bundle, callingUid, callingPid, callingUserId,
-                    modality, requireConfirmation, callback);
-            mPendingAuthSession.mState = STATE_AUTH_CALLED;
-            // No polymorphism :(
-            if ((modality & TYPE_FINGERPRINT) != 0) {
-                mFingerprintService.prepareForAuthentication(token, sessionId, userId,
-                        mInternalReceiver, opPackageName, cookie,
-                        callingUid, callingPid, callingUserId);
-            }
-            if ((modality & TYPE_IRIS) != 0) {
-                Slog.w(TAG, "Iris unsupported");
-            }
-            if ((modality & TYPE_FACE) != 0) {
-                mFaceService.prepareForAuthentication(requireConfirmation,
-                        token, sessionId, userId, mInternalReceiver, opPackageName,
-                        cookie, callingUid, callingPid, callingUserId);
+                    modality, requireConfirmation);
+
+            if (authenticators == Authenticator.TYPE_CREDENTIAL) {
+                mPendingAuthSession.mState = STATE_SHOWING_DEVICE_CREDENTIAL;
+                mCurrentAuthSession = mPendingAuthSession;
+                mPendingAuthSession = null;
+
+                mStatusBarService.showAuthenticationDialog(
+                        mCurrentAuthSession.mBundle,
+                        mInternalReceiver,
+                        0 /* biometricModality */,
+                        false /* requireConfirmation */,
+                        mCurrentAuthSession.mUserId,
+                        mCurrentAuthSession.mOpPackageName);
+            } else {
+                mPendingAuthSession.mState = STATE_AUTH_CALLED;
+                // No polymorphism :(
+                if ((modality & TYPE_FINGERPRINT) != 0) {
+                    mFingerprintService.prepareForAuthentication(token, sessionId, userId,
+                            mInternalReceiver, opPackageName, cookie,
+                            callingUid, callingPid, callingUserId);
+                }
+                if ((modality & TYPE_IRIS) != 0) {
+                    Slog.w(TAG, "Iris unsupported");
+                }
+                if ((modality & TYPE_FACE) != 0) {
+                    mFaceService.prepareForAuthentication(requireConfirmation,
+                            token, sessionId, userId, mInternalReceiver, opPackageName,
+                            cookie, callingUid, callingPid, callingUserId);
+                }
             }
         } catch (RemoteException e) {
             Slog.e(TAG, "Unable to start authentication", e);
@@ -1609,20 +1510,7 @@
             return;
         }
 
-        if (mCurrentAuthSession != null
-                && mCurrentAuthSession.mState == STATE_BIOMETRIC_AUTH_CANCELED_SHOWING_CDC) {
-            if (DEBUG) Slog.d(TAG, "Cancel received while ConfirmDeviceCredential showing");
-            try {
-                mCurrentAuthSession.mConfirmDeviceCredentialCallback.cancel();
-            } catch (RemoteException e) {
-                Slog.e(TAG, "Unable to cancel ConfirmDeviceCredential", e);
-            }
-
-            // TODO(b/123378871): Remove when moved. Piggy back on this for now to clean up.
-            handleOnConfirmDeviceCredentialError(BiometricConstants.BIOMETRIC_ERROR_CANCELED,
-                    getContext().getString(R.string.biometric_error_canceled));
-        } else if (mCurrentAuthSession != null
-                && mCurrentAuthSession.mState != STATE_AUTH_STARTED) {
+        if (mCurrentAuthSession != null && mCurrentAuthSession.mState != STATE_AUTH_STARTED) {
             // We need to check the current authenticators state. If we're pending confirm
             // or idle, we need to dismiss the dialog and send an ERROR_CANCELED to the client,
             // since we won't be getting an onError from the driver.
@@ -1635,24 +1523,12 @@
                 );
 
                 mCurrentAuthSession = null;
-                mStatusBarService.hideBiometricDialog();
+                mStatusBarService.hideAuthenticationDialog();
             } catch (RemoteException e) {
                 Slog.e(TAG, "Remote exception", e);
             }
         } else {
-            boolean fromCDC = false;
-            if (mCurrentAuthSession != null) {
-                fromCDC = mCurrentAuthSession.mBundle.getBoolean(
-                        BiometricPrompt.KEY_FROM_CONFIRM_DEVICE_CREDENTIAL, false);
-            }
-
-            if (fromCDC) {
-                if (DEBUG) Slog.d(TAG, "Cancelling from CDC");
-                cancelInternal(token, opPackageName, false /* fromClient */);
-            } else {
-                cancelInternal(token, opPackageName, true /* fromClient */);
-            }
-
+            cancelInternal(token, opPackageName, true /* fromClient */);
         }
     }
 
diff --git a/services/core/java/com/android/server/biometrics/Utils.java b/services/core/java/com/android/server/biometrics/Utils.java
index 4fa29ac..ed5f9de 100644
--- a/services/core/java/com/android/server/biometrics/Utils.java
+++ b/services/core/java/com/android/server/biometrics/Utils.java
@@ -17,10 +17,15 @@
 package com.android.server.biometrics;
 
 import android.content.Context;
+import android.hardware.biometrics.Authenticator;
+import android.hardware.biometrics.BiometricPrompt;
 import android.os.Build;
+import android.os.Bundle;
 import android.os.UserHandle;
 import android.provider.Settings;
 
+import com.android.internal.annotations.VisibleForTesting;
+
 public class Utils {
     public static boolean isDebugEnabled(Context context, int targetUserId) {
         if (targetUserId == UserHandle.USER_NULL) {
@@ -38,4 +43,43 @@
         }
         return true;
     }
+
+    /**
+     * Combine {@link BiometricPrompt#KEY_ALLOW_DEVICE_CREDENTIAL} with
+     * {@link BiometricPrompt#KEY_AUTHENTICATORS_ALLOWED}, as the former is not flexible
+     * enough.
+     */
+    public static void combineAuthenticatorBundles(Bundle bundle) {
+        boolean biometricEnabled = true; // enabled by default
+        boolean credentialEnabled = bundle.getBoolean(
+                BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, false);
+        if (bundle.get(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED) != null) {
+            final int authenticatorFlags =
+                    bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED);
+            biometricEnabled = (authenticatorFlags & Authenticator.TYPE_BIOMETRIC) != 0;
+            // Using both KEY_ALLOW_DEVICE_CREDENTIAL and KEY_AUTHENTICATORS_ALLOWED together
+            // is not supported. Default to overwriting.
+            credentialEnabled = (authenticatorFlags & Authenticator.TYPE_CREDENTIAL) != 0;
+        }
+
+        bundle.remove(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL);
+
+        int authenticators = 0;
+        if (biometricEnabled) {
+            authenticators |= Authenticator.TYPE_BIOMETRIC;
+        }
+        if (credentialEnabled) {
+            authenticators |= Authenticator.TYPE_CREDENTIAL;
+        }
+        bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+    }
+
+    /**
+     * @param bundle should be first processed by {@link #combineAuthenticatorBundles(Bundle)}
+     * @return true if device credential allowed.
+     */
+    public static boolean isDeviceCredentialAllowed(Bundle bundle) {
+        final int authenticators = bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED);
+        return (authenticators & Authenticator.TYPE_CREDENTIAL) != 0;
+    }
 }
diff --git a/services/core/java/com/android/server/biometrics/face/FaceService.java b/services/core/java/com/android/server/biometrics/face/FaceService.java
index b1c7c76..9eb0d50 100644
--- a/services/core/java/com/android/server/biometrics/face/FaceService.java
+++ b/services/core/java/com/android/server/biometrics/face/FaceService.java
@@ -930,7 +930,8 @@
                     final Face face = new Face("", 0 /* identifier */, deviceId);
                     FaceService.super.handleRemoved(face, 0 /* remaining */);
                 }
-
+                Settings.Secure.putIntForUser(getContext().getContentResolver(),
+                        Settings.Secure.FACE_UNLOCK_RE_ENROLL, 0, UserHandle.USER_CURRENT);
             });
         }
 
diff --git a/services/core/java/com/android/server/compat/PlatformCompat.java b/services/core/java/com/android/server/compat/PlatformCompat.java
index 81e507c..852b26d 100644
--- a/services/core/java/com/android/server/compat/PlatformCompat.java
+++ b/services/core/java/com/android/server/compat/PlatformCompat.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
 import android.util.Slog;
 import android.util.StatsLog;
 
@@ -40,38 +41,80 @@
 
     public PlatformCompat(Context context) {
         mContext = context;
-        mChangeReporter = new ChangeReporter();
+        mChangeReporter = new ChangeReporter(
+                StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__SOURCE__SYSTEM_SERVER);
     }
 
     @Override
     public void reportChange(long changeId, ApplicationInfo appInfo) {
-        reportChange(changeId, appInfo, StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__STATE__LOGGED);
+        reportChange(changeId, appInfo.uid,
+                StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__STATE__LOGGED);
+    }
+
+    @Override
+    public void reportChangeByPackageName(long changeId, String packageName) {
+        ApplicationInfo appInfo = getApplicationInfo(packageName);
+        if (appInfo == null) {
+            return;
+        }
+        reportChange(changeId, appInfo);
+    }
+
+    @Override
+    public void reportChangeByUid(long changeId, int uid) {
+        reportChange(changeId, uid, StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__STATE__LOGGED);
     }
 
     @Override
     public boolean isChangeEnabled(long changeId, ApplicationInfo appInfo) {
         if (CompatConfig.get().isChangeEnabled(changeId, appInfo)) {
-            reportChange(changeId, appInfo,
+            reportChange(changeId, appInfo.uid,
                     StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__STATE__ENABLED);
             return true;
         }
-        reportChange(changeId, appInfo,
+        reportChange(changeId, appInfo.uid,
                 StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__STATE__DISABLED);
         return false;
     }
 
     @Override
+    public boolean isChangeEnabledByPackageName(long changeId, String packageName) {
+        ApplicationInfo appInfo = getApplicationInfo(packageName);
+        if (appInfo == null) {
+            return true;
+        }
+        return isChangeEnabled(changeId, appInfo);
+    }
+
+    @Override
+    public boolean isChangeEnabledByUid(long changeId, int uid) {
+        String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
+        if (packages == null || packages.length == 0) {
+            return true;
+        }
+        boolean enabled = true;
+        for (String packageName : packages) {
+            enabled = enabled && isChangeEnabledByPackageName(changeId, packageName);
+        }
+        return enabled;
+    }
+
+    @Override
     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, "platform_compat", pw)) return;
         CompatConfig.get().dumpConfig(pw);
     }
 
-    private void reportChange(long changeId, ApplicationInfo appInfo, int state) {
-        int uid = appInfo.uid;
-        //TODO(b/138374585): Implement rate limiting for the logs.
-        Slog.d(TAG, ChangeReporter.createLogString(uid, changeId, state));
-        mChangeReporter.reportChange(uid, changeId,
-                state, /* source */
-                StatsLog.APP_COMPATIBILITY_CHANGE_REPORTED__SOURCE__SYSTEM_SERVER);
+    private ApplicationInfo getApplicationInfo(String packageName) {
+        try {
+            return mContext.getPackageManager().getApplicationInfo(packageName, 0);
+        } catch (PackageManager.NameNotFoundException e) {
+            Slog.e(TAG, "No installed package " + packageName);
+        }
+        return null;
+    }
+
+    private void reportChange(long changeId, int uid, int state) {
+        mChangeReporter.reportChange(uid, changeId, state);
     }
 }
diff --git a/services/core/java/com/android/server/connectivity/Nat464Xlat.java b/services/core/java/com/android/server/connectivity/Nat464Xlat.java
index 66bd27c..aea6d8d 100644
--- a/services/core/java/com/android/server/connectivity/Nat464Xlat.java
+++ b/services/core/java/com/android/server/connectivity/Nat464Xlat.java
@@ -16,6 +16,7 @@
 
 package com.android.server.connectivity;
 
+import android.annotation.NonNull;
 import android.net.ConnectivityManager;
 import android.net.IDnsResolver;
 import android.net.INetd;
@@ -325,13 +326,13 @@
      * This is necessary because the LinkProperties in mNetwork come from the transport layer, which
      * has no idea that 464xlat is running on top of it.
      */
-    public void fixupLinkProperties(LinkProperties oldLp, LinkProperties lp) {
+    public void fixupLinkProperties(@NonNull LinkProperties oldLp, @NonNull LinkProperties lp) {
         lp.setNat64Prefix(mNat64Prefix);
 
         if (!isRunning()) {
             return;
         }
-        if (lp == null || lp.getAllInterfaceNames().contains(mIface)) {
+        if (lp.getAllInterfaceNames().contains(mIface)) {
             return;
         }
 
@@ -434,7 +435,7 @@
 
     @Override
     public void interfaceRemoved(String iface) {
-        mNetwork.handler().post(() -> { handleInterfaceRemoved(iface); });
+        mNetwork.handler().post(() -> handleInterfaceRemoved(iface));
     }
 
     @Override
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 7b3eae1..6b70e5f 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -199,13 +199,22 @@
      */
     private @NonNull List<String> mLockdownWhitelist = Collections.emptyList();
 
-    /**
-     * List of UIDs for which networking should be blocked until VPN is ready, during brief periods
-     * when VPN is not running. For example, during system startup or after a crash.
+     /**
+     * A memory of what UIDs this class told netd to block for the lockdown feature.
+     *
+     * Netd maintains ranges of UIDs for which network should be restricted to using only the VPN
+     * for the lockdown feature. This class manages these UIDs and sends this information to netd.
+     * To avoid sending the same commands multiple times (which would be wasteful) and to be able
+     * to revoke lists (when the rules should change), it's simplest to keep this cache of what
+     * netd knows, so it can be diffed and sent most efficiently.
+     *
+     * The contents of this list must only be changed when updating the UIDs lists with netd,
+     * since it needs to keep in sync with the picture netd has of them.
+     *
      * @see mLockdown
      */
     @GuardedBy("this")
-    private Set<UidRange> mBlockedUsers = new ArraySet<>();
+    private final Set<UidRange> mBlockedUidsAsToldToNetd = new ArraySet<>();
 
     // Handle of the user initiating VPN.
     private final int mUserHandle;
@@ -254,7 +263,7 @@
     }
 
     /**
-     * Update current state, dispaching event to listeners.
+     * Update current state, dispatching event to listeners.
      */
     @VisibleForTesting
     protected void updateState(DetailedState detailedState, String reason) {
@@ -1325,7 +1334,7 @@
      *                {@link Vpn} goes through a VPN connection or is blocked until one is
      *                available, {@code false} to lift the requirement.
      *
-     * @see #mBlockedUsers
+     * @see #mBlockedUidsAsToldToNetd
      */
     @GuardedBy("this")
     private void setVpnForcedLocked(boolean enforce) {
@@ -1336,37 +1345,47 @@
             exemptedPackages = new ArrayList<>(mLockdownWhitelist);
             exemptedPackages.add(mPackage);
         }
-        final Set<UidRange> removedRanges = new ArraySet<>(mBlockedUsers);
+        final Set<UidRange> rangesToTellNetdToRemove = new ArraySet<>(mBlockedUidsAsToldToNetd);
 
-        Set<UidRange> addedRanges = Collections.emptySet();
+        final Set<UidRange> rangesToTellNetdToAdd;
         if (enforce) {
-            addedRanges = createUserAndRestrictedProfilesRanges(mUserHandle,
-                    /* allowedApplications */ null,
-                    /* disallowedApplications */ exemptedPackages);
+            final Set<UidRange> rangesThatShouldBeBlocked =
+                    createUserAndRestrictedProfilesRanges(mUserHandle,
+                            /* allowedApplications */ null,
+                            /* disallowedApplications */ exemptedPackages);
 
             // The UID range of the first user (0-99999) would block the IPSec traffic, which comes
             // directly from the kernel and is marked as uid=0. So we adjust the range to allow
             // it through (b/69873852).
-            for (UidRange range : addedRanges) {
+            for (UidRange range : rangesThatShouldBeBlocked) {
                 if (range.start == 0) {
-                    addedRanges.remove(range);
+                    rangesThatShouldBeBlocked.remove(range);
                     if (range.stop != 0) {
-                        addedRanges.add(new UidRange(1, range.stop));
+                        rangesThatShouldBeBlocked.add(new UidRange(1, range.stop));
                     }
                 }
             }
 
-            removedRanges.removeAll(addedRanges);
-            addedRanges.removeAll(mBlockedUsers);
+            rangesToTellNetdToRemove.removeAll(rangesThatShouldBeBlocked);
+            rangesToTellNetdToAdd = rangesThatShouldBeBlocked;
+            // The ranges to tell netd to add are the ones that should be blocked minus the
+            // ones it already knows to block. Note that this will change the contents of
+            // rangesThatShouldBeBlocked, but the list of ranges that should be blocked is
+            // not used after this so it's fine to destroy it.
+            rangesToTellNetdToAdd.removeAll(mBlockedUidsAsToldToNetd);
+        } else {
+            rangesToTellNetdToAdd = Collections.emptySet();
         }
 
-        setAllowOnlyVpnForUids(false, removedRanges);
-        setAllowOnlyVpnForUids(true, addedRanges);
+        // If mBlockedUidsAsToldToNetd used to be empty, this will always be a no-op.
+        setAllowOnlyVpnForUids(false, rangesToTellNetdToRemove);
+        // If nothing should be blocked now, this will now be a no-op.
+        setAllowOnlyVpnForUids(true, rangesToTellNetdToAdd);
     }
 
     /**
-     * Either add or remove a list of {@link UidRange}s to the list of UIDs that are only allowed
-     * to make connections through sockets that have had {@code protect()} called on them.
+     * Tell netd to add or remove a list of {@link UidRange}s to the list of UIDs that are only
+     * allowed to make connections through sockets that have had {@code protect()} called on them.
      *
      * @param enforce {@code true} to add to the blacklist, {@code false} to remove.
      * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
@@ -1388,9 +1407,9 @@
             return false;
         }
         if (enforce) {
-            mBlockedUsers.addAll(ranges);
+            mBlockedUidsAsToldToNetd.addAll(ranges);
         } else {
-            mBlockedUsers.removeAll(ranges);
+            mBlockedUidsAsToldToNetd.removeAll(ranges);
         }
         return true;
     }
@@ -1557,17 +1576,18 @@
     /**
      * @param uid The target uid.
      *
-     * @return {@code true} if {@code uid} is included in one of the mBlockedUsers ranges and the
-     * VPN is not connected, or if the VPN is connected but does not apply to the {@code uid}.
+     * @return {@code true} if {@code uid} is included in one of the mBlockedUidsAsToldToNetd
+     * ranges and the VPN is not connected, or if the VPN is connected but does not apply to
+     * the {@code uid}.
      *
      * @apiNote This method don't check VPN lockdown status.
-     * @see #mBlockedUsers
+     * @see #mBlockedUidsAsToldToNetd
      */
     public synchronized boolean isBlockingUid(int uid) {
         if (mNetworkInfo.isConnected()) {
             return !appliesToUid(uid);
         } else {
-            return UidRange.containsUid(mBlockedUsers, uid);
+            return UidRange.containsUid(mBlockedUidsAsToldToNetd, uid);
         }
     }
 
diff --git a/services/core/java/com/android/server/display/ColorFade.java b/services/core/java/com/android/server/display/ColorFade.java
index c46fc20..29026e8 100644
--- a/services/core/java/com/android/server/display/ColorFade.java
+++ b/services/core/java/com/android/server/display/ColorFade.java
@@ -114,6 +114,8 @@
     private final FloatBuffer mVertexBuffer = createNativeFloatBuffer(8);
     private final FloatBuffer mTexCoordBuffer = createNativeFloatBuffer(8);
 
+    private final Transaction mTransaction = new Transaction();
+
     /**
      * Animates an color fade warming up.
      */
@@ -659,14 +661,10 @@
 
     private boolean showSurface(float alpha) {
         if (!mSurfaceVisible || mSurfaceAlpha != alpha) {
-            SurfaceControl.openTransaction();
-            try {
-                mSurfaceControl.setLayer(COLOR_FADE_LAYER);
-                mSurfaceControl.setAlpha(alpha);
-                mSurfaceControl.show();
-            } finally {
-                SurfaceControl.closeTransaction();
-            }
+            mTransaction.setLayer(mSurfaceControl, COLOR_FADE_LAYER)
+                    .setAlpha(mSurfaceControl, alpha)
+                    .show(mSurfaceControl)
+                    .apply();
             mSurfaceVisible = true;
             mSurfaceAlpha = alpha;
         }
diff --git a/services/core/java/com/android/server/display/DisplayModeDirector.java b/services/core/java/com/android/server/display/DisplayModeDirector.java
index 1fc0db3..d24bd1a 100644
--- a/services/core/java/com/android/server/display/DisplayModeDirector.java
+++ b/services/core/java/com/android/server/display/DisplayModeDirector.java
@@ -49,8 +49,9 @@
 
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.R;
+import com.android.server.display.utils.AmbientFilter;
+import com.android.server.display.utils.AmbientFilterFactory;
 import com.android.server.display.whitebalance.DisplayWhiteBalanceFactory;
-import com.android.server.display.whitebalance.AmbientFilter;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -970,7 +971,7 @@
                 if (lightSensor != null) {
                     final Resources res = mContext.getResources();
 
-                    mAmbientFilter = DisplayWhiteBalanceFactory.createBrightnessFilter(res);
+                    mAmbientFilter = AmbientFilterFactory.createBrightnessFilter(TAG, res);
                     mLightSensor = lightSensor;
 
                     onScreenOn(isDefaultDisplayOn());
diff --git a/services/core/java/com/android/server/display/utils/AmbientFilter.java b/services/core/java/com/android/server/display/utils/AmbientFilter.java
new file mode 100644
index 0000000..1a84121
--- /dev/null
+++ b/services/core/java/com/android/server/display/utils/AmbientFilter.java
@@ -0,0 +1,254 @@
+/*
+ * Copyright (C) 2019 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.display.utils;
+
+import android.util.Slog;
+
+import java.io.PrintWriter;
+import java.util.Arrays;
+
+/**
+ * The DisplayWhiteBalanceController uses the AmbientFilter to average ambient changes over time,
+ * filter out the noise, and arrive at an estimate of the actual value.
+ *
+ * When the DisplayWhiteBalanceController detects a change in ambient brightness or color
+ * temperature, it passes it to the AmbientFilter, and when it needs the actual ambient value, it
+ * asks it for an estimate.
+ *
+ * Implementations:
+ * - {@link WeightedMovingAverageAmbientFilter}
+ *   A weighted average prioritising recent changes.
+ */
+abstract public class AmbientFilter {
+
+    protected static final boolean DEBUG = false; // Enable for verbose logs.
+
+    protected final String mTag;
+    protected boolean mLoggingEnabled;
+
+    // How long ambient value changes are kept and taken into consideration.
+    private final int mHorizon; // Milliseconds
+
+    private final RollingBuffer mBuffer;
+
+    /**
+     * @param tag
+     *      The tag used for dumping and logging.
+     * @param horizon
+     *      How long ambient value changes are kept and taken into consideration.
+     *
+     * @throws IllegalArgumentException
+     *      - horizon is not positive.
+     */
+    AmbientFilter(String tag, int horizon) {
+        validateArguments(horizon);
+        mTag = tag;
+        mLoggingEnabled = false;
+        mHorizon = horizon;
+        mBuffer = new RollingBuffer();
+    }
+
+    /**
+     * Add an ambient value change.
+     *
+     * @param time
+     *      The time.
+     * @param value
+     *      The ambient value.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean addValue(long time, float value) {
+        if (value < 0.0f) {
+            return false;
+        }
+        truncateOldValues(time);
+        if (mLoggingEnabled) {
+            Slog.d(mTag, "add value: " + value + " @ " + time);
+        }
+        mBuffer.add(time, value);
+        return true;
+    }
+
+    /**
+     * Get an estimate of the actual ambient color temperature.
+     *
+     * @param time
+     *      The time.
+     *
+     * @return An estimate of the actual ambient color temperature.
+     */
+    public float getEstimate(long time) {
+        truncateOldValues(time);
+        final float value = filter(time, mBuffer);
+        if (mLoggingEnabled) {
+            Slog.d(mTag, "get estimate: " + value + " @ " + time);
+        }
+        return value;
+    }
+
+    /**
+     * Clears the filter state.
+     */
+    public void clear() {
+        mBuffer.clear();
+    }
+
+    /**
+     * Enable/disable logging.
+     *
+     * @param loggingEnabled
+     *      Whether logging is on/off.
+     *
+     * @return Whether the method succeeded or not.
+     */
+    public boolean setLoggingEnabled(boolean loggingEnabled) {
+        if (mLoggingEnabled == loggingEnabled) {
+            return false;
+        }
+        mLoggingEnabled = loggingEnabled;
+        return true;
+    }
+
+    /**
+     * Dump the state.
+     *
+     * @param writer
+     *      The PrintWriter used to dump the state.
+     */
+    public void dump(PrintWriter writer) {
+        writer.println("  " + mTag);
+        writer.println("    mLoggingEnabled=" + mLoggingEnabled);
+        writer.println("    mHorizon=" + mHorizon);
+        writer.println("    mBuffer=" + mBuffer);
+    }
+
+    private void validateArguments(int horizon) {
+        if (horizon <= 0) {
+            throw new IllegalArgumentException("horizon must be positive");
+        }
+    }
+
+    private void truncateOldValues(long time) {
+        final long minTime = time - mHorizon;
+        mBuffer.truncate(minTime);
+    }
+
+    protected abstract float filter(long time, RollingBuffer buffer);
+
+    /**
+     * A weighted average prioritising recent changes.
+     */
+    static class WeightedMovingAverageAmbientFilter extends AmbientFilter {
+
+        // How long the latest ambient value change is predicted to last.
+        private static final int PREDICTION_TIME = 100; // Milliseconds
+
+        // Recent changes are prioritised by integrating their duration over y = x + mIntercept
+        // (the higher it is, the less prioritised recent changes are).
+        private final float mIntercept;
+
+        /**
+         * @param tag
+         *      The tag used for dumping and logging.
+         * @param horizon
+         *      How long ambient value changes are kept and taken into consideration.
+         * @param intercept
+         *      Recent changes are prioritised by integrating their duration over y = x + intercept
+         *      (the higher it is, the less prioritised recent changes are).
+         *
+         * @throws IllegalArgumentException
+         *      - horizon is not positive.
+         *      - intercept is NaN or negative.
+         */
+        WeightedMovingAverageAmbientFilter(String tag, int horizon, float intercept) {
+            super(tag, horizon);
+            validateArguments(intercept);
+            mIntercept = intercept;
+        }
+
+        /**
+         * See {@link AmbientFilter#dump base class}.
+         */
+        @Override
+        public void dump(PrintWriter writer) {
+            super.dump(writer);
+            writer.println("    mIntercept=" + mIntercept);
+        }
+
+        // Normalise the times to [t1=0, t2, ..., tN, now + PREDICTION_TIME], so the first change
+        // starts at 0 and the last change is predicted to last a bit, and divide them by 1000 as
+        // milliseconds are high enough to overflow.
+        // The weight of the value from t[i] to t[i+1] is the area under (A.K.A. the integral of)
+        // y = x + mIntercept from t[i] to t[i+1].
+        @Override
+        protected float filter(long time, RollingBuffer buffer) {
+            if (buffer.isEmpty()) {
+                return -1.0f;
+            }
+            float total = 0.0f;
+            float totalWeight = 0.0f;
+            final float[] weights = getWeights(time, buffer);
+            if (DEBUG && mLoggingEnabled) {
+                Slog.v(mTag, "filter: " + buffer + " => " + Arrays.toString(weights));
+            }
+            for (int i = 0; i < weights.length; i++) {
+                final float value = buffer.getValue(i);
+                final float weight = weights[i];
+                total += weight * value;
+                totalWeight += weight;
+            }
+            if (totalWeight == 0.0f) {
+                return buffer.getValue(buffer.size() - 1);
+            }
+            return total / totalWeight;
+        }
+
+        private void validateArguments(float intercept) {
+            if (Float.isNaN(intercept) || intercept < 0.0f) {
+                throw new IllegalArgumentException("intercept must be a non-negative number");
+            }
+        }
+
+        private float[] getWeights(long time, RollingBuffer buffer) {
+            float[] weights = new float[buffer.size()];
+            final long startTime = buffer.getTime(0);
+            float previousTime = 0.0f;
+            for (int i = 1; i < weights.length; i++) {
+                final float currentTime = (buffer.getTime(i) - startTime) / 1000.0f;
+                final float weight = calculateIntegral(previousTime, currentTime);
+                weights[i - 1] = weight;
+                previousTime = currentTime;
+            }
+            final float lastTime = (time + PREDICTION_TIME - startTime) / 1000.0f;
+            final float lastWeight = calculateIntegral(previousTime, lastTime);
+            weights[weights.length - 1] = lastWeight;
+            return weights;
+        }
+
+        private float calculateIntegral(float from, float to) {
+            return antiderivative(to) - antiderivative(from);
+        }
+
+        private float antiderivative(float x) {
+            // f(x) = x + c => F(x) = 1/2 * x^2 + c * x
+            return 0.5f * x * x + mIntercept * x;
+        }
+
+    }
+
+}
diff --git a/services/core/java/com/android/server/display/utils/AmbientFilterFactory.java b/services/core/java/com/android/server/display/utils/AmbientFilterFactory.java
new file mode 100644
index 0000000..dfa1ddc
--- /dev/null
+++ b/services/core/java/com/android/server/display/utils/AmbientFilterFactory.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2019 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.display.utils;
+
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.util.TypedValue;
+
+public class AmbientFilterFactory {
+    /**
+     * Creates a temporal filter which functions as a weighted moving average buffer for recent
+     * sensor values.
+     * @param tag
+     *      The tag used for dumping and logging.
+     * @param horizon
+     *      How long ambient value changes are kept and taken into consideration.
+     * @param intercept
+     *      Recent changes are prioritised by integrating their duration over y = x + intercept
+     *      (the higher it is, the less prioritised recent changes are).
+     *
+     * @return
+     *      An AmbientFiler.
+     *
+     * @throws IllegalArgumentException
+     *      - Horizon is not positive.
+     *      - Intercept not configured.
+     */
+    public static AmbientFilter createAmbientFilter(String tag, int horizon, float intercept) {
+        if (!Float.isNaN(intercept)) {
+            return new AmbientFilter.WeightedMovingAverageAmbientFilter(tag, horizon, intercept);
+        }
+        throw new IllegalArgumentException("missing configurations: "
+                + "expected config_displayWhiteBalanceBrightnessFilterIntercept");
+    }
+
+    /**
+     * Helper to create a default BrightnessFilter which has configuration in the resource file.
+     * @param tag
+     *      The tag used for dumping and logging.
+     * @param resources
+     *      The resources used to configure the various components.
+     *
+     * @return
+     *      An AmbientFilter.
+     */
+    public static AmbientFilter createBrightnessFilter(String tag, Resources resources) {
+        final int horizon = resources.getInteger(
+                com.android.internal.R.integer.config_displayWhiteBalanceBrightnessFilterHorizon);
+        final float intercept = getFloat(resources,
+                com.android.internal.R.dimen.config_displayWhiteBalanceBrightnessFilterIntercept);
+
+        return createAmbientFilter(tag, horizon, intercept);
+    }
+
+    /**
+     * Helper to creates a default ColorTemperatureFilter which has configuration in the resource
+     * file.
+     * @param tag
+     *      The tag used for dumping and logging.
+     * @param resources
+     *      The resources used to configure the various components.
+     *
+     * @return
+     *      An AmbientFilter.
+     */
+    public static AmbientFilter createColorTemperatureFilter(String tag, Resources resources) {
+        final int horizon = resources.getInteger(
+                com.android.internal.R.integer
+                .config_displayWhiteBalanceColorTemperatureFilterHorizon);
+        final float intercept = getFloat(resources,
+                com.android.internal.R.dimen
+                .config_displayWhiteBalanceColorTemperatureFilterIntercept);
+
+        return createAmbientFilter(tag, horizon, intercept);
+    }
+
+    // Instantiation is disabled.
+    private AmbientFilterFactory() { }
+
+    private static float getFloat(Resources resources, int id) {
+        TypedValue value = new TypedValue();
+
+        resources.getValue(id, value, true /* resolveRefs */);
+        if (value.type != TypedValue.TYPE_FLOAT) {
+            return Float.NaN;
+        }
+
+        return value.getFloat();
+    }
+}
+
diff --git a/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java b/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java
deleted file mode 100644
index 3580897..0000000
--- a/services/core/java/com/android/server/display/whitebalance/AmbientFilter.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2019 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.display.whitebalance;
-
-import android.util.Slog;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.display.utils.RollingBuffer;
-
-import java.io.PrintWriter;
-import java.util.Arrays;
-
-/**
- * The DisplayWhiteBalanceController uses the AmbientFilter to average ambient changes over time,
- * filter out the noise, and arrive at an estimate of the actual value.
- *
- * When the DisplayWhiteBalanceController detects a change in ambient brightness or color
- * temperature, it passes it to the AmbientFilter, and when it needs the actual ambient value, it
- * asks it for an estimate.
- *
- * Implementations:
- * - {@link WeightedMovingAverageAmbientFilter}
- *   A weighted average prioritising recent changes.
- */
-abstract public class AmbientFilter {
-
-    protected static final boolean DEBUG = false; // Enable for verbose logs.
-
-    protected final String mTag;
-    protected boolean mLoggingEnabled;
-
-    // How long ambient value changes are kept and taken into consideration.
-    private final int mHorizon; // Milliseconds
-
-    private final RollingBuffer mBuffer;
-
-    /**
-     * @param tag
-     *      The tag used for dumping and logging.
-     * @param horizon
-     *      How long ambient value changes are kept and taken into consideration.
-     *
-     * @throws IllegalArgumentException
-     *      - horizon is not positive.
-     */
-    AmbientFilter(String tag, int horizon) {
-        validateArguments(horizon);
-        mTag = tag;
-        mLoggingEnabled = false;
-        mHorizon = horizon;
-        mBuffer = new RollingBuffer();
-    }
-
-    /**
-     * Add an ambient value change.
-     *
-     * @param time
-     *      The time.
-     * @param value
-     *      The ambient value.
-     *
-     * @return Whether the method succeeded or not.
-     */
-    public boolean addValue(long time, float value) {
-        if (value < 0.0f) {
-            return false;
-        }
-        truncateOldValues(time);
-        if (mLoggingEnabled) {
-            Slog.d(mTag, "add value: " + value + " @ " + time);
-        }
-        mBuffer.add(time, value);
-        return true;
-    }
-
-    /**
-     * Get an estimate of the actual ambient color temperature.
-     *
-     * @param time
-     *      The time.
-     *
-     * @return An estimate of the actual ambient color temperature.
-     */
-    public float getEstimate(long time) {
-        truncateOldValues(time);
-        final float value = filter(time, mBuffer);
-        if (mLoggingEnabled) {
-            Slog.d(mTag, "get estimate: " + value + " @ " + time);
-        }
-        return value;
-    }
-
-    /**
-     * Clears the filter state.
-     */
-    public void clear() {
-        mBuffer.clear();
-    }
-
-    /**
-     * Enable/disable logging.
-     *
-     * @param loggingEnabled
-     *      Whether logging is on/off.
-     *
-     * @return Whether the method succeeded or not.
-     */
-    public boolean setLoggingEnabled(boolean loggingEnabled) {
-        if (mLoggingEnabled == loggingEnabled) {
-            return false;
-        }
-        mLoggingEnabled = loggingEnabled;
-        return true;
-    }
-
-    /**
-     * Dump the state.
-     *
-     * @param writer
-     *      The PrintWriter used to dump the state.
-     */
-    public void dump(PrintWriter writer) {
-        writer.println("  " + mTag);
-        writer.println("    mLoggingEnabled=" + mLoggingEnabled);
-        writer.println("    mHorizon=" + mHorizon);
-        writer.println("    mBuffer=" + mBuffer);
-    }
-
-    private void validateArguments(int horizon) {
-        if (horizon <= 0) {
-            throw new IllegalArgumentException("horizon must be positive");
-        }
-    }
-
-    private void truncateOldValues(long time) {
-        final long minTime = time - mHorizon;
-        mBuffer.truncate(minTime);
-    }
-
-    protected abstract float filter(long time, RollingBuffer buffer);
-
-    /**
-     * A weighted average prioritising recent changes.
-     */
-    static class WeightedMovingAverageAmbientFilter extends AmbientFilter {
-
-        // How long the latest ambient value change is predicted to last.
-        private static final int PREDICTION_TIME = 100; // Milliseconds
-
-        // Recent changes are prioritised by integrating their duration over y = x + mIntercept
-        // (the higher it is, the less prioritised recent changes are).
-        private final float mIntercept;
-
-        /**
-         * @param tag
-         *      The tag used for dumping and logging.
-         * @param horizon
-         *      How long ambient value changes are kept and taken into consideration.
-         * @param intercept
-         *      Recent changes are prioritised by integrating their duration over y = x + intercept
-         *      (the higher it is, the less prioritised recent changes are).
-         *
-         * @throws IllegalArgumentException
-         *      - horizon is not positive.
-         *      - intercept is NaN or negative.
-         */
-        WeightedMovingAverageAmbientFilter(String tag, int horizon, float intercept) {
-            super(tag, horizon);
-            validateArguments(intercept);
-            mIntercept = intercept;
-        }
-
-        /**
-         * See {@link AmbientFilter#dump base class}.
-         */
-        @Override
-        public void dump(PrintWriter writer) {
-            super.dump(writer);
-            writer.println("    mIntercept=" + mIntercept);
-        }
-
-        // Normalise the times to [t1=0, t2, ..., tN, now + PREDICTION_TIME], so the first change
-        // starts at 0 and the last change is predicted to last a bit, and divide them by 1000 as
-        // milliseconds are high enough to overflow.
-        // The weight of the value from t[i] to t[i+1] is the area under (A.K.A. the integral of)
-        // y = x + mIntercept from t[i] to t[i+1].
-        @Override
-        protected float filter(long time, RollingBuffer buffer) {
-            if (buffer.isEmpty()) {
-                return -1.0f;
-            }
-            float total = 0.0f;
-            float totalWeight = 0.0f;
-            final float[] weights = getWeights(time, buffer);
-            if (DEBUG && mLoggingEnabled) {
-                Slog.v(mTag, "filter: " + buffer + " => " + Arrays.toString(weights));
-            }
-            for (int i = 0; i < weights.length; i++) {
-                final float value = buffer.getValue(i);
-                final float weight = weights[i];
-                total += weight * value;
-                totalWeight += weight;
-            }
-            if (totalWeight == 0.0f) {
-                return buffer.getValue(buffer.size() - 1);
-            }
-            return total / totalWeight;
-        }
-
-        private void validateArguments(float intercept) {
-            if (Float.isNaN(intercept) || intercept < 0.0f) {
-                throw new IllegalArgumentException("intercept must be a non-negative number");
-            }
-        }
-
-        private float[] getWeights(long time, RollingBuffer buffer) {
-            float[] weights = new float[buffer.size()];
-            final long startTime = buffer.getTime(0);
-            float previousTime = 0.0f;
-            for (int i = 1; i < weights.length; i++) {
-                final float currentTime = (buffer.getTime(i) - startTime) / 1000.0f;
-                final float weight = calculateIntegral(previousTime, currentTime);
-                weights[i - 1] = weight;
-                previousTime = currentTime;
-            }
-            final float lastTime = (time + PREDICTION_TIME - startTime) / 1000.0f;
-            final float lastWeight = calculateIntegral(previousTime, lastTime);
-            weights[weights.length - 1] = lastWeight;
-            return weights;
-        }
-
-        private float calculateIntegral(float from, float to) {
-            return antiderivative(to) - antiderivative(from);
-        }
-
-        private float antiderivative(float x) {
-            // f(x) = x + c => F(x) = 1/2 * x^2 + c * x
-            return 0.5f * x * x + mIntercept * x;
-        }
-
-    }
-
-}
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
index 7b1f4c3..88a7077 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceController.java
@@ -24,6 +24,7 @@
 import com.android.internal.util.Preconditions;
 import com.android.server.LocalServices;
 import com.android.server.display.color.ColorDisplayService.ColorDisplayServiceInternal;
+import com.android.server.display.utils.AmbientFilter;
 import com.android.server.display.utils.History;
 
 import java.io.PrintWriter;
@@ -63,7 +64,13 @@
     AmbientFilter mColorTemperatureFilter;
     private DisplayWhiteBalanceThrottler mThrottler;
 
+    // In low brightness conditions the ALS readings are more noisy and produce
+    // high errors. This default is introduced to provide a fixed display color
+    // temperature when sensor readings become unreliable.
     private final float mLowLightAmbientColorTemperature;
+    // In high brightness conditions certain color temperatures can cause peak display
+    // brightness to drop. This fixed color temperature can be used to compensate for
+    // this effect.
     private final float mHighLightAmbientColorTemperature;
 
     private float mAmbientColorTemperature;
@@ -84,12 +91,14 @@
     // A piecewise linear relationship between ambient and display color temperatures.
     private Spline.LinearSpline mAmbientToDisplayColorTemperatureSpline;
 
-    // In very low or very high brightness conditions ambient EQ should to set to a default
-    // instead of using mAmbientToDisplayColorTemperatureSpline. However, setting ambient EQ
-    // based on thresholds can cause the display to rapidly change color temperature. To solve
-    // this, mLowLightAmbientBrightnessToBiasSpline and mHighLightAmbientBrightnessToBiasSpline
-    // are used to smoothly interpolate from ambient color temperature to the defaults.
-    // A piecewise linear relationship between low light brightness and low light bias.
+    // In very low or very high brightness conditions Display White Balance should
+    // be to set to a default instead of using mAmbientToDisplayColorTemperatureSpline.
+    // However, setting Display White Balance based on thresholds can cause the
+    // display to rapidly change color temperature. To solve this,
+    // mLowLightAmbientBrightnessToBiasSpline and
+    // mHighLightAmbientBrightnessToBiasSpline are used to smoothly interpolate from
+    // ambient color temperature to the defaults. A piecewise linear relationship
+    // between low light brightness and low light bias.
     private Spline.LinearSpline mLowLightAmbientBrightnessToBiasSpline;
 
     // A piecewise linear relationship between high light brightness and high light bias.
diff --git a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
index bf0a1d1..a72b1ed 100644
--- a/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
+++ b/services/core/java/com/android/server/display/whitebalance/DisplayWhiteBalanceFactory.java
@@ -23,6 +23,8 @@
 import android.util.TypedValue;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.display.utils.AmbientFilter;
+import com.android.server.display.utils.AmbientFilterFactory;
 
 /**
  * The DisplayWhiteBalanceFactory creates and configures an DisplayWhiteBalanceController.
@@ -58,10 +60,12 @@
             SensorManager sensorManager, Resources resources) {
         final AmbientSensor.AmbientBrightnessSensor brightnessSensor =
                 createBrightnessSensor(handler, sensorManager, resources);
-        final AmbientFilter brightnessFilter = createBrightnessFilter(resources);
+        final AmbientFilter brightnessFilter =
+                AmbientFilterFactory.createBrightnessFilter(BRIGHTNESS_FILTER_TAG, resources);
         final AmbientSensor.AmbientColorTemperatureSensor colorTemperatureSensor =
                 createColorTemperatureSensor(handler, sensorManager, resources);
-        final AmbientFilter colorTemperatureFilter = createColorTemperatureFilter(resources);
+        final AmbientFilter colorTemperatureFilter = AmbientFilterFactory
+                .createColorTemperatureFilter(COLOR_TEMPERATURE_FILTER_TAG, resources);
         final DisplayWhiteBalanceThrottler throttler = createThrottler(resources);
         final float[] displayWhiteBalanceLowLightAmbientBrightnesses = getFloatArray(resources,
                 com.android.internal.R.array
@@ -112,23 +116,6 @@
     }
 
     /**
-     * Creates a BrightnessFilter which functions as a weighted moving average buffer for recent
-     * brightness values.
-     */
-    public static AmbientFilter createBrightnessFilter(Resources resources) {
-        final int horizon = resources.getInteger(
-                com.android.internal.R.integer.config_displayWhiteBalanceBrightnessFilterHorizon);
-        final float intercept = getFloat(resources,
-                com.android.internal.R.dimen.config_displayWhiteBalanceBrightnessFilterIntercept);
-        if (!Float.isNaN(intercept)) {
-            return new AmbientFilter.WeightedMovingAverageAmbientFilter(
-                    BRIGHTNESS_FILTER_TAG, horizon, intercept);
-        }
-        throw new IllegalArgumentException("missing configurations: "
-                + "expected config_displayWhiteBalanceBrightnessFilterIntercept");
-    }
-
-    /**
      * Creates an ambient color sensor instance to redirect sensor data to callbacks.
      */
     @VisibleForTesting
@@ -143,21 +130,6 @@
         return new AmbientSensor.AmbientColorTemperatureSensor(handler, sensorManager, name, rate);
     }
 
-    private static AmbientFilter createColorTemperatureFilter(Resources resources) {
-        final int horizon = resources.getInteger(
-                com.android.internal.R.integer
-                .config_displayWhiteBalanceColorTemperatureFilterHorizon);
-        final float intercept = getFloat(resources,
-                com.android.internal.R.dimen
-                .config_displayWhiteBalanceColorTemperatureFilterIntercept);
-        if (!Float.isNaN(intercept)) {
-            return new AmbientFilter.WeightedMovingAverageAmbientFilter(
-                    COLOR_TEMPERATURE_FILTER_TAG, horizon, intercept);
-        }
-        throw new IllegalArgumentException("missing configurations: "
-                + "expected config_displayWhiteBalanceColorTemperatureFilterIntercept");
-    }
-
     private static DisplayWhiteBalanceThrottler createThrottler(Resources resources) {
         final int increaseDebounce = resources.getInteger(
                 com.android.internal.R.integer.config_displayWhiteBalanceDecreaseDebounce);
diff --git a/services/core/java/com/android/server/hdmi/Constants.java b/services/core/java/com/android/server/hdmi/Constants.java
index cfbf8bc..96ba8ef 100644
--- a/services/core/java/com/android/server/hdmi/Constants.java
+++ b/services/core/java/com/android/server/hdmi/Constants.java
@@ -394,10 +394,6 @@
     static final String PROPERTY_PREFERRED_ADDRESS_PLAYBACK = "persist.sys.hdmi.addr.playback";
     static final String PROPERTY_PREFERRED_ADDRESS_TV = "persist.sys.hdmi.addr.tv";
 
-    // Property name for the local device configurations.
-    // TODO(OEM): OEM should provide this property, and the value is the comma separated integer
-    //     values which denotes the device type in HDMI Spec 1.4.
-    static final String PROPERTY_DEVICE_TYPE = "ro.hdmi.device_type";
 
     // TODO(OEM): Set this to false to keep the playback device in sleep upon hotplug event.
     //            True by default.
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
index 4f4baab..61d4d4b 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystem.java
@@ -850,36 +850,25 @@
                         mAddress, Constants.ADDR_BROADCAST, systemAudioStatusOn));
 
         if (systemAudioStatusOn) {
+            // If TV sends out SAM Request with a path of a non-CEC device, which should not show
+            // up in the CEC device list and not under the current AVR device, the AVR would switch
+            // to ARC.
             int sourcePhysicalAddress = HdmiUtils.twoBytesToInt(message.getParams());
-            if (sourcePhysicalAddress != getActiveSource().physicalAddress) {
-                // If the Active Source recorded by the current device is not synced up with TV,
-                // update the Active Source internally.
-                if (sourcePhysicalAddress == mService.getPhysicalAddress()) {
-                    // If the active path is the current device itself, update with local info
-                    if (mService.playback() != null) {
-                        setActiveSource(mService.playback().mAddress, sourcePhysicalAddress);
-                    } else {
-                        setActiveSource(mAddress, sourcePhysicalAddress);
-                    }
-                } else {
-                    // If it's not the current device, look for the device info from the list
-                    for (HdmiDeviceInfo info : HdmiUtils.sparseArrayToList(mDeviceInfos)) {
-                        if (info.getPhysicalAddress() == sourcePhysicalAddress) {
-                            setActiveSource(info.getLogicalAddress(), info.getPhysicalAddress());
-                            break;
-                        }
-                    }
-                }
-                // If the Active path from TV's System Audio Mode request does not belong to any
-                // device in the local device list, record the new Active physicalAddress with an
-                // unregistered logical address first. Then query the Active Source again.
-                if (sourcePhysicalAddress != getActiveSource().physicalAddress) {
-                    setActiveSource(Constants.ADDR_UNREGISTERED, sourcePhysicalAddress);
-                    mService.sendCecCommand(
-                        HdmiCecMessageBuilder.buildRequestActiveSource(mAddress));
+            if (HdmiUtils.getLocalPortFromPhysicalAddress(
+                    sourcePhysicalAddress, getDeviceInfo().getPhysicalAddress())
+                            != HdmiUtils.TARGET_NOT_UNDER_LOCAL_DEVICE) {
+                return true;
+            }
+            boolean isDeviceInCecDeviceList = false;
+            for (HdmiDeviceInfo info : HdmiUtils.sparseArrayToList(mDeviceInfos)) {
+                if (info.getPhysicalAddress() == sourcePhysicalAddress) {
+                    isDeviceInCecDeviceList = true;
+                    break;
                 }
             }
-            switchInputOnReceivingNewActivePath(sourcePhysicalAddress);
+            if (!isDeviceInCecDeviceList) {
+                switchInputOnReceivingNewActivePath(sourcePhysicalAddress);
+            }
         }
         return true;
     }
diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java
index 3856de4..1794df3 100644
--- a/services/core/java/com/android/server/hdmi/HdmiControlService.java
+++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java
@@ -56,8 +56,8 @@
 import android.media.tv.TvInputManager;
 import android.media.tv.TvInputManager.TvInputCallback;
 import android.net.Uri;
-import android.os.Build;
 import android.os.Binder;
+import android.os.Build;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.IBinder;
@@ -68,6 +68,7 @@
 import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.provider.Settings.Global;
+import android.sysprop.HdmiProperties;
 import android.text.TextUtils;
 import android.util.ArraySet;
 import android.util.Slog;
@@ -95,6 +96,8 @@
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
 
 /**
  * Provides a service for sending and processing HDMI control messages,
@@ -308,6 +311,11 @@
     private IHdmiControlCallback mDisplayStatusCallback = null;
 
     @Nullable
+    // Save callback when the device is still under logcial address allocation
+    // Invoke once new local device is ready.
+    private IHdmiControlCallback mOtpCallbackPendingAddressAllocation = null;
+
+    @Nullable
     private HdmiCecController mCecController;
 
     // HDMI port information. Stored in the unmodifiable list to keep the static information
@@ -452,7 +460,14 @@
 
     public HdmiControlService(Context context) {
         super(context);
-        mLocalDevices = getIntList(SystemProperties.get(Constants.PROPERTY_DEVICE_TYPE));
+        List<Integer> deviceTypes = HdmiProperties.device_type();
+        if (deviceTypes.contains(null)) {
+            Slog.w(TAG, "Error parsing ro.hdmi.device.type: " + SystemProperties.get(
+                    "ro.hdmi.device_type"));
+            deviceTypes = deviceTypes.stream().filter(Objects::nonNull).collect(
+                    Collectors.toList());
+        }
+        mLocalDevices = deviceTypes;
         mSettingsObserver = new SettingsObserver(mHandler);
     }
 
@@ -775,17 +790,21 @@
                     // Address allocation completed for all devices. Notify each device.
                     if (allocatingDevices.size() == ++finished[0]) {
                         mAddressAllocated = true;
-                        // Reinvoke the saved display status callback once the local device is ready.
-                        if (mDisplayStatusCallback != null) {
-                            queryDisplayStatus(mDisplayStatusCallback);
-                            mDisplayStatusCallback = null;
-                        }
                         if (initiatedBy != INITIATED_BY_HOTPLUG) {
                             // In case of the hotplug we don't call onInitializeCecComplete()
                             // since we reallocate the logical address only.
                             onInitializeCecComplete(initiatedBy);
                         }
                         notifyAddressAllocated(allocatedDevices, initiatedBy);
+                        // Reinvoke the saved display status callback once the local device is ready.
+                        if (mDisplayStatusCallback != null) {
+                            queryDisplayStatus(mDisplayStatusCallback);
+                            mDisplayStatusCallback = null;
+                        }
+                        if (mOtpCallbackPendingAddressAllocation != null) {
+                            oneTouchPlay(mOtpCallbackPendingAddressAllocation);
+                            mOtpCallbackPendingAddressAllocation = null;
+                        }
                         mCecMessageBuffer.processMessages();
                     }
                 }
@@ -2236,8 +2255,16 @@
     }
 
     @ServiceThreadOnly
-    private void oneTouchPlay(final IHdmiControlCallback callback) {
+    @VisibleForTesting
+    protected void oneTouchPlay(final IHdmiControlCallback callback) {
         assertRunOnServiceThread();
+        if (!mAddressAllocated) {
+            mOtpCallbackPendingAddressAllocation = callback;
+            Slog.d(TAG, "Local device is under address allocation. "
+                        + "Save OTP callback for later process.");
+            return;
+        }
+
         HdmiCecLocalDeviceSource source = playback();
         if (source == null) {
             source = audioSystem();
diff --git a/services/core/java/com/android/server/hdmi/OneTouchPlayAction.java b/services/core/java/com/android/server/hdmi/OneTouchPlayAction.java
index c8fc5fc..4962af1 100644
--- a/services/core/java/com/android/server/hdmi/OneTouchPlayAction.java
+++ b/services/core/java/com/android/server/hdmi/OneTouchPlayAction.java
@@ -77,7 +77,6 @@
         sendCommand(HdmiCecMessageBuilder.buildTextViewOn(getSourceAddress(), mTargetAddress));
         broadcastActiveSource();
         queryDevicePowerStatus();
-        mState = STATE_WAITING_FOR_REPORT_POWER_STATUS;
         addTimer(mState, HdmiConfig.TIMEOUT_MS);
         return true;
     }
@@ -99,6 +98,7 @@
     }
 
     private void queryDevicePowerStatus() {
+        mState = STATE_WAITING_FOR_REPORT_POWER_STATUS;
         sendCommand(HdmiCecMessageBuilder.buildGiveDevicePowerStatus(getSourceAddress(),
                 mTargetAddress));
     }
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 75b9705..7e6e668 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -47,6 +47,7 @@
 import android.hardware.input.InputManagerInternal;
 import android.hardware.input.KeyboardLayout;
 import android.hardware.input.TouchCalibration;
+import android.media.AudioManager;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.Environment;
@@ -220,6 +221,8 @@
     private static native void nativeSetFocusedApplication(long ptr,
             int displayId, InputApplicationHandle application);
     private static native void nativeSetFocusedDisplay(long ptr, int displayId);
+    private static native boolean nativeTransferTouchFocus(long ptr,
+            InputChannel fromChannel, InputChannel toChannel);
     private static native void nativeSetPointerSpeed(long ptr, int speed);
     private static native void nativeSetShowTouches(long ptr, boolean enabled);
     private static native void nativeSetInteractive(long ptr, boolean interactive);
@@ -294,6 +297,9 @@
     /** Switch code: Camera lens cover. When set the lens is covered. */
     public static final int SW_CAMERA_LENS_COVER = 0x09;
 
+    /** Switch code: Microphone. When set it is off. */
+    public static final int SW_MUTE_DEVICE = 0x0e;
+
     public static final int SW_LID_BIT = 1 << SW_LID;
     public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
     public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
@@ -304,6 +310,7 @@
     public static final int SW_JACK_BITS =
             SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
     public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
+    public static final int SW_MUTE_DEVICE_BIT = 1 << SW_MUTE_DEVICE;
 
     /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
     final boolean mUseDevInputEventForAudioJack;
@@ -970,6 +977,11 @@
     }
 
     @Override // Binder call
+    public int isMicMuted() {
+        return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_MUTE_DEVICE);
+    }
+
+    @Override // Binder call
     public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
         if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
                 "registerTabletModeChangedListener()")) {
@@ -1533,6 +1545,29 @@
         nativeSetSystemUiVisibility(mPtr, visibility);
     }
 
+    /**
+     * Atomically transfers touch focus from one window to another as identified by
+     * their input channels.  It is possible for multiple windows to have
+     * touch focus if they support split touch dispatch
+     * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
+     * method only transfers touch focus of the specified window without affecting
+     * other windows that may also have touch focus at the same time.
+     * @param fromChannel The channel of a window that currently has touch focus.
+     * @param toChannel The channel of the window that should receive touch focus in
+     * place of the first.
+     * @return True if the transfer was successful.  False if the window with the
+     * specified channel did not actually have touch focus at the time of the request.
+     */
+    public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
+        if (fromChannel == null) {
+            throw new IllegalArgumentException("fromChannel must not be null.");
+        }
+        if (toChannel == null) {
+            throw new IllegalArgumentException("toChannel must not be null.");
+        }
+        return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
+    }
+
     @Override // Binder call
     public void tryPointerSpeed(int speed) {
         if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
@@ -1779,6 +1814,12 @@
             mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
                     args).sendToTarget();
         }
+
+        if ((switchMask & SW_MUTE_DEVICE_BIT) != 0) {
+            final boolean micMute = ((switchValues & SW_MUTE_DEVICE_BIT) != 0);
+            AudioManager audioManager = mContext.getSystemService(AudioManager.class);
+            audioManager.setMicrophoneMuteFromSwitch(micMute);
+        }
     }
 
     // Native callback.
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index f20003a..b7fcd3f 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -3569,9 +3569,15 @@
             if (!calledWithValidTokenLocked(token)) {
                 return;
             }
-            if (mCurClient != null && mCurClient.client != null) {
-                executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
-                        MSG_APPLY_IME_VISIBILITY, setVisible ? 1 : 0, mCurClient));
+            if (!setVisible) {
+                // Client hides the IME directly.
+                if (mCurClient != null && mCurClient.client != null) {
+                    executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
+                            MSG_APPLY_IME_VISIBILITY, setVisible ? 1 : 0, mCurClient));
+                }
+            } else {
+                // Send to window manager to show IME after IME layout finishes.
+                mWindowManagerInternal.showImePostLayout(mLastImeTargetWindow);
             }
         }
     }
diff --git a/services/core/java/com/android/server/integrity/OWNERS b/services/core/java/com/android/server/integrity/OWNERS
new file mode 100644
index 0000000..019aa4f
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/OWNERS
@@ -0,0 +1,6 @@
+omernebil@google.com
+khelmy@google.com
+mdchurchill@google.com
+sturla@google.com
+songpan@google.com
+bjy@google.com
diff --git a/services/core/java/com/android/server/integrity/TEST_MAPPING b/services/core/java/com/android/server/integrity/TEST_MAPPING
new file mode 100644
index 0000000..b45b4ea
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/TEST_MAPPING
@@ -0,0 +1,18 @@
+{
+  "presubmit": [
+    {
+      "name": "FrameworksServicesTests",
+      "options": [
+        {
+          "include-filter": "com.android.server.integrity."
+        },
+        {
+          "include-annotation": "android.platform.test.annotations.Presubmit"
+        },
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        }
+      ]
+    }
+  ]
+}
diff --git a/services/core/java/com/android/server/integrity/engine/RuleEvaluationEngine.java b/services/core/java/com/android/server/integrity/engine/RuleEvaluationEngine.java
new file mode 100644
index 0000000..fc44306
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/engine/RuleEvaluationEngine.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2019 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.integrity.engine;
+
+import com.android.server.integrity.model.Rule;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * The engine used to evaluate rules against app installs.
+ *
+ * <p>Every app install is evaluated against rules (pushed by the verifier) by the evaluation engine
+ * to allow/block that install.
+ */
+public final class RuleEvaluationEngine {
+    private static final String TAG = "RuleEvaluation";
+
+    // The engine for loading rules, retrieving metadata for app installs, and evaluating app
+    // installs against rules.
+    private static RuleEvaluationEngine sRuleEvaluationEngine;
+
+    // The subset of rules loaded to be used to evaluate an app install request.
+    // TODO: Load rules relevant to app installs.
+    private List<Rule> mRules;
+
+    private RuleEvaluationEngine() {
+        // Initialize rules with the empty rule set.
+        mRules = new ArrayList<>();
+    }
+
+    /**
+     * Provide a singleton instance of the rule evaluation engine.
+     */
+    public static synchronized RuleEvaluationEngine getRuleEvaluationEngine() {
+        if (sRuleEvaluationEngine == null) {
+            return new RuleEvaluationEngine();
+        }
+        return sRuleEvaluationEngine;
+    }
+}
diff --git a/services/core/java/com/android/server/integrity/engine/RuleLoader.java b/services/core/java/com/android/server/integrity/engine/RuleLoader.java
new file mode 100644
index 0000000..af24d7a
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/engine/RuleLoader.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2019 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.integrity.engine;
+
+import com.android.server.integrity.model.Rule;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A helper class for loading rules to the rule evaluation engine.
+ *
+ * <p>Expose fine-grained APIs for loading rules to be passed to the rule evaluation engine.
+ *
+ * <p>It supports:
+ * <ul>
+ *     <li>Loading rules based on some keys, such as PACKAGE_NAME and APP_CERT.</li>
+ * </ul>
+ *
+ * <p>It does NOT support:
+ * <ul>
+ *     <li>Loading the list of all rules.</li>
+ *     <li>Merging rules resulting from different APIs.</li>
+ * </ul>
+ */
+final class RuleLoader {
+
+    List<Rule> loadRulesByPackageName(String packageName) {
+        // TODO: Add logic based on rule storage.
+        return new ArrayList<>();
+    }
+
+    List<Rule> loadRulesByAppCertificate(String appCertificate) {
+        // TODO: Add logic based on rule storage.
+        return new ArrayList<>();
+    }
+
+    List<Rule> loadRulesByInstallerName(String installerName) {
+        // TODO: Add logic based on rule storage.
+        return new ArrayList<>();
+    }
+
+    List<Rule> loadRulesByInstallerCertificate(String installerCertificate) {
+        // TODO: Add logic based on rule storage.
+        return new ArrayList<>();
+    }
+}
diff --git a/services/core/java/com/android/server/integrity/model/AppInstallMetadata.java b/services/core/java/com/android/server/integrity/model/AppInstallMetadata.java
new file mode 100644
index 0000000..660bd2e
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/model/AppInstallMetadata.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import android.annotation.Nullable;
+
+/**
+ * The app install metadata.
+ *
+ * <p>The integrity component retrieves metadata for app installs from package manager, passing it
+ * to the rule evaluation engine to evaluate the metadata against the rules.
+ *
+ * <p>Instances of this class are immutable.
+ */
+public final class AppInstallMetadata {
+    private final String mPackageName;
+    // Raw string encoding for the SHA-256 hash of the certificate of the app.
+    private final String mAppCertificate;
+    private final String mInstallerName;
+    // Raw string encoding for the SHA-256 hash of the certificate of the installer.
+    private final String mInstallerCertificate;
+    private final int mVersionCode;
+    private final boolean mIsPreInstalled;
+
+    private AppInstallMetadata(Builder builder) {
+        this.mPackageName = builder.mPackageName;
+        this.mAppCertificate = builder.mAppCertificate;
+        this.mInstallerName = builder.mInstallerName;
+        this.mInstallerCertificate = builder.mInstallerCertificate;
+        this.mVersionCode = builder.mVersionCode;
+        this.mIsPreInstalled = builder.mIsPreInstalled;
+    }
+
+    public String getPackageName() {
+        return mPackageName;
+    }
+
+    public String getAppCertificate() {
+        return mAppCertificate;
+    }
+
+    @Nullable
+    public String getInstallerName() {
+        return mInstallerName;
+    }
+
+    @Nullable
+    public String getInstallerCertificate() {
+        return mInstallerCertificate;
+    }
+
+    /**
+     * @see AppInstallMetadata.Builder#setVersionCode(int)
+     */
+    public int getVersionCode() {
+        return mVersionCode;
+    }
+
+    /**
+     * @see AppInstallMetadata.Builder#setIsPreInstalled(boolean)
+     */
+    public boolean isPreInstalled() {
+        return mIsPreInstalled;
+    }
+
+    /**
+     * Builder class for constructing {@link AppInstallMetadata} objects.
+     */
+    public static final class Builder {
+        private String mPackageName;
+        private String mAppCertificate;
+        private String mInstallerName;
+        private String mInstallerCertificate;
+        private int mVersionCode;
+        private boolean mIsPreInstalled;
+
+        /**
+         * Set package name of the app to be installed.
+         *
+         * @see AppInstallMetadata#getPackageName()
+         */
+        public Builder setPackageName(String packageName) {
+            this.mPackageName = checkNotNull(packageName);
+            return this;
+        }
+
+        /**
+         * Set certificate of the app to be installed.
+         *
+         * <p>It is represented as the raw string encoding for the SHA-256 hash of the certificate
+         * of the app.
+         *
+         * @see AppInstallMetadata#getAppCertificate()
+         */
+        public Builder setAppCertificate(String appCertificate) {
+            this.mAppCertificate = checkNotNull(appCertificate);
+            return this;
+        }
+
+        /**
+         * Set name of the installer installing the app.
+         *
+         * @see AppInstallMetadata#getInstallerName()
+         */
+        public Builder setInstallerName(String installerName) {
+            this.mInstallerName = checkNotNull(installerName);
+            return this;
+        }
+
+        /**
+         * Set certificate of the installer installing the app.
+         *
+         * <p>It is represented as the raw string encoding for the SHA-256 hash of the certificate
+         * of the installer.
+         *
+         * @see AppInstallMetadata#getInstallerCertificate()
+         */
+        public Builder setInstallerCertificate(String installerCertificate) {
+            this.mInstallerCertificate = checkNotNull(installerCertificate);
+            return this;
+        }
+
+        /**
+         * Set version code of the app to be installed.
+         *
+         * @see AppInstallMetadata#getVersionCode()
+         */
+        public Builder setVersionCode(int versionCode) {
+            this.mVersionCode = versionCode;
+            return this;
+        }
+
+        /**
+         * Set whether the app is pre-installed on the device or not.
+         *
+         * @see AppInstallMetadata#isPreInstalled()
+         */
+        public Builder setIsPreInstalled(boolean isPreInstalled) {
+            this.mIsPreInstalled = isPreInstalled;
+            return this;
+        }
+
+        /**
+         * Build {@link AppInstallMetadata}.
+         */
+        public AppInstallMetadata build() {
+            checkArgument(mPackageName != null);
+            checkArgument(mAppCertificate != null);
+            return new AppInstallMetadata(this);
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/integrity/model/AtomicFormula.java b/services/core/java/com/android/server/integrity/model/AtomicFormula.java
new file mode 100644
index 0000000..a9cc62a4da
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/model/AtomicFormula.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import android.annotation.Nullable;
+
+/**
+ * Represents a simple formula consisting of an app install metadata field and a value.
+ *
+ * <p>Instances of this class are immutable.
+ */
+public final class AtomicFormula extends Formula {
+
+    enum Key {
+        PACKAGE_NAME,
+        APP_CERTIFICATE,
+        INSTALLER_NAME,
+        INSTALLER_CERTIFICATE,
+        VERSION_CODE,
+        PRE_INSTALLED
+    }
+
+    enum Operator {
+        EQ,
+        LT,
+        LE,
+        GT,
+        GE
+    }
+
+    private final Key mKey;
+    private final Operator mOperator;
+
+    // The value of a key can take either 1 of 3 forms: String, Integer, or Boolean.
+    // It cannot have multiple values.
+    @Nullable
+    private final String mStringValue;
+    @Nullable
+    private final Integer mIntValue;
+    @Nullable
+    private final Boolean mBoolValue;
+
+    public AtomicFormula(Key key, Operator operator, String stringValue) {
+        validateOperator(key, operator);
+        checkArgument(
+                key == Key.PACKAGE_NAME || key == Key.APP_CERTIFICATE || key == Key.INSTALLER_NAME
+                        || key == Key.INSTALLER_CERTIFICATE,
+                String.format("Key %s cannot have string value", key));
+        this.mKey = checkNotNull(key);
+        this.mOperator = checkNotNull(operator);
+        this.mStringValue = checkNotNull(stringValue);
+        this.mIntValue = null;
+        this.mBoolValue = null;
+    }
+
+    public AtomicFormula(Key key, Operator operator, Integer intValue) {
+        validateOperator(key, operator);
+        checkArgument(key == Key.VERSION_CODE,
+                String.format("Key %s cannot have integer value", key));
+        this.mKey = checkNotNull(key);
+        this.mOperator = checkNotNull(operator);
+        this.mStringValue = null;
+        this.mIntValue = checkNotNull(intValue);
+        this.mBoolValue = null;
+    }
+
+    public AtomicFormula(Key key, Operator operator, Boolean boolValue) {
+        validateOperator(key, operator);
+        checkArgument(key == Key.PRE_INSTALLED,
+                String.format("Key %s cannot have boolean value", key));
+        this.mKey = checkNotNull(key);
+        this.mOperator = checkNotNull(operator);
+        this.mStringValue = null;
+        this.mIntValue = null;
+        this.mBoolValue = checkNotNull(boolValue);
+    }
+
+    public Key getKey() {
+        return mKey;
+    }
+
+    public Operator getOperator() {
+        return mOperator;
+    }
+
+    public String getStringValue() {
+        return mStringValue;
+    }
+
+    public Integer getIntValue() {
+        return mIntValue;
+    }
+
+    public Boolean getBoolValue() {
+        return mBoolValue;
+    }
+
+    private void validateOperator(Key key, Operator operator) {
+        boolean validOperator;
+        switch (key) {
+            case PACKAGE_NAME:
+            case APP_CERTIFICATE:
+            case INSTALLER_NAME:
+            case INSTALLER_CERTIFICATE:
+            case PRE_INSTALLED:
+                validOperator = (operator == Operator.EQ);
+                break;
+            case VERSION_CODE:
+                validOperator = true;
+                break;
+            default:
+                validOperator = false;
+        }
+        if (!validOperator) {
+            throw new IllegalArgumentException(
+                    String.format("Invalid operator %s used for key %s", operator, key));
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/integrity/model/EvaluationOutcome.java b/services/core/java/com/android/server/integrity/model/EvaluationOutcome.java
new file mode 100644
index 0000000..dc30dc3
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/model/EvaluationOutcome.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+/**
+ * A class encapsulating the result from the evaluation engine after evaluating rules against app
+ * install metadata.
+ *
+ * <p>It contains the outcome effect (whether to allow or block the install), and the rule causing
+ * that effect.
+ */
+public final class EvaluationOutcome {
+
+    public enum Effect {
+        ALLOW,
+        DENY
+    }
+
+    private final Effect mEffect;
+    private final Rule mRule;
+
+    private EvaluationOutcome(Effect effect, Rule rule) {
+        this.mEffect = effect;
+        this.mRule = rule;
+    }
+
+    public Effect getEffect() {
+        return mEffect;
+    }
+
+    public Rule getRule() {
+        return mRule;
+    }
+
+    /**
+     * Create an ALLOW evaluation outcome.
+     *
+     * @return An evaluation outcome with ALLOW effect and empty rule.
+     */
+    public static EvaluationOutcome allow() {
+        return new EvaluationOutcome(Effect.ALLOW, Rule.EMPTY);
+    }
+
+    /**
+     * Create a DENY evaluation outcome.
+     *
+     * @param rule Rule causing the DENY effect.
+     * @return An evaluation outcome with DENY effect and rule causing that effect.
+     */
+    public static EvaluationOutcome deny(Rule rule) {
+        return new EvaluationOutcome(Effect.DENY, rule);
+    }
+}
diff --git a/services/core/java/com/android/server/integrity/model/Formula.java b/services/core/java/com/android/server/integrity/model/Formula.java
new file mode 100644
index 0000000..4cfa2c7
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/model/Formula.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+/**
+ * Represents a rule logic/content.
+ */
+abstract class Formula {
+
+}
diff --git a/services/core/java/com/android/server/integrity/model/OpenFormula.java b/services/core/java/com/android/server/integrity/model/OpenFormula.java
new file mode 100644
index 0000000..e9fa1a3
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/model/OpenFormula.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+import static com.android.internal.util.Preconditions.checkArgument;
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Represents a complex formula consisting of other simple and complex formulas.
+ *
+ * <p>Instances of this class are immutable.
+ */
+public final class OpenFormula extends Formula {
+
+    enum Connector {
+        AND,
+        OR,
+        NOT
+    }
+
+    private final Connector mConnector;
+    private final List<Formula> mFormulas;
+
+    public OpenFormula(Connector connector, List<Formula> formulas) {
+        validateFormulas(connector, formulas);
+        this.mConnector = checkNotNull(connector);
+        this.mFormulas = Collections.unmodifiableList(checkNotNull(formulas));
+    }
+
+    public Connector getConnector() {
+        return mConnector;
+    }
+
+    public List<Formula> getFormulas() {
+        return mFormulas;
+    }
+
+    private void validateFormulas(Connector connector, List<Formula> formulas) {
+        switch (connector) {
+            case AND:
+            case OR:
+                checkArgument(formulas.size() >= 2,
+                        String.format("Connector %s must have at least 2 formulas", connector));
+                break;
+            case NOT:
+                checkArgument(formulas.size() == 1,
+                        String.format("Connector %s must have 1 formula only", connector));
+                break;
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/integrity/model/Rule.java b/services/core/java/com/android/server/integrity/model/Rule.java
new file mode 100644
index 0000000..3d233ab
--- /dev/null
+++ b/services/core/java/com/android/server/integrity/model/Rule.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+import static com.android.internal.util.Preconditions.checkNotNull;
+
+/**
+ * Represent rules to be used in the rule evaluation engine to match against app installs.
+ *
+ * <p>Instances of this class are immutable.
+ */
+public final class Rule {
+
+    public enum Effect {
+        DENY
+    }
+
+    // Holds an empty rule instance.
+    public static final Rule EMPTY = new Rule();
+
+    private final Formula mFormula;
+    private final Effect mEffect;
+
+    private Rule() {
+        this.mFormula = null;
+        this.mEffect = null;
+    }
+
+    public Rule(Formula formula, Effect effect) {
+        this.mFormula = checkNotNull(formula);
+        this.mEffect = checkNotNull(effect);
+    }
+
+    /**
+     * Indicates whether the rule is empty or not.
+     *
+     * @return {@code true} if the rule is empty, and {@code false} otherwise.
+     */
+    public boolean isEmpty() {
+        return mFormula == null && mEffect == null;
+    }
+
+    public Formula getFormula() {
+        return mFormula;
+    }
+
+    public Effect getEffect() {
+        return mEffect;
+    }
+}
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index b7eca29..bad484f 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -44,6 +44,7 @@
 import android.app.PendingIntent;
 import android.app.admin.DevicePolicyManager;
 import android.app.admin.DevicePolicyManagerInternal;
+import android.app.admin.DeviceStateCache;
 import android.app.admin.PasswordMetrics;
 import android.app.backup.BackupManager;
 import android.app.trust.IStrongAuthTracker;
@@ -60,7 +61,10 @@
 import android.database.sqlite.SQLiteDatabase;
 import android.hardware.authsecret.V1_0.IAuthSecret;
 import android.hardware.biometrics.BiometricManager;
+import android.hardware.face.Face;
 import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.Fingerprint;
+import android.hardware.fingerprint.FingerprintManager;
 import android.net.Uri;
 import android.os.Binder;
 import android.os.Bundle;
@@ -76,6 +80,7 @@
 import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.os.UserManagerInternal;
 import android.os.storage.IStorageManager;
 import android.os.storage.StorageManager;
 import android.provider.Settings;
@@ -115,6 +120,7 @@
 import com.android.internal.widget.LockSettingsInternal;
 import com.android.internal.widget.VerifyCredentialResponse;
 import com.android.server.LocalServices;
+import com.android.server.ServiceThread;
 import com.android.server.SystemService;
 import com.android.server.locksettings.LockSettingsStorage.CredentialHash;
 import com.android.server.locksettings.LockSettingsStorage.PersistentData;
@@ -385,8 +391,15 @@
             return mContext;
         }
 
-        public Handler getHandler() {
-            return new Handler();
+        public ServiceThread getServiceThread() {
+            ServiceThread handlerThread = new ServiceThread(TAG, Process.THREAD_PRIORITY_BACKGROUND,
+                    true /*allowIo*/);
+            handlerThread.start();
+            return handlerThread;
+        }
+
+        public Handler getHandler(ServiceThread handlerThread) {
+            return new Handler(handlerThread.getLooper());
         }
 
         public LockSettingsStorage getStorage() {
@@ -429,6 +442,10 @@
             return (UserManager) mContext.getSystemService(Context.USER_SERVICE);
         }
 
+        public UserManagerInternal getUserManagerInternal() {
+            return LocalServices.getService(UserManagerInternal.class);
+        }
+
         /**
          * Return the {@link DevicePolicyManager} object.
          *
@@ -440,6 +457,10 @@
             return (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
         }
 
+        public DeviceStateCache getDeviceStateCache() {
+            return DeviceStateCache.getInstance();
+        }
+
         public KeyStore getKeyStore() {
             return KeyStore.getInstance();
         }
@@ -473,6 +494,23 @@
         public boolean isGsiRunning() {
             return SystemProperties.getInt(GSI_RUNNING_PROP, 0) > 0;
         }
+
+        public FingerprintManager getFingerprintManager() {
+            if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
+                return (FingerprintManager) mContext.getSystemService(Context.FINGERPRINT_SERVICE);
+            } else {
+                return null;
+            }
+        }
+
+        public FaceManager getFaceManager() {
+            if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
+                return (FaceManager) mContext.getSystemService(Context.FACE_SERVICE);
+            } else {
+                return null;
+            }
+        }
+
     }
 
     public LockSettingsService(Context context) {
@@ -485,7 +523,7 @@
         mContext = injector.getContext();
         mKeyStore = injector.getKeyStore();
         mRecoverableKeyStoreManager = injector.getRecoverableKeyStoreManager(mKeyStore);
-        mHandler = injector.getHandler();
+        mHandler = injector.getHandler(injector.getServiceThread());
         mStrongAuth = injector.getStrongAuth();
         mActivityManager = injector.getActivityManager();
 
@@ -1023,11 +1061,16 @@
     }
 
     private void notifySeparateProfileChallengeChanged(int userId) {
-        final DevicePolicyManagerInternal dpmi = LocalServices.getService(
-                DevicePolicyManagerInternal.class);
-        if (dpmi != null) {
-            dpmi.reportSeparateProfileChallengeChanged(userId);
-        }
+        // LSS cannot call into DPM directly, otherwise it will cause deadlock.
+        // In this case, calling DPM on a handler thread is OK since DPM doesn't
+        // expect reportSeparateProfileChallengeChanged() to happen synchronously.
+        mHandler.post(() -> {
+            final DevicePolicyManagerInternal dpmi = LocalServices.getService(
+                    DevicePolicyManagerInternal.class);
+            if (dpmi != null) {
+                dpmi.reportSeparateProfileChallengeChanged(userId);
+            }
+        });
     }
 
     @Override
@@ -2038,7 +2081,6 @@
      * reporting the password changed.
      */
     private void notifyPasswordChanged(@UserIdInt int userId) {
-        // Same handler as notifyActivePasswordMetricsAvailable to ensure correct ordering
         mHandler.post(() -> {
             mInjector.getDevicePolicyManager().reportPasswordChanged(userId);
             LocalServices.getService(WindowManagerInternal.class).reportPasswordChanged(userId);
@@ -2699,6 +2741,7 @@
             fixateNewestUserKeyAuth(userId);
             unlockKeystore(auth.deriveKeyStorePassword(), userId);
             setKeystorePassword(null, userId);
+            removeBiometricsForUser(userId);
         }
         setSyntheticPasswordHandleLocked(newHandle, userId);
         synchronizeUnifiedWorkChallengeForProfiles(userId, profilePasswords);
@@ -2714,6 +2757,85 @@
         return newHandle;
     }
 
+    private void removeBiometricsForUser(int userId) {
+        removeAllFingerprintForUser(userId);
+        removeAllFaceForUser(userId);
+    }
+
+    private void removeAllFingerprintForUser(final int userId) {
+        FingerprintManager mFingerprintManager = mInjector.getFingerprintManager();
+        if (mFingerprintManager != null && mFingerprintManager.isHardwareDetected()) {
+            if (mFingerprintManager.hasEnrolledFingerprints(userId)) {
+                mFingerprintManager.setActiveUser(userId);
+                CountDownLatch latch = new CountDownLatch(1);
+                // For the purposes of M and N, groupId is the same as userId.
+                Fingerprint finger = new Fingerprint(null, userId, 0, 0);
+                mFingerprintManager.remove(finger, userId,
+                        fingerprintManagerRemovalCallback(latch));
+                try {
+                    latch.await(10000, TimeUnit.MILLISECONDS);
+                } catch (InterruptedException e) {
+                    Slog.e(TAG, "Latch interrupted when removing fingerprint", e);
+                }
+            }
+        }
+    }
+
+    private void removeAllFaceForUser(final int userId) {
+        FaceManager mFaceManager = mInjector.getFaceManager();
+        if (mFaceManager != null && mFaceManager.isHardwareDetected()) {
+            if (mFaceManager.hasEnrolledTemplates(userId)) {
+                mFaceManager.setActiveUser(userId);
+                CountDownLatch latch = new CountDownLatch(1);
+                Face face = new Face(null, 0, 0);
+                mFaceManager.remove(face, userId, faceManagerRemovalCallback(latch));
+                try {
+                    latch.await(10000, TimeUnit.MILLISECONDS);
+                } catch (InterruptedException e) {
+                    Slog.e(TAG, "Latch interrupted when removing face", e);
+                }
+            }
+        }
+    }
+
+    private FingerprintManager.RemovalCallback fingerprintManagerRemovalCallback(
+            CountDownLatch latch) {
+        return new FingerprintManager.RemovalCallback() {
+            @Override
+            public void onRemovalError(Fingerprint fp, int errMsgId, CharSequence err) {
+                Slog.e(TAG, String.format(
+                        "Can't remove fingerprint %d in group %d. Reason: %s",
+                        fp.getBiometricId(), fp.getGroupId(), err));
+                latch.countDown();
+            }
+
+            @Override
+            public void onRemovalSucceeded(Fingerprint fp, int remaining) {
+                if (remaining == 0) {
+                    latch.countDown();
+                }
+            }
+        };
+    }
+
+    private FaceManager.RemovalCallback faceManagerRemovalCallback(CountDownLatch latch) {
+        return new FaceManager.RemovalCallback() {
+            @Override
+            public void onRemovalError(Face face, int errMsgId, CharSequence err) {
+                Slog.e(TAG, String.format("Can't remove face %d. Reason: %s",
+                        face.getBiometricId(), err));
+                latch.countDown();
+            }
+
+            @Override
+            public void onRemovalSucceeded(Face face, int remaining) {
+                if (remaining == 0) {
+                    latch.countDown();
+                }
+            }
+        };
+    }
+
     @GuardedBy("mSpManager")
     private boolean spBasedSetLockCredentialInternalLocked(byte[] credential, int credentialType,
             byte[] savedCredential, int requestedQuality, int userId,
@@ -3026,45 +3148,43 @@
         pw.decreaseIndent();
     }
 
+    /**
+     * Cryptographically disable escrow token support for the current user, if the user is not
+     * managed (either user has a profile owner, or if device is managed). Do not disable
+     * if we are running an automotive build.
+     */
     private void disableEscrowTokenOnNonManagedDevicesIfNeeded(int userId) {
-        long ident = Binder.clearCallingIdentity();
-        try {
-            // Managed profile should have escrow enabled
-            if (mUserManager.getUserInfo(userId).isManagedProfile()) {
-                Slog.i(TAG, "Managed profile can have escrow token");
-                return;
-            }
-            DevicePolicyManager dpm = mInjector.getDevicePolicyManager();
-            // Devices with Device Owner should have escrow enabled on all users.
-            if (dpm.getDeviceOwnerComponentOnAnyUser() != null) {
-                Slog.i(TAG, "Corp-owned device can have escrow token");
-                return;
-            }
-            // We could also have a profile owner on the given (non-managed) user for unicorn cases
-            if (dpm.getProfileOwnerAsUser(userId) != null) {
-                Slog.i(TAG, "User with profile owner can have escrow token");
-                return;
-            }
-            // If the device is yet to be provisioned (still in SUW), there is still
-            // a chance that Device Owner will be set on the device later, so postpone
-            // disabling escrow token for now.
-            if (!dpm.isDeviceProvisioned()) {
-                Slog.i(TAG, "Postpone disabling escrow tokens until device is provisioned");
-                return;
-            }
+        final UserManagerInternal userManagerInternal = mInjector.getUserManagerInternal();
 
-            // Escrow tokens are enabled on automotive builds.
-            if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
-                return;
-            }
+        // Managed profile should have escrow enabled
+        if (userManagerInternal.isUserManaged(userId)) {
+            Slog.i(TAG, "Managed profile can have escrow token");
+            return;
+        }
 
-            // Disable escrow token permanently on all other device/user types.
-            Slog.i(TAG, "Disabling escrow token on user " + userId);
-            if (isSyntheticPasswordBasedCredentialLocked(userId)) {
-                mSpManager.destroyEscrowData(userId);
-            }
-        } finally {
-            Binder.restoreCallingIdentity(ident);
+        // Devices with Device Owner should have escrow enabled on all users.
+        if (userManagerInternal.isDeviceManaged()) {
+            Slog.i(TAG, "Corp-owned device can have escrow token");
+            return;
+        }
+
+        // If the device is yet to be provisioned (still in SUW), there is still
+        // a chance that Device Owner will be set on the device later, so postpone
+        // disabling escrow token for now.
+        if (!mInjector.getDeviceStateCache().isDeviceProvisioned()) {
+            Slog.i(TAG, "Postpone disabling escrow tokens until device is provisioned");
+            return;
+        }
+
+        // Escrow tokens are enabled on automotive builds.
+        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            return;
+        }
+
+        // Disable escrow token permanently on all other device/user types.
+        Slog.i(TAG, "Disabling escrow token on user " + userId);
+        if (isSyntheticPasswordBasedCredentialLocked(userId)) {
+            mSpManager.destroyEscrowData(userId);
         }
     }
 
diff --git a/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java b/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java
index ea0fb47..9246311 100644
--- a/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java
+++ b/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java
@@ -129,6 +129,9 @@
             keyStore.load(null);
 
             SecretKey decryptionKey = (SecretKey) keyStore.getKey(keyAlias, null);
+            if (decryptionKey == null) {
+                throw new IllegalStateException("SP key is missing: " + keyAlias);
+            }
             byte[] intermediate = decrypt(applicationId, APPLICATION_ID_PERSONALIZATION, blob);
             return decrypt(decryptionKey, intermediate);
         } catch (Exception e) {
@@ -143,6 +146,9 @@
             keyStore.load(null);
 
             SecretKey decryptionKey = (SecretKey) keyStore.getKey(keyAlias, null);
+            if (decryptionKey == null) {
+                throw new IllegalStateException("SP key is missing: " + keyAlias);
+            }
             byte[] intermediate = decrypt(decryptionKey, blob);
             return decrypt(applicationId, APPLICATION_ID_PERSONALIZATION, intermediate);
         } catch (CertificateException | IOException | BadPaddingException
@@ -193,6 +199,7 @@
             keyStore = KeyStore.getInstance("AndroidKeyStore");
             keyStore.load(null);
             keyStore.deleteEntry(keyAlias);
+            Slog.i(TAG, "SP key deleted: " + keyAlias);
         } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException
                 | IOException e) {
             Slog.e(TAG, "Failed to destroy blob", e);
diff --git a/services/core/java/com/android/server/locksettings/TEST_MAPPING b/services/core/java/com/android/server/locksettings/TEST_MAPPING
index c1cba5f..56f5cc0 100644
--- a/services/core/java/com/android/server/locksettings/TEST_MAPPING
+++ b/services/core/java/com/android/server/locksettings/TEST_MAPPING
@@ -1,5 +1,5 @@
 {
-    "presubmit": [
+    "presubmit-devicepolicy": [
         {
             "name": "CtsDevicePolicyManagerTestCases",
             "options": [
diff --git a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
index 043c834..668f2be 100644
--- a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
+++ b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
@@ -26,6 +26,7 @@
 import android.content.pm.PackageManager;
 import android.media.IMediaRouter2Client;
 import android.media.IMediaRouter2Manager;
+import android.media.IMediaRouterClient;
 import android.media.MediaRoute2Info;
 import android.media.MediaRoute2ProviderInfo;
 import android.os.Binder;
@@ -86,7 +87,7 @@
         final long token = Binder.clearCallingIdentity();
         try {
             synchronized (mLock) {
-                registerClientLocked(client, uid, pid, packageName, userId, trusted);
+                registerClient2Locked(client, uid, pid, packageName, userId, trusted);
             }
         } finally {
             Binder.restoreCallingIdentity(token);
@@ -99,7 +100,7 @@
         final long token = Binder.clearCallingIdentity();
         try {
             synchronized (mLock) {
-                unregisterClientLocked(client, false);
+                unregisterClient2Locked(client, false);
             }
         } finally {
             Binder.restoreCallingIdentity(token);
@@ -155,14 +156,30 @@
         }
     }
 
-    public void setControlCategories(@NonNull IMediaRouter2Client client,
+    //TODO: What would happen if a media app used MediaRouter and MediaRouter2 simultaneously?
+    public void setControlCategories(@NonNull IMediaRouterClient client,
+            @Nullable List<String> categories) {
+        Objects.requireNonNull(client, "client must not be null");
+        final long token = Binder.clearCallingIdentity();
+        try {
+            synchronized (mLock) {
+                ClientRecord clientRecord = mAllClientRecords.get(client.asBinder());
+                setControlCategoriesLocked(clientRecord, categories);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    public void setControlCategories2(@NonNull IMediaRouter2Client client,
             @Nullable List<String> categories) {
         Objects.requireNonNull(client, "client must not be null");
 
         final long token = Binder.clearCallingIdentity();
         try {
             synchronized (mLock) {
-                setControlCategoriesLocked(client, categories);
+                ClientRecord clientRecord = mAllClientRecords.get(client.asBinder());
+                setControlCategoriesLocked(clientRecord, categories);
             }
         } finally {
             Binder.restoreCallingIdentity(token);
@@ -174,7 +191,7 @@
         final long token = Binder.clearCallingIdentity();
         try {
             synchronized (mLock) {
-                selectRoute2Locked(client, route);
+                selectRoute2Locked(mAllClientRecords.get(client.asBinder()), route);
             }
         } finally {
             Binder.restoreCallingIdentity(token);
@@ -193,6 +210,36 @@
         }
     }
 
+    public void registerClient(@NonNull IMediaRouterClient client, @NonNull String packageName) {
+        Objects.requireNonNull(client, "client must not be null");
+
+        final int uid = Binder.getCallingUid();
+        final int pid = Binder.getCallingPid();
+        final int userId = UserHandle.getUserId(uid);
+
+        final long token = Binder.clearCallingIdentity();
+        try {
+            synchronized (mLock) {
+                registerClient1Locked(client, packageName, userId);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    public void unregisterClient(@NonNull IMediaRouterClient client) {
+        Objects.requireNonNull(client, "client must not be null");
+
+        final long token = Binder.clearCallingIdentity();
+        try {
+            synchronized (mLock) {
+                unregisterClient1Locked(client);
+            }
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
     //TODO: Review this is handling multi-user properly.
     void switchUser() {
         synchronized (mLock) {
@@ -217,9 +264,9 @@
         }
     }
 
-    void clientDied(ClientRecord clientRecord) {
+    void clientDied(Client2Record clientRecord) {
         synchronized (mLock) {
-            unregisterClientLocked(clientRecord.mClient, true);
+            unregisterClient2Locked(clientRecord.mClient, true);
         }
     }
 
@@ -229,18 +276,18 @@
         }
     }
 
-    private void registerClientLocked(IMediaRouter2Client client,
+    private void registerClient2Locked(IMediaRouter2Client client,
             int uid, int pid, String packageName, int userId, boolean trusted) {
         final IBinder binder = client.asBinder();
-        ClientRecord clientRecord = mAllClientRecords.get(binder);
-        if (clientRecord == null) {
+        if (mAllClientRecords.get(binder) == null) {
             boolean newUser = false;
             UserRecord userRecord = mUserRecords.get(userId);
             if (userRecord == null) {
                 userRecord = new UserRecord(userId);
                 newUser = true;
             }
-            clientRecord = new ClientRecord(userRecord, client, uid, pid, packageName, trusted);
+            Client2Record clientRecord = new Client2Record(userRecord, client, uid, pid,
+                    packageName, trusted);
             try {
                 binder.linkToDeath(clientRecord, 0);
             } catch (RemoteException ex) {
@@ -261,8 +308,8 @@
         }
     }
 
-    private void unregisterClientLocked(IMediaRouter2Client client, boolean died) {
-        ClientRecord clientRecord = mAllClientRecords.remove(client.asBinder());
+    private void unregisterClient2Locked(IMediaRouter2Client client, boolean died) {
+        Client2Record clientRecord = (Client2Record) mAllClientRecords.remove(client.asBinder());
         if (clientRecord != null) {
             UserRecord userRecord = clientRecord.mUserRecord;
             userRecord.mClientRecords.remove(clientRecord);
@@ -272,8 +319,7 @@
         }
     }
 
-    private void selectRoute2Locked(IMediaRouter2Client client, MediaRoute2Info route) {
-        ClientRecord clientRecord = mAllClientRecords.get(client.asBinder());
+    private void selectRoute2Locked(ClientRecord clientRecord, MediaRoute2Info route) {
         if (clientRecord != null) {
             MediaRoute2Info oldRoute = clientRecord.mSelectedRoute;
             clientRecord.mSelectedRoute = route;
@@ -294,10 +340,7 @@
         }
     }
 
-    private void setControlCategoriesLocked(IMediaRouter2Client client, List<String> categories) {
-        final IBinder binder = client.asBinder();
-        ClientRecord clientRecord = mAllClientRecords.get(binder);
-
+    private void setControlCategoriesLocked(ClientRecord clientRecord, List<String> categories) {
         if (clientRecord != null) {
             clientRecord.mControlCategories = categories;
 
@@ -349,9 +392,7 @@
                     obtainMessage(UserHandler::notifyProviderInfosUpdatedToManager,
                             userRecord.mHandler, manager));
 
-            final int count = userRecord.mClientRecords.size();
-            for (int i = 0; i < count; i++) {
-                ClientRecord clientRecord = userRecord.mClientRecords.get(i);
+            for (ClientRecord clientRecord : userRecord.mClientRecords) {
                 clientRecord.mUserRecord.mHandler.sendMessage(
                         obtainMessage(UserHandler::updateClientUsage,
                             clientRecord.mUserRecord.mHandler, clientRecord));
@@ -378,7 +419,7 @@
                 Slog.w(TAG, "Ignoring route selection for unknown client.");
             }
             if (clientRecord != null && managerRecord.mTrusted) {
-                selectRoute2Locked(clientRecord.mClient, route);
+                selectRoute2Locked(clientRecord, route);
             }
         }
     }
@@ -409,6 +450,37 @@
         }
     }
 
+    private void registerClient1Locked(IMediaRouterClient client, String packageName,
+            int userId) {
+        final IBinder binder = client.asBinder();
+        if (mAllClientRecords.get(binder) == null) {
+            boolean newUser = false;
+            UserRecord userRecord = mUserRecords.get(userId);
+            if (userRecord == null) {
+                userRecord = new UserRecord(userId);
+                newUser = true;
+            }
+            ClientRecord clientRecord = new Client1Record(userRecord, client, packageName);
+
+            if (newUser) {
+                mUserRecords.put(userId, userRecord);
+                initializeUserLocked(userRecord);
+            }
+
+            userRecord.mClientRecords.add(clientRecord);
+            mAllClientRecords.put(binder, clientRecord);
+        }
+    }
+
+    private void unregisterClient1Locked(IMediaRouterClient client) {
+        ClientRecord clientRecord = mAllClientRecords.remove(client.asBinder());
+        if (clientRecord != null) {
+            UserRecord userRecord = clientRecord.mUserRecord;
+            userRecord.mClientRecords.remove(clientRecord);
+            disposeUserIfNeededLocked(userRecord);
+        }
+    }
+
     final class UserRecord {
         public final int mUserId;
         final ArrayList<ClientRecord> mClientRecords = new ArrayList<>();
@@ -430,25 +502,43 @@
         }
     }
 
-    final class ClientRecord implements IBinder.DeathRecipient {
+    class ClientRecord {
         public final UserRecord mUserRecord;
-        public final IMediaRouter2Client mClient;
-        public final int mUid;
-        public final int mPid;
         public final String mPackageName;
-        public final boolean mTrusted;
         public List<String> mControlCategories;
         public MediaRoute2Info mSelectedRoute;
 
-        ClientRecord(UserRecord userRecord, IMediaRouter2Client client,
-                int uid, int pid, String packageName, boolean trusted) {
+        ClientRecord(UserRecord userRecord, String packageName) {
             mUserRecord = userRecord;
+            mPackageName = packageName;
+            mControlCategories = Collections.emptyList();
+        }
+    }
+
+    final class Client1Record extends ClientRecord {
+        public final IMediaRouterClient mClient;
+
+        Client1Record(UserRecord userRecord, IMediaRouterClient client,
+                String packageName) {
+            super(userRecord, packageName);
+            mClient = client;
+        }
+    }
+
+    final class Client2Record extends ClientRecord
+            implements IBinder.DeathRecipient {
+        public final IMediaRouter2Client mClient;
+        public final int mUid;
+        public final int mPid;
+        public final boolean mTrusted;
+
+        Client2Record(UserRecord userRecord, IMediaRouter2Client client,
+                int uid, int pid, String packageName, boolean trusted) {
+            super(userRecord, packageName);
             mClient = client;
             mUid = uid;
             mPid = pid;
-            mPackageName = packageName;
             mTrusted = trusted;
-            mControlCategories = Collections.emptyList();
         }
 
         public void dispose() {
@@ -622,7 +712,9 @@
                     managers.add(managerRecord.mManager);
                 }
                 for (ClientRecord clientRecord : mUserRecord.mClientRecords) {
-                    clients.add(clientRecord.mClient);
+                    if (clientRecord instanceof Client2Record) {
+                        clients.add(((Client2Record) clientRecord).mClient);
+                    }
                 }
             }
             for (IMediaRouter2Manager manager : managers) {
diff --git a/services/core/java/com/android/server/media/MediaRouterService.java b/services/core/java/com/android/server/media/MediaRouterService.java
index 2670cd8..796a25d 100644
--- a/services/core/java/com/android/server/media/MediaRouterService.java
+++ b/services/core/java/com/android/server/media/MediaRouterService.java
@@ -249,6 +249,7 @@
             synchronized (mLock) {
                 registerClientLocked(client, uid, pid, packageName, resolvedUserId, trusted);
             }
+            mService2.registerClient(client, packageName);
         } finally {
             Binder.restoreCallingIdentity(token);
         }
@@ -289,6 +290,7 @@
             synchronized (mLock) {
                 unregisterClientLocked(client, false);
             }
+            mService2.unregisterClient(client);
         } finally {
             Binder.restoreCallingIdentity(token);
         }
@@ -395,6 +397,12 @@
 
     // Binder call
     @Override
+    public void setControlCategories(IMediaRouterClient client, List<String> controlCategories) {
+        mService2.setControlCategories(client, controlCategories);
+    }
+
+    // Binder call
+    @Override
     public void requestUpdateVolume(IMediaRouterClient client, String routeId, int direction) {
         if (client == null) {
             throw new IllegalArgumentException("client must not be null");
@@ -487,8 +495,8 @@
 
     // Binder call
     @Override
-    public void setControlCategories(IMediaRouter2Client client, List<String> categories) {
-        mService2.setControlCategories(client, categories);
+    public void setControlCategories2(IMediaRouter2Client client, List<String> categories) {
+        mService2.setControlCategories2(client, categories);
     }
 
     void restoreBluetoothA2dp() {
@@ -561,6 +569,7 @@
         synchronized (mLock) {
             unregisterClientLocked(clientRecord.mClient, true);
         }
+        mService2.unregisterClient(clientRecord.mClient);
     }
 
     private void registerClientLocked(IMediaRouterClient client,
diff --git a/services/core/java/com/android/server/media/MediaSessionRecord.java b/services/core/java/com/android/server/media/MediaSessionRecord.java
index 248351c..0aee850 100644
--- a/services/core/java/com/android/server/media/MediaSessionRecord.java
+++ b/services/core/java/com/android/server/media/MediaSessionRecord.java
@@ -456,6 +456,7 @@
                 return;
             }
             mDestroyed = true;
+            mPlaybackState = null;
             mHandler.post(MessageHandler.MSG_DESTROYED);
         }
     }
diff --git a/services/core/java/com/android/server/notification/GroupHelper.java b/services/core/java/com/android/server/notification/GroupHelper.java
index b1cd627..9cb8a01 100644
--- a/services/core/java/com/android/server/notification/GroupHelper.java
+++ b/services/core/java/com/android/server/notification/GroupHelper.java
@@ -16,9 +16,13 @@
 package com.android.server.notification;
 
 import android.service.notification.StatusBarNotification;
+import android.util.ArrayMap;
+import android.util.ArraySet;
 import android.util.Log;
 import android.util.Slog;
 
+import com.android.internal.annotations.VisibleForTesting;
+
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedHashSet;
@@ -37,6 +41,11 @@
     private final Callback mCallback;
     private final int mAutoGroupAtCount;
 
+    // count the number of ongoing notifications per group
+    // userId -> (package name -> (group Id -> (set of notification keys)))
+    final ArrayMap<String, ArraySet<String>>
+            mOngoingGroupCount = new ArrayMap<>();
+
     // Map of user : <Map of package : notification keys>. Only contains notifications that are not
     // grouped by the app (aka no group or sort key).
     Map<Integer, Map<String, LinkedHashSet<String>>> mUngroupedNotifications = new HashMap<>();
@@ -46,10 +55,52 @@
         mCallback = callback;
     }
 
+    private String generatePackageGroupKey(int userId, String pkg, String group) {
+        return userId + "|" + pkg + "|" + group;
+    }
+
+    @VisibleForTesting
+    protected int getOngoingGroupCount(int userId, String pkg, String group) {
+        String key = generatePackageGroupKey(userId, pkg, group);
+        return mOngoingGroupCount.getOrDefault(key, new ArraySet<>(0)).size();
+    }
+
+    private void addToOngoingGroupCount(StatusBarNotification sbn, boolean add) {
+        if (sbn.getNotification().isGroupSummary()) return;
+        if (!sbn.isOngoing() && add) return;
+        String group = sbn.getGroup();
+        if (group == null) return;
+        int userId = sbn.getUser().getIdentifier();
+        String key = generatePackageGroupKey(userId, sbn.getPackageName(), group);
+        ArraySet<String> notifications = mOngoingGroupCount.getOrDefault(key, new ArraySet<>(0));
+        if (add) {
+            notifications.add(sbn.getKey());
+            mOngoingGroupCount.put(key, notifications);
+        } else {
+            notifications.remove(sbn.getKey());
+            // we dont need to put it back if it is default
+        }
+        String combinedKey = generatePackageGroupKey(userId, sbn.getPackageName(), group);
+        boolean needsOngoingFlag = notifications.size() > 0;
+        mCallback.updateAutogroupSummary(sbn.getKey(), needsOngoingFlag);
+    }
+
+    public void onNotificationUpdated(StatusBarNotification childSbn,
+            boolean autogroupSummaryExists) {
+        if (childSbn.getGroup() != AUTOGROUP_KEY
+                || childSbn.getNotification().isGroupSummary()) return;
+        if (childSbn.isOngoing()) {
+            addToOngoingGroupCount(childSbn, true);
+        } else {
+            addToOngoingGroupCount(childSbn, false);
+        }
+    }
+
     public void onNotificationPosted(StatusBarNotification sbn, boolean autogroupSummaryExists) {
         if (DEBUG) Log.i(TAG, "POSTED " + sbn.getKey());
         try {
             List<String> notificationsToGroup = new ArrayList<>();
+            if (autogroupSummaryExists) addToOngoingGroupCount(sbn, true);
             if (!sbn.isAppGroup()) {
                 // Not grouped by the app, add to the list of notifications for the app;
                 // send grouping update if app exceeds the autogrouping limit.
@@ -90,6 +141,7 @@
 
     public void onNotificationRemoved(StatusBarNotification sbn) {
         try {
+            addToOngoingGroupCount(sbn, false);
             maybeUngroup(sbn, true, sbn.getUserId());
         } catch (Exception e) {
             Slog.e(TAG, "Error processing canceled notification", e);
@@ -159,5 +211,6 @@
         void removeAutoGroup(String key);
         void addAutoGroupSummary(int userId, String pkg, String triggeringKey);
         void removeAutoGroupSummary(int user, String pkg);
+        void updateAutogroupSummary(String key, boolean needsOngoingFlag);
     }
 }
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index 48b0fd6..8560ae6 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -185,7 +185,7 @@
     }
 
     protected void addDefaultComponentOrPackage(String packageOrComponent) {
-        if (packageOrComponent != null) {
+        if (!TextUtils.isEmpty(packageOrComponent)) {
             synchronized (mDefaultsLock) {
                 ComponentName cn = ComponentName.unflattenFromString(packageOrComponent);
                 if (cn == null) {
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
old mode 100644
new mode 100755
index d480cb6e..d7efa1b
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -94,7 +94,6 @@
 import static com.android.server.am.PendingIntentRecord.FLAG_ACTIVITY_SENDER;
 import static com.android.server.am.PendingIntentRecord.FLAG_BROADCAST_SENDER;
 import static com.android.server.am.PendingIntentRecord.FLAG_SERVICE_SENDER;
-import static com.android.server.notification.PreferencesHelper.DEFAULT_ALLOW_BUBBLE;
 import static com.android.server.utils.PriorityDump.PRIORITY_ARG;
 import static com.android.server.utils.PriorityDump.PRIORITY_ARG_CRITICAL;
 import static com.android.server.utils.PriorityDump.PRIORITY_ARG_NORMAL;
@@ -523,7 +522,6 @@
 
     }
 
-
     void loadDefaultApprovedServices(int userId) {
         String defaultListenerAccess = getContext().getResources().getString(
                 com.android.internal.R.string.config_defaultListenerAccessPackages);
@@ -531,6 +529,9 @@
             String[] listeners =
                     defaultListenerAccess.split(ManagedServices.ENABLED_SERVICES_SEPARATOR);
             for (int i = 0; i < listeners.length; i++) {
+                if (TextUtils.isEmpty(listeners[i])) {
+                    continue;
+                }
                 ArraySet<ComponentName> approvedListeners =
                         mListeners.queryPackageForServices(listeners[i],
                                 MATCH_DIRECT_BOOT_AWARE
@@ -547,6 +548,9 @@
         if (defaultDndAccess != null) {
             String[] dnds = defaultDndAccess.split(ManagedServices.ENABLED_SERVICES_SEPARATOR);
             for (int i = 0; i < dnds.length; i++) {
+                if (TextUtils.isEmpty(dnds[i])) {
+                    continue;
+                }
                 mConditionProviders.addDefaultComponentOrPackage(dnds[i]);
             }
         }
@@ -565,12 +569,14 @@
                 .split(ManagedServices.ENABLED_SERVICES_SEPARATOR)));
         for (int i = 0; i < assistants.size(); i++) {
             String cnString = assistants.valueAt(i);
+            if (TextUtils.isEmpty(cnString)) {
+                continue;
+            }
             mAssistants.addDefaultComponentOrPackage(cnString);
         }
     }
 
     protected void allowDefaultApprovedServices(int userId) {
-
         ArraySet<ComponentName> defaultListeners = mListeners.getDefaultComponents();
         for (int i = 0; i < defaultListeners.size(); i++) {
             ComponentName cn = defaultListeners.valueAt(i);
@@ -595,6 +601,40 @@
         }
     }
 
+    /**
+     * This method will update the flags of the summary.
+     * It will set it to FLAG_ONGOING_EVENT if any of its group members
+     * has the same flag. It will delete the flag otherwise
+     * @param userId user id of the autogroup summary
+     * @param pkg package of the autogroup summary
+     * @param needsOngoingFlag true if the group has at least one ongoing notification
+     */
+    @GuardedBy("mNotificationLock")
+    protected void updateAutobundledSummaryFlags(int userId, String pkg, boolean needsOngoingFlag) {
+        ArrayMap<String, String> summaries = mAutobundledSummaries.get(userId);
+        if (summaries == null) {
+            return;
+        }
+        String summaryKey = summaries.get(pkg);
+        if (summaryKey == null) {
+            return;
+        }
+        NotificationRecord summary = mNotificationsByKey.get(summaryKey);
+        if (summary == null) {
+            return;
+        }
+        int oldFlags = summary.sbn.getNotification().flags;
+        if (needsOngoingFlag) {
+            summary.sbn.getNotification().flags |= FLAG_ONGOING_EVENT;
+        } else {
+            summary.sbn.getNotification().flags &= ~FLAG_ONGOING_EVENT;
+        }
+
+        if (summary.sbn.getNotification().flags != oldFlags) {
+            mHandler.post(new EnqueueNotificationRunnable(userId, summary));
+        }
+    }
+
     private void allowDndPackage(String packageName) {
         try {
             getBinderService().setNotificationPolicyAccessGranted(packageName, true);
@@ -1331,16 +1371,15 @@
                     uidList = new int[] {intent.getIntExtra(Intent.EXTRA_UID, -1)};
                 }
                 if (pkgList != null && (pkgList.length > 0)) {
-                    for (String pkgName : pkgList) {
-                        if (cancelNotifications) {
+                    if (cancelNotifications) {
+                        for (String pkgName : pkgList) {
                             cancelAllNotificationsInt(MY_UID, MY_PID, pkgName, null, 0, 0,
                                     !queryRestart, changeUserId, reason, null);
-                        } else if (hideNotifications) {
-                            hideNotificationsForPackages(pkgList);
-                        } else if (unhideNotifications) {
-                            unhideNotificationsForPackages(pkgList);
                         }
-
+                    } else if (hideNotifications) {
+                        hideNotificationsForPackages(pkgList);
+                    } else if (unhideNotifications) {
+                        unhideNotificationsForPackages(pkgList);
                     }
                 }
 
@@ -1429,10 +1468,8 @@
     private final class SettingsObserver extends ContentObserver {
         private final Uri NOTIFICATION_BADGING_URI
                 = Settings.Secure.getUriFor(Settings.Secure.NOTIFICATION_BADGING);
-        private final Uri NOTIFICATION_BUBBLES_URI_GLOBAL
+        private final Uri NOTIFICATION_BUBBLES_URI
                 = Settings.Global.getUriFor(Settings.Global.NOTIFICATION_BUBBLES);
-        private final Uri NOTIFICATION_BUBBLES_URI_SECURE
-                = Settings.Secure.getUriFor(Settings.Secure.NOTIFICATION_BUBBLES);
         private final Uri NOTIFICATION_LIGHT_PULSE_URI
                 = Settings.System.getUriFor(Settings.System.NOTIFICATION_LIGHT_PULSE);
         private final Uri NOTIFICATION_RATE_LIMIT_URI
@@ -1450,9 +1487,7 @@
                     false, this, UserHandle.USER_ALL);
             resolver.registerContentObserver(NOTIFICATION_RATE_LIMIT_URI,
                     false, this, UserHandle.USER_ALL);
-            resolver.registerContentObserver(NOTIFICATION_BUBBLES_URI_GLOBAL,
-                    false, this, UserHandle.USER_ALL);
-            resolver.registerContentObserver(NOTIFICATION_BUBBLES_URI_SECURE,
+            resolver.registerContentObserver(NOTIFICATION_BUBBLES_URI,
                     false, this, UserHandle.USER_ALL);
             update(null);
         }
@@ -1479,41 +1514,9 @@
             if (uri == null || NOTIFICATION_BADGING_URI.equals(uri)) {
                 mPreferencesHelper.updateBadgingEnabled();
             }
-            // In QPR we moved the setting to Global rather than Secure so that the setting
-            // applied to work profiles. Unfortunately we need to maintain both to pass CTS without
-            // a change to CTS outside of a normal letter release.
-            if (uri == null || NOTIFICATION_BUBBLES_URI_GLOBAL.equals(uri)) {
-                syncBubbleSettings(resolver, NOTIFICATION_BUBBLES_URI_GLOBAL);
+            if (uri == null || NOTIFICATION_BUBBLES_URI.equals(uri)) {
                 mPreferencesHelper.updateBubblesEnabled();
             }
-            if (NOTIFICATION_BUBBLES_URI_SECURE.equals(uri)) {
-                syncBubbleSettings(resolver, NOTIFICATION_BUBBLES_URI_SECURE);
-            }
-        }
-
-        private void syncBubbleSettings(ContentResolver resolver, Uri settingToFollow) {
-            boolean followSecureSetting = settingToFollow.equals(NOTIFICATION_BUBBLES_URI_SECURE);
-
-            int secureSettingValue = Settings.Secure.getInt(resolver,
-                    Settings.Secure.NOTIFICATION_BUBBLES, DEFAULT_ALLOW_BUBBLE ? 1 : 0);
-            int globalSettingValue = Settings.Global.getInt(resolver,
-                    Settings.Global.NOTIFICATION_BUBBLES, DEFAULT_ALLOW_BUBBLE ? 1 : 0);
-
-            if (globalSettingValue == secureSettingValue) {
-                return;
-            }
-
-            if (followSecureSetting) {
-                // Global => secure
-                Settings.Global.putInt(resolver,
-                        Settings.Global.NOTIFICATION_BUBBLES,
-                        secureSettingValue);
-            } else {
-                // Secure => Global
-                Settings.Secure.putInt(resolver,
-                        Settings.Secure.NOTIFICATION_BADGING,
-                        globalSettingValue);
-            }
         }
     }
 
@@ -1948,7 +1951,6 @@
                 });
     }
 
-
     private GroupHelper getGroupHelper() {
         mAutoGroupAtCount =
                 getContext().getResources().getInteger(R.integer.config_autoGroupAtCount);
@@ -1978,6 +1980,15 @@
                     clearAutogroupSummaryLocked(userId, pkg);
                 }
             }
+
+            @Override
+            public void updateAutogroupSummary(String key, boolean needsOngoingFlag) {
+                synchronized (mNotificationLock) {
+                    NotificationRecord r = mNotificationsByKey.get(key);
+                    updateAutobundledSummaryFlags(r.getUser().getIdentifier(),
+                            r.sbn.getPackageName(), needsOngoingFlag);
+                }
+            }
         });
     }
 
@@ -5045,12 +5056,13 @@
         final int contentViewSize = contentView.estimateMemoryUsage();
         if (contentViewSize > mWarnRemoteViewsSizeBytes
                 && contentViewSize < mStripRemoteViewsSizeBytes) {
-            Slog.w(TAG, "RemoteViews too large on tag: " + tag + " id: " + id
+            Slog.w(TAG, "RemoteViews too large on pkg: " + pkg + " tag: " + tag + " id: " + id
                     + " this might be stripped in a future release");
         }
         if (contentViewSize >= mStripRemoteViewsSizeBytes) {
             mUsageStats.registerImageRemoved(pkg);
-            Slog.w(TAG, "Removed too large RemoteViews on tag: " + tag + " id: " + id);
+            Slog.w(TAG,
+                    "Removed too large RemoteViews on pkg: " + pkg + " tag: " + tag + " id: " + id);
             return true;
         }
         return false;
@@ -5792,6 +5804,10 @@
                                             n, hasAutoGroupSummaryLocked(n));
                                 }
                             });
+                        } else if (oldSbn != null) {
+                            final NotificationRecord finalRecord = r;
+                            mHandler.post(() -> mGroupHelper.onNotificationUpdated(
+                                    finalRecord.sbn, hasAutoGroupSummaryLocked(n)));
                         }
                     } else {
                         Slog.e(TAG, "Not posting notification without small icon: " + notification);
diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java
index f63aa52..6510923 100644
--- a/services/core/java/com/android/server/notification/ZenModeHelper.java
+++ b/services/core/java/com/android/server/notification/ZenModeHelper.java
@@ -1179,7 +1179,7 @@
 
             if (mZenMode == Global.ZEN_MODE_OFF
                     || (mZenMode == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS
-                    && !ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(mConfig))) {
+                    && !ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(mConfig))) {
                 // in priority only with ringer not muted, save ringer mode changes
                 // in dnd off, save ringer mode changes
                 setPreviousRingerModeSetting(ringerModeNew);
@@ -1200,7 +1200,7 @@
                             && (mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS
                             || mZenMode == Global.ZEN_MODE_ALARMS
                             || (mZenMode == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS
-                            && ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(
+                            && ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(
                             mConfig)))) {
                         newZen = Global.ZEN_MODE_OFF;
                     } else if (mZenMode != Global.ZEN_MODE_OFF) {
@@ -1264,29 +1264,21 @@
 
         @Override
         public int getRingerModeAffectedStreams(int streams) {
-            // ringtone and notification streams are always affected by ringer mode
-            // system stream is affected by ringer mode when not in priority-only
+            // ringtone, notification and system streams are always affected by ringer mode
+            // zen muting is handled in AudioService.java's mZenModeAffectedStreams
             streams |= (1 << AudioSystem.STREAM_RING) |
                     (1 << AudioSystem.STREAM_NOTIFICATION) |
                     (1 << AudioSystem.STREAM_SYSTEM);
 
             if (mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS) {
-                // alarm and music streams affected by ringer mode when in total silence
+                // alarm and music streams affected by ringer mode (cannot be adjusted) when in
+                // total silence
                 streams |= (1 << AudioSystem.STREAM_ALARM) |
                         (1 << AudioSystem.STREAM_MUSIC);
             } else {
                 streams &= ~((1 << AudioSystem.STREAM_ALARM) |
                         (1 << AudioSystem.STREAM_MUSIC));
             }
-
-            if (mZenMode == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS
-                    && ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(mConfig)) {
-                // system stream is not affected by ringer mode in priority only when the ringer
-                // is zen muted (all other notification categories are muted)
-                streams &= ~(1 << AudioSystem.STREAM_SYSTEM);
-            } else {
-                streams |= (1 << AudioSystem.STREAM_SYSTEM);
-            }
             return streams;
         }
     }
diff --git a/services/core/java/com/android/server/om/IdmapManager.java b/services/core/java/com/android/server/om/IdmapManager.java
index 288ef0e..f3c9128 100644
--- a/services/core/java/com/android/server/om/IdmapManager.java
+++ b/services/core/java/com/android/server/om/IdmapManager.java
@@ -30,20 +30,17 @@
 import android.util.Slog;
 
 import com.android.server.om.OverlayManagerServiceImpl.PackageManagerHelper;
-import com.android.server.pm.Installer;
 
 import java.io.File;
 
 /**
  * Handle the creation and deletion of idmap files.
  *
- * The actual work is performed by the idmap binary, launched through Installer
- * and installd (or idmap2).
+ * The actual work is performed by the idmap binary, launched through idmap2d.
  *
  * Note: this class is subclassed in the OMS unit tests, and hence not marked as final.
  */
 class IdmapManager {
-    private static final boolean FEATURE_FLAG_IDMAP2 = true;
     private static final boolean VENDOR_IS_Q_OR_LATER;
     static {
         final String value = SystemProperties.get("ro.vndk.version", "29");
@@ -58,12 +55,10 @@
         VENDOR_IS_Q_OR_LATER = isQOrLater;
     }
 
-    private final Installer mInstaller;
     private final PackageManagerHelper mPackageManager;
     private final IdmapDaemon mIdmapDaemon;
 
-    IdmapManager(final Installer installer, final PackageManagerHelper packageManager) {
-        mInstaller = installer;
+    IdmapManager(final PackageManagerHelper packageManager) {
         mPackageManager = packageManager;
         mIdmapDaemon = IdmapDaemon.getInstance();
     }
@@ -78,18 +73,13 @@
         final String targetPath = targetPackage.applicationInfo.getBaseCodePath();
         final String overlayPath = overlayPackage.applicationInfo.getBaseCodePath();
         try {
-            if (FEATURE_FLAG_IDMAP2) {
-                int policies = calculateFulfilledPolicies(targetPackage, overlayPackage, userId);
-                boolean enforce = enforceOverlayable(overlayPackage);
-                if (mIdmapDaemon.verifyIdmap(overlayPath, policies, enforce, userId)) {
-                    return true;
-                }
-                return mIdmapDaemon.createIdmap(targetPath, overlayPath, policies,
-                        enforce, userId) != null;
-            } else {
-                mInstaller.idmap(targetPath, overlayPath, sharedGid);
+            int policies = calculateFulfilledPolicies(targetPackage, overlayPackage, userId);
+            boolean enforce = enforceOverlayable(overlayPackage);
+            if (mIdmapDaemon.verifyIdmap(overlayPath, policies, enforce, userId)) {
                 return true;
             }
+            return mIdmapDaemon.createIdmap(targetPath, overlayPath, policies,
+                    enforce, userId) != null;
         } catch (Exception e) {
             Slog.w(TAG, "failed to generate idmap for " + targetPath + " and "
                     + overlayPath + ": " + e.getMessage());
@@ -102,12 +92,7 @@
             Slog.d(TAG, "remove idmap for " + oi.baseCodePath);
         }
         try {
-            if (FEATURE_FLAG_IDMAP2) {
-                return mIdmapDaemon.removeIdmap(oi.baseCodePath, userId);
-            } else {
-                mInstaller.removeIdmap(oi.baseCodePath);
-                return true;
-            }
+            return mIdmapDaemon.removeIdmap(oi.baseCodePath, userId);
         } catch (Exception e) {
             Slog.w(TAG, "failed to remove idmap for " + oi.baseCodePath + ": " + e.getMessage());
             return false;
@@ -125,19 +110,12 @@
 
     private @NonNull String getIdmapPath(@NonNull final String overlayPackagePath,
             final int userId) {
-        if (FEATURE_FLAG_IDMAP2) {
-            try {
-                return mIdmapDaemon.getIdmapPath(overlayPackagePath, userId);
-            } catch (Exception e) {
-                Slog.w(TAG, "failed to get idmap path for " + overlayPackagePath + ": "
-                        + e.getMessage());
-                return "";
-            }
-        } else {
-            final StringBuilder sb = new StringBuilder("/data/resource-cache/");
-            sb.append(overlayPackagePath.substring(1).replace('/', '@'));
-            sb.append("@idmap");
-            return sb.toString();
+        try {
+            return mIdmapDaemon.getIdmapPath(overlayPackagePath, userId);
+        } catch (Exception e) {
+            Slog.w(TAG, "failed to get idmap path for " + overlayPackagePath + ": "
+                    + e.getMessage());
+            return "";
         }
     }
 
diff --git a/services/core/java/com/android/server/om/OverlayManagerService.java b/services/core/java/com/android/server/om/OverlayManagerService.java
index f8b3fb2..9e7b4648 100644
--- a/services/core/java/com/android/server/om/OverlayManagerService.java
+++ b/services/core/java/com/android/server/om/OverlayManagerService.java
@@ -62,7 +62,6 @@
 import com.android.server.IoThread;
 import com.android.server.LocalServices;
 import com.android.server.SystemService;
-import com.android.server.pm.Installer;
 import com.android.server.pm.UserManagerService;
 
 import libcore.util.EmptyArray;
@@ -230,8 +229,7 @@
 
     private final AtomicBoolean mPersistSettingsScheduled = new AtomicBoolean(false);
 
-    public OverlayManagerService(@NonNull final Context context,
-            @NonNull final Installer installer) {
+    public OverlayManagerService(@NonNull final Context context) {
         super(context);
         try {
             traceBegin(TRACE_TAG_RRO, "OMS#OverlayManagerService");
@@ -239,7 +237,7 @@
                     new File(Environment.getDataSystemDirectory(), "overlays.xml"), "overlays");
             mPackageManager = new PackageManagerHelper();
             mUserManager = UserManagerService.getInstance();
-            IdmapManager im = new IdmapManager(installer, mPackageManager);
+            IdmapManager im = new IdmapManager(mPackageManager);
             mSettings = new OverlayManagerSettings();
             mImpl = new OverlayManagerServiceImpl(mPackageManager, im, mSettings,
                     getDefaultOverlayPackages(), new OverlayChangeListener());
@@ -740,6 +738,25 @@
         }
 
         @Override
+        public void invalidateCachesForOverlay(@Nullable String packageName, int userId)
+                throws RemoteException {
+            if (packageName == null) {
+                return;
+            }
+
+            enforceChangeOverlayPackagesPermission("invalidateCachesForOverlay");
+            userId = handleIncomingUser(userId, "invalidateCachesForOverlay");
+            final long ident = Binder.clearCallingIdentity();
+            try {
+                synchronized (mLock) {
+                    mImpl.removeIdmapForOverlay(packageName, userId);
+                }
+            } finally {
+                Binder.restoreCallingIdentity(ident);
+            }
+        }
+
+        @Override
         public void onShellCommand(@NonNull final FileDescriptor in,
                 @NonNull final FileDescriptor out, @NonNull final FileDescriptor err,
                 @NonNull final String[] args, @NonNull final ShellCallback callback,
diff --git a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
index 934511b..019c952 100644
--- a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
+++ b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
@@ -651,6 +651,11 @@
         return mDefaultOverlays;
     }
 
+    void removeIdmapForOverlay(String packageName, int userId) {
+        final OverlayInfo oi = mSettings.getOverlayInfo(packageName, userId);
+        removeIdmapIfPossible(oi);
+    }
+
     List<String> getEnabledOverlayPackageNames(@NonNull final String targetPackageName,
             final int userId) {
         final List<OverlayInfo> overlays = mSettings.getOverlaysForTarget(targetPackageName,
diff --git a/services/core/java/com/android/server/pm/ComponentResolver.java b/services/core/java/com/android/server/pm/ComponentResolver.java
index 8facce1..976cdfb 100644
--- a/services/core/java/com/android/server/pm/ComponentResolver.java
+++ b/services/core/java/com/android/server/pm/ComponentResolver.java
@@ -23,6 +23,7 @@
 import static com.android.server.pm.PackageManagerService.DEBUG_REMOVE;
 import static com.android.server.pm.PackageManagerService.fixProcessName;
 
+import android.annotation.Nullable;
 import android.content.ComponentName;
 import android.content.Intent;
 import android.content.IntentFilter;
@@ -219,12 +220,14 @@
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryActivities(Intent intent, String resolvedType, int flags, int userId) {
         synchronized (mLock) {
             return mActivities.queryIntent(intent, resolvedType, flags, userId);
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryActivities(Intent intent, String resolvedType, int flags,
             List<PackageParser.Activity> activities, int userId) {
         synchronized (mLock) {
@@ -233,12 +236,14 @@
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryProviders(Intent intent, String resolvedType, int flags, int userId) {
         synchronized (mLock) {
             return mProviders.queryIntent(intent, resolvedType, flags, userId);
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryProviders(Intent intent, String resolvedType, int flags,
             List<PackageParser.Provider> providers, int userId) {
         synchronized (mLock) {
@@ -246,6 +251,7 @@
         }
     }
 
+    @Nullable
     List<ProviderInfo> queryProviders(String processName, String metaDataKey, int uid, int flags,
             int userId) {
         if (!sUserManager.exists(userId)) {
@@ -285,6 +291,7 @@
         return providerList;
     }
 
+    @Nullable
     ProviderInfo queryProvider(String authority, int flags, int userId) {
         synchronized (mLock) {
             final PackageParser.Provider p = mProvidersByAuthority.get(authority);
@@ -326,12 +333,14 @@
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryReceivers(Intent intent, String resolvedType, int flags, int userId) {
         synchronized (mLock) {
             return mReceivers.queryIntent(intent, resolvedType, flags, userId);
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryReceivers(Intent intent, String resolvedType, int flags,
             List<PackageParser.Activity> receivers, int userId) {
         synchronized (mLock) {
@@ -339,12 +348,14 @@
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryServices(Intent intent, String resolvedType, int flags, int userId) {
         synchronized (mLock) {
             return mServices.queryIntent(intent, resolvedType, flags, userId);
         }
     }
 
+    @Nullable
     List<ResolveInfo> queryServices(Intent intent, String resolvedType, int flags,
             List<PackageParser.Service> services, int userId) {
         synchronized (mLock) {
@@ -1355,6 +1366,7 @@
             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
         }
 
+        @Nullable
         List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
                 int userId) {
             if (!sUserManager.exists(userId)) {
@@ -1366,6 +1378,7 @@
                     userId);
         }
 
+        @Nullable
         List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
                 int flags, List<PackageParser.Provider> packageProviders, int userId) {
             if (!sUserManager.exists(userId)) {
diff --git a/services/core/java/com/android/server/pm/LauncherAppsService.java b/services/core/java/com/android/server/pm/LauncherAppsService.java
index 3464cab..2b6c347 100644
--- a/services/core/java/com/android/server/pm/LauncherAppsService.java
+++ b/services/core/java/com/android/server/pm/LauncherAppsService.java
@@ -62,6 +62,7 @@
 import android.os.UserManagerInternal;
 import android.provider.Settings;
 import android.util.Log;
+import android.util.Pair;
 import android.util.Slog;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -1024,8 +1025,22 @@
             }
 
             @Override
-            public void onPackagesSuspended(String[] packages, Bundle launcherExtras) {
+            public void onPackagesSuspended(String[] packages) {
                 UserHandle user = new UserHandle(getChangingUserId());
+                PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
+                final ArrayList<Pair<String, Bundle>> packagesWithExtras = new ArrayList<>();
+                final ArrayList<String> packagesWithoutExtras = new ArrayList<>();
+                for (String pkg : packages) {
+                    final Bundle launcherExtras = pmi.getSuspendedPackageLauncherExtras(pkg,
+                            user.getIdentifier());
+                    if (launcherExtras != null) {
+                        packagesWithExtras.add(new Pair<>(pkg, launcherExtras));
+                    } else {
+                        packagesWithoutExtras.add(pkg);
+                    }
+                }
+                final String[] packagesNullExtras = packagesWithoutExtras.toArray(
+                        new String[packagesWithoutExtras.size()]);
                 final int n = mListeners.beginBroadcast();
                 try {
                     for (int i = 0; i < n; i++) {
@@ -1033,7 +1048,13 @@
                         BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
                         if (!isEnabledProfileOf(cookie.user, user, "onPackagesSuspended")) continue;
                         try {
-                            listener.onPackagesSuspended(user, packages, launcherExtras);
+                            listener.onPackagesSuspended(user, packagesNullExtras, null);
+                            for (int idx = 0; idx < packagesWithExtras.size(); idx++) {
+                                Pair<String, Bundle> packageExtraPair = packagesWithExtras.get(idx);
+                                listener.onPackagesSuspended(user,
+                                        new String[]{packageExtraPair.first},
+                                        packageExtraPair.second);
+                            }
                         } catch (RemoteException re) {
                             Slog.d(TAG, "Callback failed ", re);
                         }
@@ -1041,8 +1062,6 @@
                 } finally {
                     mListeners.finishBroadcast();
                 }
-
-                super.onPackagesSuspended(packages, launcherExtras);
             }
 
             @Override
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index b632d18f..a7d4237 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -259,6 +259,10 @@
         // Don't hold mSessions lock when calling restoreSession, since it might trigger an APK
         // atomic install which needs to query sessions, which requires lock on mSessions.
         for (PackageInstallerSession session : stagedSessionsToRestore) {
+            if (mPm.isDeviceUpgrading()) {
+                session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
+                        "Build fingerprint has changed");
+            }
             mStagingManager.restoreSession(session);
         }
         // Broadcasts are not sent while we restore sessions on boot, since no processes would be
@@ -491,6 +495,7 @@
 
             params.installFlags &= ~PackageManager.INSTALL_FROM_ADB;
             params.installFlags &= ~PackageManager.INSTALL_ALL_USERS;
+            params.installFlags &= ~PackageManager.INSTALL_ALLOW_TEST;
             params.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
             if ((params.installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0
                     && !mPm.isCallerVerifier(callingUid)) {
diff --git a/services/core/java/com/android/server/pm/PackageList.java b/services/core/java/com/android/server/pm/PackageList.java
new file mode 100644
index 0000000..60bc8a8
--- /dev/null
+++ b/services/core/java/com/android/server/pm/PackageList.java
@@ -0,0 +1,82 @@
+/*
+ * 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.pm;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.pm.PackageManagerInternal;
+import android.content.pm.PackageManagerInternal.PackageListObserver;
+
+import com.android.server.LocalServices;
+
+import java.util.List;
+
+/**
+ * All of the package name installed on the system.
+ * <p>A self observable list that automatically removes the listener when it goes out of scope.
+ *
+ * @hide Only for use within the system server.
+ */
+public class PackageList implements PackageListObserver, AutoCloseable {
+    private final PackageListObserver mWrappedObserver;
+    private final List<String> mPackageNames;
+
+    /**
+     * Create a new object.
+     * <p>Ownership of the given {@link List} transfers to this object and should not
+     * be modified by the caller.
+     */
+    public PackageList(@NonNull List<String> packageNames, @Nullable PackageListObserver observer) {
+        mPackageNames = packageNames;
+        mWrappedObserver = observer;
+    }
+
+    @Override
+    public void onPackageAdded(String packageName, int uid) {
+        if (mWrappedObserver != null) {
+            mWrappedObserver.onPackageAdded(packageName, uid);
+        }
+    }
+
+    @Override
+    public void onPackageChanged(String packageName, int uid) {
+        if (mWrappedObserver != null) {
+            mWrappedObserver.onPackageChanged(packageName, uid);
+        }
+    }
+
+    @Override
+    public void onPackageRemoved(String packageName, int uid) {
+        if (mWrappedObserver != null) {
+            mWrappedObserver.onPackageRemoved(packageName, uid);
+        }
+    }
+
+    @Override
+    public void close() throws Exception {
+        LocalServices.getService(PackageManagerInternal.class).removePackageListObserver(this);
+    }
+
+    /**
+     * Returns the names of packages installed on the system.
+     * <p>The list is a copy-in-time and the actual set of installed packages may differ. Real
+     * time updates to the package list are sent via the {@link PackageListObserver} callback.
+     */
+    public @NonNull List<String> getPackageNames() {
+        return mPackageNames;
+    }
+}
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 587862a..67339c8 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -37,7 +37,7 @@
 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
-import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
+import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKED_COMPAT;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
@@ -137,7 +137,6 @@
 import android.content.IntentSender.SendIntentException;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
-import android.content.pm.AppsQueryHelper;
 import android.content.pm.AuxiliaryResolveInfo;
 import android.content.pm.ChangedPackages;
 import android.content.pm.ComponentInfo;
@@ -163,7 +162,6 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageInfoLite;
 import android.content.pm.PackageInstaller;
-import android.content.pm.PackageList;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
 import android.content.pm.PackageManager.ModuleInfoFlags;
@@ -372,7 +370,6 @@
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.BiConsumer;
 import java.util.function.Consumer;
-import java.util.function.Predicate;
 
 /**
  * Keep track of all those APKs everywhere.
@@ -581,16 +578,6 @@
 
     private static final String PACKAGE_SCHEME = "package";
 
-    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
-
-    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
-
-    private static final String SYSTEM_EXT_OVERLAY_DIR = "/system_ext/overlay";
-
-    private static final String ODM_OVERLAY_DIR = "/odm/overlay";
-
-    private static final String OEM_OVERLAY_DIR = "/oem/overlay";
-
     /** Canonical intent used to identify what counts as a "web browser" app */
     private static final Intent sBrowserIntent;
     static {
@@ -756,6 +743,26 @@
     private final Injector mInjector;
 
     /**
+     * The list of all system partitions that may contain packages in ascending order of
+     * specificity (the more generic, the earlier in the list a partition appears).
+     */
+    @VisibleForTesting(visibility = Visibility.PRIVATE)
+    static final List<SystemPartition> SYSTEM_PARTITIONS = Collections.unmodifiableList(
+            Arrays.asList(
+                    new SystemPartition(Environment.getRootDirectory(), 0 /* scanFlag */,
+                            true /* hasPriv */, false /* hasOverlays */),
+                    new SystemPartition(Environment.getVendorDirectory(), SCAN_AS_VENDOR,
+                            true /* hasPriv */, true /* hasOverlays */),
+                    new SystemPartition(Environment.getOdmDirectory(), SCAN_AS_ODM,
+                            true /* hasPriv */, true /* hasOverlays */),
+                    new SystemPartition(Environment.getOemDirectory(), SCAN_AS_OEM,
+                            false /* hasPriv */, true /* hasOverlays */),
+                    new SystemPartition(Environment.getProductDirectory(), SCAN_AS_PRODUCT,
+                            true /* hasPriv */, true /* hasOverlays */),
+                    new SystemPartition(Environment.getSystemExtDirectory(), SCAN_AS_SYSTEM_EXT,
+                            true /* hasPriv */, true /* hasOverlays */)));
+
+    /**
      * Unit tests will instantiate, extend and/or mock to mock dependencies / behaviors.
      *
      * NOTE: All getters should return the same instance for every call.
@@ -1582,7 +1589,7 @@
     private static final int USER_RUNTIME_GRANT_MASK =
             FLAG_PERMISSION_USER_SET
             | FLAG_PERMISSION_USER_FIXED
-            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
+            | FLAG_PERMISSION_REVOKED_COMPAT;
 
     final @Nullable String mRequiredVerifierPackage;
     final @NonNull String mRequiredInstallerPackage;
@@ -2463,54 +2470,21 @@
         PackageManagerService m = new PackageManagerService(injector, factoryTest, onlyCore);
         t.traceEnd(); // "create package manager"
 
-        m.enableSystemUserPackages();
+        m.installWhitelistedSystemPackages();
         ServiceManager.addService("package", m);
         final PackageManagerNative pmn = m.new PackageManagerNative();
         ServiceManager.addService("package_native", pmn);
         return m;
     }
 
-    private void enableSystemUserPackages() {
-        if (!UserManager.isSplitSystemUser()) {
-            return;
-        }
-        // For system user, enable apps based on the following conditions:
-        // - app is whitelisted or belong to one of these groups:
-        //   -- system app which has no launcher icons
-        //   -- system app which has INTERACT_ACROSS_USERS permission
-        //   -- system IME app
-        // - app is not in the blacklist
-        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
-        Set<String> enableApps = new ArraySet<>();
-        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
-                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
-                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
-        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
-        enableApps.addAll(wlApps);
-        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
-                /* systemAppsOnly */ false, UserHandle.SYSTEM));
-        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
-        enableApps.removeAll(blApps);
-        Log.i(TAG, "Applications installed for system user: " + enableApps);
-        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
-                UserHandle.SYSTEM);
-        final int allAppsSize = allAps.size();
+    /** Install/uninstall system packages for all users based on their user-type, as applicable. */
+    private void installWhitelistedSystemPackages() {
         synchronized (mLock) {
-            for (int i = 0; i < allAppsSize; i++) {
-                String pName = allAps.get(i);
-                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
-                // Should not happen, but we shouldn't be failing if it does
-                if (pkgSetting == null) {
-                    continue;
-                }
-                boolean install = enableApps.contains(pName);
-                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
-                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
-                            + " for system user");
-                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
-                }
+            final boolean scheduleWrite = mUserManager.installWhitelistedSystemPackages(
+                    isFirstBoot(), isDeviceUpgrading());
+            if (scheduleWrite) {
+                scheduleWritePackageRestrictionsLocked(UserHandle.USER_ALL);
             }
-            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
         }
     }
 
@@ -2552,6 +2526,51 @@
         }
     }
 
+    @VisibleForTesting(visibility = Visibility.PRIVATE)
+    static class SystemPartition {
+        public final File folder;
+        public final int scanFlag;
+        public final File appFolder;
+        @Nullable
+        public final File privAppFolder;
+        @Nullable
+        public final File overlayFolder;
+
+        private SystemPartition(File folder, int scanFlag, boolean hasPrivApps,
+                boolean hasOverlays) {
+            this.folder = folder;
+            this.scanFlag = scanFlag;
+            this.appFolder = toCanonical(new File(folder, "app"));
+            this.privAppFolder = hasPrivApps ? toCanonical(new File(folder, "priv-app")) : null;
+            this.overlayFolder = hasOverlays ? toCanonical(new File(folder, "overlay")) : null;
+        }
+
+        public boolean containsPrivApp(File scanFile) {
+            return FileUtils.contains(privAppFolder, scanFile);
+        }
+
+        public boolean containsApp(File scanFile) {
+            return FileUtils.contains(appFolder, scanFile);
+        }
+
+        public boolean containsPath(String path) {
+            return path.startsWith(folder.getPath() + "/");
+        }
+
+        public boolean containsPrivPath(String path) {
+            return privAppFolder != null && path.startsWith(privAppFolder.getPath() + "/");
+        }
+
+        private static File toCanonical(File dir) {
+            try {
+                return dir.getCanonicalFile();
+            } catch (IOException e) {
+                // failed to look up canonical path, continue with original one
+                return dir;
+            }
+        }
+    }
+
     public PackageManagerService(Injector injector, boolean onlyCore, boolean factoryTest) {
         final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
                 Trace.TRACE_TAG_PACKAGE_MANAGER);
@@ -2775,215 +2794,35 @@
             // any apps.)
             // For security and version matching reason, only consider overlay packages if they
             // reside in the right directory.
-            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_VENDOR,
-                    0);
-            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_PRODUCT,
-                    0);
-            scanDirTracedLI(new File(SYSTEM_EXT_OVERLAY_DIR),
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_SYSTEM_EXT,
-                    0);
-            scanDirTracedLI(new File(ODM_OVERLAY_DIR),
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_ODM,
-                    0);
-            scanDirTracedLI(new File(OEM_OVERLAY_DIR),
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_OEM,
-                    0);
+            final int systemParseFlags = mDefParseFlags | PackageParser.PARSE_IS_SYSTEM_DIR;
+            final int systemScanFlags = scanFlags | SCAN_AS_SYSTEM;
+            for (int i = SYSTEM_PARTITIONS.size() - 1; i >= 0; i--) {
+                final SystemPartition partition = SYSTEM_PARTITIONS.get(i);
+                if (partition.overlayFolder == null) {
+                    continue;
+                }
+                scanDirTracedLI(partition.overlayFolder, systemParseFlags,
+                        systemScanFlags | partition.scanFlag, 0);
+            }
 
             mParallelPackageParserCallback.findStaticOverlayPackages();
 
-            // Find base frameworks (resource packages without code).
-            scanDirTracedLI(frameworkDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_NO_DEX
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_PRIVILEGED,
-                    0);
+            scanDirTracedLI(frameworkDir, systemParseFlags,
+                    systemScanFlags | SCAN_NO_DEX | SCAN_AS_PRIVILEGED, 0);
             if (!mPackages.containsKey("android")) {
                 throw new IllegalStateException(
                         "Failed to load frameworks package; check log for warnings");
             }
-
-            // Collect privileged system packages.
-            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
-            scanDirTracedLI(privilegedAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_PRIVILEGED,
-                    0);
-
-            // Collect ordinary system packages.
-            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
-            scanDirTracedLI(systemAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM,
-                    0);
-
-            // Collect privileged vendor packages.
-            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
-            try {
-                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
+            for (int i = 0, size = SYSTEM_PARTITIONS.size(); i < size; i++) {
+                final SystemPartition partition = SYSTEM_PARTITIONS.get(i);
+                if (partition.privAppFolder != null) {
+                    scanDirTracedLI(partition.privAppFolder, systemParseFlags,
+                            systemScanFlags | SCAN_AS_PRIVILEGED | partition.scanFlag, 0);
+                }
+                scanDirTracedLI(partition.appFolder, systemParseFlags,
+                        systemScanFlags | partition.scanFlag, 0);
             }
-            scanDirTracedLI(privilegedVendorAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_VENDOR
-                    | SCAN_AS_PRIVILEGED,
-                    0);
 
-            // Collect ordinary vendor packages.
-            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
-            try {
-                vendorAppDir = vendorAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
-            }
-            scanDirTracedLI(vendorAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_VENDOR,
-                    0);
-
-            // Collect privileged odm packages. /odm is another vendor partition
-            // other than /vendor.
-            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
-                        "priv-app");
-            try {
-                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
-            }
-            scanDirTracedLI(privilegedOdmAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_VENDOR
-                    | SCAN_AS_PRIVILEGED,
-                    0);
-
-            // Collect ordinary odm packages. /odm is another vendor partition
-            // other than /vendor.
-            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
-            try {
-                odmAppDir = odmAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
-            }
-            scanDirTracedLI(odmAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_VENDOR,
-                    0);
-
-            // Collect all OEM packages.
-            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
-            scanDirTracedLI(oemAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_OEM,
-                    0);
-
-            // Collected privileged /product packages.
-            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
-            try {
-                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
-            }
-            scanDirTracedLI(privilegedProductAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_PRODUCT
-                    | SCAN_AS_PRIVILEGED,
-                    0);
-
-            // Collect ordinary /product packages.
-            File productAppDir = new File(Environment.getProductDirectory(), "app");
-            try {
-                productAppDir = productAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
-            }
-            scanDirTracedLI(productAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_PRODUCT,
-                    0);
-
-            // Collected privileged /system_ext packages.
-            File privilegedSystemExtAppDir =
-                    new File(Environment.getSystemExtDirectory(), "priv-app");
-            try {
-                privilegedSystemExtAppDir =
-                        privilegedSystemExtAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
-            }
-            scanDirTracedLI(privilegedSystemExtAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_SYSTEM_EXT
-                    | SCAN_AS_PRIVILEGED,
-                    0);
-
-            // Collect ordinary /system_ext packages.
-            File systemExtAppDir = new File(Environment.getSystemExtDirectory(), "app");
-            try {
-                systemExtAppDir = systemExtAppDir.getCanonicalFile();
-            } catch (IOException e) {
-                // failed to look up canonical path, continue with original one
-            }
-            scanDirTracedLI(systemExtAppDir,
-                    mDefParseFlags
-                    | PackageParser.PARSE_IS_SYSTEM_DIR,
-                    scanFlags
-                    | SCAN_AS_SYSTEM
-                    | SCAN_AS_SYSTEM_EXT,
-                    0);
 
             // Prune any system packages that no longer exist.
             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
@@ -3151,89 +2990,26 @@
                         logCriticalInfo(Log.WARN, "Expected better " + packageName
                                 + " but never showed up; reverting to system");
 
-                        final @ParseFlags int reparseFlags;
-                        final @ScanFlags int rescanFlags;
-                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_PRIVILEGED;
-                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM;
-                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
-                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_VENDOR
-                                    | SCAN_AS_PRIVILEGED;
-                        } else if (FileUtils.contains(vendorAppDir, scanFile)
-                                || FileUtils.contains(odmAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_VENDOR;
-                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_OEM;
-                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_PRODUCT
-                                    | SCAN_AS_PRIVILEGED;
-                        } else if (FileUtils.contains(productAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_PRODUCT;
-                        } else if (FileUtils.contains(privilegedSystemExtAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_SYSTEM_EXT
-                                    | SCAN_AS_PRIVILEGED;
-                        } else if (FileUtils.contains(systemExtAppDir, scanFile)) {
-                            reparseFlags =
-                                    mDefParseFlags |
-                                    PackageParser.PARSE_IS_SYSTEM_DIR;
-                            rescanFlags =
-                                    scanFlags
-                                    | SCAN_AS_SYSTEM
-                                    | SCAN_AS_SYSTEM_EXT;
-                        } else {
+                        @ParseFlags int reparseFlags = 0;
+                        @ScanFlags int rescanFlags = 0;
+                        for (int i1 = 0, size = SYSTEM_PARTITIONS.size(); i1 < size; i1++) {
+                            SystemPartition partition = SYSTEM_PARTITIONS.get(i1);
+                            if (partition.containsPrivApp(scanFile)) {
+                                reparseFlags = systemParseFlags;
+                                rescanFlags = systemScanFlags | SCAN_AS_PRIVILEGED
+                                        | partition.scanFlag;
+                                break;
+                            }
+                            if (partition.containsApp(scanFile)) {
+                                reparseFlags = systemParseFlags;
+                                rescanFlags = systemScanFlags | partition.scanFlag;
+                                break;
+                            }
+                        }
+                        if (rescanFlags == 0) {
                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
                             continue;
                         }
-
                         mSettings.enableSystemPackageLPw(packageName);
 
                         try {
@@ -3271,7 +3047,7 @@
 
             // Resolve protected action filters. Only the setup wizard is allowed to
             // have a high priority filter for these actions.
-            mSetupWizardPackage = getSetupWizardPackageName();
+            mSetupWizardPackage = getSetupWizardPackageNameImpl();
             mComponentResolver.fixProtectedFilterPriorities();
 
             mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
@@ -7199,7 +6975,7 @@
      * @param intent
      * @return A filtered list of resolved activities.
      */
-    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
+    private List<ResolveInfo> applyPostResolutionFilter(@NonNull List<ResolveInfo> resolveInfos,
             String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid,
             boolean resolveForStart, int userId, Intent intent) {
         final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(userId);
@@ -7856,6 +7632,9 @@
             if (pkgName == null) {
                 final List<ResolveInfo> result =
                         mComponentResolver.queryReceivers(intent, resolvedType, flags, userId);
+                if (result == null) {
+                    return Collections.emptyList();
+                }
                 return applyPostResolutionFilter(
                         result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
                         intent);
@@ -7864,6 +7643,9 @@
             if (pkg != null) {
                 final List<ResolveInfo> result = mComponentResolver.queryReceivers(
                         intent, resolvedType, flags, pkg.receivers, userId);
+                if (result == null) {
+                    return Collections.emptyList();
+                }
                 return applyPostResolutionFilter(
                         result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
                         intent);
@@ -7958,15 +7740,25 @@
         synchronized (mLock) {
             String pkgName = intent.getPackage();
             if (pkgName == null) {
+                final List<ResolveInfo> resolveInfos = mComponentResolver.queryServices(intent,
+                        resolvedType, flags, userId);
+                if (resolveInfos == null) {
+                    return Collections.emptyList();
+                }
                 return applyPostServiceResolutionFilter(
-                        mComponentResolver.queryServices(intent, resolvedType, flags, userId),
+                        resolveInfos,
                         instantAppPkgName);
             }
             final PackageParser.Package pkg = mPackages.get(pkgName);
             if (pkg != null) {
+                final List<ResolveInfo> resolveInfos = mComponentResolver.queryServices(intent,
+                        resolvedType, flags, pkg.services,
+                        userId);
+                if (resolveInfos == null) {
+                    return Collections.emptyList();
+                }
                 return applyPostServiceResolutionFilter(
-                        mComponentResolver.queryServices(intent, resolvedType, flags, pkg.services,
-                                userId),
+                        resolveInfos,
                         instantAppPkgName);
             }
             return Collections.emptyList();
@@ -8076,15 +7868,25 @@
         synchronized (mLock) {
             String pkgName = intent.getPackage();
             if (pkgName == null) {
+                final List<ResolveInfo> resolveInfos = mComponentResolver.queryProviders(intent,
+                        resolvedType, flags, userId);
+                if (resolveInfos == null) {
+                    return Collections.emptyList();
+                }
                 return applyPostContentProviderResolutionFilter(
-                        mComponentResolver.queryProviders(intent, resolvedType, flags, userId),
+                        resolveInfos,
                         instantAppPkgName);
             }
             final PackageParser.Package pkg = mPackages.get(pkgName);
             if (pkg != null) {
+                final List<ResolveInfo> resolveInfos = mComponentResolver.queryProviders(intent,
+                        resolvedType, flags,
+                        pkg.providers, userId);
+                if (resolveInfos == null) {
+                    return Collections.emptyList();
+                }
                 return applyPostContentProviderResolutionFilter(
-                        mComponentResolver.queryProviders(intent, resolvedType, flags,
-                                pkg.providers, userId),
+                        resolveInfos,
                         instantAppPkgName);
             }
             return Collections.emptyList();
@@ -8375,15 +8177,20 @@
 
     @Override
     public boolean isInstantApp(String packageName, int userId) {
-        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
+        final int callingUid = Binder.getCallingUid();
+        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
                 true /* requireFullPermission */, false /* checkShell */,
                 "isInstantApp");
+
+        return isInstantAppInternal(packageName, userId, callingUid);
+    }
+
+    private boolean isInstantAppInternal(String packageName, @UserIdInt int userId,
+            int callingUid) {
         if (HIDE_EPHEMERAL_APIS) {
             return false;
         }
-
         synchronized (mLock) {
-            int callingUid = Binder.getCallingUid();
             if (Process.isIsolated(callingUid)) {
                 callingUid = mIsolatedOwners.get(callingUid);
             }
@@ -12665,14 +12472,10 @@
     }
 
     private void sendPackagesSuspendedForUser(String[] pkgList, int[] uidList, int userId,
-            boolean suspended, PersistableBundle launcherExtras) {
+            boolean suspended) {
         final Bundle extras = new Bundle(3);
         extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
         extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList);
-        if (launcherExtras != null) {
-            extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
-                    new Bundle(launcherExtras.deepCopy()));
-        }
         sendPackageBroadcast(
                 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
                         : Intent.ACTION_PACKAGES_UNSUSPENDED,
@@ -12937,8 +12740,6 @@
             if (ownerUid == callingUid) {
                 return;
             }
-            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
-                    + userId + " has an active DO or PO");
         }
 
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
@@ -12946,6 +12747,7 @@
 
         final int packageUid = getPackageUid(callingPackage, 0, userId);
         final boolean allowedPackageUid = packageUid == callingUid;
+        // TODO(b/139383163): remove special casing for shell and enforce INTERACT_ACROSS_USERS_FULL
         final boolean allowedShell = callingUid == SHELL_UID
                 && UserHandle.isSameApp(packageUid, callingUid);
 
@@ -12996,20 +12798,27 @@
                 unactionedPackages.add(packageName);
                 continue;
             }
+            boolean packageUnsuspended;
             synchronized (mLock) {
-                pkgSetting.setSuspended(suspended, callingPackage, dialogInfo, appExtras,
-                        launcherExtras, userId);
+                if (suspended) {
+                    pkgSetting.addOrUpdateSuspension(callingPackage, dialogInfo, appExtras,
+                            launcherExtras, userId);
+                } else {
+                    pkgSetting.removeSuspension(callingPackage, userId);
+                }
+                packageUnsuspended = !suspended && !pkgSetting.getSuspended(userId);
             }
-            changedPackagesList.add(packageName);
-            changedUids.add(UserHandle.getUid(userId, pkgSetting.appId));
+            if (suspended || packageUnsuspended) {
+                changedPackagesList.add(packageName);
+                changedUids.add(UserHandle.getUid(userId, pkgSetting.appId));
+            }
         }
 
         if (!changedPackagesList.isEmpty()) {
             final String[] changedPackages = changedPackagesList.toArray(
                     new String[changedPackagesList.size()]);
-            sendPackagesSuspendedForUser(
-                    changedPackages, changedUids.toArray(), userId, suspended, launcherExtras);
-            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
+            sendPackagesSuspendedForUser(changedPackages, changedUids.toArray(), userId, suspended);
+            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, userId);
             synchronized (mLock) {
                 scheduleWritePackageRestrictionsLocked(userId);
             }
@@ -13018,38 +12827,40 @@
     }
 
     @Override
-    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
+    public Bundle getSuspendedPackageAppExtras(String packageName, int userId) {
         final int callingUid = Binder.getCallingUid();
         if (getPackageUid(packageName, 0, userId) != callingUid) {
             throw new SecurityException("Calling package " + packageName
                     + " does not belong to calling uid " + callingUid);
         }
+        return getSuspendedPackageAppExtrasInternal(packageName, userId);
+    }
+
+    private Bundle getSuspendedPackageAppExtrasInternal(String packageName, int userId) {
         synchronized (mLock) {
             final PackageSetting ps = mSettings.mPackages.get(packageName);
-            if (ps == null || shouldFilterApplicationLocked(ps, callingUid, userId)) {
+            if (ps == null) {
                 throw new IllegalArgumentException("Unknown target package: " + packageName);
             }
-            final PackageUserState packageUserState = ps.readUserState(userId);
-            if (packageUserState.suspended) {
-                return packageUserState.suspendedAppExtras;
+            final PackageUserState pus = ps.readUserState(userId);
+            final Bundle allExtras = new Bundle();
+            if (pus.suspended) {
+                for (int i = 0; i < pus.suspendParams.size(); i++) {
+                    final PackageUserState.SuspendParams params = pus.suspendParams.valueAt(i);
+                    if (params != null && params.appExtras != null) {
+                        allExtras.putAll(params.appExtras);
+                    }
+                }
             }
-            return null;
+            return (allExtras.size() > 0) ? allExtras : null;
         }
     }
 
     private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
-            PersistableBundle appExtras, int userId) {
-        final String action;
-        final Bundle intentExtras = new Bundle();
-        if (suspended) {
-            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
-            if (appExtras != null) {
-                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
-                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
-            }
-        } else {
-            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
-        }
+            int userId) {
+        final String action = suspended
+                ? Intent.ACTION_MY_PACKAGE_SUSPENDED
+                : Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
         mHandler.post(() -> {
             try {
                 final IActivityManager am = ActivityManager.getService();
@@ -13060,6 +12871,16 @@
                 }
                 final int[] targetUserIds = new int[] {userId};
                 for (String packageName : affectedPackages) {
+                    final Bundle appExtras = suspended
+                            ? getSuspendedPackageAppExtrasInternal(packageName, userId)
+                            : null;
+                    final Bundle intentExtras;
+                    if (appExtras != null) {
+                        intentExtras = new Bundle(1);
+                        intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, appExtras);
+                    } else {
+                        intentExtras = null;
+                    }
                     doSendBroadcast(am, action, null, intentExtras,
                             Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
                             targetUserIds, false);
@@ -13092,57 +12913,32 @@
      * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
      * synchronously
      *
-     * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
-     * @param affectedUser The user for which the changes are taking place.
+     * @param suspendingPackage The suspending package
+     * @param userId The user for which the changes are taking place.
      */
-    void unsuspendForSuspendingPackage(final String packageName, int affectedUser) {
-        final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? mUserManager.getUserIds()
-                : new int[] {affectedUser};
-        for (int userId : userIds) {
-            unsuspendForSuspendingPackages(packageName::equals, userId);
-        }
-    }
-
-    /**
-     * Immediately unsuspends any packages in the given users not suspended by the platform or root.
-     * To be called when a profile owner or a device owner is added.
-     *
-     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
-     * synchronously
-     *
-     * @param userIds The users for which to unsuspend packages
-     */
-    void unsuspendForNonSystemSuspendingPackages(ArraySet<Integer> userIds) {
-        final int sz = userIds.size();
-        for (int i = 0; i < sz; i++) {
-            unsuspendForSuspendingPackages(
-                    (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage),
-                    userIds.valueAt(i));
-        }
-    }
-
-    private void unsuspendForSuspendingPackages(Predicate<String> packagePredicate, int userId) {
-        final List<String> affectedPackages = new ArrayList<>();
-        final IntArray affectedUids = new IntArray();
+    private void unsuspendForSuspendingPackage(String suspendingPackage, int userId) {
+        final List<String> unsuspendedPackages = new ArrayList<>();
+        final IntArray unsuspendedUids = new IntArray();
         synchronized (mLock) {
             for (PackageSetting ps : mSettings.mPackages.values()) {
                 final PackageUserState pus = ps.readUserState(userId);
-                if (pus.suspended && packagePredicate.test(pus.suspendingPackage)) {
-                    ps.setSuspended(false, null, null, null, null, userId);
-                    affectedPackages.add(ps.name);
-                    affectedUids.add(UserHandle.getUid(userId, ps.getAppId()));
+                if (pus.suspended) {
+                    ps.removeSuspension(suspendingPackage, userId);
+                    if (!ps.getSuspended(userId)) {
+                        unsuspendedPackages.add(ps.name);
+                        unsuspendedUids.add(UserHandle.getUid(userId, ps.getAppId()));
+                    }
                 }
             }
         }
-        if (!affectedPackages.isEmpty()) {
-            final String[] packageArray = affectedPackages.toArray(
-                    new String[affectedPackages.size()]);
-            sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
-            sendPackagesSuspendedForUser(
-                    packageArray, affectedUids.toArray(), userId, false, null);
-            // Write package restrictions immediately to avoid an inconsistent state.
-            mSettings.writePackageRestrictionsLPr(userId);
+        if (!unsuspendedPackages.isEmpty()) {
+            final String[] packageArray = unsuspendedPackages.toArray(
+                    new String[unsuspendedPackages.size()]);
+            sendMyPackageSuspendedOrUnsuspended(packageArray, false, userId);
+            sendPackagesSuspendedForUser(packageArray, unsuspendedUids.toArray(), userId, false);
         }
+        // Write package restrictions immediately to avoid an inconsistent state.
+        mSettings.writePackageRestrictionsLPr(userId);
     }
 
     @Override
@@ -13441,9 +13237,11 @@
      * @return verification timeout in milliseconds
      */
     private long getVerificationTimeout() {
-        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
-                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
-                DEFAULT_VERIFICATION_TIMEOUT);
+        long timeout = Global.getLong(mContext.getContentResolver(),
+                Global.PACKAGE_VERIFIER_TIMEOUT, DEFAULT_VERIFICATION_TIMEOUT);
+        // The setting can be used to increase the timeout but not decrease it, since that is
+        // equivalent to disabling the verifier.
+        return Math.max(timeout, DEFAULT_VERIFICATION_TIMEOUT);
     }
 
     /**
@@ -13474,22 +13272,18 @@
             return false;
         }
 
-        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
-
         // Check if installing from ADB
         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
             // Do not run verification in a test harness environment
             if (ActivityManager.isRunningInTestHarness()) {
                 return false;
             }
-            if (ensureVerifyAppsEnabled) {
+            if (isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS)) {
                 return true;
             }
             // Check if the developer does not want package verification for ADB installs
-            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
-                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
-                return false;
-            }
+            return Global.getInt(mContext.getContentResolver(),
+                    Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0;
         } else {
             // only when not installed from ADB, skip verification for instant apps when
             // the installer and verifier are the same.
@@ -13507,14 +13301,8 @@
                     } catch (SecurityException ignore) { }
                 }
             }
-        }
-
-        if (ensureVerifyAppsEnabled) {
             return true;
         }
-
-        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
-                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
     }
 
     @Override
@@ -15307,19 +15095,6 @@
         return disabled;
     }
 
-    @GuardedBy("mLock")
-    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
-            String installerPackageName) {
-        // Enable the parent package
-        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
-        // Enable the child packages
-        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
-        for (int i = 0; i < childCount; i++) {
-            PackageParser.Package childPkg = pkg.childPackages.get(i);
-            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
-        }
-    }
-
     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
             int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
         // Update the parent package setting
@@ -17929,8 +17704,14 @@
                 }
             }
             if (removedAppId >= 0) {
+                // If a system app's updates are uninstalled the UID is not actually removed. Some
+                // services need to know the package name affected.
+                if (extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
+                    extras.putString(Intent.EXTRA_PACKAGE_NAME, removedPackage);
+                }
+
                 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
-                        removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
+                        null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
                     null, null, broadcastUsers, instantUserIds);
             }
         }
@@ -18079,70 +17860,15 @@
     }
 
     static boolean locationIsPrivileged(String path) {
-        try {
-            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
-            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
-            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
-            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
-            final File privilegedSystemExtAppDir =
-                    new File(Environment.getSystemExtDirectory(), "priv-app");
-            return path.startsWith(privilegedAppDir.getCanonicalPath() + "/")
-                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath() + "/")
-                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath() + "/")
-                    || path.startsWith(privilegedProductAppDir.getCanonicalPath() + "/")
-                    || path.startsWith(privilegedSystemExtAppDir.getCanonicalPath() + "/");
-        } catch (IOException e) {
-            Slog.e(TAG, "Unable to access code path " + path);
+        for (int i = 0, size = SYSTEM_PARTITIONS.size(); i < size; i++) {
+            SystemPartition partition = SYSTEM_PARTITIONS.get(i);
+            if (partition.containsPrivPath(path)) {
+                return true;
+            }
         }
         return false;
     }
 
-    static boolean locationIsOem(String path) {
-        try {
-            return path.startsWith(Environment.getOemDirectory().getCanonicalPath() + "/");
-        } catch (IOException e) {
-            Slog.e(TAG, "Unable to access code path " + path);
-        }
-        return false;
-    }
-
-    static boolean locationIsVendor(String path) {
-        try {
-            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath() + "/")
-                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath() + "/");
-        } catch (IOException e) {
-            Slog.e(TAG, "Unable to access code path " + path);
-        }
-        return false;
-    }
-
-    static boolean locationIsProduct(String path) {
-        try {
-            return path.startsWith(Environment.getProductDirectory().getCanonicalPath() + "/");
-        } catch (IOException e) {
-            Slog.e(TAG, "Unable to access code path " + path);
-        }
-        return false;
-    }
-
-    static boolean locationIsSystemExt(String path) {
-        try {
-            return path.startsWith(
-              Environment.getSystemExtDirectory().getCanonicalPath() + "/");
-        } catch (IOException e) {
-            Slog.e(TAG, "Unable to access code path " + path);
-        }
-        return false;
-    }
-
-    static boolean locationIsOdm(String path) {
-        try {
-            return path.startsWith(Environment.getOdmDirectory().getCanonicalPath() + "/");
-        } catch (IOException e) {
-            Slog.e(TAG, "Unable to access code path " + path);
-        }
-        return false;
-    }
 
     /*
      * Tries to delete system package.
@@ -18253,23 +17979,15 @@
                 | PackageParser.PARSE_MUST_BE_APK
                 | PackageParser.PARSE_IS_SYSTEM_DIR;
         @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
-        if (locationIsPrivileged(codePathString)) {
-            scanFlags |= SCAN_AS_PRIVILEGED;
-        }
-        if (locationIsOem(codePathString)) {
-            scanFlags |= SCAN_AS_OEM;
-        }
-        if (locationIsVendor(codePathString)) {
-            scanFlags |= SCAN_AS_VENDOR;
-        }
-        if (locationIsProduct(codePathString)) {
-            scanFlags |= SCAN_AS_PRODUCT;
-        }
-        if (locationIsSystemExt(codePathString)) {
-            scanFlags |= SCAN_AS_SYSTEM_EXT;
-        }
-        if (locationIsOdm(codePathString)) {
-            scanFlags |= SCAN_AS_ODM;
+        for (int i = 0, size = SYSTEM_PARTITIONS.size(); i < size; i++) {
+            SystemPartition partition = SYSTEM_PARTITIONS.get(i);
+            if (partition.containsPath(codePathString)) {
+                scanFlags |= partition.scanFlag;
+                if (partition.containsPrivPath(codePathString)) {
+                    scanFlags |= SCAN_AS_PRIVILEGED;
+                }
+                break;
+            }
         }
 
         final File codePath = new File(codePathString);
@@ -18711,10 +18429,7 @@
                     false /*hidden*/,
                     0 /*distractionFlags*/,
                     false /*suspended*/,
-                    null /*suspendingPackage*/,
-                    null /*dialogInfo*/,
-                    null /*suspendedAppExtras*/,
-                    null /*suspendedLauncherExtras*/,
+                    null /*suspendParams*/,
                     false /*instantApp*/,
                     false /*virtualPreload*/,
                     null /*lastDisableAppCaller*/,
@@ -19962,7 +19677,7 @@
                 set, comp, userId);
     }
 
-    private @Nullable String getSetupWizardPackageName() {
+    private @Nullable String getSetupWizardPackageNameImpl() {
         final Intent intent = new Intent(Intent.ACTION_MAIN);
         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
 
@@ -20069,6 +19784,14 @@
         return systemCaptionsServiceComponentName.getPackageName();
     }
 
+    @Override
+    public String getSetupWizardPackageName() {
+        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
+            throw new SecurityException("Non-system caller");
+        }
+        return mPmInternal.getSetupWizardPackageName();
+    }
+
     public String getIncidentReportApproverPackageName() {
         return mContext.getString(R.string.config_incidentReportApproverPackage);
     }
@@ -20269,7 +19992,11 @@
             }
         }
         synchronized (mLock) {
-            scheduleWritePackageRestrictionsLocked(userId);
+            if ((flags & PackageManager.SYNCHRONOUS) != 0) {
+                flushPackageRestrictionsAsUserInternalLocked(userId);
+            } else {
+                scheduleWritePackageRestrictionsLocked(userId);
+            }
             updateSequenceNumberLP(pkgSetting, new int[] { userId });
             final long callingId = Binder.clearCallingIdentity();
             try {
@@ -20330,11 +20057,16 @@
         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
                 false /* checkShell */, "flushPackageRestrictions");
         synchronized (mLock) {
-            mSettings.writePackageRestrictionsLPr(userId);
-            mDirtyUsers.remove(userId);
-            if (mDirtyUsers.isEmpty()) {
-                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
-            }
+            flushPackageRestrictionsAsUserInternalLocked(userId);
+        }
+    }
+
+    @GuardedBy("mLock")
+    private void flushPackageRestrictionsAsUserInternalLocked(int userId) {
+        mSettings.writePackageRestrictionsLPr(userId);
+        mDirtyUsers.remove(userId);
+        if (mDirtyUsers.isEmpty()) {
+            mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
         }
     }
 
@@ -20544,7 +20276,7 @@
                     mInjector.getPermissionPolicyInternal();
             permissionPolicyInternal.setOnInitializedCallback(userId -> {
                 // The SDK updated case is already handled when we run during the ctor.
-                synchronized (mPackages) {
+                synchronized (mLock) {
                     mPermissionManager.updateAllPermissions(
                             StorageManager.UUID_PRIVATE_INTERNAL, false);
                 }
@@ -22558,10 +22290,19 @@
         }
     }
 
-    /** Called by UserManagerService */
-    void createNewUser(int userId, String[] disallowedPackages) {
+    /**
+     * Called by UserManagerService.
+     *
+     * @param installablePackages system packages that should be initially installed for this user,
+     *                            or {@code null} if all system packages should be installed
+     * @param disallowedPackages packages that should not be initially installed. Takes precedence
+     *                           over installablePackages.
+     */
+    void createNewUser(int userId, @Nullable Set<String> installablePackages,
+            String[] disallowedPackages) {
         synchronized (mInstallLock) {
-            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
+            mSettings.createNewUserLI(this, mInstaller, userId,
+                    installablePackages, disallowedPackages);
         }
         synchronized (mLock) {
             scheduleWritePackageRestrictionsLocked(userId);
@@ -23216,11 +22957,21 @@
         public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
             synchronized (mLock) {
                 final PackageSetting ps = mSettings.mPackages.get(packageName);
-                PersistableBundle launcherExtras = null;
+                final Bundle allExtras = new Bundle();
                 if (ps != null) {
-                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
+                    final PackageUserState pus = ps.readUserState(userId);
+                    if (pus.suspended) {
+                        for (int i = 0; i < pus.suspendParams.size(); i++) {
+                            final PackageUserState.SuspendParams params =
+                                    pus.suspendParams.valueAt(i);
+                            if (params != null && params.launcherExtras != null) {
+                                allExtras.putAll(params.launcherExtras);
+                            }
+                        }
+                    }
+
                 }
-                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
+                return (allExtras.size() > 0) ? allExtras : null;
             }
         }
 
@@ -23236,16 +22987,38 @@
         public String getSuspendingPackage(String suspendedPackage, int userId) {
             synchronized (mLock) {
                 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
-                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
+                if (ps != null) {
+                    final PackageUserState pus = ps.readUserState(userId);
+                    if (pus.suspended) {
+                        String suspendingPackage = null;
+                        for (int i = 0; i < pus.suspendParams.size(); i++) {
+                            suspendingPackage = pus.suspendParams.keyAt(i);
+                            if (PLATFORM_PACKAGE_NAME.equals(suspendingPackage)) {
+                                return suspendingPackage;
+                            }
+                        }
+                        return suspendingPackage;
+                    }
+                }
+                return null;
             }
         }
 
         @Override
-        public SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage, int userId) {
+        public SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage,
+                String suspendingPackage, int userId) {
             synchronized (mLock) {
                 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
-                return (ps != null) ? ps.readUserState(userId).dialogInfo : null;
+                if (ps != null) {
+                    final PackageUserState pus = ps.readUserState(userId);
+                    if (pus.suspended) {
+                        final PackageUserState.SuspendParams suspendParams =
+                                pus.suspendParams.get(suspendingPackage);
+                        return (suspendParams != null) ? suspendParams.dialogInfo : null;
+                    }
+                }
             }
+            return null;
         }
 
         @Override
@@ -23322,7 +23095,6 @@
                     usersWithPoOrDo.add(profileOwnerPackages.keyAt(i));
                 }
             }
-            unsuspendForNonSystemSuspendingPackages(usersWithPoOrDo);
         }
 
         @Override
@@ -23370,6 +23142,19 @@
         }
 
         @Override
+        public boolean setInstalled(PackageParser.Package pkg, @UserIdInt int userId,
+                boolean installed) {
+            synchronized (mLock) {
+                final PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
+                if (ps.getInstalled(userId) != installed) {
+                    ps.setInstalled(installed, userId);
+                    return true;
+                }
+                return false;
+            }
+        }
+
+        @Override
         public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
                 Intent origIntent, String resolvedType, String callingPackage,
                 Bundle verificationBundle, int userId) {
@@ -23380,19 +23165,20 @@
 
         @Override
         public void grantImplicitAccess(int userId, Intent intent,
-                int callingAppId, int targetAppId) {
+                int callingUid, int targetAppId) {
             synchronized (mLock) {
-                final PackageParser.Package callingPackage = getPackage(
-                        UserHandle.getUid(userId, callingAppId));
-                final PackageParser.Package targetPackage = getPackage(
-                        UserHandle.getUid(userId, targetAppId));
+                final PackageParser.Package callingPackage = getPackage(callingUid);
+                final PackageParser.Package targetPackage =
+                        getPackage(UserHandle.getUid(userId, targetAppId));
                 if (callingPackage == null || targetPackage == null) {
                     return;
                 }
 
-                if (isInstantApp(callingPackage.packageName, userId)) {
+                final boolean instantApp = isInstantAppInternal(callingPackage.packageName, userId,
+                        callingUid);
+                if (instantApp) {
                     mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
-                            callingAppId, targetAppId);
+                            UserHandle.getAppId(callingUid), targetAppId);
                 } else {
                     mAppsFilter.grantImplicitAccess(
                             callingPackage.packageName, targetPackage.packageName, userId);
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index fe529a1..1c1c947 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -496,6 +496,10 @@
             getErrPrintWriter().println("Error: no package specified");
             return 1;
         }
+        userId = translateUserId(userId, true /*allowAll*/, "runPath");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         return displayPackageFilePath(pkg, userId);
     }
 
@@ -718,6 +722,10 @@
 
         final String filter = getNextArg();
 
+        userId = translateUserId(userId, true /*allowAll*/, "runListPackages");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         @SuppressWarnings("unchecked")
         final ParceledListSlice<PackageInfo> slice =
                 mInterface.getInstalledPackages(getFlags, userId);
@@ -743,7 +751,7 @@
                     (!listThirdParty || !isSystem) &&
                     (!listApexOnly || isApex)) {
                 pw.print("package:");
-                if (showSourceDir && !isApex) {
+                if (showSourceDir) {
                     pw.print(info.applicationInfo.sourceDir);
                     pw.print("=");
                 }
@@ -1285,7 +1293,7 @@
 
     private int runInstallExisting() throws RemoteException {
         final PrintWriter pw = getOutPrintWriter();
-        int userId = UserHandle.USER_SYSTEM;
+        int userId = UserHandle.USER_CURRENT;
         int installFlags = PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS;
         String opt;
         boolean waitTillComplete = false;
@@ -1320,6 +1328,10 @@
             pw.println("Error: package name not specified");
             return 1;
         }
+        userId = translateUserId(userId, true /*allowAll*/, "runInstallExisting");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
 
         int installReason = PackageManager.INSTALL_REASON_UNKNOWN;
         try {
@@ -1945,6 +1957,10 @@
             getErrPrintWriter().println("Error: no package or component specified");
             return 1;
         }
+        userId = translateUserId(userId, true /*allowAll*/, "runSetEnabledSetting");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         ComponentName cn = ComponentName.unflattenFromString(pkg);
         if (cn == null) {
             mInterface.setApplicationEnabledSetting(pkg, state, 0, userId,
@@ -1974,6 +1990,10 @@
             getErrPrintWriter().println("Error: no package or component specified");
             return 1;
         }
+        userId = translateUserId(userId, true /*allowAll*/, "runSetHiddenSetting");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         mInterface.setApplicationHiddenSettingAsUser(pkg, state, userId);
         getOutPrintWriter().println("Package " + pkg + " new hidden state: "
                 + mInterface.getApplicationHiddenSettingAsUser(pkg, userId));
@@ -2043,8 +2063,14 @@
             info = null;
         }
         try {
+            userId = translateUserId(userId, true /*allowAll*/, "runSuspend");
+            if (userId == UserHandle.USER_ALL) {
+                userId = UserHandle.USER_SYSTEM;
+            }
             mInterface.setPackagesSuspendedAsUser(new String[]{packageName}, suspendedState,
-                    appExtras, launcherExtras, info, callingPackage, userId);
+                    ((appExtras.size() > 0) ? appExtras : null),
+                    ((launcherExtras.size() > 0) ? launcherExtras : null),
+                    info, callingPackage, userId);
             pw.println("Package " + packageName + " new suspended state: "
                     + mInterface.isPackageSuspendedForUser(packageName, userId));
             return 0;
@@ -2074,7 +2100,7 @@
             getErrPrintWriter().println("Error: no permission specified");
             return 1;
         }
-
+        userId = translateUserId(userId, true /*allowAll*/, "runGrantRevokePermission");
         if (grant) {
             mPermissionManager.grantRuntimePermission(pkg, perm, userId);
         } else {
@@ -2262,6 +2288,10 @@
                 return 1;
         }
 
+        userId = translateUserId(userId, true /*allowAll*/, "runSetAppLink");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         final PackageInfo info = mInterface.getPackageInfo(pkg, 0, userId);
         if (info == null) {
             getErrPrintWriter().println("Error: package " + pkg + " not found.");
@@ -2302,6 +2332,10 @@
             return 1;
         }
 
+        userId = translateUserId(userId, true /*allowAll*/, "runGetAppLink");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         final PackageInfo info = mInterface.getPackageInfo(pkg, 0, userId);
         if (info == null) {
             getErrPrintWriter().println("Error: package " + pkg + " not found.");
@@ -2381,6 +2415,7 @@
         int userId = -1;
         int flags = 0;
         String opt;
+        boolean preCreateOnly = false;
         while ((opt = getNextOption()) != null) {
             if ("--profileOf".equals(opt)) {
                 userId = UserHandle.parseUserArg(getNextArgRequired());
@@ -2394,6 +2429,8 @@
                 flags |= UserInfo.FLAG_GUEST;
             } else if ("--demo".equals(opt)) {
                 flags |= UserInfo.FLAG_DEMO;
+            } else if ("--pre-create-only".equals(opt)) {
+                preCreateOnly = true;
             } else {
                 getErrPrintWriter().println("Error: unknown option " + opt);
                 return 1;
@@ -2417,7 +2454,7 @@
             accm.addSharedAccountsFromParentUser(parentUserId, userId,
                     (Process.myUid() == Process.ROOT_UID) ? "root" : "com.android.shell");
         } else if (userId < 0) {
-            info = um.createUser(name, flags);
+            info = preCreateOnly ? um.preCreateUser(flags) : um.createUser(name, flags);
         } else {
             info = um.createProfileForUser(name, flags, userId, null);
         }
@@ -2666,8 +2703,7 @@
             }
             pkgName = componentName.getPackageName();
         }
-
-
+        userId = translateUserId(userId, true /*allowAll*/, "runInstallCreate");
         final CompletableFuture<Boolean> future = new CompletableFuture<>();
         final RemoteCallback callback = new RemoteCallback(res -> future.complete(res != null));
         try {
@@ -2763,8 +2799,10 @@
             }
         }
 
-        userId = translateUserId(userId, false /*allowAll*/, "runSetHarmfulAppWarning");
-
+        userId = translateUserId(userId, true /*allowAll*/, "runSetHarmfulAppWarning");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         final String packageName = getNextArgRequired();
         final String warning = getNextArg();
 
@@ -2786,8 +2824,10 @@
             }
         }
 
-        userId = translateUserId(userId, false /*allowAll*/, "runGetHarmfulAppWarning");
-
+        userId = translateUserId(userId, true /*allowAll*/, "runGetHarmfulAppWarning");
+        if (userId == UserHandle.USER_ALL) {
+            userId = UserHandle.USER_SYSTEM;
+        }
         final String packageName = getNextArgRequired();
         final CharSequence warning = mInterface.getHarmfulAppWarning(packageName, userId);
         if (!TextUtils.isEmpty(warning)) {
@@ -2824,7 +2864,7 @@
 
     private int doCreateSession(SessionParams params, String installerPackageName, int userId)
             throws RemoteException {
-        userId = translateUserId(userId, true /*allowAll*/, "runInstallCreate");
+        userId = translateUserId(userId, true /*allowAll*/, "doCreateSession");
         if (userId == UserHandle.USER_ALL) {
             userId = UserHandle.USER_SYSTEM;
             params.installFlags |= PackageManager.INSTALL_ALL_USERS;
@@ -3115,13 +3155,13 @@
         pw.println("  dump PACKAGE");
         pw.println("    Print various system state associated with the given PACKAGE.");
         pw.println("");
-        pw.println("  list features");
-        pw.println("    Prints all features of the system.");
-        pw.println("");
         pw.println("  has-feature FEATURE_NAME [version]");
         pw.println("    Prints true and returns exit status 0 when system has a FEATURE_NAME,");
         pw.println("    otherwise prints false and returns exit status 1");
         pw.println("");
+        pw.println("  list features");
+        pw.println("    Prints all features of the system.");
+        pw.println("");
         pw.println("  list instrumentation [-f] [TARGET-PACKAGE]");
         pw.println("    Prints all test packages; optionally only those targeting TARGET-PACKAGE");
         pw.println("    Options:");
@@ -3161,11 +3201,14 @@
         pw.println("      -u: list only the permissions users will see");
         pw.println("");
         pw.println("  list staged-sessions [--only-ready] [--only-sessionid] [--only-parent]");
-        pw.println("    Displays list of all staged sessions on device.");
+        pw.println("    Prints all staged sessions.");
         pw.println("      --only-ready: show only staged sessions that are ready");
         pw.println("      --only-sessionid: show only sessionId of each session");
         pw.println("      --only-parent: hide all children sessions");
         pw.println("");
+        pw.println("  list users");
+        pw.println("    Prints all users.");
+        pw.println("");
         pw.println("  resolve-activity [--brief] [--components] [--query-flags FLAGS]");
         pw.println("       [--user USER_ID] INTENT");
         pw.println("    Prints the activity that resolves to the given INTENT.");
@@ -3186,7 +3229,7 @@
         pw.println("       [-p INHERIT_PACKAGE] [--install-location 0/1/2]");
         pw.println("       [--install-reason 0/1/2/3/4] [--originating-uri URI]");
         pw.println("       [--referrer URI] [--abi ABI_NAME] [--force-sdk]");
-        pw.println("       [--preload] [--instantapp] [--full] [--dont-kill]");
+        pw.println("       [--preload] [--instant] [--full] [--dont-kill]");
         pw.println("       [--enable-rollback]");
         pw.println("       [--force-uuid internal|UUID] [--pkg PACKAGE] [-S BYTES]");
         pw.println("       [--apex] [--wait TIMEOUT]");
@@ -3209,7 +3252,7 @@
         pw.println("      --referrer: set URI that instigated the install of the app");
         pw.println("      --pkg: specify expected package name of app being installed");
         pw.println("      --abi: override the default ABI of the platform");
-        pw.println("      --instantapp: cause the app to be installed as an ephemeral install app");
+        pw.println("      --instant: cause the app to be installed as an ephemeral install app");
         pw.println("      --full: cause the app to be installed as a non-ephemeral full app");
         pw.println("      --install-location: force the install location:");
         pw.println("          0=auto, 1=internal only, 2=prefer external");
@@ -3222,11 +3265,20 @@
         pw.println("          for pre-reboot verification to complete. If TIMEOUT is not");
         pw.println("          specified it will wait for " + DEFAULT_WAIT_MS + " milliseconds.");
         pw.println("");
+        pw.println("  install-existing [--user USER_ID|all|current]");
+        pw.println("       [--instant] [--full] [--wait] [--restrict-permissions] PACKAGE");
+        pw.println("    Installs an existing application for a new user.  Options are:");
+        pw.println("      --user: install for the given user.");
+        pw.println("      --instant: install as an instant app");
+        pw.println("      --full: install as a full app");
+        pw.println("      --wait: wait until the package is installed");
+        pw.println("      --restrict-permissions: don't whitelist restricted permissions");
+        pw.println("");
         pw.println("  install-create [-lrtsfdg] [-i PACKAGE] [--user USER_ID|all|current]");
         pw.println("       [-p INHERIT_PACKAGE] [--install-location 0/1/2]");
         pw.println("       [--install-reason 0/1/2/3/4] [--originating-uri URI]");
         pw.println("       [--referrer URI] [--abi ABI_NAME] [--force-sdk]");
-        pw.println("       [--preload] [--instantapp] [--full] [--dont-kill]");
+        pw.println("       [--preload] [--instant] [--full] [--dont-kill]");
         pw.println("       [--force-uuid internal|UUID] [--pkg PACKAGE] [--apex] [-S BYTES]");
         pw.println("       [--multi-package] [--staged]");
         pw.println("    Like \"install\", but starts an install session.  Use \"install-write\"");
@@ -3315,8 +3367,11 @@
         pw.println("  trim-caches DESIRED_FREE_SPACE [internal|UUID]");
         pw.println("    Trim cache files to reach the given free space.");
         pw.println("");
+        pw.println("  list users");
+        pw.println("    Lists the current users.");
+        pw.println("");
         pw.println("  create-user [--profileOf USER_ID] [--managed] [--restricted] [--ephemeral]");
-        pw.println("      [--guest] USER_NAME");
+        pw.println("      [--guest] [--pre-create-only] USER_NAME");
         pw.println("    Create a new user with the given USER_NAME, printing the new user identifier");
         pw.println("    of the user.");
         pw.println("");
diff --git a/services/core/java/com/android/server/pm/PackageSettingBase.java b/services/core/java/com/android/server/pm/PackageSettingBase.java
index 029673f..0da6b54 100644
--- a/services/core/java/com/android/server/pm/PackageSettingBase.java
+++ b/services/core/java/com/android/server/pm/PackageSettingBase.java
@@ -29,6 +29,7 @@
 import android.content.pm.SuspendDialogInfo;
 import android.os.PersistableBundle;
 import android.service.pm.PackageProto;
+import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.SparseArray;
 import android.util.proto.ProtoOutputStream;
@@ -405,14 +406,28 @@
         return readUserState(userId).suspended;
     }
 
-    void setSuspended(boolean suspended, String suspendingPackage, SuspendDialogInfo dialogInfo,
+    void addOrUpdateSuspension(String suspendingPackage, SuspendDialogInfo dialogInfo,
             PersistableBundle appExtras, PersistableBundle launcherExtras, int userId) {
         final PackageUserState existingUserState = modifyUserState(userId);
-        existingUserState.suspended = suspended;
-        existingUserState.suspendingPackage = suspended ? suspendingPackage : null;
-        existingUserState.dialogInfo = suspended ? dialogInfo : null;
-        existingUserState.suspendedAppExtras = suspended ? appExtras : null;
-        existingUserState.suspendedLauncherExtras = suspended ? launcherExtras : null;
+        final PackageUserState.SuspendParams newSuspendParams =
+                PackageUserState.SuspendParams.getInstanceOrNull(dialogInfo, appExtras,
+                        launcherExtras);
+        if (existingUserState.suspendParams == null) {
+            existingUserState.suspendParams = new ArrayMap<>();
+        }
+        existingUserState.suspendParams.put(suspendingPackage, newSuspendParams);
+        existingUserState.suspended = true;
+    }
+
+    void removeSuspension(String suspendingPackage, int userId) {
+        final PackageUserState existingUserState = modifyUserState(userId);
+        if (existingUserState.suspendParams != null) {
+            existingUserState.suspendParams.remove(suspendingPackage);
+            if (existingUserState.suspendParams.size() == 0) {
+                existingUserState.suspendParams = null;
+            }
+        }
+        existingUserState.suspended = (existingUserState.suspendParams != null);
     }
 
     public boolean getInstantApp(int userId) {
@@ -433,9 +448,7 @@
 
     void setUserState(int userId, long ceDataInode, int enabled, boolean installed, boolean stopped,
             boolean notLaunched, boolean hidden, int distractionFlags, boolean suspended,
-            String suspendingPackage,
-            SuspendDialogInfo dialogInfo, PersistableBundle suspendedAppExtras,
-            PersistableBundle suspendedLauncherExtras, boolean instantApp,
+            ArrayMap<String, PackageUserState.SuspendParams> suspendParams, boolean instantApp,
             boolean virtualPreload, String lastDisableAppCaller,
             ArraySet<String> enabledComponents, ArraySet<String> disabledComponents,
             int domainVerifState, int linkGeneration, int installReason,
@@ -449,10 +462,7 @@
         state.hidden = hidden;
         state.distractionFlags = distractionFlags;
         state.suspended = suspended;
-        state.suspendingPackage = suspendingPackage;
-        state.dialogInfo = dialogInfo;
-        state.suspendedAppExtras = suspendedAppExtras;
-        state.suspendedLauncherExtras = suspendedLauncherExtras;
+        state.suspendParams = suspendParams;
         state.lastDisableAppCaller = lastDisableAppCaller;
         state.enabledComponents = enabledComponents;
         state.disabledComponents = disabledComponents;
@@ -467,9 +477,8 @@
     void setUserState(int userId, PackageUserState otherState) {
         setUserState(userId, otherState.ceDataInode, otherState.enabled, otherState.installed,
                 otherState.stopped, otherState.notLaunched, otherState.hidden,
-                otherState.distractionFlags, otherState.suspended, otherState.suspendingPackage,
-                otherState.dialogInfo, otherState.suspendedAppExtras,
-                otherState.suspendedLauncherExtras, otherState.instantApp,
+                otherState.distractionFlags, otherState.suspended, otherState.suspendParams,
+                otherState.instantApp,
                 otherState.virtualPreload, otherState.lastDisableAppCaller,
                 otherState.enabledComponents, otherState.disabledComponents,
                 otherState.domainVerificationStatus, otherState.appLinkGeneration,
@@ -633,7 +642,10 @@
             proto.write(PackageProto.UserInfoProto.DISTRACTION_FLAGS, state.distractionFlags);
             proto.write(PackageProto.UserInfoProto.IS_SUSPENDED, state.suspended);
             if (state.suspended) {
-                proto.write(PackageProto.UserInfoProto.SUSPENDING_PACKAGE, state.suspendingPackage);
+                for (int j = 0; j < state.suspendParams.size(); j++) {
+                    proto.write(PackageProto.UserInfoProto.SUSPENDING_PACKAGE,
+                            state.suspendParams.keyAt(j));
+                }
             }
             proto.write(PackageProto.UserInfoProto.IS_STOPPED, state.stopped);
             proto.write(PackageProto.UserInfoProto.IS_LAUNCHED, !state.notLaunched);
diff --git a/services/core/java/com/android/server/pm/SELinuxMMAC.java b/services/core/java/com/android/server/pm/SELinuxMMAC.java
index b94047e..b464988 100644
--- a/services/core/java/com/android/server/pm/SELinuxMMAC.java
+++ b/services/core/java/com/android/server/pm/SELinuxMMAC.java
@@ -78,6 +78,13 @@
         sMacPermissions.add(new File(
             Environment.getRootDirectory(), "/etc/selinux/plat_mac_permissions.xml"));
 
+        // SystemExt mac permissions (optional).
+        final File systemExtMacPermission = new File(
+                Environment.getSystemExtDirectory(), "/etc/selinux/system_ext_mac_permissions.xml");
+        if (systemExtMacPermission.exists()) {
+            sMacPermissions.add(systemExtMacPermission);
+        }
+
         // Product mac permissions (optional).
         final File productMacPermission = new File(
                 Environment.getProductDirectory(), "/etc/selinux/product_mac_permissions.xml");
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index 1873a4e..0db6e79 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -205,9 +205,22 @@
     private static final String TAG_DEFAULT_BROWSER = "default-browser";
     private static final String TAG_DEFAULT_DIALER = "default-dialer";
     private static final String TAG_VERSION = "version";
+    /**
+     * @deprecated Moved to {@link android.content.pm.PackageUserState.SuspendParams}
+     */
+    @Deprecated
     private static final String TAG_SUSPENDED_DIALOG_INFO = "suspended-dialog-info";
+    /**
+     * @deprecated Moved to {@link android.content.pm.PackageUserState.SuspendParams}
+     */
+    @Deprecated
     private static final String TAG_SUSPENDED_APP_EXTRAS = "suspended-app-extras";
+    /**
+     * @deprecated Moved to {@link android.content.pm.PackageUserState.SuspendParams}
+     */
+    @Deprecated
     private static final String TAG_SUSPENDED_LAUNCHER_EXTRAS = "suspended-launcher-extras";
+    private static final String TAG_SUSPEND_PARAMS = "suspend-params";
 
     public static final String ATTR_NAME = "name";
     public static final String ATTR_PACKAGE = "package";
@@ -660,10 +673,7 @@
                                 false /*hidden*/,
                                 0 /*distractionFlags*/,
                                 false /*suspended*/,
-                                null /*suspendingPackage*/,
-                                null /*dialogInfo*/,
-                                null /*suspendedAppExtras*/,
-                                null /*suspendedLauncherExtras*/,
+                                null /*suspendParams*/,
                                 instantApp,
                                 virtualPreload,
                                 null /*lastDisableAppCaller*/,
@@ -1550,10 +1560,7 @@
                                 false /*hidden*/,
                                 0 /*distractionFlags*/,
                                 false /*suspended*/,
-                                null /*suspendingPackage*/,
-                                null /*dialogInfo*/,
-                                null /*suspendedAppExtras*/,
-                                null /*suspendedLauncherExtras*/,
+                                null /*suspendParams*/,
                                 false /*instantApp*/,
                                 false /*virtualPreload*/,
                                 null /*lastDisableAppCaller*/,
@@ -1628,12 +1635,12 @@
                             ATTR_DISTRACTION_FLAGS, 0);
                     final boolean suspended = XmlUtils.readBooleanAttribute(parser, ATTR_SUSPENDED,
                             false);
-                    String suspendingPackage = parser.getAttributeValue(null,
+                    String oldSuspendingPackage = parser.getAttributeValue(null,
                             ATTR_SUSPENDING_PACKAGE);
                     final String dialogMessage = parser.getAttributeValue(null,
                             ATTR_SUSPEND_DIALOG_MESSAGE);
-                    if (suspended && suspendingPackage == null) {
-                        suspendingPackage = PLATFORM_PACKAGE_NAME;
+                    if (suspended && oldSuspendingPackage == null) {
+                        oldSuspendingPackage = PLATFORM_PACKAGE_NAME;
                     }
 
                     final boolean blockUninstall = XmlUtils.readBooleanAttribute(parser,
@@ -1663,9 +1670,10 @@
                     ArraySet<String> disabledComponents = null;
                     PersistableBundle suspendedAppExtras = null;
                     PersistableBundle suspendedLauncherExtras = null;
-                    SuspendDialogInfo suspendDialogInfo = null;
+                    SuspendDialogInfo oldSuspendDialogInfo = null;
 
                     int packageDepth = parser.getDepth();
+                    ArrayMap<String, PackageUserState.SuspendParams> suspendParamsMap = null;
                     while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
                             && (type != XmlPullParser.END_TAG
                             || parser.getDepth() > packageDepth)) {
@@ -1687,26 +1695,48 @@
                                 suspendedLauncherExtras = PersistableBundle.restoreFromXml(parser);
                                 break;
                             case TAG_SUSPENDED_DIALOG_INFO:
-                                suspendDialogInfo = SuspendDialogInfo.restoreFromXml(parser);
+                                oldSuspendDialogInfo = SuspendDialogInfo.restoreFromXml(parser);
+                                break;
+                            case TAG_SUSPEND_PARAMS:
+                                final String suspendingPackage = parser.getAttributeValue(null,
+                                        ATTR_SUSPENDING_PACKAGE);
+                                if (suspendingPackage == null) {
+                                    Slog.wtf(TAG, "No suspendingPackage found inside tag "
+                                            + TAG_SUSPEND_PARAMS);
+                                    continue;
+                                }
+                                if (suspendParamsMap == null) {
+                                    suspendParamsMap = new ArrayMap<>();
+                                }
+                                suspendParamsMap.put(suspendingPackage,
+                                        PackageUserState.SuspendParams.restoreFromXml(parser));
                                 break;
                             default:
                                 Slog.wtf(TAG, "Unknown tag " + parser.getName() + " under tag "
                                         + TAG_PACKAGE);
                         }
                     }
-                    if (suspendDialogInfo == null && !TextUtils.isEmpty(dialogMessage)) {
-                        suspendDialogInfo = new SuspendDialogInfo.Builder()
+                    if (oldSuspendDialogInfo == null && !TextUtils.isEmpty(dialogMessage)) {
+                        oldSuspendDialogInfo = new SuspendDialogInfo.Builder()
                                 .setMessage(dialogMessage)
                                 .build();
                     }
+                    if (suspended && suspendParamsMap == null) {
+                        final PackageUserState.SuspendParams suspendParams =
+                                PackageUserState.SuspendParams.getInstanceOrNull(
+                                        oldSuspendDialogInfo,
+                                        suspendedAppExtras,
+                                        suspendedLauncherExtras);
+                        suspendParamsMap = new ArrayMap<>();
+                        suspendParamsMap.put(oldSuspendingPackage, suspendParams);
+                    }
 
                     if (blockUninstall) {
                         setBlockUninstallLPw(userId, name, true);
                     }
                     ps.setUserState(userId, ceDataInode, enabled, installed, stopped, notLaunched,
-                            hidden, distractionFlags, suspended, suspendingPackage,
-                            suspendDialogInfo,
-                            suspendedAppExtras, suspendedLauncherExtras, instantApp, virtualPreload,
+                            hidden, distractionFlags, suspended, suspendParamsMap,
+                            instantApp, virtualPreload,
                             enabledCaller, enabledComponents, disabledComponents, verifState,
                             linkGeneration, installReason, harmfulAppWarning);
                 } else if (tagName.equals("preferred-activities")) {
@@ -2006,35 +2036,6 @@
                 }
                 if (ustate.suspended) {
                     serializer.attribute(null, ATTR_SUSPENDED, "true");
-                    if (ustate.suspendingPackage != null) {
-                        serializer.attribute(null, ATTR_SUSPENDING_PACKAGE,
-                                ustate.suspendingPackage);
-                    }
-                    if (ustate.dialogInfo != null) {
-                        serializer.startTag(null, TAG_SUSPENDED_DIALOG_INFO);
-                        ustate.dialogInfo.saveToXml(serializer);
-                        serializer.endTag(null, TAG_SUSPENDED_DIALOG_INFO);
-                    }
-                    if (ustate.suspendedAppExtras != null) {
-                        serializer.startTag(null, TAG_SUSPENDED_APP_EXTRAS);
-                        try {
-                            ustate.suspendedAppExtras.saveToXml(serializer);
-                        } catch (XmlPullParserException xmle) {
-                            Slog.wtf(TAG, "Exception while trying to write suspendedAppExtras for "
-                                    + pkg + ". Will be lost on reboot", xmle);
-                        }
-                        serializer.endTag(null, TAG_SUSPENDED_APP_EXTRAS);
-                    }
-                    if (ustate.suspendedLauncherExtras != null) {
-                        serializer.startTag(null, TAG_SUSPENDED_LAUNCHER_EXTRAS);
-                        try {
-                            ustate.suspendedLauncherExtras.saveToXml(serializer);
-                        } catch (XmlPullParserException xmle) {
-                            Slog.wtf(TAG, "Exception while trying to write suspendedLauncherExtras"
-                                    + " for " + pkg + ". Will be lost on reboot", xmle);
-                        }
-                        serializer.endTag(null, TAG_SUSPENDED_LAUNCHER_EXTRAS);
-                    }
                 }
                 if (ustate.instantApp) {
                     serializer.attribute(null, ATTR_INSTANT_APP, "true");
@@ -2067,6 +2068,19 @@
                     serializer.attribute(null, ATTR_HARMFUL_APP_WARNING,
                             ustate.harmfulAppWarning);
                 }
+                if (ustate.suspended) {
+                    for (int i = 0; i < ustate.suspendParams.size(); i++) {
+                        final String suspendingPackage = ustate.suspendParams.keyAt(i);
+                        serializer.startTag(null, TAG_SUSPEND_PARAMS);
+                        serializer.attribute(null, ATTR_SUSPENDING_PACKAGE, suspendingPackage);
+                        final PackageUserState.SuspendParams params =
+                                ustate.suspendParams.valueAt(i);
+                        if (params != null) {
+                            params.saveToXml(serializer);
+                        }
+                        serializer.endTag(null, TAG_SUSPEND_PARAMS);
+                    }
+                }
                 if (!ArrayUtils.isEmpty(ustate.enabledComponents)) {
                     serializer.startTag(null, TAG_ENABLED_COMPONENTS);
                     for (final String name : ustate.enabledComponents) {
@@ -4014,8 +4028,9 @@
         }
     }
 
-    void createNewUserLI(@NonNull PackageManagerService service,
-            @NonNull Installer installer, int userHandle, String[] disallowedPackages) {
+    void createNewUserLI(@NonNull PackageManagerService service, @NonNull Installer installer,
+            @UserIdInt int userHandle, @Nullable Set<String> installablePackages,
+            String[] disallowedPackages) {
         final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
                 Trace.TRACE_TAG_PACKAGE_MANAGER);
         t.traceBegin("createNewUser-" + userHandle);
@@ -4025,6 +4040,7 @@
         String[] seinfos;
         int[] targetSdkVersions;
         int packagesCount;
+        final boolean skipPackageWhitelist = installablePackages == null;
         synchronized (mLock) {
             Collection<PackageSetting> packages = mPackages.values();
             packagesCount = packages.size();
@@ -4040,6 +4056,7 @@
                     continue;
                 }
                 final boolean shouldInstall = ps.isSystem() &&
+                        (skipPackageWhitelist || installablePackages.contains(ps.name)) &&
                         !ArrayUtils.contains(disallowedPackages, ps.name) &&
                         !ps.pkg.applicationInfo.hiddenUntilInstalled;
                 // Only system apps are initially installed.
@@ -4763,13 +4780,6 @@
             pw.print(ps.getHidden(user.id));
             pw.print(" suspended=");
             pw.print(ps.getSuspended(user.id));
-            if (ps.getSuspended(user.id)) {
-                final PackageUserState pus = ps.readUserState(user.id);
-                pw.print(" suspendingPackage=");
-                pw.print(pus.suspendingPackage);
-                pw.print(" dialogInfo=");
-                pw.print(pus.dialogInfo);
-            }
             pw.print(" stopped=");
             pw.print(ps.getStopped(user.id));
             pw.print(" notLaunched=");
@@ -4781,6 +4791,23 @@
             pw.print(" virtual=");
             pw.println(ps.getVirtulalPreload(user.id));
 
+            if (ps.getSuspended(user.id)) {
+                pw.print(prefix);
+                pw.println("  Suspend params:");
+                final PackageUserState pus = ps.readUserState(user.id);
+                for (int i = 0; i < pus.suspendParams.size(); i++) {
+                    pw.print(prefix);
+                    pw.print("    suspendingPackage=");
+                    pw.print(pus.suspendParams.keyAt(i));
+                    final PackageUserState.SuspendParams params = pus.suspendParams.valueAt(i);
+                    if (params != null) {
+                        pw.print(" dialogInfo=");
+                        pw.print(params.dialogInfo);
+                    }
+                    pw.println();
+                }
+            }
+
             String[] overlayPaths = ps.getOverlayPaths(user.id);
             if (overlayPaths != null && overlayPaths.length > 0) {
                 pw.print(prefix); pw.println("  overlay paths:");
diff --git a/services/core/java/com/android/server/pm/ShortcutService.java b/services/core/java/com/android/server/pm/ShortcutService.java
index ebba128..8253b392 100644
--- a/services/core/java/com/android/server/pm/ShortcutService.java
+++ b/services/core/java/com/android/server/pm/ShortcutService.java
@@ -1200,12 +1200,20 @@
         return mUsers.get(userId) != null;
     }
 
+    private int mLastLockedUser = -1;
+
     /** Return the per-user state. */
     @GuardedBy("mLock")
     @NonNull
     ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
         if (!isUserUnlockedL(userId)) {
-            wtf("User still locked");
+            // Only do wtf once for each user. (until the user is unlocked)
+            if (userId != mLastLockedUser) {
+                wtf("User still locked");
+                mLastLockedUser = userId;
+            }
+        } else {
+            mLastLockedUser = -1;
         }
 
         ShortcutUser userPackages = mUsers.get(userId);
diff --git a/services/core/java/com/android/server/pm/StagingManager.java b/services/core/java/com/android/server/pm/StagingManager.java
index 1cea4ca..6b4ef69 100644
--- a/services/core/java/com/android/server/pm/StagingManager.java
+++ b/services/core/java/com/android/server/pm/StagingManager.java
@@ -318,7 +318,7 @@
         // The APEX part of the session is activated, proceed with the installation of APKs.
         try {
             Slog.d(TAG, "Installing APK packages in session " + session.sessionId);
-            installApksInSession(session, /* preReboot */ false);
+            installApksInSession(session);
         } catch (PackageManagerException e) {
             session.setStagedSessionFailed(e.error, e.getMessage());
 
@@ -410,72 +410,23 @@
         return apkSession;
     }
 
-    private void commitApkSession(@NonNull PackageInstallerSession apkSession,
-            PackageInstallerSession originalSession, boolean preReboot)
-            throws PackageManagerException {
-        final int errorCode = preReboot ? SessionInfo.STAGED_SESSION_VERIFICATION_FAILED
-                : SessionInfo.STAGED_SESSION_ACTIVATION_FAILED;
-        if (preReboot) {
-            final LocalIntentReceiverAsync receiver = new LocalIntentReceiverAsync(
-                    (Intent result) -> {
-                        int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
-                                PackageInstaller.STATUS_FAILURE);
-                        if (status != PackageInstaller.STATUS_SUCCESS) {
-                            final String errorMessage = result.getStringExtra(
-                                    PackageInstaller.EXTRA_STATUS_MESSAGE);
-                            Slog.e(TAG, "Failure to install APK staged session "
-                                    + originalSession.sessionId + " [" + errorMessage + "]");
-                            originalSession.setStagedSessionFailed(errorCode, errorMessage);
-                            return;
-                        }
-                        mPreRebootVerificationHandler.notifyPreRebootVerification_Apk_Complete(
-                                originalSession.sessionId);
-                    });
-            apkSession.commit(receiver.getIntentSender(), false);
-            return;
-        }
-
-        if ((apkSession.params.installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) {
-            // If rollback is available for this session, notify the rollback
-            // manager of the apk session so it can properly enable rollback.
-            final IRollbackManager rm = IRollbackManager.Stub.asInterface(
-                    ServiceManager.getService(Context.ROLLBACK_SERVICE));
-            try {
-                rm.notifyStagedApkSession(originalSession.sessionId, apkSession.sessionId);
-            } catch (RemoteException re) {
-                Slog.e(TAG, "Failed to notifyStagedApkSession for session: "
-                        + originalSession.sessionId, re);
-            }
-        }
-
-        final LocalIntentReceiverSync receiver = new LocalIntentReceiverSync();
-        apkSession.commit(receiver.getIntentSender(), false);
-        final Intent result = receiver.getResult();
-        final int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
-                PackageInstaller.STATUS_FAILURE);
-        if (status != PackageInstaller.STATUS_SUCCESS) {
-            final String errorMessage = result.getStringExtra(
-                    PackageInstaller.EXTRA_STATUS_MESSAGE);
-            Slog.e(TAG, "Failure to install APK staged session "
-                    + originalSession.sessionId + " [" + errorMessage + "]");
-            throw new PackageManagerException(errorCode, errorMessage);
-        }
-    }
-
-    private void installApksInSession(@NonNull PackageInstallerSession session,
-                                         boolean preReboot) throws PackageManagerException {
+    /**
+     * Extract apks in the given session into a new session. Returns {@code null} if there is no
+     * apks in the given session. Only parent session is returned for multi-package session.
+     */
+    @Nullable
+    private PackageInstallerSession extractApksInSession(PackageInstallerSession session,
+            boolean preReboot) throws PackageManagerException {
         final int errorCode = preReboot ? SessionInfo.STAGED_SESSION_VERIFICATION_FAILED
                 : SessionInfo.STAGED_SESSION_ACTIVATION_FAILED;
         if (!session.isMultiPackage() && !isApexSession(session)) {
-            // APK single-packaged staged session. Do a regular install.
-            PackageInstallerSession apkSession = createAndWriteApkSession(session, preReboot);
-            commitApkSession(apkSession, session, preReboot);
+            return createAndWriteApkSession(session, preReboot);
         } else if (session.isMultiPackage()) {
             // For multi-package staged sessions containing APKs, we identify which child sessions
             // contain an APK, and with those then create a new multi-package group of sessions,
             // carrying over all the session parameters and unmarking them as staged. On commit the
             // sessions will be installed atomically.
-            List<PackageInstallerSession> childSessions;
+            final List<PackageInstallerSession> childSessions;
             synchronized (mStagedSessions) {
                 childSessions =
                         Arrays.stream(session.getChildSessionIds())
@@ -487,18 +438,18 @@
             }
             if (childSessions.isEmpty()) {
                 // APEX-only multi-package staged session, nothing to do.
-                return;
+                return null;
             }
-            PackageInstaller.SessionParams params = session.params.copy();
+            final PackageInstaller.SessionParams params = session.params.copy();
             params.isStaged = false;
             if (preReboot) {
                 params.installFlags &= ~PackageManager.INSTALL_ENABLE_ROLLBACK;
             }
             // TODO(b/129744602): use the userid from the original session.
-            int apkParentSessionId = mPi.createSession(
+            final int apkParentSessionId = mPi.createSession(
                     params, session.getInstallerPackageName(),
                     0 /* UserHandle.SYSTEM */);
-            PackageInstallerSession apkParentSession = mPi.getSession(apkParentSessionId);
+            final PackageInstallerSession apkParentSession = mPi.getSession(apkParentSessionId);
             try {
                 apkParentSession.open();
             } catch (IOException e) {
@@ -519,9 +470,75 @@
                             "Failed to add a child session " + apkChildSession.sessionId);
                 }
             }
-            commitApkSession(apkParentSession, session, preReboot);
+            return apkParentSession;
         }
-        // APEX single-package staged session, nothing to do.
+        return null;
+    }
+
+    private void verifyApksInSession(PackageInstallerSession session)
+            throws PackageManagerException {
+
+        final PackageInstallerSession apksToVerify = extractApksInSession(
+                session,  /* preReboot */ true);
+        if (apksToVerify == null) {
+            return;
+        }
+
+        final LocalIntentReceiverAsync receiver = new LocalIntentReceiverAsync(
+                (Intent result) -> {
+                    int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
+                            PackageInstaller.STATUS_FAILURE);
+                    if (status != PackageInstaller.STATUS_SUCCESS) {
+                        final String errorMessage = result.getStringExtra(
+                                PackageInstaller.EXTRA_STATUS_MESSAGE);
+                        Slog.e(TAG, "Failure to verify APK staged session "
+                                + session.sessionId + " [" + errorMessage + "]");
+                        session.setStagedSessionFailed(
+                                SessionInfo.STAGED_SESSION_VERIFICATION_FAILED, errorMessage);
+                        return;
+                    }
+                    mPreRebootVerificationHandler.notifyPreRebootVerification_Apk_Complete(
+                            session.sessionId);
+                });
+
+        apksToVerify.commit(receiver.getIntentSender(), false);
+    }
+
+    private void installApksInSession(@NonNull PackageInstallerSession session)
+            throws PackageManagerException {
+
+        final PackageInstallerSession apksToInstall = extractApksInSession(
+                session, /* preReboot */ false);
+        if (apksToInstall == null) {
+            return;
+        }
+
+        if ((apksToInstall.params.installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) {
+            // If rollback is available for this session, notify the rollback
+            // manager of the apk session so it can properly enable rollback.
+            final IRollbackManager rm = IRollbackManager.Stub.asInterface(
+                    ServiceManager.getService(Context.ROLLBACK_SERVICE));
+            try {
+                rm.notifyStagedApkSession(session.sessionId, apksToInstall.sessionId);
+            } catch (RemoteException re) {
+                Slog.e(TAG, "Failed to notifyStagedApkSession for session: "
+                        + session.sessionId, re);
+            }
+        }
+
+        final LocalIntentReceiverSync receiver = new LocalIntentReceiverSync();
+        apksToInstall.commit(receiver.getIntentSender(), false);
+        final Intent result = receiver.getResult();
+        final int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
+                PackageInstaller.STATUS_FAILURE);
+        if (status != PackageInstaller.STATUS_SUCCESS) {
+            final String errorMessage = result.getStringExtra(
+                    PackageInstaller.EXTRA_STATUS_MESSAGE);
+            Slog.e(TAG, "Failure to install APK staged session "
+                    + session.sessionId + " [" + errorMessage + "]");
+            throw new PackageManagerException(
+                    SessionInfo.STAGED_SESSION_ACTIVATION_FAILED, errorMessage);
+        }
     }
 
     void commitSession(@NonNull PackageInstallerSession session) {
@@ -836,8 +853,8 @@
                 Slog.d(TAG, "Running a pre-reboot verification for APKs in session "
                         + session.sessionId + " by performing a dry-run install");
 
-                // installApksInSession will notify the handler when APK verification is complete
-                installApksInSession(session, /* preReboot */ true);
+                // verifyApksInSession will notify the handler when APK verification is complete
+                verifyApksInSession(session);
                 // TODO(b/118865310): abort the session on apexd.
             } catch (PackageManagerException e) {
                 session.setStagedSessionFailed(e.error, e.getMessage());
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index 9371c44..95baa01 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -41,6 +41,7 @@
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ShortcutServiceInternal;
 import android.content.pm.UserInfo;
+import android.content.pm.UserInfo.UserInfoFlag;
 import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.os.Binder;
@@ -158,6 +159,7 @@
     private static final String ATTR_SERIAL_NO = "serialNumber";
     private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
     private static final String ATTR_PARTIAL = "partial";
+    private static final String ATTR_PRE_CREATED = "preCreated";
     private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
     private static final String ATTR_USER_VERSION = "version";
     private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
@@ -207,7 +209,8 @@
             | UserInfo.FLAG_DEMO;
 
     @VisibleForTesting
-    static final int MIN_USER_ID = 10;
+    static final int MIN_USER_ID = UserHandle.MIN_SECONDARY_USER_ID;
+
     // We need to keep process uid within Integer.MAX_VALUE.
     @VisibleForTesting
     static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
@@ -250,6 +253,9 @@
 
     private static final IBinder mUserRestriconToken = new Binder();
 
+    /** Installs system packages based on user-type. */
+    private final UserSystemPackageInstaller mSystemPackageInstaller;
+
     /**
      * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
      */
@@ -550,6 +556,7 @@
             readUserListLP();
             sInstance = this;
         }
+        mSystemPackageInstaller = new UserSystemPackageInstaller(this);
         mLocalService = new LocalService();
         LocalServices.addService(UserManagerInternal.class, mLocalService);
         mLockPatternUtils = new LockPatternUtils(mContext);
@@ -593,7 +600,8 @@
             final int userSize = mUsers.size();
             for (int i = 0; i < userSize; i++) {
                 UserInfo ui = mUsers.valueAt(i).info;
-                if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
+                if ((ui.partial || ui.guestToRemove || (ui.isEphemeral() && !ui.preCreated))
+                        && i != 0) {
                     partials.add(ui);
                     addRemovingUserIdLocked(ui.id);
                     ui.partial = true;
@@ -656,20 +664,25 @@
         return null;
     }
 
-    @Override
     public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
+        return getUsers(/*excludePartial= */ true, excludeDying, /* excludePreCreated= */ true);
+    }
+
+    @Override
+    public @NonNull List<UserInfo> getUsers(boolean excludePartial, boolean excludeDying,
+            boolean excludePreCreated) {
         checkManageOrCreateUsersPermission("query users");
         synchronized (mUsersLock) {
             ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
             final int userSize = mUsers.size();
             for (int i = 0; i < userSize; i++) {
                 UserInfo ui = mUsers.valueAt(i).info;
-                if (ui.partial) {
+                if ((excludePartial && ui.partial)
+                        || (excludeDying && mRemovingUserIds.get(ui.id))
+                        || (excludePreCreated && ui.preCreated)) {
                     continue;
                 }
-                if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
-                    users.add(userWithName(ui));
-                }
+                users.add(userWithName(ui));
             }
             return users;
         }
@@ -1192,7 +1205,7 @@
 
     private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
             String name) {
-        int callingUserId = UserHandle.getCallingUserId();
+        final int callingUserId = UserHandle.getCallingUserId();
         if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
                 hasManageUsersPermission()) {
             return;
@@ -1206,7 +1219,7 @@
 
     @Override
     public boolean isDemoUser(@UserIdInt int userId) {
-        int callingUserId = UserHandle.getCallingUserId();
+        final int callingUserId = UserHandle.getCallingUserId();
         if (callingUserId != userId && !hasManageUsersPermission()) {
             throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
                     + " is a demo user");
@@ -1218,6 +1231,19 @@
     }
 
     @Override
+    public boolean isPreCreated(@UserIdInt int userId) {
+        final int callingUserId = UserHandle.getCallingUserId();
+        if (callingUserId != userId && !hasManageUsersPermission()) {
+            throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
+                    + " is pre-created");
+        }
+        synchronized (mUsersLock) {
+            UserInfo userInfo = getUserInfoLU(userId);
+            return userInfo != null && userInfo.preCreated;
+        }
+    }
+
+    @Override
     public boolean isRestricted() {
         synchronized (mUsersLock) {
             return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
@@ -1867,7 +1893,7 @@
         // Skip over users being removed
         for (int i = 0; i < totalUserCount; i++) {
             UserInfo user = mUsers.valueAt(i).info;
-            if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
+            if (!mRemovingUserIds.get(user.id) && !user.isGuest() && !user.preCreated) {
                 aliveUserCount++;
             }
         }
@@ -2358,6 +2384,9 @@
         if (userInfo.partial) {
             serializer.attribute(null, ATTR_PARTIAL, "true");
         }
+        if (userInfo.preCreated) {
+            serializer.attribute(null, ATTR_PRE_CREATED, "true");
+        }
         if (userInfo.guestToRemove) {
             serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
         }
@@ -2514,6 +2543,7 @@
         int profileBadge = 0;
         int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
         boolean partial = false;
+        boolean preCreated = false;
         boolean guestToRemove = false;
         boolean persistSeedData = false;
         String seedAccountName = null;
@@ -2558,6 +2588,10 @@
             if ("true".equals(valueString)) {
                 partial = true;
             }
+            valueString = parser.getAttributeValue(null, ATTR_PRE_CREATED);
+            if ("true".equals(valueString)) {
+                preCreated = true;
+            }
             valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
             if ("true".equals(valueString)) {
                 guestToRemove = true;
@@ -2611,6 +2645,7 @@
         userInfo.lastLoggedInTime = lastLoggedInTime;
         userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
         userInfo.partial = partial;
+        userInfo.preCreated = preCreated;
         userInfo.guestToRemove = guestToRemove;
         userInfo.profileGroupId = profileGroupId;
         userInfo.profileBadge = profileBadge;
@@ -2682,7 +2717,8 @@
     public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags,
             @UserIdInt int userId, String[] disallowedPackages) {
         checkManageOrCreateUsersPermission(flags);
-        return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
+        return createUserInternalUnchecked(name, flags, userId, /* preCreate= */ false,
+                disallowedPackages);
     }
 
     @Override
@@ -2697,12 +2733,27 @@
         return createUserInternal(name, flags, UserHandle.USER_NULL);
     }
 
-    private UserInfo createUserInternal(String name, int flags, int parentId) {
+    @Override
+    public UserInfo preCreateUser(int flags) {
+        checkManageOrCreateUsersPermission(flags);
+
+        Preconditions.checkArgument(!UserInfo.isManagedProfile(flags),
+                "cannot pre-create managed profiles");
+
+        Slog.i(LOG_TAG, "Pre-creating user with flags " + UserInfo.flagsToString(flags));
+
+        return createUserInternalUnchecked(/* name= */ null, flags,
+                /* parentId= */ UserHandle.USER_NULL, /* preCreate= */ true,
+                /* disallowedPackages= */ null);
+    }
+
+    private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
+            @UserIdInt int parentId) {
         return createUserInternal(name, flags, parentId, null);
     }
 
-    private UserInfo createUserInternal(String name, int flags, int parentId,
-            String[] disallowedPackages) {
+    private UserInfo createUserInternal(@Nullable String name, @UserInfoFlag int flags,
+            @UserIdInt int parentId, @Nullable String[] disallowedPackages) {
         String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
                 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
                 : UserManager.DISALLOW_ADD_USER;
@@ -2710,21 +2761,56 @@
             Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
             return null;
         }
-        return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
+        return createUserInternalUnchecked(name, flags, parentId, /* preCreate= */ false,
+                disallowedPackages);
     }
 
-    private UserInfo createUserInternalUnchecked(@Nullable String name, int flags,
-            int parentId, @Nullable String[] disallowedPackages) {
-        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
-        t.traceBegin("createUser");
-        UserInfo userInfo =
-                createUserInternalUncheckedNoTracing(name, flags, parentId, disallowedPackages, t);
-        t.traceEnd();
-        return userInfo;
+    private UserInfo createUserInternalUnchecked(@Nullable String name, @UserInfoFlag int flags,
+            @UserIdInt int parentId, boolean preCreate,
+            @Nullable String[] disallowedPackages) {
+        final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
+        t.traceBegin("createUser-" + flags);
+        try {
+            return createUserInternalUncheckedNoTracing(name, flags, parentId, preCreate,
+                disallowedPackages, t);
+        } finally {
+            t.traceEnd();
+        }
     }
 
-    private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name, int flags,
-            int parentId, @Nullable String[] disallowedPackages, @NonNull TimingsTraceAndSlog t) {
+    private UserInfo createUserInternalUncheckedNoTracing(@Nullable String name,
+            @UserInfoFlag int flags, @UserIdInt int parentId, boolean preCreate,
+            @Nullable String[] disallowedPackages, @NonNull TimingsTraceAndSlog t) {
+
+        // First try to use a pre-created user (if available).
+        // NOTE: currently we don't support pre-created managed profiles
+        if (!preCreate && (parentId < 0 && !UserInfo.isManagedProfile(flags))) {
+            final UserData preCreatedUserData;
+            synchronized (mUsersLock) {
+                preCreatedUserData = getPreCreatedUserLU(flags);
+            }
+            if (preCreatedUserData != null) {
+                final UserInfo preCreatedUser = preCreatedUserData.info;
+                Log.i(LOG_TAG, "Reusing pre-created user " + preCreatedUser.id + " for flags + "
+                        + UserInfo.flagsToString(flags));
+                if (DBG) {
+                    Log.d(LOG_TAG, "pre-created user flags: "
+                            + UserInfo.flagsToString(preCreatedUser.flags)
+                            + " new-user flags: " + UserInfo.flagsToString(flags));
+                }
+                preCreatedUser.name = name;
+                preCreatedUser.preCreated = false;
+                preCreatedUser.creationTime = getCreationTime();
+
+                dispatchUserAddedIntent(preCreatedUser);
+
+                writeUserLP(preCreatedUserData);
+                writeUserListLP();
+
+                return preCreatedUser;
+            }
+        }
+
         DeviceStorageMonitorInternal dsm = LocalServices
                 .getService(DeviceStorageMonitorInternal.class);
         if (dsm.isMemoryLow()) {
@@ -2732,8 +2818,8 @@
             return null;
         }
 
-        final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
-        final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
+        final boolean isGuest = UserInfo.isGuest(flags);
+        final boolean isManagedProfile = UserInfo.isManagedProfile(flags);
         final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
         final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
         final long ident = Binder.clearCallingIdentity();
@@ -2754,8 +2840,8 @@
                     return null;
                 }
                 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
-                    // If we're not adding a guest/demo user or a managed profile and the limit has
-                    // been reached, cannot add a user.
+                    // If we're not adding a guest/demo user or a managed profile,
+                    // and the limit has been reached, cannot add a user.
                     Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
                     return null;
                 }
@@ -2790,8 +2876,7 @@
 
                 userId = getNextAvailableId();
                 Environment.getUserSystemDirectory(userId).mkdirs();
-                boolean ephemeralGuests = Resources.getSystem()
-                        .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
+                boolean ephemeralGuests = areGuestUsersEphemeral();
 
                 synchronized (mUsersLock) {
                     // Add ephemeral flag to guests/users if required. Also inherit it from parent.
@@ -2802,9 +2887,9 @@
 
                     userInfo = new UserInfo(userId, name, null, flags);
                     userInfo.serialNumber = mNextSerialNumber++;
-                    long now = System.currentTimeMillis();
-                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
+                    userInfo.creationTime = getCreationTime();
                     userInfo.partial = true;
+                    userInfo.preCreated = preCreate;
                     userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
                     if (isManagedProfile && parentId != UserHandle.USER_NULL) {
                         userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
@@ -2842,8 +2927,10 @@
                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
             t.traceEnd();
 
+            final Set<String> installablePackages =
+                    mSystemPackageInstaller.getInstallablePackagesForUserType(flags);
             t.traceBegin("PM.createNewUser");
-            mPm.createNewUser(userId, disallowedPackages);
+            mPm.createNewUser(userId, installablePackages, disallowedPackages);
             t.traceEnd();
 
             userInfo.partial = false;
@@ -2863,20 +2950,104 @@
 
             t.traceBegin("PM.onNewUserCreated");
             mPm.onNewUserCreated(userId);
-            t.traceEnd();
 
-            Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
-            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
-            mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
-                    android.Manifest.permission.MANAGE_USERS);
-            MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
-                    : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
+            if (preCreate) {
+                // Must start user (which will be stopped right away, through
+                // UserController.finishUserUnlockedCompleted) so services can properly
+                // intialize it.
+                // TODO(b/140750212): in the long-term, we should add a onCreateUser() callback
+                // on SystemService instead.
+                Slog.i(LOG_TAG, "starting pre-created user " + userInfo.toFullString());
+                final IActivityManager am = ActivityManager.getService();
+                try {
+                    am.startUserInBackground(userId);
+                } catch (RemoteException e) {
+                    Slog.w(LOG_TAG, "could not start pre-created user " + userId, e);
+                }
+            } else {
+                dispatchUserAddedIntent(userInfo);
+            }
+
         } finally {
             Binder.restoreCallingIdentity(ident);
         }
+
+        // TODO(b/140750212): it's possible to reach "max users overflow" when the user is created
+        // "from scratch" (i.e., not from a pre-created user) and reaches the maximum number of
+        // users without counting the pre-created one. Then when the pre-created is converted, the
+        // "effective" number of max users is exceeds. Example:
+        // Max: 3 Current: 2 full (u0 and u10) + 1 pre-created (u11)
+        // Step 1: create(/* flags doesn't match u11 */): u12 is created, "effective max" is now 3
+        //         (u0, u10, u12) but "real" max is 4 (u0, u10, u11, u12)
+        // Step 2: create(/* flags match u11 */): u11 is converted, now "effective max" is also 4
+        //         (u0, u10, u11, u12)
+        // One way to avoid this issue is by removing a pre-created user from the pool when the
+        // "real" max exceeds the max here.
+
         return userInfo;
     }
 
+    /** Install/uninstall system packages for all users based on their user-type, as applicable. */
+    boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade) {
+        return mSystemPackageInstaller.installWhitelistedSystemPackages(isFirstBoot, isUpgrade);
+    }
+
+    private long getCreationTime() {
+        final long now = System.currentTimeMillis();
+        return (now > EPOCH_PLUS_30_YEARS) ? now : 0;
+    }
+
+    private void dispatchUserAddedIntent(@NonNull UserInfo userInfo) {
+        Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
+        addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
+        mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
+                android.Manifest.permission.MANAGE_USERS);
+        MetricsLogger.count(mContext, userInfo.isGuest() ? TRON_GUEST_CREATED
+                : (userInfo.isDemo() ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
+    }
+
+    private boolean areGuestUsersEphemeral() {
+        return Resources.getSystem()
+                .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
+    }
+
+    /**
+     * Gets a pre-created user for the given flag.
+     *
+     * <p>Should be used only during user creation, so the pre-created user can be used (instead of
+     * creating and initializing a new user from scratch).
+     */
+    // TODO(b/140750212): add unit test
+    @GuardedBy("mUsersLock")
+    private @Nullable UserData getPreCreatedUserLU(@UserInfoFlag int flags) {
+        if (DBG) {
+            Slog.d(LOG_TAG, "getPreCreatedUser(): initialFlags= " + UserInfo.flagsToString(flags));
+        }
+        flags |= UserInfo.FLAG_FULL;
+        if (UserInfo.isGuest(flags) && areGuestUsersEphemeral()) {
+            flags |= UserInfo.FLAG_EPHEMERAL;
+        }
+        if (DBG) {
+            Slog.d(LOG_TAG, "getPreCreatedUser(): targetFlags= " + UserInfo.flagsToString(flags));
+        }
+        final int userSize = mUsers.size();
+        for (int i = 0; i < userSize; i++) {
+            final UserData user = mUsers.valueAt(i);
+            if (DBG) Slog.d(LOG_TAG, i + ":" + user.info.toFullString());
+            if (user.info.preCreated
+                    && (user.info.flags & ~UserInfo.FLAG_INITIALIZED) == flags) {
+                if (!user.info.isInitialized()) {
+                    Slog.w(LOG_TAG, "found pre-created user for flags "
+                            + "" + UserInfo.flagsToString(flags)
+                            + ", but it's not initialized yet: " + user.info.toFullString());
+                    continue;
+                }
+                return user;
+            }
+        }
+        return null;
+    }
+
     @VisibleForTesting
     UserData putUserInfo(UserInfo userInfo) {
         final UserData userData = new UserData();
@@ -3717,7 +3888,7 @@
         try {
             switch(cmd) {
                 case "list":
-                    return runList(pw);
+                    return runList(pw, shell);
                 default:
                     return shell.handleDefaultCommands(cmd);
             }
@@ -3727,17 +3898,58 @@
         return -1;
     }
 
-    private int runList(PrintWriter pw) throws RemoteException {
+    private int runList(PrintWriter pw, Shell shell) throws RemoteException {
+        boolean all = false;
+        boolean verbose = false;
+        String opt;
+        while ((opt = shell.getNextOption()) != null) {
+            switch (opt) {
+                case "-v":
+                    verbose = true;
+                    break;
+                case "--all":
+                    all = true;
+                    break;
+                default:
+                    pw.println("Invalid option: " + opt);
+                    return -1;
+            }
+        }
         final IActivityManager am = ActivityManager.getService();
-        final List<UserInfo> users = getUsers(false);
+        final List<UserInfo> users = getUsers(/* excludePartial= */ !all,
+                /* excludingDying=*/ false, /* excludePreCreated= */ !all);
         if (users == null) {
             pw.println("Error: couldn't get users");
             return 1;
         } else {
-            pw.println("Users:");
-            for (int i = 0; i < users.size(); i++) {
-                String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
-                pw.println("\t" + users.get(i).toString() + running);
+            final int size = users.size();
+            int currentUser = UserHandle.USER_NULL;
+            if (verbose) {
+                pw.printf("%d users:\n\n", size);
+                currentUser = am.getCurrentUser().id;
+            } else {
+                // NOTE: the standard "list users" command is used by integration tests and
+                // hence should not be changed. If you need to add more info, use the
+                // verbose option.
+                pw.println("Users:");
+            }
+            for (int i = 0; i < size; i++) {
+                final UserInfo user = users.get(i);
+                final boolean running = am.isUserRunning(user.id, 0);
+                final boolean current = user.id == currentUser;
+                if (verbose) {
+                    pw.printf("%d: id=%d, name=%s, flags=%s%s%s%s%s\n", i, user.id, user.name,
+                            UserInfo.flagsToString(user.flags),
+                            running ? " (running)" : "",
+                            user.partial ? " (partial)" : "",
+                            user.preCreated ? " (pre-created)" : "",
+                            current ? " (current)" : "");
+                } else {
+                    // NOTE: the standard "list users" command is used by integration tests and
+                    // hence should not be changed. If you need to add more info, use the
+                    // verbose option.
+                    pw.printf("\t%s%s\n", user, running ? " running" : "");
+                }
             }
             return 0;
         }
@@ -3774,6 +3986,9 @@
                     if (userInfo.partial) {
                         pw.print(" <partial>");
                     }
+                    if (userInfo.preCreated) {
+                        pw.print(" <pre-created>");
+                    }
                     pw.println();
                     pw.print("    Flags: "); pw.print(userInfo.flags); pw.print(" (");
                     pw.print(UserInfo.flagsToString(userInfo.flags)); pw.println(")");
@@ -3856,13 +4071,17 @@
 
         // Dump some capabilities
         pw.println();
-        pw.println("  Max users: " + UserManager.getMaxSupportedUsers());
+        pw.print("  Max users: " + UserManager.getMaxSupportedUsers());
+        pw.println(" (limit reached: " + isUserLimitReached() + ")");
         pw.println("  Supports switchable users: " + UserManager.supportsMultipleUsers());
-        pw.println("  All guests ephemeral: " + Resources.getSystem().getBoolean(
-                com.android.internal.R.bool.config_guestUserEphemeral));
+        pw.println("  All guests ephemeral: " + areGuestUsersEphemeral());
         pw.println("  Is split-system user: " + UserManager.isSplitSystemUser());
         pw.println("  Is headless-system mode: " + UserManager.isHeadlessSystemUserMode());
         pw.println("  User version: " + mUserVersion);
+
+        // Dump package whitelist
+        pw.println();
+        mSystemPackageInstaller.dump(pw);
     }
 
     private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
@@ -3964,6 +4183,13 @@
         }
 
         @Override
+        public boolean isDeviceManaged() {
+            synchronized (mUsersLock) {
+                return mIsDeviceManaged;
+            }
+        }
+
+        @Override
         public void setUserManaged(@UserIdInt int userId, boolean isManaged) {
             synchronized (mUsersLock) {
                 mIsUserManaged.put(userId, isManaged);
@@ -3971,6 +4197,13 @@
         }
 
         @Override
+        public boolean isUserManaged(@UserIdInt int userId) {
+            synchronized (mUsersLock) {
+                return mIsUserManaged.get(userId);
+            }
+        }
+
+        @Override
         public void setUserIcon(@UserIdInt int userId, Bitmap bitmap) {
             long ident = Binder.clearCallingIdentity();
             try {
@@ -4047,7 +4280,7 @@
         public UserInfo createUserEvenWhenDisallowed(String name, int flags,
                 String[] disallowedPackages) {
             UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
-                    disallowedPackages);
+                    /* preCreated= */ false, disallowedPackages);
             // Keep this in sync with UserManager.createUser
             if (user != null && !user.isAdmin() && !user.isDemo()) {
                 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
@@ -4190,6 +4423,7 @@
             return restrictions != null && restrictions.getBoolean(restrictionKey);
         }
 
+        @Override
         public @Nullable UserInfo getUserInfo(@UserIdInt int userId) {
             UserData userData;
             synchronized (mUsersLock) {
@@ -4240,7 +4474,7 @@
             pw.println("  help");
             pw.println("    Print this help text.");
             pw.println("");
-            pw.println("  list");
+            pw.println("  list [-v] [-all]");
             pw.println("    Prints all users on the system.");
         }
     }
diff --git a/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java b/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java
new file mode 100644
index 0000000..036d1e8
--- /dev/null
+++ b/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java
@@ -0,0 +1,459 @@
+/*
+ * Copyright (C) 2019 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.pm;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.UserIdInt;
+import android.content.pm.PackageManagerInternal;
+import android.content.pm.PackageParser;
+import android.content.pm.UserInfo;
+import android.content.res.Resources;
+import android.os.SystemProperties;
+import android.os.UserHandle;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.util.Slog;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.LocalServices;
+import com.android.server.SystemConfig;
+
+import java.io.PrintWriter;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.Set;
+
+/**
+ * Responsible for un/installing system packages based on user type.
+ *
+ * <p>Uses the SystemConfig's install-in-user-type whitelist;
+ * see {@link SystemConfig#getAndClearPackageToUserTypeWhitelist} and
+ * {@link SystemConfig#getAndClearPackageToUserTypeBlacklist}.
+ *
+ * <p>If {@link #isEnforceMode()} is false, then all system packages are always installed for all
+ * users. The following applies when it is true.
+ *
+ * Any package can be in one of three states in the SystemConfig whitelist
+ * <ol>
+ *     <li>Explicitly blacklisted for a particular user type</li>
+ *     <li>Explicitly whitelisted for a particular user type</li>
+ *     <li>Not mentioned at all, for any user type (neither whitelisted nor blacklisted)</li>
+ * </ol>
+ * Blacklisting always takes precedence - if a package is blacklisted for a particular user,
+ * it won't be installed on that type of user (even if it is also whitelisted for that user).
+ * Next comes whitelisting - if it is whitelisted for a particular user, it will be installed on
+ * that type of user (as long as it isn't blacklisted).
+ * Finally, if the package is not mentioned at all (i.e. neither whitelisted nor blacklisted for
+ * any user types) in the SystemConfig 'install-in-user-type' lists
+ * then:
+ * <ul>
+ *     <li>If {@link #isImplicitWhitelistMode()}, the package is implicitly treated as whitelisted
+ *          for all users</li>
+ *     <li>Otherwise, the package is implicitly treated as blacklisted for all non-SYSTEM users</li>
+ *     <li>Either way, for {@link UserHandle#USER_SYSTEM}, the package will be implicitly
+ *          whitelisted so that it can be used for local development purposes.</li>
+ * </ul>
+ */
+class UserSystemPackageInstaller {
+    private static final String TAG = "UserManagerService";
+
+    /**
+     * System Property whether to only install system packages on a user if they're whitelisted for
+     * that user type. These are flags and can be freely combined.
+     * <ul>
+     * <li> 0 (0b000) - disable whitelist (install all system packages; no logging)</li>
+     * <li> 1 (0b001) - enforce (only install system packages if they are whitelisted)</li>
+     * <li> 2 (0b010) - log (log when a non-whitelisted package is run)</li>
+     * <li> 4 (0b100) - implicitly whitelist any package not mentioned in the whitelist</li>
+     * <li>-1         - use device default (as defined in res/res/values/config.xml)</li>
+     * </ul>
+     * Note: This list must be kept current with config_userTypePackageWhitelistMode in
+     * frameworks/base/core/res/res/values/config.xml
+     */
+    static final String PACKAGE_WHITELIST_MODE_PROP = "persist.debug.user.package_whitelist_mode";
+    static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE = 0;
+    static final int USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE = 0b001;
+    static final int USER_TYPE_PACKAGE_WHITELIST_MODE_LOG = 0b010;
+    static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST = 0b100;
+    static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT = -1;
+
+    @IntDef(flag = true, prefix = "USER_TYPE_PACKAGE_WHITELIST_MODE_", value = {
+            USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE,
+            USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE,
+            USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE,
+            USER_TYPE_PACKAGE_WHITELIST_MODE_LOG,
+            USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface PackageWhitelistMode {}
+
+    /**
+     * Maps system package manifest names to the user flags on which they should be initially
+     * installed.
+     * <p>Packages that are whitelisted, but then blacklisted so that they aren't to be installed on
+     * any user, are purposefully still present in this list.
+     */
+    private final ArrayMap<String, Integer> mWhitelitsedPackagesForUserTypes;
+
+    private final UserManagerService mUm;
+
+    UserSystemPackageInstaller(UserManagerService ums) {
+        mUm = ums;
+        mWhitelitsedPackagesForUserTypes =
+                determineWhitelistedPackagesForUserTypes(SystemConfig.getInstance());
+    }
+
+    /** Constructor for testing purposes. */
+    @VisibleForTesting
+    UserSystemPackageInstaller(UserManagerService ums, ArrayMap<String, Integer> whitelist) {
+        mUm = ums;
+        mWhitelitsedPackagesForUserTypes = whitelist;
+    }
+
+    /**
+     * During OTAs and first boot, install/uninstall all system packages for all users based on the
+     * user's UserInfo flags and the SystemConfig whitelist.
+     * We do NOT uninstall packages during an OTA though.
+     *
+     * This is responsible for enforcing the whitelist for pre-existing users (i.e. USER_SYSTEM);
+     * enforcement for new users is done when they are created in UserManagerService.createUser().
+     */
+    boolean installWhitelistedSystemPackages(boolean isFirstBoot, boolean isUpgrade) {
+        final int mode = getWhitelistMode();
+        checkWhitelistedSystemPackages(mode);
+        if (!isUpgrade && !isFirstBoot) {
+            return false;
+        }
+        Slog.i(TAG, "Reviewing whitelisted packages due to "
+                + (isFirstBoot ? "[firstBoot]" : "") + (isUpgrade ? "[upgrade]" : ""));
+        final PackageManagerInternal pmInt = LocalServices.getService(PackageManagerInternal.class);
+        // Install/uninstall system packages per user.
+        for (int userId : mUm.getUserIds()) {
+            final Set<String> userWhitelist = getInstallablePackagesForUserId(userId);
+            pmInt.forEachPackage(pkg -> {
+                if (!pkg.isSystem()) {
+                    return;
+                }
+                final boolean install =
+                        (userWhitelist == null || userWhitelist.contains(pkg.packageName))
+                        && !pkg.applicationInfo.hiddenUntilInstalled;
+                if (isUpgrade && !isFirstBoot && !install) {
+                    return; // To be careful, we don’t uninstall apps during OTAs
+                }
+                final boolean changed = pmInt.setInstalled(pkg, userId, install);
+                if (changed) {
+                    Slog.i(TAG, (install ? "Installed " : "Uninstalled ")
+                            + pkg.packageName + " for user " + userId);
+                }
+            });
+        }
+        return true;
+    }
+
+    /**
+     * Checks whether the system packages and the mWhitelistedPackagesForUserTypes whitelist are
+     * in 1-to-1 correspondence.
+     */
+    private void checkWhitelistedSystemPackages(@PackageWhitelistMode int mode) {
+        if (!isLogMode(mode) && !isEnforceMode(mode)) {
+            return;
+        }
+        Slog.v(TAG,  "Checking that all system packages are whitelisted.");
+        final Set<String> allWhitelistedPackages = getWhitelistedSystemPackages();
+        PackageManagerInternal pmInt = LocalServices.getService(PackageManagerInternal.class);
+
+        // Check whether all whitelisted packages are indeed on the system.
+        for (String pkgName : allWhitelistedPackages) {
+            PackageParser.Package pkg = pmInt.getPackage(pkgName);
+            if (pkg == null) {
+                Slog.w(TAG, pkgName + " is whitelisted but not present.");
+            } else if (!pkg.isSystem()) {
+                Slog.w(TAG, pkgName + " is whitelisted and present but not a system package.");
+            }
+        }
+
+        // Check whether all system packages are indeed whitelisted.
+        if (isImplicitWhitelistMode(mode) && !isLogMode(mode)) {
+            return;
+        }
+        final boolean doWtf = isEnforceMode(mode);
+        pmInt.forEachPackage(pkg -> {
+            if (pkg.isSystem() && !allWhitelistedPackages.contains(pkg.manifestPackageName)) {
+                final String msg = "System package " + pkg.manifestPackageName
+                        + " is not whitelisted using 'install-in-user-type' in SystemConfig "
+                        + "for any user types!";
+                if (doWtf) {
+                    Slog.wtf(TAG, msg);
+                } else {
+                    Slog.e(TAG, msg);
+                }
+            }
+        });
+    }
+
+    /** Whether to only install system packages in new users for which they are whitelisted. */
+    boolean isEnforceMode() {
+        return isEnforceMode(getWhitelistMode());
+    }
+
+    /**
+     * Whether to log a warning concerning potential problems with the user-type package whitelist.
+     */
+    boolean isLogMode() {
+        return isLogMode(getWhitelistMode());
+    }
+
+    /**
+     * Whether to treat all packages that are not mentioned at all in the whitelist to be implicitly
+     * whitelisted for all users.
+     */
+    boolean isImplicitWhitelistMode() {
+        return isImplicitWhitelistMode(getWhitelistMode());
+    }
+
+    /** See {@link #isEnforceMode()}. */
+    private static boolean isEnforceMode(int whitelistMode) {
+        return (whitelistMode & USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE) != 0;
+    }
+
+    /** See {@link #isLogMode()}. */
+    private static boolean isLogMode(int whitelistMode) {
+        return (whitelistMode & USER_TYPE_PACKAGE_WHITELIST_MODE_LOG) != 0;
+    }
+
+    /** See {@link #isImplicitWhitelistMode()}. */
+    private static boolean isImplicitWhitelistMode(int whitelistMode) {
+        return (whitelistMode & USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST) != 0;
+    }
+
+    /** Gets the PackageWhitelistMode for use of {@link #mWhitelitsedPackagesForUserTypes}. */
+    private @PackageWhitelistMode int getWhitelistMode() {
+        final int runtimeMode = SystemProperties.getInt(
+                PACKAGE_WHITELIST_MODE_PROP, USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT);
+        if (runtimeMode != USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT) {
+            return runtimeMode;
+        }
+        return Resources.getSystem()
+                .getInteger(com.android.internal.R.integer.config_userTypePackageWhitelistMode);
+    }
+
+    /**
+     * Gets the system packages names that should be installed on the given user.
+     * See {@link #getInstallablePackagesForUserType(int)}.
+     */
+    private @Nullable Set<String> getInstallablePackagesForUserId(@UserIdInt int userId) {
+        return getInstallablePackagesForUserType(mUm.getUserInfo(userId).flags);
+    }
+
+    /**
+     * Gets the system package names that should be installed on a user with the given flags, as
+     * determined by SystemConfig, the whitelist mode, and the apps actually on the device.
+     * Names are the {@link PackageParser.Package#packageName}, not necessarily the manifest names.
+     *
+     * Returns null if all system packages should be installed (due enforce-mode being off).
+     */
+    @Nullable Set<String> getInstallablePackagesForUserType(int flags) {
+        final int mode = getWhitelistMode();
+        if (!isEnforceMode(mode)) {
+            return null;
+        }
+        final boolean isSystemUser = (flags & UserInfo.FLAG_SYSTEM) != 0;
+        final boolean isImplicitWhitelistMode = isImplicitWhitelistMode(mode);
+        final Set<String> whitelistedPackages = getWhitelistedPackagesForUserType(flags);
+
+        final Set<String> installPackages = new ArraySet<>();
+        final PackageManagerInternal pmInt = LocalServices.getService(PackageManagerInternal.class);
+        pmInt.forEachPackage(pkg -> {
+            if (!pkg.isSystem()) {
+                return;
+            }
+            if (shouldInstallPackage(pkg, mWhitelitsedPackagesForUserTypes,
+                    whitelistedPackages, isImplicitWhitelistMode, isSystemUser)) {
+                // Although the whitelist uses manifest names, this function returns packageNames.
+                installPackages.add(pkg.packageName);
+            }
+        });
+        return installPackages;
+    }
+
+    /**
+     * Returns whether the given system package should be installed on the given user, based on the
+     * the given whitelist of system packages.
+     *
+     * @param sysPkg the system package. Must be a system package; no verification for this is done.
+     * @param userTypeWhitelist map of package manifest names to user flags on which they should be
+     *                          installed
+     * @param userWhitelist set of package manifest names that should be installed on this
+     *                      particular user. This must be consistent with userTypeWhitelist, but is
+     *                      passed in separately to avoid repeatedly calculating it from
+     *                      userTypeWhitelist.
+     * @param isImplicitWhitelistMode whether non-mentioned packages are implicitly whitelisted.
+     * @param isSystemUser whether the user is USER_SYSTEM (which gets special treatment).
+     */
+    @VisibleForTesting
+    static boolean shouldInstallPackage(PackageParser.Package sysPkg,
+            @NonNull ArrayMap<String, Integer> userTypeWhitelist,
+            @NonNull Set<String> userWhitelist, boolean isImplicitWhitelistMode,
+            boolean isSystemUser) {
+
+        final String pkgName = sysPkg.manifestPackageName;
+        boolean install = (isImplicitWhitelistMode && !userTypeWhitelist.containsKey(pkgName))
+                || userWhitelist.contains(pkgName);
+
+        // For the purposes of local development, any package that isn't even mentioned in the
+        // whitelist at all is implicitly treated as whitelisted for the SYSTEM user.
+        if (!install && isSystemUser && !userTypeWhitelist.containsKey(pkgName)) {
+            install = true;
+            Slog.e(TAG, "System package " + pkgName + " is not mentioned "
+                    + "in SystemConfig's 'install-in-user-type' but we are "
+                    + "implicitly treating it as whitelisted for the SYSTEM user.");
+        }
+        return install;
+    }
+
+    /**
+     * Gets the package manifest names that are whitelisted for a user with the given flags,
+     * as determined by SystemConfig.
+     */
+    @VisibleForTesting
+    @NonNull Set<String> getWhitelistedPackagesForUserType(int flags) {
+        Set<String> installablePkgs = new ArraySet<>(mWhitelitsedPackagesForUserTypes.size());
+        for (int i = 0; i < mWhitelitsedPackagesForUserTypes.size(); i++) {
+            String pkgName = mWhitelitsedPackagesForUserTypes.keyAt(i);
+            int whitelistedUserTypes = mWhitelitsedPackagesForUserTypes.valueAt(i);
+            if ((flags & whitelistedUserTypes) != 0) {
+                installablePkgs.add(pkgName);
+            }
+        }
+        return installablePkgs;
+    }
+
+    /**
+     * Set of package manifest names that are included anywhere in the package-to-user-type
+     * whitelist, as determined by SystemConfig.
+     *
+     * Packages that are whitelisted, but then blacklisted so that they aren't to be installed on
+     * any user, are still present in this list, since that is a valid scenario (e.g. if an OEM
+     * completely blacklists an AOSP app).
+     */
+    private Set<String> getWhitelistedSystemPackages() {
+        return mWhitelitsedPackagesForUserTypes.keySet();
+    }
+
+    /**
+     * Returns a map of package manifest names to the user flags on which it is to be installed.
+     * Also, clears this data from SystemConfig where it was stored inefficiently (and therefore
+     * should be called exactly once, even if the data isn't useful).
+     *
+     * Any system packages not present in this map should not even be on the device at all.
+     * To enforce this:
+     * <ul>
+     *  <li>Illegal user types are ignored.</li>
+     *  <li>Packages that never whitelisted at all (even if they are explicitly blacklisted) are
+     *          ignored.</li>
+     *  <li>Packages that are blacklisted whenever they are whitelisted will be stored with the
+     *          flag 0 (since this is a valid scenario, e.g. if an OEM completely blacklists an AOSP
+     *          app).</li>
+     * </ul>
+     */
+    @VisibleForTesting
+    static ArrayMap<String, Integer> determineWhitelistedPackagesForUserTypes(
+            SystemConfig sysConfig) {
+
+        final ArrayMap<String, Set<String>> whitelist =
+                sysConfig.getAndClearPackageToUserTypeWhitelist();
+        // result maps packageName -> userTypes on which the package should be installed.
+        final ArrayMap<String, Integer> result = new ArrayMap<>(whitelist.size() + 1);
+        // First, do the whitelisted user types.
+        for (int i = 0; i < whitelist.size(); i++) {
+            final String pkgName = whitelist.keyAt(i);
+            final int flags = getFlagsFromUserTypes(whitelist.valueAt(i));
+            if (flags != 0) {
+                result.put(pkgName, flags);
+            }
+        }
+        // Then, un-whitelist any blacklisted user types.
+        // TODO(b/141370854): Right now, the blacklist is actually just an 'unwhitelist'. Which
+        //                    direction we go depends on how we design user subtypes, which is still
+        //                    being designed. For now, unwhitelisting works for current use-cases.
+        final ArrayMap<String, Set<String>> blacklist =
+                sysConfig.getAndClearPackageToUserTypeBlacklist();
+        for (int i = 0; i < blacklist.size(); i++) {
+            final String pkgName = blacklist.keyAt(i);
+            final int nonFlags = getFlagsFromUserTypes(blacklist.valueAt(i));
+            final Integer flags = result.get(pkgName);
+            if (flags != null) {
+                result.put(pkgName, flags & ~nonFlags);
+            }
+        }
+        // Regardless of the whitelists/blacklists, ensure mandatory packages.
+        result.put("android",
+                UserInfo.FLAG_SYSTEM | UserInfo.FLAG_FULL | UserInfo.PROFILE_FLAGS_MASK);
+        return result;
+    }
+
+    /** Converts a user types, as used in SystemConfig, to a UserInfo flag. */
+    private static int getFlagsFromUserTypes(Iterable<String> userTypes) {
+        int flags = 0;
+        for (String type : userTypes) {
+            switch (type) {
+                case "GUEST":
+                    flags |= UserInfo.FLAG_GUEST;
+                    break;
+                case "RESTRICTED":
+                    flags |= UserInfo.FLAG_RESTRICTED;
+                    break;
+                case "MANAGED_PROFILE":
+                    flags |= UserInfo.FLAG_MANAGED_PROFILE;
+                    break;
+                case "EPHEMERAL":
+                    flags |= UserInfo.FLAG_EPHEMERAL;
+                    break;
+                case "DEMO":
+                    flags |= UserInfo.FLAG_DEMO;
+                    break;
+                case "FULL":
+                    flags |= UserInfo.FLAG_FULL;
+                    break;
+                case "SYSTEM":
+                    flags |= UserInfo.FLAG_SYSTEM;
+                    break;
+                case "PROFILE":
+                    flags |= UserInfo.PROFILE_FLAGS_MASK;
+                    break;
+                default:
+                    Slog.w(TAG, "SystemConfig contained an invalid user type: " + type);
+                    break;
+                // Other UserInfo flags are forbidden.
+                // In particular, FLAG_INITIALIZED, FLAG_DISABLED, FLAG_QUIET_MODE are inapplicable.
+                // The following are invalid now, but are reconsiderable: FLAG_PRIMARY, FLAG_ADMIN.
+            }
+        }
+        return flags;
+    }
+
+    void dump(PrintWriter pw) {
+        for (int i = 0; i < mWhitelitsedPackagesForUserTypes.size(); i++) {
+            final String pkgName = mWhitelitsedPackagesForUserTypes.keyAt(i);
+            final String whitelistedUserTypes =
+                    UserInfo.flagsToString(mWhitelitsedPackagesForUserTypes.valueAt(i));
+            pw.println("    " + pkgName + ": " + whitelistedUserTypes);
+        }
+    }
+}
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 3e655ed..793cdd2 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -190,6 +190,7 @@
     static {
         STORAGE_PERMISSIONS.add(Manifest.permission.READ_EXTERNAL_STORAGE);
         STORAGE_PERMISSIONS.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
+        STORAGE_PERMISSIONS.add(Manifest.permission.ACCESS_MEDIA_LOCATION);
     }
 
     private static final int MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS = 1;
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index a57321e..89908f0 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -24,7 +24,7 @@
 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
-import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
+import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKED_COMPAT;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_WHEN_REQUESTED;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
@@ -53,7 +53,6 @@
 import android.annotation.Nullable;
 import android.annotation.UserIdInt;
 import android.app.ActivityManager;
-import android.app.AppOpsManager;
 import android.app.ApplicationPackageManager;
 import android.app.IActivityManager;
 import android.content.Context;
@@ -795,79 +794,57 @@
         synchronized (mLock) {
             checkPermissionDelegate = mCheckPermissionDelegate;
         }
-        if (checkPermissionDelegate == null)  {
+        if (checkPermissionDelegate == null) {
             return checkPermissionImpl(permName, pkgName, userId);
         }
         return checkPermissionDelegate.checkPermission(permName, pkgName, userId,
                 this::checkPermissionImpl);
     }
 
-    private int checkPermissionImpl(@NonNull String permissionName, @NonNull String packageName,
-            @UserIdInt int userId) {
-        final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
+    private int checkPermissionImpl(String permName, String pkgName, int userId) {
+        final PackageParser.Package pkg = mPackageManagerInt.getPackage(pkgName);
         if (pkg == null) {
             return PackageManager.PERMISSION_DENIED;
         }
-        return checkPermissionInternal(pkg, true, permissionName, true, userId)
-                ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
+        return checkPermissionInternal(pkg, true, permName, userId);
     }
 
-    private boolean checkPermissionInternal(@NonNull Package pkg, boolean isPackageExplicit,
-            @NonNull String permissionName, boolean useRequestedPermissionsForLegacyApps,
-            @UserIdInt int userId) {
+    private int checkPermissionInternal(@NonNull Package pkg, boolean isPackageExplicit,
+            @NonNull String permissionName, @UserIdInt int userId) {
         final int callingUid = getCallingUid();
         if (isPackageExplicit || pkg.mSharedUserId == null) {
             if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) {
-                return false;
+                return PackageManager.PERMISSION_DENIED;
             }
         } else {
             if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
-                return false;
+                return PackageManager.PERMISSION_DENIED;
             }
         }
 
         final int uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
         final PackageSetting ps = (PackageSetting) pkg.mExtras;
         if (ps == null) {
-            return false;
+            return PackageManager.PERMISSION_DENIED;
         }
         final PermissionsState permissionsState = ps.getPermissionsState();
 
-        if (checkSinglePermissionInternal(uid, permissionsState, permissionName,
-                useRequestedPermissionsForLegacyApps)) {
-            return true;
+        if (checkSinglePermissionInternal(uid, permissionsState, permissionName)) {
+            return PackageManager.PERMISSION_GRANTED;
         }
 
         final String fullerPermissionName = FULLER_PERMISSION_MAP.get(permissionName);
-        if (fullerPermissionName != null && checkSinglePermissionInternal(uid, permissionsState,
-                fullerPermissionName, useRequestedPermissionsForLegacyApps)) {
-            return true;
+        if (fullerPermissionName != null
+                && checkSinglePermissionInternal(uid, permissionsState, fullerPermissionName)) {
+            return PackageManager.PERMISSION_GRANTED;
         }
 
-        return false;
+        return PackageManager.PERMISSION_DENIED;
     }
 
     private boolean checkSinglePermissionInternal(int uid,
-            @NonNull PermissionsState permissionsState, @NonNull String permissionName,
-            boolean useRequestedPermissionsForLegacyApps) {
-        boolean hasPermission = permissionsState.hasPermission(permissionName,
-                UserHandle.getUserId(uid));
-
-        if (!hasPermission && useRequestedPermissionsForLegacyApps
-                && mSettings.isPermissionRuntime(permissionName)) {
-            final String[] packageNames = mContext.getPackageManager().getPackagesForUid(uid);
-            final int packageNamesSize = packageNames != null ? packageNames.length : 0;
-            for (int i = 0; i < packageNamesSize; i++) {
-                final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageNames[i]);
-                if (pkg != null && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
-                        && pkg.requestedPermissions.contains(permissionName)) {
-                    hasPermission = true;
-                    break;
-                }
-            }
-        }
-
-        if (!hasPermission) {
+            @NonNull PermissionsState permissionsState, @NonNull String permissionName) {
+        if (!permissionsState.hasPermission(permissionName, UserHandle.getUserId(uid))) {
             return false;
         }
 
@@ -891,19 +868,18 @@
 
         final CheckPermissionDelegate checkPermissionDelegate;
         synchronized (mLock) {
-            if (mCheckPermissionDelegate == null)  {
-                return checkUidPermissionImpl(permName, uid);
-            }
             checkPermissionDelegate = mCheckPermissionDelegate;
         }
+        if (checkPermissionDelegate == null)  {
+            return checkUidPermissionImpl(permName, uid);
+        }
         return checkPermissionDelegate.checkUidPermission(permName, uid,
                 this::checkUidPermissionImpl);
     }
 
-    private int checkUidPermissionImpl(@NonNull String permissionName, int uid) {
+    private int checkUidPermissionImpl(String permName, int uid) {
         final PackageParser.Package pkg = mPackageManagerInt.getPackage(uid);
-        return checkUidPermissionInternal(uid, pkg, permissionName, true)
-                ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
+        return checkUidPermissionInternal(pkg, uid, permName);
     }
 
     /**
@@ -913,25 +889,24 @@
      *
      * @see SystemConfig#getSystemPermissions()
      */
-    private boolean checkUidPermissionInternal(int uid, @Nullable Package pkg,
-            @NonNull String permissionName, boolean useRequestedPermissionsForLegacyApps) {
+    private int checkUidPermissionInternal(@Nullable Package pkg, int uid,
+            @NonNull String permissionName) {
         if (pkg != null) {
             final int userId = UserHandle.getUserId(uid);
-            return checkPermissionInternal(pkg, false, permissionName,
-                    useRequestedPermissionsForLegacyApps, userId);
+            return checkPermissionInternal(pkg, false, permissionName, userId);
         }
 
         if (checkSingleUidPermissionInternal(uid, permissionName)) {
-            return true;
+            return PackageManager.PERMISSION_GRANTED;
         }
 
         final String fullerPermissionName = FULLER_PERMISSION_MAP.get(permissionName);
         if (fullerPermissionName != null
                 && checkSingleUidPermissionInternal(uid, fullerPermissionName)) {
-            return true;
+            return PackageManager.PERMISSION_GRANTED;
         }
 
-        return false;
+        return PackageManager.PERMISSION_DENIED;
     }
 
     private boolean checkSingleUidPermissionInternal(int uid, @NonNull String permissionName) {
@@ -941,17 +916,6 @@
         }
     }
 
-    private int computeRuntimePermissionAppOpMode(int uid, @NonNull String permissionName) {
-        boolean granted = isUidPermissionGranted(uid, permissionName);
-        // TODO: Foreground permissions.
-        return granted ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
-    }
-
-    private boolean isUidPermissionGranted(int uid, @NonNull String permissionName) {
-        final PackageParser.Package pkg = mPackageManagerInt.getPackage(uid);
-        return checkUidPermissionInternal(uid, pkg, permissionName, false);
-    }
-
     @Override
     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
         mContext.enforceCallingOrSelfPermission(
@@ -1295,7 +1259,7 @@
         }
 
         if (bp.isSoftRestricted() && !SoftRestrictedPermissionPolicy.forPermission(mContext,
-                pkg.applicationInfo, UserHandle.of(userId), permName).canBeGranted()) {
+                pkg.applicationInfo, UserHandle.of(userId), permName).mayGrantPermission()) {
             Log.e(TAG, "Cannot grant soft restricted permission " + permName + " for package "
                     + packageName);
             return;
@@ -1514,7 +1478,7 @@
         // These are flags that can change base on user actions.
         final int userSettableMask = FLAG_PERMISSION_USER_SET
                 | FLAG_PERMISSION_USER_FIXED
-                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
+                | FLAG_PERMISSION_REVOKED_COMPAT
                 | FLAG_PERMISSION_REVIEW_REQUIRED;
 
         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
@@ -1577,7 +1541,6 @@
             }
         };
 
-        final AppOpsManager appOpsManager = mContext.getSystemService(AppOpsManager.class);
         for (int i = 0; i < permissionCount; i++) {
             final String permName = pkg.requestedPermissions.get(i);
             final BasePermission bp;
@@ -1624,7 +1587,7 @@
             final int uid = mPackageManagerInt.getPackageUid(packageName, 0, userId);
             final int targetSdk = mPackageManagerInt.getUidTargetSdkVersion(uid);
             final int flags = (targetSdk < Build.VERSION_CODES.M && bp.isRuntime())
-                    ? FLAG_PERMISSION_REVIEW_REQUIRED | FLAG_PERMISSION_REVOKE_ON_UPGRADE
+                    ? FLAG_PERMISSION_REVIEW_REQUIRED | FLAG_PERMISSION_REVOKED_COMPAT
                     : 0;
 
             updatePermissionFlagsInternal(
@@ -1643,16 +1606,9 @@
 
             // If this permission was granted by default, make sure it is.
             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
+                // PermissionPolicyService will handle the app op for runtime permissions later.
                 grantRuntimePermissionInternal(permName, packageName, false,
                         Process.SYSTEM_UID, userId, delayingPermCallback);
-                // Allow app op later as we are holding mPackages
-                // PermissionPolicyService will handle the app op for foreground/background
-                // permissions.
-                String appOp = AppOpsManager.permissionToOp(permName);
-                if (appOp != null) {
-                    mHandler.post(() -> appOpsManager.setUidMode(appOp, uid,
-                            AppOpsManager.MODE_ALLOWED));
-                }
             // If permission review is enabled the permissions for a legacy apps
             // are represented as constantly granted runtime ones, so don't revoke.
             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
@@ -1697,10 +1653,11 @@
         if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
             return null;
         }
+        DefaultBrowserProvider provider;
         synchronized (mLock) {
-            return mDefaultBrowserProvider == null
-                    ? null : mDefaultBrowserProvider.getDefaultBrowser(userId);
+            provider = mDefaultBrowserProvider;
         }
+        return provider != null ? provider.getDefaultBrowser(userId) : null;
     }
 
     @Override
@@ -1716,23 +1673,27 @@
 
     private boolean setDefaultBrowserInternal(String packageName, boolean async,
             boolean doGrant, int userId) {
+        if (userId == UserHandle.USER_ALL) {
+            return false;
+        }
+        DefaultBrowserProvider provider;
         synchronized (mLock) {
-            if (userId == UserHandle.USER_ALL) {
+            provider = mDefaultBrowserProvider;
+        }
+        if (provider == null) {
+            return false;
+        }
+        if (async) {
+            provider.setDefaultBrowserAsync(packageName, userId);
+        } else {
+            if (!provider.setDefaultBrowser(packageName, userId)) {
                 return false;
             }
-            if (mDefaultBrowserProvider == null) {
-                return false;
-            }
-            if (async) {
-                mDefaultBrowserProvider.setDefaultBrowserAsync(packageName, userId);
-            } else {
-                if (!mDefaultBrowserProvider.setDefaultBrowser(packageName, userId)) {
-                    return false;
-                }
-            }
-            if (doGrant && packageName != null) {
-                mDefaultPermissionGrantPolicy
-                        .grantDefaultPermissionsToDefaultBrowser(packageName, userId);
+        }
+        if (doGrant && packageName != null) {
+            synchronized (mLock) {
+                mDefaultPermissionGrantPolicy.grantDefaultPermissionsToDefaultBrowser(packageName,
+                        userId);
             }
         }
         return true;
@@ -2536,8 +2497,8 @@
                                         wasChanged = true;
                                     }
 
-                                    if ((flags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0) {
-                                        flags &= ~FLAG_PERMISSION_REVOKE_ON_UPGRADE;
+                                    if ((flags & FLAG_PERMISSION_REVOKED_COMPAT) != 0) {
+                                        flags &= ~FLAG_PERMISSION_REVOKED_COMPAT;
                                         wasChanged = true;
                                     // Hard restricted permissions cannot be held.
                                     } else if (!permissionPolicyInitialized
@@ -2556,7 +2517,7 @@
                                                 bp.getSourcePackageName())) {
                                             if (!bp.isRemoved()) {
                                                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED
-                                                        | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
+                                                        | FLAG_PERMISSION_REVOKED_COMPAT;
                                                 wasChanged = true;
                                             }
                                         }
@@ -2671,8 +2632,8 @@
                                         wasChanged = true;
                                     }
 
-                                    if ((flags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0) {
-                                        flags &= ~FLAG_PERMISSION_REVOKE_ON_UPGRADE;
+                                    if ((flags & FLAG_PERMISSION_REVOKED_COMPAT) != 0) {
+                                        flags &= ~FLAG_PERMISSION_REVOKED_COMPAT;
                                         wasChanged = true;
                                     // Hard restricted permissions cannot be held.
                                     } else if (!permissionPolicyInitialized ||
@@ -3407,6 +3368,9 @@
         final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
 
+        final int compatFlags = PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED
+                | PackageManager.FLAG_PERMISSION_REVOKED_COMPAT;
+
         final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
                 >= Build.VERSION_CODES.M;
 
@@ -3430,12 +3394,11 @@
                                 callingUid, userId, callback);
                     }
                 } else {
-                    // In permission review mode we clear the review flag when we
-                    // are asked to install the app with all permissions granted.
-                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
-                        updatePermissionFlagsInternal(permission, pkg.packageName,
-                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, callingUid,
-                                userId, false, callback);
+                    // In permission review mode we clear the review flag and the revoked compat
+                    // flag when we are asked to install the app with all permissions granted.
+                    if ((flags & compatFlags) != 0) {
+                        updatePermissionFlagsInternal(permission, pkg.packageName, compatFlags,
+                                0, callingUid, userId, false, callback);
                     }
                 }
             }
@@ -4334,15 +4297,17 @@
 
         @Override
         public void setDefaultHome(String packageName, int userId, Consumer<Boolean> callback) {
-            synchronized (mLock) {
-                if (userId == UserHandle.USER_ALL) {
-                    return;
-                }
-                if (mDefaultHomeProvider == null) {
-                    return;
-                }
-                mDefaultHomeProvider.setDefaultHomeAsync(packageName, userId, callback);
+            if (userId == UserHandle.USER_ALL) {
+                return;
             }
+            DefaultHomeProvider provider;
+            synchronized (mLock) {
+                provider = mDefaultHomeProvider;
+            }
+            if (provider == null) {
+                return;
+            }
+            provider.setDefaultHomeAsync(packageName, userId, callback);
         }
 
         @Override
@@ -4403,26 +4368,29 @@
 
         @Override
         public String getDefaultBrowser(int userId) {
+            DefaultBrowserProvider provider;
             synchronized (mLock) {
-                return mDefaultBrowserProvider == null
-                        ? null : mDefaultBrowserProvider.getDefaultBrowser(userId);
+                provider = mDefaultBrowserProvider;
             }
+            return provider != null ? provider.getDefaultBrowser(userId) : null;
         }
 
         @Override
         public String getDefaultDialer(int userId) {
+            DefaultDialerProvider provider;
             synchronized (mLock) {
-                return mDefaultDialerProvider == null
-                        ? null : mDefaultDialerProvider.getDefaultDialer(userId);
+                provider = mDefaultDialerProvider;
             }
+            return provider != null ? provider.getDefaultDialer(userId) : null;
         }
 
         @Override
         public String getDefaultHome(int userId) {
+            DefaultHomeProvider provider;
             synchronized (mLock) {
-                return mDefaultHomeProvider == null
-                        ? null : mDefaultHomeProvider.getDefaultHome(userId);
+                provider = mDefaultHomeProvider;
             }
+            return provider != null ? provider.getDefaultHome(userId) : null;
         }
 
         @Override
@@ -4465,12 +4433,6 @@
                         StorageManager.UUID_PRIVATE_INTERNAL, true, mDefaultPermissionCallback);
             }
         }
-
-        @Override
-        public int computeRuntimePermissionAppOpMode(int uid, @NonNull String permissionName) {
-            return PermissionManagerService.this.computeRuntimePermissionAppOpMode(uid,
-                    permissionName);
-        }
     }
 
     private static final class OnPermissionChangeListeners extends Handler {
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
index 8f22f92..04ec5ba 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
@@ -445,13 +445,4 @@
 
     /** Called when a new user has been created. */
     public abstract void onNewUserCreated(@UserIdInt int userId);
-
-    /**
-     * Compute an app op mode based on its runtime permission state.
-     *
-     * @param uid the uid for the app op
-     * @param permissionName the permission name for the app op
-     * @return the computed mode
-     */
-    public abstract int computeRuntimePermissionAppOpMode(int uid, @NonNull String permissionName);
 }
diff --git a/services/core/java/com/android/server/policy/LegacyGlobalActions.java b/services/core/java/com/android/server/policy/LegacyGlobalActions.java
index 9cb2441..bbee393b 100644
--- a/services/core/java/com/android/server/policy/LegacyGlobalActions.java
+++ b/services/core/java/com/android/server/policy/LegacyGlobalActions.java
@@ -370,8 +370,7 @@
                         // Take an "interactive" bugreport.
                         MetricsLogger.action(mContext,
                                 MetricsEvent.ACTION_BUGREPORT_FROM_POWER_MENU_INTERACTIVE);
-                        ActivityManager.getService().requestBugReport(
-                                ActivityManager.BUGREPORT_OPTION_INTERACTIVE);
+                        ActivityManager.getService().requestInteractiveBugReport();
                     } catch (RemoteException e) {
                     }
                 }
@@ -388,8 +387,7 @@
             try {
                 // Take a "full" bugreport.
                 MetricsLogger.action(mContext, MetricsEvent.ACTION_BUGREPORT_FROM_POWER_MENU_FULL);
-                ActivityManager.getService().requestBugReport(
-                        ActivityManager.BUGREPORT_OPTION_FULL);
+                ActivityManager.getService().requestFullBugReport();
             } catch (RemoteException e) {
             }
             return false;
diff --git a/services/core/java/com/android/server/policy/PermissionPolicyService.java b/services/core/java/com/android/server/policy/PermissionPolicyService.java
index 1bf319d..77c16e3 100644
--- a/services/core/java/com/android/server/policy/PermissionPolicyService.java
+++ b/services/core/java/com/android/server/policy/PermissionPolicyService.java
@@ -17,13 +17,12 @@
 package com.android.server.policy;
 
 import static android.app.AppOpsManager.MODE_ALLOWED;
-import static android.app.AppOpsManager.MODE_DEFAULT;
-import static android.app.AppOpsManager.MODE_ERRORED;
 import static android.app.AppOpsManager.MODE_FOREGROUND;
 import static android.app.AppOpsManager.MODE_IGNORED;
 import static android.app.AppOpsManager.OP_NONE;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_APPLY_RESTRICTION;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
+import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKED_COMPAT;
 import static android.content.pm.PackageManager.GET_PERMISSIONS;
 
 import android.annotation.NonNull;
@@ -157,13 +156,12 @@
                     appOpsService.startWatchingMode(getSwitchOp(perm.name), null, appOpsListener);
                 } else if (perm.isSoftRestricted()) {
                     appOpsService.startWatchingMode(getSwitchOp(perm.name), null, appOpsListener);
-
                     SoftRestrictedPermissionPolicy policy =
                             SoftRestrictedPermissionPolicy.forPermission(null, null, null,
                                     perm.name);
-                    if (policy.resolveAppOp() != OP_NONE) {
-                        appOpsService.startWatchingMode(policy.resolveAppOp(), null,
-                                appOpsListener);
+                    int extraAppOp = policy.getExtraAppOpCode();
+                    if (extraAppOp != OP_NONE) {
+                        appOpsService.startWatchingMode(extraAppOp, null, appOpsListener);
                     }
                 }
             }
@@ -395,24 +393,6 @@
         private final @NonNull SparseIntArray mAllUids = new SparseIntArray();
 
         /**
-         * All ops that need to be set to default
-         *
-         * Currently, only used by the restricted permissions logic.
-         *
-         * @see #syncPackages
-         */
-        private final @NonNull ArrayList<OpToChange> mOpsToDefault = new ArrayList<>();
-
-        /**
-         * All ops that need to be flipped to allow if default.
-         *
-         * Currently, only used by the restricted permissions logic.
-         *
-         * @see #syncPackages
-         */
-        private final @NonNull ArrayList<OpToChange> mOpsToAllowIfDefault = new ArrayList<>();
-
-        /**
          * All ops that need to be flipped to allow.
          *
          * @see #syncPackages
@@ -420,15 +400,6 @@
         private final @NonNull ArrayList<OpToChange> mOpsToAllow = new ArrayList<>();
 
         /**
-         * All ops that need to be flipped to ignore if default.
-         *
-         * Currently, only used by the restricted permissions logic.
-         *
-         * @see #syncPackages
-         */
-        private final @NonNull ArrayList<OpToChange> mOpsToIgnoreIfDefault = new ArrayList<>();
-
-        /**
          * All ops that need to be flipped to ignore.
          *
          * @see #syncPackages
@@ -436,6 +407,15 @@
         private final @NonNull ArrayList<OpToChange> mOpsToIgnore = new ArrayList<>();
 
         /**
+         * All ops that need to be flipped to ignore if not allowed.
+         *
+         * Currently, only used by soft restricted permissions logic.
+         *
+         * @see #syncPackages
+         */
+        private final @NonNull ArrayList<OpToChange> mOpsToIgnoreIfNotAllowed = new ArrayList<>();
+
+        /**
          * All ops that need to be flipped to foreground.
          *
          * Currently, only used by the foreground/background permissions logic.
@@ -444,16 +424,6 @@
          */
         private final @NonNull ArrayList<OpToChange> mOpsToForeground = new ArrayList<>();
 
-        /**
-         * All ops that need to be flipped to foreground if allow.
-         *
-         * Currently, only used by the foreground/background permissions logic.
-         *
-         * @see #syncPackages
-         */
-        private final @NonNull ArrayList<OpToChange> mOpsToForegroundIfAllow =
-                new ArrayList<>();
-
         PermissionToOpSynchroniser(@NonNull Context context) {
             mContext = context;
             mPackageManager = context.getPackageManager();
@@ -463,7 +433,7 @@
         /**
          * Set app ops that were added in {@link #addPackage}.
          *
-         * <p>This processes ops previously added by {@link #addOpIfRestricted}
+         * <p>This processes ops previously added by {@link #addAppOps(PackageInfo, String)}
          */
         private void syncPackages() {
             // Remember which ops were already set. This makes sure that we always set the most
@@ -479,32 +449,6 @@
                 alreadySetAppOps.put(IntPair.of(op.uid, op.code), 1);
             }
 
-            final int allowIfDefaultCount = mOpsToAllowIfDefault.size();
-            for (int i = 0; i < allowIfDefaultCount; i++) {
-                final OpToChange op = mOpsToAllowIfDefault.get(i);
-                if (alreadySetAppOps.indexOfKey(IntPair.of(op.uid, op.code)) >= 0) {
-                    continue;
-                }
-
-                boolean wasSet = setUidModeAllowedIfDefault(op.code, op.uid, op.packageName);
-                if (wasSet) {
-                    alreadySetAppOps.put(IntPair.of(op.uid, op.code), 1);
-                }
-            }
-
-            final int foregroundIfAllowedCount = mOpsToForegroundIfAllow.size();
-            for (int i = 0; i < foregroundIfAllowedCount; i++) {
-                final OpToChange op = mOpsToForegroundIfAllow.get(i);
-                if (alreadySetAppOps.indexOfKey(IntPair.of(op.uid, op.code)) >= 0) {
-                    continue;
-                }
-
-                boolean wasSet = setUidModeForegroundIfAllow(op.code, op.uid, op.packageName);
-                if (wasSet) {
-                    alreadySetAppOps.put(IntPair.of(op.uid, op.code), 1);
-                }
-            }
-
             final int foregroundCount = mOpsToForeground.size();
             for (int i = 0; i < foregroundCount; i++) {
                 final OpToChange op = mOpsToForeground.get(i);
@@ -527,180 +471,154 @@
                 alreadySetAppOps.put(IntPair.of(op.uid, op.code), 1);
             }
 
-            final int ignoreIfDefaultCount = mOpsToIgnoreIfDefault.size();
-            for (int i = 0; i < ignoreIfDefaultCount; i++) {
-                final OpToChange op = mOpsToIgnoreIfDefault.get(i);
+            final int ignoreIfNotAllowedCount = mOpsToIgnoreIfNotAllowed.size();
+            for (int i = 0; i < ignoreIfNotAllowedCount; i++) {
+                final OpToChange op = mOpsToIgnoreIfNotAllowed.get(i);
                 if (alreadySetAppOps.indexOfKey(IntPair.of(op.uid, op.code)) >= 0) {
                     continue;
                 }
 
-                boolean wasSet = setUidModeIgnoredIfDefault(op.code, op.uid, op.packageName);
+                boolean wasSet = setUidModeIgnoredIfNotAllowed(op.code, op.uid, op.packageName);
                 if (wasSet) {
                     alreadySetAppOps.put(IntPair.of(op.uid, op.code), 1);
                 }
             }
-
-            final int defaultCount = mOpsToDefault.size();
-            for (int i = 0; i < defaultCount; i++) {
-                final OpToChange op = mOpsToDefault.get(i);
-                if (alreadySetAppOps.indexOfKey(IntPair.of(op.uid, op.code)) >= 0) {
-                    continue;
-                }
-
-                setUidModeDefault(op.code, op.uid, op.packageName);
-                alreadySetAppOps.put(IntPair.of(op.uid, op.code), 1);
-            }
         }
 
         /**
-         * Add op that belong to a restricted permission for later processing in
-         * {@link #syncPackages()}.
-         *
-         * <p>Note: Called with the package lock held. Do <u>not</u> call into app-op manager.
-         *
-         * @param permissionInfo The permission that is currently looked at
-         * @param pkg The package looked at
+         * Note: Called with the package lock held. Do <u>not</u> call into app-op manager.
          */
-        private void addOpIfRestricted(@NonNull PermissionInfo permissionInfo,
-                @NonNull PackageInfo pkg) {
-            final String permission = permissionInfo.name;
-            final int opCode = getSwitchOp(permission);
-            final int uid = pkg.applicationInfo.uid;
-
-            if (!permissionInfo.isRestricted()) {
+        private void addAppOps(@NonNull PackageInfo packageInfo, @NonNull String permissionName) {
+            PermissionInfo permissionInfo = getPermissionInfo(permissionName);
+            if (permissionInfo == null) {
                 return;
             }
-
-            final boolean applyRestriction =
-                    (mPackageManager.getPermissionFlags(permission, pkg.packageName,
-                    mContext.getUser()) & FLAG_PERMISSION_APPLY_RESTRICTION) != 0;
-
-            if (permissionInfo.isHardRestricted()) {
-                if (opCode != OP_NONE) {
-                    if (applyRestriction) {
-                        mOpsToDefault.add(new OpToChange(uid, pkg.packageName, opCode));
-                    } else {
-                        mOpsToAllowIfDefault.add(new OpToChange(uid, pkg.packageName, opCode));
-                    }
-                }
-            } else if (permissionInfo.isSoftRestricted()) {
-                final SoftRestrictedPermissionPolicy policy =
-                        SoftRestrictedPermissionPolicy.forPermission(mContext, pkg.applicationInfo,
-                                mContext.getUser(), permission);
-
-                if (opCode != OP_NONE) {
-                    if (policy.canBeGranted()) {
-                        mOpsToAllowIfDefault.add(new OpToChange(uid, pkg.packageName, opCode));
-                    } else {
-                        mOpsToDefault.add(new OpToChange(uid, pkg.packageName, opCode));
-                    }
-                }
-
-                final int op = policy.resolveAppOp();
-                if (op != OP_NONE) {
-                    switch (policy.getDesiredOpMode()) {
-                        case MODE_DEFAULT:
-                            mOpsToDefault.add(new OpToChange(uid, pkg.packageName, op));
-                            break;
-                        case MODE_ALLOWED:
-                            if (policy.shouldSetAppOpIfNotDefault()) {
-                                mOpsToAllow.add(new OpToChange(uid, pkg.packageName, op));
-                            } else {
-                                mOpsToAllowIfDefault.add(
-                                        new OpToChange(uid, pkg.packageName, op));
-                            }
-                            break;
-                        case MODE_FOREGROUND:
-                            Slog.wtf(LOG_TAG,
-                                    "Setting appop to foreground is not implemented");
-                            break;
-                        case MODE_IGNORED:
-                            if (policy.shouldSetAppOpIfNotDefault()) {
-                                mOpsToIgnore.add(new OpToChange(uid, pkg.packageName, op));
-                            } else {
-                                mOpsToIgnoreIfDefault.add(
-                                        new OpToChange(uid, pkg.packageName,
-                                                op));
-                            }
-                            break;
-                        case MODE_ERRORED:
-                            Slog.wtf(LOG_TAG, "Setting appop to errored is not implemented");
-                    }
-                }
-            }
+            addPermissionAppOp(packageInfo, permissionInfo);
+            addExtraAppOp(packageInfo, permissionInfo);
         }
 
-        private boolean isBgPermRestricted(@NonNull String pkg, @NonNull String perm, int uid) {
-            try {
-                final PermissionInfo bgPermInfo = mPackageManager.getPermissionInfo(perm, 0);
-
-                if (bgPermInfo.isSoftRestricted()) {
-                    Slog.wtf(LOG_TAG, "Support for soft restricted background permissions not "
-                            + "implemented");
-                }
-
-                return bgPermInfo.isHardRestricted() && (mPackageManager.getPermissionFlags(
-                                perm, pkg, UserHandle.getUserHandleForUid(uid))
-                                & FLAG_PERMISSION_APPLY_RESTRICTION) != 0;
-            } catch (NameNotFoundException e) {
-                Slog.w(LOG_TAG, "Cannot read permission state of " + perm, e);
-                return false;
-            }
-        }
-
-        /**
-         * Add op that belong to a foreground permission for later processing in
-         * {@link #syncPackages()}.
-         *
-         * <p>Note: Called with the package lock held. Do <u>not</u> call into app-op manager.
-         *
-         * @param permissionInfo The permission that is currently looked at
-         * @param pkg The package looked at
-         */
-        private void addOpIfFgPermissions(@NonNull PermissionInfo permissionInfo,
-                @NonNull PackageInfo pkg) {
-            final String bgPermissionName = permissionInfo.backgroundPermission;
-
-            if (bgPermissionName == null) {
+        private void addPermissionAppOp(@NonNull PackageInfo packageInfo,
+                @NonNull PermissionInfo permissionInfo) {
+            if (!permissionInfo.isRuntime()) {
                 return;
             }
 
-            final String permission = permissionInfo.name;
-            final int opCode = getSwitchOp(permission);
-            final String pkgName = pkg.packageName;
-            final int uid = pkg.applicationInfo.uid;
-
-            // App does not support runtime permissions. Hence the state is encoded in the app-op.
-            // To not override unrecoverable state don't change app-op unless bg perm is reviewed.
-            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
-                // If the review is required for this permission, the grant state does not
-                // really matter. To have a stable state, don't change the app-op if review is still
-                // pending.
-                int flags = mPackageManager.getPermissionFlags(bgPermissionName,
-                        pkg.packageName, UserHandle.getUserHandleForUid(uid));
-
-                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0
-                        && isBgPermRestricted(pkgName, bgPermissionName, uid)) {
-                    mOpsToForegroundIfAllow.add(new OpToChange(uid, pkgName, opCode));
-                }
-
+            String permissionName = permissionInfo.name;
+            String packageName = packageInfo.packageName;
+            int permissionFlags = mPackageManager.getPermissionFlags(permissionName,
+                    packageName, mContext.getUser());
+            boolean isReviewRequired = (permissionFlags & FLAG_PERMISSION_REVIEW_REQUIRED) != 0;
+            if (isReviewRequired) {
                 return;
             }
 
-            if (mPackageManager.checkPermission(permission, pkgName)
-                    == PackageManager.PERMISSION_GRANTED) {
-                final boolean isBgHardRestricted = isBgPermRestricted(pkgName, bgPermissionName,
-                        uid);
-                final boolean isBgPermGranted = mPackageManager.checkPermission(bgPermissionName,
-                        pkgName) == PackageManager.PERMISSION_GRANTED;
+            // TODO: COARSE_LOCATION and FINE_LOCATION shares the same app op. We are solving this
+            //  with switch op but once we start syncing single permission this won't work.
+            int appOpCode = getSwitchOp(permissionName);
+            if (appOpCode == OP_NONE) {
+                // Note that background permissions don't have an associated app op.
+                return;
+            }
 
-                if (!isBgHardRestricted && isBgPermGranted) {
-                    mOpsToAllow.add(new OpToChange(uid, pkgName, opCode));
+            int appOpMode;
+            boolean shouldGrantAppOp = shouldGrantAppOp(packageInfo, permissionInfo);
+            if (shouldGrantAppOp) {
+                if (permissionInfo.backgroundPermission != null) {
+                    PermissionInfo backgroundPermissionInfo = getPermissionInfo(
+                            permissionInfo.backgroundPermission);
+                    boolean shouldGrantBackgroundAppOp = backgroundPermissionInfo != null
+                            && shouldGrantAppOp(packageInfo, backgroundPermissionInfo);
+                    appOpMode = shouldGrantBackgroundAppOp ? MODE_ALLOWED : MODE_FOREGROUND;
                 } else {
-                    mOpsToForeground.add(new OpToChange(uid, pkgName, opCode));
+                    appOpMode = MODE_ALLOWED;
                 }
             } else {
-                mOpsToIgnore.add(new OpToChange(uid, pkgName, opCode));
+                appOpMode = MODE_IGNORED;
+            }
+
+            int uid = packageInfo.applicationInfo.uid;
+            OpToChange opToChange = new OpToChange(uid, packageName, appOpCode);
+            switch (appOpMode) {
+                case MODE_ALLOWED:
+                    mOpsToAllow.add(opToChange);
+                    break;
+                case MODE_FOREGROUND:
+                    mOpsToForeground.add(opToChange);
+                    break;
+                case MODE_IGNORED:
+                    mOpsToIgnore.add(opToChange);
+                    break;
+            }
+        }
+
+        @Nullable
+        private PermissionInfo getPermissionInfo(@NonNull String permissionName) {
+            try {
+                return mPackageManager.getPermissionInfo(permissionName, 0);
+            } catch (PackageManager.NameNotFoundException e) {
+                return null;
+            }
+        }
+
+        private boolean shouldGrantAppOp(@NonNull PackageInfo packageInfo,
+                @NonNull PermissionInfo permissionInfo) {
+            String permissionName = permissionInfo.name;
+            String packageName = packageInfo.packageName;
+            boolean isGranted = mPackageManager.checkPermission(permissionName, packageName)
+                    == PackageManager.PERMISSION_GRANTED;
+            if (!isGranted) {
+                return false;
+            }
+
+            int permissionFlags = mPackageManager.getPermissionFlags(permissionName, packageName,
+                    mContext.getUser());
+            boolean isRevokedCompat = (permissionFlags & FLAG_PERMISSION_REVOKED_COMPAT)
+                    == FLAG_PERMISSION_REVOKED_COMPAT;
+            if (isRevokedCompat) {
+                return false;
+            }
+
+            if (permissionInfo.isHardRestricted()) {
+                boolean shouldApplyRestriction =
+                        (permissionFlags & FLAG_PERMISSION_APPLY_RESTRICTION)
+                                == FLAG_PERMISSION_APPLY_RESTRICTION;
+                return !shouldApplyRestriction;
+            } else if (permissionInfo.isSoftRestricted()) {
+                SoftRestrictedPermissionPolicy policy =
+                        SoftRestrictedPermissionPolicy.forPermission(mContext,
+                                packageInfo.applicationInfo, mContext.getUser(), permissionName);
+                return policy.mayGrantPermission();
+            } else {
+                return true;
+            }
+        }
+
+        private void addExtraAppOp(@NonNull PackageInfo packageInfo,
+                @NonNull PermissionInfo permissionInfo) {
+            if (!permissionInfo.isSoftRestricted()) {
+                return;
+            }
+
+            String permissionName = permissionInfo.name;
+            SoftRestrictedPermissionPolicy policy =
+                    SoftRestrictedPermissionPolicy.forPermission(mContext,
+                            packageInfo.applicationInfo, mContext.getUser(), permissionName);
+            int extraOpCode = policy.getExtraAppOpCode();
+            if (extraOpCode == OP_NONE) {
+                return;
+            }
+
+            int uid = packageInfo.applicationInfo.uid;
+            String packageName = packageInfo.packageName;
+            OpToChange extraOpToChange = new OpToChange(uid, packageName, extraOpCode);
+            if (policy.mayAllowExtraAppOp()) {
+                mOpsToAllow.add(extraOpToChange);
+            } else {
+                if (policy.mayDenyExtraAppOpIfGranted()) {
+                    mOpsToIgnore.add(extraOpToChange);
+                } else {
+                    mOpsToIgnoreIfNotAllowed.add(extraOpToChange);
+                }
             }
         }
 
@@ -726,77 +644,44 @@
             }
 
             for (String permission : pkg.requestedPermissions) {
-                final int opCode = getSwitchOp(permission);
-                if (opCode == OP_NONE) {
-                    continue;
-                }
-
-                final PermissionInfo permissionInfo;
-                try {
-                    permissionInfo = mPackageManager.getPermissionInfo(permission, 0);
-                } catch (PackageManager.NameNotFoundException e) {
-                    continue;
-                }
-
-                addOpIfRestricted(permissionInfo, pkg);
-                addOpIfFgPermissions(permissionInfo, pkg);
+                addAppOps(pkg, permission);
             }
         }
 
-        private boolean setUidModeAllowedIfDefault(int opCode, int uid,
-                @NonNull String packageName) {
-            return setUidModeIfMode(opCode, uid, MODE_DEFAULT, MODE_ALLOWED, packageName);
-        }
-
         private void setUidModeAllowed(int opCode, int uid, @NonNull String packageName) {
             setUidMode(opCode, uid, MODE_ALLOWED, packageName);
         }
 
-        private boolean setUidModeForegroundIfAllow(int opCode, int uid,
-                @NonNull String packageName) {
-            return setUidModeIfMode(opCode, uid, MODE_ALLOWED, MODE_FOREGROUND, packageName);
-        }
-
         private void setUidModeForeground(int opCode, int uid, @NonNull String packageName) {
             setUidMode(opCode, uid, MODE_FOREGROUND, packageName);
         }
 
-        private boolean setUidModeIgnoredIfDefault(int opCode, int uid,
-                @NonNull String packageName) {
-            return setUidModeIfMode(opCode, uid, MODE_DEFAULT, MODE_IGNORED, packageName);
-        }
-
         private void setUidModeIgnored(int opCode, int uid, @NonNull String packageName) {
             setUidMode(opCode, uid, MODE_IGNORED, packageName);
         }
 
+        private boolean setUidModeIgnoredIfNotAllowed(int opCode, int uid,
+                @NonNull String packageName) {
+            final int currentMode = mAppOpsManager.unsafeCheckOpRaw(AppOpsManager.opToPublicName(
+                    opCode), uid, packageName);
+            if (currentMode != MODE_ALLOWED) {
+                if (currentMode != MODE_IGNORED) {
+                    mAppOpsManager.setUidMode(opCode, uid, MODE_IGNORED);
+                }
+                return true;
+            }
+            return false;
+        }
+
         private void setUidMode(int opCode, int uid, int mode,
                 @NonNull String packageName) {
             final int currentMode = mAppOpsManager.unsafeCheckOpRaw(AppOpsManager
                     .opToPublicName(opCode), uid, packageName);
-
             if (currentMode != mode) {
                 mAppOpsManager.setUidMode(opCode, uid, mode);
             }
         }
 
-        private boolean setUidModeIfMode(int opCode, int uid, int requiredModeBefore, int newMode,
-                @NonNull String packageName) {
-            final int currentMode = mAppOpsManager.unsafeCheckOpRaw(AppOpsManager
-                    .opToPublicName(opCode), uid, packageName);
-
-            if (currentMode == requiredModeBefore) {
-                mAppOpsManager.setUidMode(opCode, uid, newMode);
-                return true;
-            }
-
-            return false;
-        }
-
-        private void setUidModeDefault(int opCode, int uid, String packageName) {
-            setUidMode(opCode, uid, MODE_DEFAULT, packageName);
-        }
-
         private class OpToChange {
             final int uid;
             final @NonNull String packageName;
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index ab531899..c851cc6 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -23,6 +23,7 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
 import static android.content.Context.CONTEXT_RESTRICTED;
 import static android.content.Context.WINDOW_SERVICE;
+import static android.content.pm.PackageManager.FEATURE_AUTOMOTIVE;
 import static android.content.pm.PackageManager.FEATURE_HDMI_CEC;
 import static android.content.pm.PackageManager.FEATURE_LEANBACK;
 import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
@@ -204,6 +205,7 @@
 import com.android.internal.os.RoSystemProperties;
 import com.android.internal.policy.IKeyguardDismissCallback;
 import com.android.internal.policy.IShortcutService;
+import com.android.internal.policy.KeyInterceptionInfo;
 import com.android.internal.policy.PhoneWindow;
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.internal.util.ArrayUtils;
@@ -384,6 +386,7 @@
     BurnInProtectionHelper mBurnInProtectionHelper;
     private DisplayFoldController mDisplayFoldController;
     AppOpsManager mAppOpsManager;
+    private boolean mHasFeatureAuto;
     private boolean mHasFeatureWatch;
     private boolean mHasFeatureLeanback;
     private boolean mHasFeatureHdmiCec;
@@ -1603,7 +1606,7 @@
             mDisplayId = displayId;
         }
 
-        int handleHomeButton(WindowState win, KeyEvent event) {
+        int handleHomeButton(IBinder focusedToken, KeyEvent event) {
             final boolean keyguardOn = keyguardOn();
             final int repeatCount = event.getRepeatCount();
             final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
@@ -1646,18 +1649,18 @@
                 return -1;
             }
 
-            // If a system window has focus, then it doesn't make sense
-            // right now to interact with applications.
-            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
-            if (attrs != null) {
-                final int type = attrs.type;
-                if (type == TYPE_KEYGUARD_DIALOG
-                        || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
+            final KeyInterceptionInfo info =
+                    mWindowManagerInternal.getKeyInterceptionInfoFromToken(focusedToken);
+            if (info != null) {
+                // If a system window has focus, then it doesn't make sense
+                // right now to interact with applications.
+                if (info.layoutParamsType == TYPE_KEYGUARD_DIALOG
+                        || (info.layoutParamsPrivateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
                     // the "app" is keyguard, so give it the key
                     return 0;
                 }
                 for (int t : WINDOW_TYPES_WHERE_HOME_DOESNT_WORK) {
-                    if (type == t) {
+                    if (info.layoutParamsType == t) {
                         // don't do anything, but also don't pass it to the app
                         return -1;
                     }
@@ -1752,6 +1755,7 @@
         mDisplayManager = mContext.getSystemService(DisplayManager.class);
         mHasFeatureWatch = mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH);
         mHasFeatureLeanback = mContext.getPackageManager().hasSystemFeature(FEATURE_LEANBACK);
+        mHasFeatureAuto = mContext.getPackageManager().hasSystemFeature(FEATURE_AUTOMOTIVE);
         mHasFeatureHdmiCec = mContext.getPackageManager().hasSystemFeature(FEATURE_HDMI_CEC);
         mAccessibilityShortcutController =
                 new AccessibilityShortcutController(mContext, new Handler(), mCurrentUserId);
@@ -2598,8 +2602,9 @@
     // TODO(b/117479243): handle it in InputPolicy
     /** {@inheritDoc} */
     @Override
-    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
-        final long result = interceptKeyBeforeDispatchingInner(win, event, policyFlags);
+    public long interceptKeyBeforeDispatching(IBinder focusedToken, KeyEvent event,
+            int policyFlags) {
+        final long result = interceptKeyBeforeDispatchingInner(focusedToken, event, policyFlags);
         final int eventDisplayId = event.getDisplayId();
         if (result == 0 && !mPerDisplayFocusEnabled
                 && eventDisplayId != INVALID_DISPLAY && eventDisplayId != mTopFocusedDisplayId) {
@@ -2627,7 +2632,7 @@
         return result;
     }
 
-    private long interceptKeyBeforeDispatchingInner(WindowState win, KeyEvent event,
+    private long interceptKeyBeforeDispatchingInner(IBinder focusedToken, KeyEvent event,
             int policyFlags) {
         final boolean keyguardOn = keyguardOn();
         final int keyCode = event.getKeyCode();
@@ -2730,7 +2735,7 @@
                 handler = new DisplayHomeButtonHandler(displayId);
                 mDisplayHomeButtonHandlers.put(displayId, handler);
             }
-            return handler.handleHomeButton(win, event);
+            return handler.handleHomeButton(focusedToken, event);
         } else if (keyCode == KeyEvent.KEYCODE_MENU) {
             // Hijack modified menu keys for debugging features
             final int chordBug = KeyEvent.META_SHIFT_ON;
@@ -3120,8 +3125,7 @@
                 || Settings.Global.getInt(mContext.getContentResolver(),
                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) == 1) {
             try {
-                ActivityManager.getService()
-                        .requestBugReport(ActivityManager.BUGREPORT_OPTION_FULL);
+                ActivityManager.getService().requestFullBugReport();
             } catch (RemoteException e) {
                 Slog.e(TAG, "Error taking bugreport", e);
             }
@@ -3131,10 +3135,15 @@
     // TODO(b/117479243): handle it in InputPolicy
     /** {@inheritDoc} */
     @Override
-    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
+    public KeyEvent dispatchUnhandledKey(IBinder focusedToken, KeyEvent event, int policyFlags) {
         // Note: This method is only called if the initial down was unhandled.
         if (DEBUG_INPUT) {
-            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
+            final KeyInterceptionInfo info =
+                    mWindowManagerInternal.getKeyInterceptionInfoFromToken(focusedToken);
+            final String title = info == null ? "<unknown>" : info.windowTitle;
+            Slog.d(TAG, "Unhandled key: inputToken=" + focusedToken
+                    + ", title=" + title
+                    + ", action=" + event.getAction()
                     + ", flags=" + event.getFlags()
                     + ", keyCode=" + event.getKeyCode()
                     + ", scanCode=" + event.getScanCode()
@@ -3173,7 +3182,7 @@
                         event.getDeviceId(), event.getScanCode(),
                         flags, event.getSource(), event.getDisplayId(), null);
 
-                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
+                if (!interceptFallback(focusedToken, fallbackEvent, policyFlags)) {
                     fallbackEvent.recycle();
                     fallbackEvent = null;
                 }
@@ -3197,11 +3206,12 @@
         return fallbackEvent;
     }
 
-    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
+    private boolean interceptFallback(IBinder focusedToken, KeyEvent fallbackEvent,
+            int policyFlags) {
         int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
         if ((actions & ACTION_PASS_TO_USER) != 0) {
             long delayMillis = interceptKeyBeforeDispatching(
-                    win, fallbackEvent, policyFlags);
+                    focusedToken, fallbackEvent, policyFlags);
             if (delayMillis == 0) {
                 return true;
             }
@@ -4533,6 +4543,12 @@
     private void wakeUpFromPowerKey(long eventTime) {
         wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey,
                 PowerManager.WAKE_REASON_POWER_BUTTON, "android.policy:POWER");
+
+        // Turn on the connected TV and switch HDMI input if we're a HDMI playback device.
+        final HdmiControl hdmiControl = getHdmiControl();
+        if (hdmiControl != null) {
+            hdmiControl.turnOnTv();
+        }
     }
 
     private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, @WakeReason int reason,
@@ -4565,7 +4581,7 @@
         // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
         // as well as enabling the orientation change logic/sensor.
         mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
-                WAITING_FOR_DRAWN_TIMEOUT);
+                WAITING_FOR_DRAWN_TIMEOUT, INVALID_DISPLAY);
     }
 
     // Called on the DisplayManager's DisplayPowerController thread.
@@ -5215,7 +5231,7 @@
             awakenDreams();
         }
 
-        if (!isUserSetupComplete()) {
+        if (!mHasFeatureAuto && !isUserSetupComplete()) {
             Slog.i(TAG, "Not going home because user setup is in progress.");
             return;
         }
diff --git a/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java b/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java
index c1a6dbd..b0f22e4 100644
--- a/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java
+++ b/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java
@@ -18,9 +18,6 @@
 
 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
-import static android.app.AppOpsManager.MODE_ALLOWED;
-import static android.app.AppOpsManager.MODE_DEFAULT;
-import static android.app.AppOpsManager.MODE_IGNORED;
 import static android.app.AppOpsManager.OP_LEGACY_STORAGE;
 import static android.app.AppOpsManager.OP_NONE;
 import static android.content.pm.PackageManager.FLAG_PERMISSION_APPLY_RESTRICTION;
@@ -55,22 +52,7 @@
     private static final SoftRestrictedPermissionPolicy DUMMY_POLICY =
             new SoftRestrictedPermissionPolicy() {
                 @Override
-                public int resolveAppOp() {
-                    return OP_NONE;
-                }
-
-                @Override
-                public int getDesiredOpMode() {
-                    return MODE_DEFAULT;
-                }
-
-                @Override
-                public boolean shouldSetAppOpIfNotDefault() {
-                    return false;
-                }
-
-                @Override
-                public boolean canBeGranted() {
+                public boolean mayGrantPermission() {
                     return true;
                 }
             };
@@ -114,10 +96,8 @@
      * Get the policy for a soft restricted permission.
      *
      * @param context A context to use
-     * @param appInfo The application the permission belongs to. Can be {@code null}, but then
-     *                only {@link #resolveAppOp} will work.
-     * @param user The user the app belongs to. Can be {@code null}, but then only
-     *             {@link #resolveAppOp} will work.
+     * @param appInfo The application the permission belongs to.
+     * @param user The user the app belongs to.
      * @param permission The name of the permission
      *
      * @return The policy for this permission
@@ -130,82 +110,46 @@
             // where the restricted state allows the permission but only for accessing the medial
             // collections.
             case READ_EXTERNAL_STORAGE: {
-                final int flags;
-                final boolean applyRestriction;
                 final boolean isWhiteListed;
-                final boolean hasRequestedLegacyExternalStorage;
+                boolean shouldApplyRestriction;
                 final int targetSDK;
+                final boolean hasRequestedLegacyExternalStorage;
 
                 if (appInfo != null) {
                     PackageManager pm = context.getPackageManager();
-                    flags = pm.getPermissionFlags(permission, appInfo.packageName, user);
-                    applyRestriction = (flags & FLAG_PERMISSION_APPLY_RESTRICTION) != 0;
+                    int flags = pm.getPermissionFlags(permission, appInfo.packageName, user);
                     isWhiteListed = (flags & FLAGS_PERMISSION_RESTRICTION_ANY_EXEMPT) != 0;
+                    shouldApplyRestriction = (flags & FLAG_PERMISSION_APPLY_RESTRICTION) != 0;
                     targetSDK = getMinimumTargetSDK(context, appInfo, user);
-
-                    boolean hasAnyRequestedLegacyExternalStorage =
-                            appInfo.hasRequestedLegacyExternalStorage();
-
-                    // hasRequestedLegacyExternalStorage is per package. To make sure two apps in
-                    // the same shared UID do not fight over what to set, always compute the
-                    // combined hasRequestedLegacyExternalStorage
-                    String[] uidPkgs = pm.getPackagesForUid(appInfo.uid);
-                    if (uidPkgs != null) {
-                        for (String uidPkg : uidPkgs) {
-                            if (!uidPkg.equals(appInfo.packageName)) {
-                                ApplicationInfo uidPkgInfo;
-                                try {
-                                    uidPkgInfo = pm.getApplicationInfoAsUser(uidPkg, 0, user);
-                                } catch (PackageManager.NameNotFoundException e) {
-                                    continue;
-                                }
-
-                                hasAnyRequestedLegacyExternalStorage |=
-                                        uidPkgInfo.hasRequestedLegacyExternalStorage();
-                            }
-                        }
-                    }
-
-                    hasRequestedLegacyExternalStorage = hasAnyRequestedLegacyExternalStorage;
+                    hasRequestedLegacyExternalStorage = hasUidRequestedLegacyExternalStorage(
+                            appInfo.uid, context);
                 } else {
-                    flags = 0;
-                    applyRestriction = false;
                     isWhiteListed = false;
-                    hasRequestedLegacyExternalStorage = false;
+                    shouldApplyRestriction = false;
                     targetSDK = 0;
+                    hasRequestedLegacyExternalStorage = false;
                 }
 
+                // We have a check in PermissionPolicyService.PermissionToOpSynchroniser.setUidMode
+                // to prevent apps losing files in legacy storage, because we are holding the
+                // package manager lock here. If we ever remove this policy that check should be
+                // removed as well.
                 return new SoftRestrictedPermissionPolicy() {
                     @Override
-                    public int resolveAppOp() {
+                    public boolean mayGrantPermission() {
+                        return isWhiteListed || targetSDK >= Build.VERSION_CODES.Q;
+                    }
+                    @Override
+                    public int getExtraAppOpCode() {
                         return OP_LEGACY_STORAGE;
                     }
-
                     @Override
-                    public int getDesiredOpMode() {
-                        if (applyRestriction) {
-                            return MODE_DEFAULT;
-                        } else if (hasRequestedLegacyExternalStorage) {
-                            return MODE_ALLOWED;
-                        } else {
-                            return MODE_IGNORED;
-                        }
+                    public boolean mayAllowExtraAppOp() {
+                        return !shouldApplyRestriction && hasRequestedLegacyExternalStorage;
                     }
-
                     @Override
-                    public boolean shouldSetAppOpIfNotDefault() {
-                        // Do not switch from allowed -> ignored as this would mean to retroactively
-                        // turn on isolated storage. This will make the app loose all its files.
-                        return getDesiredOpMode() != MODE_IGNORED;
-                    }
-
-                    @Override
-                    public boolean canBeGranted() {
-                        if (isWhiteListed || targetSDK >= Build.VERSION_CODES.Q) {
-                            return true;
-                        } else {
-                            return false;
-                        }
+                    public boolean mayDenyExtraAppOpIfGranted() {
+                        return shouldApplyRestriction;
                     }
                 };
             }
@@ -225,22 +169,7 @@
 
                 return new SoftRestrictedPermissionPolicy() {
                     @Override
-                    public int resolveAppOp() {
-                        return OP_NONE;
-                    }
-
-                    @Override
-                    public int getDesiredOpMode() {
-                        return MODE_DEFAULT;
-                    }
-
-                    @Override
-                    public boolean shouldSetAppOpIfNotDefault() {
-                        return false;
-                    }
-
-                    @Override
-                    public boolean canBeGranted() {
+                    public boolean mayGrantPermission() {
                         return isWhiteListed || targetSDK >= Build.VERSION_CODES.Q;
                     }
                 };
@@ -250,25 +179,51 @@
         }
     }
 
-    /**
-     * @return An app op to be changed based on the state of the permission or
-     * {@link AppOpsManager#OP_NONE} if not app-op should be set.
-     */
-    public abstract int resolveAppOp();
-
-    /**
-     * @return The mode the {@link #resolveAppOp() app op} should be in.
-     */
-    public abstract @AppOpsManager.Mode int getDesiredOpMode();
-
-    /**
-     * @return If the {@link #resolveAppOp() app op} should be set even if the app-op is currently
-     * not {@link AppOpsManager#MODE_DEFAULT}.
-     */
-    public abstract boolean shouldSetAppOpIfNotDefault();
+    private static boolean hasUidRequestedLegacyExternalStorage(int uid, @NonNull Context context) {
+        PackageManager packageManager = context.getPackageManager();
+        String[] packageNames = packageManager.getPackagesForUid(uid);
+        if (packageNames == null) {
+            return false;
+        }
+        UserHandle user = UserHandle.getUserHandleForUid(uid);
+        for (String packageName : packageNames) {
+            ApplicationInfo applicationInfo;
+            try {
+                applicationInfo = packageManager.getApplicationInfoAsUser(packageName, 0, user);
+            } catch (PackageManager.NameNotFoundException e) {
+                continue;
+            }
+            if (applicationInfo.hasRequestedLegacyExternalStorage()) {
+                return true;
+            }
+        }
+        return false;
+    }
 
     /**
      * @return If the permission can be granted
      */
-    public abstract boolean canBeGranted();
+    public abstract boolean mayGrantPermission();
+
+    /**
+     * @return An app op to be changed based on the state of the permission or
+     * {@link AppOpsManager#OP_NONE} if not app-op should be set.
+     */
+    public int getExtraAppOpCode() {
+        return OP_NONE;
+    }
+
+    /**
+     * @return Whether the {@link #getExtraAppOpCode() app op} may be granted.
+     */
+    public boolean mayAllowExtraAppOp() {
+        return false;
+    }
+
+    /**
+     * @return Whether the {@link #getExtraAppOpCode() app op} may be denied if was granted.
+     */
+    public boolean mayDenyExtraAppOpIfGranted() {
+        return false;
+    }
 }
diff --git a/services/core/java/com/android/server/policy/WindowManagerPolicy.java b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
index 6d9c710..01250db 100644
--- a/services/core/java/com/android/server/policy/WindowManagerPolicy.java
+++ b/services/core/java/com/android/server/policy/WindowManagerPolicy.java
@@ -173,7 +173,7 @@
 
     /**
      * Interface to the Window Manager state associated with a particular
-     * window.  You can hold on to an instance of this interface from the call
+     * window. You can hold on to an instance of this interface from the call
      * to prepareAddWindow() until removeWindow().
      */
     public interface WindowState {
@@ -1025,7 +1025,7 @@
      * behavior for keys that can not be overridden by applications.
      * This method is called from the input thread, with no locks held.
      *
-     * @param win The window that currently has focus.  This is where the key
+     * @param focusedToken Client window token that currently has focus. This is where the key
      *            event will normally go.
      * @param event The key event.
      * @param policyFlags The policy flags associated with the key.
@@ -1034,7 +1034,7 @@
      * milliseconds by which the key dispatch should be delayed before trying
      * again.
      */
-    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags);
+    long interceptKeyBeforeDispatching(IBinder focusedToken, KeyEvent event, int policyFlags);
 
     /**
      * Called from the input dispatcher thread when an application did not handle
@@ -1043,14 +1043,14 @@
      * <p>Allows you to define default global behavior for keys that were not handled
      * by applications.  This method is called from the input thread, with no locks held.
      *
-     * @param win The window that currently has focus.  This is where the key
+     * @param focusedToken Client window token that currently has focus. This is where the key
      *            event will normally go.
      * @param event The key event.
      * @param policyFlags The policy flags associated with the key.
      * @return Returns an alternate key event to redispatch as a fallback, or null to give up.
      * The caller is responsible for recycling the key event.
      */
-    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags);
+    KeyEvent dispatchUnhandledKey(IBinder focusedToken, KeyEvent event, int policyFlags);
 
     /**
      * Called when the top focused display is changed.
diff --git a/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java b/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java
index 712012d..017c684 100644
--- a/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java
+++ b/services/core/java/com/android/server/policy/role/LegacyRoleResolutionPolicy.java
@@ -21,6 +21,7 @@
 import android.app.role.RoleManager;
 import android.content.ComponentName;
 import android.content.Context;
+import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManagerInternal;
 import android.content.pm.ResolveInfo;
@@ -34,9 +35,9 @@
 import com.android.server.LocalServices;
 import com.android.server.role.RoleManagerService;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Logic to retrieve the various legacy(pre-Q) equivalents of role holders.
@@ -125,9 +126,21 @@
             }
             case RoleManager.ROLE_HOME: {
                 PackageManager packageManager = mContext.getPackageManager();
-                List<ResolveInfo> resolveInfos = new ArrayList<>();
-                ComponentName componentName = packageManager.getHomeActivities(resolveInfos);
-                String packageName = componentName != null ? componentName.getPackageName() : null;
+                String packageName;
+                if (packageManager.isDeviceUpgrading()) {
+                    ResolveInfo resolveInfo = packageManager.resolveActivityAsUser(
+                            new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME),
+                            PackageManager.MATCH_DEFAULT_ONLY
+                                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
+                                    | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
+                    packageName = resolveInfo != null && resolveInfo.activityInfo != null
+                            ? resolveInfo.activityInfo.packageName : null;
+                    if (packageName != null && isSettingsApplication(packageName, userId)) {
+                        packageName = null;
+                    }
+                } else {
+                    packageName = null;
+                }
                 return CollectionUtils.singletonOrEmpty(packageName);
             }
             case RoleManager.ROLE_EMERGENCY: {
@@ -142,4 +155,16 @@
             }
         }
     }
+
+    private boolean isSettingsApplication(@NonNull String packageName, @UserIdInt int userId) {
+        PackageManager packageManager = mContext.getPackageManager();
+        ResolveInfo resolveInfo = packageManager.resolveActivityAsUser(new Intent(
+                Settings.ACTION_SETTINGS), PackageManager.MATCH_DEFAULT_ONLY
+                | PackageManager.MATCH_DIRECT_BOOT_AWARE
+                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
+        if (resolveInfo == null || resolveInfo.activityInfo == null) {
+            return false;
+        }
+        return Objects.equals(packageName, resolveInfo.activityInfo.packageName);
+    }
 }
diff --git a/services/core/java/com/android/server/protolog/ProtoLogImpl.java b/services/core/java/com/android/server/protolog/ProtoLogImpl.java
new file mode 100644
index 0000000..20bab55
--- /dev/null
+++ b/services/core/java/com/android/server/protolog/ProtoLogImpl.java
@@ -0,0 +1,454 @@
+/*
+ * Copyright (C) 2019 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.protolog;
+
+import static com.android.server.protolog.ProtoLogFileProto.LOG;
+import static com.android.server.protolog.ProtoLogFileProto.MAGIC_NUMBER;
+import static com.android.server.protolog.ProtoLogFileProto.MAGIC_NUMBER_H;
+import static com.android.server.protolog.ProtoLogFileProto.MAGIC_NUMBER_L;
+import static com.android.server.protolog.ProtoLogFileProto.REAL_TIME_TO_ELAPSED_TIME_OFFSET_MILLIS;
+import static com.android.server.protolog.ProtoLogFileProto.VERSION;
+import static com.android.server.protolog.ProtoLogMessage.BOOLEAN_PARAMS;
+import static com.android.server.protolog.ProtoLogMessage.DOUBLE_PARAMS;
+import static com.android.server.protolog.ProtoLogMessage.ELAPSED_REALTIME_NANOS;
+import static com.android.server.protolog.ProtoLogMessage.MESSAGE_HASH;
+import static com.android.server.protolog.ProtoLogMessage.SINT64_PARAMS;
+import static com.android.server.protolog.ProtoLogMessage.STR_PARAMS;
+
+import android.annotation.Nullable;
+import android.os.ShellCommand;
+import android.os.SystemClock;
+import android.util.Slog;
+import android.util.proto.ProtoOutputStream;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.protolog.common.IProtoLogGroup;
+import com.android.server.protolog.common.LogDataType;
+import com.android.server.utils.TraceBuffer;
+import com.android.server.wm.ProtoLogGroup;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.IllegalFormatConversionException;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+
+/**
+ * A service for the ProtoLog logging system.
+ */
+public class ProtoLogImpl {
+    private static final TreeMap<String, IProtoLogGroup> LOG_GROUPS = new TreeMap<>();
+
+    private static void addLogGroupEnum(IProtoLogGroup[] config) {
+        Arrays.stream(config).forEach(group -> LOG_GROUPS.put(group.name(), group));
+    }
+
+    static {
+        addLogGroupEnum(ProtoLogGroup.values());
+    }
+
+    /** Used by the ProtoLogTool, do not call directly - use {@code ProtoLog} class instead. */
+    public static void d(IProtoLogGroup group, int messageHash, int paramsMask,
+            @Nullable String messageString,
+            Object... args) {
+        getSingleInstance()
+                .log(LogLevel.DEBUG, group, messageHash, paramsMask, messageString, args);
+    }
+
+    /** Used by the ProtoLogTool, do not call directly - use {@code ProtoLog} class instead. */
+    public static void v(IProtoLogGroup group, int messageHash, int paramsMask,
+            @Nullable String messageString,
+            Object... args) {
+        getSingleInstance().log(LogLevel.VERBOSE, group, messageHash, paramsMask, messageString,
+                args);
+    }
+
+    /** Used by the ProtoLogTool, do not call directly - use {@code ProtoLog} class instead. */
+    public static void i(IProtoLogGroup group, int messageHash, int paramsMask,
+            @Nullable String messageString,
+            Object... args) {
+        getSingleInstance().log(LogLevel.INFO, group, messageHash, paramsMask, messageString, args);
+    }
+
+    /** Used by the ProtoLogTool, do not call directly - use {@code ProtoLog} class instead. */
+    public static void w(IProtoLogGroup group, int messageHash, int paramsMask,
+            @Nullable String messageString,
+            Object... args) {
+        getSingleInstance().log(LogLevel.WARN, group, messageHash, paramsMask, messageString, args);
+    }
+
+    /** Used by the ProtoLogTool, do not call directly - use {@code ProtoLog} class instead. */
+    public static void e(IProtoLogGroup group, int messageHash, int paramsMask,
+            @Nullable String messageString,
+            Object... args) {
+        getSingleInstance()
+                .log(LogLevel.ERROR, group, messageHash, paramsMask, messageString, args);
+    }
+
+    /** Used by the ProtoLogTool, do not call directly - use {@code ProtoLog} class instead. */
+    public static void wtf(IProtoLogGroup group, int messageHash, int paramsMask,
+            @Nullable String messageString,
+            Object... args) {
+        getSingleInstance().log(LogLevel.WTF, group, messageHash, paramsMask, messageString, args);
+    }
+
+    /** Returns true iff logging is enabled for the given {@code IProtoLogGroup}. */
+    public static boolean isEnabled(IProtoLogGroup group) {
+        return group.isLogToProto()
+                || (group.isLogToProto() && getSingleInstance().isProtoEnabled());
+    }
+
+    private static final int BUFFER_CAPACITY = 1024 * 1024;
+    private static final String LOG_FILENAME = "/data/misc/wmtrace/wm_log.pb";
+    private static final String VIEWER_CONFIG_FILENAME = "/system/etc/protolog.conf.json.gz";
+    private static final String TAG = "ProtoLog";
+    private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
+    static final String PROTOLOG_VERSION = "1.0.0";
+
+    private final File mLogFile;
+    private final TraceBuffer mBuffer;
+    private final ProtoLogViewerConfigReader mViewerConfig;
+
+    private boolean mProtoLogEnabled;
+    private boolean mProtoLogEnabledLockFree;
+    private final Object mProtoLogEnabledLock = new Object();
+
+    private static ProtoLogImpl sServiceInstance = null;
+
+    /**
+     * Returns the single instance of the ProtoLogImpl singleton class.
+     */
+    public static synchronized ProtoLogImpl getSingleInstance() {
+        if (sServiceInstance == null) {
+            sServiceInstance = new ProtoLogImpl(new File(LOG_FILENAME), BUFFER_CAPACITY,
+                    new ProtoLogViewerConfigReader());
+        }
+        return sServiceInstance;
+    }
+
+    @VisibleForTesting
+    public static synchronized void setSingleInstance(@Nullable ProtoLogImpl instance) {
+        sServiceInstance = instance;
+    }
+
+    @VisibleForTesting
+    public enum LogLevel {
+        DEBUG, VERBOSE, INFO, WARN, ERROR, WTF
+    }
+
+    /**
+     * Main log method, do not call directly.
+     */
+    @VisibleForTesting
+    public void log(LogLevel level, IProtoLogGroup group, int messageHash, int paramsMask,
+            @Nullable String messageString, Object[] args) {
+        if (group.isLogToProto()) {
+            logToProto(messageHash, paramsMask, args);
+        }
+        if (group.isLogToLogcat()) {
+            logToLogcat(group.getTag(), level, messageHash, messageString, args);
+        }
+    }
+
+    private void logToLogcat(String tag, LogLevel level, int messageHash,
+            @Nullable String messageString, Object[] args) {
+        String message = null;
+        if (messageString == null) {
+            messageString = mViewerConfig.getViewerString(messageHash);
+        }
+        if (messageString != null) {
+            try {
+                message = String.format(messageString, args);
+            } catch (IllegalFormatConversionException ex) {
+                Slog.w(TAG, "Invalid ProtoLog format string.", ex);
+            }
+        }
+        if (message == null) {
+            StringBuilder builder = new StringBuilder("UNKNOWN MESSAGE (" + messageHash + ")");
+            for (Object o : args) {
+                builder.append(" ").append(o);
+            }
+            message = builder.toString();
+        }
+        passToLogcat(tag, level, message);
+    }
+
+    /**
+     * SLog wrapper.
+     */
+    @VisibleForTesting
+    public void passToLogcat(String tag, LogLevel level, String message) {
+        switch (level) {
+            case DEBUG:
+                Slog.d(tag, message);
+                break;
+            case VERBOSE:
+                Slog.v(tag, message);
+                break;
+            case INFO:
+                Slog.i(tag, message);
+                break;
+            case WARN:
+                Slog.w(tag, message);
+                break;
+            case ERROR:
+                Slog.e(tag, message);
+                break;
+            case WTF:
+                Slog.wtf(tag, message);
+                break;
+        }
+    }
+
+    private void logToProto(int messageHash, int paramsMask, Object[] args) {
+        if (!isProtoEnabled()) {
+            return;
+        }
+        try {
+            ProtoOutputStream os = new ProtoOutputStream();
+            long token = os.start(LOG);
+            os.write(MESSAGE_HASH, messageHash);
+            os.write(ELAPSED_REALTIME_NANOS, SystemClock.elapsedRealtimeNanos());
+
+            if (args != null) {
+                int argIndex = 0;
+                ArrayList<Long> longParams = new ArrayList<>();
+                ArrayList<Double> doubleParams = new ArrayList<>();
+                ArrayList<Boolean> booleanParams = new ArrayList<>();
+                for (Object o : args) {
+                    int type = LogDataType.bitmaskToLogDataType(paramsMask, argIndex);
+                    try {
+                        switch (type) {
+                            case LogDataType.STRING:
+                                os.write(STR_PARAMS, o.toString());
+                                break;
+                            case LogDataType.LONG:
+                                longParams.add(((Number) o).longValue());
+                                break;
+                            case LogDataType.DOUBLE:
+                                doubleParams.add(((Number) o).doubleValue());
+                                break;
+                            case LogDataType.BOOLEAN:
+                                booleanParams.add((boolean) o);
+                                break;
+                        }
+                    } catch (ClassCastException ex) {
+                        // Should not happen unless there is an error in the ProtoLogTool.
+                        os.write(STR_PARAMS, "(INVALID PARAMS_MASK) " + o.toString());
+                        Slog.e(TAG, "Invalid ProtoLog paramsMask", ex);
+                    }
+                    argIndex++;
+                }
+                if (longParams.size() > 0) {
+                    os.writePackedSInt64(SINT64_PARAMS,
+                            longParams.stream().mapToLong(i -> i).toArray());
+                }
+                if (doubleParams.size() > 0) {
+                    os.writePackedDouble(DOUBLE_PARAMS,
+                            doubleParams.stream().mapToDouble(i -> i).toArray());
+                }
+                if (booleanParams.size() > 0) {
+                    boolean[] arr = new boolean[booleanParams.size()];
+                    for (int i = 0; i < booleanParams.size(); i++) {
+                        arr[i] = booleanParams.get(i);
+                    }
+                    os.writePackedBool(BOOLEAN_PARAMS, arr);
+                }
+            }
+            os.end(token);
+            mBuffer.add(os);
+        } catch (Exception e) {
+            Slog.e(TAG, "Exception while logging to proto", e);
+        }
+    }
+
+
+    @VisibleForTesting
+    ProtoLogImpl(File file, int bufferCapacity, ProtoLogViewerConfigReader viewerConfig) {
+        mLogFile = file;
+        mBuffer = new TraceBuffer(bufferCapacity);
+        mViewerConfig = viewerConfig;
+    }
+
+    /**
+     * Starts the logging a circular proto buffer.
+     *
+     * @param pw Print writer
+     */
+    public void startProtoLog(@Nullable PrintWriter pw) {
+        if (isProtoEnabled()) {
+            return;
+        }
+        synchronized (mProtoLogEnabledLock) {
+            logAndPrintln(pw, "Start logging to " + mLogFile + ".");
+            mBuffer.resetBuffer();
+            mProtoLogEnabled = true;
+            mProtoLogEnabledLockFree = true;
+        }
+    }
+
+    /**
+     * Stops logging to proto.
+     *
+     * @param pw          Print writer
+     * @param writeToFile If the current buffer should be written to disk or not
+     */
+    public void stopProtoLog(@Nullable PrintWriter pw, boolean writeToFile) {
+        if (!isProtoEnabled()) {
+            return;
+        }
+        synchronized (mProtoLogEnabledLock) {
+            logAndPrintln(pw, "Stop logging to " + mLogFile + ". Waiting for log to flush.");
+            mProtoLogEnabled = mProtoLogEnabledLockFree = false;
+            if (writeToFile) {
+                writeProtoLogToFileLocked();
+                logAndPrintln(pw, "Log written to " + mLogFile + ".");
+            }
+            if (mProtoLogEnabled) {
+                logAndPrintln(pw, "ERROR: logging was re-enabled while waiting for flush.");
+                throw new IllegalStateException("logging enabled while waiting for flush.");
+            }
+        }
+    }
+
+    /**
+     * Returns {@code true} iff logging to proto is enabled.
+     */
+    public boolean isProtoEnabled() {
+        return mProtoLogEnabledLockFree;
+    }
+
+    private int setLogging(ShellCommand shell, boolean setTextLogging, boolean value) {
+        String group;
+        while ((group = shell.getNextArg()) != null) {
+            IProtoLogGroup g = LOG_GROUPS.get(group);
+            if (g != null) {
+                if (setTextLogging) {
+                    g.setLogToLogcat(value);
+                } else {
+                    g.setLogToProto(value);
+                }
+            } else {
+                logAndPrintln(shell.getOutPrintWriter(), "No IProtoLogGroup named " + group);
+                return -1;
+            }
+        }
+        return 0;
+    }
+
+    private int unknownCommand(PrintWriter pw) {
+        pw.println("Unknown command");
+        pw.println("Window manager logging options:");
+        pw.println("  start: Start proto logging");
+        pw.println("  stop: Stop proto logging");
+        pw.println("  enable [group...]: Enable proto logging for given groups");
+        pw.println("  disable [group...]: Disable proto logging for given groups");
+        pw.println("  enable-text [group...]: Enable logcat logging for given groups");
+        pw.println("  disable-text [group...]: Disable logcat logging for given groups");
+        return -1;
+    }
+
+    /**
+     * Responds to a shell command.
+     */
+    public int onShellCommand(ShellCommand shell) {
+        PrintWriter pw = shell.getOutPrintWriter();
+        String cmd = shell.getNextArg();
+        if (cmd == null) {
+            return unknownCommand(pw);
+        }
+        switch (cmd) {
+            case "start":
+                startProtoLog(pw);
+                return 0;
+            case "stop":
+                stopProtoLog(pw, true);
+                return 0;
+            case "status":
+                logAndPrintln(pw, getStatus());
+                return 0;
+            case "enable":
+                return setLogging(shell, false, true);
+            case "enable-text":
+                mViewerConfig.loadViewerConfig(pw, VIEWER_CONFIG_FILENAME);
+                return setLogging(shell, true, true);
+            case "disable":
+                return setLogging(shell, false, false);
+            case "disable-text":
+                return setLogging(shell, true, false);
+            default:
+                return unknownCommand(pw);
+        }
+    }
+
+    /**
+     * Returns a human-readable ProtoLog status text.
+     */
+    public String getStatus() {
+        return "ProtoLog status: "
+                + ((isProtoEnabled()) ? "Enabled" : "Disabled")
+                + "\nEnabled log groups: \n  Proto: "
+                + LOG_GROUPS.values().stream().filter(
+                    it -> it.isEnabled() && it.isLogToProto())
+                .map(IProtoLogGroup::name).collect(Collectors.joining(" "))
+                + "\n  Logcat: "
+                + LOG_GROUPS.values().stream().filter(
+                    it -> it.isEnabled() && it.isLogToLogcat())
+                .map(IProtoLogGroup::name).collect(Collectors.joining(" "))
+                + "\nLogging definitions loaded: " + mViewerConfig.knownViewerStringsNumber();
+    }
+
+    /**
+     * Writes the log buffer to a new file for the bugreport.
+     *
+     * This method is synchronized with {@code #startProtoLog(PrintWriter)} and
+     * {@link #stopProtoLog(PrintWriter, boolean)}.
+     */
+    public void writeProtoLogToFile() {
+        synchronized (mProtoLogEnabledLock) {
+            writeProtoLogToFileLocked();
+        }
+    }
+
+    private void writeProtoLogToFileLocked() {
+        try {
+            long offset =
+                    (System.currentTimeMillis() - (SystemClock.elapsedRealtimeNanos() / 1000000));
+            ProtoOutputStream proto = new ProtoOutputStream();
+            proto.write(MAGIC_NUMBER, MAGIC_NUMBER_VALUE);
+            proto.write(VERSION, PROTOLOG_VERSION);
+            proto.write(REAL_TIME_TO_ELAPSED_TIME_OFFSET_MILLIS, offset);
+            mBuffer.writeTraceToFile(mLogFile, proto);
+        } catch (IOException e) {
+            Slog.e(TAG, "Unable to write buffer to file", e);
+        }
+    }
+
+
+    static void logAndPrintln(@Nullable PrintWriter pw, String msg) {
+        Slog.i(TAG, msg);
+        if (pw != null) {
+            pw.println(msg);
+            pw.flush();
+        }
+    }
+}
+
diff --git a/services/core/java/com/android/server/protolog/ProtoLogViewerConfigReader.java b/services/core/java/com/android/server/protolog/ProtoLogViewerConfigReader.java
new file mode 100644
index 0000000..4944217
--- /dev/null
+++ b/services/core/java/com/android/server/protolog/ProtoLogViewerConfigReader.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2019 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.protolog;
+
+import static com.android.server.protolog.ProtoLogImpl.logAndPrintln;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.zip.GZIPInputStream;
+
+/**
+ * Handles loading and parsing of ProtoLog viewer configuration.
+ */
+public class ProtoLogViewerConfigReader {
+    private Map<Integer, String> mLogMessageMap = null;
+
+    /** Returns message format string for its hash or null if unavailable. */
+    public synchronized String getViewerString(int messageHash) {
+        if (mLogMessageMap != null) {
+            return mLogMessageMap.get(messageHash);
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Reads the specified viewer configuration file. Does nothing if the config is already loaded.
+     */
+    public synchronized void loadViewerConfig(PrintWriter pw, String viewerConfigFilename) {
+        if (mLogMessageMap != null) {
+            return;
+        }
+        try {
+            InputStreamReader config = new InputStreamReader(
+                    new GZIPInputStream(new FileInputStream(viewerConfigFilename)));
+            BufferedReader reader = new BufferedReader(config);
+            StringBuilder builder = new StringBuilder();
+            String line;
+            while ((line = reader.readLine()) != null) {
+                builder.append(line).append('\n');
+            }
+            reader.close();
+            JSONObject json = new JSONObject(builder.toString());
+            JSONObject messages = json.getJSONObject("messages");
+
+            mLogMessageMap = new TreeMap<>();
+            Iterator it = messages.keys();
+            while (it.hasNext()) {
+                String key = (String) it.next();
+                try {
+                    int hash = Integer.parseInt(key);
+                    JSONObject val = messages.getJSONObject(key);
+                    String msg = val.getString("message");
+                    mLogMessageMap.put(hash, msg);
+                } catch (NumberFormatException expected) {
+                    // Not a messageHash - skip it
+                }
+            }
+            logAndPrintln(pw, "Loaded " + mLogMessageMap.size() + " log definitions from "
+                    + viewerConfigFilename);
+        } catch (FileNotFoundException e) {
+            logAndPrintln(pw, "Unable to load log definitions: File "
+                    + viewerConfigFilename + " not found." + e);
+        } catch (IOException e) {
+            logAndPrintln(pw, "Unable to load log definitions: IOException while reading "
+                    + viewerConfigFilename + ". " + e);
+        } catch (JSONException e) {
+            logAndPrintln(pw,
+                    "Unable to load log definitions: JSON parsing exception while reading "
+                            + viewerConfigFilename + ". " + e);
+        }
+    }
+
+    /**
+     * Returns the number of loaded log definitions kept in memory.
+     */
+    public synchronized int knownViewerStringsNumber() {
+        if (mLogMessageMap != null) {
+            return mLogMessageMap.size();
+        }
+        return 0;
+    }
+}
diff --git a/services/core/java/com/android/server/protolog/common/BitmaskConversionException.java b/services/core/java/com/android/server/protolog/common/BitmaskConversionException.java
new file mode 100644
index 0000000..7bb27b2
--- /dev/null
+++ b/services/core/java/com/android/server/protolog/common/BitmaskConversionException.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2019 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.protolog.common;
+
+/**
+ * Error while converting a bitmask representing a list of LogDataTypes.
+ */
+public class BitmaskConversionException extends RuntimeException {
+    BitmaskConversionException(String msg) {
+        super(msg);
+    }
+}
diff --git a/services/core/java/com/android/server/protolog/common/IProtoLogGroup.java b/services/core/java/com/android/server/protolog/common/IProtoLogGroup.java
new file mode 100644
index 0000000..2c65341
--- /dev/null
+++ b/services/core/java/com/android/server/protolog/common/IProtoLogGroup.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2019 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.protolog.common;
+
+/**
+ * Defines a log group configuration object for ProtoLog. Should be implemented as en enum.
+ */
+public interface IProtoLogGroup {
+    /**
+     * if false all log statements for this group are excluded from compilation,
+     */
+    boolean isEnabled();
+
+    /**
+     * is binary logging enabled for the group.
+     */
+    boolean isLogToProto();
+
+    /**
+     * is text logging enabled for the group.
+     */
+    boolean isLogToLogcat();
+
+    /**
+     * returns true is any logging is enabled for this group.
+     */
+    default boolean isLogToAny() {
+        return isLogToLogcat() || isLogToProto();
+    }
+
+    /**
+     * returns the name of the source of the logged message
+     */
+    String getTag();
+
+    /**
+     * set binary logging for this group.
+     */
+    void setLogToProto(boolean logToProto);
+
+    /**
+     * set text logging for this group.
+     */
+    void setLogToLogcat(boolean logToLogcat);
+
+    /**
+     * returns name of the logging group.
+     */
+    String name();
+}
diff --git a/services/core/java/com/android/server/protolog/common/InvalidFormatStringException.java b/services/core/java/com/android/server/protolog/common/InvalidFormatStringException.java
new file mode 100644
index 0000000..947bf98
--- /dev/null
+++ b/services/core/java/com/android/server/protolog/common/InvalidFormatStringException.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2019 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.protolog.common;
+
+/**
+ * Unsupported/invalid message format string error.
+ */
+public class InvalidFormatStringException extends RuntimeException {
+    public InvalidFormatStringException(String message) {
+        super(message);
+    }
+
+    public InvalidFormatStringException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}
diff --git a/services/core/java/com/android/server/protolog/common/LogDataType.java b/services/core/java/com/android/server/protolog/common/LogDataType.java
new file mode 100644
index 0000000..e73b41a
--- /dev/null
+++ b/services/core/java/com/android/server/protolog/common/LogDataType.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2019 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.protolog.common;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Represents a type of logged data encoded in the proto.
+ */
+public class LogDataType {
+    // When updating this list make sure to update bitmask conversion methods accordingly.
+    // STR type should be the first in the enum in order to be the default type.
+    public static final int STRING = 0b00;
+    public static final int LONG = 0b01;
+    public static final int DOUBLE = 0b10;
+    public static final int BOOLEAN = 0b11;
+
+    private static final int TYPE_WIDTH = 2;
+    private static final int TYPE_MASK = 0b11;
+
+    /**
+     * Creates a bitmask representing a list of data types.
+     */
+    public static int logDataTypesToBitMask(List<Integer> types) {
+        if (types.size() > 16) {
+            throw new BitmaskConversionException("Too many log call parameters "
+                    + "- max 16 parameters supported");
+        }
+        int mask = 0;
+        for (int i = 0; i < types.size(); i++) {
+            int x = types.get(i);
+            mask = mask | (x << (i * TYPE_WIDTH));
+        }
+        return mask;
+    }
+
+    /**
+     * Decodes a bitmask to a list of LogDataTypes of provided length.
+     */
+    public static int bitmaskToLogDataType(int bitmask, int index) {
+        if (index > 16) {
+            throw new BitmaskConversionException("Max 16 parameters allowed");
+        }
+        return (bitmask >> (index * TYPE_WIDTH)) & TYPE_MASK;
+    }
+
+    /**
+     * Creates a list of LogDataTypes from a message format string.
+     */
+    public static List<Integer> parseFormatString(String messageString) {
+        ArrayList<Integer> types = new ArrayList<>();
+        for (int i = 0; i < messageString.length(); ) {
+            if (messageString.charAt(i) == '%') {
+                if (i + 1 >= messageString.length()) {
+                    throw new InvalidFormatStringException("Invalid format string in config");
+                }
+                switch (messageString.charAt(i + 1)) {
+                    case 'b':
+                        types.add(LogDataType.BOOLEAN);
+                        break;
+                    case 'd':
+                    case 'o':
+                    case 'x':
+                        types.add(LogDataType.LONG);
+                        break;
+                    case 'f':
+                    case 'e':
+                    case 'g':
+                        types.add(LogDataType.DOUBLE);
+                        break;
+                    case 's':
+                        types.add(LogDataType.STRING);
+                        break;
+                    case '%':
+                        break;
+                    default:
+                        throw new InvalidFormatStringException("Invalid format string field"
+                                + " %${messageString[i + 1]}");
+                }
+                i += 2;
+            } else {
+                i += 1;
+            }
+        }
+        return types;
+    }
+}
diff --git a/services/core/java/com/android/server/protolog/common/ProtoLog.java b/services/core/java/com/android/server/protolog/common/ProtoLog.java
new file mode 100644
index 0000000..b631bcb
--- /dev/null
+++ b/services/core/java/com/android/server/protolog/common/ProtoLog.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2019 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.protolog.common;
+
+/**
+ * ProtoLog API - exposes static logging methods. Usage of this API is similar
+ * to {@code android.utils.Log} class. Instead of plain text log messages each call consists of
+ * a messageString, which is a format string for the log message (has to be a string literal or
+ * a concatenation of string literals) and a vararg array of parameters for the formatter.
+ *
+ * The syntax for the message string is a subset of {@code java.util.Formatter} syntax.
+ * Supported conversions:
+ * %b - boolean
+ * %d, %o and %x - integral type (Short, Integer or Long)
+ * %f, %e and %g - floating point type (Float or Double)
+ * %s - string
+ * %% - a literal percent character
+ * The width and precision modifiers are supported, argument_index and flags are not.
+ *
+ * Methods in this class are stubs, that are replaced by optimised versions by the ProtoLogTool
+ * during build.
+ */
+public class ProtoLog {
+    /**
+     * DEBUG level log.
+     *
+     * @param group         {@code IProtoLogGroup} controlling this log call.
+     * @param messageString constant format string for the logged message.
+     * @param args          parameters to be used with the format string.
+     */
+    public static void d(IProtoLogGroup group, String messageString, Object... args) {
+        // Stub, replaced by the ProtoLogTool.
+        throw new UnsupportedOperationException(
+                "ProtoLog calls MUST be processed with ProtoLogTool");
+    }
+
+    /**
+     * VERBOSE level log.
+     *
+     * @param group         {@code IProtoLogGroup} controlling this log call.
+     * @param messageString constant format string for the logged message.
+     * @param args          parameters to be used with the format string.
+     */
+    public static void v(IProtoLogGroup group, String messageString, Object... args) {
+        // Stub, replaced by the ProtoLogTool.
+        throw new UnsupportedOperationException(
+                "ProtoLog calls MUST be processed with ProtoLogTool");
+    }
+
+    /**
+     * INFO level log.
+     *
+     * @param group         {@code IProtoLogGroup} controlling this log call.
+     * @param messageString constant format string for the logged message.
+     * @param args          parameters to be used with the format string.
+     */
+    public static void i(IProtoLogGroup group, String messageString, Object... args) {
+        // Stub, replaced by the ProtoLogTool.
+        throw new UnsupportedOperationException(
+                "ProtoLog calls MUST be processed with ProtoLogTool");
+    }
+
+    /**
+     * WARNING level log.
+     *
+     * @param group         {@code IProtoLogGroup} controlling this log call.
+     * @param messageString constant format string for the logged message.
+     * @param args          parameters to be used with the format string.
+     */
+    public static void w(IProtoLogGroup group, String messageString, Object... args) {
+        // Stub, replaced by the ProtoLogTool.
+        throw new UnsupportedOperationException(
+                "ProtoLog calls MUST be processed with ProtoLogTool");
+    }
+
+    /**
+     * ERROR level log.
+     *
+     * @param group         {@code IProtoLogGroup} controlling this log call.
+     * @param messageString constant format string for the logged message.
+     * @param args          parameters to be used with the format string.
+     */
+    public static void e(IProtoLogGroup group, String messageString, Object... args) {
+        // Stub, replaced by the ProtoLogTool.
+        throw new UnsupportedOperationException(
+                "ProtoLog calls MUST be processed with ProtoLogTool");
+    }
+
+    /**
+     * WHAT A TERRIBLE FAILURE level log.
+     *
+     * @param group         {@code IProtoLogGroup} controlling this log call.
+     * @param messageString constant format string for the logged message.
+     * @param args          parameters to be used with the format string.
+     */
+    public static void wtf(IProtoLogGroup group, String messageString, Object... args) {
+        // Stub, replaced by the ProtoLogTool.
+        throw new UnsupportedOperationException(
+                "ProtoLog calls MUST be processed with ProtoLogTool");
+    }
+}
diff --git a/services/core/java/com/android/server/role/RoleManagerService.java b/services/core/java/com/android/server/role/RoleManagerService.java
index bf8c042..aac0f90 100644
--- a/services/core/java/com/android/server/role/RoleManagerService.java
+++ b/services/core/java/com/android/server/role/RoleManagerService.java
@@ -51,7 +51,6 @@
 import android.os.UserHandle;
 import android.os.UserManagerInternal;
 import android.service.sms.FinancialSmsService;
-import android.telephony.IFinancialSmsCallback;
 import android.text.TextUtils;
 import android.util.ArrayMap;
 import android.util.ArraySet;
@@ -269,6 +268,7 @@
         maybeMigrateRole(RoleManager.ROLE_DIALER, userId);
         maybeMigrateRole(RoleManager.ROLE_SMS, userId);
         maybeMigrateRole(RoleManager.ROLE_EMERGENCY, userId);
+        maybeMigrateRole(RoleManager.ROLE_HOME, userId);
 
         // Some package state has changed, so grant default roles again.
         Slog.i(LOG_TAG, "Granting default roles...");
@@ -701,40 +701,6 @@
             dumpOutputStream.flush();
         }
 
-        /**
-         * Get filtered SMS messages for financial app.
-         */
-        @Override
-        public void getSmsMessagesForFinancialApp(
-                String callingPkg, Bundle params, IFinancialSmsCallback callback) {
-            int mode = PermissionChecker.checkCallingOrSelfPermission(
-                    getContext(),
-                    AppOpsManager.OPSTR_SMS_FINANCIAL_TRANSACTIONS);
-
-            if (mode == PermissionChecker.PERMISSION_GRANTED) {
-                FinancialSmsManager financialSmsManager = new FinancialSmsManager(getContext());
-                financialSmsManager.getSmsMessages(new RemoteCallback((result) -> {
-                    CursorWindow messages = null;
-                    if (result == null) {
-                        Slog.w(LOG_TAG, "result is null.");
-                    } else {
-                        messages = result.getParcelable(FinancialSmsService.EXTRA_SMS_MSGS);
-                    }
-                    try {
-                        callback.onGetSmsMessagesForFinancialApp(messages);
-                    } catch (RemoteException e) {
-                        // do nothing
-                    }
-                }), params);
-            } else {
-                try {
-                    callback.onGetSmsMessagesForFinancialApp(null);
-                } catch (RemoteException e) {
-                    // do nothing
-                }
-            }
-        }
-
         private int getUidForPackage(String packageName) {
             long ident = Binder.clearCallingIdentity();
             try {
diff --git a/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java b/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java
index cae09ea3..1123f70 100644
--- a/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java
+++ b/services/core/java/com/android/server/rollback/AppDataRollbackHelper.java
@@ -23,17 +23,12 @@
 import android.util.Slog;
 import android.util.SparseLongArray;
 
+import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.server.pm.Installer;
 import com.android.server.pm.Installer.InstallerException;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
-import java.util.Set;
 
 /**
  * Encapsulates the logic for initiating userdata snapshots and rollbacks via installd.
@@ -56,6 +51,8 @@
      * {@code userIds}. Updates said {@code packageRollbackInfo} with the inodes of the CE user data
      * snapshot folders.
      */
+    @GuardedBy("rollback.mLock")
+    // TODO(b/136241838): Move into Rollback and synchronize there.
     public void snapshotAppData(
             int snapshotId, PackageRollbackInfo packageRollbackInfo, int[] userIds) {
         for (int user : userIds) {
@@ -81,7 +78,6 @@
                         + packageRollbackInfo.getPackageName() + ", userId: " + user, ie);
             }
         }
-        packageRollbackInfo.getSnapshottedUsers().addAll(IntArray.wrap(userIds));
     }
 
     /**
@@ -92,6 +88,8 @@
      *         to {@code packageRollbackInfo} are restricted to the removal or addition of {@code
      *         userId} to the list of pending backups or restores.
      */
+    @GuardedBy("rollback.mLock")
+    // TODO(b/136241838): Move into Rollback and synchronize there.
     public boolean restoreAppData(int rollbackId, PackageRollbackInfo packageRollbackInfo,
             int userId, int appId, String seInfo) {
         int storageFlags = Installer.FLAG_STORAGE_DE;
@@ -135,6 +133,8 @@
      * Deletes an app data snapshot with a given {@code rollbackId} for a specified package
      * {@code packageName} for a given {@code user}.
      */
+    @GuardedBy("rollback.mLock")
+    // TODO(b/136241838): Move into Rollback and synchronize there.
     public void destroyAppDataSnapshot(int rollbackId, PackageRollbackInfo packageRollbackInfo,
             int user) {
         int storageFlags = Installer.FLAG_STORAGE_DE;
@@ -156,141 +156,68 @@
     }
 
     /**
-     * Computes the list of pending backups for {@code userId} given lists of rollbacks.
-     * Packages pending backup for the given user are added to {@code pendingBackupPackages} along
-     * with their corresponding {@code PackageRollbackInfo}.
+     * Commits the pending backups and restores for a given {@code userId} and {@code rollback}. If
+     * the rollback has a pending backup, it is updated with a mapping from {@code userId} to inode
+     * of the CE user data snapshot.
      *
-     * @return the list of rollbacks that have pending backups. Note that some of the
-     *         backups won't be performed, because they might be counteracted by pending restores.
+     * @return true if any backups or restores were found for the userId
      */
-    private static List<Rollback> computePendingBackups(int userId,
-            Map<String, PackageRollbackInfo> pendingBackupPackages,
-            List<Rollback> rollbacks) {
-        List<Rollback> rollbacksWithPendingBackups = new ArrayList<>();
-
-        for (Rollback rollback : rollbacks) {
-            for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                final IntArray pendingBackupUsers = info.getPendingBackups();
-                if (pendingBackupUsers != null) {
-                    final int idx = pendingBackupUsers.indexOf(userId);
-                    if (idx != -1) {
-                        pendingBackupPackages.put(info.getPackageName(), info);
-                        if (rollbacksWithPendingBackups.indexOf(rollback) == -1) {
-                            rollbacksWithPendingBackups.add(rollback);
-                        }
-                    }
+    @GuardedBy("rollback.mLock")
+    boolean commitPendingBackupAndRestoreForUser(int userId, Rollback rollback) {
+        boolean foundBackupOrRestore = false;
+        for (PackageRollbackInfo info : rollback.info.getPackages()) {
+            boolean hasPendingBackup = false;
+            boolean hasPendingRestore = false;
+            final IntArray pendingBackupUsers = info.getPendingBackups();
+            if (pendingBackupUsers != null) {
+                if (pendingBackupUsers.indexOf(userId) != -1) {
+                    hasPendingBackup = true;
+                    foundBackupOrRestore = true;
                 }
             }
-        }
-        return rollbacksWithPendingBackups;
-    }
 
-    /**
-     * Computes the list of pending restores for {@code userId} given lists of rollbacks.
-     * Packages pending restore are added to {@code pendingRestores} along with their corresponding
-     * {@code PackageRollbackInfo}.
-     *
-     * @return the list of rollbacks that have pending restores. Note that some of the
-     *         restores won't be performed, because they might be counteracted by pending backups.
-     */
-    private static List<Rollback> computePendingRestores(int userId,
-            Map<String, PackageRollbackInfo> pendingRestorePackages,
-            List<Rollback> rollbacks) {
-        List<Rollback> rollbacksWithPendingRestores = new ArrayList<>();
-
-        for (Rollback rollback : rollbacks) {
-            for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                final RestoreInfo ri = info.getRestoreInfo(userId);
-                if (ri != null) {
-                    pendingRestorePackages.put(info.getPackageName(), info);
-                    if (rollbacksWithPendingRestores.indexOf(rollback) == -1) {
-                        rollbacksWithPendingRestores.add(rollback);
-                    }
-                }
+            RestoreInfo ri = info.getRestoreInfo(userId);
+            if (ri != null) {
+                hasPendingRestore = true;
+                foundBackupOrRestore = true;
             }
-        }
 
-        return rollbacksWithPendingRestores;
-    }
-
-    /**
-     * Commits the list of pending backups and restores for a given {@code userId}. For rollbacks
-     * with pending backups, updates the {@code Rollback} instance with a mapping from
-     * {@code userId} to inode of the CE user data snapshot.
-     *
-     * @return the set of rollbacks with changes that should be stored on disk.
-     */
-    public Set<Rollback> commitPendingBackupAndRestoreForUser(int userId,
-            List<Rollback> rollbacks) {
-
-        final Map<String, PackageRollbackInfo> pendingBackupPackages = new HashMap<>();
-        final List<Rollback> pendingBackups = computePendingBackups(userId,
-                pendingBackupPackages, rollbacks);
-
-        final Map<String, PackageRollbackInfo> pendingRestorePackages = new HashMap<>();
-        final List<Rollback> pendingRestores = computePendingRestores(userId,
-                pendingRestorePackages, rollbacks);
-
-        // First remove unnecessary backups, i.e. when user did not unlock their phone between the
-        // request to backup data and the request to restore it.
-        Iterator<Map.Entry<String, PackageRollbackInfo>> iter =
-                pendingBackupPackages.entrySet().iterator();
-        while (iter.hasNext()) {
-            PackageRollbackInfo backupPackage = iter.next().getValue();
-            PackageRollbackInfo restorePackage =
-                    pendingRestorePackages.get(backupPackage.getPackageName());
-            if (restorePackage != null) {
-                backupPackage.removePendingBackup(userId);
-                backupPackage.removePendingRestoreInfo(userId);
-                iter.remove();
-                pendingRestorePackages.remove(backupPackage.getPackageName());
+            if (hasPendingBackup && hasPendingRestore) {
+                // Remove unnecessary backup, i.e. when user did not unlock their phone between the
+                // request to backup data and the request to restore it.
+                info.removePendingBackup(userId);
+                info.removePendingRestoreInfo(userId);
+                continue;
             }
-        }
 
-        if (!pendingBackupPackages.isEmpty()) {
-            for (Rollback rollback : pendingBackups) {
-                for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                    final IntArray pendingBackupUsers = info.getPendingBackups();
-                    final int idx = pendingBackupUsers.indexOf(userId);
-                    if (idx != -1) {
-                        try {
-                            long ceSnapshotInode = mInstaller.snapshotAppData(info.getPackageName(),
-                                    userId, rollback.info.getRollbackId(),
-                                    Installer.FLAG_STORAGE_CE);
-                            info.putCeSnapshotInode(userId, ceSnapshotInode);
-                            pendingBackupUsers.remove(idx);
-                        } catch (InstallerException ie) {
-                            Slog.e(TAG,
-                                    "Unable to create app data snapshot for: "
+            if (hasPendingBackup) {
+                int idx = pendingBackupUsers.indexOf(userId);
+                try {
+                    long ceSnapshotInode = mInstaller.snapshotAppData(info.getPackageName(),
+                            userId, rollback.info.getRollbackId(),
+                            Installer.FLAG_STORAGE_CE);
+                    info.putCeSnapshotInode(userId, ceSnapshotInode);
+                    pendingBackupUsers.remove(idx);
+                } catch (InstallerException ie) {
+                    Slog.e(TAG,
+                            "Unable to create app data snapshot for: "
                                     + info.getPackageName() + ", userId: " + userId, ie);
-                        }
-                    }
+                }
+            }
+
+            if (hasPendingRestore) {
+                try {
+                    mInstaller.restoreAppDataSnapshot(info.getPackageName(), ri.appId,
+                            ri.seInfo, userId, rollback.info.getRollbackId(),
+                            Installer.FLAG_STORAGE_CE);
+                    info.removeRestoreInfo(ri);
+                } catch (InstallerException ie) {
+                    Slog.e(TAG, "Unable to restore app data snapshot for: "
+                            + info.getPackageName(), ie);
                 }
             }
         }
-
-        if (!pendingRestorePackages.isEmpty()) {
-            for (Rollback rollback : pendingRestores) {
-                for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                    final RestoreInfo ri = info.getRestoreInfo(userId);
-                    if (ri != null) {
-                        try {
-                            mInstaller.restoreAppDataSnapshot(info.getPackageName(), ri.appId,
-                                    ri.seInfo, userId, rollback.info.getRollbackId(),
-                                    Installer.FLAG_STORAGE_CE);
-                            info.removeRestoreInfo(ri);
-                        } catch (InstallerException ie) {
-                            Slog.e(TAG, "Unable to restore app data snapshot for: "
-                                    + info.getPackageName(), ie);
-                        }
-                    }
-                }
-            }
-        }
-
-        final Set<Rollback> changed = new HashSet<>(pendingBackups);
-        changed.addAll(pendingRestores);
-        return changed;
+        return foundBackupOrRestore;
     }
 
     /**
diff --git a/services/core/java/com/android/server/rollback/Rollback.java b/services/core/java/com/android/server/rollback/Rollback.java
index 6769fe0..1cf07cb 100644
--- a/services/core/java/com/android/server/rollback/Rollback.java
+++ b/services/core/java/com/android/server/rollback/Rollback.java
@@ -16,27 +16,54 @@
 
 package com.android.server.rollback;
 
+import static com.android.server.rollback.RollbackManagerServiceImpl.sendFailure;
+
+import android.Manifest;
 import android.annotation.IntDef;
 import android.annotation.NonNull;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentSender;
+import android.content.pm.PackageInstaller;
+import android.content.pm.PackageManager;
+import android.content.pm.UserInfo;
+import android.content.pm.VersionedPackage;
+import android.content.rollback.PackageRollbackInfo;
 import android.content.rollback.RollbackInfo;
+import android.content.rollback.RollbackManager;
+import android.os.Binder;
+import android.os.ParcelFileDescriptor;
+import android.os.UserManager;
+import android.util.IntArray;
+import android.util.Slog;
+import android.util.SparseLongArray;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.IndentingPrintWriter;
 
 import java.io.File;
+import java.io.IOException;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.text.ParseException;
 import java.time.Instant;
 import java.util.ArrayList;
+import java.util.List;
 
 
 /**
- * Information about a rollback available for a set of atomically installed
- * packages.
+ * Information about a rollback available for a set of atomically installed packages.
  */
 class Rollback {
+
+    private static final String TAG = "RollbackManager";
+
     @IntDef(flag = true, prefix = { "ROLLBACK_STATE_" }, value = {
             ROLLBACK_STATE_ENABLING,
             ROLLBACK_STATE_AVAILABLE,
             ROLLBACK_STATE_COMMITTED,
+            ROLLBACK_STATE_DELETED
     })
     @Retention(RetentionPolicy.SOURCE)
     @interface RollbackState {}
@@ -58,6 +85,17 @@
     static final int ROLLBACK_STATE_COMMITTED = 3;
 
     /**
+     * The rollback has been deleted.
+     */
+    static final int ROLLBACK_STATE_DELETED = 4;
+
+    /**
+     * The session ID for the staged session if this rollback data represents a staged session,
+     * {@code -1} otherwise.
+     */
+    private final int mStagedSessionId;
+
+    /**
      * The rollback info for this rollback.
      */
     public final RollbackInfo info;
@@ -74,23 +112,20 @@
      * The timestamp is not applicable for all rollback states, but we make
      * sure to keep it non-null to avoid potential errors there.
      */
+    @GuardedBy("mLock")
     private @NonNull Instant mTimestamp;
 
     /**
-     * The session ID for the staged session if this rollback data represents a staged session,
-     * {@code -1} otherwise.
-     */
-    private final int mStagedSessionId;
-
-    /**
      * The current state of the rollback.
      * ENABLING, AVAILABLE, or COMMITTED.
      */
+    @GuardedBy("mLock")
     private @RollbackState int mState;
 
     /**
      * The id of the post-reboot apk session for a staged install, if any.
      */
+    @GuardedBy("mLock")
     private int mApkSessionId = -1;
 
     /**
@@ -98,10 +133,15 @@
      * for this rollback because it has just been committed but the rollback
      * has not yet been fully applied.
      */
-    // NOTE: All accesses to this field are from the RollbackManager handler thread.
+    @GuardedBy("mLock")
     private boolean mRestoreUserDataInProgress = false;
 
     /**
+     * Lock object to guard all access to Rollback state.
+     */
+    private final Object mLock = new Object();
+
+    /**
      * Constructs a new, empty Rollback instance.
      *
      * @param rollbackId the id of the rollback.
@@ -152,14 +192,19 @@
      * Returns the time when the upgrade occurred, for purposes of expiring rollback data.
      */
     Instant getTimestamp() {
-        return mTimestamp;
+        synchronized (mLock) {
+            return mTimestamp;
+        }
     }
 
     /**
      * Sets the time at which upgrade occurred.
      */
     void setTimestamp(Instant timestamp) {
-        mTimestamp = timestamp;
+        synchronized (mLock) {
+            mTimestamp = timestamp;
+            RollbackStore.saveRollback(this);
+        }
     }
 
     /**
@@ -174,49 +219,357 @@
      * Returns true if the rollback is in the ENABLING state.
      */
     boolean isEnabling() {
-        return mState == ROLLBACK_STATE_ENABLING;
+        synchronized (mLock) {
+            return mState == ROLLBACK_STATE_ENABLING;
+        }
     }
 
     /**
      * Returns true if the rollback is in the AVAILABLE state.
      */
     boolean isAvailable() {
-        return mState == ROLLBACK_STATE_AVAILABLE;
+        synchronized (mLock) {
+            return mState == ROLLBACK_STATE_AVAILABLE;
+        }
     }
 
     /**
      * Returns true if the rollback is in the COMMITTED state.
      */
     boolean isCommitted() {
-        return mState == ROLLBACK_STATE_COMMITTED;
+        synchronized (mLock) {
+            return mState == ROLLBACK_STATE_COMMITTED;
+        }
     }
 
     /**
-     * Sets the state of the rollback to AVAILABLE.
+     * Returns true if the rollback is in the DELETED state.
      */
-    void setAvailable() {
-        mState = ROLLBACK_STATE_AVAILABLE;
+    boolean isDeleted() {
+        synchronized (mLock) {
+            return mState == ROLLBACK_STATE_DELETED;
+        }
     }
 
     /**
-     * Sets the state of the rollback to COMMITTED.
+     * Saves this rollback to persistent storage.
      */
-    void setCommitted() {
-        mState = ROLLBACK_STATE_COMMITTED;
+    void saveRollback() {
+        synchronized (mLock) {
+            RollbackStore.saveRollback(this);
+        }
+    }
+
+    /**
+     * Enables this rollback for the provided package.
+     *
+     * @return boolean True if the rollback was enabled successfully for the specified package.
+     */
+    boolean enableForPackage(String packageName, long newVersion, long installedVersion,
+            boolean isApex, String sourceDir, String[] splitSourceDirs) {
+        try {
+            RollbackStore.backupPackageCodePath(this, packageName, sourceDir);
+            if (!ArrayUtils.isEmpty(splitSourceDirs)) {
+                for (String dir : splitSourceDirs) {
+                    RollbackStore.backupPackageCodePath(this, packageName, dir);
+                }
+            }
+        } catch (IOException e) {
+            Slog.e(TAG, "Unable to copy package for rollback for " + packageName, e);
+            return false;
+        }
+
+        PackageRollbackInfo packageRollbackInfo = new PackageRollbackInfo(
+                new VersionedPackage(packageName, newVersion),
+                new VersionedPackage(packageName, installedVersion),
+                new IntArray() /* pendingBackups */, new ArrayList<>() /* pendingRestores */,
+                isApex, new IntArray(), new SparseLongArray() /* ceSnapshotInodes */);
+
+        synchronized (mLock) {
+            info.getPackages().add(packageRollbackInfo);
+        }
+
+        return true;
+    }
+
+    /**
+     * Snapshots user data for the provided package and user ids. Does nothing if this rollback is
+     * not in the ENABLING state.
+     */
+    void snapshotUserData(String packageName, int[] userIds, AppDataRollbackHelper dataHelper) {
+        synchronized (mLock) {
+            if (!isEnabling()) {
+                return;
+            }
+
+            for (PackageRollbackInfo pkgRollbackInfo : info.getPackages()) {
+                if (pkgRollbackInfo.getPackageName().equals(packageName)) {
+                    dataHelper.snapshotAppData(info.getRollbackId(), pkgRollbackInfo, userIds);
+
+                    RollbackStore.saveRollback(this);
+                    pkgRollbackInfo.getSnapshottedUsers().addAll(IntArray.wrap(userIds));
+                    break;
+                }
+            }
+        }
+    }
+
+    /**
+     * Commits the pending backups and restores for a given {@code userId}. If this rollback has a
+     * pending backup, it is updated with a mapping from {@code userId} to inode of the CE user data
+     * snapshot.
+     */
+    void commitPendingBackupAndRestoreForUser(int userId, AppDataRollbackHelper dataHelper) {
+        synchronized (mLock) {
+            if (dataHelper.commitPendingBackupAndRestoreForUser(userId, this)) {
+                RollbackStore.saveRollback(this);
+            }
+        }
+    }
+
+    /**
+     * Changes the state of the rollback to AVAILABLE. This also changes the timestamp to the
+     * current time and saves the rollback. Does nothing if this rollback is already in the
+     * DELETED state.
+     */
+    void makeAvailable() {
+        synchronized (mLock) {
+            if (isDeleted()) {
+                Slog.w(TAG, "Cannot make deleted rollback available.");
+                return;
+            }
+            mState = ROLLBACK_STATE_AVAILABLE;
+            mTimestamp = Instant.now();
+            RollbackStore.saveRollback(this);
+        }
+    }
+
+    /**
+     * Commits the rollback.
+     */
+    void commit(final Context context, List<VersionedPackage> causePackages,
+            String callerPackageName, IntentSender statusReceiver) {
+        synchronized (mLock) {
+            if (!isAvailable()) {
+                sendFailure(context, statusReceiver,
+                        RollbackManager.STATUS_FAILURE_ROLLBACK_UNAVAILABLE,
+                        "Rollback unavailable");
+                return;
+            }
+
+            // Get a context to use to install the downgraded version of the package.
+            Context pkgContext;
+            try {
+                pkgContext = context.createPackageContext(callerPackageName, 0);
+            } catch (PackageManager.NameNotFoundException e) {
+                sendFailure(context, statusReceiver, RollbackManager.STATUS_FAILURE,
+                        "Invalid callerPackageName");
+                return;
+            }
+
+            PackageManager pm = pkgContext.getPackageManager();
+            try {
+                PackageInstaller packageInstaller = pm.getPackageInstaller();
+                PackageInstaller.SessionParams parentParams = new PackageInstaller.SessionParams(
+                        PackageInstaller.SessionParams.MODE_FULL_INSTALL);
+                parentParams.setRequestDowngrade(true);
+                parentParams.setMultiPackage();
+                if (isStaged()) {
+                    parentParams.setStaged();
+                }
+
+                int parentSessionId = packageInstaller.createSession(parentParams);
+                PackageInstaller.Session parentSession = packageInstaller.openSession(
+                        parentSessionId);
+
+                for (PackageRollbackInfo pkgRollbackInfo : info.getPackages()) {
+                    PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
+                            PackageInstaller.SessionParams.MODE_FULL_INSTALL);
+                    // TODO: We can't get the installerPackageName for apex
+                    // (b/123920130). Is it okay to ignore the installer package
+                    // for apex?
+                    if (!pkgRollbackInfo.isApex()) {
+                        String installerPackageName =
+                                pm.getInstallerPackageName(pkgRollbackInfo.getPackageName());
+                        if (installerPackageName != null) {
+                            params.setInstallerPackageName(installerPackageName);
+                        }
+                    }
+                    params.setRequestDowngrade(true);
+                    params.setRequiredInstalledVersionCode(
+                            pkgRollbackInfo.getVersionRolledBackFrom().getLongVersionCode());
+                    if (isStaged()) {
+                        params.setStaged();
+                    }
+                    if (pkgRollbackInfo.isApex()) {
+                        params.setInstallAsApex();
+                    }
+                    int sessionId = packageInstaller.createSession(params);
+                    PackageInstaller.Session session = packageInstaller.openSession(sessionId);
+                    File[] packageCodePaths = RollbackStore.getPackageCodePaths(
+                            this, pkgRollbackInfo.getPackageName());
+                    if (packageCodePaths == null) {
+                        sendFailure(context, statusReceiver, RollbackManager.STATUS_FAILURE,
+                                "Backup copy of package inaccessible");
+                        return;
+                    }
+
+                    for (File packageCodePath : packageCodePaths) {
+                        try (ParcelFileDescriptor fd = ParcelFileDescriptor.open(packageCodePath,
+                                ParcelFileDescriptor.MODE_READ_ONLY)) {
+                            final long token = Binder.clearCallingIdentity();
+                            try {
+                                session.write(packageCodePath.getName(), 0,
+                                        packageCodePath.length(),
+                                        fd);
+                            } finally {
+                                Binder.restoreCallingIdentity(token);
+                            }
+                        }
+                    }
+                    parentSession.addChildSessionId(sessionId);
+                }
+
+                final LocalIntentReceiver receiver = new LocalIntentReceiver(
+                        (Intent result) -> {
+                            int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
+                                    PackageInstaller.STATUS_FAILURE);
+                            if (status != PackageInstaller.STATUS_SUCCESS) {
+                                // Committing the rollback failed, but we still have all the info we
+                                // need to try rolling back again, so restore the rollback state to
+                                // how it was before we tried committing.
+                                // TODO: Should we just kill this rollback if commit failed?
+                                // Why would we expect commit not to fail again?
+                                // TODO: Could this cause a rollback to be resurrected
+                                // if it should otherwise have expired by now?
+                                synchronized (mLock) {
+                                    mState = ROLLBACK_STATE_AVAILABLE;
+                                    mRestoreUserDataInProgress = false;
+                                }
+                                sendFailure(context, statusReceiver,
+                                        RollbackManager.STATUS_FAILURE_INSTALL,
+                                        "Rollback downgrade install failed: "
+                                                + result.getStringExtra(
+                                                PackageInstaller.EXTRA_STATUS_MESSAGE));
+                                return;
+                            }
+
+                            synchronized (mLock) {
+                                if (!isStaged()) {
+                                    // All calls to restoreUserData should have
+                                    // completed by now for a non-staged install.
+                                    mRestoreUserDataInProgress = false;
+                                }
+
+                                info.setCommittedSessionId(parentSessionId);
+                                info.getCausePackages().addAll(causePackages);
+                                RollbackStore.deletePackageCodePaths(this);
+                                RollbackStore.saveRollback(this);
+                            }
+
+                            // Send success.
+                            try {
+                                final Intent fillIn = new Intent();
+                                fillIn.putExtra(
+                                        RollbackManager.EXTRA_STATUS,
+                                        RollbackManager.STATUS_SUCCESS);
+                                statusReceiver.sendIntent(context, 0, fillIn, null, null);
+                            } catch (IntentSender.SendIntentException e) {
+                                // Nowhere to send the result back to, so don't bother.
+                            }
+
+                            Intent broadcast = new Intent(Intent.ACTION_ROLLBACK_COMMITTED);
+
+                            for (UserInfo userInfo : UserManager.get(context).getUsers(true)) {
+                                context.sendBroadcastAsUser(broadcast,
+                                        userInfo.getUserHandle(),
+                                        Manifest.permission.MANAGE_ROLLBACKS);
+                            }
+                        }
+                );
+
+                mState = ROLLBACK_STATE_COMMITTED;
+                mRestoreUserDataInProgress = true;
+                parentSession.commit(receiver.getIntentSender());
+            } catch (IOException e) {
+                Slog.e(TAG, "Rollback failed", e);
+                sendFailure(context, statusReceiver, RollbackManager.STATUS_FAILURE,
+                        "IOException: " + e.toString());
+            }
+        }
+    }
+
+    /**
+     * Restores user data for the specified package if this rollback is currently marked as
+     * having a restore in progress.
+     *
+     * @return boolean True if this rollback has a restore in progress and contains the specified
+     * package.
+     */
+    boolean restoreUserDataForPackageIfInProgress(String packageName, int[] userIds, int appId,
+            String seInfo, AppDataRollbackHelper dataHelper) {
+        synchronized (mLock) {
+            if (!isRestoreUserDataInProgress()) {
+                return false;
+            }
+
+            boolean foundPackage = false;
+            for (PackageRollbackInfo pkgRollbackInfo : info.getPackages()) {
+                if (pkgRollbackInfo.getPackageName().equals(packageName)) {
+                    foundPackage = true;
+                    boolean changedRollback = false;
+                    for (int userId : userIds) {
+                        changedRollback |= dataHelper.restoreAppData(
+                                info.getRollbackId(), pkgRollbackInfo, userId, appId, seInfo);
+                    }
+                    // We've updated metadata about this rollback, so save it to flash.
+                    if (changedRollback) {
+                        RollbackStore.saveRollback(this);
+                    }
+                    break;
+                }
+            }
+            return foundPackage;
+        }
+    }
+
+    /**
+     * Deletes app data snapshots associated with this rollback, and moves to the DELETED state.
+     */
+    void delete(AppDataRollbackHelper dataHelper) {
+        synchronized (mLock) {
+            for (PackageRollbackInfo pkgInfo : info.getPackages()) {
+                IntArray snapshottedUsers = pkgInfo.getSnapshottedUsers();
+                for (int i = 0; i < snapshottedUsers.size(); i++) {
+                    // Destroy app data snapshot.
+                    int userId = snapshottedUsers.get(i);
+
+                    dataHelper.destroyAppDataSnapshot(info.getRollbackId(), pkgInfo, userId);
+                }
+            }
+
+            RollbackStore.deleteRollback(this);
+            mState = ROLLBACK_STATE_DELETED;
+        }
     }
 
     /**
      * Returns the id of the post-reboot apk session for a staged install, if any.
      */
     int getApkSessionId() {
-        return mApkSessionId;
+        synchronized (mLock) {
+            return mApkSessionId;
+        }
     }
 
     /**
      * Sets the id of the post-reboot apk session for a staged install.
      */
     void setApkSessionId(int apkSessionId) {
-        mApkSessionId = apkSessionId;
+        synchronized (mLock) {
+            mApkSessionId = apkSessionId;
+            RollbackStore.saveRollback(this);
+        }
     }
 
     /**
@@ -224,7 +577,9 @@
      * rollback because it has just been committed but the rollback has not yet been fully applied.
      */
     boolean isRestoreUserDataInProgress() {
-        return mRestoreUserDataInProgress;
+        synchronized (mLock) {
+            return mRestoreUserDataInProgress;
+        }
     }
 
     /**
@@ -232,7 +587,75 @@
      * rollback because it has just been committed but the rollback has not yet been fully applied.
      */
     void setRestoreUserDataInProgress(boolean restoreUserDataInProgress) {
-        mRestoreUserDataInProgress = restoreUserDataInProgress;
+        synchronized (mLock) {
+            mRestoreUserDataInProgress = restoreUserDataInProgress;
+            RollbackStore.saveRollback(this);
+        }
+    }
+
+    /**
+     * Returns true if this rollback includes the package with the provided {@code packageName}.
+     */
+    boolean includesPackage(String packageName) {
+        synchronized (mLock) {
+            for (PackageRollbackInfo packageRollbackInfo : info.getPackages()) {
+                if (packageRollbackInfo.getPackageName().equals(packageName)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    /**
+     * Returns true if this rollback includes the package with the provided {@code packageName}
+     * with a <i>version rolled back from</i> that is not {@code versionCode}.
+     */
+    boolean includesPackageWithDifferentVersion(String packageName, long versionCode) {
+        synchronized (mLock) {
+            for (PackageRollbackInfo pkgRollbackInfo : info.getPackages()) {
+                if (pkgRollbackInfo.getPackageName().equals(packageName)
+                        && pkgRollbackInfo.getVersionRolledBackFrom().getLongVersionCode()
+                        != versionCode) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    /**
+     * Returns a list containing the names of all the packages included in this rollback.
+     */
+    List<String> getPackageNames() {
+        synchronized (mLock) {
+            List<String> result = new ArrayList<>();
+            for (PackageRollbackInfo pkgRollbackInfo : info.getPackages()) {
+                result.add(pkgRollbackInfo.getPackageName());
+            }
+            return result;
+        }
+    }
+
+    /**
+     * Returns a list containing the names of all the apex packages included in this rollback.
+     */
+    List<String> getApexPackageNames() {
+        synchronized (mLock) {
+            List<String> result = new ArrayList<>();
+            for (PackageRollbackInfo pkgRollbackInfo : info.getPackages()) {
+                if (pkgRollbackInfo.isApex()) {
+                    result.add(pkgRollbackInfo.getPackageName());
+                }
+            }
+            return result;
+        }
+    }
+
+    int getPackageCount() {
+        synchronized (mLock) {
+            return info.getPackages().size();
+        }
     }
 
     static String rollbackStateToString(@RollbackState int state) {
@@ -255,6 +678,38 @@
     }
 
     String getStateAsString() {
-        return rollbackStateToString(mState);
+        synchronized (mLock) {
+            return rollbackStateToString(mState);
+        }
+    }
+
+    void dump(IndentingPrintWriter ipw) {
+        synchronized (mLock) {
+            ipw.println(info.getRollbackId() + ":");
+            ipw.increaseIndent();
+            ipw.println("-state: " + getStateAsString());
+            ipw.println("-timestamp: " + getTimestamp());
+            if (getStagedSessionId() != -1) {
+                ipw.println("-stagedSessionId: " + getStagedSessionId());
+            }
+            ipw.println("-packages:");
+            ipw.increaseIndent();
+            for (PackageRollbackInfo pkg : info.getPackages()) {
+                ipw.println(pkg.getPackageName()
+                        + " " + pkg.getVersionRolledBackFrom().getLongVersionCode()
+                        + " -> " + pkg.getVersionRolledBackTo().getLongVersionCode());
+            }
+            ipw.decreaseIndent();
+            if (isCommitted()) {
+                ipw.println("-causePackages:");
+                ipw.increaseIndent();
+                for (VersionedPackage cPkg : info.getCausePackages()) {
+                    ipw.println(cPkg.getPackageName() + " " + cPkg.getLongVersionCode());
+                }
+                ipw.decreaseIndent();
+                ipw.println("-committedSessionId: " + info.getCommittedSessionId());
+            }
+            ipw.decreaseIndent();
+        }
     }
 }
diff --git a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
index 96d284b..cd44f64 100644
--- a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
+++ b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
@@ -36,14 +36,12 @@
 import android.content.pm.UserInfo;
 import android.content.pm.VersionedPackage;
 import android.content.rollback.IRollbackManager;
-import android.content.rollback.PackageRollbackInfo;
 import android.content.rollback.RollbackInfo;
 import android.content.rollback.RollbackManager;
 import android.os.Binder;
 import android.os.Environment;
 import android.os.Handler;
 import android.os.HandlerThread;
-import android.os.ParcelFileDescriptor;
 import android.os.Process;
 import android.os.SystemClock;
 import android.os.UserHandle;
@@ -53,10 +51,8 @@
 import android.util.IntArray;
 import android.util.Slog;
 import android.util.SparseBooleanArray;
-import android.util.SparseLongArray;
 
 import com.android.internal.annotations.GuardedBy;
-import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.IndentingPrintWriter;
 import com.android.server.LocalServices;
 import com.android.server.Watchdog;
@@ -64,7 +60,6 @@
 
 import java.io.File;
 import java.io.FileDescriptor;
-import java.io.IOException;
 import java.io.PrintWriter;
 import java.security.SecureRandom;
 import java.time.Instant;
@@ -219,7 +214,7 @@
                     synchronized (mLock) {
                         for (NewRollback rollback : mNewRollbacks) {
                             if (rollback.hasToken(token)) {
-                                rollback.isCancelled = true;
+                                rollback.setCancelled();
                                 return;
                             }
                         }
@@ -332,8 +327,8 @@
                     Iterator<Rollback> iter = mRollbacks.iterator();
                     while (iter.hasNext()) {
                         Rollback rollback = iter.next();
-                        rollback.setTimestamp(rollback.getTimestamp().plusMillis(timeDifference));
-                        saveRollback(rollback);
+                        rollback.setTimestamp(
+                                rollback.getTimestamp().plusMillis(timeDifference));
                     }
                 }
             }
@@ -358,148 +353,13 @@
         Slog.i(TAG, "Initiating rollback");
 
         Rollback rollback = getRollbackForId(rollbackId);
-        if (rollback == null || !rollback.isAvailable()) {
-            sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE_ROLLBACK_UNAVAILABLE,
+        if (rollback == null) {
+            sendFailure(
+                    mContext, statusReceiver, RollbackManager.STATUS_FAILURE_ROLLBACK_UNAVAILABLE,
                     "Rollback unavailable");
             return;
         }
-
-        // Get a context for the caller to use to install the downgraded
-        // version of the package.
-        final Context context;
-        try {
-            context = mContext.createPackageContext(callerPackageName, 0);
-        } catch (PackageManager.NameNotFoundException e) {
-            sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE,
-                    "Invalid callerPackageName");
-            return;
-        }
-
-        PackageManager pm = context.getPackageManager();
-        try {
-            PackageInstaller packageInstaller = pm.getPackageInstaller();
-            PackageInstaller.SessionParams parentParams = new PackageInstaller.SessionParams(
-                    PackageInstaller.SessionParams.MODE_FULL_INSTALL);
-            parentParams.setRequestDowngrade(true);
-            parentParams.setMultiPackage();
-            if (rollback.isStaged()) {
-                parentParams.setStaged();
-            }
-
-            int parentSessionId = packageInstaller.createSession(parentParams);
-            PackageInstaller.Session parentSession = packageInstaller.openSession(parentSessionId);
-
-            for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
-                        PackageInstaller.SessionParams.MODE_FULL_INSTALL);
-                // TODO: We can't get the installerPackageName for apex
-                // (b/123920130). Is it okay to ignore the installer package
-                // for apex?
-                if (!info.isApex()) {
-                    String installerPackageName = pm.getInstallerPackageName(info.getPackageName());
-                    if (installerPackageName != null) {
-                        params.setInstallerPackageName(installerPackageName);
-                    }
-                }
-                params.setRequestDowngrade(true);
-                params.setRequiredInstalledVersionCode(
-                        info.getVersionRolledBackFrom().getLongVersionCode());
-                if (rollback.isStaged()) {
-                    params.setStaged();
-                }
-                if (info.isApex()) {
-                    params.setInstallAsApex();
-                }
-                int sessionId = packageInstaller.createSession(params);
-                PackageInstaller.Session session = packageInstaller.openSession(sessionId);
-                File[] packageCodePaths = RollbackStore.getPackageCodePaths(
-                        rollback, info.getPackageName());
-                if (packageCodePaths == null) {
-                    sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE,
-                            "Backup copy of package inaccessible");
-                    return;
-                }
-
-                for (File packageCodePath : packageCodePaths) {
-                    try (ParcelFileDescriptor fd = ParcelFileDescriptor.open(packageCodePath,
-                                ParcelFileDescriptor.MODE_READ_ONLY)) {
-                        final long token = Binder.clearCallingIdentity();
-                        try {
-                            session.write(packageCodePath.getName(), 0, packageCodePath.length(),
-                                    fd);
-                        } finally {
-                            Binder.restoreCallingIdentity(token);
-                        }
-                    }
-                }
-                parentSession.addChildSessionId(sessionId);
-            }
-
-            final LocalIntentReceiver receiver = new LocalIntentReceiver(
-                    (Intent result) -> {
-                        getHandler().post(() -> {
-
-                            int status = result.getIntExtra(PackageInstaller.EXTRA_STATUS,
-                                    PackageInstaller.STATUS_FAILURE);
-                            if (status != PackageInstaller.STATUS_SUCCESS) {
-                                // Committing the rollback failed, but we
-                                // still have all the info we need to try
-                                // rolling back again, so restore the rollback
-                                // state to how it was before we tried
-                                // committing.
-                                // TODO: Should we just kill this rollback if
-                                // commit failed? Why would we expect commit
-                                // not to fail again?
-                                synchronized (mLock) {
-                                    // TODO: Could this cause a rollback to be
-                                    // resurrected if it should otherwise have
-                                    // expired by now?
-                                    rollback.setAvailable();
-                                    rollback.setRestoreUserDataInProgress(false);
-                                }
-                                sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE_INSTALL,
-                                        "Rollback downgrade install failed: "
-                                        + result.getStringExtra(
-                                                PackageInstaller.EXTRA_STATUS_MESSAGE));
-                                return;
-                            }
-
-                            synchronized (mLock) {
-                                if (!rollback.isStaged()) {
-                                    // All calls to restoreUserData should have
-                                    // completed by now for a non-staged install.
-                                    rollback.setRestoreUserDataInProgress(false);
-                                }
-
-                                rollback.info.setCommittedSessionId(parentSessionId);
-                                rollback.info.getCausePackages().addAll(causePackages);
-                            }
-                            mRollbackStore.deletePackageCodePaths(rollback);
-                            saveRollback(rollback);
-
-                            sendSuccess(statusReceiver);
-
-                            Intent broadcast = new Intent(Intent.ACTION_ROLLBACK_COMMITTED);
-
-                            for (UserInfo userInfo : UserManager.get(mContext).getUsers(true)) {
-                                mContext.sendBroadcastAsUser(broadcast, userInfo.getUserHandle(),
-                                        Manifest.permission.MANAGE_ROLLBACKS);
-                            }
-                        });
-                    }
-            );
-
-            synchronized (mLock) {
-                rollback.setCommitted();
-                rollback.setRestoreUserDataInProgress(true);
-            }
-            parentSession.commit(receiver.getIntentSender());
-        } catch (IOException e) {
-            Slog.e(TAG, "Rollback failed", e);
-            sendFailure(statusReceiver, RollbackManager.STATUS_FAILURE,
-                    "IOException: " + e.toString());
-            return;
-        }
+        rollback.commit(mContext, causePackages, callerPackageName, statusReceiver);
     }
 
     @Override
@@ -534,20 +394,14 @@
             Iterator<Rollback> iter = mRollbacks.iterator();
             while (iter.hasNext()) {
                 Rollback rollback = iter.next();
-                for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                    if (info.getPackageName().equals(packageName)) {
-                        iter.remove();
-                        deleteRollback(rollback);
-                        break;
-                    }
+                if (rollback.includesPackage(packageName)) {
+                    iter.remove();
+                    rollback.delete(mAppDataRollbackHelper);
                 }
             }
             for (NewRollback newRollback : mNewRollbacks) {
-                for (PackageRollbackInfo info : newRollback.rollback.info.getPackages()) {
-                    if (info.getPackageName().equals(packageName)) {
-                        newRollback.isCancelled = true;
-                        break;
-                    }
+                if (newRollback.rollback.includesPackage(packageName)) {
+                    newRollback.setCancelled();
                 }
             }
         }
@@ -578,12 +432,11 @@
                 rollbacks = new ArrayList<>(mRollbacks);
             }
 
-            final Set<Rollback> changed =
-                    mAppDataRollbackHelper.commitPendingBackupAndRestoreForUser(userId, rollbacks);
-
-            for (Rollback rollback : changed) {
-                saveRollback(rollback);
+            for (int i = 0; i < rollbacks.size(); i++) {
+                Rollback rollback = rollbacks.get(i);
+                rollback.commitPendingBackupAndRestoreForUser(userId, mAppDataRollbackHelper);
             }
+
             latch.countDown();
         });
 
@@ -624,11 +477,7 @@
                             restoreInProgress.add(rollback);
                         }
 
-                        for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                            if (info.isApex()) {
-                                apexPackageNames.add(info.getPackageName());
-                            }
-                        }
+                        apexPackageNames.addAll(rollback.getApexPackageNames());
                     }
                 }
             }
@@ -642,7 +491,7 @@
                     // mRollbacks, or is it okay to leave as
                     // unavailable until the next reboot when it will go
                     // away on its own?
-                    deleteRollback(rollback);
+                    rollback.delete(mAppDataRollbackHelper);
                 } else if (session.isStagedSessionApplied()) {
                     makeRollbackAvailable(rollback);
                 }
@@ -655,10 +504,7 @@
                 // TODO: What if session is null?
                 if (session != null) {
                     if (session.isStagedSessionApplied() || session.isStagedSessionFailed()) {
-                        synchronized (mLock) {
-                            rollback.setRestoreUserDataInProgress(false);
-                        }
-                        saveRollback(rollback);
+                        rollback.setRestoreUserDataInProgress(false);
                     }
                 }
             }
@@ -687,24 +533,18 @@
     private void onPackageReplaced(String packageName) {
         // TODO: Could this end up incorrectly deleting a rollback for a
         // package that is about to be installed?
-        VersionedPackage installedVersion = getInstalledPackageVersion(packageName);
+        long installedVersion = getInstalledPackageVersion(packageName);
 
         synchronized (mLock) {
             Iterator<Rollback> iter = mRollbacks.iterator();
             while (iter.hasNext()) {
                 Rollback rollback = iter.next();
                 // TODO: Should we remove rollbacks in the ENABLING state here?
-                if (rollback.isEnabling() || rollback.isAvailable()) {
-                    for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                        if (info.getPackageName().equals(packageName)
-                                && !packageVersionsEqual(
-                                    info.getVersionRolledBackFrom(),
-                                    installedVersion)) {
-                            iter.remove();
-                            deleteRollback(rollback);
-                            break;
-                        }
-                    }
+                if ((rollback.isEnabling() || rollback.isAvailable())
+                        && rollback.includesPackageWithDifferentVersion(packageName,
+                        installedVersion)) {
+                    iter.remove();
+                    rollback.delete(mAppDataRollbackHelper);
                 }
             }
         }
@@ -725,27 +565,14 @@
      * @param status the RollbackManager.STATUS_* code with the failure.
      * @param message the failure message.
      */
-    private void sendFailure(IntentSender statusReceiver, @RollbackManager.Status int status,
-            String message) {
+    static void sendFailure(Context context, IntentSender statusReceiver,
+            @RollbackManager.Status int status, String message) {
         Slog.e(TAG, message);
         try {
             final Intent fillIn = new Intent();
             fillIn.putExtra(RollbackManager.EXTRA_STATUS, status);
             fillIn.putExtra(RollbackManager.EXTRA_STATUS_MESSAGE, message);
-            statusReceiver.sendIntent(mContext, 0, fillIn, null, null);
-        } catch (IntentSender.SendIntentException e) {
-            // Nowhere to send the result back to, so don't bother.
-        }
-    }
-
-    /**
-     * Notifies an IntentSender of success.
-     */
-    private void sendSuccess(IntentSender statusReceiver) {
-        try {
-            final Intent fillIn = new Intent();
-            fillIn.putExtra(RollbackManager.EXTRA_STATUS, RollbackManager.STATUS_SUCCESS);
-            statusReceiver.sendIntent(mContext, 0, fillIn, null, null);
+            statusReceiver.sendIntent(context, 0, fillIn, null, null);
         } catch (IntentSender.SendIntentException e) {
             // Nowhere to send the result back to, so don't bother.
         }
@@ -763,13 +590,14 @@
                 if (!rollback.isAvailable()) {
                     continue;
                 }
+                Instant rollbackTimestamp = rollback.getTimestamp();
                 if (!now.isBefore(
-                            rollback.getTimestamp()
-                                    .plusMillis(mRollbackLifetimeDurationInMillis))) {
+                        rollbackTimestamp
+                                .plusMillis(mRollbackLifetimeDurationInMillis))) {
                     iter.remove();
-                    deleteRollback(rollback);
-                } else if (oldest == null || oldest.isAfter(rollback.getTimestamp())) {
-                    oldest = rollback.getTimestamp();
+                    rollback.delete(mAppDataRollbackHelper);
+                } else if (oldest == null || oldest.isAfter(rollbackTimestamp)) {
+                    oldest = rollbackTimestamp;
                 }
             }
         }
@@ -878,8 +706,8 @@
             for (int i = 0; i < mRollbacks.size(); ++i) {
                 Rollback rollback = mRollbacks.get(i);
                 if (rollback.getApkSessionId() == parentSession.getSessionId()) {
-                    // This is the apk session for a staged session with rollback enabled. We do not
-                    // need to create a new rollback for this session.
+                    // This is the apk session for a staged session with rollback enabled. We do
+                    // not need to create a new rollback for this session.
                     return true;
                 }
             }
@@ -937,7 +765,7 @@
         }
 
         // Get information about the package to be installed.
-        PackageParser.PackageLite newPackage = null;
+        PackageParser.PackageLite newPackage;
         try {
             newPackage = PackageParser.parsePackageLite(new File(session.resolvedBaseCodePath), 0);
         } catch (PackageParser.PackageParserException e) {
@@ -956,11 +784,9 @@
             return false;
         }
 
-        VersionedPackage newVersion = new VersionedPackage(packageName, newPackage.versionCode);
         final boolean isApex = ((installFlags & PackageManager.INSTALL_APEX) != 0);
 
         // Get information about the currently installed package.
-        PackageManager pm = mContext.getPackageManager();
         final PackageInfo pkgInfo;
         try {
             pkgInfo = getPackageInfo(packageName);
@@ -971,31 +797,10 @@
             return false;
         }
 
-        VersionedPackage installedVersion = new VersionedPackage(packageName,
-                pkgInfo.getLongVersionCode());
-
-        PackageRollbackInfo packageRollbackInfo = new PackageRollbackInfo(
-                newVersion, installedVersion,
-                new IntArray() /* pendingBackups */, new ArrayList<>() /* pendingRestores */,
-                isApex, new IntArray(), new SparseLongArray() /* ceSnapshotInodes */);
-
-        try {
-            ApplicationInfo appInfo = pkgInfo.applicationInfo;
-            RollbackStore.backupPackageCodePath(rollback, packageName, appInfo.sourceDir);
-            if (!ArrayUtils.isEmpty(appInfo.splitSourceDirs)) {
-                for (String sourceDir : appInfo.splitSourceDirs) {
-                    RollbackStore.backupPackageCodePath(rollback, packageName, sourceDir);
-                }
-            }
-        } catch (IOException e) {
-            Slog.e(TAG, "Unable to copy package for rollback for " + packageName, e);
-            return false;
-        }
-
-        synchronized (mLock) {
-            rollback.info.getPackages().add(packageRollbackInfo);
-        }
-        return true;
+        ApplicationInfo appInfo = pkgInfo.applicationInfo;
+        return rollback.enableForPackage(packageName, newPackage.versionCode,
+                pkgInfo.getLongVersionCode(), isApex, appInfo.sourceDir,
+                appInfo.splitSourceDirs);
     }
 
     @Override
@@ -1008,7 +813,7 @@
 
         getHandler().post(() -> {
             snapshotUserDataInternal(packageName, userIds);
-            restoreUserDataInternal(packageName, userIds, appId, ceDataInode, seInfo, token);
+            restoreUserDataInternal(packageName, userIds, appId, seInfo);
             final PackageManagerInternal pmi = LocalServices.getService(
                     PackageManagerInternal.class);
             pmi.finishPackageInstall(token, false);
@@ -1020,62 +825,27 @@
             // staged installs
             for (int i = 0; i < mRollbacks.size(); i++) {
                 Rollback rollback = mRollbacks.get(i);
-                if (!rollback.isEnabling()) {
-                    continue;
-                }
-
-                for (PackageRollbackInfo info : rollback.info.getPackages()) {
-                    if (info.getPackageName().equals(packageName)) {
-                        mAppDataRollbackHelper.snapshotAppData(
-                                rollback.info.getRollbackId(), info, userIds);
-                        saveRollback(rollback);
-                        break;
-                    }
-                }
+                rollback.snapshotUserData(packageName, userIds, mAppDataRollbackHelper);
             }
             // non-staged installs
-            PackageRollbackInfo info;
             for (NewRollback rollback : mNewRollbacks) {
-                info = getPackageRollbackInfo(rollback.rollback, packageName);
-                if (info != null) {
-                    mAppDataRollbackHelper.snapshotAppData(
-                            rollback.rollback.info.getRollbackId(), info, userIds);
-                    saveRollback(rollback.rollback);
-                }
+                rollback.rollback.snapshotUserData(
+                        packageName, userIds, mAppDataRollbackHelper);
             }
         }
     }
 
-    private void restoreUserDataInternal(String packageName, int[] userIds, int appId,
-            long ceDataInode, String seInfo, int token) {
-        PackageRollbackInfo info = null;
-        Rollback rollback = null;
+    private void restoreUserDataInternal(
+            String packageName, int[] userIds, int appId, String seInfo) {
         synchronized (mLock) {
             for (int i = 0; i < mRollbacks.size(); ++i) {
-                Rollback candidate = mRollbacks.get(i);
-                if (candidate.isRestoreUserDataInProgress()) {
-                    info = getPackageRollbackInfo(candidate, packageName);
-                    if (info != null) {
-                        rollback = candidate;
-                        break;
-                    }
+                Rollback rollback = mRollbacks.get(i);
+                if (rollback.restoreUserDataForPackageIfInProgress(
+                        packageName, userIds, appId, seInfo, mAppDataRollbackHelper)) {
+                    return;
                 }
             }
         }
-
-        if (rollback == null) {
-            return;
-        }
-
-        for (int userId : userIds) {
-            final boolean changedRollback = mAppDataRollbackHelper.restoreAppData(
-                    rollback.info.getRollbackId(), info, userId, appId, seInfo);
-
-            // We've updated metadata about this rollback, so save it to flash.
-            if (changedRollback) {
-                saveRollback(rollback);
-            }
-        }
     }
 
     @Override
@@ -1147,7 +917,6 @@
                 for (int i = 0; i < mRollbacks.size(); ++i) {
                     Rollback candidate = mRollbacks.get(i);
                     if (candidate.getStagedSessionId() == originalSessionId) {
-                        candidate.setApkSessionId(apkSessionId);
                         rollback = candidate;
                         break;
                     }
@@ -1162,7 +931,7 @@
             }
 
             if (rollback != null) {
-                saveRollback(rollback);
+                rollback.setApkSessionId(apkSessionId);
             }
         });
     }
@@ -1207,24 +976,23 @@
 
     /**
      * Gets the version of the package currently installed.
-     * Returns null if the package is not currently installed.
+     * Returns -1 if the package is not currently installed.
      */
-    private VersionedPackage getInstalledPackageVersion(String packageName) {
-        PackageManager pm = mContext.getPackageManager();
-        PackageInfo pkgInfo = null;
+    private long getInstalledPackageVersion(String packageName) {
+        PackageInfo pkgInfo;
         try {
             pkgInfo = getPackageInfo(packageName);
         } catch (PackageManager.NameNotFoundException e) {
-            return null;
+            return -1;
         }
 
-        return new VersionedPackage(packageName, pkgInfo.getLongVersionCode());
+        return pkgInfo.getLongVersionCode();
     }
 
     /**
-     * Gets PackageInfo for the given package.
-     * Matches any user and apex. Returns null if no such package is
-     * installed.
+     * Gets PackageInfo for the given package. Matches any user and apex.
+     *
+     * @throws PackageManager.NameNotFoundException if no such package is installed.
      */
     private PackageInfo getPackageInfo(String packageName)
             throws PackageManager.NameNotFoundException {
@@ -1240,13 +1008,6 @@
         }
     }
 
-
-    private boolean packageVersionsEqual(VersionedPackage a, VersionedPackage b) {
-        return a != null && b != null
-            && a.getPackageName().equals(b.getPackageName())
-            && a.getLongVersionCode() == b.getLongVersionCode();
-    }
-
     private class SessionCallback extends PackageInstaller.SessionCallback {
 
         @Override
@@ -1281,9 +1042,8 @@
     }
 
     /**
-     * Add a rollback to the list of rollbacks.
-     * This should be called after rollback has been enabled for all packages
-     * in the rollback. It does not make the rollback available yet.
+     * Add a rollback to the list of rollbacks. This should be called after rollback has been
+     * enabled for all packages in the rollback. It does not make the rollback available yet.
      *
      * @return the Rollback instance for a successfully enable-completed rollback,
      * or null on error.
@@ -1292,25 +1052,23 @@
         Rollback rollback = newRollback.rollback;
         if (!success) {
             // The install session was aborted, clean up the pending install.
-            deleteRollback(rollback);
+            rollback.delete(mAppDataRollbackHelper);
             return null;
         }
-        if (newRollback.isCancelled) {
+
+        if (newRollback.isCancelled()) {
             Slog.e(TAG, "Rollback has been cancelled by PackageManager");
-            deleteRollback(rollback);
+            rollback.delete(mAppDataRollbackHelper);
             return null;
         }
 
-        // It's safe to access rollback.info outside a synchronized block because
-        // this is running on the handler thread and all changes to the
-        // rollback.info occur on the handler thread.
-        if (rollback.info.getPackages().size() != newRollback.packageSessionIds.length) {
+        if (rollback.getPackageCount() != newRollback.getPackageSessionIdCount()) {
             Slog.e(TAG, "Failed to enable rollback for all packages in session.");
-            deleteRollback(rollback);
+            rollback.delete(mAppDataRollbackHelper);
             return null;
         }
 
-        saveRollback(rollback);
+        rollback.saveRollback();
         synchronized (mLock) {
             // Note: There is a small window of time between when
             // the session has been committed by the package
@@ -1328,26 +1086,16 @@
         return rollback;
     }
 
+    @GuardedBy("rollback.getLock")
     private void makeRollbackAvailable(Rollback rollback) {
-        // TODO: What if the rollback has since been expired, for example due
-        // to a new package being installed. Won't this revive an expired
-        // rollback? Consider adding a ROLLBACK_STATE_EXPIRED to address this.
-        synchronized (mLock) {
-            rollback.setAvailable();
-            rollback.setTimestamp(Instant.now());
-        }
-        saveRollback(rollback);
+        rollback.makeAvailable();
 
         // TODO(zezeozue): Provide API to explicitly start observing instead
         // of doing this for all rollbacks. If we do this for all rollbacks,
         // should document in PackageInstaller.SessionParams#setEnableRollback
-        // After enabling and commiting any rollback, observe packages and
+        // After enabling and committing any rollback, observe packages and
         // prepare to rollback if packages crashes too frequently.
-        List<String> packages = new ArrayList<>();
-        for (int i = 0; i < rollback.info.getPackages().size(); i++) {
-            packages.add(rollback.info.getPackages().get(i).getPackageName());
-        }
-        mPackageHealthObserver.startObservingHealth(packages,
+        mPackageHealthObserver.startObservingHealth(rollback.getPackageNames(),
                 mRollbackLifetimeDurationInMillis);
         scheduleExpiration(mRollbackLifetimeDurationInMillis);
     }
@@ -1368,21 +1116,6 @@
         return null;
     }
 
-    /**
-     * Returns the {@code PackageRollbackInfo} associated with {@code packageName} from
-     * a specified {@code Rollback}.
-     */
-    private static PackageRollbackInfo getPackageRollbackInfo(Rollback rollback,
-            String packageName) {
-        for (PackageRollbackInfo info : rollback.info.getPackages()) {
-            if (info.getPackageName().equals(packageName)) {
-                return info;
-            }
-        }
-
-        return null;
-    }
-
     @GuardedBy("mLock")
     private int allocateRollbackIdLocked() {
         int n = 0;
@@ -1398,64 +1131,12 @@
         throw new IllegalStateException("Failed to allocate rollback ID");
     }
 
-    private void deleteRollback(Rollback rollback) {
-        for (PackageRollbackInfo info : rollback.info.getPackages()) {
-            IntArray snapshottedUsers = info.getSnapshottedUsers();
-            for (int i = 0; i < snapshottedUsers.size(); i++) {
-                int userId = snapshottedUsers.get(i);
-                mAppDataRollbackHelper.destroyAppDataSnapshot(rollback.info.getRollbackId(),
-                        info, userId);
-            }
-        }
-        mRollbackStore.deleteRollback(rollback);
-    }
-
-    /**
-     * Saves a rollback, swallowing any IOExceptions.
-     * For those times when it's not obvious what to do about the IOException.
-     * TODO: Double check we can't do a better job handling the IOException in
-     * a cases where this method is called.
-     */
-    private void saveRollback(Rollback rollback) {
-        try {
-            mRollbackStore.saveRollback(rollback);
-        } catch (IOException ioe) {
-            Slog.e(TAG, "Unable to save rollback for: "
-                    + rollback.info.getRollbackId(), ioe);
-        }
-    }
-
     @Override
     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
         synchronized (mLock) {
             for (Rollback rollback : mRollbacks) {
-                RollbackInfo info = rollback.info;
-                ipw.println(info.getRollbackId() + ":");
-                ipw.increaseIndent();
-                ipw.println("-state: " + rollback.getStateAsString());
-                ipw.println("-timestamp: " + rollback.getTimestamp());
-                if (rollback.getStagedSessionId() != -1) {
-                    ipw.println("-stagedSessionId: " + rollback.getStagedSessionId());
-                }
-                ipw.println("-packages:");
-                ipw.increaseIndent();
-                for (PackageRollbackInfo pkg : info.getPackages()) {
-                    ipw.println(pkg.getPackageName()
-                            + " " + pkg.getVersionRolledBackFrom().getLongVersionCode()
-                            + " -> " + pkg.getVersionRolledBackTo().getLongVersionCode());
-                }
-                ipw.decreaseIndent();
-                if (rollback.isCommitted()) {
-                    ipw.println("-causePackages:");
-                    ipw.increaseIndent();
-                    for (VersionedPackage cPkg : info.getCausePackages()) {
-                        ipw.println(cPkg.getPackageName() + " " + cPkg.getLongVersionCode());
-                    }
-                    ipw.decreaseIndent();
-                    ipw.println("-committedSessionId: " + info.getCommittedSessionId());
-                }
-                ipw.decreaseIndent();
+                rollback.dump(ipw);
             }
         }
     }
@@ -1475,22 +1156,51 @@
         public final Rollback rollback;
 
         /**
-         * This array holds all of the rollback tokens associated with package sessions included
-         * in this rollback. This is used to identify which rollback should be cancelled in case
-         * {@link PackageManager} sends an {@link Intent#ACTION_CANCEL_ENABLE_ROLLBACK} intent.
+         * This array holds all of the rollback tokens associated with package sessions included in
+         * this rollback.
          */
+        @GuardedBy("mNewRollbackLock")
         private final IntArray mTokens = new IntArray();
 
         /**
-         * Session ids for all packages in the install.
-         * For multi-package sessions, this is the list of child session ids.
-         * For normal sessions, this list is a single element with the normal
+         * Session ids for all packages in the install. For multi-package sessions, this is the list
+         * of child session ids. For normal sessions, this list is a single element with the normal
          * session id.
          */
-        public final int[] packageSessionIds;
+        private final int[] mPackageSessionIds;
+
+        @GuardedBy("mNewRollbackLock")
+        private boolean mIsCancelled = false;
+
+        private final Object mNewRollbackLock = new Object();
+
+        NewRollback(Rollback rollback, int[] packageSessionIds) {
+            this.rollback = rollback;
+            this.mPackageSessionIds = packageSessionIds;
+        }
 
         /**
-         * Flag to determine whether the rollback has been cancelled.
+         * Adds a rollback token to be associated with this NewRollback. This may be used to
+         * identify which rollback should be cancelled in case {@link PackageManager} sends an
+         * {@link Intent#ACTION_CANCEL_ENABLE_ROLLBACK} intent.
+         */
+        void addToken(int token) {
+            synchronized (mNewRollbackLock) {
+                mTokens.add(token);
+            }
+        }
+
+        /**
+         * Returns true if this NewRollback is associated with the provided {@code token}.
+         */
+        boolean hasToken(int token) {
+            synchronized (mNewRollbackLock) {
+                return mTokens.indexOf(token) != -1;
+            }
+        }
+
+        /**
+         * Returns true if this NewRollback has been cancelled.
          *
          * <p>Rollback could be invalidated and cancelled if RollbackManager receives
          * {@link Intent#ACTION_CANCEL_ENABLE_ROLLBACK} from {@link PackageManager}.
@@ -1500,23 +1210,43 @@
          * {@link PackageInstaller.SessionCallback#onFinished(int, boolean)} before it broadcasts
          * {@link Intent#ACTION_CANCEL_ENABLE_ROLLBACK}.
          */
-        public boolean isCancelled = false;
-
-        NewRollback(Rollback rollback, int[] packageSessionIds) {
-            this.rollback = rollback;
-            this.packageSessionIds = packageSessionIds;
+        boolean isCancelled() {
+            synchronized (mNewRollbackLock) {
+                return mIsCancelled;
+            }
         }
 
-        public void addToken(int token) {
-            mTokens.add(token);
+        /**
+         * Sets this NewRollback to be marked as cancelled.
+         */
+        void setCancelled() {
+            synchronized (mNewRollbackLock) {
+                mIsCancelled = true;
+            }
         }
 
-        public boolean hasToken(int token) {
-            return mTokens.indexOf(token) != -1;
+        /**
+         * Returns true if this NewRollback contains the provided {@code packageSessionId}.
+         */
+        boolean containsSessionId(int packageSessionId) {
+            for (int id : mPackageSessionIds) {
+                if (id == packageSessionId) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        /**
+         * Returns the number of package session ids in this NewRollback.
+         */
+        int getPackageSessionIdCount() {
+            return mPackageSessionIds.length;
         }
     }
 
-    NewRollback createNewRollbackLocked(PackageInstaller.SessionInfo parentSession) {
+    @GuardedBy("mLock")
+    private NewRollback createNewRollbackLocked(PackageInstaller.SessionInfo parentSession) {
         int rollbackId = allocateRollbackIdLocked();
         final Rollback rollback;
         int parentSessionId = parentSession.getSessionId();
@@ -1542,14 +1272,13 @@
      * Returns null if no NewRollback is found for the given package
      * session.
      */
+    @GuardedBy("mLock")
     NewRollback getNewRollbackForPackageSessionLocked(int packageSessionId) {
         // We expect mNewRollbacks to be a very small list; linear search
         // should be plenty fast.
         for (NewRollback newRollback: mNewRollbacks) {
-            for (int id : newRollback.packageSessionIds) {
-                if (id == packageSessionId) {
-                    return newRollback;
-                }
+            if (newRollback.containsSessionId(packageSessionId)) {
+                return newRollback;
             }
         }
         return null;
diff --git a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
index 9c19aec..83891f6 100644
--- a/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
+++ b/services/core/java/com/android/server/rollback/RollbackPackageHealthObserver.java
@@ -370,7 +370,7 @@
     private void checkAndMitigateNativeCrashes() {
         mNumberOfNativeCrashPollsRemaining--;
         // Check if native watchdog reported a crash
-        if ("1".equals(SystemProperties.get("ro.init.updatable_crashing"))) {
+        if ("1".equals(SystemProperties.get("sys.init.updatable_crashing"))) {
             execute(getModuleMetadataPackage());
             // we stop polling after an attempt to execute rollback, regardless of whether the
             // attempt succeeds or not
diff --git a/services/core/java/com/android/server/rollback/RollbackStore.java b/services/core/java/com/android/server/rollback/RollbackStore.java
index 772c53f..425da37 100644
--- a/services/core/java/com/android/server/rollback/RollbackStore.java
+++ b/services/core/java/com/android/server/rollback/RollbackStore.java
@@ -27,6 +27,9 @@
 import android.util.Slog;
 import android.util.SparseLongArray;
 
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.VisibleForTesting;
+
 import libcore.io.IoUtils;
 
 import org.json.JSONArray;
@@ -250,7 +253,8 @@
     /**
      * Saves the given rollback to persistent storage.
      */
-    void saveRollback(Rollback rollback) throws IOException {
+    @GuardedBy("rollback.mLock")
+    static void saveRollback(Rollback rollback) {
         try {
             JSONObject dataJson = new JSONObject();
             dataJson.put("info", rollbackInfoToJson(rollback.info));
@@ -263,15 +267,15 @@
             PrintWriter pw = new PrintWriter(new File(rollback.getBackupDir(), "rollback.json"));
             pw.println(dataJson.toString());
             pw.close();
-        } catch (JSONException e) {
-            throw new IOException(e);
+        } catch (JSONException | IOException e) {
+            Slog.e(TAG, "Unable to save rollback for: " + rollback.info.getRollbackId(), e);
         }
     }
 
     /**
      * Removes all persistent storage associated with the given rollback.
      */
-    void deleteRollback(Rollback rollback) {
+    static void deleteRollback(Rollback rollback) {
         removeFile(rollback.getBackupDir());
     }
 
@@ -285,19 +289,25 @@
             JSONObject dataJson = new JSONObject(
                     IoUtils.readFileAsString(rollbackJsonFile.getAbsolutePath()));
 
-            return new Rollback(
-                    rollbackInfoFromJson(dataJson.getJSONObject("info")),
-                    backupDir,
-                    Instant.parse(dataJson.getString("timestamp")),
-                    dataJson.getInt("stagedSessionId"),
-                    rollbackStateFromString(dataJson.getString("state")),
-                    dataJson.getInt("apkSessionId"),
-                    dataJson.getBoolean("restoreUserDataInProgress"));
+            return rollbackFromJson(dataJson, backupDir);
         } catch (JSONException | DateTimeParseException | ParseException e) {
             throw new IOException(e);
         }
     }
 
+    @VisibleForTesting
+    static Rollback rollbackFromJson(JSONObject dataJson, File backupDir)
+            throws JSONException, ParseException {
+        return new Rollback(
+                rollbackInfoFromJson(dataJson.getJSONObject("info")),
+                backupDir,
+                Instant.parse(dataJson.getString("timestamp")),
+                dataJson.getInt("stagedSessionId"),
+                rollbackStateFromString(dataJson.getString("state")),
+                dataJson.getInt("apkSessionId"),
+                dataJson.getBoolean("restoreUserDataInProgress"));
+    }
+
     private static JSONObject toJson(VersionedPackage pkg) throws JSONException {
         JSONObject json = new JSONObject();
         json.put("packageName", pkg.getPackageName());
diff --git a/services/core/java/com/android/server/slice/SliceManagerService.java b/services/core/java/com/android/server/slice/SliceManagerService.java
index 5fd2ab8..3b2f324 100644
--- a/services/core/java/com/android/server/slice/SliceManagerService.java
+++ b/services/core/java/com/android/server/slice/SliceManagerService.java
@@ -180,8 +180,13 @@
         verifyCaller(pkg);
         enforceAccess(pkg, uri);
         uri = maybeAddUserId(uri, Binder.getCallingUserHandle().getIdentifier());
-        if (getPinnedSlice(uri).unpin(pkg, token)) {
-            removePinnedSlice(uri);
+        try {
+            PinnedSliceState slice = getPinnedSlice(uri);
+            if (slice != null && slice.unpin(pkg, token)) {
+                removePinnedSlice(uri);
+            }
+        } catch (IllegalStateException exception) {
+            Slog.w(TAG, exception.getMessage());
         }
     }
 
diff --git a/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java b/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java
index 3076284..8431ae4 100644
--- a/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java
+++ b/services/core/java/com/android/server/stats/ProcfsMemoryUtil.java
@@ -15,6 +15,7 @@
  */
 package com.android.server.stats;
 
+import android.annotation.Nullable;
 import android.os.FileUtils;
 import android.util.Slog;
 
@@ -22,46 +23,77 @@
 
 import java.io.File;
 import java.io.IOException;
-import java.util.Locale;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 final class ProcfsMemoryUtil {
     private static final String TAG = "ProcfsMemoryUtil";
 
-    /** Path to procfs status file: /proc/pid/status. */
-    private static final String STATUS_FILE_FMT = "/proc/%d/status";
-
-    private static final Pattern RSS_HIGH_WATER_MARK_IN_KILOBYTES =
-            Pattern.compile("VmHWM:\\s*(\\d+)\\s*kB");
+    private static final Pattern STATUS_MEMORY_STATS =
+            Pattern.compile(String.join(
+                    ".*",
+                    "Uid:\\s*(\\d+)\\s*",
+                    "VmHWM:\\s*(\\d+)\\s*kB",
+                    "VmRSS:\\s*(\\d+)\\s*kB",
+                    "RssAnon:\\s*(\\d+)\\s*kB",
+                    "VmSwap:\\s*(\\d+)\\s*kB"), Pattern.DOTALL);
 
     private ProcfsMemoryUtil() {}
 
     /**
-     * Reads RSS high-water mark of a process from procfs. Returns value of the VmHWM field in
-     * /proc/PID/status in kilobytes or 0 if not available.
+     * Reads memory stats of a process from procfs. Returns values of the VmHWM, VmRss, AnonRSS,
+     * VmSwap fields in /proc/pid/status in kilobytes or null if not available.
      */
-    static int readRssHighWaterMarkFromProcfs(int pid) {
-        final String statusPath = String.format(Locale.US, STATUS_FILE_FMT, pid);
-        return parseVmHWMFromStatus(readFile(statusPath));
+    @Nullable
+    static MemorySnapshot readMemorySnapshotFromProcfs(int pid) {
+        return parseMemorySnapshotFromStatus(readFile("/proc/" + pid + "/status"));
+    }
+
+    @VisibleForTesting
+    @Nullable
+    static MemorySnapshot parseMemorySnapshotFromStatus(String contents) {
+        if (contents.isEmpty()) {
+            return null;
+        }
+        try {
+            final Matcher matcher = STATUS_MEMORY_STATS.matcher(contents);
+            if (matcher.find()) {
+                final MemorySnapshot snapshot = new MemorySnapshot();
+                snapshot.uid = Integer.parseInt(matcher.group(1));
+                snapshot.rssHighWaterMarkInKilobytes = Integer.parseInt(matcher.group(2));
+                snapshot.rssInKilobytes = Integer.parseInt(matcher.group(3));
+                snapshot.anonRssInKilobytes = Integer.parseInt(matcher.group(4));
+                snapshot.swapInKilobytes = Integer.parseInt(matcher.group(5));
+                return snapshot;
+            }
+        } catch (NumberFormatException e) {
+            Slog.e(TAG, "Failed to parse value", e);
+        }
+        return null;
     }
 
     /**
-     * Parses RSS high-water mark out from the contents of the /proc/pid/status file in procfs. The
-     * returned value is in kilobytes.
+     * Reads cmdline of a process from procfs.
+     *
+     * Returns content of /proc/pid/cmdline (e.g. /system/bin/statsd) or an empty string
+     * if the file is not available.
+     */
+    public static String readCmdlineFromProcfs(int pid) {
+        return parseCmdline(readFile("/proc/" + pid + "/cmdline"));
+    }
+
+    /**
+     * Parses cmdline out of the contents of the /proc/pid/cmdline file in procfs.
+     *
+     * Parsing is required to strip anything after the first null byte.
      */
     @VisibleForTesting
-    static int parseVmHWMFromStatus(String contents) {
-        if (contents.isEmpty()) {
-            return 0;
+    static String parseCmdline(String contents) {
+        int firstNullByte = contents.indexOf("\0");
+        if (firstNullByte == -1) {
+            return contents;
         }
-        final Matcher matcher = RSS_HIGH_WATER_MARK_IN_KILOBYTES.matcher(contents);
-        try {
-            return matcher.find() ? Integer.parseInt(matcher.group(1)) : 0;
-        } catch (NumberFormatException e) {
-            Slog.e(TAG, "Failed to parse value", e);
-            return 0;
-        }
+        return contents.substring(0, firstNullByte);
     }
 
     private static String readFile(String path) {
@@ -72,4 +104,12 @@
             return "";
         }
     }
+
+    static final class MemorySnapshot {
+        public int uid;
+        public int rssHighWaterMarkInKilobytes;
+        public int rssInKilobytes;
+        public int anonRssInKilobytes;
+        public int swapInKilobytes;
+    }
 }
diff --git a/services/core/java/com/android/server/stats/StatsCompanionService.java b/services/core/java/com/android/server/stats/StatsCompanionService.java
deleted file mode 100644
index 19b8055..0000000
--- a/services/core/java/com/android/server/stats/StatsCompanionService.java
+++ /dev/null
@@ -1,2737 +0,0 @@
-/*
- * 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.stats;
-
-import static android.app.AppOpsManager.OP_FLAGS_ALL_TRUSTED;
-import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
-import static android.content.pm.PermissionInfo.PROTECTION_DANGEROUS;
-import static android.os.Process.getPidsForCommands;
-import static android.os.Process.getUidForPid;
-import static android.os.storage.VolumeInfo.TYPE_PRIVATE;
-import static android.os.storage.VolumeInfo.TYPE_PUBLIC;
-
-import static com.android.internal.util.Preconditions.checkNotNull;
-import static com.android.server.am.MemoryStatUtil.readCmdlineFromProcfs;
-import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
-import static com.android.server.am.MemoryStatUtil.readMemoryStatFromProcfs;
-import static com.android.server.stats.IonMemoryUtil.readProcessSystemIonHeapSizesFromDebugfs;
-import static com.android.server.stats.IonMemoryUtil.readSystemIonHeapSizeFromDebugfs;
-import static com.android.server.stats.ProcfsMemoryUtil.readRssHighWaterMarkFromProcfs;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.ActivityManagerInternal;
-import android.app.AlarmManager;
-import android.app.AlarmManager.OnAlarmListener;
-import android.app.AppOpsManager;
-import android.app.AppOpsManager.HistoricalOps;
-import android.app.AppOpsManager.HistoricalOpsRequest;
-import android.app.AppOpsManager.HistoricalPackageOps;
-import android.app.AppOpsManager.HistoricalUidOps;
-import android.app.ProcessMemoryState;
-import android.app.StatsManager;
-import android.bluetooth.BluetoothActivityEnergyInfo;
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.UidTraffic;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.IntentSender;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PermissionInfo;
-import android.content.pm.UserInfo;
-import android.hardware.biometrics.BiometricsProtoEnums;
-import android.hardware.face.FaceManager;
-import android.hardware.fingerprint.FingerprintManager;
-import android.net.ConnectivityManager;
-import android.net.INetworkStatsService;
-import android.net.Network;
-import android.net.NetworkRequest;
-import android.net.NetworkStats;
-import android.net.wifi.IWifiManager;
-import android.net.wifi.WifiActivityEnergyInfo;
-import android.os.BatteryStats;
-import android.os.BatteryStatsInternal;
-import android.os.Binder;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.CoolingDevice;
-import android.os.Environment;
-import android.os.FileUtils;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.IBinder;
-import android.os.IStatsCompanionService;
-import android.os.IStatsManager;
-import android.os.IStoraged;
-import android.os.IThermalEventListener;
-import android.os.IThermalService;
-import android.os.Looper;
-import android.os.ParcelFileDescriptor;
-import android.os.Parcelable;
-import android.os.Process;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.StatFs;
-import android.os.StatsDimensionsValue;
-import android.os.StatsLogEventWrapper;
-import android.os.SynchronousResultReceiver;
-import android.os.SystemClock;
-import android.os.SystemProperties;
-import android.os.Temperature;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.os.storage.DiskInfo;
-import android.os.storage.StorageManager;
-import android.os.storage.VolumeInfo;
-import android.provider.Settings;
-import android.stats.storage.StorageEnums;
-import android.telephony.ModemActivityInfo;
-import android.telephony.TelephonyManager;
-import android.util.ArrayMap;
-import android.util.ArraySet;
-import android.util.Log;
-import android.util.Slog;
-import android.util.StatsLog;
-import android.util.proto.ProtoOutputStream;
-import android.util.proto.ProtoStream;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.app.procstats.IProcessStats;
-import com.android.internal.app.procstats.ProcessStats;
-import com.android.internal.os.BackgroundThread;
-import com.android.internal.os.BatterySipper;
-import com.android.internal.os.BatteryStatsHelper;
-import com.android.internal.os.BinderCallsStats.ExportedCallStat;
-import com.android.internal.os.KernelCpuSpeedReader;
-import com.android.internal.os.KernelCpuThreadReader;
-import com.android.internal.os.KernelCpuThreadReaderDiff;
-import com.android.internal.os.KernelCpuThreadReaderSettingsObserver;
-import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidActiveTimeReader;
-import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidClusterTimeReader;
-import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidFreqTimeReader;
-import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidUserSysTimeReader;
-import com.android.internal.os.KernelWakelockReader;
-import com.android.internal.os.KernelWakelockStats;
-import com.android.internal.os.LooperStats;
-import com.android.internal.os.PowerProfile;
-import com.android.internal.os.ProcessCpuTracker;
-import com.android.internal.os.StoragedUidIoStatsReader;
-import com.android.internal.util.DumpUtils;
-import com.android.server.BinderCallsStatsService;
-import com.android.server.LocalServices;
-import com.android.server.SystemService;
-import com.android.server.SystemServiceManager;
-import com.android.server.am.MemoryStatUtil.MemoryStat;
-import com.android.server.role.RoleManagerInternal;
-import com.android.server.stats.IonMemoryUtil.IonAllocations;
-import com.android.server.storage.DiskStatsFileLogger;
-import com.android.server.storage.DiskStatsLoggingService;
-
-import libcore.io.IoUtils;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.time.Instant;
-import java.time.temporal.ChronoUnit;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.UUID;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-/**
- * Helper service for statsd (the native stats management service in cmds/statsd/).
- * Used for registering and receiving alarms on behalf of statsd.
- *
- * @hide
- */
-public class StatsCompanionService extends IStatsCompanionService.Stub {
-    /**
-     * How long to wait on an individual subsystem to return its stats.
-     */
-    private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
-    private static final long MILLIS_IN_A_DAY = TimeUnit.DAYS.toMillis(1);
-
-    public static final String RESULT_RECEIVER_CONTROLLER_KEY = "controller_activity";
-    public static final String CONFIG_DIR = "/data/misc/stats-service";
-
-    static final String TAG = "StatsCompanionService";
-    static final boolean DEBUG = false;
-    /**
-     * Hard coded field ids of frameworks/base/cmds/statsd/src/uid_data.proto
-     * to be used in ProtoOutputStream.
-     */
-    private static final int APPLICATION_INFO_FIELD_ID = 1;
-    private static final int UID_FIELD_ID = 1;
-    private static final int VERSION_FIELD_ID = 2;
-    private static final int VERSION_STRING_FIELD_ID = 3;
-    private static final int PACKAGE_NAME_FIELD_ID = 4;
-    private static final int INSTALLER_FIELD_ID = 5;
-
-    public static final int CODE_DATA_BROADCAST = 1;
-    public static final int CODE_SUBSCRIBER_BROADCAST = 1;
-    public static final int CODE_ACTIVE_CONFIGS_BROADCAST = 1;
-    /**
-     * The last report time is provided with each intent registered to
-     * StatsManager#setFetchReportsOperation. This allows easy de-duping in the receiver if
-     * statsd is requesting the client to retrieve the same statsd data. The last report time
-     * corresponds to the last_report_elapsed_nanos that will provided in the current
-     * ConfigMetricsReport, and this timestamp also corresponds to the
-     * current_report_elapsed_nanos of the most recently obtained ConfigMetricsReport.
-     */
-    public static final String EXTRA_LAST_REPORT_TIME = "android.app.extra.LAST_REPORT_TIME";
-    public static final int DEATH_THRESHOLD = 10;
-    /**
-     * Which native processes to snapshot memory for.
-     *
-     * <p>Processes are matched by their cmdline in procfs. Example: cat /proc/pid/cmdline returns
-     * /system/bin/statsd for the stats daemon.
-     */
-    private static final String[] MEMORY_INTERESTING_NATIVE_PROCESSES = new String[]{
-            "/system/bin/statsd",  // Stats daemon.
-            "/system/bin/surfaceflinger",
-            "/system/bin/apexd",  // APEX daemon.
-            "/system/bin/audioserver",
-            "/system/bin/cameraserver",
-            "/system/bin/drmserver",
-            "/system/bin/healthd",
-            "/system/bin/incidentd",
-            "/system/bin/installd",
-            "/system/bin/lmkd",  // Low memory killer daemon.
-            "/system/bin/logd",
-            "media.codec",
-            "media.extractor",
-            "media.metrics",
-            "/system/bin/mediadrmserver",
-            "/system/bin/mediaserver",
-            "/system/bin/performanced",
-            "/system/bin/tombstoned",
-            "/system/bin/traced",  // Perfetto.
-            "/system/bin/traced_probes",  // Perfetto.
-            "webview_zygote",
-            "zygote",
-            "zygote64",
-    };
-
-    private static final int CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES = 8;
-
-    static final class CompanionHandler extends Handler {
-        CompanionHandler(Looper looper) {
-            super(looper);
-        }
-    }
-
-    private final Context mContext;
-    private final AlarmManager mAlarmManager;
-    private final INetworkStatsService mNetworkStatsService;
-    @GuardedBy("sStatsdLock")
-    private static IStatsManager sStatsd;
-    private static final Object sStatsdLock = new Object();
-
-    private final OnAlarmListener mAnomalyAlarmListener = new AnomalyAlarmListener();
-    private final OnAlarmListener mPullingAlarmListener = new PullingAlarmListener();
-    private final OnAlarmListener mPeriodicAlarmListener = new PeriodicAlarmListener();
-    private final BroadcastReceiver mAppUpdateReceiver;
-    private final BroadcastReceiver mUserUpdateReceiver;
-    private final ShutdownEventReceiver mShutdownEventReceiver;
-    private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
-    private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
-    private IWifiManager mWifiManager = null;
-    private TelephonyManager mTelephony = null;
-    @GuardedBy("sStatsdLock")
-    private final HashSet<Long> mDeathTimeMillis = new HashSet<>();
-    @GuardedBy("sStatsdLock")
-    private final HashMap<Long, String> mDeletedFiles = new HashMap<>();
-    private final CompanionHandler mHandler;
-
-    // Disables throttler on CPU time readers.
-    private KernelCpuUidUserSysTimeReader mCpuUidUserSysTimeReader =
-            new KernelCpuUidUserSysTimeReader(false);
-    private KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
-    private KernelCpuUidFreqTimeReader mCpuUidFreqTimeReader =
-            new KernelCpuUidFreqTimeReader(false);
-    private KernelCpuUidActiveTimeReader mCpuUidActiveTimeReader =
-            new KernelCpuUidActiveTimeReader(false);
-    private KernelCpuUidClusterTimeReader mCpuUidClusterTimeReader =
-            new KernelCpuUidClusterTimeReader(false);
-    private StoragedUidIoStatsReader mStoragedUidIoStatsReader =
-            new StoragedUidIoStatsReader();
-    @Nullable
-    private final KernelCpuThreadReaderDiff mKernelCpuThreadReader;
-
-    private long mDebugElapsedClockPreviousValue = 0;
-    private long mDebugElapsedClockPullCount = 0;
-    private long mDebugFailingElapsedClockPreviousValue = 0;
-    private long mDebugFailingElapsedClockPullCount = 0;
-    private BatteryStatsHelper mBatteryStatsHelper = null;
-    private static final int MAX_BATTERY_STATS_HELPER_FREQUENCY_MS = 1000;
-    private long mBatteryStatsHelperTimestampMs = -MAX_BATTERY_STATS_HELPER_FREQUENCY_MS;
-
-    private static IThermalService sThermalService;
-    private File mBaseDir =
-            new File(SystemServiceManager.ensureSystemDir(), "stats_companion");
-    @GuardedBy("this")
-    ProcessCpuTracker mProcessCpuTracker = null;
-
-    public StatsCompanionService(Context context) {
-        super();
-        mContext = context;
-        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
-        mNetworkStatsService = INetworkStatsService.Stub.asInterface(
-              ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
-        mBaseDir.mkdirs();
-        mAppUpdateReceiver = new AppUpdateReceiver();
-        mUserUpdateReceiver = new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                synchronized (sStatsdLock) {
-                    sStatsd = fetchStatsdService();
-                    if (sStatsd == null) {
-                        Slog.w(TAG, "Could not access statsd for UserUpdateReceiver");
-                        return;
-                    }
-                    try {
-                        // Pull the latest state of UID->app name, version mapping.
-                        // Needed since the new user basically has a version of every app.
-                        informAllUidsLocked(context);
-                    } catch (RemoteException e) {
-                        Slog.e(TAG, "Failed to inform statsd latest update of all apps", e);
-                        forgetEverythingLocked();
-                    }
-                }
-            }
-        };
-        mShutdownEventReceiver = new ShutdownEventReceiver();
-        if (DEBUG) Slog.d(TAG, "Registered receiver for ACTION_PACKAGE_REPLACED and ADDED.");
-        PowerProfile powerProfile = new PowerProfile(context);
-        final int numClusters = powerProfile.getNumCpuClusters();
-        mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
-        int firstCpuOfCluster = 0;
-        for (int i = 0; i < numClusters; i++) {
-            final int numSpeedSteps = powerProfile.getNumSpeedStepsInCpuCluster(i);
-            mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
-                    numSpeedSteps);
-            firstCpuOfCluster += powerProfile.getNumCoresInCpuCluster(i);
-        }
-
-        // Enable push notifications of throttling from vendor thermal
-        // management subsystem via thermalservice.
-        IBinder b = ServiceManager.getService("thermalservice");
-
-        if (b != null) {
-            sThermalService = IThermalService.Stub.asInterface(b);
-            try {
-                sThermalService.registerThermalEventListener(
-                        new ThermalEventListener());
-                Slog.i(TAG, "register thermal listener successfully");
-            } catch (RemoteException e) {
-                // Should never happen.
-                Slog.e(TAG, "register thermal listener error");
-            }
-        } else {
-            Slog.e(TAG, "cannot find thermalservice, no throttling push notifications");
-        }
-
-        // Default NetworkRequest should cover all transport types.
-        final NetworkRequest request = new NetworkRequest.Builder().build();
-        final ConnectivityManager connectivityManager =
-                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-        connectivityManager.registerNetworkCallback(request, new ConnectivityStatsCallback());
-
-        HandlerThread handlerThread = new HandlerThread(TAG);
-        handlerThread.start();
-        mHandler = new CompanionHandler(handlerThread.getLooper());
-
-        mKernelCpuThreadReader =
-                KernelCpuThreadReaderSettingsObserver.getSettingsModifiedReader(mContext);
-    }
-
-    @Override
-    public void sendDataBroadcast(IBinder intentSenderBinder, long lastReportTimeNs) {
-        enforceCallingPermission();
-        IntentSender intentSender = new IntentSender(intentSenderBinder);
-        Intent intent = new Intent();
-        intent.putExtra(EXTRA_LAST_REPORT_TIME, lastReportTimeNs);
-        try {
-            intentSender.sendIntent(mContext, CODE_DATA_BROADCAST, intent, null, null);
-        } catch (IntentSender.SendIntentException e) {
-            Slog.w(TAG, "Unable to send using IntentSender");
-        }
-    }
-
-    @Override
-    public void sendActiveConfigsChangedBroadcast(IBinder intentSenderBinder, long[] configIds) {
-        enforceCallingPermission();
-        IntentSender intentSender = new IntentSender(intentSenderBinder);
-        Intent intent = new Intent();
-        intent.putExtra(StatsManager.EXTRA_STATS_ACTIVE_CONFIG_KEYS, configIds);
-        try {
-            intentSender.sendIntent(mContext, CODE_ACTIVE_CONFIGS_BROADCAST, intent, null, null);
-            if (DEBUG) {
-                Slog.d(TAG, "Sent broadcast with config ids " + Arrays.toString(configIds));
-            }
-        } catch (IntentSender.SendIntentException e) {
-            Slog.w(TAG, "Unable to send active configs changed broadcast using IntentSender");
-        }
-    }
-
-    @Override
-    public void sendSubscriberBroadcast(IBinder intentSenderBinder, long configUid, long configKey,
-            long subscriptionId, long subscriptionRuleId, String[] cookies,
-            StatsDimensionsValue dimensionsValue) {
-        enforceCallingPermission();
-        IntentSender intentSender = new IntentSender(intentSenderBinder);
-        Intent intent =
-                new Intent()
-                        .putExtra(StatsManager.EXTRA_STATS_CONFIG_UID, configUid)
-                        .putExtra(StatsManager.EXTRA_STATS_CONFIG_KEY, configKey)
-                        .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_ID, subscriptionId)
-                        .putExtra(StatsManager.EXTRA_STATS_SUBSCRIPTION_RULE_ID, subscriptionRuleId)
-                        .putExtra(StatsManager.EXTRA_STATS_DIMENSIONS_VALUE, dimensionsValue);
-
-        ArrayList<String> cookieList = new ArrayList<>(cookies.length);
-        for (String cookie : cookies) {
-            cookieList.add(cookie);
-        }
-        intent.putStringArrayListExtra(
-                StatsManager.EXTRA_STATS_BROADCAST_SUBSCRIBER_COOKIES, cookieList);
-
-        if (DEBUG) {
-            Slog.d(TAG,
-                    String.format("Statsd sendSubscriberBroadcast with params {%d %d %d %d %s %s}",
-                            configUid, configKey, subscriptionId, subscriptionRuleId,
-                            Arrays.toString(cookies),
-                            dimensionsValue));
-        }
-        try {
-            intentSender.sendIntent(mContext, CODE_SUBSCRIBER_BROADCAST, intent, null, null);
-        } catch (IntentSender.SendIntentException e) {
-            Slog.w(TAG,
-                    "Unable to send using IntentSender from uid " + configUid
-                            + "; presumably it had been cancelled.");
-        }
-    }
-
-    private final static int[] toIntArray(List<Integer> list) {
-        int[] ret = new int[list.size()];
-        for (int i = 0; i < ret.length; i++) {
-            ret[i] = list.get(i);
-        }
-        return ret;
-    }
-
-    private final static long[] toLongArray(List<Long> list) {
-        long[] ret = new long[list.size()];
-        for (int i = 0; i < ret.length; i++) {
-            ret[i] = list.get(i);
-        }
-        return ret;
-    }
-
-    // Assumes that sStatsdLock is held.
-    @GuardedBy("sStatsdLock")
-    private final void informAllUidsLocked(Context context) throws RemoteException {
-        UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
-        PackageManager pm = context.getPackageManager();
-        final List<UserInfo> users = um.getUsers(true);
-        if (DEBUG) {
-            Slog.d(TAG, "Iterating over " + users.size() + " profiles.");
-        }
-
-        ParcelFileDescriptor[] fds;
-        try {
-            fds = ParcelFileDescriptor.createPipe();
-        } catch (IOException e) {
-            Slog.e(TAG, "Failed to create a pipe to send uid map data.", e);
-            return;
-        }
-        sStatsd.informAllUidData(fds[0]);
-        try {
-            fds[0].close();
-        } catch (IOException e) {
-            Slog.e(TAG, "Failed to close the read side of the pipe.", e);
-        }
-        final ParcelFileDescriptor writeFd = fds[1];
-        BackgroundThread.getHandler().post(() -> {
-            FileOutputStream fout = new ParcelFileDescriptor.AutoCloseOutputStream(writeFd);
-            try {
-                ProtoOutputStream output = new ProtoOutputStream(fout);
-                int numRecords = 0;
-                // Add in all the apps for every user/profile.
-                for (UserInfo profile : users) {
-                    List<PackageInfo> pi =
-                            pm.getInstalledPackagesAsUser(PackageManager.MATCH_KNOWN_PACKAGES,
-                                    profile.id);
-                    for (int j = 0; j < pi.size(); j++) {
-                        if (pi.get(j).applicationInfo != null) {
-                            String installer;
-                            try {
-                                installer = pm.getInstallerPackageName(pi.get(j).packageName);
-                            } catch (IllegalArgumentException e) {
-                                installer = "";
-                            }
-                            long applicationInfoToken =
-                                    output.start(ProtoStream.FIELD_TYPE_MESSAGE
-                                            | ProtoStream.FIELD_COUNT_REPEATED
-                                                    | APPLICATION_INFO_FIELD_ID);
-                            output.write(ProtoStream.FIELD_TYPE_INT32
-                                    | ProtoStream.FIELD_COUNT_SINGLE | UID_FIELD_ID,
-                                            pi.get(j).applicationInfo.uid);
-                            output.write(ProtoStream.FIELD_TYPE_INT64
-                                    | ProtoStream.FIELD_COUNT_SINGLE
-                                            | VERSION_FIELD_ID, pi.get(j).getLongVersionCode());
-                            output.write(ProtoStream.FIELD_TYPE_STRING
-                                    | ProtoStream.FIELD_COUNT_SINGLE | VERSION_STRING_FIELD_ID,
-                                            pi.get(j).versionName);
-                            output.write(ProtoStream.FIELD_TYPE_STRING
-                                    | ProtoStream.FIELD_COUNT_SINGLE
-                                            | PACKAGE_NAME_FIELD_ID, pi.get(j).packageName);
-                            output.write(ProtoStream.FIELD_TYPE_STRING
-                                    | ProtoStream.FIELD_COUNT_SINGLE
-                                            | INSTALLER_FIELD_ID,
-                                                    installer == null ? "" : installer);
-                            numRecords++;
-                            output.end(applicationInfoToken);
-                        }
-                    }
-                }
-                output.flush();
-                if (DEBUG) {
-                    Slog.d(TAG, "Sent data for " + numRecords + " apps");
-                }
-            } finally {
-                IoUtils.closeQuietly(fout);
-            }
-        });
-    }
-
-    private final static class AppUpdateReceiver extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            /**
-             * App updates actually consist of REMOVE, ADD, and then REPLACE broadcasts. To avoid
-             * waste, we ignore the REMOVE and ADD broadcasts that contain the replacing flag.
-             * If we can't find the value for EXTRA_REPLACING, we default to false.
-             */
-            if (!intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)
-                    && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
-                return; // Keep only replacing or normal add and remove.
-            }
-            if (DEBUG) Slog.d(TAG, "StatsCompanionService noticed an app was updated.");
-            synchronized (sStatsdLock) {
-                if (sStatsd == null) {
-                    Slog.w(TAG, "Could not access statsd to inform it of an app update");
-                    return;
-                }
-                try {
-                    if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
-                        Bundle b = intent.getExtras();
-                        int uid = b.getInt(Intent.EXTRA_UID);
-                        boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
-                        if (!replacing) {
-                            // Don't bother sending an update if we're right about to get another
-                            // intent for the new version that's added.
-                            PackageManager pm = context.getPackageManager();
-                            String app = intent.getData().getSchemeSpecificPart();
-                            sStatsd.informOnePackageRemoved(app, uid);
-                        }
-                    } else {
-                        PackageManager pm = context.getPackageManager();
-                        Bundle b = intent.getExtras();
-                        int uid = b.getInt(Intent.EXTRA_UID);
-                        String app = intent.getData().getSchemeSpecificPart();
-                        PackageInfo pi = pm.getPackageInfo(app, PackageManager.MATCH_ANY_USER);
-                        String installer;
-                        try {
-                            installer = pm.getInstallerPackageName(app);
-                        } catch (IllegalArgumentException e) {
-                            installer = "";
-                        }
-                        sStatsd.informOnePackage(app, uid, pi.getLongVersionCode(), pi.versionName,
-                                installer == null ? "" : installer);
-                    }
-                } catch (Exception e) {
-                    Slog.w(TAG, "Failed to inform statsd of an app update", e);
-                }
-            }
-        }
-    }
-
-    public final static class AnomalyAlarmListener implements OnAlarmListener {
-        @Override
-        public void onAlarm() {
-            Slog.i(TAG, "StatsCompanionService believes an anomaly has occurred at time "
-                    + System.currentTimeMillis() + "ms.");
-            synchronized (sStatsdLock) {
-                if (sStatsd == null) {
-                    Slog.w(TAG, "Could not access statsd to inform it of anomaly alarm firing");
-                    return;
-                }
-                try {
-                    // Two-way call to statsd to retain AlarmManager wakelock
-                    sStatsd.informAnomalyAlarmFired();
-                } catch (RemoteException e) {
-                    Slog.w(TAG, "Failed to inform statsd of anomaly alarm firing", e);
-                }
-            }
-            // AlarmManager releases its own wakelock here.
-        }
-    }
-
-    public final static class PullingAlarmListener implements OnAlarmListener {
-        @Override
-        public void onAlarm() {
-            if (DEBUG) {
-                Slog.d(TAG, "Time to poll something.");
-            }
-            synchronized (sStatsdLock) {
-                if (sStatsd == null) {
-                    Slog.w(TAG, "Could not access statsd to inform it of pulling alarm firing.");
-                    return;
-                }
-                try {
-                    // Two-way call to statsd to retain AlarmManager wakelock
-                    sStatsd.informPollAlarmFired();
-                } catch (RemoteException e) {
-                    Slog.w(TAG, "Failed to inform statsd of pulling alarm firing.", e);
-                }
-            }
-        }
-    }
-
-    public final static class PeriodicAlarmListener implements OnAlarmListener {
-        @Override
-        public void onAlarm() {
-            if (DEBUG) {
-                Slog.d(TAG, "Time to trigger periodic alarm.");
-            }
-            synchronized (sStatsdLock) {
-                if (sStatsd == null) {
-                    Slog.w(TAG, "Could not access statsd to inform it of periodic alarm firing.");
-                    return;
-                }
-                try {
-                    // Two-way call to statsd to retain AlarmManager wakelock
-                    sStatsd.informAlarmForSubscriberTriggeringFired();
-                } catch (RemoteException e) {
-                    Slog.w(TAG, "Failed to inform statsd of periodic alarm firing.", e);
-                }
-            }
-            // AlarmManager releases its own wakelock here.
-        }
-    }
-
-    public final static class ShutdownEventReceiver extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            /**
-             * Skip immediately if intent is not relevant to device shutdown.
-             */
-            if (!intent.getAction().equals(Intent.ACTION_REBOOT)
-                    && !(intent.getAction().equals(Intent.ACTION_SHUTDOWN)
-                    && (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0)) {
-                return;
-            }
-
-            Slog.i(TAG, "StatsCompanionService noticed a shutdown.");
-            synchronized (sStatsdLock) {
-                if (sStatsd == null) {
-                    Slog.w(TAG, "Could not access statsd to inform it of a shutdown event.");
-                    return;
-                }
-                try {
-                    sStatsd.informDeviceShutdown();
-                } catch (Exception e) {
-                    Slog.w(TAG, "Failed to inform statsd of a shutdown event.", e);
-                }
-            }
-        }
-    }
-
-    @Override // Binder call
-    public void setAnomalyAlarm(long timestampMs) {
-        enforceCallingPermission();
-        if (DEBUG) Slog.d(TAG, "Setting anomaly alarm for " + timestampMs);
-        final long callingToken = Binder.clearCallingIdentity();
-        try {
-            // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
-            // only fire when it awakens.
-            // AlarmManager will automatically cancel any previous mAnomalyAlarmListener alarm.
-            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".anomaly",
-                    mAnomalyAlarmListener, mHandler);
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    @Override // Binder call
-    public void cancelAnomalyAlarm() {
-        enforceCallingPermission();
-        if (DEBUG) Slog.d(TAG, "Cancelling anomaly alarm");
-        final long callingToken = Binder.clearCallingIdentity();
-        try {
-            mAlarmManager.cancel(mAnomalyAlarmListener);
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    @Override // Binder call
-    public void setAlarmForSubscriberTriggering(long timestampMs) {
-        enforceCallingPermission();
-        if (DEBUG) {
-            Slog.d(TAG,
-                    "Setting periodic alarm in about " + (timestampMs
-                            - SystemClock.elapsedRealtime()));
-        }
-        final long callingToken = Binder.clearCallingIdentity();
-        try {
-            // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
-            // only fire when it awakens.
-            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, TAG + ".periodic",
-                    mPeriodicAlarmListener, mHandler);
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    @Override // Binder call
-    public void cancelAlarmForSubscriberTriggering() {
-        enforceCallingPermission();
-        if (DEBUG) {
-            Slog.d(TAG, "Cancelling periodic alarm");
-        }
-        final long callingToken = Binder.clearCallingIdentity();
-        try {
-            mAlarmManager.cancel(mPeriodicAlarmListener);
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    @Override // Binder call
-    public void setPullingAlarm(long nextPullTimeMs) {
-        enforceCallingPermission();
-        if (DEBUG) {
-            Slog.d(TAG, "Setting pulling alarm in about "
-                    + (nextPullTimeMs - SystemClock.elapsedRealtime()));
-        }
-        final long callingToken = Binder.clearCallingIdentity();
-        try {
-            // using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
-            // only fire when it awakens.
-            mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, nextPullTimeMs, TAG + ".pull",
-                    mPullingAlarmListener, mHandler);
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    @Override // Binder call
-    public void cancelPullingAlarm() {
-        enforceCallingPermission();
-        if (DEBUG) {
-            Slog.d(TAG, "Cancelling pulling alarm");
-        }
-        final long callingToken = Binder.clearCallingIdentity();
-        try {
-            mAlarmManager.cancel(mPullingAlarmListener);
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    private void addNetworkStats(
-            int tag, List<StatsLogEventWrapper> ret, NetworkStats stats, boolean withFGBG) {
-        int size = stats.size();
-        long elapsedNanos = SystemClock.elapsedRealtimeNanos();
-        long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
-        NetworkStats.Entry entry = new NetworkStats.Entry(); // For recycling
-        for (int j = 0; j < size; j++) {
-            stats.getValues(j, entry);
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tag, elapsedNanos, wallClockNanos);
-            e.writeInt(entry.uid);
-            if (withFGBG) {
-                e.writeInt(entry.set);
-            }
-            e.writeLong(entry.rxBytes);
-            e.writeLong(entry.rxPackets);
-            e.writeLong(entry.txBytes);
-            e.writeLong(entry.txPackets);
-            ret.add(e);
-        }
-    }
-
-    /**
-     * Allows rollups per UID but keeping the set (foreground/background) slicing.
-     * Adapted from groupedByUid in frameworks/base/core/java/android/net/NetworkStats.java
-     */
-    private NetworkStats rollupNetworkStatsByFGBG(NetworkStats stats) {
-        final NetworkStats ret = new NetworkStats(stats.getElapsedRealtime(), 1);
-
-        final NetworkStats.Entry entry = new NetworkStats.Entry();
-        entry.iface = NetworkStats.IFACE_ALL;
-        entry.tag = NetworkStats.TAG_NONE;
-        entry.metered = NetworkStats.METERED_ALL;
-        entry.roaming = NetworkStats.ROAMING_ALL;
-
-        int size = stats.size();
-        NetworkStats.Entry recycle = new NetworkStats.Entry(); // Used for retrieving values
-        for (int i = 0; i < size; i++) {
-            stats.getValues(i, recycle);
-
-            // Skip specific tags, since already counted in TAG_NONE
-            if (recycle.tag != NetworkStats.TAG_NONE) continue;
-
-            entry.set = recycle.set; // Allows slicing by background/foreground
-            entry.uid = recycle.uid;
-            entry.rxBytes = recycle.rxBytes;
-            entry.rxPackets = recycle.rxPackets;
-            entry.txBytes = recycle.txBytes;
-            entry.txPackets = recycle.txPackets;
-            // Operations purposefully omitted since we don't use them for statsd.
-            ret.combineValues(entry);
-        }
-        return ret;
-    }
-
-    /**
-     * Helper method to extract the Parcelable controller info from a
-     * SynchronousResultReceiver.
-     */
-    private static <T extends Parcelable> T awaitControllerInfo(
-            @Nullable SynchronousResultReceiver receiver) {
-        if (receiver == null) {
-            return null;
-        }
-
-        try {
-            final SynchronousResultReceiver.Result result =
-                    receiver.awaitResult(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS);
-            if (result.bundle != null) {
-                // This is the final destination for the Bundle.
-                result.bundle.setDefusable(true);
-
-                final T data = result.bundle.getParcelable(
-                        RESULT_RECEIVER_CONTROLLER_KEY);
-                if (data != null) {
-                    return data;
-                }
-            }
-            Slog.e(TAG, "no controller energy info supplied for " + receiver.getName());
-        } catch (TimeoutException e) {
-            Slog.w(TAG, "timeout reading " + receiver.getName() + " stats");
-        }
-        return null;
-    }
-
-    private void pullKernelWakelock(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        final KernelWakelockStats wakelockStats =
-                mKernelWakelockReader.readKernelWakelockStats(mTmpWakelockStats);
-        for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
-            String name = ent.getKey();
-            KernelWakelockStats.Entry kws = ent.getValue();
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeString(name);
-            e.writeInt(kws.mCount);
-            e.writeInt(kws.mVersion);
-            e.writeLong(kws.mTotalTime);
-            pulledData.add(e);
-        }
-    }
-
-    private void pullWifiBytesTransfer(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        try {
-            // TODO: Consider caching the following call to get BatteryStatsInternal.
-            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
-            String[] ifaces = bs.getWifiIfaces();
-            if (ifaces.length == 0) {
-                return;
-            }
-            if (mNetworkStatsService == null) {
-                Slog.e(TAG, "NetworkStats Service is not available!");
-                return;
-            }
-            // Combine all the metrics per Uid into one record.
-            NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
-            addNetworkStats(tagId, pulledData, stats, false);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "Pulling netstats for wifi bytes has error", e);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    private void pullWifiBytesTransferByFgBg(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        try {
-            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
-            String[] ifaces = bs.getWifiIfaces();
-            if (ifaces.length == 0) {
-                return;
-            }
-            if (mNetworkStatsService == null) {
-                Slog.e(TAG, "NetworkStats Service is not available!");
-                return;
-            }
-            NetworkStats stats = rollupNetworkStatsByFGBG(
-                    mNetworkStatsService.getDetailedUidStats(ifaces));
-            addNetworkStats(tagId, pulledData, stats, true);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "Pulling netstats for wifi bytes w/ fg/bg has error", e);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    private void pullMobileBytesTransfer(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        try {
-            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
-            String[] ifaces = bs.getMobileIfaces();
-            if (ifaces.length == 0) {
-                return;
-            }
-            if (mNetworkStatsService == null) {
-                Slog.e(TAG, "NetworkStats Service is not available!");
-                return;
-            }
-            // Combine all the metrics per Uid into one record.
-            NetworkStats stats = mNetworkStatsService.getDetailedUidStats(ifaces).groupedByUid();
-            addNetworkStats(tagId, pulledData, stats, false);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "Pulling netstats for mobile bytes has error", e);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    private void pullBluetoothBytesTransfer(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        BluetoothActivityEnergyInfo info = fetchBluetoothData();
-        if (info.getUidTraffic() != null) {
-            for (UidTraffic traffic : info.getUidTraffic()) {
-                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                        wallClockNanos);
-                e.writeInt(traffic.getUid());
-                e.writeLong(traffic.getRxBytes());
-                e.writeLong(traffic.getTxBytes());
-                pulledData.add(e);
-            }
-        }
-    }
-
-    private void pullMobileBytesTransferByFgBg(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        try {
-            BatteryStatsInternal bs = LocalServices.getService(BatteryStatsInternal.class);
-            String[] ifaces = bs.getMobileIfaces();
-            if (ifaces.length == 0) {
-                return;
-            }
-            if (mNetworkStatsService == null) {
-                Slog.e(TAG, "NetworkStats Service is not available!");
-                return;
-            }
-            NetworkStats stats = rollupNetworkStatsByFGBG(
-                    mNetworkStatsService.getDetailedUidStats(ifaces));
-            addNetworkStats(tagId, pulledData, stats, true);
-        } catch (RemoteException e) {
-            Slog.e(TAG, "Pulling netstats for mobile bytes w/ fg/bg has error", e);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    private void pullCpuTimePerFreq(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
-            long[] clusterTimeMs = mKernelCpuSpeedReaders[cluster].readAbsolute();
-            if (clusterTimeMs != null) {
-                for (int speed = clusterTimeMs.length - 1; speed >= 0; --speed) {
-                    StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                            wallClockNanos);
-                    e.writeInt(cluster);
-                    e.writeInt(speed);
-                    e.writeLong(clusterTimeMs[speed]);
-                    pulledData.add(e);
-                }
-            }
-        }
-    }
-
-    private void pullKernelUidCpuTime(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        mCpuUidUserSysTimeReader.readAbsolute((uid, timesUs) -> {
-            long userTimeUs = timesUs[0], systemTimeUs = timesUs[1];
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(uid);
-            e.writeLong(userTimeUs);
-            e.writeLong(systemTimeUs);
-            pulledData.add(e);
-        });
-    }
-
-    private void pullKernelUidCpuFreqTime(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        mCpuUidFreqTimeReader.readAbsolute((uid, cpuFreqTimeMs) -> {
-            for (int freqIndex = 0; freqIndex < cpuFreqTimeMs.length; ++freqIndex) {
-                if (cpuFreqTimeMs[freqIndex] != 0) {
-                    StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                            wallClockNanos);
-                    e.writeInt(uid);
-                    e.writeInt(freqIndex);
-                    e.writeLong(cpuFreqTimeMs[freqIndex]);
-                    pulledData.add(e);
-                }
-            }
-        });
-    }
-
-    private void pullKernelUidCpuClusterTime(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        mCpuUidClusterTimeReader.readAbsolute((uid, cpuClusterTimesMs) -> {
-            for (int i = 0; i < cpuClusterTimesMs.length; i++) {
-                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                        wallClockNanos);
-                e.writeInt(uid);
-                e.writeInt(i);
-                e.writeLong(cpuClusterTimesMs[i]);
-                pulledData.add(e);
-            }
-        });
-    }
-
-    private void pullKernelUidCpuActiveTime(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        mCpuUidActiveTimeReader.readAbsolute((uid, cpuActiveTimesMs) -> {
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(uid);
-            e.writeLong((long) cpuActiveTimesMs);
-            pulledData.add(e);
-        });
-    }
-
-    private void pullWifiActivityInfo(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        synchronized (this) {
-            if (mWifiManager == null) {
-                mWifiManager =
-                        IWifiManager.Stub.asInterface(
-                                ServiceManager.getService(Context.WIFI_SERVICE));
-            }
-        }
-        if (mWifiManager != null) {
-            try {
-                SynchronousResultReceiver wifiReceiver = new SynchronousResultReceiver("wifi");
-                mWifiManager.requestActivityInfo(wifiReceiver);
-                final WifiActivityEnergyInfo wifiInfo = awaitControllerInfo(wifiReceiver);
-                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                        wallClockNanos);
-                e.writeLong(wifiInfo.getTimeStamp());
-                e.writeInt(wifiInfo.getStackState());
-                e.writeLong(wifiInfo.getControllerTxTimeMillis());
-                e.writeLong(wifiInfo.getControllerRxTimeMillis());
-                e.writeLong(wifiInfo.getControllerIdleTimeMillis());
-                e.writeLong(wifiInfo.getControllerEnergyUsed());
-                pulledData.add(e);
-            } catch (RemoteException e) {
-                Slog.e(TAG,
-                        "Pulling wifiManager for wifi controller activity energy info has error",
-                        e);
-            } finally {
-                Binder.restoreCallingIdentity(token);
-            }
-        }
-    }
-
-    private void pullModemActivityInfo(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        synchronized (this) {
-            if (mTelephony == null) {
-                mTelephony = TelephonyManager.from(mContext);
-            }
-        }
-        if (mTelephony != null) {
-            SynchronousResultReceiver modemReceiver = new SynchronousResultReceiver("telephony");
-            mTelephony.requestModemActivityInfo(modemReceiver);
-            final ModemActivityInfo modemInfo = awaitControllerInfo(modemReceiver);
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeLong(modemInfo.getTimestamp());
-            e.writeLong(modemInfo.getSleepTimeMillis());
-            e.writeLong(modemInfo.getIdleTimeMillis());
-            e.writeLong(modemInfo.getTransmitPowerInfo().get(0).getTimeInMillis());
-            e.writeLong(modemInfo.getTransmitPowerInfo().get(1).getTimeInMillis());
-            e.writeLong(modemInfo.getTransmitPowerInfo().get(2).getTimeInMillis());
-            e.writeLong(modemInfo.getTransmitPowerInfo().get(3).getTimeInMillis());
-            e.writeLong(modemInfo.getTransmitPowerInfo().get(4).getTimeInMillis());
-            e.writeLong(modemInfo.getReceiveTimeMillis());
-            pulledData.add(e);
-        }
-    }
-
-    private void pullBluetoothActivityInfo(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        BluetoothActivityEnergyInfo info = fetchBluetoothData();
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeLong(info.getTimeStamp());
-        e.writeInt(info.getBluetoothStackState());
-        e.writeLong(info.getControllerTxTimeMillis());
-        e.writeLong(info.getControllerRxTimeMillis());
-        e.writeLong(info.getControllerIdleTimeMillis());
-        e.writeLong(info.getControllerEnergyUsed());
-        pulledData.add(e);
-    }
-
-    private synchronized BluetoothActivityEnergyInfo fetchBluetoothData() {
-        final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        if (adapter != null) {
-            SynchronousResultReceiver bluetoothReceiver = new SynchronousResultReceiver(
-                    "bluetooth");
-            adapter.requestControllerActivityEnergyInfo(bluetoothReceiver);
-            return awaitControllerInfo(bluetoothReceiver);
-        } else {
-            Slog.e(TAG, "Failed to get bluetooth adapter!");
-            return null;
-        }
-    }
-
-    private void pullSystemElapsedRealtime(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeLong(SystemClock.elapsedRealtime());
-        pulledData.add(e);
-    }
-
-    private void pullSystemUpTime(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeLong(SystemClock.uptimeMillis());
-        pulledData.add(e);
-    }
-
-    private void pullProcessMemoryState(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        List<ProcessMemoryState> processMemoryStates =
-                LocalServices.getService(
-                        ActivityManagerInternal.class).getMemoryStateForProcesses();
-        for (ProcessMemoryState processMemoryState : processMemoryStates) {
-            final MemoryStat memoryStat = readMemoryStatFromFilesystem(processMemoryState.uid,
-                    processMemoryState.pid);
-            if (memoryStat == null) {
-                continue;
-            }
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(processMemoryState.uid);
-            e.writeString(processMemoryState.processName);
-            e.writeInt(processMemoryState.oomScore);
-            e.writeLong(memoryStat.pgfault);
-            e.writeLong(memoryStat.pgmajfault);
-            e.writeLong(memoryStat.rssInBytes);
-            e.writeLong(memoryStat.cacheInBytes);
-            e.writeLong(memoryStat.swapInBytes);
-            e.writeLong(0);  // unused
-            e.writeLong(memoryStat.startTimeNanos);
-            e.writeInt(anonAndSwapInKilobytes(memoryStat));
-            pulledData.add(e);
-        }
-    }
-
-    private void pullNativeProcessMemoryState(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        final List<String> processNames = Arrays.asList(MEMORY_INTERESTING_NATIVE_PROCESSES);
-        int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
-        for (int i = 0; i < pids.length; i++) {
-            int pid = pids[i];
-            MemoryStat memoryStat = readMemoryStatFromProcfs(pid);
-            if (memoryStat == null) {
-                continue;
-            }
-            int uid = getUidForPid(pid);
-            String processName = readCmdlineFromProcfs(pid);
-            // Sometimes we get here processName that is not included in the whitelist. It comes
-            // from forking the zygote for an app. We can ignore that sample because this process
-            // is collected by ProcessMemoryState.
-            if (!processNames.contains(processName)) {
-                continue;
-            }
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(uid);
-            e.writeString(processName);
-            e.writeLong(memoryStat.pgfault);
-            e.writeLong(memoryStat.pgmajfault);
-            e.writeLong(memoryStat.rssInBytes);
-            e.writeLong(0);  // unused
-            e.writeLong(memoryStat.startTimeNanos);
-            e.writeLong(memoryStat.swapInBytes);
-            e.writeInt(anonAndSwapInKilobytes(memoryStat));
-            pulledData.add(e);
-        }
-    }
-
-    private static int anonAndSwapInKilobytes(MemoryStat memoryStat) {
-        return (int) ((memoryStat.anonRssInBytes + memoryStat.swapInBytes) / 1024);
-    }
-
-    private void pullProcessMemoryHighWaterMark(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        List<ProcessMemoryState> managedProcessList =
-                LocalServices.getService(
-                        ActivityManagerInternal.class).getMemoryStateForProcesses();
-        for (ProcessMemoryState managedProcess : managedProcessList) {
-            final int rssHighWaterMarkInKilobytes =
-                    readRssHighWaterMarkFromProcfs(managedProcess.pid);
-            if (rssHighWaterMarkInKilobytes == 0) {
-                continue;
-            }
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(managedProcess.uid);
-            e.writeString(managedProcess.processName);
-            // RSS high-water mark in bytes.
-            e.writeLong((long) rssHighWaterMarkInKilobytes * 1024L);
-            e.writeInt(rssHighWaterMarkInKilobytes);
-            pulledData.add(e);
-        }
-        int[] pids = getPidsForCommands(MEMORY_INTERESTING_NATIVE_PROCESSES);
-        for (int i = 0; i < pids.length; i++) {
-            final int pid = pids[i];
-            final int uid = getUidForPid(pid);
-            final String processName = readCmdlineFromProcfs(pid);
-            final int rssHighWaterMarkInKilobytes = readRssHighWaterMarkFromProcfs(pid);
-            if (rssHighWaterMarkInKilobytes == 0) {
-                continue;
-            }
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(uid);
-            e.writeString(processName);
-            // RSS high-water mark in bytes.
-            e.writeLong((long) rssHighWaterMarkInKilobytes * 1024L);
-            e.writeInt(rssHighWaterMarkInKilobytes);
-            pulledData.add(e);
-        }
-        // Invoke rss_hwm_reset binary to reset RSS HWM counters for all processes.
-        SystemProperties.set("sys.rss_hwm_reset.on", "1");
-    }
-
-    private void pullSystemIonHeapSize(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        final long systemIonHeapSizeInBytes = readSystemIonHeapSizeFromDebugfs();
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeLong(systemIonHeapSizeInBytes);
-        pulledData.add(e);
-    }
-
-    private void pullProcessSystemIonHeapSize(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        List<IonAllocations> result = readProcessSystemIonHeapSizesFromDebugfs();
-        for (IonAllocations allocations : result) {
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(getUidForPid(allocations.pid));
-            e.writeString(readCmdlineFromProcfs(allocations.pid));
-            e.writeInt((int) (allocations.totalSizeInBytes / 1024));
-            e.writeInt(allocations.count);
-            e.writeInt((int) (allocations.maxSizeInBytes / 1024));
-            pulledData.add(e);
-        }
-    }
-
-    private void pullBinderCallsStats(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        BinderCallsStatsService.Internal binderStats =
-                LocalServices.getService(BinderCallsStatsService.Internal.class);
-        if (binderStats == null) {
-            throw new IllegalStateException("binderStats is null");
-        }
-
-        List<ExportedCallStat> callStats = binderStats.getExportedCallStats();
-        binderStats.reset();
-        for (ExportedCallStat callStat : callStats) {
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(callStat.workSourceUid);
-            e.writeString(callStat.className);
-            e.writeString(callStat.methodName);
-            e.writeLong(callStat.callCount);
-            e.writeLong(callStat.exceptionCount);
-            e.writeLong(callStat.latencyMicros);
-            e.writeLong(callStat.maxLatencyMicros);
-            e.writeLong(callStat.cpuTimeMicros);
-            e.writeLong(callStat.maxCpuTimeMicros);
-            e.writeLong(callStat.maxReplySizeBytes);
-            e.writeLong(callStat.maxRequestSizeBytes);
-            e.writeLong(callStat.recordedCallCount);
-            e.writeInt(callStat.screenInteractive ? 1 : 0);
-            e.writeInt(callStat.callingUid);
-            pulledData.add(e);
-        }
-    }
-
-    private void pullBinderCallsStatsExceptions(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        BinderCallsStatsService.Internal binderStats =
-                LocalServices.getService(BinderCallsStatsService.Internal.class);
-        if (binderStats == null) {
-            throw new IllegalStateException("binderStats is null");
-        }
-
-        ArrayMap<String, Integer> exceptionStats = binderStats.getExportedExceptionStats();
-        // TODO: decouple binder calls exceptions with the rest of the binder calls data so that we
-        // can reset the exception stats.
-        for (Entry<String, Integer> entry : exceptionStats.entrySet()) {
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeString(entry.getKey());
-            e.writeInt(entry.getValue());
-            pulledData.add(e);
-        }
-    }
-
-    private void pullLooperStats(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        LooperStats looperStats = LocalServices.getService(LooperStats.class);
-        if (looperStats == null) {
-            throw new IllegalStateException("looperStats null");
-        }
-
-        List<LooperStats.ExportedEntry> entries = looperStats.getEntries();
-        looperStats.reset();
-        for (LooperStats.ExportedEntry entry : entries) {
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(entry.workSourceUid);
-            e.writeString(entry.handlerClassName);
-            e.writeString(entry.threadName);
-            e.writeString(entry.messageName);
-            e.writeLong(entry.messageCount);
-            e.writeLong(entry.exceptionCount);
-            e.writeLong(entry.recordedMessageCount);
-            e.writeLong(entry.totalLatencyMicros);
-            e.writeLong(entry.cpuUsageMicros);
-            e.writeBoolean(entry.isInteractive);
-            e.writeLong(entry.maxCpuUsageMicros);
-            e.writeLong(entry.maxLatencyMicros);
-            e.writeLong(entry.recordedDelayMessageCount);
-            e.writeLong(entry.delayMillis);
-            e.writeLong(entry.maxDelayMillis);
-            pulledData.add(e);
-        }
-    }
-
-    private void pullDiskStats(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        // Run a quick-and-dirty performance test: write 512 bytes
-        byte[] junk = new byte[512];
-        for (int i = 0; i < junk.length; i++) junk[i] = (byte) i;  // Write nonzero bytes
-
-        File tmp = new File(Environment.getDataDirectory(), "system/statsdperftest.tmp");
-        FileOutputStream fos = null;
-        IOException error = null;
-
-        long before = SystemClock.elapsedRealtime();
-        try {
-            fos = new FileOutputStream(tmp);
-            fos.write(junk);
-        } catch (IOException e) {
-            error = e;
-        } finally {
-            try {
-                if (fos != null) fos.close();
-            } catch (IOException e) {
-                // Do nothing.
-            }
-        }
-
-        long latency = SystemClock.elapsedRealtime() - before;
-        if (tmp.exists()) tmp.delete();
-
-        if (error != null) {
-            Slog.e(TAG, "Error performing diskstats latency test");
-            latency = -1;
-        }
-        // File based encryption.
-        boolean fileBased = StorageManager.isFileEncryptedNativeOnly();
-
-        //Recent disk write speed. Binder call to storaged.
-        int writeSpeed = -1;
-        try {
-            IBinder binder = ServiceManager.getService("storaged");
-            if (binder == null) {
-                Slog.e(TAG, "storaged not found");
-            }
-            IStoraged storaged = IStoraged.Stub.asInterface(binder);
-            writeSpeed = storaged.getRecentPerf();
-        } catch (RemoteException e) {
-            Slog.e(TAG, "storaged not found");
-        }
-
-        // Add info pulledData.
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeLong(latency);
-        e.writeBoolean(fileBased);
-        e.writeInt(writeSpeed);
-        pulledData.add(e);
-    }
-
-    private void pullDirectoryUsage(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        StatFs statFsData = new StatFs(Environment.getDataDirectory().getAbsolutePath());
-        StatFs statFsSystem = new StatFs(Environment.getRootDirectory().getAbsolutePath());
-        StatFs statFsCache = new StatFs(Environment.getDownloadCacheDirectory().getAbsolutePath());
-
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__DATA);
-        e.writeLong(statFsData.getAvailableBytes());
-        e.writeLong(statFsData.getTotalBytes());
-        pulledData.add(e);
-
-        e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__CACHE);
-        e.writeLong(statFsCache.getAvailableBytes());
-        e.writeLong(statFsCache.getTotalBytes());
-        pulledData.add(e);
-
-        e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeInt(StatsLog.DIRECTORY_USAGE__DIRECTORY__SYSTEM);
-        e.writeLong(statFsSystem.getAvailableBytes());
-        e.writeLong(statFsSystem.getTotalBytes());
-        pulledData.add(e);
-    }
-
-    private void pullAppSize(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        try {
-            String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
-            JSONObject json = new JSONObject(jsonStr);
-            long cache_time = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
-            JSONArray pkg_names = json.getJSONArray(DiskStatsFileLogger.PACKAGE_NAMES_KEY);
-            JSONArray app_sizes = json.getJSONArray(DiskStatsFileLogger.APP_SIZES_KEY);
-            JSONArray app_data_sizes = json.getJSONArray(DiskStatsFileLogger.APP_DATA_KEY);
-            JSONArray app_cache_sizes = json.getJSONArray(DiskStatsFileLogger.APP_CACHES_KEY);
-            // Sanity check: Ensure all 4 lists have the same length.
-            int length = pkg_names.length();
-            if (app_sizes.length() != length || app_data_sizes.length() != length
-                    || app_cache_sizes.length() != length) {
-                Slog.e(TAG, "formatting error in diskstats cache file!");
-                return;
-            }
-            for (int i = 0; i < length; i++) {
-                StatsLogEventWrapper e =
-                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-                e.writeString(pkg_names.getString(i));
-                e.writeLong(app_sizes.optLong(i, -1L));
-                e.writeLong(app_data_sizes.optLong(i, -1L));
-                e.writeLong(app_cache_sizes.optLong(i, -1L));
-                e.writeLong(cache_time);
-                pulledData.add(e);
-            }
-        } catch (IOException | JSONException e) {
-            Slog.e(TAG, "exception reading diskstats cache file", e);
-        }
-    }
-
-    private void pullCategorySize(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        try {
-            String jsonStr = IoUtils.readFileAsString(DiskStatsLoggingService.DUMPSYS_CACHE_PATH);
-            JSONObject json = new JSONObject(jsonStr);
-            long cacheTime = json.optLong(DiskStatsFileLogger.LAST_QUERY_TIMESTAMP_KEY, -1L);
-
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_SIZE);
-            e.writeLong(json.optLong(DiskStatsFileLogger.APP_SIZE_AGG_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_DATA_SIZE);
-            e.writeLong(json.optLong(DiskStatsFileLogger.APP_DATA_SIZE_AGG_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__APP_CACHE_SIZE);
-            e.writeLong(json.optLong(DiskStatsFileLogger.APP_CACHE_AGG_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__PHOTOS);
-            e.writeLong(json.optLong(DiskStatsFileLogger.PHOTOS_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__VIDEOS);
-            e.writeLong(json.optLong(DiskStatsFileLogger.VIDEOS_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__AUDIO);
-            e.writeLong(json.optLong(DiskStatsFileLogger.AUDIO_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__DOWNLOADS);
-            e.writeLong(json.optLong(DiskStatsFileLogger.DOWNLOADS_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__SYSTEM);
-            e.writeLong(json.optLong(DiskStatsFileLogger.SYSTEM_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-
-            e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(StatsLog.CATEGORY_SIZE__CATEGORY__OTHER);
-            e.writeLong(json.optLong(DiskStatsFileLogger.MISC_KEY, -1L));
-            e.writeLong(cacheTime);
-            pulledData.add(e);
-        } catch (IOException | JSONException e) {
-            Slog.e(TAG, "exception reading diskstats cache file", e);
-        }
-    }
-
-    private void pullNumBiometricsEnrolled(int modality, int tagId, long elapsedNanos,
-            long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        final PackageManager pm = mContext.getPackageManager();
-        FingerprintManager fingerprintManager = null;
-        FaceManager faceManager = null;
-
-        if (pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
-            fingerprintManager = mContext.getSystemService(
-                    FingerprintManager.class);
-        }
-        if (pm.hasSystemFeature(PackageManager.FEATURE_FACE)) {
-            faceManager = mContext.getSystemService(FaceManager.class);
-        }
-
-        if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT && fingerprintManager == null) {
-            return;
-        }
-        if (modality == BiometricsProtoEnums.MODALITY_FACE && faceManager == null) {
-            return;
-        }
-        UserManager userManager = mContext.getSystemService(UserManager.class);
-        if (userManager == null) {
-            return;
-        }
-
-        final long token = Binder.clearCallingIdentity();
-        for (UserInfo user : userManager.getUsers()) {
-            final int userId = user.getUserHandle().getIdentifier();
-            int numEnrolled = 0;
-            if (modality == BiometricsProtoEnums.MODALITY_FINGERPRINT) {
-                numEnrolled = fingerprintManager.getEnrolledFingerprints(userId).size();
-            } else if (modality == BiometricsProtoEnums.MODALITY_FACE) {
-                numEnrolled = faceManager.getEnrolledFaces(userId).size();
-            } else {
-                return;
-            }
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(userId);
-            e.writeInt(numEnrolled);
-            pulledData.add(e);
-        }
-        Binder.restoreCallingIdentity(token);
-    }
-
-    // read high watermark for section
-    private long readProcStatsHighWaterMark(int section) {
-        try {
-            File[] files = mBaseDir.listFiles((d, name) -> {
-                return name.toLowerCase().startsWith(String.valueOf(section) + '_');
-            });
-            if (files == null || files.length == 0) {
-                return 0;
-            }
-            if (files.length > 1) {
-                Log.e(TAG, "Only 1 file expected for high water mark. Found " + files.length);
-            }
-            return Long.valueOf(files[0].getName().split("_")[1]);
-        } catch (SecurityException e) {
-            Log.e(TAG, "Failed to get procstats high watermark file.", e);
-        } catch (NumberFormatException e) {
-            Log.e(TAG, "Failed to parse file name.", e);
-        }
-        return 0;
-    }
-
-    private IProcessStats mProcessStats =
-            IProcessStats.Stub.asInterface(ServiceManager.getService(ProcessStats.SERVICE_NAME));
-
-    private void pullProcessStats(int section, int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        synchronized (this) {
-            try {
-                long lastHighWaterMark = readProcStatsHighWaterMark(section);
-                List<ParcelFileDescriptor> statsFiles = new ArrayList<>();
-                long highWaterMark = mProcessStats.getCommittedStats(
-                        lastHighWaterMark, section, true, statsFiles);
-                if (statsFiles.size() != 1) {
-                    return;
-                }
-                InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(
-                        statsFiles.get(0));
-                int[] len = new int[1];
-                byte[] stats = readFully(stream, len);
-                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                        wallClockNanos);
-                e.writeStorage(Arrays.copyOf(stats, len[0]));
-                pulledData.add(e);
-                new File(mBaseDir.getAbsolutePath() + "/" + section + "_"
-                        + lastHighWaterMark).delete();
-                new File(
-                        mBaseDir.getAbsolutePath() + "/" + section + "_"
-                                + highWaterMark).createNewFile();
-            } catch (IOException e) {
-                Log.e(TAG, "Getting procstats failed: ", e);
-            } catch (RemoteException e) {
-                Log.e(TAG, "Getting procstats failed: ", e);
-            } catch (SecurityException e) {
-                Log.e(TAG, "Getting procstats failed: ", e);
-            }
-        }
-    }
-
-    static byte[] readFully(InputStream stream, int[] outLen) throws IOException {
-        int pos = 0;
-        final int initialAvail = stream.available();
-        byte[] data = new byte[initialAvail > 0 ? (initialAvail + 1) : 16384];
-        while (true) {
-            int amt = stream.read(data, pos, data.length - pos);
-            if (DEBUG) {
-                Slog.i(TAG, "Read " + amt + " bytes at " + pos + " of avail " + data.length);
-            }
-            if (amt < 0) {
-                if (DEBUG) {
-                    Slog.i(TAG, "**** FINISHED READING: pos=" + pos + " len=" + data.length);
-                }
-                outLen[0] = pos;
-                return data;
-            }
-            pos += amt;
-            if (pos >= data.length) {
-                byte[] newData = new byte[pos + 16384];
-                if (DEBUG) {
-                    Slog.i(TAG, "Copying " + pos + " bytes to new array len " + newData.length);
-                }
-                System.arraycopy(data, 0, newData, 0, pos);
-                data = newData;
-            }
-        }
-    }
-
-    private void pullPowerProfile(
-            int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        PowerProfile powerProfile = new PowerProfile(mContext);
-        checkNotNull(powerProfile);
-
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                wallClockNanos);
-        ProtoOutputStream proto = new ProtoOutputStream();
-        powerProfile.writeToProto(proto);
-        proto.flush();
-        e.writeStorage(proto.getBytes());
-        pulledData.add(e);
-    }
-
-    private void pullBuildInformation(int tagId,
-            long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeString(Build.FINGERPRINT);
-        e.writeString(Build.BRAND);
-        e.writeString(Build.PRODUCT);
-        e.writeString(Build.DEVICE);
-        e.writeString(Build.VERSION.RELEASE);
-        e.writeString(Build.ID);
-        e.writeString(Build.VERSION.INCREMENTAL);
-        e.writeString(Build.TYPE);
-        e.writeString(Build.TAGS);
-        pulledData.add(e);
-    }
-
-    private BatteryStatsHelper getBatteryStatsHelper() {
-        if (mBatteryStatsHelper == null) {
-            final long callingToken = Binder.clearCallingIdentity();
-            try {
-                // clearCallingIdentity required for BatteryStatsHelper.checkWifiOnly().
-                mBatteryStatsHelper = new BatteryStatsHelper(mContext, false);
-            } finally {
-                Binder.restoreCallingIdentity(callingToken);
-            }
-            mBatteryStatsHelper.create((Bundle) null);
-        }
-        long currentTime = SystemClock.elapsedRealtime();
-        if (currentTime - mBatteryStatsHelperTimestampMs >= MAX_BATTERY_STATS_HELPER_FREQUENCY_MS) {
-            // Load BatteryStats and do all the calculations.
-            mBatteryStatsHelper.refreshStats(BatteryStats.STATS_SINCE_CHARGED, UserHandle.USER_ALL);
-            // Calculations are done so we don't need to save the raw BatteryStats data in RAM.
-            mBatteryStatsHelper.clearStats();
-            mBatteryStatsHelperTimestampMs = currentTime;
-        }
-        return mBatteryStatsHelper;
-    }
-
-    private long milliAmpHrsToNanoAmpSecs(double mAh) {
-        final long MILLI_AMP_HR_TO_NANO_AMP_SECS = 1_000_000L * 3600L;
-        return (long) (mAh * MILLI_AMP_HR_TO_NANO_AMP_SECS + 0.5);
-    }
-
-    private void pullDeviceCalculatedPowerUse(int tagId,
-            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        BatteryStatsHelper bsHelper = getBatteryStatsHelper();
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeLong(milliAmpHrsToNanoAmpSecs(bsHelper.getComputedPower()));
-        pulledData.add(e);
-    }
-
-    private void pullDeviceCalculatedPowerBlameUid(int tagId,
-            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
-        if (sippers == null) {
-            return;
-        }
-        for (BatterySipper bs : sippers) {
-            if (bs.drainType != bs.drainType.APP) {
-                continue;
-            }
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(bs.uidObj.getUid());
-            e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
-            pulledData.add(e);
-        }
-    }
-
-    private void pullDeviceCalculatedPowerBlameOther(int tagId,
-            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        final List<BatterySipper> sippers = getBatteryStatsHelper().getUsageList();
-        if (sippers == null) {
-            return;
-        }
-        for (BatterySipper bs : sippers) {
-            if (bs.drainType == bs.drainType.APP) {
-                continue; // This is a separate atom; see pullDeviceCalculatedPowerBlameUid().
-            }
-            if (bs.drainType == bs.drainType.USER) {
-                continue; // This is not supported. We purposefully calculate over USER_ALL.
-            }
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e.writeInt(bs.drainType.ordinal());
-            e.writeLong(milliAmpHrsToNanoAmpSecs(bs.totalPowerMah));
-            pulledData.add(e);
-        }
-    }
-
-    private void pullDiskIo(int tagId, long elapsedNanos, final long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        mStoragedUidIoStatsReader.readAbsolute((uid, fgCharsRead, fgCharsWrite, fgBytesRead,
-                fgBytesWrite, bgCharsRead, bgCharsWrite, bgBytesRead, bgBytesWrite,
-                fgFsync, bgFsync) -> {
-            StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                    wallClockNanos);
-            e.writeInt(uid);
-            e.writeLong(fgCharsRead);
-            e.writeLong(fgCharsWrite);
-            e.writeLong(fgBytesRead);
-            e.writeLong(fgBytesWrite);
-            e.writeLong(bgCharsRead);
-            e.writeLong(bgCharsWrite);
-            e.writeLong(bgBytesRead);
-            e.writeLong(bgBytesWrite);
-            e.writeLong(fgFsync);
-            e.writeLong(bgFsync);
-            pulledData.add(e);
-        });
-    }
-
-    private void pullProcessCpuTime(int tagId, long elapsedNanos, final long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        synchronized (this) {
-            if (mProcessCpuTracker == null) {
-                mProcessCpuTracker = new ProcessCpuTracker(false);
-                mProcessCpuTracker.init();
-            }
-            mProcessCpuTracker.update();
-            for (int i = 0; i < mProcessCpuTracker.countStats(); i++) {
-                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
-                StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos,
-                        wallClockNanos);
-                e.writeInt(st.uid);
-                e.writeString(st.name);
-                e.writeLong(st.base_utime);
-                e.writeLong(st.base_stime);
-                pulledData.add(e);
-            }
-        }
-    }
-
-    private void pullCpuTimePerThreadFreq(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        if (this.mKernelCpuThreadReader == null) {
-            throw new IllegalStateException("mKernelCpuThreadReader is null");
-        }
-        ArrayList<KernelCpuThreadReader.ProcessCpuUsage> processCpuUsages =
-                this.mKernelCpuThreadReader.getProcessCpuUsageDiffed();
-        if (processCpuUsages == null) {
-            throw new IllegalStateException("processCpuUsages is null");
-        }
-        int[] cpuFrequencies = mKernelCpuThreadReader.getCpuFrequenciesKhz();
-        if (cpuFrequencies.length > CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES) {
-            String message = "Expected maximum " + CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES
-                    + " frequencies, but got " + cpuFrequencies.length;
-            Slog.w(TAG, message);
-            throw new IllegalStateException(message);
-        }
-        for (int i = 0; i < processCpuUsages.size(); i++) {
-            KernelCpuThreadReader.ProcessCpuUsage processCpuUsage = processCpuUsages.get(i);
-            ArrayList<KernelCpuThreadReader.ThreadCpuUsage> threadCpuUsages =
-                    processCpuUsage.threadCpuUsages;
-            for (int j = 0; j < threadCpuUsages.size(); j++) {
-                KernelCpuThreadReader.ThreadCpuUsage threadCpuUsage = threadCpuUsages.get(j);
-                if (threadCpuUsage.usageTimesMillis.length != cpuFrequencies.length) {
-                    String message = "Unexpected number of usage times,"
-                            + " expected " + cpuFrequencies.length
-                            + " but got " + threadCpuUsage.usageTimesMillis.length;
-                    Slog.w(TAG, message);
-                    throw new IllegalStateException(message);
-                }
-
-                StatsLogEventWrapper e =
-                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-                e.writeInt(processCpuUsage.uid);
-                e.writeInt(processCpuUsage.processId);
-                e.writeInt(threadCpuUsage.threadId);
-                e.writeString(processCpuUsage.processName);
-                e.writeString(threadCpuUsage.threadName);
-                for (int k = 0; k < CPU_TIME_PER_THREAD_FREQ_MAX_NUM_FREQUENCIES; k++) {
-                    if (k < cpuFrequencies.length) {
-                        e.writeInt(cpuFrequencies[k]);
-                        e.writeInt(threadCpuUsage.usageTimesMillis[k]);
-                    } else {
-                        // If we have no more frequencies to write, we still must write empty data.
-                        // We know that this data is empty (and not just zero) because all
-                        // frequencies are expected to be greater than zero
-                        e.writeInt(0);
-                        e.writeInt(0);
-                    }
-                }
-                pulledData.add(e);
-            }
-        }
-    }
-
-    private void pullTemperature(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long callingToken = Binder.clearCallingIdentity();
-        try {
-            List<Temperature> temperatures = sThermalService.getCurrentTemperatures();
-            for (Temperature temp : temperatures) {
-                StatsLogEventWrapper e =
-                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-                e.writeInt(temp.getType());
-                e.writeString(temp.getName());
-                e.writeInt((int) (temp.getValue() * 10));
-                e.writeInt(temp.getStatus());
-                pulledData.add(e);
-            }
-        } catch (RemoteException e) {
-            // Should not happen.
-            Slog.e(TAG, "Disconnected from thermal service. Cannot pull temperatures.");
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    private void pullCoolingDevices(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long callingToken = Binder.clearCallingIdentity();
-        try {
-            List<CoolingDevice> devices = sThermalService.getCurrentCoolingDevices();
-            for (CoolingDevice device : devices) {
-                StatsLogEventWrapper e =
-                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-                e.writeInt(device.getType());
-                e.writeString(device.getName());
-                e.writeInt((int) (device.getValue()));
-                pulledData.add(e);
-            }
-        } catch (RemoteException e) {
-            // Should not happen.
-            Slog.e(TAG, "Disconnected from thermal service. Cannot pull temperatures.");
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    private void pullDebugElapsedClock(int tagId,
-            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        final long elapsedMillis = SystemClock.elapsedRealtime();
-        final long clockDiffMillis = mDebugElapsedClockPreviousValue == 0
-                ? 0 : elapsedMillis - mDebugElapsedClockPreviousValue;
-
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeLong(mDebugElapsedClockPullCount);
-        e.writeLong(elapsedMillis);
-        // Log it twice to be able to test multi-value aggregation from ValueMetric.
-        e.writeLong(elapsedMillis);
-        e.writeLong(clockDiffMillis);
-        e.writeInt(1 /* always set */);
-        pulledData.add(e);
-
-        if (mDebugElapsedClockPullCount % 2 == 1) {
-            StatsLogEventWrapper e2 = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-            e2.writeLong(mDebugElapsedClockPullCount);
-            e2.writeLong(elapsedMillis);
-            // Log it twice to be able to test multi-value aggregation from ValueMetric.
-            e2.writeLong(elapsedMillis);
-            e2.writeLong(clockDiffMillis);
-            e2.writeInt(2 /* set on odd pulls */);
-            pulledData.add(e2);
-        }
-
-        mDebugElapsedClockPullCount++;
-        mDebugElapsedClockPreviousValue = elapsedMillis;
-    }
-
-    private void pullDebugFailingElapsedClock(int tagId,
-            long elapsedNanos, final long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        final long elapsedMillis = SystemClock.elapsedRealtime();
-        // Fails every 5 buckets.
-        if (mDebugFailingElapsedClockPullCount++ % 5 == 0) {
-            mDebugFailingElapsedClockPreviousValue = elapsedMillis;
-            throw new RuntimeException("Failing debug elapsed clock");
-        }
-
-        e.writeLong(mDebugFailingElapsedClockPullCount);
-        e.writeLong(elapsedMillis);
-        // Log it twice to be able to test multi-value aggregation from ValueMetric.
-        e.writeLong(elapsedMillis);
-        e.writeLong(mDebugFailingElapsedClockPreviousValue == 0
-                ? 0 : elapsedMillis - mDebugFailingElapsedClockPreviousValue);
-        mDebugFailingElapsedClockPreviousValue = elapsedMillis;
-        pulledData.add(e);
-    }
-
-    private void pullDangerousPermissionState(long elapsedNanos, final long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        try {
-            PackageManager pm = mContext.getPackageManager();
-
-            List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
-
-            int numUsers = users.size();
-            for (int userNum = 0; userNum < numUsers; userNum++) {
-                UserHandle user = users.get(userNum).getUserHandle();
-
-                List<PackageInfo> pkgs = pm.getInstalledPackagesAsUser(
-                        PackageManager.GET_PERMISSIONS, user.getIdentifier());
-
-                int numPkgs = pkgs.size();
-                for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
-                    PackageInfo pkg = pkgs.get(pkgNum);
-
-                    if (pkg.requestedPermissions == null) {
-                        continue;
-                    }
-
-                    int numPerms = pkg.requestedPermissions.length;
-                    for (int permNum  = 0; permNum < numPerms; permNum++) {
-                        String permName = pkg.requestedPermissions[permNum];
-
-                        PermissionInfo permissionInfo;
-                        int permissionFlags = 0;
-                        try {
-                            permissionInfo = pm.getPermissionInfo(permName, 0);
-                            permissionFlags =
-                                pm.getPermissionFlags(permName, pkg.packageName, user);
-
-                        } catch (PackageManager.NameNotFoundException ignored) {
-                            continue;
-                        }
-
-                        if (permissionInfo.getProtection() != PROTECTION_DANGEROUS) {
-                            continue;
-                        }
-
-                        StatsLogEventWrapper e = new StatsLogEventWrapper(
-                                StatsLog.DANGEROUS_PERMISSION_STATE, elapsedNanos, wallClockNanos);
-
-                        e.writeString(permName);
-                        e.writeInt(pkg.applicationInfo.uid);
-                        e.writeString(pkg.packageName);
-                        e.writeBoolean((pkg.requestedPermissionsFlags[permNum]
-                                & REQUESTED_PERMISSION_GRANTED) != 0);
-                        e.writeInt(permissionFlags);
-
-                        pulledData.add(e);
-                    }
-                }
-            }
-        } catch (Throwable t) {
-            Log.e(TAG, "Could not read permissions", t);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    private void pullAppOps(long elapsedNanos, final long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long token = Binder.clearCallingIdentity();
-        try {
-            AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
-
-            CompletableFuture<HistoricalOps> ops = new CompletableFuture<>();
-            HistoricalOpsRequest histOpsRequest =
-                    new HistoricalOpsRequest.Builder(
-                            Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli(),
-                            Long.MAX_VALUE).build();
-            appOps.getHistoricalOps(histOpsRequest, mContext.getMainExecutor(), ops::complete);
-
-            HistoricalOps histOps = ops.get(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS,
-                    TimeUnit.MILLISECONDS);
-
-            StatsLogEventWrapper e = new StatsLogEventWrapper(StatsLog.APP_OPS, elapsedNanos,
-                    wallClockNanos);
-
-            for (int uidIdx = 0; uidIdx < histOps.getUidCount(); uidIdx++) {
-                final HistoricalUidOps uidOps = histOps.getUidOpsAt(uidIdx);
-                final int uid = uidOps.getUid();
-                for (int pkgIdx = 0; pkgIdx < uidOps.getPackageCount(); pkgIdx++) {
-                    final HistoricalPackageOps packageOps = uidOps.getPackageOpsAt(pkgIdx);
-                    for (int opIdx = 0; opIdx < packageOps.getOpCount(); opIdx++) {
-                        final AppOpsManager.HistoricalOp op  = packageOps.getOpAt(opIdx);
-                        e.writeInt(uid);
-                        e.writeString(packageOps.getPackageName());
-                        e.writeInt(op.getOpCode());
-                        e.writeLong(op.getForegroundAccessCount(OP_FLAGS_ALL_TRUSTED));
-                        e.writeLong(op.getBackgroundAccessCount(OP_FLAGS_ALL_TRUSTED));
-                        e.writeLong(op.getForegroundRejectCount(OP_FLAGS_ALL_TRUSTED));
-                        e.writeLong(op.getBackgroundRejectCount(OP_FLAGS_ALL_TRUSTED));
-                        e.writeLong(op.getForegroundAccessDuration(OP_FLAGS_ALL_TRUSTED));
-                        e.writeLong(op.getBackgroundAccessDuration(OP_FLAGS_ALL_TRUSTED));
-                        pulledData.add(e);
-                    }
-                }
-            }
-        } catch (Throwable t) {
-            Log.e(TAG, "Could not read appops", t);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-
-    /**
-     * Add a RoleHolder atom for each package that holds a role.
-     *
-     * @param elapsedNanos the time since boot
-     * @param wallClockNanos the time on the clock
-     * @param pulledData the data sink to write to
-     */
-    private void pullRoleHolders(long elapsedNanos, final long wallClockNanos,
-            @NonNull List<StatsLogEventWrapper> pulledData) {
-        long callingToken = Binder.clearCallingIdentity();
-        try {
-            PackageManager pm = mContext.getPackageManager();
-            RoleManagerInternal rmi = LocalServices.getService(RoleManagerInternal.class);
-
-            List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
-
-            int numUsers = users.size();
-            for (int userNum = 0; userNum < numUsers; userNum++) {
-                int userId = users.get(userNum).getUserHandle().getIdentifier();
-
-                ArrayMap<String, ArraySet<String>> roles = rmi.getRolesAndHolders(
-                        userId);
-
-                int numRoles = roles.size();
-                for (int roleNum = 0; roleNum < numRoles; roleNum++) {
-                    String roleName = roles.keyAt(roleNum);
-                    ArraySet<String> holders = roles.valueAt(roleNum);
-
-                    int numHolders = holders.size();
-                    for (int holderNum = 0; holderNum < numHolders; holderNum++) {
-                        String holderName = holders.valueAt(holderNum);
-
-                        PackageInfo pkg;
-                        try {
-                            pkg = pm.getPackageInfoAsUser(holderName, 0, userId);
-                        } catch (PackageManager.NameNotFoundException e) {
-                            Log.w(TAG, "Role holder " + holderName + " not found");
-                            return;
-                        }
-
-                        StatsLogEventWrapper e = new StatsLogEventWrapper(StatsLog.ROLE_HOLDER,
-                                elapsedNanos, wallClockNanos);
-                        e.writeInt(pkg.applicationInfo.uid);
-                        e.writeString(holderName);
-                        e.writeString(roleName);
-                        pulledData.add(e);
-                    }
-                }
-            }
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    private void pullTimeZoneDataInfo(int tagId,
-            long elapsedNanos, long wallClockNanos, List<StatsLogEventWrapper> pulledData) {
-        String tzDbVersion = "Unknown";
-        try {
-            tzDbVersion = android.icu.util.TimeZone.getTZDataVersion();
-        } catch (Exception e) {
-            Log.e(TAG, "Getting tzdb version failed: ", e);
-        }
-
-        StatsLogEventWrapper e = new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-        e.writeString(tzDbVersion);
-        pulledData.add(e);
-    }
-
-    private void pullExternalStorageInfo(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        StorageManager storageManager = mContext.getSystemService(StorageManager.class);
-        if (storageManager != null) {
-            List<VolumeInfo> volumes = storageManager.getVolumes();
-            for (VolumeInfo vol : volumes) {
-                final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
-                final DiskInfo diskInfo = vol.getDisk();
-                if (diskInfo != null) {
-                    if (envState.equals(Environment.MEDIA_MOUNTED)) {
-                        // Get the type of the volume, if it is adoptable or portable.
-                        int volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__OTHER;
-                        if (vol.getType() == TYPE_PUBLIC) {
-                            volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__PUBLIC;
-                        } else if (vol.getType() == TYPE_PRIVATE) {
-                            volumeType = StatsLog.EXTERNAL_STORAGE_INFO__VOLUME_TYPE__PRIVATE;
-                        }
-                        // Get the type of external storage inserted in the device (sd cards,
-                        // usb, etc)
-                        int externalStorageType;
-                        if (diskInfo.isSd()) {
-                            externalStorageType = StorageEnums.SD_CARD;
-                        } else if (diskInfo.isUsb()) {
-                            externalStorageType = StorageEnums.USB;
-                        } else {
-                            externalStorageType = StorageEnums.OTHER;
-                        }
-                        StatsLogEventWrapper e =
-                                new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-                        e.writeInt(externalStorageType);
-                        e.writeInt(volumeType);
-                        e.writeLong(diskInfo.size);
-                        pulledData.add(e);
-                    }
-                }
-            }
-        }
-    }
-
-    private void pullAppsOnExternalStorageInfo(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        PackageManager pm = mContext.getPackageManager();
-        StorageManager storage = mContext.getSystemService(StorageManager.class);
-        List<ApplicationInfo> apps = pm.getInstalledApplications(/* flags = */ 0);
-        for (ApplicationInfo appInfo : apps) {
-            UUID storageUuid = appInfo.storageUuid;
-            if (storageUuid != null) {
-                VolumeInfo volumeInfo = storage.findVolumeByUuid(appInfo.storageUuid.toString());
-                if (volumeInfo != null) {
-                    DiskInfo diskInfo = volumeInfo.getDisk();
-                    if (diskInfo != null) {
-                        int externalStorageType = -1;
-                        if (diskInfo.isSd()) {
-                            externalStorageType = StorageEnums.SD_CARD;
-                        } else if (diskInfo.isUsb()) {
-                            externalStorageType = StorageEnums.USB;
-                        } else if (appInfo.isExternal()) {
-                            externalStorageType = StorageEnums.OTHER;
-                        }
-                        // App is installed on external storage.
-                        if (externalStorageType != -1) {
-                            StatsLogEventWrapper e =
-                                    new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-                            e.writeInt(externalStorageType);
-                            e.writeString(appInfo.packageName);
-                            pulledData.add(e);
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    private void pullFaceSettings(int tagId, long elapsedNanos, long wallClockNanos,
-            List<StatsLogEventWrapper> pulledData) {
-        long callingToken = Binder.clearCallingIdentity();
-        try {
-            List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
-            int numUsers = users.size();
-            for (int userNum = 0; userNum < numUsers; userNum++) {
-                int userId = users.get(userNum).getUserHandle().getIdentifier();
-
-                StatsLogEventWrapper e =
-                        new StatsLogEventWrapper(tagId, elapsedNanos, wallClockNanos);
-                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                        Settings.Secure.FACE_UNLOCK_KEYGUARD_ENABLED, 1,
-                        userId) != 0);
-                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                        Settings.Secure.FACE_UNLOCK_DISMISSES_KEYGUARD,
-                        0, userId) != 0);
-                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                        Settings.Secure.FACE_UNLOCK_ATTENTION_REQUIRED, 1,
-                        userId) != 0);
-                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                        Settings.Secure.FACE_UNLOCK_APP_ENABLED, 1,
-                        userId) != 0);
-                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                        Settings.Secure.FACE_UNLOCK_ALWAYS_REQUIRE_CONFIRMATION, 0,
-                        userId) != 0);
-                e.writeBoolean(Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                        Settings.Secure.FACE_UNLOCK_DIVERSITY_REQUIRED, 1,
-                        userId) != 0);
-
-                pulledData.add(e);
-            }
-        } finally {
-            Binder.restoreCallingIdentity(callingToken);
-        }
-    }
-
-    /**
-     * Pulls various data.
-     */
-    @Override // Binder call
-    public StatsLogEventWrapper[] pullData(int tagId) {
-        enforceCallingPermission();
-        if (DEBUG) {
-            Slog.d(TAG, "Pulling " + tagId);
-        }
-        List<StatsLogEventWrapper> ret = new ArrayList<>();
-        long elapsedNanos = SystemClock.elapsedRealtimeNanos();
-        long wallClockNanos = SystemClock.currentTimeMicro() * 1000L;
-        switch (tagId) {
-            case StatsLog.WIFI_BYTES_TRANSFER: {
-                pullWifiBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.MOBILE_BYTES_TRANSFER: {
-                pullMobileBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.WIFI_BYTES_TRANSFER_BY_FG_BG: {
-                pullWifiBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.MOBILE_BYTES_TRANSFER_BY_FG_BG: {
-                pullMobileBytesTransferByFgBg(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.BLUETOOTH_BYTES_TRANSFER: {
-                pullBluetoothBytesTransfer(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.KERNEL_WAKELOCK: {
-                pullKernelWakelock(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.CPU_TIME_PER_FREQ: {
-                pullCpuTimePerFreq(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.CPU_TIME_PER_UID: {
-                pullKernelUidCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.CPU_TIME_PER_UID_FREQ: {
-                pullKernelUidCpuFreqTime(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.CPU_CLUSTER_TIME: {
-                pullKernelUidCpuClusterTime(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.CPU_ACTIVE_TIME: {
-                pullKernelUidCpuActiveTime(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.WIFI_ACTIVITY_INFO: {
-                pullWifiActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.MODEM_ACTIVITY_INFO: {
-                pullModemActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.BLUETOOTH_ACTIVITY_INFO: {
-                pullBluetoothActivityInfo(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.SYSTEM_UPTIME: {
-                pullSystemUpTime(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.SYSTEM_ELAPSED_REALTIME: {
-                pullSystemElapsedRealtime(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.PROCESS_MEMORY_STATE: {
-                pullProcessMemoryState(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.NATIVE_PROCESS_MEMORY_STATE: {
-                pullNativeProcessMemoryState(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.PROCESS_MEMORY_HIGH_WATER_MARK: {
-                pullProcessMemoryHighWaterMark(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.SYSTEM_ION_HEAP_SIZE: {
-                pullSystemIonHeapSize(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.PROCESS_SYSTEM_ION_HEAP_SIZE: {
-                pullProcessSystemIonHeapSize(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.BINDER_CALLS: {
-                pullBinderCallsStats(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.BINDER_CALLS_EXCEPTIONS: {
-                pullBinderCallsStatsExceptions(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.LOOPER_STATS: {
-                pullLooperStats(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DISK_STATS: {
-                pullDiskStats(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DIRECTORY_USAGE: {
-                pullDirectoryUsage(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.APP_SIZE: {
-                pullAppSize(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.CATEGORY_SIZE: {
-                pullCategorySize(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.NUM_FINGERPRINTS_ENROLLED: {
-                pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FINGERPRINT, tagId,
-                        elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.NUM_FACES_ENROLLED: {
-                pullNumBiometricsEnrolled(BiometricsProtoEnums.MODALITY_FACE, tagId, elapsedNanos,
-                        wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.PROC_STATS: {
-                pullProcessStats(ProcessStats.REPORT_ALL, tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.PROC_STATS_PKG_PROC: {
-                pullProcessStats(ProcessStats.REPORT_PKG_PROC_STATS, tagId, elapsedNanos,
-                        wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DISK_IO: {
-                pullDiskIo(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.POWER_PROFILE: {
-                pullPowerProfile(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.BUILD_INFORMATION: {
-                pullBuildInformation(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.PROCESS_CPU_TIME: {
-                pullProcessCpuTime(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.CPU_TIME_PER_THREAD_FREQ: {
-                pullCpuTimePerThreadFreq(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DEVICE_CALCULATED_POWER_USE: {
-                pullDeviceCalculatedPowerUse(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DEVICE_CALCULATED_POWER_BLAME_UID: {
-                pullDeviceCalculatedPowerBlameUid(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DEVICE_CALCULATED_POWER_BLAME_OTHER: {
-                pullDeviceCalculatedPowerBlameOther(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.TEMPERATURE: {
-                pullTemperature(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.COOLING_DEVICE: {
-                pullCoolingDevices(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DEBUG_ELAPSED_CLOCK: {
-                pullDebugElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DEBUG_FAILING_ELAPSED_CLOCK: {
-                pullDebugFailingElapsedClock(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.ROLE_HOLDER: {
-                pullRoleHolders(elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.DANGEROUS_PERMISSION_STATE: {
-                pullDangerousPermissionState(elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.TIME_ZONE_DATA_INFO: {
-                pullTimeZoneDataInfo(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.EXTERNAL_STORAGE_INFO: {
-                pullExternalStorageInfo(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.APPS_ON_EXTERNAL_STORAGE_INFO: {
-                pullAppsOnExternalStorageInfo(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.FACE_SETTINGS: {
-                pullFaceSettings(tagId, elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            case StatsLog.APP_OPS: {
-                pullAppOps(elapsedNanos, wallClockNanos, ret);
-                break;
-            }
-            default:
-                Slog.w(TAG, "No such tagId data as " + tagId);
-                return null;
-        }
-        return ret.toArray(new StatsLogEventWrapper[ret.size()]);
-    }
-
-    @Override // Binder call
-    public void statsdReady() {
-        enforceCallingPermission();
-        if (DEBUG) {
-            Slog.d(TAG, "learned that statsdReady");
-        }
-        sayHiToStatsd(); // tell statsd that we're ready too and link to it
-        mContext.sendBroadcastAsUser(new Intent(StatsManager.ACTION_STATSD_STARTED)
-                        .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
-                UserHandle.SYSTEM, android.Manifest.permission.DUMP);
-    }
-
-    @Override
-    public void triggerUidSnapshot() {
-        enforceCallingPermission();
-        synchronized (sStatsdLock) {
-            final long token = Binder.clearCallingIdentity();
-            try {
-                informAllUidsLocked(mContext);
-            } catch (RemoteException e) {
-                Slog.e(TAG, "Failed to trigger uid snapshot.", e);
-            } finally {
-                restoreCallingIdentity(token);
-            }
-        }
-    }
-
-    private void enforceCallingPermission() {
-        if (Binder.getCallingPid() == Process.myPid()) {
-            return;
-        }
-        mContext.enforceCallingPermission(android.Manifest.permission.STATSCOMPANION, null);
-    }
-
-    // Lifecycle and related code
-
-    /**
-     * Fetches the statsd IBinder service
-     */
-    private static IStatsManager fetchStatsdService() {
-        return IStatsManager.Stub.asInterface(ServiceManager.getService("stats"));
-    }
-
-    public static final class Lifecycle extends SystemService {
-        private StatsCompanionService mStatsCompanionService;
-
-        public Lifecycle(Context context) {
-            super(context);
-        }
-
-        @Override
-        public void onStart() {
-            mStatsCompanionService = new StatsCompanionService(getContext());
-            try {
-                publishBinderService(Context.STATS_COMPANION_SERVICE,
-                        mStatsCompanionService);
-                if (DEBUG) Slog.d(TAG, "Published " + Context.STATS_COMPANION_SERVICE);
-            } catch (Exception e) {
-                Slog.e(TAG, "Failed to publishBinderService", e);
-            }
-        }
-
-        @Override
-        public void onBootPhase(int phase) {
-            super.onBootPhase(phase);
-            if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
-                mStatsCompanionService.systemReady();
-            }
-        }
-    }
-
-    /**
-     * Now that the android system is ready, StatsCompanion is ready too, so inform statsd.
-     */
-    private void systemReady() {
-        if (DEBUG) Slog.d(TAG, "Learned that systemReady");
-        sayHiToStatsd();
-    }
-
-    /**
-     * Tells statsd that statscompanion is ready. If the binder call returns, link to
-     * statsd.
-     */
-    private void sayHiToStatsd() {
-        synchronized (sStatsdLock) {
-            if (sStatsd != null) {
-                Slog.e(TAG, "Trying to fetch statsd, but it was already fetched",
-                        new IllegalStateException(
-                                "sStatsd is not null when being fetched"));
-                return;
-            }
-            sStatsd = fetchStatsdService();
-            if (sStatsd == null) {
-                Slog.i(TAG,
-                        "Could not yet find statsd to tell it that StatsCompanion is "
-                                + "alive.");
-                return;
-            }
-            if (DEBUG) Slog.d(TAG, "Saying hi to statsd");
-            try {
-                sStatsd.statsCompanionReady();
-                // If the statsCompanionReady two-way binder call returns, link to statsd.
-                try {
-                    sStatsd.asBinder().linkToDeath(new StatsdDeathRecipient(), 0);
-                } catch (RemoteException e) {
-                    Slog.e(TAG, "linkToDeath(StatsdDeathRecipient) failed", e);
-                    forgetEverythingLocked();
-                }
-                // Setup broadcast receiver for updates.
-                IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REPLACED);
-                filter.addAction(Intent.ACTION_PACKAGE_ADDED);
-                filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
-                filter.addDataScheme("package");
-                mContext.registerReceiverAsUser(mAppUpdateReceiver, UserHandle.ALL, filter,
-                        null,
-                        null);
-
-                // Setup receiver for user initialize (which happens once for a new user)
-                // and
-                // if a user is removed.
-                filter = new IntentFilter(Intent.ACTION_USER_INITIALIZE);
-                filter.addAction(Intent.ACTION_USER_REMOVED);
-                mContext.registerReceiverAsUser(mUserUpdateReceiver, UserHandle.ALL,
-                        filter, null, null);
-
-                // Setup receiver for device reboots or shutdowns.
-                filter = new IntentFilter(Intent.ACTION_REBOOT);
-                filter.addAction(Intent.ACTION_SHUTDOWN);
-                mContext.registerReceiverAsUser(
-                        mShutdownEventReceiver, UserHandle.ALL, filter, null, null);
-                final long token = Binder.clearCallingIdentity();
-                try {
-                    // Pull the latest state of UID->app name, version mapping when
-                    // statsd starts.
-                    informAllUidsLocked(mContext);
-                } finally {
-                    restoreCallingIdentity(token);
-                }
-                Slog.i(TAG, "Told statsd that StatsCompanionService is alive.");
-            } catch (RemoteException e) {
-                Slog.e(TAG, "Failed to inform statsd that statscompanion is ready", e);
-                forgetEverythingLocked();
-            }
-        }
-    }
-
-    private class StatsdDeathRecipient implements IBinder.DeathRecipient {
-        @Override
-        public void binderDied() {
-            Slog.i(TAG, "Statsd is dead - erase all my knowledge.");
-            synchronized (sStatsdLock) {
-                long now = SystemClock.elapsedRealtime();
-                for (Long timeMillis : mDeathTimeMillis) {
-                    long ageMillis = now - timeMillis;
-                    if (ageMillis > MILLIS_IN_A_DAY) {
-                        mDeathTimeMillis.remove(timeMillis);
-                    }
-                }
-                for (Long timeMillis : mDeletedFiles.keySet()) {
-                    long ageMillis = now - timeMillis;
-                    if (ageMillis > MILLIS_IN_A_DAY * 7) {
-                        mDeletedFiles.remove(timeMillis);
-                    }
-                }
-                mDeathTimeMillis.add(now);
-                if (mDeathTimeMillis.size() >= DEATH_THRESHOLD) {
-                    mDeathTimeMillis.clear();
-                    File[] configs = FileUtils.listFilesOrEmpty(new File(CONFIG_DIR));
-                    if (configs.length > 0) {
-                        String fileName = configs[0].getName();
-                        if (configs[0].delete()) {
-                            mDeletedFiles.put(now, fileName);
-                        }
-                    }
-                }
-                forgetEverythingLocked();
-            }
-        }
-    }
-
-    @GuardedBy("StatsCompanionService.sStatsdLock")
-    private void forgetEverythingLocked() {
-        sStatsd = null;
-        mContext.unregisterReceiver(mAppUpdateReceiver);
-        mContext.unregisterReceiver(mUserUpdateReceiver);
-        mContext.unregisterReceiver(mShutdownEventReceiver);
-        cancelAnomalyAlarm();
-        cancelPullingAlarm();
-
-        BinderCallsStatsService.Internal binderStats =
-                LocalServices.getService(BinderCallsStatsService.Internal.class);
-        if (binderStats != null) {
-            binderStats.reset();
-        }
-
-        LooperStats looperStats = LocalServices.getService(LooperStats.class);
-        if (looperStats != null) {
-            looperStats.reset();
-        }
-    }
-
-    @Override
-    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
-        if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
-
-        synchronized (sStatsdLock) {
-            writer.println(
-                    "Number of configuration files deleted: " + mDeletedFiles.size());
-            if (mDeletedFiles.size() > 0) {
-                writer.println("  timestamp, deleted file name");
-            }
-            long lastBootMillis =
-                    SystemClock.currentThreadTimeMillis() - SystemClock.elapsedRealtime();
-            for (Long elapsedMillis : mDeletedFiles.keySet()) {
-                long deletionMillis = lastBootMillis + elapsedMillis;
-                writer.println(
-                        "  " + deletionMillis + ", " + mDeletedFiles.get(elapsedMillis));
-            }
-        }
-    }
-
-    // Thermal event received from vendor thermal management subsystem
-    private static final class ThermalEventListener extends IThermalEventListener.Stub {
-        @Override
-        public void notifyThrottling(Temperature temp) {
-            StatsLog.write(StatsLog.THERMAL_THROTTLING_SEVERITY_STATE_CHANGED, temp.getType(),
-                    temp.getName(), (int) (temp.getValue() * 10), temp.getStatus());
-        }
-    }
-
-    private static final class ConnectivityStatsCallback extends
-            ConnectivityManager.NetworkCallback {
-        @Override
-        public void onAvailable(Network network) {
-            StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
-                    StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__CONNECTED);
-        }
-
-        @Override
-        public void onLost(Network network) {
-            StatsLog.write(StatsLog.CONNECTIVITY_STATE_CHANGED, network.netId,
-                    StatsLog.CONNECTIVITY_STATE_CHANGED__STATE__DISCONNECTED);
-        }
-    }
-}
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index 8897eca..3439d38 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -609,13 +609,13 @@
     }
 
     @Override
-    public void showBiometricDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
-            int type, boolean requireConfirmation, int userId, String opPackageName) {
+    public void showAuthenticationDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
+            int biometricModality, boolean requireConfirmation, int userId, String opPackageName) {
         enforceBiometricDialog();
         if (mBar != null) {
             try {
-                mBar.showBiometricDialog(bundle, receiver, type, requireConfirmation, userId,
-                        opPackageName);
+                mBar.showAuthenticationDialog(bundle, receiver, biometricModality,
+                        requireConfirmation, userId, opPackageName);
             } catch (RemoteException ex) {
             }
         }
@@ -644,22 +644,22 @@
     }
 
     @Override
-    public void onBiometricError(String error) {
+    public void onBiometricError(int errorCode, String error) {
         enforceBiometricDialog();
         if (mBar != null) {
             try {
-                mBar.onBiometricError(error);
+                mBar.onBiometricError(errorCode, error);
             } catch (RemoteException ex) {
             }
         }
     }
 
     @Override
-    public void hideBiometricDialog() {
+    public void hideAuthenticationDialog() {
         enforceBiometricDialog();
         if (mBar != null) {
             try {
-                mBar.hideBiometricDialog();
+                mBar.hideAuthenticationDialog();
             } catch (RemoteException ex) {
             }
         }
diff --git a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
index 4c93564..5493afd 100644
--- a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
+++ b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
@@ -365,10 +365,16 @@
     protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, fout)) return;
         IndentingPrintWriter pw = new IndentingPrintWriter(fout, "  ");
-        TextClassificationManager tcm = mContext.getSystemService(TextClassificationManager.class);
-        tcm.dump(pw);
 
-        pw.printPair("context", mContext); pw.println();
+        // Create a TCM instance with the system server identity. TCM creates a ContentObserver
+        // to listen for settings changes. It does not pass the checkContentProviderAccess check
+        // if we are using the shell identity, because AMS does not track of processes spawn from
+        // shell.
+        Binder.withCleanCallingIdentity(
+                () -> mContext.getSystemService(TextClassificationManager.class).dump(pw));
+
+        pw.printPair("context", mContext);
+        pw.println();
         synchronized (mLock) {
             int size = mUserStates.size();
             pw.print("Number user states: "); pw.println(size);
diff --git a/services/core/java/com/android/server/tv/TvRemoteProviderProxy.java b/services/core/java/com/android/server/tv/TvRemoteProviderProxy.java
index f8ffb7c..b7bc77d 100644
--- a/services/core/java/com/android/server/tv/TvRemoteProviderProxy.java
+++ b/services/core/java/com/android/server/tv/TvRemoteProviderProxy.java
@@ -21,8 +21,6 @@
 import android.content.Intent;
 import android.content.ServiceConnection;
 import android.media.tv.ITvRemoteProvider;
-import android.media.tv.ITvRemoteServiceInput;
-import android.os.Binder;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.os.UserHandle;
@@ -30,44 +28,33 @@
 import android.util.Slog;
 
 import java.io.PrintWriter;
-import java.lang.ref.WeakReference;
 
 /**
  * Maintains a connection to a tv remote provider service.
  */
 final class TvRemoteProviderProxy implements ServiceConnection {
-    private static final String TAG = "TvRemoteProvProxy";  // max. 23 chars
+    private static final String TAG = "TvRemoteProviderProxy";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.VERBOSE);
-    private static final boolean DEBUG_KEY = false;
 
 
     // This should match TvRemoteProvider.ACTION_TV_REMOTE_PROVIDER
     protected static final String SERVICE_INTERFACE =
             "com.android.media.tv.remoteprovider.TvRemoteProvider";
     private final Context mContext;
+    private final Object mLock;
     private final ComponentName mComponentName;
     private final int mUserId;
     private final int mUid;
 
-    /**
-     * State guarded by mLock.
-     *  This is the first lock in sequence for an incoming call.
-     *  The second lock is always {@link TvRemoteService#mLock}
-     *
-     *  There are currently no methods that break this sequence.
-     */
-    private final Object mLock = new Object();
-
-    private ProviderMethods mProviderMethods;
-    // Connection state
+    // State changes happen only in the main thread, hence no lock is needed
     private boolean mRunning;
     private boolean mBound;
-    private Connection mActiveConnection;
+    private boolean mConnected;
 
-    TvRemoteProviderProxy(Context context, ProviderMethods provider,
+    TvRemoteProviderProxy(Context context, Object lock,
                           ComponentName componentName, int userId, int uid) {
         mContext = context;
-        mProviderMethods = provider;
+        mLock = lock;
         mComponentName = componentName;
         mUserId = userId;
         mUid = uid;
@@ -78,7 +65,7 @@
         pw.println(prefix + "  mUserId=" + mUserId);
         pw.println(prefix + "  mRunning=" + mRunning);
         pw.println(prefix + "  mBound=" + mBound);
-        pw.println(prefix + "  mActiveConnection=" + mActiveConnection);
+        pw.println(prefix + "  mConnected=" + mConnected);
     }
 
     public boolean hasComponentName(String packageName, String className) {
@@ -109,11 +96,9 @@
     }
 
     public void rebindIfDisconnected() {
-        synchronized (mLock) {
-            if (mActiveConnection == null && mRunning) {
-                unbind();
-                bind();
-            }
+        if (mRunning && !mConnected) {
+            unbind();
+            bind();
         }
     }
 
@@ -129,7 +114,7 @@
                 mBound = mContext.bindServiceAsUser(service, this,
                         Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
                         new UserHandle(mUserId));
-                if (!mBound && DEBUG) {
+                if (DEBUG && !mBound) {
                     Slog.d(TAG, this + ": Bind failed");
                 }
             } catch (SecurityException ex) {
@@ -147,7 +132,6 @@
             }
 
             mBound = false;
-            disconnect();
             mContext.unbindService(this);
         }
     }
@@ -158,392 +142,27 @@
             Slog.d(TAG, this + ": onServiceConnected()");
         }
 
-        if (mBound) {
-            disconnect();
+        mConnected = true;
 
-            ITvRemoteProvider provider = ITvRemoteProvider.Stub.asInterface(service);
-            if (provider != null) {
-                Connection connection = new Connection(provider);
-                if (connection.register()) {
-                    synchronized (mLock) {
-                        mActiveConnection = connection;
-                    }
-                    if (DEBUG) {
-                        Slog.d(TAG, this + ": Connected successfully.");
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.d(TAG, this + ": Registration failed");
-                    }
-                }
-            } else {
-                Slog.e(TAG, this + ": Service returned invalid remote-control provider binder");
-            }
+        final ITvRemoteProvider provider = ITvRemoteProvider.Stub.asInterface(service);
+        if (provider == null) {
+            Slog.e(TAG, this + ": Invalid binder");
+            return;
+        }
+
+        try {
+            provider.setRemoteServiceInputSink(new TvRemoteServiceInput(mLock, provider));
+        } catch (RemoteException e) {
+            Slog.e(TAG, this + ": Failed remote call to setRemoteServiceInputSink");
         }
     }
 
     @Override
     public void onServiceDisconnected(ComponentName name) {
-        if (DEBUG) Slog.d(TAG, this + ": Service disconnected");
-        disconnect();
-    }
+        mConnected = false;
 
-    private void disconnect() {
-        synchronized (mLock) {
-            if (mActiveConnection != null) {
-                mActiveConnection.dispose();
-                mActiveConnection = null;
-            }
-        }
-    }
-
-    interface ProviderMethods {
-        // InputBridge
-        boolean openInputBridge(TvRemoteProviderProxy provider, IBinder token, String name,
-                                int width, int height, int maxPointers);
-
-        void closeInputBridge(TvRemoteProviderProxy provider, IBinder token);
-
-        void clearInputBridge(TvRemoteProviderProxy provider, IBinder token);
-
-        void sendKeyDown(TvRemoteProviderProxy provider, IBinder token, int keyCode);
-
-        void sendKeyUp(TvRemoteProviderProxy provider, IBinder token, int keyCode);
-
-        void sendPointerDown(TvRemoteProviderProxy provider, IBinder token, int pointerId, int x,
-                             int y);
-
-        void sendPointerUp(TvRemoteProviderProxy provider, IBinder token, int pointerId);
-
-        void sendPointerSync(TvRemoteProviderProxy provider, IBinder token);
-    }
-
-    private final class Connection {
-        private final ITvRemoteProvider mTvRemoteProvider;
-        private final RemoteServiceInputProvider mServiceInputProvider;
-
-        public Connection(ITvRemoteProvider provider) {
-            mTvRemoteProvider = provider;
-            mServiceInputProvider = new RemoteServiceInputProvider(this);
-        }
-
-        public boolean register() {
-            if (DEBUG) Slog.d(TAG, "Connection::register()");
-            try {
-                mTvRemoteProvider.setRemoteServiceInputSink(mServiceInputProvider);
-                return true;
-            } catch (RemoteException ex) {
-                dispose();
-                return false;
-            }
-        }
-
-        public void dispose() {
-            if (DEBUG) Slog.d(TAG, "Connection::dispose()");
-            mServiceInputProvider.dispose();
-        }
-
-
-        public void onInputBridgeConnected(IBinder token) {
-            if (DEBUG) Slog.d(TAG, this + ": onInputBridgeConnected");
-            try {
-                mTvRemoteProvider.onInputBridgeConnected(token);
-            } catch (RemoteException ex) {
-                Slog.e(TAG, "Failed to deliver onInputBridgeConnected. ", ex);
-            }
-        }
-
-        void openInputBridge(final IBinder token, final String name, final int width,
-                             final int height, final int maxPointers) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG) {
-                        Slog.d(TAG, this + ": openInputBridge," +
-                                " token=" + token + ", name=" + name);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        if (mProviderMethods.openInputBridge(TvRemoteProviderProxy.this, token,
-                                                             name, width, height, maxPointers)) {
-                            onInputBridgeConnected(token);
-                        }
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "openInputBridge, Invalid connection or incorrect uid: " + Binder
-                                        .getCallingUid());
-                    }
-                }
-            }
-        }
-
-        void closeInputBridge(final IBinder token) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG) {
-                        Slog.d(TAG, this + ": closeInputBridge," +
-                                " token=" + token);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        mProviderMethods.closeInputBridge(TvRemoteProviderProxy.this, token);
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "closeInputBridge, Invalid connection or incorrect uid: " +
-                                        Binder.getCallingUid());
-                    }
-                }
-            }
-        }
-
-        void clearInputBridge(final IBinder token) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG) {
-                        Slog.d(TAG, this + ": clearInputBridge," +
-                                " token=" + token);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        mProviderMethods.clearInputBridge(TvRemoteProviderProxy.this, token);
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "clearInputBridge, Invalid connection or incorrect uid: " +
-                                        Binder.getCallingUid());
-                    }
-                }
-            }
-        }
-
-        void sendTimestamp(final IBinder token, final long timestamp) {
-            if (DEBUG) {
-                Slog.e(TAG, "sendTimestamp is deprecated, please remove all usages of this API.");
-            }
-        }
-
-        void sendKeyDown(final IBinder token, final int keyCode) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG_KEY) {
-                        Slog.d(TAG, this + ": sendKeyDown," +
-                                " token=" + token + ", keyCode=" + keyCode);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        mProviderMethods.sendKeyDown(TvRemoteProviderProxy.this, token, keyCode);
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "sendKeyDown, Invalid connection or incorrect uid: " + Binder
-                                        .getCallingUid());
-                    }
-                }
-            }
-        }
-
-        void sendKeyUp(final IBinder token, final int keyCode) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG_KEY) {
-                        Slog.d(TAG, this + ": sendKeyUp," +
-                                " token=" + token + ", keyCode=" + keyCode);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        mProviderMethods.sendKeyUp(TvRemoteProviderProxy.this, token, keyCode);
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "sendKeyUp, Invalid connection or incorrect uid: " + Binder
-                                        .getCallingUid());
-                    }
-                }
-            }
-        }
-
-        void sendPointerDown(final IBinder token, final int pointerId, final int x, final int y) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG_KEY) {
-                        Slog.d(TAG, this + ": sendPointerDown," +
-                                " token=" + token + ", pointerId=" + pointerId);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        mProviderMethods.sendPointerDown(TvRemoteProviderProxy.this, token,
-                                pointerId, x, y);
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "sendPointerDown, Invalid connection or incorrect uid: " + Binder
-                                        .getCallingUid());
-                    }
-                }
-            }
-        }
-
-        void sendPointerUp(final IBinder token, final int pointerId) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG_KEY) {
-                        Slog.d(TAG, this + ": sendPointerUp," +
-                                " token=" + token + ", pointerId=" + pointerId);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        mProviderMethods.sendPointerUp(TvRemoteProviderProxy.this, token,
-                                pointerId);
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "sendPointerUp, Invalid connection or incorrect uid: " + Binder
-                                        .getCallingUid());
-                    }
-                }
-            }
-        }
-
-        void sendPointerSync(final IBinder token) {
-            synchronized (mLock) {
-                if (mActiveConnection == this && Binder.getCallingUid() == mUid) {
-                    if (DEBUG_KEY) {
-                        Slog.d(TAG, this + ": sendPointerSync," +
-                                " token=" + token);
-                    }
-                    final long idToken = Binder.clearCallingIdentity();
-                    try {
-                        if (mProviderMethods != null) {
-                            mProviderMethods.sendPointerSync(TvRemoteProviderProxy.this, token);
-                        }
-                    } finally {
-                        Binder.restoreCallingIdentity(idToken);
-                    }
-                } else {
-                    if (DEBUG) {
-                        Slog.w(TAG,
-                                "sendPointerSync, Invalid connection or incorrect uid: " + Binder
-                                        .getCallingUid());
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * Receives events from the connected provider.
-     * <p>
-     * This inner class is static and only retains a weak reference to the connection
-     * to prevent the client from being leaked in case the service is holding an
-     * active reference to the client's callback.
-     * </p>
-     */
-    private static final class RemoteServiceInputProvider extends ITvRemoteServiceInput.Stub {
-        private final WeakReference<Connection> mConnectionRef;
-
-        public RemoteServiceInputProvider(Connection connection) {
-            mConnectionRef = new WeakReference<Connection>(connection);
-        }
-
-        public void dispose() {
-            // Terminate the connection.
-            mConnectionRef.clear();
-        }
-
-        @Override
-        public void openInputBridge(IBinder token, String name, int width,
-                                    int height, int maxPointers) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.openInputBridge(token, name, width, height, maxPointers);
-            }
-        }
-
-        @Override
-        public void closeInputBridge(IBinder token) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.closeInputBridge(token);
-            }
-        }
-
-        @Override
-        public void clearInputBridge(IBinder token) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.clearInputBridge(token);
-            }
-        }
-
-        @Override
-        public void sendTimestamp(IBinder token, long timestamp) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.sendTimestamp(token, timestamp);
-            }
-        }
-
-        @Override
-        public void sendKeyDown(IBinder token, int keyCode) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.sendKeyDown(token, keyCode);
-            }
-        }
-
-        @Override
-        public void sendKeyUp(IBinder token, int keyCode) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.sendKeyUp(token, keyCode);
-            }
-        }
-
-        @Override
-        public void sendPointerDown(IBinder token, int pointerId, int x, int y)
-                throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.sendPointerDown(token, pointerId, x, y);
-            }
-        }
-
-        @Override
-        public void sendPointerUp(IBinder token, int pointerId) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.sendPointerUp(token, pointerId);
-            }
-        }
-
-        @Override
-        public void sendPointerSync(IBinder token) throws RemoteException {
-            Connection connection = mConnectionRef.get();
-            if (connection != null) {
-                connection.sendPointerSync(token);
-            }
+        if (DEBUG) {
+            Slog.d(TAG, this + ": onServiceDisconnected()");
         }
     }
 }
diff --git a/services/core/java/com/android/server/tv/TvRemoteProviderWatcher.java b/services/core/java/com/android/server/tv/TvRemoteProviderWatcher.java
index 0d29edd..cddcabe 100644
--- a/services/core/java/com/android/server/tv/TvRemoteProviderWatcher.java
+++ b/services/core/java/com/android/server/tv/TvRemoteProviderWatcher.java
@@ -41,27 +41,27 @@
  */
 final class TvRemoteProviderWatcher {
 
-    private static final String TAG = "TvRemoteProvWatcher";  // max. 23 chars
+    private static final String TAG = "TvRemoteProviderWatcher";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.VERBOSE);
 
     private final Context mContext;
-    private final TvRemoteProviderProxy.ProviderMethods mProvider;
     private final Handler mHandler;
     private final PackageManager mPackageManager;
     private final ArrayList<TvRemoteProviderProxy> mProviderProxies = new ArrayList<>();
     private final int mUserId;
     private final String mUnbundledServicePackage;
+    private final Object mLock;
 
     private boolean mRunning;
 
-    TvRemoteProviderWatcher(Context context, TvRemoteProviderProxy.ProviderMethods provider) {
+    TvRemoteProviderWatcher(Context context, Object lock) {
         mContext = context;
-        mProvider = provider;
         mHandler = new Handler(true);
         mUserId = UserHandle.myUserId();
         mPackageManager = context.getPackageManager();
         mUnbundledServicePackage = context.getString(
                 com.android.internal.R.string.config_tvRemoteServicePackage);
+        mLock = lock;
     }
 
     public void start() {
@@ -116,7 +116,7 @@
                 int sourceIndex = findProvider(serviceInfo.packageName, serviceInfo.name);
                 if (sourceIndex < 0) {
                     TvRemoteProviderProxy providerProxy =
-                            new TvRemoteProviderProxy(mContext, mProvider,
+                            new TvRemoteProviderProxy(mContext, mLock,
                                     new ComponentName(serviceInfo.packageName, serviceInfo.name),
                                     mUserId, serviceInfo.applicationInfo.uid);
                     providerProxy.start();
diff --git a/services/core/java/com/android/server/tv/TvRemoteService.java b/services/core/java/com/android/server/tv/TvRemoteService.java
index bee6fb3..5894645 100644
--- a/services/core/java/com/android/server/tv/TvRemoteService.java
+++ b/services/core/java/com/android/server/tv/TvRemoteService.java
@@ -17,17 +17,11 @@
 package com.android.server.tv;
 
 import android.content.Context;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.ArrayMap;
 import android.util.Slog;
 
 import com.android.server.SystemService;
 import com.android.server.Watchdog;
 
-import java.io.IOException;
-import java.util.Map;
-
 /**
  * TvRemoteService represents a system service that allows a connected
  * remote control (emote) service to inject white-listed input events
@@ -38,27 +32,17 @@
 public class TvRemoteService extends SystemService implements Watchdog.Monitor {
     private static final String TAG = "TvRemoteService";
     private static final boolean DEBUG = false;
-    private static final boolean DEBUG_KEYS = false;
-
-    private final TvRemoteProviderWatcher mWatcher;
-    private Map<IBinder, UinputBridge> mBridgeMap = new ArrayMap();
 
     /**
-     * State guarded by mLock.
-     *  This is the second lock in sequence for an incoming call.
-     *  The first lock is always {@link TvRemoteProviderProxy#mLock}
-     *
-     *  There are currently no methods that break this sequence.
-     *  Special note:
-     *  Outgoing call informInputBridgeConnected(), which is called from
-     *  openInputBridgeInternalLocked() uses a handler thereby relinquishing held locks.
+     * All actions on input bridges are serialized using mLock.
+     * This is necessary because {@link UInputBridge} is not thread-safe.
      */
     private final Object mLock = new Object();
+    private final TvRemoteProviderWatcher mWatcher;
 
     public TvRemoteService(Context context) {
         super(context);
-        mWatcher = new TvRemoteProviderWatcher(context,
-                                               new UserProvider(TvRemoteService.this));
+        mWatcher = new TvRemoteProviderWatcher(context, mLock);
         Watchdog.getInstance().addMonitor(this);
     }
 
@@ -81,214 +65,4 @@
             mWatcher.start(); // Also schedules the start of all providers.
         }
     }
-
-    private boolean openInputBridgeInternalLocked(final IBinder token,
-                                                  String name, int width, int height,
-                                                  int maxPointers) {
-        if (DEBUG) {
-            Slog.d(TAG, "openInputBridgeInternalLocked(), token: " + token + ", name: " + name +
-                    ", width: " + width + ", height: " + height + ", maxPointers: " + maxPointers);
-        }
-
-        try {
-            //Create a new bridge, if one does not exist already
-            if (mBridgeMap.containsKey(token)) {
-                if (DEBUG) Slog.d(TAG, "RemoteBridge already exists");
-                return true;
-            }
-
-            UinputBridge inputBridge = new UinputBridge(token, name, width, height, maxPointers);
-            mBridgeMap.put(token, inputBridge);
-
-            try {
-                token.linkToDeath(new IBinder.DeathRecipient() {
-                    @Override
-                    public void binderDied() {
-                        synchronized (mLock) {
-                            closeInputBridgeInternalLocked(token);
-                        }
-                    }
-                }, 0);
-            } catch (RemoteException e) {
-                if (DEBUG) Slog.d(TAG, "Token is already dead");
-                closeInputBridgeInternalLocked(token);
-                return false;
-            }
-        } catch (IOException ioe) {
-            Slog.e(TAG, "Cannot create device for " + name);
-            return false;
-        }
-        return true;
-    }
-
-    private void closeInputBridgeInternalLocked(IBinder token) {
-        if (DEBUG) {
-            Slog.d(TAG, "closeInputBridgeInternalLocked(), token: " + token);
-        }
-
-        // Close an existing RemoteBridge
-        UinputBridge inputBridge = mBridgeMap.get(token);
-        if (inputBridge != null) {
-            inputBridge.close(token);
-        }
-
-        mBridgeMap.remove(token);
-    }
-
-    private void clearInputBridgeInternalLocked(IBinder token) {
-        if (DEBUG) {
-            Slog.d(TAG, "clearInputBridgeInternalLocked(), token: " + token);
-        }
-
-        UinputBridge inputBridge = mBridgeMap.get(token);
-        if (inputBridge != null) {
-            inputBridge.clear(token);
-        }
-    }
-
-    private void sendKeyDownInternalLocked(IBinder token, int keyCode) {
-        if (DEBUG_KEYS) {
-            Slog.d(TAG, "sendKeyDownInternalLocked(), token: " + token + ", keyCode: " + keyCode);
-        }
-
-        UinputBridge inputBridge = mBridgeMap.get(token);
-        if (inputBridge != null) {
-            inputBridge.sendKeyDown(token, keyCode);
-        }
-    }
-
-    private void sendKeyUpInternalLocked(IBinder token, int keyCode) {
-        if (DEBUG_KEYS) {
-            Slog.d(TAG, "sendKeyUpInternalLocked(), token: " + token + ", keyCode: " + keyCode);
-        }
-
-        UinputBridge inputBridge = mBridgeMap.get(token);
-        if (inputBridge != null) {
-            inputBridge.sendKeyUp(token, keyCode);
-        }
-    }
-
-    private void sendPointerDownInternalLocked(IBinder token, int pointerId, int x, int y) {
-        if (DEBUG_KEYS) {
-            Slog.d(TAG, "sendPointerDownInternalLocked(), token: " + token + ", pointerId: " +
-                    pointerId + ", x: " + x + ", y: " + y);
-        }
-
-        UinputBridge inputBridge = mBridgeMap.get(token);
-        if (inputBridge != null) {
-            inputBridge.sendPointerDown(token, pointerId, x, y);
-        }
-    }
-
-    private void sendPointerUpInternalLocked(IBinder token, int pointerId) {
-        if (DEBUG_KEYS) {
-            Slog.d(TAG, "sendPointerUpInternalLocked(), token: " + token + ", pointerId: " +
-                    pointerId);
-        }
-
-        UinputBridge inputBridge = mBridgeMap.get(token);
-        if (inputBridge != null) {
-            inputBridge.sendPointerUp(token, pointerId);
-        }
-    }
-
-    private void sendPointerSyncInternalLocked(IBinder token) {
-        if (DEBUG_KEYS) {
-            Slog.d(TAG, "sendPointerSyncInternalLocked(), token: " + token);
-        }
-
-        UinputBridge inputBridge = mBridgeMap.get(token);
-        if (inputBridge != null) {
-            inputBridge.sendPointerSync(token);
-        }
-    }
-
-    private final class UserProvider implements TvRemoteProviderProxy.ProviderMethods {
-
-        private final TvRemoteService mService;
-
-        public UserProvider(TvRemoteService service) {
-            mService = service;
-        }
-
-        @Override
-        public boolean openInputBridge(TvRemoteProviderProxy provider, IBinder token, String name,
-                                       int width, int height, int maxPointers) {
-            if (DEBUG) {
-                Slog.d(TAG, "openInputBridge(), token: " + token +
-                        ", name: " + name + ", width: " + width +
-                        ", height: " + height + ", maxPointers: " + maxPointers);
-            }
-
-            synchronized (mLock) {
-                return mService.openInputBridgeInternalLocked(token, name, width,
-                               height, maxPointers);
-            }
-        }
-
-        @Override
-        public void closeInputBridge(TvRemoteProviderProxy provider, IBinder token) {
-            if (DEBUG) Slog.d(TAG, "closeInputBridge(), token: " + token);
-            synchronized (mLock) {
-                    mService.closeInputBridgeInternalLocked(token);
-            }
-        }
-
-        @Override
-        public void clearInputBridge(TvRemoteProviderProxy provider, IBinder token) {
-            if (DEBUG) Slog.d(TAG, "clearInputBridge(), token: " + token);
-            synchronized (mLock) {
-                    mService.clearInputBridgeInternalLocked(token);
-            }
-        }
-
-        @Override
-        public void sendKeyDown(TvRemoteProviderProxy provider, IBinder token, int keyCode) {
-            if (DEBUG_KEYS) {
-                Slog.d(TAG, "sendKeyDown(), token: " + token + ", keyCode: " + keyCode);
-            }
-            synchronized (mLock) {
-                    mService.sendKeyDownInternalLocked(token, keyCode);
-            }
-        }
-
-        @Override
-        public void sendKeyUp(TvRemoteProviderProxy provider, IBinder token, int keyCode) {
-            if (DEBUG_KEYS) {
-                Slog.d(TAG, "sendKeyUp(), token: " + token + ", keyCode: " + keyCode);
-            }
-            synchronized (mLock) {
-                    mService.sendKeyUpInternalLocked(token, keyCode);
-            }
-        }
-
-        @Override
-        public void sendPointerDown(TvRemoteProviderProxy provider, IBinder token, int pointerId,
-                                    int x, int y) {
-            if (DEBUG_KEYS) {
-                Slog.d(TAG, "sendPointerDown(), token: " + token + ", pointerId: " + pointerId);
-            }
-            synchronized (mLock) {
-                    mService.sendPointerDownInternalLocked(token, pointerId, x, y);
-            }
-        }
-
-        @Override
-        public void sendPointerUp(TvRemoteProviderProxy provider, IBinder token, int pointerId) {
-            if (DEBUG_KEYS) {
-                Slog.d(TAG, "sendPointerUp(), token: " + token + ", pointerId: " + pointerId);
-            }
-            synchronized (mLock) {
-                    mService.sendPointerUpInternalLocked(token, pointerId);
-            }
-        }
-
-        @Override
-        public void sendPointerSync(TvRemoteProviderProxy provider, IBinder token) {
-            if (DEBUG_KEYS) Slog.d(TAG, "sendPointerSync(), token: " + token);
-            synchronized (mLock) {
-                    mService.sendPointerSyncInternalLocked(token);
-            }
-        }
-    }
 }
diff --git a/services/core/java/com/android/server/tv/TvRemoteServiceInput.java b/services/core/java/com/android/server/tv/TvRemoteServiceInput.java
new file mode 100644
index 0000000..8fe6da5
--- /dev/null
+++ b/services/core/java/com/android/server/tv/TvRemoteServiceInput.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2019 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.tv;
+
+import android.media.tv.ITvRemoteProvider;
+import android.media.tv.ITvRemoteServiceInput;
+import android.os.Binder;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.util.ArrayMap;
+import android.util.Slog;
+
+import java.io.IOException;
+import java.util.Map;
+
+final class TvRemoteServiceInput extends ITvRemoteServiceInput.Stub {
+    private static final String TAG = "TvRemoteServiceInput";
+    private static final boolean DEBUG = false;
+    private static final boolean DEBUG_KEYS = false;
+
+    private final Map<IBinder, UinputBridge> mBridgeMap;
+    private final Object mLock;
+    private final ITvRemoteProvider mProvider;
+
+    TvRemoteServiceInput(Object lock, ITvRemoteProvider provider) {
+        mBridgeMap = new ArrayMap();
+        mLock = lock;
+        mProvider = provider;
+    }
+
+    @Override
+    public void openInputBridge(IBinder token, String name, int width,
+                                int height, int maxPointers) {
+        if (DEBUG) {
+            Slog.d(TAG, "openInputBridge(), token: " + token
+                    + ", name: " + name + ", width: " + width
+                    + ", height: " + height + ", maxPointers: " + maxPointers);
+        }
+
+        synchronized (mLock) {
+            if (mBridgeMap.containsKey(token)) {
+                if (DEBUG) {
+                    Slog.d(TAG, "InputBridge already exists");
+                }
+            } else {
+                final long idToken = Binder.clearCallingIdentity();
+                try {
+                    mBridgeMap.put(token,
+                                   new UinputBridge(token, name, width, height, maxPointers));
+                    token.linkToDeath(new IBinder.DeathRecipient() {
+                        @Override
+                        public void binderDied() {
+                            closeInputBridge(token);
+                        }
+                    }, 0);
+                } catch (IOException e) {
+                    Slog.e(TAG, "Cannot create device for " + name);
+                    return;
+                } catch (RemoteException e) {
+                    Slog.e(TAG, "Token is already dead");
+                    closeInputBridge(token);
+                    return;
+                } finally {
+                    Binder.restoreCallingIdentity(idToken);
+                }
+            }
+        }
+
+        try {
+            mProvider.onInputBridgeConnected(token);
+        } catch (RemoteException e) {
+            Slog.e(TAG, "Failed remote call to onInputBridgeConnected");
+        }
+    }
+
+    @Override
+    public void closeInputBridge(IBinder token) {
+        if (DEBUG) {
+            Slog.d(TAG, "closeInputBridge(), token: " + token);
+        }
+
+        synchronized (mLock) {
+            UinputBridge inputBridge = mBridgeMap.remove(token);
+            if (inputBridge == null) {
+                return;
+            }
+
+            final long idToken = Binder.clearCallingIdentity();
+            try {
+                inputBridge.close(token);
+            } finally {
+                Binder.restoreCallingIdentity(idToken);
+            }
+        }
+    }
+
+    @Override
+    public void clearInputBridge(IBinder token) {
+        if (DEBUG) {
+            Slog.d(TAG, "clearInputBridge, token: " + token);
+        }
+
+        synchronized (mLock) {
+            UinputBridge inputBridge = mBridgeMap.get(token);
+            if (inputBridge == null) {
+                return;
+            }
+
+            final long idToken = Binder.clearCallingIdentity();
+            try {
+                inputBridge.clear(token);
+            } finally {
+                Binder.restoreCallingIdentity(idToken);
+            }
+        }
+    }
+
+    @Override
+    public void sendTimestamp(IBinder token, long timestamp) {
+        if (DEBUG) {
+            Slog.e(TAG, "sendTimestamp is deprecated, please remove all usages of this API.");
+        }
+    }
+
+    @Override
+    public void sendKeyDown(IBinder token, int keyCode) {
+        if (DEBUG_KEYS) {
+            Slog.d(TAG, "sendKeyDown(), token: " + token + ", keyCode: " + keyCode);
+        }
+
+        synchronized (mLock) {
+            UinputBridge inputBridge = mBridgeMap.get(token);
+            if (inputBridge == null) {
+                return;
+            }
+
+            final long idToken = Binder.clearCallingIdentity();
+            try {
+                inputBridge.sendKeyDown(token, keyCode);
+            } finally {
+                Binder.restoreCallingIdentity(idToken);
+            }
+        }
+    }
+
+    @Override
+    public void sendKeyUp(IBinder token, int keyCode) {
+        if (DEBUG_KEYS) {
+            Slog.d(TAG, "sendKeyUp(), token: " + token + ", keyCode: " + keyCode);
+        }
+
+        synchronized (mLock) {
+            UinputBridge inputBridge = mBridgeMap.get(token);
+            if (inputBridge == null) {
+                return;
+            }
+
+            final long idToken = Binder.clearCallingIdentity();
+            try {
+                inputBridge.sendKeyUp(token, keyCode);
+            } finally {
+                Binder.restoreCallingIdentity(idToken);
+            }
+        }
+    }
+
+    @Override
+    public void sendPointerDown(IBinder token, int pointerId, int x, int y) {
+        if (DEBUG_KEYS) {
+            Slog.d(TAG, "sendPointerDown(), token: " + token + ", pointerId: "
+                    + pointerId + ", x: " + x + ", y: " + y);
+        }
+
+        synchronized (mLock) {
+            UinputBridge inputBridge = mBridgeMap.get(token);
+            if (inputBridge == null) {
+                return;
+            }
+
+            final long idToken = Binder.clearCallingIdentity();
+            try {
+                inputBridge.sendPointerDown(token, pointerId, x, y);
+            } finally {
+                Binder.restoreCallingIdentity(idToken);
+            }
+        }
+    }
+
+    @Override
+    public void sendPointerUp(IBinder token, int pointerId) {
+        if (DEBUG_KEYS) {
+            Slog.d(TAG, "sendPointerUp(), token: " + token + ", pointerId: " + pointerId);
+        }
+
+        synchronized (mLock) {
+            UinputBridge inputBridge = mBridgeMap.get(token);
+            if (inputBridge == null) {
+                return;
+            }
+
+            final long idToken = Binder.clearCallingIdentity();
+            try {
+                inputBridge.sendPointerUp(token, pointerId);
+            } finally {
+                Binder.restoreCallingIdentity(idToken);
+            }
+        }
+    }
+
+    @Override
+    public void sendPointerSync(IBinder token) {
+        if (DEBUG_KEYS) {
+            Slog.d(TAG, "sendPointerSync(), token: " + token);
+        }
+
+        synchronized (mLock) {
+            UinputBridge inputBridge = mBridgeMap.get(token);
+            if (inputBridge == null) {
+                return;
+            }
+
+            final long idToken = Binder.clearCallingIdentity();
+            try {
+                inputBridge.sendPointerSync(token);
+            } finally {
+                Binder.restoreCallingIdentity(idToken);
+            }
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/utils/TraceBuffer.java b/services/core/java/com/android/server/utils/TraceBuffer.java
new file mode 100644
index 0000000..0567960
--- /dev/null
+++ b/services/core/java/com/android/server/utils/TraceBuffer.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2019 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.utils;
+
+import android.util.proto.ProtoOutputStream;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Queue;
+
+/**
+ * Buffer used for tracing and logging.
+ */
+public class TraceBuffer {
+    private final Object mBufferLock = new Object();
+
+    private final Queue<ProtoOutputStream> mBuffer = new ArrayDeque<>();
+    private int mBufferUsedSize;
+    private int mBufferCapacity;
+
+    public TraceBuffer(int bufferCapacity) {
+        mBufferCapacity = bufferCapacity;
+        resetBuffer();
+    }
+
+    public int getAvailableSpace() {
+        return mBufferCapacity - mBufferUsedSize;
+    }
+
+    /**
+     * Returns buffer size.
+     */
+    public int size() {
+        return mBuffer.size();
+    }
+
+    public void setCapacity(int capacity) {
+        mBufferCapacity = capacity;
+    }
+
+    /**
+     * Inserts the specified element into this buffer.
+     *
+     * @param proto the element to add
+     * @throws IllegalStateException if the element cannot be added because it is larger
+     *                               than the buffer size.
+     */
+    public void add(ProtoOutputStream proto) {
+        int protoLength = proto.getRawSize();
+        if (protoLength > mBufferCapacity) {
+            throw new IllegalStateException("Trace object too large for the buffer. Buffer size:"
+                    + mBufferCapacity + " Object size: " + protoLength);
+        }
+        synchronized (mBufferLock) {
+            discardOldest(protoLength);
+            mBuffer.add(proto);
+            mBufferUsedSize += protoLength;
+            mBufferLock.notify();
+        }
+    }
+
+    boolean contains(byte[] other) {
+        return mBuffer.stream()
+                .anyMatch(p -> Arrays.equals(p.getBytes(), other));
+    }
+
+    /**
+     * Writes the trace buffer to disk inside the encapsulatingProto..
+     */
+    public void writeTraceToFile(File traceFile, ProtoOutputStream encapsulatingProto)
+            throws IOException {
+        synchronized (mBufferLock) {
+            traceFile.delete();
+            try (OutputStream os = new FileOutputStream(traceFile)) {
+                traceFile.setReadable(true /* readable */, false /* ownerOnly */);
+                os.write(encapsulatingProto.getBytes());
+                for (ProtoOutputStream protoOutputStream : mBuffer) {
+                    encapsulatingProto = protoOutputStream;
+                    byte[] protoBytes = encapsulatingProto.getBytes();
+                    os.write(protoBytes);
+                }
+                os.flush();
+            }
+        }
+    }
+
+    /**
+     * Checks if the element can be added to the buffer. The element is already certain to be
+     * smaller than the overall buffer size.
+     *
+     * @param protoLength byte array representation of the Proto object to add
+     */
+    private void discardOldest(int protoLength) {
+        long availableSpace = getAvailableSpace();
+
+        while (availableSpace < protoLength) {
+
+            ProtoOutputStream item = mBuffer.poll();
+            if (item == null) {
+                throw new IllegalStateException("No element to discard from buffer");
+            }
+            mBufferUsedSize -= item.getRawSize();
+            availableSpace = getAvailableSpace();
+        }
+    }
+
+    /**
+     * Removes all elements form the buffer
+     */
+    public void resetBuffer() {
+        synchronized (mBufferLock) {
+            mBuffer.clear();
+            mBufferUsedSize = 0;
+        }
+    }
+
+    @VisibleForTesting
+    int getBufferSize() {
+        return mBufferUsedSize;
+    }
+
+    /**
+     * Returns the buffer status in human-readable form.
+     */
+    public String getStatus() {
+        synchronized (mBufferLock) {
+            return "Buffer size: "
+                    + mBufferCapacity
+                    + " bytes"
+                    + "\n"
+                    + "Buffer usage: "
+                    + mBufferUsedSize
+                    + " bytes"
+                    + "\n"
+                    + "Elements in the buffer: "
+                    + mBuffer.size();
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index 59f051b..10415f5 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -271,11 +271,11 @@
         }
     }
 
-    /** NOTE: This has to be called within a surface transaction. */
-    public void drawMagnifiedRegionBorderIfNeededLocked(int displayId) {
+    public void drawMagnifiedRegionBorderIfNeededLocked(int displayId,
+            SurfaceControl.Transaction t) {
         final DisplayMagnifier displayMagnifier = mDisplayMagnifiers.get(displayId);
         if (displayMagnifier != null) {
-            displayMagnifier.drawMagnifiedRegionBorderIfNeededLocked();
+            displayMagnifier.drawMagnifiedRegionBorderIfNeededLocked(t);
         }
         // Not relevant for the window observer.
     }
@@ -431,7 +431,7 @@
                 Slog.i(LOG_TAG, "Rotation: " + Surface.rotationToString(rotation)
                         + " displayId: " + displayContent.getDisplayId());
             }
-            mMagnifedViewport.onRotationChangedLocked();
+            mMagnifedViewport.onRotationChangedLocked(displayContent.getPendingTransaction());
             mHandler.sendEmptyMessage(MyHandler.MESSAGE_NOTIFY_ROTATION_CHANGED);
         }
 
@@ -536,9 +536,8 @@
                     .sendToTarget();
         }
 
-        /** NOTE: This has to be called within a surface transaction. */
-        public void drawMagnifiedRegionBorderIfNeededLocked() {
-            mMagnifedViewport.drawWindowIfNeededLocked();
+        public void drawMagnifiedRegionBorderIfNeededLocked(SurfaceControl.Transaction t) {
+            mMagnifedViewport.drawWindowIfNeededLocked(t);
         }
 
         private final class MagnifiedViewport {
@@ -744,7 +743,7 @@
                 return letterboxBounds;
             }
 
-            public void onRotationChangedLocked() {
+            public void onRotationChangedLocked(SurfaceControl.Transaction t) {
                 // If we are showing the magnification border, hide it immediately so
                 // the user does not see strange artifacts during rotation. The screenshot
                 // used for rotation already has the border. After the rotation is complete
@@ -758,7 +757,7 @@
                     mHandler.sendMessageDelayed(message, delay);
                 }
                 recomputeBoundsLocked();
-                mWindow.updateSize();
+                mWindow.updateSize(t);
             }
 
             public void setMagnifiedRegionBorderShownLocked(boolean shown, boolean animate) {
@@ -784,10 +783,9 @@
                 return mMagnificationSpec;
             }
 
-            /** NOTE: This has to be called within a surface transaction. */
-            public void drawWindowIfNeededLocked() {
+            public void drawWindowIfNeededLocked(SurfaceControl.Transaction t) {
                 recomputeBoundsLocked();
-                mWindow.drawIfNeeded();
+                mWindow.drawIfNeeded(t);
             }
 
             public void destroyWindow() {
@@ -837,10 +835,11 @@
                         /* ignore */
                     }
                     mSurfaceControl = surfaceControl;
-                    mSurfaceControl.setLayer(mService.mPolicy.getWindowLayerFromTypeLw(
-                            TYPE_MAGNIFICATION_OVERLAY)
-                            * WindowManagerService.TYPE_LAYER_MULTIPLIER);
-                    mSurfaceControl.setPosition(0, 0);
+                    mService.mTransactionFactory.get().setLayer(mSurfaceControl,
+                            mService.mPolicy.getWindowLayerFromTypeLw(TYPE_MAGNIFICATION_OVERLAY)
+                                    * WindowManagerService.TYPE_LAYER_MULTIPLIER)
+                            .setPosition(mSurfaceControl, 0, 0)
+                            .apply();
                     mSurface.copyFrom(mSurfaceControl);
 
                     mAnimationController = new AnimationController(context,
@@ -905,10 +904,10 @@
                     }
                 }
 
-                public void updateSize() {
+                public void updateSize(SurfaceControl.Transaction t) {
                     synchronized (mService.mGlobalLock) {
                         mWindowManager.getDefaultDisplay().getRealSize(mTempPoint);
-                        mSurfaceControl.setBufferSize(mTempPoint.x, mTempPoint.y);
+                        t.setBufferSize(mSurfaceControl, mTempPoint.x, mTempPoint.y);
                         invalidate(mDirtyRect);
                     }
                 }
@@ -923,8 +922,7 @@
                     mService.scheduleAnimationLocked();
                 }
 
-                /** NOTE: This has to be called within a surface transaction. */
-                public void drawIfNeeded() {
+                public void drawIfNeeded(SurfaceControl.Transaction t) {
                     synchronized (mService.mGlobalLock) {
                         if (!mInvalidated) {
                             return;
@@ -959,9 +957,9 @@
                             canvas.drawPath(path, mPaint);
 
                             mSurface.unlockCanvasAndPost(canvas);
-                            mSurfaceControl.show();
+                            t.show(mSurfaceControl);
                         } else {
-                            mSurfaceControl.hide();
+                            t.hide(mSurfaceControl);
                         }
                     }
                 }
diff --git a/services/core/java/com/android/server/wm/ActivityDisplay.java b/services/core/java/com/android/server/wm/ActivityDisplay.java
index e488cc9..9d9a37c 100644
--- a/services/core/java/com/android/server/wm/ActivityDisplay.java
+++ b/services/core/java/com/android/server/wm/ActivityDisplay.java
@@ -50,9 +50,9 @@
 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 static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
 import static com.android.server.wm.RootActivityContainer.FindTaskResult;
 import static com.android.server.wm.RootActivityContainer.TAG_STATES;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL;
 
@@ -76,6 +76,7 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.am.EventLogTags;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -84,8 +85,7 @@
  * Exactly one of these classes per Display in the system. Capable of holding zero or more
  * attached {@link ActivityStack}s.
  */
-class ActivityDisplay extends ConfigurationContainer<ActivityStack>
-        implements WindowContainerListener {
+class ActivityDisplay extends ConfigurationContainer<ActivityStack> {
     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityDisplay" : TAG_ATM;
     private static final String TAG_STACK = TAG + POSTFIX_STACK;
 
@@ -201,11 +201,6 @@
         }
     }
 
-    @Override
-    public void onInitializeOverrideConfiguration(Configuration config) {
-        getRequestedOverrideConfiguration().updateFrom(config);
-    }
-
     void addChild(ActivityStack stack, int position) {
         if (position == POSITION_BOTTOM) {
             position = 0;
@@ -291,9 +286,7 @@
         }
 
         // Since positionChildAt() is called during the creation process of pinned stacks,
-        // ActivityStack#getStack() can be null. In this special case,
-        // since DisplayContest#positionStackAt() is called in TaskStack#onConfigurationChanged(),
-        // we don't have to call WindowContainerController#positionChildAt() here.
+        // ActivityStack#getStack() can be null.
         if (stack.getTaskStack() != null && mDisplayContent != null) {
             mDisplayContent.positionStackAt(insertPosition,
                     stack.getTaskStack(), includingParents);
@@ -1202,8 +1195,8 @@
         // Stacks could be reparented from the removed display to other display. While
         // reparenting the last stack of the removed display, the remove display is ready to be
         // released (no more ActivityStack). But, we cannot release it at that moment or the
-        // related WindowContainer and WindowContainerController will also be removed. So, we
-        // set display as removed after reparenting stack finished.
+        // related WindowContainer will also be removed. So, we set display as removed after
+        // reparenting stack finished.
         final ActivityDisplay toDisplay = mRootActivityContainer.getDefaultDisplay();
         mRootActivityContainer.mStackSupervisor.beginDeferResume();
         try {
@@ -1304,8 +1297,8 @@
         final AppWindowToken newFocus;
         final IBinder token = r.appToken;
         if (token == null) {
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "Clearing focused app, displayId="
-                    + mDisplayId);
+            ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Clearing focused app, displayId=%d",
+                    mDisplayId);
             newFocus = null;
         } else {
             newFocus = mService.mWindowManager.mRoot.getAppWindowToken(token);
@@ -1313,8 +1306,9 @@
                 Slog.w(TAG_WM, "Attempted to set focus to non-existing app token: " + token
                         + ", displayId=" + mDisplayId);
             }
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "Set focused app to: " + newFocus
-                    + " moveFocusNow=" + moveFocusNow + " displayId=" + mDisplayId);
+            ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
+                    "Set focused app to: %s moveFocusNow=%b displayId=%d", newFocus,
+                            moveFocusNow, mDisplayId);
         }
 
         final boolean changed = mDisplayContent.setFocusedApp(newFocus);
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index c54ccd4..4f52d9d 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -54,20 +54,14 @@
 import static android.content.pm.ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
 import static android.content.pm.ActivityInfo.CONFIG_UI_MODE;
 import static android.content.pm.ActivityInfo.CONFIG_WINDOW_CONFIGURATION;
-import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
 import static android.content.pm.ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
 import static android.content.pm.ActivityInfo.FLAG_IMMERSIVE;
-import static android.content.pm.ActivityInfo.FLAG_INHERIT_SHOW_WHEN_LOCKED;
 import static android.content.pm.ActivityInfo.FLAG_MULTIPROCESS;
 import static android.content.pm.ActivityInfo.FLAG_NO_HISTORY;
 import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
-import static android.content.pm.ActivityInfo.FLAG_SHOW_WHEN_LOCKED;
 import static android.content.pm.ActivityInfo.FLAG_STATE_NOT_NEEDED;
-import static android.content.pm.ActivityInfo.FLAG_TURN_SCREEN_ON;
-import static android.content.pm.ActivityInfo.LAUNCH_MULTIPLE;
 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_INSTANCE;
 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TASK;
-import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TOP;
 import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_ALWAYS;
 import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_DEFAULT;
 import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_IF_WHITELISTED;
@@ -86,7 +80,6 @@
 import static android.content.res.Configuration.ORIENTATION_UNDEFINED;
 import static android.content.res.Configuration.UI_MODE_TYPE_MASK;
 import static android.content.res.Configuration.UI_MODE_TYPE_VR_HEADSET;
-import static android.os.Build.VERSION_CODES.HONEYCOMB;
 import static android.os.Build.VERSION_CODES.O;
 import static android.os.Process.SYSTEM_UID;
 import static android.view.Display.DEFAULT_DISPLAY;
@@ -96,7 +89,7 @@
 import static android.view.WindowManager.TRANSIT_ACTIVITY_CLOSE;
 import static android.view.WindowManager.TRANSIT_TASK_CLOSE;
 
-import static com.android.server.am.ActivityRecordProto.CONFIGURATION_CONTAINER;
+import static com.android.server.am.ActivityRecordProto.APP_WINDOW_TOKEN;
 import static com.android.server.am.ActivityRecordProto.FRONT_OF_TASK;
 import static com.android.server.am.ActivityRecordProto.IDENTIFIER;
 import static com.android.server.am.ActivityRecordProto.PROC_ID;
@@ -151,15 +144,12 @@
 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.wm.IdentifierProto.HASH_CODE;
-import static com.android.server.wm.IdentifierProto.TITLE;
-import static com.android.server.wm.IdentifierProto.USER_ID;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_STARTING_WINDOW;
+import static com.android.server.wm.ActivityTaskManagerService.getInputDispatchingTimeoutLocked;
 import static com.android.server.wm.TaskPersister.DEBUG;
 import static com.android.server.wm.TaskPersister.IMAGE_EXTENSION;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TOKEN_MOVEMENT;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
@@ -212,7 +202,6 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.SystemClock;
-import android.os.UserHandle;
 import android.os.storage.StorageManager;
 import android.service.voice.IVoiceInteractionSession;
 import android.util.ArraySet;
@@ -226,19 +215,16 @@
 import android.view.DisplayCutout;
 import android.view.IAppTransitionAnimationSpecsFuture;
 import android.view.IApplicationToken;
-import android.view.RemoteAnimationDefinition;
 import android.view.WindowManager.LayoutParams;
 
-import com.android.internal.R;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.ResolverActivity;
 import com.android.internal.content.ReferrerIntent;
 import com.android.internal.util.XmlUtils;
-import com.android.server.AttributeCache;
-import com.android.server.AttributeCache.Entry;
 import com.android.server.am.AppTimeTracker;
 import com.android.server.am.EventLogTags;
 import com.android.server.am.PendingIntentRecord;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.uri.UriPermissionOwner;
 import com.android.server.wm.ActivityMetricsLogger.WindowingModeTransitionInfoSnapshot;
 import com.android.server.wm.ActivityStack.ActivityState;
@@ -262,7 +248,7 @@
 /**
  * An entry in the history stack, representing an activity.
  */
-final class ActivityRecord extends ConfigurationContainer {
+final class ActivityRecord extends AppWindowToken {
     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityRecord" : TAG_ATM;
     private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE;
     private static final String TAG_APP = TAG + POSTFIX_APP;
@@ -291,29 +277,17 @@
     // How many activities have to be scheduled to stop to force a stop pass.
     private static final int MAX_STOPPING_TO_FORCE = 3;
 
-    final ActivityTaskManagerService mAtmService; // owner
-    final IApplicationToken.Stub appToken; // window manager token
-    // TODO: Remove after unification
-    AppWindowToken mAppWindowToken;
-
+    // TODO: Move to AppWindowToken?
     final ActivityInfo info; // activity info provided by developer in AndroidManifest
     final int launchedFromPid; // always the pid who started the activity.
     final int launchedFromUid; // always the uid who started the activity.
     final String launchedFromPackage; // always the package who started the activity.
-    final int mUserId;          // Which user is this running for?
     final Intent intent;    // the original intent that generated us
-    final ComponentName mActivityComponent;  // the intent component, or target of an alias.
     final String shortComponentName; // the short component name of the intent
     final String resolvedType; // as per original caller;
-    final String packageName; // the package implementing intent's component
     final String processName; // process where this component wants to run
     final String taskAffinity; // as per ActivityInfo.taskAffinity
     final boolean stateNotNeeded; // As per ActivityInfo.flags
-    boolean fullscreen; // The activity is opaque and fills the entire space of this task.
-    // TODO: See if it possible to combine this with the fullscreen field.
-    final boolean hasWallpaper; // Has a wallpaper window as a background.
-    @VisibleForTesting
-    boolean noDisplay;  // activity is not displayed?
     @VisibleForTesting
     int mHandoverLaunchDisplayId = INVALID_DISPLAY; // Handover launch display id to next activity.
     private final boolean componentSpecified;  // did caller specify an explicit component?
@@ -324,7 +298,6 @@
     private int icon;               // resource identifier of activity's icon.
     private int logo;               // resource identifier of activity's logo.
     private int theme;              // resource identifier of activity's theme.
-    private int realTheme;          // actual theme resource we will use, never 0.
     private int windowFlags;        // custom window flags for preview window.
     private TaskRecord task;        // the task this is in.
     private long createTime = System.currentTimeMillis();
@@ -374,6 +347,7 @@
     boolean visible;        // does this activity's window need to be shown?
     boolean visibleIgnoringKeyguard; // is this activity visible, ignoring the fact that Keyguard
                                      // might hide this activity?
+    // TODO: figureout how to consolidate with the same variable in AppWindowToken.
     private boolean mDeferHidingClient; // If true we told WM to defer reporting to the client
                                         // process that it is hidden.
     boolean sleeping;       // have we told the activity to sleep?
@@ -393,8 +367,6 @@
     long lastLaunchTime;    // time of last launch of this activity
     ComponentName requestedVrComponent; // the requested component for handling VR mode.
 
-    String stringName;      // for caching of toString().
-
     private boolean inHistory;  // are we in the history stack?
     final ActivityStackSupervisor mStackSupervisor;
     final RootActivityContainer mRootActivityContainer;
@@ -411,8 +383,6 @@
     int mRelaunchReason = RELAUNCH_REASON_NONE;
 
     TaskDescription taskDescription; // the recents information for this activity
-    boolean mLaunchTaskBehind; // this activity is actively being launched with
-        // ActivityOptions.setLaunchTaskBehind, will be cleared once launch is completed.
 
     // These configurations are collected from application's resources based on size-sensitive
     // qualifiers. For example, layout-w800dp will be added to mHorizontalSizeConfigurations as 800
@@ -430,17 +400,6 @@
     boolean pendingVoiceInteractionStart;   // Waiting for activity-invoked voice session
     IVoiceInteractionSession voiceSession;  // Voice interaction session for this activity
 
-    // A hint to override the window specified rotation animation, or -1
-    // to use the window specified value. We use this so that
-    // we can select the right animation in the cases of starting
-    // windows, where the app hasn't had time to set a value
-    // on the window.
-    int mRotationAnimationHint = -1;
-
-    private boolean mShowWhenLocked;
-    private boolean mInheritShownWhenLocked;
-    private boolean mTurnScreenOn;
-
     /**
      * Current sequencing integer of the configuration, for skipping old activity configurations.
      */
@@ -603,7 +562,7 @@
                 pw.print(" idle="); pw.print(idle);
                 pw.print(" mStartingWindowState=");
                 pw.println(startingWindowStateToString(mStartingWindowState));
-        pw.print(prefix); pw.print("fullscreen="); pw.print(fullscreen);
+        pw.print(prefix); pw.print("occludesParent="); pw.print(occludesParent());
                 pw.print(" noDisplay="); pw.print(noDisplay);
                 pw.print(" immersive="); pw.print(immersive);
                 pw.print(" launchMode="); pw.println(launchMode);
@@ -855,22 +814,7 @@
         }
     }
 
-    @Override
-    protected int getChildCount() {
-        // {@link ActivityRecord} is a leaf node and has no children.
-        return 0;
-    }
-
-    @Override
-    protected ConfigurationContainer getChildAt(int index) {
-        return null;
-    }
-
-    @Override
-    protected ConfigurationContainer getParent() {
-        return getTaskRecord();
-    }
-
+    // TODO: Remove once TaskRecord and Task are unified.
     TaskRecord getTaskRecord() {
         return task;
     }
@@ -914,31 +858,63 @@
 
         this.task = task;
 
-        if (!reparenting) {
+        // This is attaching the activity to the task which we only want to do once.
+        // TODO: Need to re-work after unifying the task level since it will already have a parent
+        // then. Just need to restructure the re-parent case not to do this. NOTE that the
+        // reparenting flag passed in can't be used directly for this as it isn't set in
+        // ActivityRecord#reparent() case that ends up calling this method.
+        if (task != null && getParent() == null) {
+            inHistory = true;
+            final Task container = task.getTask();
+            if (container != null) {
+                onAttachToTask(task.voiceSession != null, container.getDisplayContent(),
+                        getInputDispatchingTimeoutLocked(this) * 1000000L);
+                ProtoLog.v(WM_DEBUG_ADD_REMOVE, "setTask: %s at top.", this);
+                container.addChild(this, Integer.MAX_VALUE /* add on top */);
+            }
+
+            // TODO(b/36505427): Maybe this call should be moved inside
+            // updateOverrideConfiguration()
+            task.updateOverrideConfigurationFromLaunchBounds();
+            // Make sure override configuration is up-to-date before using to create window
+            // controller.
+            updateOverrideConfiguration();
+
+            task.addActivityToTop(this);
+
+            // When an activity is started directly into a split-screen fullscreen stack, we need to
+            // update the initial multi-window modes so that the callbacks are scheduled correctly
+            // when the user leaves that mode.
+            mLastReportedMultiWindowMode = inMultiWindowMode();
+            mLastReportedPictureInPictureMode = inPinnedWindowingMode();
+        } else if (!reparenting) {
             onParentChanged();
         }
     }
 
     /**
-     * Notifies AWT that this app is waiting to pause in order to determine if it will enter PIP.
-     * This information helps AWT know that the app is in the process of pausing before it gets the
-     * signal on the WM side.
+     * Sets the Task on this activity for the purposes of re-use during launch where we will
+     * re-use another activity instead of this one for the launch.
      */
-    void setWillCloseOrEnterPip(boolean willCloseOrEnterPip) {
-        if (mAppWindowToken == null) {
-            return;
-        }
-
-        mAppWindowToken.setWillCloseOrEnterPip(willCloseOrEnterPip);
+    void setTaskForReuse(TaskRecord task) {
+        this.task = task;
     }
 
     static class Token extends IApplicationToken.Stub {
-        private final WeakReference<ActivityRecord> weakActivity;
+        private WeakReference<ActivityRecord> weakActivity;
         private final String name;
+        private final String tokenString;
 
-        Token(ActivityRecord activity, Intent intent) {
-            weakActivity = new WeakReference<>(activity);
+        Token(Intent intent) {
             name = intent.getComponent().flattenToShortString();
+            tokenString = "Token{" + Integer.toHexString(System.identityHashCode(this)) + "}";
+        }
+
+        private void attach(ActivityRecord activity) {
+            if (weakActivity != null) {
+                throw new IllegalStateException("Already attached..." + this);
+            }
+            weakActivity = new WeakReference<>(activity);
         }
 
         private static @Nullable ActivityRecord tokenToActivityRecordLocked(Token token) {
@@ -958,7 +934,9 @@
             sb.append("Token{");
             sb.append(Integer.toHexString(System.identityHashCode(this)));
             sb.append(' ');
-            sb.append(weakActivity.get());
+            if (weakActivity != null) {
+                sb.append(weakActivity.get());
+            }
             sb.append('}');
             return sb.toString();
         }
@@ -1005,14 +983,15 @@
             ActivityRecord _resultTo, String _resultWho, int _reqCode, boolean _componentSpecified,
             boolean _rootVoiceInteraction, ActivityStackSupervisor supervisor,
             ActivityOptions options, ActivityRecord sourceRecord) {
-        mAtmService = _service;
+        super(_service.mWindowManager, _service, new Token(_intent), aInfo, options, _intent,
+                null /* displayContent */);
+        appToken.attach(this);
+
         mRootActivityContainer = _service.mRootActivityContainer;
-        appToken = new Token(this, _intent);
         info = aInfo;
         launchedFromPid = _launchedFromPid;
         launchedFromUid = _launchedFromUid;
         launchedFromPackage = _launchedFromPackage;
-        mUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
         intent = _intent;
         shortComponentName = _intent.getComponent().flattenToShortString();
         resolvedType = _resolvedType;
@@ -1037,17 +1016,6 @@
         hasBeenLaunched = false;
         mStackSupervisor = supervisor;
 
-        // If the class name in the intent doesn't match that of the target, this is
-        // probably an alias. We have to create a new ComponentName object to keep track
-        // of the real activity name, so that FLAG_ACTIVITY_CLEAR_TOP is handled properly.
-        if (aInfo.targetActivity == null
-                || (aInfo.targetActivity.equals(_intent.getComponent().getClassName())
-                && (aInfo.launchMode == LAUNCH_MULTIPLE
-                || aInfo.launchMode == LAUNCH_SINGLE_TOP))) {
-            mActivityComponent = _intent.getComponent();
-        } else {
-            mActivityComponent = new ComponentName(aInfo.packageName, aInfo.targetActivity);
-        }
         taskAffinity = aInfo.taskAffinity;
         stateNotNeeded = (aInfo.flags & FLAG_STATE_NOT_NEEDED) != 0;
         nonLocalizedLabel = aInfo.nonLocalizedLabel;
@@ -1060,11 +1028,6 @@
         icon = aInfo.getIconResource();
         logo = aInfo.getLogoResource();
         theme = aInfo.getThemeResource();
-        realTheme = theme;
-        if (realTheme == 0) {
-            realTheme = aInfo.applicationInfo.targetSdkVersion < HONEYCOMB
-                    ? android.R.style.Theme : android.R.style.Theme_Holo;
-        }
         if ((aInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
             windowFlags |= LayoutParams.FLAG_HARDWARE_ACCELERATED;
         }
@@ -1080,21 +1043,8 @@
             intent.addFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
         }
 
-        packageName = aInfo.applicationInfo.packageName;
         launchMode = aInfo.launchMode;
 
-        Entry ent = AttributeCache.instance().get(packageName,
-                realTheme, com.android.internal.R.styleable.Window, mUserId);
-
-        if (ent != null) {
-            fullscreen = !ActivityInfo.isTranslucentOrFloating(ent.array);
-            hasWallpaper = ent.array.getBoolean(R.styleable.Window_windowShowWallpaper, false);
-            noDisplay = ent.array.getBoolean(R.styleable.Window_windowNoDisplay, false);
-        } else {
-            hasWallpaper = false;
-            noDisplay = false;
-        }
-
         setActivityType(_componentSpecified, _launchedFromUid, _intent, options, sourceRecord);
 
         immersive = (aInfo.flags & FLAG_IMMERSIVE) != 0;
@@ -1102,11 +1052,6 @@
         requestedVrComponent = (aInfo.requestedVrComponent == null) ?
                 null : ComponentName.unflattenFromString(aInfo.requestedVrComponent);
 
-        mShowWhenLocked = (aInfo.flags & FLAG_SHOW_WHEN_LOCKED) != 0;
-        mInheritShownWhenLocked = (aInfo.privateFlags & FLAG_INHERIT_SHOW_WHEN_LOCKED) != 0;
-        mTurnScreenOn = (aInfo.flags & FLAG_TURN_SCREEN_ON) != 0;
-
-        mRotationAnimationHint = aInfo.rotationAnimation;
         lockTaskLaunchMode = aInfo.lockTaskLaunchMode;
         if (info.applicationInfo.isPrivilegedApp()
                 && (lockTaskLaunchMode == LOCK_TASK_LAUNCH_MODE_ALWAYS
@@ -1116,13 +1061,6 @@
 
         if (options != null) {
             pendingOptions = options;
-            mLaunchTaskBehind = options.getLaunchTaskBehind();
-
-            final int rotationAnimation = pendingOptions.getRotationAnimationHint();
-            // Only override manifest supplied option if set.
-            if (rotationAnimation >= 0) {
-                mRotationAnimationHint = rotationAnimation;
-            }
             final PendingIntent usageReport = pendingOptions.getUsageTimeReport();
             if (usageReport != null) {
                 appTimeTracker = new AppTimeTracker(usageReport);
@@ -1152,97 +1090,28 @@
         return hasProcess() && app.hasThread();
     }
 
-    void createAppWindowToken() {
-        if (mAppWindowToken != null) {
-            throw new IllegalArgumentException("App Window Token=" + mAppWindowToken
-                    + " already created for r=" + this);
-        }
-
-        inHistory = true;
-
-        // TODO(b/36505427): Maybe this call should be moved inside updateOverrideConfiguration()
-        task.updateOverrideConfigurationFromLaunchBounds();
-        // Make sure override configuration is up-to-date before using to create window controller.
-        updateOverrideConfiguration();
-
-        // TODO: remove after unification
-        mAppWindowToken = mAtmService.mWindowManager.mRoot.getAppWindowToken(appToken.asBinder());
-        if (mAppWindowToken != null) {
-            // TODO: Should this throw an exception instead?
-            Slog.w(TAG, "Attempted to add existing app token: " + appToken);
-        } else {
-            final Task container = task.getTask();
-            if (container == null) {
-                throw new IllegalArgumentException("createAppWindowToken: invalid task =" + task);
-            }
-            mAppWindowToken = createAppWindow(mAtmService.mWindowManager, appToken,
-                    task.voiceSession != null, container.getDisplayContent(),
-                    ActivityTaskManagerService.getInputDispatchingTimeoutLocked(this)
-                            * 1000000L, fullscreen,
-                    (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0,
-                    info.applicationInfo.targetSdkVersion,
-                    info.screenOrientation, mRotationAnimationHint,
-                    mLaunchTaskBehind, isAlwaysFocusable());
-            if (DEBUG_TOKEN_MOVEMENT || DEBUG_ADD_REMOVE) {
-                Slog.v(TAG, "addAppToken: "
-                        + mAppWindowToken + " task=" + container + " at "
-                        + Integer.MAX_VALUE);
-            }
-            container.addChild(mAppWindowToken, Integer.MAX_VALUE /* add on top */);
-        }
-
-        task.addActivityToTop(this);
-
-        // When an activity is started directly into a split-screen fullscreen stack, we need to
-        // update the initial multi-window modes so that the callbacks are scheduled correctly when
-        // the user leaves that mode.
-        mLastReportedMultiWindowMode = inMultiWindowMode();
-        mLastReportedPictureInPictureMode = inPinnedWindowingMode();
-    }
-
     boolean addStartingWindow(String pkg, int theme, CompatibilityInfo compatInfo,
             CharSequence nonLocalizedLabel, int labelRes, int icon, int logo, int windowFlags,
             IBinder transferFrom, boolean newTask, boolean taskSwitch, boolean processRunning,
             boolean allowTaskSnapshot, boolean activityCreated, boolean fromRecents) {
-        if (DEBUG_STARTING_WINDOW) {
-            Slog.v(TAG, "setAppStartingWindow: token=" + appToken
-                    + " pkg=" + pkg + " transferFrom=" + transferFrom + " newTask=" + newTask
-                    + " taskSwitch=" + taskSwitch + " processRunning=" + processRunning
-                    + " allowTaskSnapshot=" + allowTaskSnapshot);
-        }
-        if (mAppWindowToken == null) {
-            Slog.w(TAG_WM, "Attempted to set icon of non-existing app token: " + appToken);
-            return false;
-        }
-        if (mAppWindowToken.getTask() == null) {
-            // Can be removed after unification of Task and TaskRecord.
+        ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "setAppStartingWindow: token=%s"
+                    + " pkg=%s transferFrom=%s newTask=%b taskSwitch=%b processRunning=%b"
+                    + " allowTaskSnapshot=%b", appToken, pkg, transferFrom, newTask, taskSwitch,
+                processRunning, allowTaskSnapshot);
+        if (getParent() == null) {
             Slog.w(TAG_WM, "Attempted to start a window to an app token not having attached to any"
                     + " task: " + appToken);
             return false;
         }
-        return mAppWindowToken.addStartingWindow(pkg, theme, compatInfo, nonLocalizedLabel,
+        return super.addStartingWindow(pkg, theme, compatInfo, nonLocalizedLabel,
                 labelRes, icon, logo, windowFlags, transferFrom, newTask, taskSwitch,
                 processRunning, allowTaskSnapshot, activityCreated, fromRecents);
     }
 
-    // TODO: Remove after unification
-    @VisibleForTesting
-    AppWindowToken createAppWindow(WindowManagerService service, IApplicationToken token,
-            boolean voiceInteraction, DisplayContent dc, long inputDispatchingTimeoutNanos,
-            boolean fullscreen, boolean showForAllUsers, int targetSdk, int orientation,
-            int rotationAnimationHint, boolean launchTaskBehind,
-            boolean alwaysFocusable) {
-        return new AppWindowToken(service, token, mActivityComponent, voiceInteraction, dc,
-                inputDispatchingTimeoutNanos, fullscreen, showForAllUsers, targetSdk, orientation,
-                rotationAnimationHint, launchTaskBehind, alwaysFocusable,
-                this);
-    }
-
     void removeWindowContainer() {
-        if (mAtmService.mWindowManager.mRoot == null) return;
+        if (mWmService.mRoot == null) return;
 
-        final DisplayContent dc = mAtmService.mWindowManager.mRoot.getDisplayContent(
-                getDisplayId());
+        final DisplayContent dc = mWmService.mRoot.getDisplayContent(getDisplayId());
         if (dc == null) {
             Slog.w(TAG, "removeWindowContainer: Attempted to remove token: "
                     + appToken + " from non-existing displayId=" + getDisplayId());
@@ -1258,7 +1127,7 @@
      * should ensure that the {@param newTask} is not already the parent of this activity.
      */
     void reparent(TaskRecord newTask, int position, String reason) {
-        if (mAppWindowToken == null) {
+        if (getParent() == null) {
             Slog.w(TAG, "reparent: Attempted to reparent non-existing app token: " + appToken);
             return;
         }
@@ -1277,7 +1146,7 @@
                     + " r=" + this + " (" + prevTask.getStackId() + ")");
         }
 
-        mAppWindowToken.reparent(newTask.getTask(), position);
+        reparent(newTask.getTask(), position);
 
         // Reparenting prevents informing the parent stack of activity removal in the case that
         // the new stack has the same parent. we must manually signal here if this is not the case.
@@ -1368,6 +1237,7 @@
     /**
      * @return Stack value from current task, null if there is no task.
      */
+    // TODO: Remove once ActivityStack and TaskStack are unified.
     <T extends ActivityStack> T getActivityStack() {
         return task != null ? (T) task.getStack() : null;
     }
@@ -1382,14 +1252,13 @@
     }
 
     boolean setOccludesParent(boolean occludesParent) {
-        final boolean changed = mAppWindowToken.setOccludesParent(occludesParent);
+        final boolean changed = super.setOccludesParent(occludesParent);
         if (changed) {
             if (!occludesParent) {
                 getActivityStack().convertActivityToTranslucent(this);
             }
             // Keep track of the number of fullscreen activities in this task.
             task.numFullscreen += occludesParent ? +1 : -1;
-            fullscreen = occludesParent;
         }
         // Always ensure visibility if this activity doesn't occlude parent, so the
         // {@link #returningOptions} of the activity under this one can be applied in
@@ -1558,10 +1427,6 @@
                 OP_PICTURE_IN_PICTURE, info.applicationInfo.uid, packageName) == MODE_ALLOWED;
     }
 
-    boolean isAlwaysFocusable() {
-        return (info.flags & FLAG_ALWAYS_FOCUSABLE) != 0;
-    }
-
     /** Move activity with its stack to front and make the stack focused. */
     boolean moveFocusableActivityToTop(String reason) {
         if (!isFocusable()) {
@@ -1709,7 +1574,7 @@
             final TaskRecord task = getTaskRecord();
             EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
                     mUserId, System.identityHashCode(this),
-                    task.taskId, shortComponentName, reason);
+                    task.mTaskId, shortComponentName, reason);
             final ArrayList<ActivityRecord> activities = task.mActivities;
             final int index = activities.indexOf(this);
             if (index < (activities.size() - 1)) {
@@ -1858,25 +1723,27 @@
         // implied that the current finishing activity should be added into stopping list rather
         // than destroy immediately.
         final boolean isNextNotYetVisible = next != null && (!next.nowVisible || !next.visible);
-        final ActivityStack stack = getActivityStack();
-        final boolean notFocusedStack = stack != mRootActivityContainer.getTopDisplayFocusedStack();
+        final boolean notGlobalFocusedStack =
+                getActivityStack() != mRootActivityContainer.getTopDisplayFocusedStack();
         if (isVisible && isNextNotYetVisible) {
+            // Add this activity to the list of stopping activities. It will be processed and
+            // destroyed when the next activity reports idle.
             addToStopping(false /* scheduleIdle */, false /* idleDelayed */,
                     "completeFinishing");
-            if (DEBUG_STATES) {
-                Slog.v(TAG_STATES, "Moving to STOPPING: " + this + " (finish requested)");
-            }
             setState(STOPPING, "completeFinishing");
-            if (notFocusedStack) {
+            if (notGlobalFocusedStack) {
+                // Ensuring visibility and configuration only for non-focused stacks since this
+                // method call is relatively expensive and not necessary for focused stacks.
                 mRootActivityContainer.ensureVisibilityAndConfig(next, getDisplayId(),
                         false /* markFrozenIfConfigChanged */, true /* deferResume */);
             }
-        } else if (isVisible && isState(PAUSED) && getActivityStack().isFocusedStackOnDisplay()
-                && !inPinnedWindowingMode()) {
-            // TODO(b/137329632): Currently non-focused stack is handled differently.
-            addToFinishingAndWaitForIdle();
+        } else if (addToFinishingAndWaitForIdle()) {
+            // We added this activity to the finishing list and something else is becoming resumed.
+            // The activity will complete finishing when the next activity reports idle. No need to
+            // do anything else here.
         } else {
-            // Not waiting for the next one to become visible - finish right away.
+            // Not waiting for the next one to become visible, and nothing else will be resumed in
+            // place of this activity - requesting destruction right away.
             activityRemoved = destroyIfPossible(reason);
         }
 
@@ -1933,13 +1800,20 @@
         return activityRemoved;
     }
 
+    /**
+     * Add this activity to the list of finishing and trigger resuming of activities in focused
+     * stacks.
+     * @return {@code true} if some other activity is being resumed as a result of this call.
+     */
     @VisibleForTesting
-    void addToFinishingAndWaitForIdle() {
+    boolean addToFinishingAndWaitForIdle() {
         if (DEBUG_STATES) Slog.v(TAG, "Enqueueing pending finish: " + this);
         setState(FINISHING, "addToFinishingAndWaitForIdle");
-        mStackSupervisor.mFinishingActivities.add(this);
+        if (!mStackSupervisor.mFinishingActivities.contains(this)) {
+            mStackSupervisor.mFinishingActivities.add(this);
+        }
         resumeKeyDispatchingLocked();
-        mRootActivityContainer.resumeFocusedStacksTopActivities();
+        return mRootActivityContainer.resumeFocusedStacksTopActivities();
     }
 
     /**
@@ -1969,7 +1843,7 @@
         }
 
         EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY, mUserId,
-                System.identityHashCode(this), getTaskRecord().taskId, shortComponentName, reason);
+                System.identityHashCode(this), getTaskRecord().mTaskId, shortComponentName, reason);
 
         boolean removedFromHistory = false;
 
@@ -2107,7 +1981,7 @@
                 // work.
                 // TODO: If the callers to removeTask() changes such that we have multiple places
                 //       where we are destroying the task, move this back into removeTask()
-                mStackSupervisor.removeTaskByIdLocked(task.taskId, false /* killProcess */,
+                mStackSupervisor.removeTaskByIdLocked(task.mTaskId, false /* killProcess */,
                         !REMOVE_FROM_RECENTS, reason);
             }
 
@@ -2202,9 +2076,7 @@
         stack.removeTimeoutsForActivity(this);
         // Clean-up activities are no longer relaunching (e.g. app process died). Notify window
         // manager so it can update its bookkeeping.
-        if (mAppWindowToken != null) {
-            mAppWindowToken.clearRelaunching();
-        }
+        clearRelaunching();
     }
 
     /**
@@ -2223,7 +2095,7 @@
         final String strData = data != null ? data.toSafeString() : null;
 
         EventLog.writeEvent(tag,
-                mUserId, System.identityHashCode(this), task.taskId,
+                mUserId, System.identityHashCode(this), task.mTaskId,
                 shortComponentName, intent.getAction(),
                 intent.getType(), strData, intent.getFlags());
     }
@@ -2370,7 +2242,7 @@
      */
     void applyOptionsLocked(ActivityOptions pendingOptions, Intent intent) {
         final int animationType = pendingOptions.getAnimationType();
-        final DisplayContent displayContent = mAppWindowToken.getDisplayContent();
+        final DisplayContent displayContent = getDisplayContent();
         switch (animationType) {
             case ANIM_CUSTOM:
                 displayContent.mAppTransition.overridePendingAppTransition(
@@ -2504,11 +2376,8 @@
         if (!keysPaused) {
             keysPaused = true;
 
-            // TODO: remove the check after unification with AppWindowToken. The DC check is not
-            // needed after no mock mAppWindowToken in tests.
-            if (mAppWindowToken != null && mAppWindowToken.getDisplayContent() != null) {
-                mAppWindowToken.getDisplayContent().getInputMonitor().pauseDispatchingLw(
-                        mAppWindowToken);
+            if (getDisplayContent() != null) {
+                getDisplayContent().getInputMonitor().pauseDispatchingLw(this);
             }
         }
     }
@@ -2517,11 +2386,8 @@
         if (keysPaused) {
             keysPaused = false;
 
-            // TODO: remove the check after unification with AppWindowToken. The DC check is not
-            // needed after no mock mAppWindowToken in tests.
-            if (mAppWindowToken != null && mAppWindowToken.getDisplayContent() != null) {
-                mAppWindowToken.getDisplayContent().getInputMonitor().resumeDispatchingLw(
-                        mAppWindowToken);
+            if (getDisplayContent() != null) {
+                getDisplayContent().getInputMonitor().resumeDispatchingLw(this);
             }
         }
     }
@@ -2543,12 +2409,12 @@
     }
 
     void setVisibility(boolean visible) {
-        if (mAppWindowToken == null) {
+        if (getParent() == null) {
             Slog.w(TAG_WM, "Attempted to set visibility of non-existing app token: "
                     + appToken);
             return;
         }
-        mAppWindowToken.setVisibility(visible, mDeferHidingClient);
+        setVisibility(visible, mDeferHidingClient);
         mAtmService.addWindowLayoutReasons(
                 ActivityTaskManagerService.LAYOUT_REASON_VISIBILITY_CHANGED);
         mStackSupervisor.getActivityMetricsLogger().notifyVisibilityChanged(this);
@@ -2584,12 +2450,12 @@
         // an indication that the Surface will eventually be destroyed.
         // This however isn't necessarily true if we are going to sleep.
         if (state == STOPPING && !isSleeping()) {
-            if (mAppWindowToken == null) {
+            if (getParent() == null) {
                 Slog.w(TAG_WM, "Attempted to notify stopping on non-existing app token: "
                         + appToken);
                 return;
             }
-            mAppWindowToken.detachChildren();
+            detachChildren();
         }
 
         if (state == RESUMED) {
@@ -2648,23 +2514,20 @@
     }
 
     void notifyAppResumed(boolean wasStopped) {
-        if (mAppWindowToken == null) {
+        if (getParent() == null) {
             Slog.w(TAG_WM, "Attempted to notify resumed of non-existing app token: "
                     + appToken);
             return;
         }
-        mAppWindowToken.notifyAppResumed(wasStopped);
+        super.notifyAppResumed(wasStopped);
     }
 
     void notifyUnknownVisibilityLaunched() {
 
         // No display activities never add a window, so there is no point in waiting them for
         // relayout.
-        if (!noDisplay) {
-            if (mAppWindowToken != null) {
-                mAppWindowToken.getDisplayContent().mUnknownAppVisibilityController
-                        .notifyLaunched(mAppWindowToken);
-            }
+        if (!noDisplay && getDisplayContent() != null) {
+            getDisplayContent().mUnknownAppVisibilityController.notifyLaunched(this);
         }
     }
 
@@ -2964,10 +2827,7 @@
             display.handleActivitySizeCompatModeIfNeeded(r);
         }
 
-        if (r.mAppWindowToken != null) {
-            r.mAppWindowToken.getDisplayContent().mUnknownAppVisibilityController
-                    .notifyAppResumedFinished(r.mAppWindowToken);
-        }
+        r.getDisplayContent().mUnknownAppVisibilityController.notifyAppResumedFinished(r);
     }
 
     /**
@@ -3115,9 +2975,7 @@
                 setState(STOPPED, "activityStoppedLocked");
             }
 
-            if (mAppWindowToken != null) {
-                mAppWindowToken.notifyAppStopped();
-            }
+            notifyAppStopped();
 
             if (finishing) {
                 clearOptionsLocked();
@@ -3194,9 +3052,11 @@
         stack.removeLaunchTickMessages();
     }
 
-    // IApplicationToken
+    boolean mayFreezeScreenLocked() {
+        return mayFreezeScreenLocked(app);
+    }
 
-    public boolean mayFreezeScreenLocked(WindowProcessController app) {
+    private boolean mayFreezeScreenLocked(WindowProcessController app) {
         // Only freeze the screen if this activity is currently attached to
         // an application, and that application is not blocked or unresponding.
         // In any other case, we can't count on getting the screen unfrozen,
@@ -3204,9 +3064,13 @@
         return hasProcess() && !app.isCrashing() && !app.isNotResponding();
     }
 
-    public void startFreezingScreenLocked(WindowProcessController app, int configChanges) {
+    void startFreezingScreenLocked(int configChanges) {
+        startFreezingScreenLocked(app, configChanges);
+    }
+
+    void startFreezingScreenLocked(WindowProcessController app, int configChanges) {
         if (mayFreezeScreenLocked(app)) {
-            if (mAppWindowToken == null) {
+            if (getParent() == null) {
                 Slog.w(TAG_WM,
                         "Attempted to freeze screen with non-existing app token: " + appToken);
                 return;
@@ -3214,31 +3078,29 @@
 
             // Window configuration changes only effect windows, so don't require a screen freeze.
             int freezableConfigChanges = configChanges & ~(CONFIG_WINDOW_CONFIGURATION);
-            if (freezableConfigChanges == 0 && mAppWindowToken.okToDisplay()) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Skipping set freeze of " + appToken);
+            if (freezableConfigChanges == 0 && okToDisplay()) {
+                ProtoLog.v(WM_DEBUG_ORIENTATION, "Skipping set freeze of %s", appToken);
                 return;
             }
 
-            mAppWindowToken.startFreezingScreen();
+            startFreezingScreen();
         }
     }
 
-    public void stopFreezingScreenLocked(boolean force) {
+    void stopFreezingScreenLocked(boolean force) {
         if (force || frozenBeforeDestroy) {
             frozenBeforeDestroy = false;
-            if (mAppWindowToken == null) {
+            if (getParent() == null) {
                 return;
             }
-            if (DEBUG_ORIENTATION) {
-                Slog.v(TAG_WM, "Clear freezing of " + appToken + ": hidden="
-                        + mAppWindowToken.isHidden() + " freezing="
-                        + mAppWindowToken.isFreezingScreen());
-            }
-            mAppWindowToken.stopFreezingScreen(true, force);
+            ProtoLog.v(WM_DEBUG_ORIENTATION,
+                        "Clear freezing of %s: hidden=%b freezing=%b", appToken,
+                                isHidden(), isFreezingScreen());
+            stopFreezingScreen(true, force);
         }
     }
 
-    public void reportFullyDrawnLocked(boolean restoredFromBundle) {
+    void reportFullyDrawnLocked(boolean restoredFromBundle) {
         final WindowingModeTransitionInfoSnapshot info = mStackSupervisor
                 .getActivityMetricsLogger().logAppTransitionReportedDrawn(this, restoredFromBundle);
         if (info != null) {
@@ -3247,74 +3109,42 @@
         }
     }
 
-    /**
-     * Called when the starting window for this container is drawn.
-     */
-    public void onStartingWindowDrawn(long timestamp) {
-        synchronized (mAtmService.mGlobalLock) {
-            mStackSupervisor.getActivityMetricsLogger().notifyStartingWindowDrawn(
-                    getWindowingMode(), timestamp);
-        }
-    }
-
     /** Called when the windows associated app window container are drawn. */
-    public void onWindowsDrawn(boolean drawn, long timestamp) {
-        synchronized (mAtmService.mGlobalLock) {
-            mDrawn = drawn;
-            if (!drawn) {
-                return;
-            }
-            final WindowingModeTransitionInfoSnapshot info = mStackSupervisor
-                    .getActivityMetricsLogger().notifyWindowsDrawn(getWindowingMode(), timestamp);
-            final int windowsDrawnDelayMs = info != null ? info.windowsDrawnDelayMs : INVALID_DELAY;
-            final @LaunchState int launchState = info != null ? info.getLaunchState() : -1;
-            mStackSupervisor.reportActivityLaunchedLocked(false /* timeout */, this,
-                    windowsDrawnDelayMs, launchState);
-            mStackSupervisor.stopWaitingForActivityVisible(this);
-            finishLaunchTickingLocked();
-            if (task != null) {
-                task.hasBeenVisible = true;
-            }
+    void onWindowsDrawn(boolean drawn, long timestamp) {
+        mDrawn = drawn;
+        if (!drawn) {
+            return;
+        }
+        final WindowingModeTransitionInfoSnapshot info = mStackSupervisor
+                .getActivityMetricsLogger().notifyWindowsDrawn(getWindowingMode(), timestamp);
+        final int windowsDrawnDelayMs = info != null ? info.windowsDrawnDelayMs : INVALID_DELAY;
+        final @LaunchState int launchState = info != null ? info.getLaunchState() : -1;
+        mStackSupervisor.reportActivityLaunchedLocked(false /* timeout */, this,
+                windowsDrawnDelayMs, launchState);
+        mStackSupervisor.stopWaitingForActivityVisible(this);
+        finishLaunchTickingLocked();
+        if (task != null) {
+            task.hasBeenVisible = true;
         }
     }
 
     /** Called when the windows associated app window container are visible. */
-    public void onWindowsVisible() {
-        synchronized (mAtmService.mGlobalLock) {
-            mStackSupervisor.stopWaitingForActivityVisible(this);
-            if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsVisibleLocked(): " + this);
-            if (!nowVisible) {
-                nowVisible = true;
-                lastVisibleTime = SystemClock.uptimeMillis();
-                mAtmService.scheduleAppGcsLocked();
-            }
+    void onWindowsVisible() {
+        super.onWindowsVisible();
+        mStackSupervisor.stopWaitingForActivityVisible(this);
+        if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsVisibleLocked(): " + this);
+        if (!nowVisible) {
+            nowVisible = true;
+            lastVisibleTime = SystemClock.uptimeMillis();
+            mAtmService.scheduleAppGcsLocked();
         }
     }
 
     /** Called when the windows associated app window container are no longer visible. */
-    public void onWindowsGone() {
-        synchronized (mAtmService.mGlobalLock) {
-            if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsGone(): " + this);
-            nowVisible = false;
-        }
-    }
-
-    void onAnimationFinished() {
-        if (mRootActivityContainer.allResumedActivitiesIdle()
-                || mStackSupervisor.isStoppingNoHistoryActivity()) {
-            // If all activities are already idle or there is an activity that must be
-            // stopped immediately after visible, then we now need to make sure we perform
-            // the full stop of this activity. This is because we won't do that while they are still
-            // waiting for the animation to finish.
-            if (mStackSupervisor.mStoppingActivities.contains(this)) {
-                mStackSupervisor.scheduleIdleLocked();
-            }
-        } else {
-            // Instead of doing the full stop routine here, let's just hide any activities
-            // we now can, and let them stop when the normal idle happens.
-            mStackSupervisor.processStoppingActivitiesLocked(null /* idleActivity */,
-                    false /* remove */, true /* processPausingActivities */);
-        }
+    void onWindowsGone() {
+        super.onWindowsGone();
+        if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsGone(): " + this);
+        nowVisible = false;
     }
 
     /**
@@ -3419,7 +3249,7 @@
                 || (onlyRoot && activityNdx > task.findRootIndex(true /* effectiveRoot */))) {
             return INVALID_TASK_ID;
         }
-        return task.taskId;
+        return task.mTaskId;
     }
 
     static ActivityRecord isInStackLocked(IBinder token) {
@@ -3474,8 +3304,8 @@
         Bitmap icon;
         if (_taskDescription.getIconFilename() == null &&
                 (icon = _taskDescription.getIcon()) != null) {
-            final String iconFilename = createImageFilename(createTime, task.taskId);
-            final File iconFile = new File(TaskPersister.getUserImagesDir(task.userId),
+            final String iconFilename = createImageFilename(createTime, task.mTaskId);
+            final File iconFile = new File(TaskPersister.getUserImagesDir(task.mUserId),
                     iconFilename);
             final String iconFilePath = iconFile.getAbsolutePath();
             mAtmService.getRecentTasks().saveImage(icon, iconFilePath);
@@ -3500,9 +3330,6 @@
 
     void showStartingWindow(ActivityRecord prev, boolean newTask, boolean taskSwitch,
             boolean fromRecents) {
-        if (mAppWindowToken == null) {
-            return;
-        }
         if (mTaskOverlay) {
             // We don't show starting window for overlay activities.
             return;
@@ -3530,26 +3357,20 @@
         if (mStartingWindowState == STARTING_WINDOW_SHOWN && behindFullscreenActivity) {
             if (DEBUG_VISIBILITY) Slog.w(TAG_VISIBILITY, "Found orphaned starting window " + this);
             mStartingWindowState = STARTING_WINDOW_REMOVED;
-            mAppWindowToken.removeStartingWindow();
+            removeStartingWindow();
         }
     }
 
     void setRequestedOrientation(int requestedOrientation) {
-        setOrientation(requestedOrientation, mayFreezeScreenLocked(app));
+        setOrientation(requestedOrientation, mayFreezeScreenLocked());
         mAtmService.getTaskChangeNotificationController().notifyActivityRequestedOrientationChanged(
-                task.taskId, requestedOrientation);
+                task.mTaskId, requestedOrientation);
     }
 
     private void setOrientation(int requestedOrientation, boolean freezeScreenIfNeeded) {
-        if (mAppWindowToken == null) {
-            Slog.w(TAG_WM,
-                    "Attempted to set orientation of non-existing app token: " + appToken);
-            return;
-        }
-
         final IBinder binder =
                 (freezeScreenIfNeeded && appToken != null) ? appToken.asBinder() : null;
-        mAppWindowToken.setOrientation(requestedOrientation, binder, this);
+        setOrientation(requestedOrientation, binder, this);
 
         // Push the new configuration to the requested app in case where it's not pushed, e.g. when
         // the request is handled at task level with letterbox.
@@ -3559,23 +3380,6 @@
         }
     }
 
-    int getOrientation() {
-        if (mAppWindowToken == null) {
-            return info.screenOrientation;
-        }
-
-        return mAppWindowToken.getOrientationIgnoreVisibility();
-    }
-
-    void setDisablePreviewScreenshots(boolean disable) {
-        if (mAppWindowToken == null) {
-            Slog.w(TAG_WM, "Attempted to set disable screenshots of non-existing app"
-                    + " token: " + appToken);
-            return;
-        }
-        mAppWindowToken.setDisablePreviewScreenshots(disable);
-    }
-
     /**
      * Set the last reported global configuration to the client. Should be called whenever a new
      * global configuration is sent to the client for this activity.
@@ -3598,33 +3402,6 @@
     }
 
     /**
-     * Get the configuration orientation by the requested screen orientation
-     * ({@link ActivityInfo.ScreenOrientation}) of this activity.
-     *
-     * @return orientation in ({@link Configuration#ORIENTATION_LANDSCAPE},
-     *         {@link Configuration#ORIENTATION_PORTRAIT},
-     *         {@link Configuration#ORIENTATION_UNDEFINED}).
-     */
-    int getRequestedConfigurationOrientation() {
-        final int screenOrientation = getOrientation();
-        if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
-            // NOSENSOR means the display's "natural" orientation, so return that.
-            final ActivityDisplay display = getDisplay();
-            if (display != null && display.mDisplayContent != null) {
-                return display.mDisplayContent.getNaturalOrientation();
-            }
-        } else if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
-            // LOCKED means the activity's orientation remains unchanged, so return existing value.
-            return getConfiguration().orientation;
-        } else if (isFixedOrientationLandscape(screenOrientation)) {
-            return ORIENTATION_LANDSCAPE;
-        } else if (isFixedOrientationPortrait(screenOrientation)) {
-            return ORIENTATION_PORTRAIT;
-        }
-        return ORIENTATION_UNDEFINED;
-    }
-
-    /**
      * @return {@code true} if this activity is in size compatibility mode that uses the different
      *         density or bounds from its parent.
      */
@@ -3705,6 +3482,8 @@
     // TODO(b/36505427): Consider moving this method and similar ones to ConfigurationContainer.
     private void updateOverrideConfiguration() {
         final Configuration overrideConfig = mTmpConfig;
+        overrideConfig.setTo(getRequestedOverrideConfiguration());
+
         if (shouldUseSizeCompatMode()) {
             if (mCompatDisplayInsets != null) {
                 // The override configuration is set only once in size compatibility mode.
@@ -3723,7 +3502,6 @@
             // are relative to bounds and density, they will be calculated in
             // {@link TaskRecord#computeConfigResourceOverrides} and the result will also be
             // relatively fixed.
-            overrideConfig.unset();
             overrideConfig.colorMode = parentConfig.colorMode;
             overrideConfig.densityDpi = parentConfig.densityDpi;
             overrideConfig.screenLayout = parentConfig.screenLayout
@@ -3750,7 +3528,6 @@
                 return;
             }
 
-            overrideConfig.unset();
             overrideConfig.windowConfiguration.setBounds(mTmpBounds);
         }
 
@@ -3877,22 +3654,6 @@
             onMergedOverrideConfigurationChanged();
         }
 
-        // TODO(b/80414790): Remove code below after unification.
-        // Same as above it doesn't notify configuration listeners, and consequently AppWindowToken
-        // can't get updated seq number. However WindowState's merged override configuration needs
-        // to have this seq number because that's also used for activity config pushes during layout
-        // traversal. Therefore explicitly update them here.
-        if (mAppWindowToken == null) {
-            return;
-        }
-        final Configuration appWindowTokenRequestedOverrideConfig =
-                mAppWindowToken.getRequestedOverrideConfiguration();
-        if (appWindowTokenRequestedOverrideConfig.seq != getResolvedOverrideConfiguration().seq) {
-            appWindowTokenRequestedOverrideConfig.seq =
-                    getResolvedOverrideConfiguration().seq;
-            mAppWindowToken.onMergedOverrideConfigurationChanged();
-        }
-
         final ActivityDisplay display = getDisplay();
         if (display == null) {
             return;
@@ -3920,7 +3681,7 @@
 
     /** Returns true if the configuration is compatible with this activity. */
     boolean isConfigurationCompatible(Configuration config) {
-        final int orientation = getOrientation();
+        final int orientation = getRequestedOrientation();
         if (isFixedOrientationPortrait(orientation)
                 && config.orientation != ORIENTATION_PORTRAIT) {
             return false;
@@ -4153,7 +3914,7 @@
         if (shouldRelaunchLocked(changes, mTmpConfig) || forceNewConfig) {
             // Aha, the activity isn't handling the change, so DIE DIE DIE.
             configChangeFlags |= changes;
-            startFreezingScreenLocked(app, globalChanges);
+            startFreezingScreenLocked(globalChanges);
             forceNewConfig = false;
             preserveWindow &= isResizeOnlyChange(changes);
             final boolean hasResizeChange = hasResizeChange(changes & ~info.getRealConfigChanged());
@@ -4309,18 +4070,16 @@
                         + " preserveWindow=" + preserveWindow);
         EventLog.writeEvent(andResume ? AM_RELAUNCH_RESUME_ACTIVITY
                         : AM_RELAUNCH_ACTIVITY, mUserId, System.identityHashCode(this),
-                task.taskId, shortComponentName);
+                task.mTaskId, shortComponentName);
 
-        startFreezingScreenLocked(app, 0);
+        startFreezingScreenLocked(0);
 
         try {
             if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_SWITCH,
                     "Moving to " + (andResume ? "RESUMED" : "PAUSED") + " Relaunching " + this
                             + " callers=" + Debug.getCallers(6));
             forceNewConfig = false;
-            if (mAppWindowToken != null) {
-                mAppWindowToken.startRelaunching();
-            }
+            startRelaunching();
             final ClientTransactionItem callbackItem = ActivityRelaunchItem.obtain(pendingResults,
                     pendingNewIntents, configChangeFlags,
                     new MergedConfiguration(mAtmService.getGlobalConfiguration(),
@@ -4409,8 +4168,8 @@
             return;
         }
 
-        if (mAppWindowToken != null) {
-            mAppWindowToken.startFreezingScreen();
+        if (getParent() != null) {
+            startFreezingScreen();
         }
         // The process will be killed until the activity reports stopped with saved state (see
         // {@link ActivityTaskManagerService.activityStopped}).
@@ -4578,67 +4337,24 @@
         return info.applicationInfo.uid;
     }
 
-    void setShowWhenLocked(boolean showWhenLocked) {
-        mShowWhenLocked = showWhenLocked;
-        mRootActivityContainer.ensureActivitiesVisible(null, 0 /* configChanges */,
-                false /* preserveWindows */);
-    }
-
-    void setInheritShowWhenLocked(boolean inheritShowWhenLocked) {
-        mInheritShownWhenLocked = inheritShowWhenLocked;
-        mRootActivityContainer.ensureActivitiesVisible(null, 0, false);
-    }
-
-    /**
-     * @return true if the activity windowing mode is not
-     *         {@link android.app.WindowConfiguration#WINDOWING_MODE_PINNED} and a) activity
-     *         contains windows that have {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED} set or if the
-     *         activity has set {@link #mShowWhenLocked}, or b) if the activity has set
-     *         {@link #mInheritShownWhenLocked} and the activity behind this satisfies the
-     *         conditions a) above.
-     *         Multi-windowing mode will be exited if true is returned.
-     */
-    boolean canShowWhenLocked() {
-        if (!inPinnedWindowingMode() && (mShowWhenLocked
-                || (mAppWindowToken != null && mAppWindowToken.containsShowWhenLockedWindow()))) {
-            return true;
-        } else if (mInheritShownWhenLocked) {
-            ActivityRecord r = getActivityBelow();
-            return r != null && !r.inPinnedWindowingMode() && (r.mShowWhenLocked
-                    || (r.mAppWindowToken != null
-                        && r.mAppWindowToken.containsShowWhenLockedWindow()));
-        } else {
-            return false;
-        }
-    }
-
-    /**
-     * @return an {@link ActivityRecord} of the activity below this activity, or {@code null} if no
-     * such activity exists.
-     */
-    @Nullable
-    private ActivityRecord getActivityBelow() {
-        final int pos = task.mActivities.indexOf(this);
-        if (pos == -1) {
-            throw new IllegalStateException("Activity not found in its task");
-        }
-        return pos == 0 ? null : task.getChildAt(pos - 1);
-    }
-
-    void setTurnScreenOn(boolean turnScreenOn) {
-        mTurnScreenOn = turnScreenOn;
+    @Override
+    int getPid() {
+        return app != null ? app.getPid() : 0;
     }
 
     /**
      * Determines whether this ActivityRecord can turn the screen on. It checks whether the flag
-     * {@link #mTurnScreenOn} is set and checks whether the ActivityRecord should be visible
-     * depending on Keyguard state
+     * {@link AppWindowToken#getTurnScreenOnFlag} is set and checks whether the ActivityRecord
+     * should be visible depending on Keyguard state
      *
      * @return true if the screen can be turned on, false otherwise.
      */
     boolean canTurnScreenOn() {
+        if (!getTurnScreenOnFlag()) {
+            return false;
+        }
         final ActivityStack stack = getActivityStack();
-        return mTurnScreenOn && stack != null &&
+        return stack != null &&
                 stack.checkKeyguardVisibility(this, true /* shouldBeVisible */, true /* isTop */);
     }
 
@@ -4652,10 +4368,6 @@
         return app == null || app.updateTopResumingActivityInProcessIfNeeded(this);
     }
 
-    boolean getTurnScreenOnFlag() {
-        return mTurnScreenOn;
-    }
-
     boolean isTopRunningActivity() {
         return mRootActivityContainer.topRunningActivity() == this;
     }
@@ -4690,20 +4402,11 @@
         return task.getChildAt(0) == this;
     }
 
-    void registerRemoteAnimations(RemoteAnimationDefinition definition) {
-        if (mAppWindowToken == null) {
-            Slog.w(TAG_WM, "Attempted to register remote animations with non-existing app"
-                    + " token: " + appToken);
-            return;
-        }
-        mAppWindowToken.registerRemoteAnimations(definition);
-    }
-
     @Override
     public String toString() {
         if (stringName != null) {
-            return stringName + " t" + (task == null ? INVALID_TASK_ID : task.taskId) +
-                    (finishing ? " f}" : "}");
+            return stringName + " t" + (task == null ? INVALID_TASK_ID : task.mTaskId) +
+                    (finishing ? " f}" : "") + (mIsExiting ? " mIsExiting=" : "") + "}";
         }
         StringBuilder sb = new StringBuilder(128);
         sb.append("ActivityRecord{");
@@ -4713,15 +4416,7 @@
         sb.append(' ');
         sb.append(intent.getComponent().flattenToShortString());
         stringName = sb.toString();
-        return toString();
-    }
-
-    void writeIdentifierToProto(ProtoOutputStream proto, long fieldId) {
-        final long token = proto.start(fieldId);
-        proto.write(HASH_CODE, System.identityHashCode(this));
-        proto.write(USER_ID, mUserId);
-        proto.write(TITLE, intent.getComponent().flattenToShortString());
-        proto.end(token);
+        return stringName;
     }
 
     /**
@@ -4729,7 +4424,7 @@
      * {@code ActivityRecordProto} is the outer-most proto data.
      */
     void writeToProto(ProtoOutputStream proto) {
-        super.writeToProto(proto, CONFIGURATION_CONTAINER, WindowTraceLogLevel.ALL);
+        super.writeToProto(proto, APP_WINDOW_TOKEN, WindowTraceLogLevel.ALL);
         writeIdentifierToProto(proto, IDENTIFIER);
         proto.write(STATE, mState.toString());
         proto.write(VISIBLE, visible);
@@ -4737,7 +4432,7 @@
         if (hasProcess()) {
             proto.write(PROC_ID, app.getPid());
         }
-        proto.write(TRANSLUCENT, !fullscreen);
+        proto.write(TRANSLUCENT, !occludesParent());
     }
 
     public void writeToProto(ProtoOutputStream proto, long fieldId) {
diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java
index 2ab3e01..5959254 100644
--- a/services/core/java/com/android/server/wm/ActivityStack.java
+++ b/services/core/java/com/android/server/wm/ActivityStack.java
@@ -775,7 +775,7 @@
             // multi-window mode.
             final String packageName = topActivity.info.applicationInfo.packageName;
             mService.getTaskChangeNotificationController().notifyActivityForcedResizable(
-                    topTask.taskId, FORCED_RESIZEABLE_REASON_SPLIT_SCREEN, packageName);
+                    topTask.mTaskId, FORCED_RESIZEABLE_REASON_SPLIT_SCREEN, packageName);
         }
 
         mService.deferWindowLayout();
@@ -1114,7 +1114,7 @@
     final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
         for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
             TaskRecord task = mTaskHistory.get(taskNdx);
-            if (task.taskId == taskId) {
+            if (task.mTaskId == taskId) {
                 continue;
             }
             ArrayList<ActivityRecord> activities = task.mActivities;
@@ -1150,7 +1150,7 @@
     TaskRecord taskForIdLocked(int id) {
         for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
             final TaskRecord task = mTaskHistory.get(taskNdx);
-            if (task.taskId == id) {
+            if (task.mTaskId == id) {
                 return task;
             }
         }
@@ -1345,7 +1345,7 @@
                 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session");
                 continue;
             }
-            if (task.userId != userId) {
+            if (task.mUserId != userId) {
                 // Looking for a different task.
                 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": different user");
                 continue;
@@ -1896,7 +1896,7 @@
                     continue;
                 }
 
-                if (r.fullscreen || r.hasWallpaper) {
+                if (r.occludesParent() || r.hasWallpaper) {
                     // Stack isn't translucent if it has at least one fullscreen activity
                     // that is visible.
                     return false;
@@ -2106,7 +2106,11 @@
             boolean aboveTop = top != null;
             final boolean stackShouldBeVisible = shouldBeVisible(starting);
             boolean behindFullscreenActivity = !stackShouldBeVisible;
-            final boolean resumeTopActivity = isFocusable() && isInStackLocked(starting) == null;
+            // We should not resume activities that being launched behind because these
+            // activities are actually behind other fullscreen activities, but still required
+            // to be visible (such as performing Recents animation).
+            final boolean resumeTopActivity = isFocusable() && isInStackLocked(starting) == null
+                    && top != null && !top.mLaunchTaskBehind;
             for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
                 final TaskRecord task = mTaskHistory.get(taskNdx);
                 final ArrayList<ActivityRecord> activities = task.mActivities;
@@ -2255,8 +2259,7 @@
                 .isKeyguardOrAodShowing(displayId);
         final boolean keyguardLocked = mStackSupervisor.getKeyguardController().isKeyguardLocked();
         final boolean showWhenLocked = r.canShowWhenLocked();
-        final boolean dismissKeyguard = r.mAppWindowToken != null
-                && r.mAppWindowToken.containsDismissKeyguardWindow();
+        final boolean dismissKeyguard = r.containsDismissKeyguardWindow();
         if (shouldBeVisible) {
             if (dismissKeyguard && mTopDismissingKeyguardActivity == null) {
                 mTopDismissingKeyguardActivity = r;
@@ -2325,18 +2328,14 @@
             // get it started and resume if no other stack in this stack is resumed.
             if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Start and freeze screen for " + r);
             if (r != starting) {
-                r.startFreezingScreenLocked(r.app, configChanges);
+                r.startFreezingScreenLocked(configChanges);
             }
             if (!r.visible || r.mLaunchTaskBehind) {
                 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Starting and making visible: " + r);
                 r.setVisible(true);
             }
             if (r != starting) {
-                // We should not resume activities that being launched behind because these
-                // activities are actually behind other fullscreen activities, but still required
-                // to be visible (such as performing Recents animation).
-                mStackSupervisor.startSpecificActivityLocked(r, andResume && !r.mLaunchTaskBehind,
-                        true /* checkConfig */);
+                mStackSupervisor.startSpecificActivityLocked(r, andResume, true /* checkConfig */);
                 return true;
             }
         }
@@ -2345,7 +2344,7 @@
 
     private boolean updateBehindFullscreen(boolean stackInvisible, boolean behindFullscreenActivity,
             ActivityRecord r) {
-        if (r.fullscreen) {
+        if (r.occludesParent()) {
             if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Fullscreen: at " + r
                         + " stackInvisible=" + stackInvisible
                         + " behindFullscreenActivity=" + behindFullscreenActivity);
@@ -2431,12 +2430,12 @@
                     if (r == topActivity) {
                         aboveTop = false;
                     }
-                    behindFullscreenActivity |= r.fullscreen;
+                    behindFullscreenActivity |= r.occludesParent();
                     continue;
                 }
 
                 r.removeOrphanedStartingWindow(behindFullscreenActivity);
-                behindFullscreenActivity |= r.fullscreen;
+                behindFullscreenActivity |= r.occludesParent();
             }
         }
     }
@@ -2566,8 +2565,7 @@
                 final boolean canShowWhenLocked = !mTopActivityOccludesKeyguard
                         && next.canShowWhenLocked();
                 final boolean mayDismissKeyguard = mTopDismissingKeyguardActivity != next
-                        && next.mAppWindowToken != null
-                        && next.mAppWindowToken.containsDismissKeyguardWindow();
+                        && next.containsDismissKeyguardWindow();
 
                 if (canShowWhenLocked || mayDismissKeyguard) {
                     ensureActivitiesVisibleLocked(null /* starting */, 0 /* configChanges */,
@@ -2776,7 +2774,7 @@
             final boolean lastActivityTranslucent = lastFocusedStack != null
                     && (lastFocusedStack.inMultiWindowMode()
                     || (lastFocusedStack.mLastPausedActivity != null
-                    && !lastFocusedStack.mLastPausedActivity.fullscreen));
+                    && !lastFocusedStack.mLastPausedActivity.occludesParent()));
 
             // This activity is now becoming visible.
             if (!next.visible || next.stopped || lastActivityTranslucent) {
@@ -2865,7 +2863,7 @@
                 next.notifyAppResumed(next.stopped);
 
                 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.mUserId,
-                        System.identityHashCode(next), next.getTaskRecord().taskId,
+                        System.identityHashCode(next), next.getTaskRecord().mTaskId,
                         next.shortComponentName);
 
                 next.sleeping = false;
@@ -2975,7 +2973,7 @@
         // The task can't be shown, put non-current user tasks below current user tasks.
         while (maxPosition > 0) {
             final TaskRecord tmpTask = mTaskHistory.get(maxPosition - 1);
-            if (!mStackSupervisor.isCurrentProfileLocked(tmpTask.userId)
+            if (!mStackSupervisor.isCurrentProfileLocked(tmpTask.mUserId)
                     || tmpTask.topRunningActivityLocked() == null) {
                 break;
             }
@@ -3028,7 +3026,7 @@
     void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
             boolean newTask, boolean keepCurTransition, ActivityOptions options) {
         TaskRecord rTask = r.getTaskRecord();
-        final int taskId = rTask.taskId;
+        final int taskId = rTask.mTaskId;
         final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();
         // mLaunchTaskBehind tasks get placed at the back of the task stack.
         if (!r.mLaunchTaskBehind && allowMoveToFront
@@ -3055,7 +3053,7 @@
                     if (!startIt) {
                         if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
                                 + task, new RuntimeException("here").fillInStackTrace());
-                        r.createAppWindowToken();
+                        r.setTask(rTask);
                         ActivityOptions.abort(options);
                         return;
                     }
@@ -3082,12 +3080,7 @@
         // Slot the activity into the history stack and proceed
         if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
                 new RuntimeException("here").fillInStackTrace());
-        // TODO: Need to investigate if it is okay for the controller to already be created by the
-        // time we get to this point. I think it is, but need to double check.
-        // Use test in b/34179495 to trace the call path.
-        if (r.mAppWindowToken == null) {
-            r.createAppWindowToken();
-        }
+        r.setTask(task);
 
         // The transition animation and starting window are not needed if {@code allowMoveToFront}
         // is false, because the activity won't be visible.
@@ -3944,7 +3937,7 @@
                 if (r.finishing) {
                     continue;
                 }
-                if (r.fullscreen) {
+                if (r.occludesParent()) {
                     lastIsOpaque = true;
                 }
                 if (owner != null && r.app != owner) {
@@ -4105,7 +4098,7 @@
                             Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
                             EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
                                     r.mUserId, System.identityHashCode(r),
-                                    r.getTaskRecord().taskId, r.shortComponentName,
+                                    r.getTaskRecord().mTaskId, r.shortComponentName,
                                     "proc died without state saved");
                         }
                     } else {
@@ -4230,7 +4223,7 @@
             }
 
             mRootActivityContainer.resumeFocusedStacksTopActivities();
-            EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, tr.taskId);
+            EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.mUserId, tr.mTaskId);
             mService.getTaskChangeNotificationController().notifyTaskMovedToFront(tr.getTaskInfo());
         } finally {
             getDisplay().continueUpdateImeTarget();
@@ -4335,7 +4328,7 @@
                 final ActivityRecord r = activities.get(activityIndex);
                 updatedConfig |= r.ensureActivityConfiguration(0 /* globalChanges */,
                         preserveWindow);
-                if (r.fullscreen) {
+                if (r.occludesParent()) {
                     behindFullscreen = true;
                     break;
                 }
@@ -4438,7 +4431,7 @@
                 if (r.appToken == token) {
                     return true;
                 }
-                if (r.fullscreen && !r.finishing) {
+                if (r.occludesParent() && !r.finishing) {
                     return false;
                 }
             }
@@ -4527,7 +4520,7 @@
                 continue;
             }
             if (task.effectiveUid != callingUid) {
-                if (task.userId != userId && !crossUser && !profileIds.contains(task.userId)) {
+                if (task.mUserId != userId && !crossUser && !profileIds.contains(task.mUserId)) {
                     // Skip if the caller does not have cross user permission or cannot access
                     // the task's profile
                     continue;
@@ -4552,7 +4545,7 @@
                 // For the focused stack top task, update the last stack active time so that it can
                 // be used to determine the order of the tasks (it may not be set for newly created
                 // tasks)
-                task.lastActiveTime = SystemClock.elapsedRealtime();
+                task.touchActiveTime();
                 topTask = false;
             }
             tasksOut.add(task);
@@ -4661,7 +4654,7 @@
             if (needSep) {
                 pw.println("");
             }
-            pw.println(prefix + "Task id #" + task.taskId);
+            pw.println(prefix + "Task id #" + task.mTaskId);
             pw.println(prefix + "mBounds=" + task.getRequestedOverrideBounds());
             pw.println(prefix + "mMinWidth=" + task.mMinWidth);
             pw.println(prefix + "mMinHeight=" + task.mMinHeight);
@@ -4718,8 +4711,7 @@
                 if (a.info.packageName.equals(packageName)) {
                     a.forceNewConfig = true;
                     if (starting != null && a == starting && a.visible) {
-                        a.startFreezingScreenLocked(starting.app,
-                                CONFIG_SCREEN_LAYOUT);
+                        a.startFreezingScreenLocked(CONFIG_SCREEN_LAYOUT);
                     }
                 }
             }
@@ -4740,7 +4732,7 @@
         final boolean removed = mTaskHistory.remove(task);
 
         if (removed) {
-            EventLog.writeEvent(EventLogTags.AM_REMOVE_TASK, task.taskId, getStackId());
+            EventLog.writeEvent(EventLogTags.AM_REMOVE_TASK, task.mTaskId, getStackId());
         }
 
         removeActivitiesFromLRUList(task);
@@ -4892,7 +4884,7 @@
             mStackSupervisor.scheduleUpdatePictureInPictureModeIfNeeded(task, prevStack);
         } else if (task.voiceSession != null) {
             try {
-                task.voiceSession.taskStarted(task.intent, task.taskId);
+                task.voiceSession.taskStarted(task.intent, task.mTaskId);
             } catch (RemoteException e) {
             }
         }
@@ -4950,7 +4942,7 @@
             if (top != null && !top.isConfigurationCompatible(parentConfig)) {
                 // The final orientation of this activity will change after moving to full screen.
                 // Start freezing screen here to prevent showing a temporary full screen window.
-                top.startFreezingScreenLocked(top.app, CONFIG_SCREEN_LAYOUT);
+                top.startFreezingScreenLocked(CONFIG_SCREEN_LAYOUT);
                 mService.moveTasksToFullscreenStack(mStackId, true /* onTop */);
                 return;
             }
diff --git a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
index d151f86..f1284d81 100644
--- a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
@@ -821,7 +821,7 @@
                                 + " with results=" + results + " newIntents=" + newIntents
                                 + " andResume=" + andResume);
                 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.mUserId,
-                        System.identityHashCode(r), task.taskId, r.shortComponentName);
+                        System.identityHashCode(r), task.mTaskId, r.shortComponentName);
                 if (r.isActivityTypeHome()) {
                     // Home process is the root process of the task.
                     updateHomeProcess(task.mActivities.get(0).app);
@@ -1765,7 +1765,7 @@
             moveTasksToFullscreenStackLocked(stack, !ON_TOP);
         } else {
             for (int i = tasks.size() - 1; i >= 0; i--) {
-                removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */,
+                removeTaskByIdLocked(tasks.get(i).mTaskId, true /* killProcess */,
                         REMOVE_FROM_RECENTS, "remove-stack");
             }
         }
@@ -1817,7 +1817,7 @@
 
         // Find any running services associated with this app and stop if needed.
         final Message msg = PooledLambda.obtainMessage(ActivityManagerInternal::cleanUpServices,
-                mService.mAmInternal, tr.userId, component, new Intent(tr.getBaseIntent()));
+                mService.mAmInternal, tr.mUserId, component, new Intent(tr.getBaseIntent()));
         mService.mH.sendMessage(msg);
 
         if (!killProcess) {
@@ -1834,7 +1834,7 @@
             SparseArray<WindowProcessController> uids = pmap.valueAt(i);
             for (int j = 0; j < uids.size(); j++) {
                 WindowProcessController proc = uids.valueAt(j);
-                if (proc.mUserId != tr.userId) {
+                if (proc.mUserId != tr.mUserId) {
                     // Don't kill process for a different user.
                     continue;
                 }
@@ -1901,7 +1901,7 @@
                 "Added restored task=" + task + " to stack=" + stack);
         final ArrayList<ActivityRecord> activities = task.mActivities;
         for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
-            activities.get(activityNdx).createAppWindowToken();
+            activities.get(activityNdx).setTask(task);
         }
         return true;
     }
@@ -1916,7 +1916,7 @@
         if (wasTrimmed) {
             // Task was trimmed from the recent tasks list -- remove the active task record as well
             // since the user won't really be able to go back to it
-            removeTaskByIdLocked(task.taskId, killProcess, false /* removeFromRecents */,
+            removeTaskByIdLocked(task.mTaskId, killProcess, false /* removeFromRecents */,
                     "recent-task-trimmed");
         }
         task.removedFromRecents();
@@ -2123,6 +2123,7 @@
         return false;
     }
 
+    // TODO: Change method name to reflect what it actually does.
     final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
             boolean remove, boolean processPausingActivities) {
         ArrayList<ActivityRecord> stops = null;
@@ -2131,7 +2132,7 @@
         for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
             ActivityRecord s = mStoppingActivities.get(activityNdx);
 
-            final boolean animating = s.mAppWindowToken.isSelfAnimating();
+            final boolean animating = s.isSelfAnimating();
 
             if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
                     + " animating=" + animating + " finishing=" + s.finishing);
@@ -2476,15 +2477,13 @@
             return;
         }
         mService.getTaskChangeNotificationController().notifyActivityForcedResizable(
-                task.taskId, reason, topActivity.info.applicationInfo.packageName);
+                task.mTaskId, reason, topActivity.info.applicationInfo.packageName);
     }
 
     void activityRelaunchedLocked(IBinder token) {
         final ActivityRecord r = ActivityRecord.isInStackLocked(token);
         if (r != null) {
-            if (r.mAppWindowToken != null) {
-                r.mAppWindowToken.finishRelaunching();
-            }
+            r.finishRelaunching();
             if (r.getActivityStack().shouldSleepOrShutDownActivities()) {
                 r.setSleeping(true, true);
             }
@@ -2700,7 +2699,7 @@
      * @param task The task to put into resizing mode
      */
     void setResizingDuringAnimation(TaskRecord task) {
-        mResizingTasksDuringAnimation.add(task.taskId);
+        mResizingTasksDuringAnimation.add(task.mTaskId);
         task.setTaskDockedResizing(true);
     }
 
@@ -2762,7 +2761,7 @@
 
             // If the user must confirm credentials (e.g. when first launching a work app and the
             // Work Challenge is present) let startActivityInPackage handle the intercepting.
-            if (!mService.mAmInternal.shouldConfirmCredentials(task.userId)
+            if (!mService.mAmInternal.shouldConfirmCredentials(task.mUserId)
                     && task.getRootActivity() != null) {
                 final ActivityRecord targetActivity = task.getTopActivity();
 
@@ -2771,7 +2770,7 @@
                 mActivityMetricsLogger.notifyActivityLaunching(task.intent);
                 try {
                     mService.moveTaskToFrontLocked(null /* appThread */, null /* callingPackage */,
-                            task.taskId, 0, options, true /* fromRecents */);
+                            task.mTaskId, 0, options, true /* fromRecents */);
                     // Apply options to prevent pendingOptions be taken by client to make sure
                     // the override pending app transition will be applied immediately.
                     targetActivity.applyOptionsLocked();
@@ -2788,7 +2787,7 @@
             callingPackage = task.mCallingPackage;
             intent = task.intent;
             intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
-            userId = task.userId;
+            userId = task.mUserId;
             return mService.getActivityStartController().startActivityInPackage(
                     task.mCallingUid, callingPid, callingUid, callingPackage, intent, null, null,
                     null, 0, 0, options, userId, task, "startActivityFromRecents",
diff --git a/services/core/java/com/android/server/wm/ActivityStartController.java b/services/core/java/com/android/server/wm/ActivityStartController.java
index 919141c..6ee64f3 100644
--- a/services/core/java/com/android/server/wm/ActivityStartController.java
+++ b/services/core/java/com/android/server/wm/ActivityStartController.java
@@ -386,6 +386,8 @@
                     throw new IllegalArgumentException("File descriptors passed in Intent");
                 }
 
+                // Get the flag earlier because the intent may be modified in resolveActivity below.
+                final boolean componentSpecified = intent.getComponent() != null;
                 // Don't modify the client's object!
                 intent = new Intent(intent);
 
@@ -409,7 +411,6 @@
                         .setCaller(caller)
                         .setResolvedType(resolvedTypes[i])
                         .setActivityInfo(aInfo)
-                        .setResultTo(resultTo)
                         .setRequestCode(-1)
                         .setCallingPid(callingPid)
                         .setCallingUid(callingUid)
@@ -417,7 +418,7 @@
                         .setRealCallingPid(realCallingPid)
                         .setRealCallingUid(realCallingUid)
                         .setActivityOptions(checkedOptions)
-                        .setComponentSpecified(intent.getComponent() != null)
+                        .setComponentSpecified(componentSpecified)
 
                         // Top activity decides on animation being run, so we allow only for the
                         // top one as otherwise an activity below might consume it.
@@ -430,7 +431,8 @@
             // Lock the loop to ensure the activities launched in a sequence.
             synchronized (mService.mGlobalLock) {
                 for (int i = 0; i < starters.length; i++) {
-                    final int startResult = starters[i].setOutActivity(outActivity).execute();
+                    final int startResult = starters[i].setResultTo(resultTo)
+                            .setOutActivity(outActivity).execute();
                     if (startResult < START_SUCCESS) {
                         // Abort by error result and recycle unused starters.
                         for (int j = i + 1; j < starters.length; j++) {
diff --git a/services/core/java/com/android/server/wm/ActivityStartInterceptor.java b/services/core/java/com/android/server/wm/ActivityStartInterceptor.java
index 9d08e10..effd154a 100644
--- a/services/core/java/com/android/server/wm/ActivityStartInterceptor.java
+++ b/services/core/java/com/android/server/wm/ActivityStartInterceptor.java
@@ -249,7 +249,8 @@
         if (PLATFORM_PACKAGE_NAME.equals(suspendingPackage)) {
             return interceptSuspendedByAdminPackage();
         }
-        final SuspendDialogInfo dialogInfo = pmi.getSuspendedDialogInfo(suspendedPackage, mUserId);
+        final SuspendDialogInfo dialogInfo = pmi.getSuspendedDialogInfo(suspendedPackage,
+                suspendingPackage, mUserId);
         mIntent = SuspendedAppActivity.createSuspendedAppInterceptIntent(suspendedPackage,
                 suspendingPackage, dialogInfo, mUserId);
         mCallingPid = mRealCallingPid;
@@ -273,7 +274,7 @@
         // ConfirmCredentials intent and unassign it, as otherwise the task will move to
         // front even if ConfirmCredentials is cancelled.
         if (mInTask != null) {
-            mIntent.putExtra(EXTRA_TASK_ID, mInTask.taskId);
+            mIntent.putExtra(EXTRA_TASK_ID, mInTask.mTaskId);
             mInTask = null;
         }
         if (mActivityOptions == null) {
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index 47be792..9397893 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -1552,12 +1552,12 @@
                 mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.mUserId);
         mService.getPackageManagerInternalLocked().grantImplicitAccess(
                 mStartActivity.mUserId, mIntent,
-                UserHandle.getAppId(mCallingUid),
+                mCallingUid,
                 UserHandle.getAppId(mStartActivity.info.applicationInfo.uid)
         );
         if (newTask) {
             EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, mStartActivity.mUserId,
-                    mStartActivity.getTaskRecord().taskId);
+                    mStartActivity.getTaskRecord().mTaskId);
         }
         mStartActivity.logStartActivity(
                 EventLogTags.AM_CREATE_ACTIVITY, mStartActivity.getTaskRecord());
@@ -1684,14 +1684,16 @@
                         == (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                         && mLaunchMode == LAUNCH_MULTIPLE;
 
-        // If mStartActivity does not have a task associated with it, associate it with the
-        // reused activity's task. Do not do so if we're clearing top and resetting for a
-        // standard launchMode activity.
-        if (mStartActivity.getTaskRecord() == null && !clearTopAndResetStandardLaunchMode) {
-            mStartActivity.setTask(targetTask);
-        }
-
+        boolean clearTaskForReuse = false;
         if (reusedActivity != null) {
+            // If mStartActivity does not have a task associated with it, associate it with the
+            // reused activity's task. Do not do so if we're clearing top and resetting for a
+            // standard launchMode activity.
+            if (mStartActivity.getTaskRecord() == null && !clearTopAndResetStandardLaunchMode) {
+                mStartActivity.setTaskForReuse(reusedActivity.getTaskRecord());
+                clearTaskForReuse = true;
+            }
+
             if (targetTask.intent == null) {
                 // This task was started because of movement of the activity based on
                 // affinity...
@@ -1739,11 +1741,23 @@
 
         complyActivityFlags(targetTask, reusedActivity);
 
+        if (clearTaskForReuse) {
+            // Clear task for re-use so later code to methods
+            // {@link #setTaskFromReuseOrCreateNewTask}, {@link #setTaskFromSourceRecord}, or
+            // {@link #setTaskFromInTask} can parent it to the task.
+            mStartActivity.setTaskForReuse(null);
+        }
+
         if (mAddingToTask) {
             return START_SUCCESS;
         }
 
-        if (!mMovedToFront && mDoResume) {
+        if (mMovedToFront) {
+            // We moved the task to front, use starting window to hide initial drawn delay.
+            targetTaskTop.showStartingWindow(null /* prev */, false /* newTask */,
+                    true /* taskSwitch */);
+        } else if (mDoResume) {
+            // Make sure the stack and its belonging display are moved to topmost.
             mTargetStack.moveToFront("intentActivityFound");
         }
         // We didn't do anything...  but it was needed (a.k.a., client don't use that intent!)
@@ -2349,11 +2363,6 @@
                 }
 
                 mOptions = null;
-
-                // We are moving a task to the front, use starting window to hide initial drawn
-                // delay.
-                intentActivity.showStartingWindow(null /* prev */, false /* newTask */,
-                        true /* taskSwitch */);
             }
         }
         // Need to update mTargetStack because if task was moved out of it, the original stack may
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index 468a13d..750fc68 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -807,7 +807,7 @@
         mUiHandler = new UiHandler();
         mIntentFirewall = intentFirewall;
         final File systemDir = SystemServiceManager.ensureSystemDir();
-        mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
+        mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
         mCompatModePackages = new CompatModePackages(this, systemDir, mH);
         mPendingIntentController = intentController;
 
@@ -845,6 +845,11 @@
         return supervisor;
     }
 
+    protected AppWarnings createAppWarnings(
+            Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
+        return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
+    }
+
     public void setWindowManager(WindowManagerService wm) {
         synchronized (mGlobalLock) {
             mWindowManager = wm;
@@ -1613,7 +1618,7 @@
                     // because we don't support returning them across task boundaries. Also, to
                     // keep backwards compatibility we remove the task from recents when finishing
                     // task with root activity.
-                    res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
+                    res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
                             finishWithRootActivity, "finish-activity");
                     if (!res) {
                         Slog.i(TAG, "Removing task failed to finish activity");
@@ -1813,11 +1818,9 @@
     @Override
     public int getRequestedOrientation(IBinder token) {
         synchronized (mGlobalLock) {
-            ActivityRecord r = ActivityRecord.isInStackLocked(token);
-            if (r == null) {
-                return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
-            }
-            return r.getOrientation();
+            final ActivityRecord r = ActivityRecord.isInStackLocked(token);
+            return (r != null)
+                    ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
         }
     }
 
@@ -2230,7 +2233,7 @@
             final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
                     MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
             if (tr != null) {
-                return tr.lastTaskDescription;
+                return tr.mTaskDescription;
             }
         }
         return null;
@@ -3029,7 +3032,7 @@
             }
             if (structure != null) {
                 // Pre-fill the task/activity component for all assist data receivers
-                structure.setTaskId(pae.activity.getTaskRecord().taskId);
+                structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
                 structure.setActivityComponent(pae.activity.mActivityComponent);
                 structure.setHomeActivity(pae.isHome);
             }
@@ -3056,7 +3059,7 @@
                 // Caller wants result sent back to them.
                 sendBundle = new Bundle();
                 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
-                        pae.activity.getTaskRecord().taskId);
+                        pae.activity.getTaskRecord().mTaskId);
                 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
                         pae.activity.assistToken);
                 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
@@ -3152,11 +3155,11 @@
                     stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
                     return INVALID_TASK_ID;
                 }
-                task.lastTaskDescription.copyFrom(description);
+                task.mTaskDescription.copyFrom(description);
 
                 // TODO: Send the thumbnail to WM to store it.
 
-                return task.taskId;
+                return task.mTaskId;
             }
         } finally {
             Binder.restoreCallingIdentity(callingIdent);
@@ -4964,8 +4967,8 @@
                 if (lastTask != task) {
                     lastTask = task;
                     pw.print("TASK "); pw.print(lastTask.affinity);
-                    pw.print(" id="); pw.print(lastTask.taskId);
-                    pw.print(" userId="); pw.println(lastTask.userId);
+                    pw.print(" id="); pw.print(lastTask.mTaskId);
+                    pw.print(" userId="); pw.println(lastTask.mUserId);
                     if (dumpAll) {
                         lastTask.dump(pw, "  ");
                     }
diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java
index 66d52cc..93c461f 100644
--- a/services/core/java/com/android/server/wm/AppTransition.java
+++ b/services/core/java/com/android/server/wm/AppTransition.java
@@ -70,8 +70,9 @@
 import static com.android.internal.R.styleable.WindowAnimation_wallpaperOpenExitAnimation;
 import static com.android.server.wm.AppTransitionProto.APP_TRANSITION_STATE;
 import static com.android.server.wm.AppTransitionProto.LAST_USED_APP_TRANSITION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS_ANIM;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
 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.WindowManagerInternal.AppTransitionListener;
@@ -131,6 +132,7 @@
 import com.android.internal.util.DumpUtils.Dump;
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.AttributeCache;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.animation.ClipRectLRAnimation;
 import com.android.server.wm.animation.ClipRectTBAnimation;
 import com.android.server.wm.animation.CurvedTranslateAnimation;
@@ -1630,70 +1632,61 @@
             a = loadAnimationRes(lp, enter
                     ? com.android.internal.R.anim.voice_activity_open_enter
                     : com.android.internal.R.anim.voice_activity_open_exit);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation voice:"
-                    + " anim=" + a + " transit=" + appTransitionToString(transit)
-                    + " isEntrance=" + enter + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation voice: anim=%s transit=%s isEntrance=%b Callers=%s", a,
+                    appTransitionToString(transit), enter, Debug.getCallers(3));
         } else if (isVoiceInteraction && (transit == TRANSIT_ACTIVITY_CLOSE
                 || transit == TRANSIT_TASK_CLOSE
                 || transit == TRANSIT_TASK_TO_BACK)) {
             a = loadAnimationRes(lp, enter
                     ? com.android.internal.R.anim.voice_activity_close_enter
                     : com.android.internal.R.anim.voice_activity_close_exit);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation voice:"
-                    + " anim=" + a + " transit=" + appTransitionToString(transit)
-                    + " isEntrance=" + enter + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation voice: anim=%s transit=%s isEntrance=%b Callers=%s", a,
+                    appTransitionToString(transit), enter, Debug.getCallers(3));
         } else if (transit == TRANSIT_ACTIVITY_RELAUNCH) {
             a = createRelaunchAnimation(frame, insets);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation:"
-                    + " anim=" + a + " nextAppTransition=" + mNextAppTransition
-                    + " transit=" + appTransitionToString(transit)
-                    + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s nextAppTransition=%d transit=%s Callers=%s", a,
+                    mNextAppTransition, appTransitionToString(transit),
+                    Debug.getCallers(3));
         } else if (mNextAppTransitionType == NEXT_TRANSIT_TYPE_CUSTOM) {
             a = loadAnimationRes(mNextAppTransitionPackage, enter ?
                     mNextAppTransitionEnter : mNextAppTransitionExit);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation:"
-                    + " anim=" + a + " nextAppTransition=ANIM_CUSTOM"
-                    + " transit=" + appTransitionToString(transit) + " isEntrance=" + enter
-                    + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s nextAppTransition=ANIM_CUSTOM transit=%s "
+                            + "isEntrance=%b Callers=%s",
+                    a, appTransitionToString(transit), enter, Debug.getCallers(3));
         } else if (mNextAppTransitionType == NEXT_TRANSIT_TYPE_CUSTOM_IN_PLACE) {
             a = loadAnimationRes(mNextAppTransitionPackage, mNextAppTransitionInPlace);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation:"
-                    + " anim=" + a + " nextAppTransition=ANIM_CUSTOM_IN_PLACE"
-                    + " transit=" + appTransitionToString(transit)
-                    + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s nextAppTransition=ANIM_CUSTOM_IN_PLACE "
+                            + "transit=%s Callers=%s",
+                    a, appTransitionToString(transit), Debug.getCallers(3));
         } else if (mNextAppTransitionType == NEXT_TRANSIT_TYPE_CLIP_REVEAL) {
             a = createClipRevealAnimationLocked(transit, enter, frame, displayFrame);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation:"
-                            + " anim=" + a + " nextAppTransition=ANIM_CLIP_REVEAL"
-                            + " transit=" + appTransitionToString(transit)
-                            + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s nextAppTransition=ANIM_CLIP_REVEAL "
+                            + "transit=%s Callers=%s",
+                    a, appTransitionToString(transit), Debug.getCallers(3));
         } else if (mNextAppTransitionType == NEXT_TRANSIT_TYPE_SCALE_UP) {
             a = createScaleUpAnimationLocked(transit, enter, frame);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation:"
-                    + " anim=" + a + " nextAppTransition=ANIM_SCALE_UP"
-                    + " transit=" + appTransitionToString(transit) + " isEntrance=" + enter
-                    + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s nextAppTransition=ANIM_SCALE_UP transit=%s "
+                            + "isEntrance=%s Callers=%s",
+                    a, appTransitionToString(transit), enter, Debug.getCallers(3));
         } else if (mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_SCALE_UP ||
                 mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_SCALE_DOWN) {
             mNextAppTransitionScaleUp =
                     (mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_SCALE_UP);
             a = createThumbnailEnterExitAnimationLocked(getThumbnailTransitionState(enter),
                     frame, transit, taskId);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
-                String animName = mNextAppTransitionScaleUp ?
-                        "ANIM_THUMBNAIL_SCALE_UP" : "ANIM_THUMBNAIL_SCALE_DOWN";
-                Slog.v(TAG, "applyAnimation:"
-                        + " anim=" + a + " nextAppTransition=" + animName
-                        + " transit=" + appTransitionToString(transit) + " isEntrance=" + enter
-                        + " Callers=" + Debug.getCallers(3));
-            }
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s nextAppTransition=%s transit=%s isEntrance=%b "
+                            + "Callers=%s",
+                    a,  mNextAppTransitionScaleUp
+                            ? "ANIM_THUMBNAIL_SCALE_UP" : "ANIM_THUMBNAIL_SCALE_DOWN",
+                    appTransitionToString(transit), enter, Debug.getCallers(3));
         } else if (mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_ASPECT_SCALE_UP ||
                 mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_ASPECT_SCALE_DOWN) {
             mNextAppTransitionScaleUp =
@@ -1701,30 +1694,27 @@
             a = createAspectScaledThumbnailEnterExitAnimationLocked(
                     getThumbnailTransitionState(enter), uiMode, orientation, transit, frame,
                     insets, surfaceInsets, stableInsets, freeform, taskId);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
-                String animName = mNextAppTransitionScaleUp ?
-                        "ANIM_THUMBNAIL_ASPECT_SCALE_UP" : "ANIM_THUMBNAIL_ASPECT_SCALE_DOWN";
-                Slog.v(TAG, "applyAnimation:"
-                        + " anim=" + a + " nextAppTransition=" + animName
-                        + " transit=" + appTransitionToString(transit) + " isEntrance=" + enter
-                        + " Callers=" + Debug.getCallers(3));
-            }
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s nextAppTransition=%s transit=%s isEntrance=%b "
+                            + "Callers=%s",
+                    a, mNextAppTransitionScaleUp
+                            ? "ANIM_THUMBNAIL_ASPECT_SCALE_UP"
+                        : "ANIM_THUMBNAIL_ASPECT_SCALE_DOWN",
+                    appTransitionToString(transit), enter, Debug.getCallers(3));
         } else if (mNextAppTransitionType == NEXT_TRANSIT_TYPE_OPEN_CROSS_PROFILE_APPS && enter) {
             a = loadAnimationRes("android",
                     com.android.internal.R.anim.task_open_enter_cross_profile_apps);
-            Slog.v(TAG,
-                    "applyAnimation NEXT_TRANSIT_TYPE_OPEN_CROSS_PROFILE_APPS:"
-                            + " anim=" + a + " transit=" + appTransitionToString(transit)
-                            + " isEntrance=true" + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation NEXT_TRANSIT_TYPE_OPEN_CROSS_PROFILE_APPS: "
+                            + "anim=%s transit=%s isEntrance=true Callers=%s",
+                    a, appTransitionToString(transit), Debug.getCallers(3));
         } else if (transit == TRANSIT_TASK_CHANGE_WINDOWING_MODE) {
             // In the absence of a specific adapter, we just want to keep everything stationary.
             a = new AlphaAnimation(1.f, 1.f);
             a.setDuration(WindowChangeAnimationSpec.ANIMATION_DURATION);
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
-                Slog.v(TAG, "applyAnimation:"
-                        + " anim=" + a + " transit=" + appTransitionToString(transit)
-                        + " isEntrance=" + enter + " Callers=" + Debug.getCallers(3));
-            }
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s transit=%s isEntrance=%b Callers=%s",
+                    a, appTransitionToString(transit), enter, Debug.getCallers(3));
         } else {
             int animAttr = 0;
             switch (transit) {
@@ -1787,12 +1777,11 @@
                             : WindowAnimation_launchTaskBehindTargetAnimation;
             }
             a = animAttr != 0 ? loadAnimationAttr(lp, animAttr, transit) : null;
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
-                    "applyAnimation:"
-                    + " anim=" + a
-                    + " animAttr=0x" + Integer.toHexString(animAttr)
-                    + " transit=" + appTransitionToString(transit) + " isEntrance=" + enter
-                    + " Callers=" + Debug.getCallers(3));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: anim=%s animAttr=0x%x transit=%s isEntrance=%b "
+                            + "Callers=%s",
+                    a, animAttr, appTransitionToString(transit), enter,
+                    Debug.getCallers(3));
         }
         return a;
     }
@@ -1941,8 +1930,8 @@
     }
 
     void overridePendingAppTransitionRemote(RemoteAnimationAdapter remoteAnimationAdapter) {
-        if (DEBUG_APP_TRANSITIONS) Slog.i(TAG, "Override pending remote transitionSet="
-                + isTransitionSet() + " adapter=" + remoteAnimationAdapter);
+        ProtoLog.i(WM_DEBUG_APP_TRANSITIONS, "Override pending remote transitionSet=%b adapter=%s",
+                        isTransitionSet(), remoteAnimationAdapter);
         if (isTransitionSet()) {
             clear();
             mNextAppTransitionType = NEXT_TRANSIT_TYPE_REMOTE;
@@ -2214,12 +2203,11 @@
      */
     boolean prepareAppTransitionLocked(@TransitionType int transit, boolean alwaysKeepCurrent,
             @TransitionFlags int flags, boolean forceOverride) {
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Prepare app transition:"
-                + " transit=" + appTransitionToString(transit)
-                + " " + this
-                + " alwaysKeepCurrent=" + alwaysKeepCurrent
-                + " displayId=" + mDisplayContent.getDisplayId()
-                + " Callers=" + Debug.getCallers(5));
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                "Prepare app transition: transit=%s %s alwaysKeepCurrent=%b displayId=%d "
+                        + "Callers=%s",
+                appTransitionToString(transit), this, alwaysKeepCurrent,
+                mDisplayContent.getDisplayId(), Debug.getCallers(5));
         final boolean allowSetCrashing = !isKeyguardTransit(mNextAppTransition)
                 && transit == TRANSIT_CRASHING_ACTIVITY_CLOSE;
         if (forceOverride || isKeyguardTransit(transit) || !isTransitionSet()
@@ -2305,15 +2293,14 @@
             }
             if (isTransitionSet() || !dc.mOpeningApps.isEmpty() || !dc.mClosingApps.isEmpty()
                     || !dc.mChangingApps.isEmpty()) {
-                if (DEBUG_APP_TRANSITIONS) {
-                    Slog.v(TAG_WM, "*** APP TRANSITION TIMEOUT."
-                            + " displayId=" + dc.getDisplayId()
-                            + " isTransitionSet()="
-                            + dc.mAppTransition.isTransitionSet()
-                            + " mOpeningApps.size()=" + dc.mOpeningApps.size()
-                            + " mClosingApps.size()=" + dc.mClosingApps.size()
-                            + " mChangingApps.size()=" + dc.mChangingApps.size());
-                }
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                            "*** APP TRANSITION TIMEOUT. displayId=%d isTransitionSet()=%b "
+                                    + "mOpeningApps.size()=%d mClosingApps.size()=%d "
+                                    + "mChangingApps.size()=%d",
+                            dc.getDisplayId(), dc.mAppTransition.isTransitionSet(),
+                            dc.mOpeningApps.size(), dc.mClosingApps.size(),
+                            dc.mChangingApps.size());
+
                 setTimeout();
                 mService.mWindowPlacerLocked.performSurfacePlacement();
             }
diff --git a/services/core/java/com/android/server/wm/AppTransitionController.java b/services/core/java/com/android/server/wm/AppTransitionController.java
index 6b2f9da..20a871b 100644
--- a/services/core/java/com/android/server/wm/AppTransitionController.java
+++ b/services/core/java/com/android/server/wm/AppTransitionController.java
@@ -48,7 +48,7 @@
 import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_SPLASH_SCREEN;
 import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_WINDOWS_DRAWN;
 import static com.android.server.wm.AppTransition.isKeyguardGoingAwayTransit;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
@@ -66,6 +66,7 @@
 import android.view.animation.Animation;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.util.function.Predicate;
 
@@ -104,7 +105,7 @@
         }
         Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "AppTransitionReady");
 
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "**** GOOD TO GO");
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "**** GOOD TO GO");
         final AppTransition appTransition = mDisplayContent.mAppTransition;
         int transit = appTransition.getAppTransition();
         if (mDisplayContent.mSkipAppTransitionAnimation && !isKeyguardGoingAwayTransit(transit)) {
@@ -348,7 +349,7 @@
         final int appsCount = openingApps.size();
         for (int i = 0; i < appsCount; i++) {
             AppWindowToken wtoken = openingApps.valueAt(i);
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Now opening app" + wtoken);
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now opening app %s", wtoken);
 
             if (!wtoken.commitVisibility(animLp, true, transit, false, voiceInteraction)) {
                 // This token isn't going to be animating. Add it to the list of tokens to
@@ -383,7 +384,7 @@
         for (int i = 0; i < appsCount; i++) {
             AppWindowToken wtoken = closingApps.valueAt(i);
 
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Now closing app " + wtoken);
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now closing app %s", wtoken);
             // TODO: Do we need to add to mNoAnimationNotifyOnTransitionFinished like above if not
             //       animating?
             wtoken.commitVisibility(animLp, false, transit, false, voiceInteraction);
@@ -410,7 +411,7 @@
         final int appsCount = apps.size();
         for (int i = 0; i < appsCount; i++) {
             AppWindowToken wtoken = apps.valueAt(i);
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Now changing app" + wtoken);
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now changing app %s", wtoken);
             wtoken.cancelAnimationOnly();
             wtoken.applyAnimationLocked(null, transit, true, false);
             wtoken.updateReportedVisibilityLocked();
@@ -445,13 +446,12 @@
     }
 
     private boolean transitionGoodToGo(ArraySet<AppWindowToken> apps, SparseIntArray outReasons) {
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
-                "Checking " + apps.size() + " opening apps (frozen="
-                        + mService.mDisplayFrozen + " timeout="
-                        + mDisplayContent.mAppTransition.isTimeout() + ")...");
-        final ScreenRotationAnimation screenRotationAnimation =
-                mService.mAnimator.getScreenRotationAnimationLocked(
-                        Display.DEFAULT_DISPLAY);
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                "Checking %d opening apps (frozen=%b timeout=%b)...", apps.size(),
+                mService.mDisplayFrozen, mDisplayContent.mAppTransition.isTimeout());
+
+        final ScreenRotationAnimation screenRotationAnimation = mService.mRoot.getDisplayContent(
+                Display.DEFAULT_DISPLAY).getRotationAnimation();
 
         if (!mDisplayContent.mAppTransition.isTimeout()) {
             // Imagine the case where we are changing orientation due to an app transition, but a
@@ -463,20 +463,18 @@
             // app transition.
             if (screenRotationAnimation != null && screenRotationAnimation.isAnimating() &&
                     mDisplayContent.getDisplayRotation().needsUpdate()) {
-                if (DEBUG_APP_TRANSITIONS) {
-                    Slog.v(TAG, "Delaying app transition for screen rotation animation to finish");
-                }
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                        "Delaying app transition for screen rotation animation to finish");
                 return false;
             }
             for (int i = 0; i < apps.size(); i++) {
                 AppWindowToken wtoken = apps.valueAt(i);
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
-                        "Check opening app=" + wtoken + ": allDrawn="
-                                + wtoken.allDrawn + " startingDisplayed="
-                                + wtoken.startingDisplayed + " startingMoved="
-                                + wtoken.startingMoved + " isRelaunching()="
-                                + wtoken.isRelaunching() + " startingWindow="
-                                + wtoken.startingWindow);
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                                "Check opening app=%s: allDrawn=%b startingDisplayed=%b "
+                                        + "startingMoved=%b isRelaunching()=%b startingWindow=%s",
+                                wtoken, wtoken.allDrawn, wtoken.startingDisplayed,
+                                wtoken.startingMoved, wtoken.isRelaunching(),
+                                wtoken.startingWindow);
 
 
                 final boolean allDrawn = wtoken.allDrawn && !wtoken.isRelaunching();
@@ -496,15 +494,13 @@
 
             // We also need to wait for the specs to be fetched, if needed.
             if (mDisplayContent.mAppTransition.isFetchingAppTransitionsSpecs()) {
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "isFetchingAppTransitionSpecs=true");
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "isFetchingAppTransitionSpecs=true");
                 return false;
             }
 
             if (!mDisplayContent.mUnknownAppVisibilityController.allResolved()) {
-                if (DEBUG_APP_TRANSITIONS) {
-                    Slog.v(TAG, "unknownApps is not empty: "
-                            + mDisplayContent.mUnknownAppVisibilityController.getDebugMessage());
-                }
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "unknownApps is not empty: %s",
+                            mDisplayContent.mUnknownAppVisibilityController.getDebugMessage());
                 return false;
             }
 
@@ -549,22 +545,20 @@
                 true /* ignoreHidden */);
 
         boolean openingCanBeWallpaperTarget = canBeWallpaperTarget(openingApps);
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
-                "New wallpaper target=" + wallpaperTarget
-                        + ", oldWallpaper=" + oldWallpaper
-                        + ", openingApps=" + openingApps
-                        + ", closingApps=" + closingApps);
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                        "New wallpaper target=%s, oldWallpaper=%s, openingApps=%s, closingApps=%s",
+                        wallpaperTarget, oldWallpaper, openingApps, closingApps);
 
         if (openingCanBeWallpaperTarget && transit == TRANSIT_KEYGUARD_GOING_AWAY) {
             transit = TRANSIT_KEYGUARD_GOING_AWAY_ON_WALLPAPER;
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
-                    "New transit: " + AppTransition.appTransitionToString(transit));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                    "New transit: %s", AppTransition.appTransitionToString(transit));
         }
         // We never want to change from a Keyguard transit to a non-Keyguard transit, as our logic
         // relies on the fact that we always execute a Keyguard transition after preparing one.
         else if (!isKeyguardGoingAwayTransit(transit)) {
             if (closingAppHasWallpaper && openingAppHasWallpaper) {
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Wallpaper animation!");
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Wallpaper animation!");
                 switch (transit) {
                     case TRANSIT_ACTIVITY_OPEN:
                     case TRANSIT_TASK_OPEN:
@@ -577,16 +571,17 @@
                         transit = TRANSIT_WALLPAPER_INTRA_CLOSE;
                         break;
                 }
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
-                        "New transit: " + AppTransition.appTransitionToString(transit));
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                        "New transit: %s", AppTransition.appTransitionToString(transit));
             } else if (oldWallpaper != null && !mDisplayContent.mOpeningApps.isEmpty()
                     && !openingApps.contains(oldWallpaper.mAppToken)
                     && closingApps.contains(oldWallpaper.mAppToken)
                     && topClosingApp == oldWallpaper.mAppToken) {
                 // We are transitioning from an activity with a wallpaper to one without.
                 transit = TRANSIT_WALLPAPER_CLOSE;
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "New transit away from wallpaper: "
-                        + AppTransition.appTransitionToString(transit));
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                        "New transit away from wallpaper: %s",
+                                AppTransition.appTransitionToString(transit));
             } else if (wallpaperTarget != null && wallpaperTarget.isVisibleLw()
                     && openingApps.contains(wallpaperTarget.mAppToken)
                     && topOpeningApp == wallpaperTarget.mAppToken
@@ -594,8 +589,8 @@
                 // We are transitioning from an activity without
                 // a wallpaper to now showing the wallpaper
                 transit = TRANSIT_WALLPAPER_OPEN;
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "New transit into wallpaper: "
-                        + AppTransition.appTransitionToString(transit));
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "New transit into wallpaper: %s",
+                        AppTransition.appTransitionToString(transit));
             }
         }
         return transit;
@@ -722,8 +717,7 @@
             final WindowState win = mDisplayContent.findFocusedWindow();
             if (win != null) {
                 final AppWindowToken wtoken = win.mAppToken;
-                if (DEBUG_APP_TRANSITIONS)
-                    Slog.v(TAG, "Now animating app in place " + wtoken);
+                ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Now animating app in place %s", wtoken);
                 wtoken.cancelAnimation();
                 wtoken.applyAnimationLocked(null, transit, false, false);
                 wtoken.updateReportedVisibilityLocked();
diff --git a/services/core/java/com/android/server/wm/AppWindowThumbnail.java b/services/core/java/com/android/server/wm/AppWindowThumbnail.java
index b52ade4..2b05024 100644
--- a/services/core/java/com/android/server/wm/AppWindowThumbnail.java
+++ b/services/core/java/com/android/server/wm/AppWindowThumbnail.java
@@ -22,7 +22,7 @@
 import static com.android.server.wm.AppWindowThumbnailProto.HEIGHT;
 import static com.android.server.wm.AppWindowThumbnailProto.SURFACE_ANIMATOR;
 import static com.android.server.wm.AppWindowThumbnailProto.WIDTH;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 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.MAX_ANIMATION_DURATION;
@@ -31,7 +31,6 @@
 import android.graphics.PixelFormat;
 import android.graphics.Point;
 import android.os.Binder;
-import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
 import android.view.Surface;
 import android.view.SurfaceControl;
@@ -39,6 +38,7 @@
 import android.view.SurfaceControl.Transaction;
 import android.view.animation.Animation;
 
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.SurfaceAnimator.Animatable;
 
 import java.util.function.Supplier;
@@ -104,9 +104,7 @@
                         window != null ? window.mOwnerUid : Binder.getCallingUid())
                 .build();
 
-        if (SHOW_TRANSACTIONS) {
-            Slog.i(TAG, "  THUMBNAIL " + mSurfaceControl + ": CREATE");
-        }
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "  THUMBNAIL %s: CREATE", mSurfaceControl);
 
         // Transfer the thumbnail to the surface
         drawSurface.copyFrom(mSurfaceControl);
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index f647fe4..a261341 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -21,8 +21,15 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.content.pm.ActivityInfo.COLOR_MODE_DEFAULT;
+import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
+import static android.content.pm.ActivityInfo.FLAG_INHERIT_SHOW_WHEN_LOCKED;
+import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
+import static android.content.pm.ActivityInfo.FLAG_TURN_SCREEN_ON;
+import static android.content.pm.ActivityInfo.LAUNCH_MULTIPLE;
+import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TOP;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_BEHIND;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
+import static android.os.Build.VERSION_CODES.HONEYCOMB;
 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
 import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
 import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
@@ -62,17 +69,19 @@
 import static com.android.server.wm.AppWindowTokenProto.STARTING_WINDOW;
 import static com.android.server.wm.AppWindowTokenProto.THUMBNAIL;
 import static com.android.server.wm.AppWindowTokenProto.WINDOW_TOKEN;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
+import static com.android.server.wm.IdentifierProto.HASH_CODE;
+import static com.android.server.wm.IdentifierProto.TITLE;
+import static com.android.server.wm.IdentifierProto.USER_ID;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS_ANIM;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_STARTING_WINDOW;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW_VERBOSE;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TOKEN_MOVEMENT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_MOVEMENT;
 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_ACTIVITY_DRAWN;
@@ -85,12 +94,17 @@
 import static com.android.server.wm.WindowStateAnimator.STACK_CLIP_BEFORE_ANIM;
 
 import android.annotation.CallSuper;
+import android.annotation.Nullable;
 import android.annotation.Size;
 import android.app.Activity;
 import android.app.ActivityManager;
+import android.app.ActivityOptions;
 import android.content.ComponentName;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.res.CompatibilityInfo;
 import android.content.res.Configuration;
+import android.content.res.Resources;
 import android.graphics.GraphicBuffer;
 import android.graphics.PixelFormat;
 import android.graphics.Point;
@@ -99,14 +113,13 @@
 import android.os.Build;
 import android.os.Debug;
 import android.os.IBinder;
-import android.os.RemoteException;
 import android.os.SystemClock;
 import android.os.Trace;
+import android.os.UserHandle;
 import android.util.ArraySet;
 import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
 import android.view.DisplayInfo;
-import android.view.IApplicationToken;
 import android.view.InputApplicationHandle;
 import android.view.RemoteAnimationAdapter;
 import android.view.RemoteAnimationDefinition;
@@ -124,6 +137,7 @@
 import com.android.server.display.color.ColorDisplayService;
 import com.android.server.policy.WindowManagerPolicy;
 import com.android.server.policy.WindowManagerPolicy.StartingSurface;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.RemoteAnimationController.RemoteAnimationRecord;
 import com.android.server.wm.WindowManagerService.H;
 
@@ -140,8 +154,8 @@
  * Version of WindowToken that is specifically for a particular application (or
  * really activity) that is displaying windows.
  */
-class AppWindowToken extends WindowToken implements WindowManagerService.AppFreezeListener,
-        ConfigurationContainerListener {
+// TODO: Fully merge this class into ActivityRecord class since they are really the same thing...
+class AppWindowToken extends WindowToken implements WindowManagerService.AppFreezeListener {
     private static final String TAG = TAG_WITH_CLASS_NAME ? "AppWindowToken" : TAG_WM;
 
     /**
@@ -149,17 +163,36 @@
      */
     @VisibleForTesting static final int Z_BOOST_BASE = 800570000;
 
+    final ActivityTaskManagerService mAtmService;
     // Non-null only for application tokens.
-    final IApplicationToken appToken;
+    // TODO: rename to mActivityToken
+    final ActivityRecord.Token appToken;
+    // All about me
+    final ActivityInfo mActivityInfo;
+    // Which user is this running for?
+    final int mUserId;
+    // The package implementing intent's component
+    // TODO: rename to mPackageName
+    final String packageName;
+    // the intent component, or target of an alias.
     final ComponentName mActivityComponent;
-    final boolean mVoiceInteraction;
+    boolean mVoiceInteraction;
 
     /**
      * The activity is opaque and fills the entire space of this task.
      * @see WindowContainer#fillsParent()
      */
     private boolean mOccludesParent;
+    // Has a wallpaper window as a background.
+    // TODO: Rename to mHasWallpaper and also see if it possible to combine this with the
+    // mOccludesParent field.
+    final boolean hasWallpaper;
+    // activity is not displayed?
+    // TODO: rename to mNoDisplay
+    @VisibleForTesting
+    boolean noDisplay;
     boolean mShowForAllUsers;
+    // TODO: Make this final
     int mTargetSdk;
 
     // Flag set while reparenting to prevent actions normally triggered by an individual parent
@@ -234,10 +267,12 @@
     boolean mLaunchTaskBehind;
     boolean mEnteringAnimation;
 
-    private boolean mAlwaysFocusable;
-
     boolean mAppStopped;
-    int mRotationAnimationHint;
+    // A hint to override the window specified rotation animation, or -1 to use the window specified
+    // value. We use this so that we can select the right animation in the cases of starting
+    // windows, where the app hasn't had time to set a value on the window.
+    int mRotationAnimationHint = -1;
+
     private int mPendingRelaunchCount;
 
     private boolean mLastContainsShowWhenLockedWindow;
@@ -261,9 +296,6 @@
 
     private Task mLastParent;
 
-    // TODO: Remove after unification
-    ActivityRecord mActivityRecord;
-
     /**
      * @see #currentLaunchCanTurnScreenOn()
      */
@@ -327,6 +359,10 @@
     private static final int STARTING_WINDOW_TYPE_SNAPSHOT = 1;
     private static final int STARTING_WINDOW_TYPE_SPLASH_SCREEN = 2;
 
+    private boolean mShowWhenLocked;
+    private boolean mInheritShownWhenLocked;
+    private boolean mTurnScreenOn;
+
     private AppSaturationInfo mLastAppSaturationInfo;
 
     private final ColorDisplayService.ColorTransformController mColorTransformController =
@@ -341,23 +377,67 @@
                 }
             });
 
-    AppWindowToken(WindowManagerService service, IApplicationToken token,
-            ComponentName activityComponent, boolean voiceInteraction, DisplayContent dc,
-            long inputDispatchingTimeoutNanos, boolean fullscreen, boolean showForAllUsers,
-            int targetSdk, int orientation, int rotationAnimationHint,
-            boolean launchTaskBehind, boolean alwaysFocusable,
-            ActivityRecord activityRecord) {
-        this(service, token, activityComponent, voiceInteraction, dc, fullscreen);
-        // TODO: remove after unification
-        mActivityRecord = activityRecord;
-        mActivityRecord.registerConfigurationChangeListener(this);
-        mInputDispatchingTimeoutNanos = inputDispatchingTimeoutNanos;
-        mShowForAllUsers = showForAllUsers;
-        mTargetSdk = targetSdk;
-        mOrientation = orientation;
-        mLaunchTaskBehind = launchTaskBehind;
-        mAlwaysFocusable = alwaysFocusable;
-        mRotationAnimationHint = rotationAnimationHint;
+    AppWindowToken(WindowManagerService service, ActivityTaskManagerService atm,
+            ActivityRecord.Token token, ActivityInfo aInfo, ActivityOptions options, Intent intent,
+            DisplayContent dc) {
+        super(service, token != null ? token.asBinder() : null, TYPE_APPLICATION, true, dc,
+                false /* ownerCanManageAppTokens */);
+        mAtmService = atm;
+        appToken = token;
+        mActivityInfo = aInfo;
+        mUserId = UserHandle.getUserId(mActivityInfo.applicationInfo.uid);
+        packageName = mActivityInfo.applicationInfo.packageName;
+        mInputApplicationHandle = new InputApplicationHandle(appToken);
+
+        // If the class name in the intent doesn't match that of the target, this is probably an
+        // alias. We have to create a new ComponentName object to keep track of the real activity
+        // name, so that FLAG_ACTIVITY_CLEAR_TOP is handled properly.
+        if (mActivityInfo.targetActivity == null
+                || (mActivityInfo.targetActivity.equals(intent.getComponent().getClassName())
+                && (mActivityInfo.launchMode == LAUNCH_MULTIPLE
+                || mActivityInfo.launchMode == LAUNCH_SINGLE_TOP))) {
+            mActivityComponent = intent.getComponent();
+        } else {
+            mActivityComponent =
+                    new ComponentName(mActivityInfo.packageName, mActivityInfo.targetActivity);
+        }
+
+        mTargetSdk = mActivityInfo.applicationInfo.targetSdkVersion;
+        mShowForAllUsers = (mActivityInfo.flags & FLAG_SHOW_FOR_ALL_USERS) != 0;
+        setOrientation(mActivityInfo.screenOrientation);
+        mRotationAnimationHint = mActivityInfo.rotationAnimation;
+
+        mShowWhenLocked = (aInfo.flags & ActivityInfo.FLAG_SHOW_WHEN_LOCKED) != 0;
+        mInheritShownWhenLocked = (aInfo.privateFlags & FLAG_INHERIT_SHOW_WHEN_LOCKED) != 0;
+        mTurnScreenOn = (aInfo.flags & FLAG_TURN_SCREEN_ON) != 0;
+
+        int realTheme = mActivityInfo.getThemeResource();
+        if (realTheme == Resources.ID_NULL) {
+            realTheme = aInfo.applicationInfo.targetSdkVersion < HONEYCOMB
+                    ? android.R.style.Theme : android.R.style.Theme_Holo;
+        }
+
+        final AttributeCache.Entry ent = AttributeCache.instance().get(packageName,
+                realTheme, com.android.internal.R.styleable.Window, mUserId);
+
+        if (ent != null) {
+            mOccludesParent = !ActivityInfo.isTranslucentOrFloating(ent.array);
+            hasWallpaper = ent.array.getBoolean(R.styleable.Window_windowShowWallpaper, false);
+            noDisplay = ent.array.getBoolean(R.styleable.Window_windowNoDisplay, false);
+        } else {
+            hasWallpaper = false;
+            noDisplay = false;
+        }
+
+        if (options != null) {
+            mLaunchTaskBehind = options.getLaunchTaskBehind();
+
+            final int rotationAnimation = options.getRotationAnimationHint();
+            // Only override manifest supplied option if set.
+            if (rotationAnimation >= 0) {
+                mRotationAnimationHint = rotationAnimation;
+            }
+        }
 
         // Application tokens start out hidden.
         setHidden(true);
@@ -365,20 +445,19 @@
 
         ColorDisplayService.ColorDisplayServiceInternal cds = LocalServices.getService(
                 ColorDisplayService.ColorDisplayServiceInternal.class);
-        cds.attachColorTransformController(activityRecord.packageName, activityRecord.mUserId,
+        cds.attachColorTransformController(packageName, mUserId,
                 new WeakReference<>(mColorTransformController));
     }
 
-    AppWindowToken(WindowManagerService service, IApplicationToken token,
-            ComponentName activityComponent, boolean voiceInteraction, DisplayContent dc,
-            boolean fillsParent) {
-        super(service, token != null ? token.asBinder() : null, TYPE_APPLICATION, true, dc,
-                false /* ownerCanManageAppTokens */);
-        appToken = token;
-        mActivityComponent = activityComponent;
+    void onAttachToTask(boolean voiceInteraction, DisplayContent dc,
+            long inputDispatchingTimeoutNanos) {
+        mInputDispatchingTimeoutNanos = inputDispatchingTimeoutNanos;
         mVoiceInteraction = voiceInteraction;
-        mOccludesParent = fillsParent;
-        mInputApplicationHandle = new InputApplicationHandle(appToken.asBinder());
+        onDisplayChanged(dc);
+
+        // Application tokens start out hidden.
+        setHidden(true);
+        hiddenRequested = true;
     }
 
     void onFirstWindowDrawn(WindowState win, WindowStateAnimator winAnimator) {
@@ -388,8 +467,8 @@
         removeDeadWindows();
 
         if (startingWindow != null) {
-            if (DEBUG_STARTING_WINDOW || DEBUG_ANIM) Slog.v(TAG, "Finish starting "
-                    + win.mToken + ": first real window is shown, no animation");
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Finish starting %s"
+                        + ": first real window is shown, no animation", win.mToken);
             // If this initial window is animating, stop it -- we will do an animation to reveal
             // it from behind the starting window, so there is no need for it to also be doing its
             // own stuff.
@@ -433,43 +512,33 @@
         if (DEBUG_VISIBILITY) Slog.v(TAG, "VIS " + this + ": interesting="
                 + numInteresting + " visible=" + numVisible);
         if (nowDrawn != reportedDrawn) {
-            if (mActivityRecord != null) {
-                mActivityRecord.onWindowsDrawn(nowDrawn, SystemClock.uptimeMillis());
-            }
+            onWindowsDrawn(nowDrawn, SystemClock.uptimeMillis());
             reportedDrawn = nowDrawn;
         }
         if (nowVisible != reportedVisible) {
             if (DEBUG_VISIBILITY) Slog.v(TAG,
                     "Visibility changed in " + this + ": vis=" + nowVisible);
             reportedVisible = nowVisible;
-            if (mActivityRecord != null) {
-                if (nowVisible) {
-                    onWindowsVisible();
-                } else {
-                    onWindowsGone();
-                }
+            if (nowVisible) {
+                onWindowsVisible();
+            } else {
+                onWindowsGone();
             }
         }
     }
 
-    private void onWindowsGone() {
-        if (mActivityRecord == null) {
-            return;
-        }
-        if (DEBUG_VISIBILITY) {
-            Slog.v(TAG_WM, "Reporting gone in " + mActivityRecord.appToken);
-        }
-        mActivityRecord.onWindowsGone();
+    // Mostly implemented in ActivityRecord.
+    void onWindowsDrawn(boolean drawn, long timestamp) {
     }
 
-    private void onWindowsVisible() {
-        if (mActivityRecord == null) {
-            return;
-        }
-        if (DEBUG_VISIBILITY) {
-            Slog.v(TAG_WM, "Reporting visible in " + mActivityRecord.appToken);
-        }
-        mActivityRecord.onWindowsVisible();
+    // Mostly implemented in ActivityRecord. Keeping here for the logpoint.
+    void onWindowsGone() {
+        if (DEBUG_VISIBILITY) Slog.v(TAG_WM, "Reporting gone in " + appToken);
+    }
+
+    // Mostly implemented in ActivityRecord. Keeping here for the logpoint.
+    void onWindowsVisible() {
+        if (DEBUG_VISIBILITY) Slog.v(TAG_WM, "Reporting visible in " + appToken);
     }
 
     boolean isClientHidden() {
@@ -480,8 +549,9 @@
         if (mClientHidden == hideClient || (hideClient && mDeferHidingClient)) {
             return;
         }
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "setClientHidden: " + this
-                + " clientHidden=" + hideClient + " Callers=" + Debug.getCallers(5));
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                "setClientHidden: %s clientHidden=%b Callers=%s", this, hideClient,
+                        Debug.getCallers(5));
         mClientHidden = hideClient;
         sendAppVisibilityToClients();
     }
@@ -507,12 +577,10 @@
             return;
         }
 
-        if (DEBUG_APP_TRANSITIONS || DEBUG_ORIENTATION) {
-            Slog.v(TAG_WM, "setAppVisibility("
-                    + appToken + ", visible=" + visible + "): " + appTransition
-                    + " hidden=" + isHidden() + " hiddenRequested="
-                    + hiddenRequested + " Callers=" + Debug.getCallers(6));
-        }
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                    "setAppVisibility(%s, visible=%b): %s hidden=%b hiddenRequested=%b Callers=%s",
+                    appToken, visible, appTransition, isHidden(), hiddenRequested,
+                    Debug.getCallers(6));
 
         final DisplayContent displayContent = getDisplayContent();
         displayContent.mOpeningApps.remove(this);
@@ -548,17 +616,20 @@
                 if (isHidden()) {
                     waitingToShow = true;
 
-                    // Let's reset the draw state in order to prevent the starting window to be
-                    // immediately dismissed when the app still has the surface.
-                    forAllWindows(w -> {
-                        if (w.mWinAnimator.mDrawState == HAS_DRAWN) {
-                            w.mWinAnimator.resetDrawState();
+                    // If the client isn't hidden, we don't need to reset the drawing state.
+                    if (isClientHidden()) {
+                        // Let's reset the draw state in order to prevent the starting window to be
+                        // immediately dismissed when the app still has the surface.
+                        forAllWindows(w -> {
+                            if (w.mWinAnimator.mDrawState == HAS_DRAWN) {
+                                w.mWinAnimator.resetDrawState();
 
-                            // Force add to mResizingWindows, so that we are guaranteed to get
-                            // another reportDrawn callback.
-                            w.resetLastContentInsets();
-                        }
-                    },  true /* traverseTopToBottom */);
+                                // Force add to mResizingWindows, so that we are guaranteed to get
+                                // another reportDrawn callback.
+                                w.resetLastContentInsets();
+                            }
+                        }, true /* traverseTopToBottom */);
+                    }
                 }
             }
 
@@ -570,7 +641,7 @@
 
             requestUpdateWallpaperIfNeeded();
 
-            if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "No longer Stopped: " + this);
+            ProtoLog.v(WM_DEBUG_ADD_REMOVE, "No longer Stopped: %s", this);
             mAppStopped = false;
 
             transferStartingWindowFromHiddenAboveTokenIfNeeded();
@@ -593,17 +664,15 @@
                 if (win != null) {
                     final AppWindowToken focusedToken = win.mAppToken;
                     if (focusedToken != null) {
-                        if (DEBUG_APP_TRANSITIONS) {
-                            Slog.d(TAG_WM, "TRANSIT_TASK_OPEN_BEHIND, "
-                                    + " adding " + focusedToken + " to mOpeningApps");
-                        }
+                        ProtoLog.d(WM_DEBUG_APP_TRANSITIONS,
+                                    "TRANSIT_TASK_OPEN_BEHIND,  adding %s to mOpeningApps",
+                                    focusedToken);
+
                         // Force animation to be loaded.
                         displayContent.mOpeningApps.add(focusedToken);
                     }
                 }
             }
-            // Changes in opening apps and closing apps may cause orientation change.
-            reportDescendantOrientationChangeIfNeeded();
             return;
         }
 
@@ -635,8 +704,9 @@
             final AccessibilityController accessibilityController =
                     mWmService.mAccessibilityController;
             boolean changed = false;
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM,
-                    "Changing app " + this + " hidden=" + isHidden() + " performLayout=" + performLayout);
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                    "Changing app %s hidden=%b performLayout=%b", this, isHidden(),
+                            performLayout);
 
             boolean runningAppAnimation = false;
 
@@ -678,10 +748,9 @@
                 forAllWindows(mWmService::makeWindowFreezingScreenIfNeededLocked, true);
             }
 
-            if (DEBUG_APP_TRANSITIONS) {
-                Slog.v(TAG_WM, "commitVisibility: " + this
-                        + ": hidden=" + isHidden() + " hiddenRequested=" + hiddenRequested);
-            }
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                        "commitVisibility: %s: hidden=%b hiddenRequested=%b", this,
+                                isHidden(), hiddenRequested);
 
             if (changed) {
                 displayContent.getInputMonitor().setUpdateInputWindowsNeededLw();
@@ -760,29 +829,27 @@
                 }
                 SurfaceControl.closeTransaction();
             }
-
-            // Visibility changes may cause orientation request change.
-            reportDescendantOrientationChangeIfNeeded();
         }
 
         return delayed;
     }
 
-    private void reportDescendantOrientationChangeIfNeeded() {
+    boolean mayFreezeScreenLocked() {
+        return false;
+    }
+
+    void reportDescendantOrientationChangeIfNeeded() {
         // Orientation request is exposed only when we're visible. Therefore visibility change
         // will change requested orientation. Notify upward the hierarchy ladder to adjust
         // configuration. This is important to cases where activities with incompatible
         // orientations launch, or user goes back from an activity of bi-orientation to an
         // activity with specified orientation.
-        if (mActivityRecord.getRequestedConfigurationOrientation() == getConfiguration().orientation
-                || getOrientationIgnoreVisibility() == SCREEN_ORIENTATION_UNSET) {
+        if (getRequestedOrientation() == SCREEN_ORIENTATION_UNSET) {
             return;
         }
 
-        final IBinder freezeToken =
-                mActivityRecord.mayFreezeScreenLocked(mActivityRecord.app)
-                        ? mActivityRecord.appToken : null;
-        onDescendantOrientationChanged(freezeToken, mActivityRecord);
+        final IBinder freezeToken = mayFreezeScreenLocked() ? appToken : null;
+        onDescendantOrientationChanged(freezeToken, this);
     }
 
     /**
@@ -832,10 +899,16 @@
         return candidate;
     }
 
+    boolean isAlwaysFocusable() {
+        return (mActivityInfo.flags & FLAG_ALWAYS_FOCUSABLE) != 0;
+    }
+
+    // TODO: Does this really need to be different from isAlwaysFocusable()? For the activity side
+    // focusable means resumeable. I guess with that in mind maybe we should rename the other
+    // method to isResumeable() or something like that.
     boolean windowsAreFocusable() {
         if (mTargetSdk < Build.VERSION_CODES.Q) {
-            final int pid = mActivityRecord != null
-                    ? (mActivityRecord.app != null ? mActivityRecord.app.getPid() : 0) : 0;
+            final int pid = getPid();
             final AppWindowToken topFocusedAppOfMyProcess =
                     mWmService.mRoot.mTopFocusedAppByProcess.get(pid);
             if (topFocusedAppOfMyProcess != null && topFocusedAppOfMyProcess != this) {
@@ -844,7 +917,12 @@
                 return false;
             }
         }
-        return getWindowConfiguration().canReceiveKeys() || mAlwaysFocusable;
+        return getWindowConfiguration().canReceiveKeys() || isAlwaysFocusable();
+    }
+
+    // Mostly implemented in ActivityRecord...
+    int getPid() {
+        return 0;
     }
 
     @Override
@@ -857,9 +935,6 @@
     @Override
     void removeImmediately() {
         onRemovedFromDisplay();
-        if (mActivityRecord != null) {
-            mActivityRecord.unregisterConfigurationChangeListener(this);
-        }
         super.removeImmediately();
     }
 
@@ -884,7 +959,7 @@
         }
         mRemovingFromDisplay = true;
 
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "Removing app token: " + this);
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, "Removing app token: %s", this);
 
         boolean delayed = commitVisibility(null, false, TRANSIT_UNSET, true, mVoiceInteraction);
 
@@ -900,11 +975,12 @@
             delayed = true;
         }
 
-        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "Removing app " + this + " delayed=" + delayed
-                + " animation=" + getAnimation() + " animating=" + isSelfAnimating());
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                "Removing app %s delayed=%b animation=%s animating=%b", this, delayed,
+                        getAnimation(), isSelfAnimating());
 
-        if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG_WM, "removeAppToken: "
-                + this + " delayed=" + delayed + " Callers=" + Debug.getCallers(4));
+        ProtoLog.v(WM_DEBUG_ADD_REMOVE, "removeAppToken: %s"
+                + " delayed=%b Callers=%s", this, delayed, Debug.getCallers(4));
 
         if (mStartingData != null) {
             removeStartingWindow();
@@ -920,8 +996,8 @@
         final TaskStack stack = getStack();
         if (delayed && !isEmpty()) {
             // set the token aside because it has an active animation to be finished
-            if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG_WM,
-                    "removeAppToken make exiting: " + this);
+            ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                    "removeAppToken make exiting: %s", this);
             if (stack != null) {
                 stack.mExitingAppTokens.add(this);
             }
@@ -941,8 +1017,9 @@
 
         final DisplayContent dc = getDisplayContent();
         if (dc.mFocusedApp == this) {
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "Removing focused app token:" + this
-                   + " displayId=" + dc.getDisplayId());
+            ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
+                    "Removing focused app token:%s displayId=%d", this,
+                            dc.getDisplayId());
             dc.setFocusedApp(null);
             mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, true /*updateInputWindows*/);
         }
@@ -1006,8 +1083,8 @@
      * up of the surfaces
      */
     void notifyAppResumed(boolean wasStopped) {
-        if (DEBUG_ADD_REMOVE) Slog.v(TAG, "notifyAppResumed: wasStopped=" + wasStopped
-                + " " + this);
+        ProtoLog.v(WM_DEBUG_ADD_REMOVE, "notifyAppResumed: wasStopped=%b %s",
+                wasStopped, this);
         mAppStopped = false;
         // Allow the window to turn the screen on once the app is resumed again.
         setCurrentLaunchCanTurnScreenOn(true);
@@ -1021,7 +1098,7 @@
      * keeping alive in case they were still being used.
      */
     void notifyAppStopped() {
-        if (DEBUG_ADD_REMOVE) Slog.v(TAG, "notifyAppStopped: " + this);
+        ProtoLog.v(WM_DEBUG_ADD_REMOVE, "notifyAppStopped: %s", this);
         mAppStopped = true;
         // Reset the last saved PiP snap fraction on app stop.
         mDisplayContent.mPinnedStackControllerLocked.resetReentrySnapFraction(mActivityComponent);
@@ -1061,7 +1138,9 @@
             if (task == null) {
                 // It is possible we have been marked as a closing app earlier. We must remove ourselves
                 // from this list so we do not participate in any future animations.
-                getDisplayContent().mClosingApps.remove(this);
+                if (getDisplayContent() != null) {
+                    getDisplayContent().mClosingApps.remove(this);
+                }
             } else if (mLastParent != null && mLastParent.mStack != null) {
                 task.mStack.mExitingAppTokens.remove(this);
             }
@@ -1084,12 +1163,12 @@
     void postWindowRemoveStartingWindowCleanup(WindowState win) {
         // TODO: Something smells about the code below...Is there a better way?
         if (startingWindow == win) {
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Notify removed startingWindow " + win);
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Notify removed startingWindow %s", win);
             removeStartingWindow();
         } else if (mChildren.size() == 0) {
             // If this is the last window and we had requested a starting transition window,
             // well there is no point now.
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Nulling last startingData");
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Nulling last startingData");
             mStartingData = null;
             if (mHiddenSetFromTransferredStartingWindow) {
                 // We set the hidden state to false for the token from a transferred starting window.
@@ -1100,8 +1179,7 @@
         } else if (mChildren.size() == 1 && startingSurface != null && !isRelaunching()) {
             // If this is the last window except for a starting transition window,
             // we need to get rid of the starting transition.
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Last window, removing starting window "
-                    + win);
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Last window, removing starting window %s", win);
             removeStartingWindow();
         }
     }
@@ -1110,8 +1188,8 @@
         for (int winNdx = mChildren.size() - 1; winNdx >= 0; --winNdx) {
             WindowState win = mChildren.get(winNdx);
             if (win.mAppDied) {
-                if (DEBUG_WINDOW_MOVEMENT || DEBUG_ADD_REMOVE) Slog.w(TAG,
-                        "removeDeadWindows: " + win);
+                ProtoLog.w(WM_DEBUG_ADD_REMOVE,
+                        "removeDeadWindows: %s", win);
                 // Set mDestroying, we don't want any animation or delayed removal here.
                 win.mDestroying = true;
                 // Also removes child windows.
@@ -1132,8 +1210,8 @@
     }
 
     void setWillReplaceWindows(boolean animate) {
-        if (DEBUG_ADD_REMOVE) Slog.d(TAG_WM,
-                "Marking app token " + this + " with replacing windows.");
+        ProtoLog.d(WM_DEBUG_ADD_REMOVE,
+                "Marking app token %s with replacing windows.", this);
 
         for (int i = mChildren.size() - 1; i >= 0; i--) {
             final WindowState w = mChildren.get(i);
@@ -1142,8 +1220,8 @@
     }
 
     void setWillReplaceChildWindows() {
-        if (DEBUG_ADD_REMOVE) Slog.d(TAG_WM, "Marking app token " + this
-                + " with replacing child windows.");
+        ProtoLog.d(WM_DEBUG_ADD_REMOVE, "Marking app token %s"
+                + " with replacing child windows.", this);
         for (int i = mChildren.size() - 1; i >= 0; i--) {
             final WindowState w = mChildren.get(i);
             w.setWillReplaceChildWindows();
@@ -1151,8 +1229,8 @@
     }
 
     void clearWillReplaceWindows() {
-        if (DEBUG_ADD_REMOVE) Slog.d(TAG_WM,
-                "Resetting app token " + this + " of replacing window marks.");
+        ProtoLog.d(WM_DEBUG_ADD_REMOVE,
+                "Resetting app token %s of replacing window marks.", this);
 
         for (int i = mChildren.size() - 1; i >= 0; i--) {
             final WindowState w = mChildren.get(i);
@@ -1317,10 +1395,9 @@
     }
 
     void reparent(Task task, int position) {
-        if (DEBUG_ADD_REMOVE) {
-            Slog.i(TAG_WM, "reparent: moving app token=" + this
-                    + " to task=" + task.mTaskId + " at " + position);
-        }
+        ProtoLog.i(WM_DEBUG_ADD_REMOVE, "reparent: moving app token=%s"
+                    + " to task=%d at %d", this, task.mTaskId, position);
+
         if (task == null) {
             throw new IllegalArgumentException("reparent: could not find task");
         }
@@ -1336,8 +1413,8 @@
                         + " belongs to a different stack than " + task);
         }
 
-        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "reParentWindowToken: removing window token=" + this
-                + " from task=" + currentTask);
+        ProtoLog.i(WM_DEBUG_ADD_REMOVE, "reParentWindowToken: removing window token=%s"
+                + " from task=%s"  , this, currentTask);
         final DisplayContent prevDisplayContent = getDisplayContent();
 
         mReparenting = true;
@@ -1457,9 +1534,10 @@
     }
 
     void startFreezingScreen() {
-        if (DEBUG_ORIENTATION) logWithStack(TAG, "Set freezing of " + appToken + ": hidden="
-                + isHidden() + " freezing=" + mFreezingScreen + " hiddenRequested="
-                + hiddenRequested);
+        ProtoLog.i(WM_DEBUG_ORIENTATION,
+                "Set freezing of %s: hidden=%b freezing=%b hiddenRequested=%b. %s",
+                        appToken, isHidden(), mFreezingScreen, hiddenRequested,
+                new RuntimeException().fillInStackTrace());
         if (!hiddenRequested) {
             if (!mFreezingScreen) {
                 mFreezingScreen = true;
@@ -1483,7 +1561,8 @@
         if (!mFreezingScreen) {
             return;
         }
-        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Clear freezing of " + this + " force=" + force);
+        ProtoLog.v(WM_DEBUG_ORIENTATION,
+                "Clear freezing of %s force=%b", this, force);
         final int count = mChildren.size();
         boolean unfrozeWindows = false;
         for (int i = 0; i < count; i++) {
@@ -1491,7 +1570,7 @@
             unfrozeWindows |= w.onStopFreezingScreen();
         }
         if (force || unfrozeWindows) {
-            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "No longer freezing: " + this);
+            ProtoLog.v(WM_DEBUG_ORIENTATION, "No longer freezing: %s", this);
             mFreezingScreen = false;
             mWmService.unregisterAppFreezeListener(this);
             mWmService.mAppsFreezingScreen--;
@@ -1542,8 +1621,8 @@
             // letting windows get shown immediately without any more transitions.
             getDisplayContent().mSkipAppTransitionAnimation = true;
 
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Moving existing starting " + tStartingWindow
-                    + " from " + fromToken + " to " + this);
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Moving existing starting %s"
+                    + " from %s to %s", tStartingWindow, fromToken, this);
 
             final long origId = Binder.clearCallingIdentity();
             try {
@@ -1561,8 +1640,8 @@
                 tStartingWindow.mToken = this;
                 tStartingWindow.mAppToken = this;
 
-                if (DEBUG_ADD_REMOVE || DEBUG_STARTING_WINDOW) Slog.v(TAG_WM,
-                        "Removing starting " + tStartingWindow + " from " + fromToken);
+                ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                        "Removing starting %s from %s", tStartingWindow, fromToken);
                 fromToken.removeChild(tStartingWindow);
                 fromToken.postWindowRemoveStartingWindowCleanup(tStartingWindow);
                 fromToken.mHiddenSetFromTransferredStartingWindow = false;
@@ -1603,8 +1682,8 @@
         } else if (fromToken.mStartingData != null) {
             // The previous app was getting ready to show a
             // starting window, but hasn't yet done so.  Steal it!
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM,
-                    "Moving pending starting from " + fromToken + " to " + this);
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW,
+                    "Moving pending starting from %s to %s", fromToken, this);
             mStartingData = fromToken.mStartingData;
             fromToken.mStartingData = null;
             fromToken.startingMoved = true;
@@ -1651,27 +1730,18 @@
     }
 
     /** Returns the app's preferred orientation regardless of its currently visibility state. */
-    int getOrientationIgnoreVisibility() {
+    int getRequestedOrientation() {
         return mOrientation;
     }
 
     /** @return {@code true} if the compatibility bounds is taking effect. */
-    boolean inSizeCompatMode() {
+    boolean hasSizeCompatBounds() {
         return mSizeCompatBounds != null;
     }
 
     @Override
     float getSizeCompatScale() {
-        return inSizeCompatMode() ? mSizeCompatScale : super.getSizeCompatScale();
-    }
-
-    /**
-     * @return Non-empty bounds if the activity has override bounds.
-     * @see ActivityRecord#resolveOverrideConfiguration(Configuration)
-     */
-    Rect getResolvedOverrideBounds() {
-        // Get bounds from resolved override configuration because it is computed with orientation.
-        return getResolvedOverrideConfiguration().windowConfiguration.getBounds();
+        return hasSizeCompatBounds() ? mSizeCompatScale : super.getSizeCompatScale();
     }
 
     @Override
@@ -1704,7 +1774,7 @@
 
         final int winMode = getWindowingMode();
 
-        if (prevWinMode == winMode) {
+        if (prevWinMode == winMode || mDisplayContent == null) {
             return;
         }
 
@@ -1876,9 +1946,10 @@
         if (mFreezingScreen) {
             showAllWindowsLocked();
             stopFreezingScreen(false, true);
-            if (DEBUG_ORIENTATION) Slog.i(TAG,
-                    "Setting mOrientationChangeComplete=true because wtoken " + this
-                    + " numInteresting=" + mNumInterestingWindows + " numDrawn=" + mNumDrawnWindows);
+            ProtoLog.i(WM_DEBUG_ORIENTATION,
+                            "Setting mOrientationChangeComplete=true because wtoken %s "
+                                    + "numInteresting=%d numDrawn=%d",
+                            this, mNumInterestingWindows, mNumDrawnWindows);
             // This will set mOrientationChangeComplete and cause a pass through layout.
             setAppLayoutChanges(FINISH_LAYOUT_REDO_WALLPAPER,
                     "checkAppWindowsReadyToShow: freezingScreen");
@@ -1946,8 +2017,9 @@
         }
     }
 
+    // Mostly implemented in ActivityRecord...
     boolean keyDispatchingTimedOut(String reason, int windowPid) {
-        return mActivityRecord != null && mActivityRecord.keyDispatchingTimedOut(reason, windowPid);
+        return false;
     }
 
     /**
@@ -1982,7 +2054,7 @@
         boolean isInterestingAndDrawn = false;
 
         if (!allDrawn && w.mightAffectAllDrawn()) {
-            if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
+            if (DEBUG_VISIBILITY || WM_DEBUG_ORIENTATION.isLogToLogcat()) {
                 Slog.v(TAG, "Eval win " + w + ": isDrawn=" + w.isDrawnLw()
                         + ", isAnimationSet=" + isSelfAnimating());
                 if (!w.isDrawnLw()) {
@@ -2003,18 +2075,18 @@
                     if (w.isDrawnLw()) {
                         mNumDrawnWindows++;
 
-                        if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) Slog.v(TAG, "tokenMayBeDrawn: "
-                                + this + " w=" + w + " numInteresting=" + mNumInterestingWindows
-                                + " freezingScreen=" + mFreezingScreen
-                                + " mAppFreezing=" + w.mAppFreezing);
+                        if (DEBUG_VISIBILITY || WM_DEBUG_ORIENTATION.isLogToLogcat()) {
+                            Slog.v(TAG, "tokenMayBeDrawn: "
+                                    + this + " w=" + w + " numInteresting=" + mNumInterestingWindows
+                                    + " freezingScreen=" + mFreezingScreen
+                                    + " mAppFreezing=" + w.mAppFreezing);
+                        }
 
                         isInterestingAndDrawn = true;
                     }
                 }
             } else if (w.isDrawnLw()) {
-                if (mActivityRecord != null) {
-                    mActivityRecord.onStartingWindowDrawn(SystemClock.uptimeMillis());
-                }
+                onStartingWindowDrawn(SystemClock.uptimeMillis());
                 startingDisplayed = true;
             }
         }
@@ -2022,6 +2094,14 @@
         return isInterestingAndDrawn;
     }
 
+    /** Called when the starting window for this container is drawn. */
+    private void onStartingWindowDrawn(long timestamp) {
+        synchronized (mAtmService.mGlobalLock) {
+            mAtmService.mStackSupervisor.getActivityMetricsLogger().notifyStartingWindowDrawn(
+                    getWindowingMode(), timestamp);
+        }
+    }
+
     void layoutLetterbox(WindowState winHint) {
         final WindowState w = findMainWindow();
         if (w == null || winHint != null && w != winHint) {
@@ -2122,9 +2202,7 @@
         // If this is a translucent window, then don't show a starting window -- the current
         // effect (a full-screen opaque starting window that fades away to the real contents
         // when it is ready) does not work for this.
-        if (DEBUG_STARTING_WINDOW) {
-            Slog.v(TAG, "Checking theme of starting window: 0x" + Integer.toHexString(theme));
-        }
+        ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Checking theme of starting window: 0x%x", theme);
         if (theme != 0) {
             AttributeCache.Entry ent = AttributeCache.instance().get(pkg, theme,
                     com.android.internal.R.styleable.Window,
@@ -2142,11 +2220,8 @@
                     com.android.internal.R.styleable.Window_windowShowWallpaper, false);
             final boolean windowDisableStarting = ent.array.getBoolean(
                     com.android.internal.R.styleable.Window_windowDisablePreview, false);
-            if (DEBUG_STARTING_WINDOW) {
-                Slog.v(TAG, "Translucent=" + windowIsTranslucent
-                        + " Floating=" + windowIsFloating
-                        + " ShowWallpaper=" + windowShowWallpaper);
-            }
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Translucent=%s Floating=%s ShowWallpaper=%s",
+                        windowIsTranslucent, windowIsFloating, windowShowWallpaper);
             if (windowIsTranslucent) {
                 return false;
             }
@@ -2178,7 +2253,7 @@
             return false;
         }
 
-        if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Creating SplashScreenStartingData");
+        ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Creating SplashScreenStartingData");
         mStartingData = new SplashScreenStartingData(mWmService, pkg,
                 theme, compatInfo, nonLocalizedLabel, labelRes, icon, logo, windowFlags,
                 getMergedOverrideConfiguration());
@@ -2192,7 +2267,7 @@
             return false;
         }
 
-        if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Creating SnapshotStartingData");
+        ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Creating SnapshotStartingData");
         mStartingData = new SnapshotStartingData(mWmService, snapshot);
         scheduleAddStartingWindow();
         return true;
@@ -2203,7 +2278,7 @@
         // want to process the message ASAP, before any other queued
         // messages.
         if (!mWmService.mAnimationHandler.hasCallbacks(mAddStartingWindow)) {
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Enqueueing ADD_STARTING");
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Enqueueing ADD_STARTING");
             mWmService.mAnimationHandler.postAtFrontOfQueue(mAddStartingWindow);
         }
     }
@@ -2220,18 +2295,17 @@
 
                 if (mStartingData == null) {
                     // Animation has been canceled... do nothing.
-                    if (DEBUG_STARTING_WINDOW) {
-                        Slog.v(TAG, "startingData was nulled out before handling"
-                                + " mAddStartingWindow: " + AppWindowToken.this);
-                    }
+                    ProtoLog.v(WM_DEBUG_STARTING_WINDOW,
+                            "startingData was nulled out before handling"
+                                + " mAddStartingWindow: %s", AppWindowToken.this);
                     return;
                 }
                 startingData = mStartingData;
             }
 
-            if (DEBUG_STARTING_WINDOW) {
-                Slog.v(TAG, "Add starting " + this + ": startingData=" + startingData);
-            }
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Add starting %s: startingData=%s",
+                    this, startingData);
+
 
             WindowManagerPolicy.StartingSurface surface = null;
             try {
@@ -2245,27 +2319,28 @@
                     // If the window was successfully added, then
                     // we need to remove it.
                     if (removed || mStartingData == null) {
-                        if (DEBUG_STARTING_WINDOW) {
-                            Slog.v(TAG, "Aborted starting " + AppWindowToken.this
-                                    + ": removed=" + removed + " startingData=" + mStartingData);
-                        }
+                        ProtoLog.v(WM_DEBUG_STARTING_WINDOW,
+                                "Aborted starting %s: removed=%b startingData=%s",
+                                    AppWindowToken.this, removed, mStartingData);
+
                         startingWindow = null;
                         mStartingData = null;
                         abort = true;
                     } else {
                         startingSurface = surface;
                     }
-                    if (DEBUG_STARTING_WINDOW && !abort) {
-                        Slog.v(TAG,
-                                "Added starting " + AppWindowToken.this + ": startingWindow="
-                                        + startingWindow + " startingView=" + startingSurface);
+                    if (!abort) {
+                        ProtoLog.v(WM_DEBUG_STARTING_WINDOW,
+                                "Added starting %s: startingWindow=%s startingView=%s",
+                                AppWindowToken.this, startingWindow, startingSurface);
                     }
                 }
                 if (abort) {
                     surface.remove();
                 }
-            } else if (DEBUG_STARTING_WINDOW) {
-                Slog.v(TAG, "Surface returned was null: " + AppWindowToken.this);
+            } else {
+                ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Surface returned was null: %s",
+                        AppWindowToken.this);
             }
         }
     };
@@ -2308,9 +2383,7 @@
             if (mStartingData != null) {
                 // Starting window has not been added yet, but it is scheduled to be added.
                 // Go ahead and cancel the request.
-                if (DEBUG_STARTING_WINDOW) {
-                    Slog.v(TAG_WM, "Clearing startingData for token=" + this);
-                }
+                ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Clearing startingData for token=%s", this);
                 mStartingData = null;
             }
             return;
@@ -2324,31 +2397,28 @@
             startingWindow = null;
             startingDisplayed = false;
             if (surface == null) {
-                if (DEBUG_STARTING_WINDOW) {
-                    Slog.v(TAG_WM, "startingWindow was set but startingSurface==null, couldn't "
+                ProtoLog.v(WM_DEBUG_STARTING_WINDOW,
+                        "startingWindow was set but startingSurface==null, couldn't "
                             + "remove");
-                }
+
                 return;
             }
         } else {
-            if (DEBUG_STARTING_WINDOW) {
-                Slog.v(TAG_WM, "Tried to remove starting window but startingWindow was null:"
-                        + this);
-            }
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW,
+                    "Tried to remove starting window but startingWindow was null: %s",
+                        this);
             return;
         }
 
-        if (DEBUG_STARTING_WINDOW) {
-            Slog.v(TAG_WM, "Schedule remove starting " + this
-                    + " startingWindow=" + startingWindow
-                    + " startingView=" + startingSurface
-                    + " Callers=" + Debug.getCallers(5));
-        }
+        ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Schedule remove starting %s startingWindow=%s"
+                    + " startingView=%s Callers=%s",
+                    this, startingWindow, startingSurface, Debug.getCallers(5));
+
 
         // Use the same thread to remove the window as we used to add it, as otherwise we end up
         // with things in the view hierarchy being called from different threads.
         mWmService.mAnimationHandler.post(() -> {
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "Removing startingView=" + surface);
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Removing startingView=%s", surface);
             try {
                 surface.remove();
             } catch (Exception e) {
@@ -2416,6 +2486,66 @@
         return false;
     }
 
+    void setShowWhenLocked(boolean showWhenLocked) {
+        mShowWhenLocked = showWhenLocked;
+        mAtmService.mRootActivityContainer.ensureActivitiesVisible(null /* starting */,
+                0 /* configChanges */, false /* preserveWindows */);
+    }
+
+    void setInheritShowWhenLocked(boolean inheritShowWhenLocked) {
+        mInheritShownWhenLocked = inheritShowWhenLocked;
+        mAtmService.mRootActivityContainer.ensureActivitiesVisible(null /* starting */,
+                0 /* configChanges */, false /* preserveWindows */);
+    }
+
+    /**
+     * @return {@code true} if the activity windowing mode is not
+     *         {@link android.app.WindowConfiguration#WINDOWING_MODE_PINNED} and a) activity
+     *         contains windows that have {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED} set or if the
+     *         activity has set {@link #mShowWhenLocked}, or b) if the activity has set
+     *         {@link #mInheritShownWhenLocked} and the activity behind this satisfies the
+     *         conditions a) above.
+     *         Multi-windowing mode will be exited if {@code true} is returned.
+     */
+    boolean canShowWhenLocked() {
+        if (!inPinnedWindowingMode() && (mShowWhenLocked || containsShowWhenLockedWindow())) {
+            return true;
+        } else if (mInheritShownWhenLocked) {
+            final AppWindowToken r = getActivityBelow();
+            return r != null && !r.inPinnedWindowingMode() && (r.mShowWhenLocked
+                    || r.containsShowWhenLockedWindow());
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * @return an {@link ActivityRecord} of the activity below this activity, or {@code null} if no
+     * such activity exists.
+     */
+    @Nullable
+    private AppWindowToken getActivityBelow() {
+        final Task task = getTask();
+        final int pos = task.mChildren.indexOf(this);
+        if (pos == -1) {
+            throw new IllegalStateException("Activity not found in its task");
+        }
+        return pos == 0 ? null : task.getChildAt(pos - 1);
+    }
+
+    void setTurnScreenOn(boolean turnScreenOn) {
+        mTurnScreenOn = turnScreenOn;
+    }
+
+    /** Mostly implemented in ActivityRecord. */
+    boolean canTurnScreenOn() {
+        return mTurnScreenOn;
+    }
+
+    boolean getTurnScreenOnFlag() {
+        return mTurnScreenOn;
+    }
+
     void checkKeyguardFlagsChanged() {
         final boolean containsDismissKeyguard = containsDismissKeyguardWindow();
         final boolean containsShowWhenLocked = containsShowWhenLockedWindow();
@@ -2544,7 +2674,7 @@
      * Creates a layer to apply crop to an animation.
      */
     private SurfaceControl createAnimationBoundsLayer(Transaction t) {
-        if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.i(TAG, "Creating animation bounds layer");
+        ProtoLog.i(WM_DEBUG_APP_TRANSITIONS_ANIM, "Creating animation bounds layer");
         final SurfaceControl.Builder builder = makeAnimationLeash()
                 .setParent(getAnimationLeashParent())
                 .setName(getSurfaceControl() + " - animation-bounds");
@@ -2580,10 +2710,9 @@
             boolean isVoiceInteraction) {
 
         if (mWmService.mDisableTransitionAnimation || !shouldAnimate(transit)) {
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
-                Slog.v(TAG_WM, "applyAnimation: transition animation is disabled or skipped."
-                        + " atoken=" + this);
-            }
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                    "applyAnimation: transition animation is disabled or skipped. "
+                            + "atoken=%s", this);
             cancelAnimation();
             return false;
         }
@@ -2683,8 +2812,8 @@
         final DisplayInfo displayInfo = displayContent.getDisplayInfo();
         final int width = displayInfo.appWidth;
         final int height = displayInfo.appHeight;
-        if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG_WM,
-                "applyAnimation: atoken=" + this);
+        ProtoLog.v(WM_DEBUG_APP_TRANSITIONS_ANIM,
+                "applyAnimation: atoken=%s", this);
 
         // Determine the visible rect to calculate the thumbnail clip
         final WindowState win = findMainWindow();
@@ -2724,9 +2853,10 @@
             // screen gets the enter animation. Both appear in the mOpeningApps set.
             enter = false;
         }
-        if (DEBUG_APP_TRANSITIONS) Slog.d(TAG_WM, "Loading animation for app transition."
-                + " transit=" + AppTransition.appTransitionToString(transit) + " enter=" + enter
-                + " frame=" + frame + " insets=" + insets + " surfaceInsets=" + surfaceInsets);
+        ProtoLog.d(WM_DEBUG_APP_TRANSITIONS,
+                "Loading animation for app transition. transit=%s enter=%b frame=%s insets=%s "
+                        + "surfaceInsets=%s",
+                AppTransition.appTransitionToString(transit), enter, frame, insets, surfaceInsets);
         final Configuration displayConfig = displayContent.getConfiguration();
         final Animation a = getDisplayContent().mAppTransition.loadAnimation(lp, transit, enter,
                 displayConfig.uiMode, displayConfig.orientation, frame, displayFrame, insets,
@@ -2800,7 +2930,7 @@
             layer += Z_BOOST_BASE;
         }
         if (!mNeedsAnimationBoundsLayer) {
-            leash.setLayer(layer);
+            t.setLayer(leash, layer);
         }
 
         final DisplayContent dc = getDisplayContent();
@@ -2893,7 +3023,21 @@
         getDisplayContent().mAppTransition.notifyAppTransitionFinishedLocked(token);
         scheduleAnimation();
 
-        mActivityRecord.onAnimationFinished();
+        if (mAtmService.mRootActivityContainer.allResumedActivitiesIdle()
+                || mAtmService.mStackSupervisor.isStoppingNoHistoryActivity()) {
+            // If all activities are already idle or there is an activity that must be
+            // stopped immediately after visible, then we now need to make sure we perform
+            // the full stop of this activity. This is because we won't do that while they are still
+            // waiting for the animation to finish.
+            if (mAtmService.mStackSupervisor.mStoppingActivities.contains(this)) {
+                mAtmService.mStackSupervisor.scheduleIdleLocked();
+            }
+        } else {
+            // Instead of doing the full stop routine here, let's just hide any activities
+            // we now can, and let them stop when the normal idle happens.
+            mAtmService.mStackSupervisor.processStoppingActivitiesLocked(null /* idleActivity */,
+                    false /* remove */, true /* processPausingActivities */);
+        }
         Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
     }
 
@@ -2960,10 +3104,13 @@
     }
 
     boolean isWaitingForTransitionStart() {
-        return getDisplayContent().mAppTransition.isTransitionSet()
-                && (getDisplayContent().mOpeningApps.contains(this)
-                    || getDisplayContent().mClosingApps.contains(this)
-                    || getDisplayContent().mChangingApps.contains(this));
+        final DisplayContent dc = getDisplayContent();
+        // TODO: Test for null can be removed once unification is done.
+        if (dc == null) return false;
+        return dc.mAppTransition.isTransitionSet()
+                && (dc.mOpeningApps.contains(this)
+                    || dc.mClosingApps.contains(this)
+                    || dc.mChangingApps.contains(this));
     }
 
     public int getTransit() {
@@ -2982,7 +3129,7 @@
         final GraphicBuffer thumbnailHeader =
                 getDisplayContent().mAppTransition.getAppTransitionThumbnailHeader(taskId);
         if (thumbnailHeader == null) {
-            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG, "No thumbnail header bitmap for: " + taskId);
+            ProtoLog.d(WM_DEBUG_APP_TRANSITIONS, "No thumbnail header bitmap for: %d", taskId);
             return;
         }
         clearThumbnail();
@@ -3207,27 +3354,17 @@
     }
 
     void writeNameToProto(ProtoOutputStream proto, long fieldId) {
-        if (appToken == null) {
-            return;
-        }
-        try {
+        if (appToken != null) {
             proto.write(fieldId, appToken.getName());
-        } catch (RemoteException e) {
-            // This shouldn't happen, but in this case fall back to outputting nothing
-            Slog.e(TAG, e.toString());
         }
     }
 
-    @Override
-    public String toString() {
-        if (stringName == null) {
-            StringBuilder sb = new StringBuilder();
-            sb.append("AppWindowToken{");
-            sb.append(Integer.toHexString(System.identityHashCode(this)));
-            sb.append(" token="); sb.append(token); sb.append('}');
-            stringName = sb.toString();
-        }
-        return stringName + ((mIsExiting) ? " mIsExiting=" : "");
+    void writeIdentifierToProto(ProtoOutputStream proto, long fieldId) {
+        final long token = proto.start(fieldId);
+        proto.write(HASH_CODE, System.identityHashCode(this));
+        proto.write(USER_ID, mUserId);
+        proto.write(TITLE, ((ActivityRecord) this).intent.getComponent().flattenToShortString());
+        proto.end(token);
     }
 
     Rect getLetterboxInsets() {
diff --git a/services/core/java/com/android/server/wm/BlackFrame.java b/services/core/java/com/android/server/wm/BlackFrame.java
index 7557271a..b4cecff 100644
--- a/services/core/java/com/android/server/wm/BlackFrame.java
+++ b/services/core/java/com/android/server/wm/BlackFrame.java
@@ -16,16 +16,14 @@
 
 package com.android.server.wm;
 
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_SURFACE_ALLOC;
 
-import android.graphics.Matrix;
 import android.graphics.Rect;
-import android.util.Slog;
 import android.view.Surface.OutOfResourcesException;
 import android.view.SurfaceControl;
 
+import com.android.server.protolog.common.ProtoLog;
+
 import java.io.PrintWriter;
 import java.util.function.Supplier;
 
@@ -33,14 +31,15 @@
  * Four black surfaces put together to make a black frame.
  */
 public class BlackFrame {
-    class BlackSurface {
+    static class BlackSurface {
         final int left;
         final int top;
         final int layer;
         final SurfaceControl surface;
 
         BlackSurface(SurfaceControl.Transaction transaction, int layer,
-                int l, int t, int r, int b, DisplayContent dc) throws OutOfResourcesException {
+                int l, int t, int r, int b, DisplayContent dc,
+                SurfaceControl surfaceControl) throws OutOfResourcesException {
             left = l;
             top = t;
             this.layer = layer;
@@ -50,7 +49,7 @@
             surface = dc.makeOverlay()
                     .setName("BlackSurface")
                     .setColorLayer()
-                    .setParent(null) // TODO: Work-around for b/69259549
+                    .setParent(surfaceControl)
                     .build();
             transaction.setWindowCrop(surface, w, h);
             transaction.setLayerStack(surface, dc.getDisplayId());
@@ -58,46 +57,15 @@
             transaction.setLayer(surface, layer);
             transaction.setPosition(surface, left, top);
             transaction.show(surface);
-            if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) Slog.i(TAG_WM,
-                            "  BLACK " + surface + ": CREATE layer=" + layer);
-        }
-
-        void setAlpha(SurfaceControl.Transaction t, float alpha) {
-            t.setAlpha(surface, alpha);
-        }
-
-        void setMatrix(SurfaceControl.Transaction t, Matrix matrix) {
-            mTmpMatrix.setTranslate(left, top);
-            mTmpMatrix.postConcat(matrix);
-            mTmpMatrix.getValues(mTmpFloats);
-            t.setPosition(surface, mTmpFloats[Matrix.MTRANS_X],
-                    mTmpFloats[Matrix.MTRANS_Y]);
-            t.setMatrix(surface,
-                    mTmpFloats[Matrix.MSCALE_X], mTmpFloats[Matrix.MSKEW_Y],
-                    mTmpFloats[Matrix.MSKEW_X], mTmpFloats[Matrix.MSCALE_Y]);
-            if (false) {
-                Slog.i(TAG_WM, "Black Surface @ (" + left + "," + top + "): ("
-                        + mTmpFloats[Matrix.MTRANS_X] + ","
-                        + mTmpFloats[Matrix.MTRANS_Y] + ") matrix=["
-                        + mTmpFloats[Matrix.MSCALE_X] + ","
-                        + mTmpFloats[Matrix.MSCALE_Y] + "]["
-                        + mTmpFloats[Matrix.MSKEW_X] + ","
-                        + mTmpFloats[Matrix.MSKEW_Y] + "]");
-            }
-        }
-
-        void clearMatrix(SurfaceControl.Transaction t) {
-            t.setMatrix(surface, 1, 0, 0, 1);
+            ProtoLog.i(WM_SHOW_SURFACE_ALLOC,
+                    "  BLACK %s: CREATE layer=%d", surface, layer);
         }
     }
 
-    final Rect mOuterRect;
-    final Rect mInnerRect;
-    final Matrix mTmpMatrix = new Matrix();
-    final float[] mTmpFloats = new float[9];
-    final BlackSurface[] mBlackSurfaces = new BlackSurface[4];
+    private final Rect mOuterRect;
+    private final Rect mInnerRect;
+    private final BlackSurface[] mBlackSurfaces = new BlackSurface[4];
 
-    final boolean mForceDefaultOrientation;
     private final Supplier<SurfaceControl.Transaction> mTransactionFactory;
 
     public void printTo(String prefix, PrintWriter pw) {
@@ -114,12 +82,12 @@
     }
 
     public BlackFrame(Supplier<SurfaceControl.Transaction> factory, SurfaceControl.Transaction t,
-            Rect outer, Rect inner, int layer, DisplayContent dc, boolean forceDefaultOrientation)
+            Rect outer, Rect inner, int layer, DisplayContent dc, boolean forceDefaultOrientation,
+            SurfaceControl surfaceControl)
             throws OutOfResourcesException {
         boolean success = false;
 
         mTransactionFactory = factory;
-        mForceDefaultOrientation = forceDefaultOrientation;
 
         // TODO: Why do we use 4 surfaces instead of just one big one behind the screenshot?
         // b/68253229
@@ -128,19 +96,20 @@
         try {
             if (outer.top < inner.top) {
                 mBlackSurfaces[0] = new BlackSurface(t, layer,
-                        outer.left, outer.top, inner.right, inner.top, dc);
+                        outer.left, outer.top, inner.right, inner.top, dc, surfaceControl);
             }
             if (outer.left < inner.left) {
                 mBlackSurfaces[1] = new BlackSurface(t, layer,
-                        outer.left, inner.top, inner.left, outer.bottom, dc);
+                        outer.left, inner.top, inner.left, outer.bottom, dc, surfaceControl);
             }
             if (outer.bottom > inner.bottom) {
                 mBlackSurfaces[2] = new BlackSurface(t, layer,
-                        inner.left, inner.bottom, outer.right, outer.bottom, dc);
+                        inner.left, inner.bottom, outer.right, outer.bottom, dc,
+                        surfaceControl);
             }
             if (outer.right > inner.right) {
                 mBlackSurfaces[3] = new BlackSurface(t, layer,
-                        inner.right, outer.top, outer.right, inner.bottom, dc);
+                        inner.right, outer.top, outer.right, inner.bottom, dc, surfaceControl);
             }
             success = true;
         } finally {
@@ -151,51 +120,14 @@
     }
 
     public void kill() {
-        if (mBlackSurfaces != null) {
-            SurfaceControl.Transaction t = mTransactionFactory.get();
-            for (int i=0; i<mBlackSurfaces.length; i++) {
-                if (mBlackSurfaces[i] != null) {
-                    if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) Slog.i(TAG_WM,
-                            "  BLACK " + mBlackSurfaces[i].surface + ": DESTROY");
-                    t.remove(mBlackSurfaces[i].surface);
-                    mBlackSurfaces[i] = null;
-                }
-            }
-            t.apply();
-        }
-    }
-
-    public void hide(SurfaceControl.Transaction t) {
-        if (mBlackSurfaces != null) {
-            for (int i=0; i<mBlackSurfaces.length; i++) {
-                if (mBlackSurfaces[i] != null) {
-                    t.hide(mBlackSurfaces[i].surface);
-                }
-            }
-        }
-    }
-
-    public void setAlpha(SurfaceControl.Transaction t, float alpha) {
-        for (int i=0; i<mBlackSurfaces.length; i++) {
+        SurfaceControl.Transaction t = mTransactionFactory.get();
+        for (int i = 0; i < mBlackSurfaces.length; i++) {
             if (mBlackSurfaces[i] != null) {
-                mBlackSurfaces[i].setAlpha(t, alpha);
+                ProtoLog.i(WM_SHOW_SURFACE_ALLOC, "  BLACK %s: DESTROY", mBlackSurfaces[i].surface);
+                t.remove(mBlackSurfaces[i].surface);
+                mBlackSurfaces[i] = null;
             }
         }
-    }
-
-    public void setMatrix(SurfaceControl.Transaction t, Matrix matrix) {
-        for (int i=0; i<mBlackSurfaces.length; i++) {
-            if (mBlackSurfaces[i] != null) {
-                mBlackSurfaces[i].setMatrix(t, matrix);
-            }
-        }
-    }
-
-    public void clearMatrix(SurfaceControl.Transaction t) {
-        for (int i=0; i<mBlackSurfaces.length; i++) {
-            if (mBlackSurfaces[i] != null) {
-                mBlackSurfaces[i].clearMatrix(t);
-            }
-        }
+        t.apply();
     }
 }
diff --git a/services/core/java/com/android/server/wm/CircularDisplayMask.java b/services/core/java/com/android/server/wm/CircularDisplayMask.java
index c1ca816..b73b481 100644
--- a/services/core/java/com/android/server/wm/CircularDisplayMask.java
+++ b/services/core/java/com/android/server/wm/CircularDisplayMask.java
@@ -56,7 +56,7 @@
     private int mMaskThickness;
 
     CircularDisplayMask(Supplier<Surface> surfaceFactory, DisplayContent dc, int zOrder,
-            int screenOffset, int maskThickness) {
+            int screenOffset, int maskThickness, SurfaceControl.Transaction t) {
         final Display display = dc.getDisplay();
         mSurface = surfaceFactory.get();
         mScreenSize = new Point();
@@ -75,10 +75,10 @@
                     .setFormat(PixelFormat.TRANSLUCENT)
                     .build();
 
-            ctrl.setLayerStack(display.getLayerStack());
-            ctrl.setLayer(zOrder);
-            ctrl.setPosition(0, 0);
-            ctrl.show();
+            t.setLayerStack(ctrl, display.getLayerStack());
+            t.setLayer(ctrl, zOrder);
+            t.setPosition(ctrl, 0, 0);
+            t.show(ctrl);
             mSurface.copyFrom(ctrl);
         } catch (OutOfResourcesException e) {
         }
@@ -91,7 +91,7 @@
         mMaskThickness = maskThickness;
     }
 
-    private void drawIfNeeded() {
+    private void drawIfNeeded(SurfaceControl.Transaction t) {
         if (!mDrawNeeded || !mVisible || mDimensionsUnequal) {
             return;
         }
@@ -108,45 +108,46 @@
             return;
         }
         switch (mRotation) {
-        case Surface.ROTATION_0:
-        case Surface.ROTATION_90:
-            // chin bottom or right
-            mSurfaceControl.setPosition(0, 0);
-            break;
-        case Surface.ROTATION_180:
-            // chin top
-            mSurfaceControl.setPosition(0, -mScreenOffset);
-            break;
-        case Surface.ROTATION_270:
-            // chin left
-            mSurfaceControl.setPosition(-mScreenOffset, 0);
-            break;
+            case Surface.ROTATION_0:
+            case Surface.ROTATION_90:
+                // chin bottom or right
+                t.setPosition(mSurfaceControl, 0, 0);
+                break;
+            case Surface.ROTATION_180:
+                // chin top
+                t.setPosition(mSurfaceControl, 0, -mScreenOffset);
+                break;
+            case Surface.ROTATION_270:
+                // chin left
+                t.setPosition(mSurfaceControl, -mScreenOffset, 0);
+                break;
         }
 
         int circleRadius = mScreenSize.x / 2;
         c.drawColor(Color.BLACK);
 
-        // The radius is reduced by mMaskThickness to provide an anti aliasing effect on the display edges.
+        // The radius is reduced by mMaskThickness to provide an anti aliasing effect on the
+        // display edges.
         c.drawCircle(circleRadius, circleRadius, circleRadius - mMaskThickness, mPaint);
         mSurface.unlockCanvasAndPost(c);
     }
 
     // Note: caller responsible for being inside
     // Surface.openTransaction() / closeTransaction()
-    public void setVisibility(boolean on) {
+    public void setVisibility(boolean on, SurfaceControl.Transaction t) {
         if (mSurfaceControl == null) {
             return;
         }
         mVisible = on;
-        drawIfNeeded();
+        drawIfNeeded(t);
         if (on) {
-            mSurfaceControl.show();
+            t.show(mSurfaceControl);
         } else {
-            mSurfaceControl.hide();
+            t.hide(mSurfaceControl);
         }
     }
 
-    void positionSurface(int dw, int dh, int rotation) {
+    void positionSurface(int dw, int dh, int rotation, SurfaceControl.Transaction t) {
         if (mLastDW == dw && mLastDH == dh && mRotation == rotation) {
             return;
         }
@@ -154,7 +155,7 @@
         mLastDH = dh;
         mDrawNeeded = true;
         mRotation = rotation;
-        drawIfNeeded();
+        drawIfNeeded(t);
     }
 
 }
diff --git a/services/core/java/com/android/server/wm/ConfigurationContainer.java b/services/core/java/com/android/server/wm/ConfigurationContainer.java
index 3886ae1..8afbbdf 100644
--- a/services/core/java/com/android/server/wm/ConfigurationContainer.java
+++ b/services/core/java/com/android/server/wm/ConfigurationContainer.java
@@ -90,7 +90,8 @@
     private ArrayList<ConfigurationContainerListener> mChangeListeners = new ArrayList<>();
 
     // TODO: Can't have ag/2592611 soon enough!
-    private final Configuration mTmpConfig = new Configuration();
+    private final Configuration mRequestsTmpConfig = new Configuration();
+    private final Configuration mResolvedTmpConfig = new Configuration();
 
     // Used for setting bounds
     private final Rect mTmpRect = new Rect();
@@ -121,12 +122,19 @@
      * @see #mFullConfiguration
      */
     public void onConfigurationChanged(Configuration newParentConfig) {
-        mTmpConfig.setTo(mResolvedOverrideConfiguration);
+        onConfigurationChanged(newParentConfig, true /*forwardToChildren*/);
+    }
+
+    // TODO: Consolidate with onConfigurationChanged() method above once unification is done. This
+    // is only currently need during the process of unification where we don't want configuration
+    // forwarded to a child from both parents.
+    public void onConfigurationChanged(Configuration newParentConfig, boolean forwardToChildren) {
+        mResolvedTmpConfig.setTo(mResolvedOverrideConfiguration);
         resolveOverrideConfiguration(newParentConfig);
         mFullConfiguration.setTo(newParentConfig);
         mLastOverrideConfigurationChanges =
                 mFullConfiguration.updateFrom(mResolvedOverrideConfiguration);
-        if (!mTmpConfig.equals(mResolvedOverrideConfiguration)) {
+        if (!mResolvedTmpConfig.equals(mResolvedOverrideConfiguration)) {
             onMergedOverrideConfigurationChanged();
             // This depends on the assumption that change-listeners don't do
             // their own override resolution. This way, dependent hierarchies
@@ -139,9 +147,11 @@
                         mResolvedOverrideConfiguration);
             }
         }
-        for (int i = getChildCount() - 1; i >= 0; --i) {
-            final ConfigurationContainer child = getChildAt(i);
-            child.onConfigurationChanged(mFullConfiguration);
+        if (forwardToChildren) {
+            for (int i = getChildCount() - 1; i >= 0; --i) {
+                final ConfigurationContainer child = getChildAt(i);
+                child.onConfigurationChanged(mFullConfiguration);
+            }
         }
     }
 
@@ -262,6 +272,11 @@
         out.set(bounds.left, bounds.top);
     }
 
+    Rect getResolvedOverrideBounds() {
+        mReturnBounds.set(getResolvedOverrideConfiguration().windowConfiguration.getBounds());
+        return mReturnBounds;
+    }
+
     /**
      * Returns the bounds requested on this container. These may not be the actual bounds the
      * container ends up with due to policy constraints. The {@link Rect} handed back is
@@ -306,9 +321,9 @@
         }
 
 
-        mTmpConfig.setTo(getRequestedOverrideConfiguration());
-        mTmpConfig.windowConfiguration.setBounds(bounds);
-        onRequestedOverrideConfigurationChanged(mTmpConfig);
+        mRequestsTmpConfig.setTo(getRequestedOverrideConfiguration());
+        mRequestsTmpConfig.windowConfiguration.setBounds(bounds);
+        onRequestedOverrideConfigurationChanged(mRequestsTmpConfig);
 
         return boundsChange;
     }
@@ -360,9 +375,9 @@
 
     /** Sets the requested windowing mode override for the configuration container. */
     public void setWindowingMode(/*@WindowConfiguration.WindowingMode*/ int windowingMode) {
-        mTmpConfig.setTo(getRequestedOverrideConfiguration());
-        mTmpConfig.windowConfiguration.setWindowingMode(windowingMode);
-        onRequestedOverrideConfigurationChanged(mTmpConfig);
+        mRequestsTmpConfig.setTo(getRequestedOverrideConfiguration());
+        mRequestsTmpConfig.windowConfiguration.setWindowingMode(windowingMode);
+        onRequestedOverrideConfigurationChanged(mRequestsTmpConfig);
     }
 
     /** Sets the always on top flag for this configuration container.
@@ -372,16 +387,16 @@
      *  - {@Link ActivityDisplay#positionChildAtTop(ActivityStack)};
      * */
     public void setAlwaysOnTop(boolean alwaysOnTop) {
-        mTmpConfig.setTo(getRequestedOverrideConfiguration());
-        mTmpConfig.windowConfiguration.setAlwaysOnTop(alwaysOnTop);
-        onRequestedOverrideConfigurationChanged(mTmpConfig);
+        mRequestsTmpConfig.setTo(getRequestedOverrideConfiguration());
+        mRequestsTmpConfig.windowConfiguration.setAlwaysOnTop(alwaysOnTop);
+        onRequestedOverrideConfigurationChanged(mRequestsTmpConfig);
     }
 
     /** Sets the windowing mode for the configuration container. */
     void setDisplayWindowingMode(int windowingMode) {
-        mTmpConfig.setTo(getRequestedOverrideConfiguration());
-        mTmpConfig.windowConfiguration.setDisplayWindowingMode(windowingMode);
-        onRequestedOverrideConfigurationChanged(mTmpConfig);
+        mRequestsTmpConfig.setTo(getRequestedOverrideConfiguration());
+        mRequestsTmpConfig.windowConfiguration.setDisplayWindowingMode(windowingMode);
+        onRequestedOverrideConfigurationChanged(mRequestsTmpConfig);
     }
 
     /**
@@ -451,9 +466,9 @@
             throw new IllegalStateException("Can't change activity type once set: " + this
                     + " activityType=" + activityTypeToString(activityType));
         }
-        mTmpConfig.setTo(getRequestedOverrideConfiguration());
-        mTmpConfig.windowConfiguration.setActivityType(activityType);
-        onRequestedOverrideConfigurationChanged(mTmpConfig);
+        mRequestsTmpConfig.setTo(getRequestedOverrideConfiguration());
+        mRequestsTmpConfig.windowConfiguration.setActivityType(activityType);
+        onRequestedOverrideConfigurationChanged(mRequestsTmpConfig);
     }
 
     public boolean isActivityTypeHome() {
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 63ff2ea..ac910cd 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -59,11 +59,10 @@
 import static android.view.WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE;
 import static android.view.WindowManager.LayoutParams.NEEDS_MENU_UNSET;
 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
-import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
+import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
 import static android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS;
 import static android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER;
-import static android.view.WindowManager.LayoutParams.TYPE_DRAWN_APPLICATION;
 import static android.view.WindowManager.LayoutParams.TYPE_DREAM;
 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
@@ -100,24 +99,21 @@
 import static com.android.server.wm.DisplayContentProto.SCREEN_ROTATION_ANIMATION;
 import static com.android.server.wm.DisplayContentProto.STACKS;
 import static com.android.server.wm.DisplayContentProto.WINDOW_CONTAINER;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_BOOT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_SCREEN_ON;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DISPLAY;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_INPUT_METHOD;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREENSHOT;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREEN_ON;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TOKEN_MOVEMENT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_STACK_CRAWLS;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 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.REPORT_FOCUS_CHANGE;
@@ -133,11 +129,9 @@
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_WILL_PLACE_SURFACES;
 import static com.android.server.wm.WindowManagerService.WINDOWS_FREEZING_SCREENS_TIMEOUT;
 import static com.android.server.wm.WindowManagerService.dipToPixel;
-import static com.android.server.wm.WindowManagerService.logSurface;
 import static com.android.server.wm.WindowState.EXCLUSION_LEFT;
 import static com.android.server.wm.WindowState.EXCLUSION_RIGHT;
 import static com.android.server.wm.WindowState.RESIZE_HANDLE_WIDTH_IN_DP;
-import static com.android.server.wm.WindowStateAnimator.DRAW_PENDING;
 import static com.android.server.wm.WindowStateAnimator.READY_TO_SHOW;
 import static com.android.server.wm.utils.RegionUtils.forEachRectReverse;
 import static com.android.server.wm.utils.RegionUtils.rectListToRegion;
@@ -173,6 +167,7 @@
 import android.util.ArraySet;
 import android.util.DisplayMetrics;
 import android.util.Slog;
+import android.util.SparseBooleanArray;
 import android.util.proto.ProtoOutputStream;
 import android.view.Display;
 import android.view.DisplayCutout;
@@ -202,6 +197,7 @@
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.AnimationThread;
 import com.android.server.policy.WindowManagerPolicy;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.utils.DisplayRotationUtil;
 import com.android.server.wm.utils.RotationCache;
 import com.android.server.wm.utils.WmDisplayCutout;
@@ -224,7 +220,7 @@
  * particular Display.
  */
 class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowContainer>
-        implements WindowManagerPolicy.DisplayContentInfo {
+        implements WindowManagerPolicy.DisplayContentInfo, ConfigurationContainerListener {
     private static final String TAG = TAG_WITH_CLASS_NAME ? "DisplayContent" : TAG_WM;
 
     /** The default scaling mode that scales content automatically. */
@@ -243,7 +239,7 @@
     private final int mDisplayId;
 
     // TODO: Remove once unification is complete.
-    ActivityDisplay mAcitvityDisplay;
+    ActivityDisplay mActivityDisplay;
 
     /** The containers below are the only child containers the display can have. */
     // Contains all window containers that are related to apps (Activities)
@@ -335,7 +331,7 @@
 
     /**
      * For default display it contains real metrics, empty for others.
-     * @see WindowManagerService#createWatermarkInTransaction()
+     * @see WindowManagerService#createWatermark()
      */
     final DisplayMetrics mRealDisplayMetrics = new DisplayMetrics();
 
@@ -442,11 +438,6 @@
     /** A collection of windows that provide tap exclude regions inside of them. */
     final ArraySet<WindowState> mTapExcludeProvidingWindows = new ArraySet<>();
 
-    private boolean mHaveBootMsg = false;
-    private boolean mHaveApp = false;
-    private boolean mHaveWallpaper = false;
-    private boolean mHaveKeyguard = true;
-
     private final LinkedList<AppWindowToken> mTmpUpdateAllDrawn = new LinkedList();
 
     private final TaskForResizePointSearchResult mTmpTaskForResizePointSearchResult =
@@ -497,6 +488,8 @@
     /** Windows removed since {@link #mCurrentFocus} was set to null. Used for ANR blaming. */
     final ArrayList<WindowState> mWinRemovedSinceNullFocus = new ArrayList<>();
 
+    private ScreenRotationAnimation mScreenRotationAnimation;
+
     /**
      * We organize all top-level Surfaces in to the following layers.
      * mOverlayLayer contains a few Surfaces which are always on top of others
@@ -521,9 +514,6 @@
      */
     private int mDeferUpdateImeTargetCount;
 
-    /** Temporary float array to retrieve 3x3 matrix values. */
-    private final float[] mTmpFloats = new float[9];
-
     private MagnificationSpec mMagnificationSpec;
 
     private InputMonitor mInputMonitor;
@@ -564,6 +554,10 @@
     // Last systemUiVisibility we dispatched to windows.
     private int mLastDispatchedSystemUiVisibility = 0;
 
+    private final ArrayList<TaskStack> mTmpAlwaysOnTopStacks = new ArrayList<>();
+    private final ArrayList<TaskStack> mTmpNormalStacks = new ArrayList<>();
+    private final ArrayList<TaskStack> mTmpHomeStacks = new ArrayList<>();
+
     /** Corner radius that windows should have in order to match the display. */
     private final float mWindowCornerRadius;
 
@@ -596,8 +590,8 @@
 
     private final ToBooleanFunction<WindowState> mFindFocusedWindow = w -> {
         final AppWindowToken focusedApp = mFocusedApp;
-        if (DEBUG_FOCUS) Slog.v(TAG_WM, "Looking for focus: " + w
-                + ", flags=" + w.mAttrs.flags + ", canReceive=" + w.canReceiveKeys());
+        ProtoLog.v(WM_DEBUG_FOCUS, "Looking for focus: %s, flags=%d, canReceive=%b",
+                w, w.mAttrs.flags, w.canReceiveKeys());
 
         if (!w.canReceiveKeys()) {
             return false;
@@ -607,22 +601,22 @@
 
         // If this window's application has been removed, just skip it.
         if (wtoken != null && (wtoken.removed || wtoken.sendingToBottom)) {
-            if (DEBUG_FOCUS) Slog.v(TAG_WM, "Skipping " + wtoken + " because "
-                    + (wtoken.removed ? "removed" : "sendingToBottom"));
+            ProtoLog.v(WM_DEBUG_FOCUS, "Skipping %s because %s", wtoken,
+                    (wtoken.removed ? "removed" : "sendingToBottom"));
             return false;
         }
 
         if (focusedApp == null) {
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "findFocusedWindow: focusedApp=null"
-                    + " using new focus @ " + w);
+            ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
+                    "findFocusedWindow: focusedApp=null using new focus @ %s", w);
             mTmpWindow = w;
             return true;
         }
 
         if (!focusedApp.windowsAreFocusable()) {
             // Current focused app windows aren't focusable...
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "findFocusedWindow: focusedApp windows not"
-                    + " focusable using new focus @ " + w);
+            ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "findFocusedWindow: focusedApp windows not"
+                    + " focusable using new focus @ %s", w);
             mTmpWindow = w;
             return true;
         }
@@ -632,14 +626,14 @@
         if (wtoken != null && w.mAttrs.type != TYPE_APPLICATION_STARTING) {
             if (focusedApp.compareTo(wtoken) > 0) {
                 // App stack below focused app stack. No focus for you!!!
-                if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM,
-                        "findFocusedWindow: Reached focused app=" + focusedApp);
+                ProtoLog.v(WM_DEBUG_FOCUS_LIGHT,
+                        "findFocusedWindow: Reached focused app=%s", focusedApp);
                 mTmpWindow = null;
                 return true;
             }
         }
 
-        if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "findFocusedWindow: Found new focus @ " + w);
+        ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "findFocusedWindow: Found new focus @ %s", w);
         mTmpWindow = w;
         return true;
     };
@@ -857,7 +851,7 @@
     DisplayContent(Display display, WindowManagerService service,
             ActivityDisplay activityDisplay) {
         super(service);
-        mAcitvityDisplay = activityDisplay;
+        mActivityDisplay = activityDisplay;
         if (service.mRoot.getDisplayContent(display.getDisplayId()) != null) {
             throw new IllegalArgumentException("Display with ID=" + display.getDisplayId()
                     + " already exists=" + service.mRoot.getDisplayContent(display.getDisplayId())
@@ -1141,9 +1135,12 @@
      * values from being replaced by the initializing {@link #ActivityDisplay}.
      */
     void initializeDisplayOverrideConfiguration() {
-        if (mAcitvityDisplay != null) {
-            mAcitvityDisplay.onInitializeOverrideConfiguration(getRequestedOverrideConfiguration());
+        if (mActivityDisplay == null) {
+            return;
         }
+        mActivityDisplay.onRequestedOverrideConfigurationChanged(
+                getResolvedOverrideConfiguration());
+        mActivityDisplay.registerConfigurationChangeListener(this);
     }
 
     void reconfigureDisplayLocked() {
@@ -1169,10 +1166,10 @@
     }
 
     void sendNewConfiguration() {
-        if (!isReady() || mAcitvityDisplay == null) {
+        if (!isReady() || mActivityDisplay == null) {
             return;
         }
-        final boolean configUpdated = mAcitvityDisplay.updateDisplayOverrideConfigurationLocked();
+        final boolean configUpdated = mActivityDisplay.updateDisplayOverrideConfigurationLocked();
         if (configUpdated) {
             return;
         }
@@ -1203,7 +1200,7 @@
 
         if (handled && requestingContainer instanceof ActivityRecord) {
             final ActivityRecord activityRecord = (ActivityRecord) requestingContainer;
-            final boolean kept = mAcitvityDisplay.updateDisplayOverrideConfigurationLocked(
+            final boolean kept = mActivityDisplay.updateDisplayOverrideConfigurationLocked(
                     config, activityRecord, false /* deferResume */, null /* result */);
             activityRecord.frozenBeforeDestroy = true;
             if (!kept) {
@@ -1212,7 +1209,7 @@
         } else {
             // We have a new configuration to push so we need to update ATMS for now.
             // TODO: Clean up display configuration push between ATMS and WMS after unification.
-            mAcitvityDisplay.updateDisplayOverrideConfigurationLocked(
+            mActivityDisplay.updateDisplayOverrideConfigurationLocked(
                     config, null /* starting */, false /* deferResume */, null);
         }
         return handled;
@@ -1305,9 +1302,9 @@
     void applyRotationLocked(final int oldRotation, final int rotation) {
         mDisplayRotation.applyCurrentRotation(rotation);
         final boolean rotateSeamlessly = mDisplayRotation.isRotatingSeamlessly();
-        final ScreenRotationAnimation screenRotationAnimation = rotateSeamlessly
-                ? null : mWmService.mAnimator.getScreenRotationAnimationLocked(mDisplayId);
         final Transaction transaction = getPendingTransaction();
+        ScreenRotationAnimation screenRotationAnimation = rotateSeamlessly
+                ? null : getRotationAnimation();
         // We need to update our screen size information to match the new rotation. If the rotation
         // has actually changed then this method will return true and, according to the comment at
         // the top of the method, the caller is obligated to call computeNewConfigurationLocked().
@@ -1330,7 +1327,7 @@
 
         forAllWindows(w -> {
             if (w.mHasSurface && !rotateSeamlessly) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Set mOrientationChanging of " + w);
+                ProtoLog.v(WM_DEBUG_ORIENTATION, "Set mOrientationChanging of %s", w);
                 w.setOrientationChanging(true);
                 mWmService.mRoot.mOrientationChangeComplete = false;
                 w.mLastFreezeDuration = 0;
@@ -1994,8 +1991,9 @@
 
         if (mWmService.mDisplayFrozen) {
             if (mLastWindowForcedOrientation != SCREEN_ORIENTATION_UNSPECIFIED) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Display id=" + mDisplayId
-                        + " is frozen, return " + mLastWindowForcedOrientation);
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
+                        "Display id=%d is frozen, return %d", mDisplayId,
+                                mLastWindowForcedOrientation);
                 // If the display is frozen, some activities may be in the middle of restarting, and
                 // thus have removed their old window. If the window has the flag to hide the lock
                 // screen, then the lock screen can re-appear and inflict its own orientation on us.
@@ -2007,8 +2005,9 @@
                 // window. We don't want to check the show when locked window directly though as
                 // things aren't stable while the display is frozen, for example the window could be
                 // momentarily unavailable due to activity relaunch.
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Display id=" + mDisplayId
-                        + " is frozen while keyguard locked, return " + getLastOrientation());
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
+                        "Display id=%d is frozen while keyguard locked, return %d",
+                                mDisplayId, getLastOrientation());
                 return getLastOrientation();
             }
         } else {
@@ -2375,6 +2374,9 @@
     void removeImmediately() {
         mRemovingDisplay = true;
         try {
+            if (mActivityDisplay != null) {
+                mActivityDisplay.unregisterConfigurationChangeListener(this);
+            }
             if (mParentWindow != null) {
                 mParentWindow.removeEmbeddedDisplayContent(this);
             }
@@ -2389,6 +2391,7 @@
             super.removeImmediately();
             if (DEBUG_DISPLAY) Slog.v(TAG_WM, "Removing display=" + this);
             mPointerEventDispatcher.dispose();
+            setRotationAnimation(null);
             mWmService.mAnimator.removeDisplayLocked(mDisplayId);
             mWindowingLayer.release();
             mOverlayLayer.release();
@@ -2553,6 +2556,17 @@
         return delta;
     }
 
+    public void setRotationAnimation(ScreenRotationAnimation screenRotationAnimation) {
+        if (mScreenRotationAnimation != null) {
+            mScreenRotationAnimation.kill();
+        }
+        mScreenRotationAnimation = screenRotationAnimation;
+    }
+
+    public ScreenRotationAnimation getRotationAnimation() {
+        return mScreenRotationAnimation;
+    }
+
     private static void createRotationMatrix(int rotation, float displayWidth, float displayHeight,
             Matrix outMatrix) {
         // For rotations without Z-ordering we don't need the target rectangle's position.
@@ -2615,8 +2629,7 @@
         proto.write(DPI, mBaseDisplayDensity);
         mDisplayInfo.writeToProto(proto, DISPLAY_INFO);
         proto.write(ROTATION, getRotation());
-        final ScreenRotationAnimation screenRotationAnimation =
-                mWmService.mAnimator.getScreenRotationAnimationLocked(mDisplayId);
+        final ScreenRotationAnimation screenRotationAnimation = getRotationAnimation();
         if (screenRotationAnimation != null) {
             screenRotationAnimation.writeToProto(proto, SCREEN_ROTATION_ANIMATION);
         }
@@ -2626,13 +2639,13 @@
             mFocusedApp.writeNameToProto(proto, FOCUSED_APP);
         }
         for (int i = mOpeningApps.size() - 1; i >= 0; i--) {
-            mOpeningApps.valueAt(i).mActivityRecord.writeIdentifierToProto(proto, OPENING_APPS);
+            mOpeningApps.valueAt(i).writeIdentifierToProto(proto, OPENING_APPS);
         }
         for (int i = mClosingApps.size() - 1; i >= 0; i--) {
-            mClosingApps.valueAt(i).mActivityRecord.writeIdentifierToProto(proto, CLOSING_APPS);
+            mClosingApps.valueAt(i).writeIdentifierToProto(proto, CLOSING_APPS);
         }
         for (int i = mChangingApps.size() - 1; i >= 0; i--) {
-            mChangingApps.valueAt(i).mActivityRecord.writeIdentifierToProto(proto, CHANGING_APPS);
+            mChangingApps.valueAt(i).writeIdentifierToProto(proto, CHANGING_APPS);
         }
         proto.end(token);
     }
@@ -2728,6 +2741,16 @@
             }
         }
 
+        final ScreenRotationAnimation rotationAnimation = getRotationAnimation();
+        if (rotationAnimation != null) {
+            pw.print(subPrefix);
+            pw.println("  mScreenRotationAnimation:");
+            rotationAnimation.printTo("  ", pw);
+        } else if (dumpAll) {
+            pw.print(subPrefix);
+            pw.println("  no ScreenRotationAnimation ");
+        }
+
         pw.println();
 
         // Dump stack references
@@ -2847,7 +2870,7 @@
         forAllWindows(mFindFocusedWindow, true /* traverseTopToBottom */);
 
         if (mTmpWindow == null) {
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "findFocusedWindow: No focusable windows.");
+            ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "findFocusedWindow: No focusable windows.");
             return null;
         }
         return mTmpWindow;
@@ -2893,11 +2916,8 @@
             mWmService.mH.obtainMessage(REPORT_FOCUS_CHANGE, this).sendToTarget();
         }
 
-        if (DEBUG_FOCUS_LIGHT || DEBUG) {
-            Slog.v(TAG_WM, "Changing focus from "
-                    + mCurrentFocus + " to " + newFocus + " displayId=" + getDisplayId()
-                    + " Callers=" + Debug.getCallers(4));
-        }
+        ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "Changing focus from %s to %s displayId=%d Callers=%s",
+                    mCurrentFocus, newFocus, getDisplayId(), Debug.getCallers(4));
         final WindowState oldFocus = mCurrentFocus;
         mCurrentFocus = newFocus;
         mLosingFocus.remove(newFocus);
@@ -3034,7 +3054,7 @@
                 Slog.w(TAG_WM, "LEAKED SURFACE (app token hidden): "
                         + w + " surface=" + wsa.mSurfaceController
                         + " token=" + w.mAppToken);
-                if (SHOW_TRANSACTIONS) logSurface(w, "LEAK DESTROY", false);
+                ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE LEAK DESTROY: %s", w);
                 wsa.destroySurface();
                 mTmpWindow = w;
             }
@@ -3329,34 +3349,38 @@
         }, true /* traverseTopToBottom */);
     }
 
-    boolean checkWaitingForWindows() {
+    /** @return {@code true} if there is window to wait before enabling the screen. */
+    boolean shouldWaitForSystemDecorWindowsOnBoot() {
+        if (!isDefaultDisplay && !supportsSystemDecorations()) {
+            // Nothing to wait because the secondary display doesn't support system decorations,
+            // there is no wallpaper, keyguard (status bar) or application (home) window to show
+            // during booting.
+            return false;
+        }
 
-        mHaveBootMsg = false;
-        mHaveApp = false;
-        mHaveWallpaper = false;
-        mHaveKeyguard = true;
+        final SparseBooleanArray drawnWindowTypes = new SparseBooleanArray();
+        // Presuppose keyguard is drawn because if its window isn't attached, we don't know if it
+        // wants to be shown or hidden, then it should not delay enabling the screen.
+        drawnWindowTypes.put(TYPE_STATUS_BAR, true);
 
-        final WindowState visibleWindow = getWindow(w -> {
-            if (w.isVisibleLw() && !w.mObscured && !w.isDrawnLw()) {
+        final WindowState visibleNotDrawnWindow = getWindow(w -> {
+            if (w.mViewVisibility == View.VISIBLE && !w.mObscured && !w.isDrawnLw()) {
                 return true;
             }
             if (w.isDrawnLw()) {
-                if (w.mAttrs.type == TYPE_BOOT_PROGRESS) {
-                    mHaveBootMsg = true;
-                } else if (w.mAttrs.type == TYPE_APPLICATION
-                        || w.mAttrs.type == TYPE_DRAWN_APPLICATION) {
-                    mHaveApp = true;
-                } else if (w.mAttrs.type == TYPE_WALLPAPER) {
-                    mHaveWallpaper = true;
-                } else if (w.mAttrs.type == TYPE_STATUS_BAR) {
-                    mHaveKeyguard = mWmService.mPolicy.isKeyguardDrawnLw();
+                final int type = w.mAttrs.type;
+                if (type == TYPE_BOOT_PROGRESS || type == TYPE_BASE_APPLICATION
+                        || type == TYPE_WALLPAPER) {
+                    drawnWindowTypes.put(type, true);
+                } else if (type == TYPE_STATUS_BAR) {
+                    drawnWindowTypes.put(TYPE_STATUS_BAR, mWmService.mPolicy.isKeyguardDrawnLw());
                 }
             }
             return false;
         });
 
-        if (visibleWindow != null) {
-            // We have a visible window.
+        if (visibleNotDrawnWindow != null) {
+            // Wait for the visible window to be drawn.
             return true;
         }
 
@@ -3368,23 +3392,27 @@
                         com.android.internal.R.bool.config_checkWallpaperAtBoot)
                 && !mWmService.mOnlyCore;
 
-        if (DEBUG_SCREEN_ON || DEBUG_BOOT) Slog.i(TAG_WM,
-                "******** booted=" + mWmService.mSystemBooted
-                + " msg=" + mWmService.mShowingBootMessages
-                + " haveBoot=" + mHaveBootMsg + " haveApp=" + mHaveApp
-                + " haveWall=" + mHaveWallpaper + " wallEnabled=" + wallpaperEnabled
-                + " haveKeyguard=" + mHaveKeyguard);
+        final boolean haveBootMsg = drawnWindowTypes.get(TYPE_BOOT_PROGRESS);
+        final boolean haveApp = drawnWindowTypes.get(TYPE_BASE_APPLICATION);
+        final boolean haveWallpaper = drawnWindowTypes.get(TYPE_WALLPAPER);
+        final boolean haveKeyguard = drawnWindowTypes.get(TYPE_STATUS_BAR);
+
+        ProtoLog.i(WM_DEBUG_SCREEN_ON,
+                "******** booted=%b msg=%b haveBoot=%b haveApp=%b haveWall=%b "
+                        + "wallEnabled=%b haveKeyguard=%b",
+                mWmService.mSystemBooted, mWmService.mShowingBootMessages, haveBootMsg,
+                haveApp, haveWallpaper, wallpaperEnabled, haveKeyguard);
 
         // If we are turning on the screen to show the boot message, don't do it until the boot
         // message is actually displayed.
-        if (!mWmService.mSystemBooted && !mHaveBootMsg) {
+        if (!mWmService.mSystemBooted && !haveBootMsg) {
             return true;
         }
 
         // If we are turning on the screen after the boot is completed normally, don't do so until
         // we have the application and wallpaper.
         if (mWmService.mSystemBooted
-                && ((!mHaveApp && !mHaveKeyguard) || (wallpaperEnabled && !mHaveWallpaper))) {
+                && ((!haveApp && !haveKeyguard) || (wallpaperEnabled && !haveWallpaper))) {
             return true;
         }
 
@@ -3490,19 +3518,6 @@
         mWmService.mWindowPlacerLocked.performSurfacePlacement();
     }
 
-    void waitForAllWindowsDrawn() {
-        final WindowManagerPolicy policy = mWmService.mPolicy;
-        forAllWindows(w -> {
-            final boolean keyguard = policy.isKeyguardHostWindow(w.mAttrs);
-            if (w.isVisibleLw() && (w.mAppToken != null || keyguard)) {
-                w.mWinAnimator.mDrawState = DRAW_PENDING;
-                // Force add to mResizingWindows.
-                w.resetLastContentInsets();
-                mWmService.mWaitingForDrawn.add(w);
-            }
-        }, true /* traverseTopToBottom */);
-    }
-
     // TODO: Super crazy long method that should be broken down...
     void applySurfaceChangesTransaction(boolean recoveringMemory) {
         final WindowSurfacePlacer surfacePlacer = mWmService.mWindowPlacerLocked;
@@ -3737,7 +3752,7 @@
         convertCropForSurfaceFlinger(frame, rot, dw, dh);
 
         final ScreenRotationAnimation screenRotationAnimation =
-                mWmService.mAnimator.getScreenRotationAnimationLocked(DEFAULT_DISPLAY);
+                mWmService.mRoot.getDisplayContent(DEFAULT_DISPLAY).getRotationAnimation();
         final boolean inRotation = screenRotationAnimation != null &&
                 screenRotationAnimation.isAnimating();
         if (DEBUG_SCREENSHOT && inRotation) Slog.v(TAG_WM, "Taking screenshot while rotating");
@@ -4210,8 +4225,8 @@
                         // associated with it will be removed as soon as their animations are
                         // complete.
                         cancelAnimation();
-                        if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG,
-                                "performLayout: App token exiting now removed" + token);
+                        ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                                "performLayout: App token exiting now removed %s", token);
                         token.removeIfPossible();
                     }
                 }
@@ -4241,15 +4256,15 @@
             final int orientation = super.getOrientation();
             if (orientation != SCREEN_ORIENTATION_UNSET
                     && orientation != SCREEN_ORIENTATION_BEHIND) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
-                        "App is requesting an orientation, return " + orientation
-                                + " for display id=" + mDisplayId);
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
+                                "App is requesting an orientation, return %d for display id=%d",
+                                orientation, mDisplayId);
                 return orientation;
             }
 
-            if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
-                    "No app is requesting an orientation, return " + getLastOrientation()
-                            + " for display id=" + mDisplayId);
+            ProtoLog.v(WM_DEBUG_ORIENTATION,
+                            "No app is requesting an orientation, return %d for display id=%d",
+                            getLastOrientation(), mDisplayId);
             // The next app has not been requested to be visible, so we keep the current orientation
             // to prevent freezing/unfreezing the display too early.
             return getLastOrientation();
@@ -4266,54 +4281,56 @@
         }
 
         void assignStackOrdering(SurfaceControl.Transaction t) {
-
-            final int HOME_STACK_STATE = 0;
-            final int NORMAL_STACK_STATE = 1;
-            final int ALWAYS_ON_TOP_STATE = 2;
+            if (getParent() == null) {
+                return;
+            }
+            mTmpAlwaysOnTopStacks.clear();
+            mTmpHomeStacks.clear();
+            mTmpNormalStacks.clear();
+            for (int i = 0; i < mChildren.size(); ++i) {
+                final TaskStack s = mChildren.get(i);
+                if (s.isAlwaysOnTop()) {
+                    mTmpAlwaysOnTopStacks.add(s);
+                } else if (s.isActivityTypeHome()) {
+                    mTmpHomeStacks.add(s);
+                } else {
+                    mTmpNormalStacks.add(s);
+                }
+            }
 
             int layer = 0;
-            int layerForAnimationLayer = 0;
-            int layerForBoostedAnimationLayer = 0;
-            int layerForHomeAnimationLayer = 0;
+            // Place home stacks to the bottom.
+            for (int i = 0; i < mTmpHomeStacks.size(); i++) {
+                mTmpHomeStacks.get(i).assignLayer(t, layer++);
+            }
+            // The home animation layer is between the home stacks and the normal stacks.
+            final int layerForHomeAnimationLayer = layer++;
+            int layerForSplitScreenDividerAnchor = layer++;
+            int layerForAnimationLayer = layer++;
+            for (int i = 0; i < mTmpNormalStacks.size(); i++) {
+                final TaskStack s = mTmpNormalStacks.get(i);
+                s.assignLayer(t, layer++);
+                if (s.inSplitScreenWindowingMode()) {
+                    // The split screen divider anchor is located above the split screen window.
+                    layerForSplitScreenDividerAnchor = layer++;
+                }
+                if (s.isTaskAnimating() || s.isAppAnimating()) {
+                    // The animation layer is located above the highest animating stack and no
+                    // higher.
+                    layerForAnimationLayer = layer++;
+                }
+            }
+            // The boosted animation layer is between the normal stacks and the always on top
+            // stacks.
+            final int layerForBoostedAnimationLayer = layer++;
+            for (int i = 0; i < mTmpAlwaysOnTopStacks.size(); i++) {
+                mTmpAlwaysOnTopStacks.get(i).assignLayer(t, layer++);
+            }
 
-            for (int state = 0; state <= ALWAYS_ON_TOP_STATE; state++) {
-                for (int i = 0; i < mChildren.size(); i++) {
-                    final TaskStack s = mChildren.get(i);
-                    if (state == HOME_STACK_STATE && !s.isActivityTypeHome()) {
-                        continue;
-                    } else if (state == NORMAL_STACK_STATE && (s.isActivityTypeHome()
-                            || s.isAlwaysOnTop())) {
-                        continue;
-                    } else if (state == ALWAYS_ON_TOP_STATE && !s.isAlwaysOnTop()) {
-                        continue;
-                    }
-                    s.assignLayer(t, layer++);
-                    if (s.inSplitScreenWindowingMode() && mSplitScreenDividerAnchor != null) {
-                        t.setLayer(mSplitScreenDividerAnchor, layer++);
-                    }
-                    if ((s.isTaskAnimating() || s.isAppAnimating())
-                            && state != ALWAYS_ON_TOP_STATE) {
-                        // Ensure the animation layer ends up above the
-                        // highest animating stack and no higher.
-                        layerForAnimationLayer = layer++;
-                    }
-                    if (state != ALWAYS_ON_TOP_STATE) {
-                        layerForBoostedAnimationLayer = layer++;
-                    }
-                }
-                if (state == HOME_STACK_STATE) {
-                    layerForHomeAnimationLayer = layer++;
-                }
-            }
-            if (mAppAnimationLayer != null) {
-                t.setLayer(mAppAnimationLayer, layerForAnimationLayer);
-            }
-            if (mBoostedAppAnimationLayer != null) {
-                t.setLayer(mBoostedAppAnimationLayer, layerForBoostedAnimationLayer);
-            }
-            if (mHomeAppAnimationLayer != null) {
-                t.setLayer(mHomeAppAnimationLayer, layerForHomeAnimationLayer);
-            }
+            t.setLayer(mHomeAppAnimationLayer, layerForHomeAnimationLayer);
+            t.setLayer(mAppAnimationLayer, layerForAnimationLayer);
+            t.setLayer(mSplitScreenDividerAnchor, layerForSplitScreenDividerAnchor);
+            t.setLayer(mBoostedAppAnimationLayer, layerForBoostedAnimationLayer);
         }
 
         @Override
@@ -4335,27 +4352,28 @@
 
         @Override
         void onParentChanged() {
-            super.onParentChanged();
             if (getParent() != null) {
-                mAppAnimationLayer = makeChildSurface(null)
-                        .setName("animationLayer")
-                        .build();
-                mBoostedAppAnimationLayer = makeChildSurface(null)
-                        .setName("boostedAnimationLayer")
-                        .build();
-                mHomeAppAnimationLayer = makeChildSurface(null)
-                        .setName("homeAnimationLayer")
-                        .build();
-                mSplitScreenDividerAnchor = makeChildSurface(null)
-                        .setName("splitScreenDividerAnchor")
-                        .build();
-                getPendingTransaction()
-                        .show(mAppAnimationLayer)
-                        .show(mBoostedAppAnimationLayer)
-                        .show(mHomeAppAnimationLayer)
-                        .show(mSplitScreenDividerAnchor);
-                scheduleAnimation();
+                super.onParentChanged(() -> {
+                    mAppAnimationLayer = makeChildSurface(null)
+                            .setName("animationLayer")
+                            .build();
+                    mBoostedAppAnimationLayer = makeChildSurface(null)
+                            .setName("boostedAnimationLayer")
+                            .build();
+                    mHomeAppAnimationLayer = makeChildSurface(null)
+                            .setName("homeAnimationLayer")
+                            .build();
+                    mSplitScreenDividerAnchor = makeChildSurface(null)
+                            .setName("splitScreenDividerAnchor")
+                            .build();
+                    getPendingTransaction()
+                            .show(mAppAnimationLayer)
+                            .show(mBoostedAppAnimationLayer)
+                            .show(mHomeAppAnimationLayer)
+                            .show(mSplitScreenDividerAnchor);
+                });
             } else {
+                super.onParentChanged();
                 mWmService.mTransactionFactory.get()
                         .remove(mAppAnimationLayer)
                         .remove(mBoostedAppAnimationLayer)
@@ -4483,8 +4501,9 @@
                         return SCREEN_ORIENTATION_UNSET;
                     }
                 }
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, win + " forcing orientation to " + req
-                        + " for display id=" + mDisplayId);
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
+                        "%s forcing orientation to %d for display id=%d", win, req,
+                                mDisplayId);
                 return (mLastWindowForcedOrientation = req);
             }
 
@@ -4659,20 +4678,7 @@
     void prepareSurfaces() {
         Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "prepareSurfaces");
         try {
-            final ScreenRotationAnimation screenRotationAnimation =
-                    mWmService.mAnimator.getScreenRotationAnimationLocked(mDisplayId);
             final Transaction transaction = getPendingTransaction();
-            if (screenRotationAnimation != null && screenRotationAnimation.isAnimating()) {
-                screenRotationAnimation.getEnterTransformation().getMatrix().getValues(mTmpFloats);
-                transaction.setMatrix(mWindowingLayer,
-                        mTmpFloats[Matrix.MSCALE_X], mTmpFloats[Matrix.MSKEW_Y],
-                        mTmpFloats[Matrix.MSKEW_X], mTmpFloats[Matrix.MSCALE_Y]);
-                transaction.setPosition(mWindowingLayer,
-                        mTmpFloats[Matrix.MTRANS_X], mTmpFloats[Matrix.MTRANS_Y]);
-                transaction.setAlpha(mWindowingLayer,
-                        screenRotationAnimation.getEnterTransformation().getAlpha());
-            }
-
             super.prepareSurfaces();
 
             // TODO: Once we totally eliminate global transaction we will pass transaction in here
@@ -4752,10 +4758,9 @@
 
     void executeAppTransition() {
         if (mAppTransition.isTransitionSet()) {
-            if (DEBUG_APP_TRANSITIONS) {
-                Slog.w(TAG_WM, "Execute app transition: " + mAppTransition + ", displayId: "
-                        + mDisplayId + " Callers=" + Debug.getCallers(5));
-            }
+            ProtoLog.w(WM_DEBUG_APP_TRANSITIONS,
+                    "Execute app transition: %s, displayId: %d Callers=%s",
+                        mAppTransition, mDisplayId, Debug.getCallers(5));
             mAppTransition.setReady();
             mWmService.mWindowPlacerLocked.requestTraversal();
         }
@@ -4902,6 +4907,10 @@
         return mWindowingLayer;
     }
 
+    SurfaceControl getOverlayLayer() {
+        return mOverlayLayer;
+    }
+
     /**
      * Updates the display's system gesture exclusion.
      *
diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java
index 10d48c4..7be4dbd 100644
--- a/services/core/java/com/android/server/wm/DisplayPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayPolicy.java
@@ -98,9 +98,9 @@
 import static com.android.server.policy.WindowManagerPolicy.TRANSIT_SHOW;
 import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT;
 import static com.android.server.wm.ActivityTaskManagerInternal.SleepToken;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_SCREEN_ON;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREEN_ON;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
@@ -168,6 +168,7 @@
 import com.android.server.policy.WindowManagerPolicy.ScreenOnListener;
 import com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs;
 import com.android.server.policy.WindowOrientationListener;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.statusbar.StatusBarManagerInternal;
 import com.android.server.wallpaper.WallpaperManagerInternal;
 import com.android.server.wm.utils.InsetUtils;
@@ -765,19 +766,19 @@
     /** Return false if it is not ready to turn on. */
     public boolean finishScreenTurningOn() {
         synchronized (mLock) {
-            if (DEBUG_SCREEN_ON) Slog.d(TAG,
-                    "finishScreenTurningOn: mAwake=" + mAwake
-                            + ", mScreenOnEarly=" + mScreenOnEarly
-                            + ", mScreenOnFully=" + mScreenOnFully
-                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
-                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
+            ProtoLog.d(WM_DEBUG_SCREEN_ON,
+                            "finishScreenTurningOn: mAwake=%b, mScreenOnEarly=%b, "
+                                    + "mScreenOnFully=%b, mKeyguardDrawComplete=%b, "
+                                    + "mWindowManagerDrawComplete=%b",
+                            mAwake, mScreenOnEarly, mScreenOnFully, mKeyguardDrawComplete,
+                            mWindowManagerDrawComplete);
 
             if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
                     || (mAwake && !mKeyguardDrawComplete)) {
                 return false;
             }
 
-            if (DEBUG_SCREEN_ON) Slog.i(TAG, "Finished screen turning on...");
+            ProtoLog.i(WM_DEBUG_SCREEN_ON, "Finished screen turning on...");
             mScreenOnListener = null;
             mScreenOnFully = true;
         }
diff --git a/services/core/java/com/android/server/wm/DisplayRotation.java b/services/core/java/com/android/server/wm/DisplayRotation.java
index 4d188f4..414e496 100644
--- a/services/core/java/com/android/server/wm/DisplayRotation.java
+++ b/services/core/java/com/android/server/wm/DisplayRotation.java
@@ -23,8 +23,8 @@
 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS;
 
 import static com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
 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.WINDOWS_FREEZING_SCREENS_ACTIVE;
@@ -58,6 +58,7 @@
 import com.android.server.UiThread;
 import com.android.server.policy.WindowManagerPolicy;
 import com.android.server.policy.WindowOrientationListener;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.statusbar.StatusBarManagerInternal;
 
 import java.io.PrintWriter;
@@ -399,24 +400,24 @@
             if (mDeferredRotationPauseCount > 0) {
                 // Rotation updates have been paused temporarily. Defer the update until updates
                 // have been resumed.
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Deferring rotation, rotation is paused.");
+                ProtoLog.v(WM_DEBUG_ORIENTATION, "Deferring rotation, rotation is paused.");
                 return false;
             }
 
             final ScreenRotationAnimation screenRotationAnimation =
-                    mService.mAnimator.getScreenRotationAnimationLocked(displayId);
+                    mDisplayContent.getRotationAnimation();
             if (screenRotationAnimation != null && screenRotationAnimation.isAnimating()) {
                 // Rotation updates cannot be performed while the previous rotation change animation
                 // is still in progress. Skip this update. We will try updating again after the
                 // animation is finished and the display is unfrozen.
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Deferring rotation, animation in progress.");
+                ProtoLog.v(WM_DEBUG_ORIENTATION, "Deferring rotation, animation in progress.");
                 return false;
             }
             if (mService.mDisplayFrozen) {
                 // Even if the screen rotation animation has finished (e.g. isAnimating returns
                 // false), there is still some time where we haven't yet unfrozen the display. We
                 // also need to abort rotation here.
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM,
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
                         "Deferring rotation, still finishing previous rotation");
                 return false;
             }
@@ -424,30 +425,30 @@
 
         if (!mService.mDisplayEnabled) {
             // No point choosing a rotation if the display is not enabled.
-            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Deferring rotation, display is not enabled.");
+            ProtoLog.v(WM_DEBUG_ORIENTATION, "Deferring rotation, display is not enabled.");
             return false;
         }
 
         final int oldRotation = mRotation;
         final int lastOrientation = mLastOrientation;
         final int rotation = rotationForOrientation(lastOrientation, oldRotation);
-        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Computed rotation=" + rotation + " for display id="
-                + displayId + " based on lastOrientation=" + lastOrientation
-                + " and oldRotation=" + oldRotation);
+        ProtoLog.v(WM_DEBUG_ORIENTATION,
+                "Computed rotation=%d for display id=%d based on lastOrientation=%d and "
+                        + "oldRotation=%d",
+                rotation, displayId, lastOrientation, oldRotation);
 
-        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Display id=" + displayId
-                + " selected orientation " + lastOrientation
-                + ", got rotation " + rotation);
+        ProtoLog.v(WM_DEBUG_ORIENTATION,
+                "Display id=%d selected orientation %d, got rotation %d", displayId,
+                        lastOrientation, rotation);
 
         if (oldRotation == rotation) {
             // No change.
             return false;
         }
 
-        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Display id=" + displayId
-                + " rotation changed to " + rotation
-                + " from " + oldRotation
-                + ", lastOrientation=" + lastOrientation);
+        ProtoLog.v(WM_DEBUG_ORIENTATION,
+                "Display id=%d rotation changed to %d from %d, lastOrientation=%d",
+                        displayId, rotation, oldRotation, lastOrientation);
 
         if (DisplayContent.deltaRotation(rotation, oldRotation) != 2) {
             mDisplayContent.mWaitingForConfig = true;
@@ -551,9 +552,8 @@
             mSeamlessRotationCount--;
         }
         if (mSeamlessRotationCount == 0) {
-            if (DEBUG_ORIENTATION) {
-                Slog.i(TAG, "Performing post-rotate rotation after seamless rotation");
-            }
+            ProtoLog.i(WM_DEBUG_ORIENTATION,
+                    "Performing post-rotate rotation after seamless rotation");
             // Finish seamless rotation.
             mRotatingSeamlessly = false;
 
@@ -844,11 +844,12 @@
 
         // Could have been invoked due to screen turning on or off or
         // change of the currently visible window's orientation.
-        if (DEBUG_ORIENTATION) Slog.v(TAG, "screenOnEarly=" + screenOnEarly
-                + ", awake=" + awake + ", currentAppOrientation=" + mCurrentAppOrientation
-                + ", orientationSensorEnabled=" + mOrientationListener.mEnabled
-                + ", keyguardDrawComplete=" + keyguardDrawComplete
-                + ", windowManagerDrawComplete=" + windowManagerDrawComplete);
+        ProtoLog.v(WM_DEBUG_ORIENTATION,
+                "screenOnEarly=%b, awake=%b, currentAppOrientation=%d, "
+                        + "orientationSensorEnabled=%b, keyguardDrawComplete=%b, "
+                        + "windowManagerDrawComplete=%b",
+                screenOnEarly, awake, mCurrentAppOrientation, mOrientationListener.mEnabled,
+                keyguardDrawComplete, windowManagerDrawComplete);
 
         boolean disable = true;
         // Note: We postpone the rotating of the screen until the keyguard as well as the
@@ -952,14 +953,11 @@
      */
     @VisibleForTesting
     int rotationForOrientation(int orientation, int lastRotation) {
-        if (DEBUG_ORIENTATION) {
-            Slog.v(TAG, "rotationForOrientation(orient="
-                        + orientation + ", last=" + lastRotation
-                        + "); user=" + mUserRotation + " "
-                        + (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
-                            ? "USER_ROTATION_LOCKED" : "")
+        ProtoLog.v(WM_DEBUG_ORIENTATION, "rotationForOrientation(orient=%d, last=%d); user=%d %s",
+                    orientation, lastRotation, mUserRotation,
+                    mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
+                            ? "USER_ROTATION_LOCKED" : ""
                         );
-        }
 
         if (isFixedToUserRotation()) {
             return mUserRotation;
@@ -1059,11 +1057,19 @@
                 preferredRotation = lastRotation;
             }
         } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
-                && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
-            // Apply rotation lock.  Does not apply to NOSENSOR.
+                && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR
+                && orientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
+                && orientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+                && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
+                && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
+            // Apply rotation lock. Does not apply to NOSENSOR or specific rotations.
             // The idea is that the user rotation expresses a weak preference for the direction
             // of gravity and as NOSENSOR is never affected by gravity, then neither should
             // NOSENSOR be affected by rotation lock (although it will be affected by docks).
+            // Also avoid setting user rotation when app has preference over one particular rotation
+            // to avoid leaving the rotation to the reverse of it which has the compatible
+            // orientation, but isn't what app wants, when the user rotation is the reverse of the
+            // preferred rotation.
             preferredRotation = mUserRotation;
         } else {
             // No overriding preference.
@@ -1372,7 +1378,7 @@
 
         @Override
         public void onProposedRotationChanged(int rotation) {
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
+            ProtoLog.v(WM_DEBUG_ORIENTATION, "onProposedRotationChanged, rotation=%d", rotation);
             Runnable r = mRunnableCache.get(rotation, null);
             if (r == null) {
                 r = new UpdateRunnable(rotation);
@@ -1385,14 +1391,14 @@
         public void enable(boolean clearCurrentRotation) {
             super.enable(clearCurrentRotation);
             mEnabled = true;
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Enabling listeners");
+            ProtoLog.v(WM_DEBUG_ORIENTATION, "Enabling listeners");
         }
 
         @Override
         public void disable() {
             super.disable();
             mEnabled = false;
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Disabling listeners");
+            ProtoLog.v(WM_DEBUG_ORIENTATION, "Disabling listeners");
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index ae3b5f2..d3e42901 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -819,9 +819,12 @@
 
         // We put all tasks into drag resizing mode - wait until all of them have completed the
         // drag resizing switch.
-        if (!mService.mWaitingForDrawn.isEmpty()) {
-            mService.mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT);
-            mService.mH.sendEmptyMessageDelayed(H.WAITING_FOR_DRAWN_TIMEOUT,
+        final Runnable existingWaitingForDrwanCallback =
+                mService.mWaitingForDrawnCallbacks.get(mService.mRoot);
+        if (existingWaitingForDrwanCallback != null) {
+            mService.mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT, mService.mRoot);
+            mService.mH.sendMessageDelayed(mService.mH.obtainMessage(H.WAITING_FOR_DRAWN_TIMEOUT,
+                    mService.mRoot),
                     IME_ADJUST_DRAWN_TIMEOUT);
             mAnimationStartDelayed = true;
             if (imeWin != null) {
@@ -838,10 +841,8 @@
             // still gets executed.
             // TODO: Have a real system where we can wait on different windows to be drawn with
             // different callbacks.
-            if (mService.mWaitingForDrawnCallback != null) {
-                mService.mWaitingForDrawnCallback.run();
-            }
-            mService.mWaitingForDrawnCallback = () -> {
+            existingWaitingForDrwanCallback.run();
+            mService.mWaitingForDrawnCallbacks.put(mService.mRoot, () -> {
                 synchronized (mService.mGlobalLock) {
                     mAnimationStartDelayed = false;
                     if (mDelayedImeWin != null) {
@@ -863,7 +864,7 @@
                     notifyAdjustedForImeChanged(
                             mAdjustedForIme || mAdjustedForDivider, duration);
                 }
-            };
+            });
         } else {
             notifyAdjustedForImeChanged(
                     adjustedForIme || adjustedForDivider, IME_ADJUST_ANIM_DURATION);
diff --git a/services/core/java/com/android/server/wm/DragDropController.java b/services/core/java/com/android/server/wm/DragDropController.java
index f8f6334..d5f403f 100644
--- a/services/core/java/com/android/server/wm/DragDropController.java
+++ b/services/core/java/com/android/server/wm/DragDropController.java
@@ -113,7 +113,7 @@
 
                     final WindowState callingWin = mService.windowForClientLocked(
                             null, window, false);
-                    if (callingWin == null) {
+                    if (callingWin == null || callingWin.cantReceiveTouchInput()) {
                         Slog.w(TAG_WM, "Bad requesting window " + window);
                         return null;  // !!! TODO: throw here?
                     }
@@ -167,8 +167,7 @@
                     final SurfaceControl surfaceControl = mDragState.mSurfaceControl;
                     if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM, ">>> OPEN TRANSACTION performDrag");
 
-                    final SurfaceControl.Transaction transaction =
-                            callingWin.getPendingTransaction();
+                    final SurfaceControl.Transaction transaction = mDragState.mTransaction;
                     transaction.setAlpha(surfaceControl, mDragState.mOriginalAlpha);
                     transaction.setPosition(
                             surfaceControl, touchX - thumbCenterX, touchY - thumbCenterY);
diff --git a/services/core/java/com/android/server/wm/DragState.java b/services/core/java/com/android/server/wm/DragState.java
index 17daabf..34820ac 100644
--- a/services/core/java/com/android/server/wm/DragState.java
+++ b/services/core/java/com/android/server/wm/DragState.java
@@ -19,10 +19,10 @@
 import static com.android.server.wm.DragDropController.MSG_ANIMATION_END;
 import static com.android.server.wm.DragDropController.MSG_DRAG_END_TIMEOUT;
 import static com.android.server.wm.DragDropController.MSG_TEAR_DOWN_DRAG_AND_DROP_INPUT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DRAG;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.animation.Animator;
@@ -58,6 +58,7 @@
 
 import com.android.internal.view.IDragAndDropPermissions;
 import com.android.server.LocalServices;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.util.ArrayList;
 
@@ -120,7 +121,7 @@
     // A surface used to catch input events for the drag-and-drop operation.
     SurfaceControl mInputSurface;
 
-    private final SurfaceControl.Transaction mTransaction;
+    final SurfaceControl.Transaction mTransaction;
 
     private final Rect mTmpClipRect = new Rect();
 
@@ -129,7 +130,6 @@
      * {@code true} when {@link #closeLocked()} is called.
      */
     private boolean mIsClosing;
-    IBinder mTransferTouchFromToken;
 
     DragState(WindowManagerService service, DragDropController controller, IBinder token,
             SurfaceControl surface, int flags, IBinder localWin) {
@@ -167,12 +167,11 @@
 
         mTmpClipRect.set(0, 0, mDisplaySize.x, mDisplaySize.y);
         mTransaction.setWindowCrop(mInputSurface, mTmpClipRect);
-        mTransaction.transferTouchFocus(mTransferTouchFromToken, h.token);
-        mTransferTouchFromToken = null;
 
-        // syncInputWindows here to ensure the input channel isn't removed before the transfer.
+        // syncInputWindows here to ensure the input window info is sent before the
+        // transferTouchFocus is called.
         mTransaction.syncInputWindows();
-        mTransaction.apply();
+        mTransaction.apply(true);
     }
 
     /**
@@ -302,9 +301,7 @@
             mDragWindowHandle.frameBottom = mDisplaySize.y;
 
             // Pause rotations before a drag.
-            if (DEBUG_ORIENTATION) {
-                Slog.d(TAG_WM, "Pausing rotation during drag");
-            }
+            ProtoLog.d(WM_DEBUG_ORIENTATION, "Pausing rotation during drag");
             mDisplayContent.getDisplayRotation().pause();
         }
 
@@ -321,9 +318,7 @@
             mDragApplicationHandle = null;
 
             // Resume rotations after a drag.
-            if (DEBUG_ORIENTATION) {
-                Slog.d(TAG_WM, "Resuming rotation after drag");
-            }
+            ProtoLog.d(WM_DEBUG_ORIENTATION, "Resuming rotation after drag");
             mDisplayContent.getDisplayRotation().resume();
         }
     }
@@ -501,10 +496,9 @@
             Slog.i(TAG_WM, ">>> OPEN TRANSACTION notifyMoveLocked");
         }
         mTransaction.setPosition(mSurfaceControl, x - mThumbOffsetX, y - mThumbOffsetY).apply();
-        if (SHOW_TRANSACTIONS) {
-            Slog.i(TAG_WM, "  DRAG " + mSurfaceControl + ": pos=(" + (int) (x - mThumbOffsetX) + ","
-                    + (int) (y - mThumbOffsetY) + ")");
-        }
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "DRAG %s: pos=(%d,%d)", mSurfaceControl,
+                (int) (x - mThumbOffsetX), (int) (y - mThumbOffsetY));
+
         notifyLocationLocked(x, y);
     }
 
diff --git a/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java b/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java
index f64592f..2165b0e 100644
--- a/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java
+++ b/services/core/java/com/android/server/wm/EmulatorDisplayOverlay.java
@@ -50,7 +50,7 @@
     private boolean mVisible;
 
     EmulatorDisplayOverlay(Supplier<Surface> surfaceFactory, Context context, DisplayContent dc,
-            int zOrder) {
+            int zOrder, SurfaceControl.Transaction t) {
         mSurface = surfaceFactory.get();
         final Display display = dc.getDisplay();
         mScreenSize = new Point();
@@ -63,9 +63,9 @@
                     .setBufferSize(mScreenSize.x, mScreenSize.y)
                     .setFormat(PixelFormat.TRANSLUCENT)
                     .build();
-            ctrl.setLayer(zOrder);
-            ctrl.setPosition(0, 0);
-            ctrl.show();
+            t.setLayer(ctrl, zOrder);
+            t.setPosition(ctrl, 0, 0);
+            t.show(ctrl);
             mSurface.copyFrom(ctrl);
         } catch (OutOfResourcesException e) {
         }
@@ -75,7 +75,7 @@
                 com.android.internal.R.drawable.emulator_circular_window_overlay);
     }
 
-    private void drawIfNeeded() {
+    private void drawIfNeeded(SurfaceControl.Transaction t) {
         if (!mDrawNeeded || !mVisible) {
             return;
         }
@@ -92,7 +92,7 @@
             return;
         }
         c.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC);
-        mSurfaceControl.setPosition(0, 0);
+        t.setPosition(mSurfaceControl, 0, 0);
         // Always draw the overlay with square dimensions
         int size = Math.max(mScreenSize.x, mScreenSize.y);
         mOverlay.setBounds(0, 0, size, size);
@@ -102,20 +102,20 @@
 
     // Note: caller responsible for being inside
     // Surface.openTransaction() / closeTransaction()
-    public void setVisibility(boolean on) {
+    public void setVisibility(boolean on, SurfaceControl.Transaction t) {
         if (mSurfaceControl == null) {
             return;
         }
         mVisible = on;
-        drawIfNeeded();
+        drawIfNeeded(t);
         if (on) {
-            mSurfaceControl.show();
+            t.show(mSurfaceControl);
         } else {
-            mSurfaceControl.hide();
+            t.hide(mSurfaceControl);
         }
     }
 
-    void positionSurface(int dw, int dh, int rotation) {
+    void positionSurface(int dw, int dh, int rotation, SurfaceControl.Transaction t) {
         if (mLastDW == dw && mLastDH == dh && mRotation == rotation) {
             return;
         }
@@ -123,7 +123,7 @@
         mLastDH = dh;
         mDrawNeeded = true;
         mRotation = rotation;
-        drawIfNeeded();
+        drawIfNeeded(t);
     }
 
 }
diff --git a/services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java b/services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java
new file mode 100644
index 0000000..7e085f6
--- /dev/null
+++ b/services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2019 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.view.InsetsSource;
+import android.view.WindowInsets;
+
+/**
+ * Controller for IME inset source on the server. It's called provider as it provides the
+ * {@link InsetsSource} to the client that uses it in {@link InsetsSourceConsumer}.
+ */
+class ImeInsetsSourceProvider extends InsetsSourceProvider {
+
+    private WindowState mCurImeTarget;
+    private Runnable mShowImeRunner;
+    private boolean mIsImeLayoutDrawn;
+
+    ImeInsetsSourceProvider(InsetsSource source,
+            InsetsStateController stateController, DisplayContent displayContent) {
+        super(source, stateController, displayContent);
+    }
+
+    /**
+     * Called when a layout pass has occurred.
+     */
+    void onPostLayout() {
+        super.onPostLayout();
+
+        if (mCurImeTarget != null
+                && mCurImeTarget == mDisplayContent.mInputMethodTarget
+                && mWin != null
+                && mWin.isDrawnLw()
+                && !mWin.mGivenInsetsPending) {
+            mIsImeLayoutDrawn = true;
+        }
+    }
+
+    /**
+     * Called when Insets have been dispatched to client.
+     */
+    void onPostInsetsDispatched() {
+        if (mIsImeLayoutDrawn && mShowImeRunner != null) {
+            // Show IME if InputMethodService requested to be shown and it's layout has finished.
+            mShowImeRunner.run();
+            mIsImeLayoutDrawn = false;
+            mShowImeRunner = null;
+        }
+    }
+
+    /**
+     * Called from {@link WindowManagerInternal#showImePostLayout} when {@link InputMethodService}
+     * requests to show IME on {@param imeTarget}.
+     * @param imeTarget imeTarget on which IME is displayed.
+     */
+    void scheduleShowImePostLayout(WindowState imeTarget) {
+        mCurImeTarget = imeTarget;
+        mShowImeRunner = () -> {
+            // Target should still be the same.
+            if (mCurImeTarget == mDisplayContent.mInputMethodTarget) {
+                mDisplayContent.mInputMethodTarget.showInsets(
+                        WindowInsets.Type.ime(), true /* fromIme */);
+            }
+            mCurImeTarget = null;
+        };
+    }
+
+}
diff --git a/services/core/java/com/android/server/wm/InputManagerCallback.java b/services/core/java/com/android/server/wm/InputManagerCallback.java
index 6830ade..ec36a82 100644
--- a/services/core/java/com/android/server/wm/InputManagerCallback.java
+++ b/services/core/java/com/android/server/wm/InputManagerCallback.java
@@ -181,9 +181,8 @@
      */
     @Override
     public long interceptKeyBeforeDispatching(
-            IBinder focus, KeyEvent event, int policyFlags) {
-        WindowState windowState = mService.windowForClientLocked(null, focus, false);
-        return mService.mPolicy.interceptKeyBeforeDispatching(windowState, event, policyFlags);
+            IBinder focusedToken, KeyEvent event, int policyFlags) {
+        return mService.mPolicy.interceptKeyBeforeDispatching(focusedToken, event, policyFlags);
     }
 
     /**
@@ -192,9 +191,8 @@
      */
     @Override
     public KeyEvent dispatchUnhandledKey(
-            IBinder focus, KeyEvent event, int policyFlags) {
-        WindowState windowState = mService.windowForClientLocked(null, focus, false);
-        return mService.mPolicy.dispatchUnhandledKey(windowState, event, policyFlags);
+            IBinder focusedToken, KeyEvent event, int policyFlags) {
+        return mService.mPolicy.dispatchUnhandledKey(focusedToken, event, policyFlags);
     }
 
     /** Callback to get pointer layer. */
diff --git a/services/core/java/com/android/server/wm/InputMonitor.java b/services/core/java/com/android/server/wm/InputMonitor.java
index dd9000e..932b4fa 100644
--- a/services/core/java/com/android/server/wm/InputMonitor.java
+++ b/services/core/java/com/android/server/wm/InputMonitor.java
@@ -26,7 +26,7 @@
 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
 import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
 
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_INPUT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_POSITIONING;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
@@ -49,6 +49,7 @@
 
 import com.android.server.AnimationThread;
 import com.android.server.policy.WindowManagerPolicy;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.io.PrintWriter;
 import java.util.Set;
@@ -331,9 +332,7 @@
      * Layer assignment is assumed to be complete by the time this is called.
      */
     public void setInputFocusLw(WindowState newWindow, boolean updateInputWindows) {
-        if (DEBUG_FOCUS_LIGHT || DEBUG_INPUT) {
-            Slog.d(TAG_WM, "Input focus has changed to " + newWindow);
-        }
+        ProtoLog.d(WM_DEBUG_FOCUS_LIGHT, "Input focus has changed to %s", newWindow);
 
         if (newWindow != mInputFocus) {
             if (newWindow != null && newWindow.canReceiveKeys()) {
@@ -528,6 +527,10 @@
             populateInputWindowHandle(
                     inputWindowHandle, w, flags, type, isVisible, hasFocus, hasWallpaper);
 
+            // register key interception info
+            mService.mKeyInterceptionInfoForToken.put(inputWindowHandle.token,
+                    w.getKeyInterceptionInfo());
+
             if (w.mWinAnimator.hasSurface()) {
                 mInputTransaction.setInputWindowInfo(
                         w.mWinAnimator.mSurfaceController.mSurfaceControl, inputWindowHandle);
diff --git a/services/core/java/com/android/server/wm/InsetsControlTarget.java b/services/core/java/com/android/server/wm/InsetsControlTarget.java
index 3db6dcf..b7184a5 100644
--- a/services/core/java/com/android/server/wm/InsetsControlTarget.java
+++ b/services/core/java/com/android/server/wm/InsetsControlTarget.java
@@ -16,9 +16,21 @@
 
 package com.android.server.wm;
 
+import android.inputmethodservice.InputMethodService;
+import android.view.WindowInsets.Type.InsetType;
+
 /**
  * Generalization of an object that can control insets state.
  */
 interface InsetsControlTarget {
     void notifyInsetsControlChanged();
+
+    /**
+     * Instructs the control target to show inset sources.
+     *
+     * @param types to specify which types of insets source window should be shown.
+     * @param fromIme {@code true} if IME show request originated from {@link InputMethodService}.
+     */
+    default void showInsets(@InsetType int types, boolean fromIme) {
+    }
 }
diff --git a/services/core/java/com/android/server/wm/InsetsSourceProvider.java b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
index 8426864..cc55e01 100644
--- a/services/core/java/com/android/server/wm/InsetsSourceProvider.java
+++ b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
@@ -47,9 +47,11 @@
  */
 class InsetsSourceProvider {
 
+    protected final DisplayContent mDisplayContent;
+    protected final @NonNull InsetsSource mSource;
+    protected WindowState mWin;
+
     private final Rect mTmpRect = new Rect();
-    private final @NonNull InsetsSource mSource;
-    private final DisplayContent mDisplayContent;
     private final InsetsStateController mStateController;
     private final InsetsSourceControl mFakeControl;
     private @Nullable InsetsSourceControl mControl;
@@ -57,7 +59,6 @@
     private @Nullable InsetsControlTarget mFakeControlTarget;
 
     private @Nullable ControlAdapter mAdapter;
-    private WindowState mWin;
     private TriConsumer<DisplayFrames, WindowState, Rect> mFrameProvider;
 
     /** The visibility override from the current controlling window. */
diff --git a/services/core/java/com/android/server/wm/InsetsStateController.java b/services/core/java/com/android/server/wm/InsetsStateController.java
index 4ebb553..b0410335c 100644
--- a/services/core/java/com/android/server/wm/InsetsStateController.java
+++ b/services/core/java/com/android/server/wm/InsetsStateController.java
@@ -108,8 +108,18 @@
      * @return The provider of a specific type.
      */
     InsetsSourceProvider getSourceProvider(@InternalInsetType int type) {
-        return mProviders.computeIfAbsent(type,
-                key -> new InsetsSourceProvider(mState.getSource(key), this, mDisplayContent));
+        if (type == TYPE_IME) {
+            return mProviders.computeIfAbsent(type,
+                    key -> new ImeInsetsSourceProvider(
+                            mState.getSource(key), this, mDisplayContent));
+        } else {
+            return mProviders.computeIfAbsent(type,
+                    key -> new InsetsSourceProvider(mState.getSource(key), this, mDisplayContent));
+        }
+    }
+
+    ImeInsetsSourceProvider getImeSourceProvider() {
+        return (ImeInsetsSourceProvider) getSourceProvider(TYPE_IME);
     }
 
     /**
@@ -124,6 +134,7 @@
             mLastState.set(mState, true /* copySources */);
             notifyInsetsChanged();
         }
+        getImeSourceProvider().onPostInsetsDispatched();
     }
 
     void onInsetsModified(WindowState windowState, InsetsState state) {
diff --git a/services/core/java/com/android/server/wm/LaunchParamsPersister.java b/services/core/java/com/android/server/wm/LaunchParamsPersister.java
index d364a37..5d27390 100644
--- a/services/core/java/com/android/server/wm/LaunchParamsPersister.java
+++ b/services/core/java/com/android/server/wm/LaunchParamsPersister.java
@@ -17,7 +17,6 @@
 package com.android.server.wm;
 
 import android.content.ComponentName;
-import android.content.pm.PackageList;
 import android.content.pm.PackageManagerInternal;
 import android.graphics.Rect;
 import android.os.Environment;
@@ -32,6 +31,7 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.server.LocalServices;
+import com.android.server.pm.PackageList;
 import com.android.server.wm.LaunchParamsController.LaunchParams;
 
 import libcore.io.IoUtils;
@@ -198,7 +198,7 @@
 
     void saveTask(TaskRecord task) {
         final ComponentName name = task.realActivity;
-        final int userId = task.userId;
+        final int userId = task.mUserId;
         PersistableLaunchParams params;
         ArrayMap<ComponentName, PersistableLaunchParams> map = mMap.get(userId);
         if (map == null) {
@@ -247,7 +247,7 @@
 
     void getLaunchParams(TaskRecord task, ActivityRecord activity, LaunchParams outParams) {
         final ComponentName name = task != null ? task.realActivity : activity.mActivityComponent;
-        final int userId = task != null ? task.userId : activity.mUserId;
+        final int userId = task != null ? task.mUserId : activity.mUserId;
 
         outParams.reset();
         Map<ComponentName, PersistableLaunchParams> map = mMap.get(userId);
diff --git a/services/core/java/com/android/server/wm/Letterbox.java b/services/core/java/com/android/server/wm/Letterbox.java
index 1bd2493..94d010e 100644
--- a/services/core/java/com/android/server/wm/Letterbox.java
+++ b/services/core/java/com/android/server/wm/Letterbox.java
@@ -247,12 +247,12 @@
             mLayoutFrameRelative.offset(-surfaceOrigin.x, -surfaceOrigin.y);
         }
 
-        private void createSurface() {
+        private void createSurface(SurfaceControl.Transaction t) {
             mSurface = mSurfaceControlFactory.get().setName("Letterbox - " + mType)
                     .setFlags(HIDDEN).setColorLayer().build();
-            mSurface.setLayer(-1);
-            mSurface.setColor(new float[]{0, 0, 0});
-            mSurface.setColorSpaceAgnostic(true);
+            t.setLayer(mSurface, -1)
+                    .setColor(mSurface, new float[]{0, 0, 0})
+                    .setColorSpaceAgnostic(mSurface, true);
         }
 
         void attachInput(WindowState win) {
@@ -300,7 +300,7 @@
             mSurfaceFrameRelative.set(mLayoutFrameRelative);
             if (!mSurfaceFrameRelative.isEmpty()) {
                 if (mSurface == null) {
-                    createSurface();
+                    createSurface(t);
                 }
                 t.setPosition(mSurface, mSurfaceFrameRelative.left, mSurfaceFrameRelative.top);
                 t.setWindowCrop(mSurface, mSurfaceFrameRelative.width(),
diff --git a/services/core/java/com/android/server/wm/LockTaskController.java b/services/core/java/com/android/server/wm/LockTaskController.java
index b30da5e..dc45686 100644
--- a/services/core/java/com/android/server/wm/LockTaskController.java
+++ b/services/core/java/com/android/server/wm/LockTaskController.java
@@ -317,12 +317,12 @@
         }
 
         // Allow recents activity if enabled by policy
-        if (task.isActivityTypeRecents() && isRecentsAllowed(task.userId)) {
+        if (task.isActivityTypeRecents() && isRecentsAllowed(task.mUserId)) {
             return false;
         }
 
         // Allow emergency calling when the device is protected by a locked keyguard
-        if (isKeyguardAllowed(task.userId) && isEmergencyCallTask(task)) {
+        if (isKeyguardAllowed(task.mUserId) && isEmergencyCallTask(task)) {
             return false;
         }
 
@@ -474,7 +474,7 @@
         if (mLockTaskModeTasks.isEmpty()) {
             if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "removeLockedTask: task=" + task +
                     " last task, reverting locktask mode. Callers=" + Debug.getCallers(3));
-            mHandler.post(() -> performStopLockTask(task.userId));
+            mHandler.post(() -> performStopLockTask(task.mUserId));
         }
     }
 
@@ -537,7 +537,7 @@
                 StatusBarManagerInternal statusBarManager = LocalServices.getService(
                         StatusBarManagerInternal.class);
                 if (statusBarManager != null) {
-                    statusBarManager.showScreenPinningRequest(task.taskId);
+                    statusBarManager.showScreenPinningRequest(task.mTaskId);
                 }
                 return;
             }
@@ -570,11 +570,11 @@
 
         final Intent taskIntent = task.intent;
         if (mLockTaskModeTasks.isEmpty() && taskIntent != null) {
-            mSupervisor.mRecentTasks.onLockTaskModeStateChanged(lockTaskModeState, task.userId);
+            mSupervisor.mRecentTasks.onLockTaskModeStateChanged(lockTaskModeState, task.mUserId);
             // Start lock task on the handler thread
             mHandler.post(() -> performStartLockTask(
                     taskIntent.getComponent().getPackageName(),
-                    task.userId,
+                    task.mUserId,
                     lockTaskModeState));
         }
         if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskMode: Locking to " + task +
@@ -640,7 +640,7 @@
                     || lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED;
 
             if (mLockTaskModeState != LOCK_TASK_MODE_LOCKED
-                    || lockedTask.userId != userId
+                    || lockedTask.mUserId != userId
                     || !wasWhitelisted || isWhitelisted) {
                 continue;
             }
@@ -704,7 +704,7 @@
         }
 
         mLockTaskFeatures.put(userId, flags);
-        if (!mLockTaskModeTasks.isEmpty() && userId == mLockTaskModeTasks.get(0).userId) {
+        if (!mLockTaskModeTasks.isEmpty() && userId == mLockTaskModeTasks.get(0).mUserId) {
             mHandler.post(() -> {
                 if (mLockTaskModeState == LOCK_TASK_MODE_LOCKED) {
                     setStatusBarState(mLockTaskModeState, userId);
diff --git a/services/core/java/com/android/server/wm/PinnedStackController.java b/services/core/java/com/android/server/wm/PinnedStackController.java
index 8e57fec..2e6df60 100644
--- a/services/core/java/com/android/server/wm/PinnedStackController.java
+++ b/services/core/java/com/android/server/wm/PinnedStackController.java
@@ -90,8 +90,6 @@
     private boolean mIsMinimized;
     private boolean mIsImeShowing;
     private int mImeHeight;
-    private boolean mIsShelfShowing;
-    private int mShelfHeight;
 
     // The set of actions and aspect-ratio for the that are currently allowed on the PiP activity
     private ArrayList<RemoteAction> mActions = new ArrayList<>();
@@ -216,7 +214,6 @@
             mPinnedStackListener = listener;
             notifyDisplayInfoChanged(mDisplayInfo);
             notifyImeVisibilityChanged(mIsImeShowing, mImeHeight);
-            notifyShelfVisibilityChanged(mIsShelfShowing, mShelfHeight);
             // The movement bounds notification needs to be sent before the minimized state, since
             // SystemUI may use the bounds to retore the minimized position
             notifyMovementBoundsChanged(false /* fromImeAdjustment */,
@@ -278,9 +275,7 @@
                 mSnapAlgorithm.applySnapFraction(defaultBounds, movementBounds, snapFraction);
             } else {
                 Gravity.apply(mDefaultStackGravity, size.getWidth(), size.getHeight(), insetBounds,
-                        0, Math.max(mIsImeShowing ? mImeHeight : 0,
-                                mIsShelfShowing ? mShelfHeight : 0),
-                        defaultBounds);
+                        0, mIsImeShowing ? mImeHeight : 0, defaultBounds);
             }
             return defaultBounds;
         }
@@ -367,21 +362,6 @@
     }
 
     /**
-     * Sets the shelf state and height.
-     */
-    void setAdjustedForShelf(boolean adjustedForShelf, int shelfHeight) {
-        final boolean shelfShowing = adjustedForShelf && shelfHeight > 0;
-        if (shelfShowing == mIsShelfShowing && shelfHeight == mShelfHeight) {
-            return;
-        }
-
-        mIsShelfShowing = shelfShowing;
-        mShelfHeight = shelfHeight;
-        notifyShelfVisibilityChanged(shelfShowing, shelfHeight);
-        notifyMovementBoundsChanged(false /* fromImeAdjustment */, true /* fromShelfAdjustment */);
-    }
-
-    /**
      * Sets the current aspect ratio.
      */
     void setAspectRatio(float aspectRatio) {
@@ -439,16 +419,6 @@
         }
     }
 
-    private void notifyShelfVisibilityChanged(boolean shelfVisible, int shelfHeight) {
-        if (mPinnedStackListener != null) {
-            try {
-                mPinnedStackListener.onShelfVisibilityChanged(shelfVisible, shelfHeight);
-            } catch (RemoteException e) {
-                Slog.e(TAG_WM, "Error delivering bounds changed event.", e);
-            }
-        }
-    }
-
     private void notifyAspectRatioChanged(float aspectRatio) {
         if (mPinnedStackListener == null) return;
         try {
@@ -613,8 +583,6 @@
         pw.println();
         pw.println(prefix + "  mIsImeShowing=" + mIsImeShowing);
         pw.println(prefix + "  mImeHeight=" + mImeHeight);
-        pw.println(prefix + "  mIsShelfShowing=" + mIsShelfShowing);
-        pw.println(prefix + "  mShelfHeight=" + mShelfHeight);
         pw.println(prefix + "  mIsMinimized=" + mIsMinimized);
         pw.println(prefix + "  mAspectRatio=" + mAspectRatio);
         pw.println(prefix + "  mMinAspectRatio=" + mMinAspectRatio);
diff --git a/services/core/java/com/android/server/wm/ProtoLogGroup.java b/services/core/java/com/android/server/wm/ProtoLogGroup.java
new file mode 100644
index 0000000..f5a1884
--- /dev/null
+++ b/services/core/java/com/android/server/wm/ProtoLogGroup.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2019 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 com.android.internal.annotations.VisibleForTesting;
+import com.android.server.protolog.common.IProtoLogGroup;
+import com.android.server.protolog.common.ProtoLog;
+
+/**
+ * Defines logging groups for ProtoLog.
+ *
+ * This file is used by the ProtoLogTool to generate optimized logging code. All of its dependencies
+ * must be included in services.core.wm.protologgroups build target.
+ */
+public enum ProtoLogGroup implements IProtoLogGroup {
+    WM_ERROR(true, true, true, Consts.TAG_WM),
+    WM_DEBUG_ORIENTATION(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_FOCUS_LIGHT(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_BOOT(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_RESIZE(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_ADD_REMOVE(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_FOCUS(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false, Consts.TAG_WM),
+    WM_DEBUG_STARTING_WINDOW(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_SHOW_TRANSACTIONS(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_SHOW_SURFACE_ALLOC(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_APP_TRANSITIONS(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_APP_TRANSITIONS_ANIM(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_RECENTS_ANIMATIONS(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_DRAW(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false, Consts.TAG_WM),
+    WM_DEBUG_REMOTE_ANIMATIONS(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_SCREEN_ON(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false, Consts.TAG_WM),
+    WM_DEBUG_KEEP_SCREEN_ON(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    WM_DEBUG_WINDOW_MOVEMENT(Consts.ENABLE_DEBUG, Consts.ENABLE_LOG_TO_PROTO_DEBUG, false,
+            Consts.TAG_WM),
+    TEST_GROUP(true, true, false, "WindowManagetProtoLogTest");
+
+    private final boolean mEnabled;
+    private volatile boolean mLogToProto;
+    private volatile boolean mLogToLogcat;
+    private final String mTag;
+
+    /**
+     * @param enabled     set to false to exclude all log statements for this group from
+     *                    compilation,
+     *                    they will not be available in runtime.
+     * @param logToProto  enable binary logging for the group
+     * @param logToLogcat enable text logging for the group
+     * @param tag         name of the source of the logged message
+     */
+    ProtoLogGroup(boolean enabled, boolean logToProto, boolean logToLogcat, String tag) {
+        this.mEnabled = enabled;
+        this.mLogToProto = logToProto;
+        this.mLogToLogcat = logToLogcat;
+        this.mTag = tag;
+    }
+
+    @Override
+    public boolean isEnabled() {
+        return mEnabled;
+    }
+
+    @Override
+    public boolean isLogToProto() {
+        return mLogToProto;
+    }
+
+    @Override
+    public boolean isLogToLogcat() {
+        return mLogToLogcat;
+    }
+
+    @Override
+    public boolean isLogToAny() {
+        return mLogToLogcat || mLogToProto;
+    }
+
+    @Override
+    public String getTag() {
+        return mTag;
+    }
+
+    @Override
+    public void setLogToProto(boolean logToProto) {
+        this.mLogToProto = logToProto;
+    }
+
+    @Override
+    public void setLogToLogcat(boolean logToLogcat) {
+        this.mLogToLogcat = logToLogcat;
+    }
+
+    /**
+     * Test function for automated integration tests. Can be also called manually from adb shell.
+     */
+    @VisibleForTesting
+    public static void testProtoLog() {
+        ProtoLog.e(ProtoLogGroup.TEST_GROUP,
+                "Test completed successfully: %b %d %o %x %e %g %f %% %s.",
+                true, 1, 2, 3, 0.4, 0.5, 0.6, "ok");
+    }
+
+    private static class Consts {
+        private static final String TAG_WM = "WindowManager";
+
+        private static final boolean ENABLE_DEBUG = false;
+        private static final boolean ENABLE_LOG_TO_PROTO_DEBUG = true;
+    }
+}
diff --git a/services/core/java/com/android/server/wm/RecentTasks.java b/services/core/java/com/android/server/wm/RecentTasks.java
index fb6b5da..7169677 100644
--- a/services/core/java/com/android/server/wm/RecentTasks.java
+++ b/services/core/java/com/android/server/wm/RecentTasks.java
@@ -120,7 +120,7 @@
 
     // Comparator to sort by taskId
     private static final Comparator<TaskRecord> TASK_ID_COMPARATOR =
-            (lhs, rhs) -> rhs.taskId - lhs.taskId;
+            (lhs, rhs) -> rhs.mTaskId - lhs.mTaskId;
 
     // Placeholder variables to keep track of activities/apps that are no longer avialble while
     // iterating through the recents list
@@ -272,9 +272,14 @@
      * app, or a timeout occurs.
      */
     void setFreezeTaskListReordering() {
+        // Only fire the callback once per quickswitch session, not on every individual switch
+        if (!mFreezeTaskListReordering) {
+            mTaskNotificationController.notifyTaskListFrozen(true);
+            mFreezeTaskListReordering = true;
+        }
+
         // Always update the reordering time when this is called to ensure that the timeout
         // is reset
-        mFreezeTaskListReordering = true;
         mService.mH.removeCallbacks(mResetFreezeTaskListOnTimeoutRunnable);
         mService.mH.postDelayed(mResetFreezeTaskListOnTimeoutRunnable, mFreezeTaskListTimeoutMs);
     }
@@ -302,6 +307,7 @@
         trimInactiveRecentTasks();
 
         mTaskNotificationController.notifyTaskStackChanged();
+        mTaskNotificationController.notifyTaskListFrozen(false);
     }
 
     /**
@@ -458,8 +464,8 @@
         // Check if any tasks are added before recents is loaded
         final SparseBooleanArray preaddedTasks = new SparseBooleanArray();
         for (final TaskRecord task : mTasks) {
-            if (task.userId == userId && shouldPersistTaskLocked(task)) {
-                preaddedTasks.put(task.taskId, true);
+            if (task.mUserId == userId && shouldPersistTaskLocked(task)) {
+                preaddedTasks.put(task.mTaskId, true);
             }
         }
 
@@ -527,12 +533,12 @@
             if (shouldPersistTaskLocked(task)) {
                 // Set of persisted taskIds for task.userId should not be null here
                 // TODO Investigate why it can happen. For now initialize with an empty set
-                if (mPersistedTaskIds.get(task.userId) == null) {
-                    Slog.wtf(TAG, "No task ids found for userId " + task.userId + ". task=" + task
+                if (mPersistedTaskIds.get(task.mUserId) == null) {
+                    Slog.wtf(TAG, "No task ids found for userId " + task.mUserId + ". task=" + task
                             + " mPersistedTaskIds=" + mPersistedTaskIds);
-                    mPersistedTaskIds.put(task.userId, new SparseBooleanArray());
+                    mPersistedTaskIds.put(task.mUserId, new SparseBooleanArray());
                 }
-                mPersistedTaskIds.get(task.userId).put(task.taskId, true);
+                mPersistedTaskIds.get(task.mUserId).put(task.mTaskId, true);
             }
         }
     }
@@ -608,7 +614,7 @@
 
         for (int i = mTasks.size() - 1; i >= 0; --i) {
             TaskRecord tr = mTasks.get(i);
-            if (tr.userId == userId) {
+            if (tr.mUserId == userId) {
                 if(DEBUG_TASKS) Slog.i(TAG_TASKS,
                         "remove RecentTask " + tr + " when finishing user" + userId);
                 remove(tr);
@@ -622,11 +628,11 @@
             final TaskRecord tr = mTasks.get(i);
             if (tr.realActivity != null
                     && packageNames.contains(tr.realActivity.getPackageName())
-                    && tr.userId == userId
+                    && tr.mUserId == userId
                     && tr.realActivitySuspended != suspended) {
                tr.realActivitySuspended = suspended;
                if (suspended) {
-                   mSupervisor.removeTaskByIdLocked(tr.taskId, false,
+                   mSupervisor.removeTaskByIdLocked(tr.mTaskId, false,
                            REMOVE_FROM_RECENTS, "suspended-package");
                }
                notifyTaskPersisterLocked(tr, false);
@@ -640,7 +646,7 @@
         }
         for (int i = mTasks.size() - 1; i >= 0; --i) {
             final TaskRecord tr = mTasks.get(i);
-            if (tr.userId == userId && !mService.getLockTaskController().isTaskWhitelisted(tr)) {
+            if (tr.mUserId == userId && !mService.getLockTaskController().isTaskWhitelisted(tr)) {
                 remove(tr);
             }
         }
@@ -651,10 +657,10 @@
             final TaskRecord tr = mTasks.get(i);
             final String taskPackageName =
                     tr.getBaseIntent().getComponent().getPackageName();
-            if (tr.userId != userId) continue;
+            if (tr.mUserId != userId) continue;
             if (!taskPackageName.equals(packageName)) continue;
 
-            mSupervisor.removeTaskByIdLocked(tr.taskId, true, REMOVE_FROM_RECENTS,
+            mSupervisor.removeTaskByIdLocked(tr.mTaskId, true, REMOVE_FROM_RECENTS,
                     "remove-package-task");
         }
     }
@@ -663,7 +669,7 @@
         Set<Integer> profileIds = getProfileIds(userId);
         for (int i = mTasks.size() - 1; i >= 0; --i) {
             final TaskRecord tr = mTasks.get(i);
-            if (!profileIds.contains(tr.userId)) continue;
+            if (!profileIds.contains(tr.mUserId)) continue;
             if (isVisibleRecentTask(tr)) {
                 mTasks.remove(i);
                 notifyTaskRemoved(tr, true /* wasTrimmed */, true /* killProcess */);
@@ -675,7 +681,7 @@
             int userId) {
         for (int i = mTasks.size() - 1; i >= 0; --i) {
             final TaskRecord tr = mTasks.get(i);
-            if (userId != UserHandle.USER_ALL && tr.userId != userId) {
+            if (userId != UserHandle.USER_ALL && tr.mUserId != userId) {
                 continue;
             }
 
@@ -683,7 +689,7 @@
             final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName)
                     && (filterByClasses == null || filterByClasses.contains(cn.getClassName()));
             if (sameComponent) {
-                mSupervisor.removeTaskByIdLocked(tr.taskId, false,
+                mSupervisor.removeTaskByIdLocked(tr.mTaskId, false,
                         REMOVE_FROM_RECENTS, "disabled-package");
             }
         }
@@ -709,7 +715,7 @@
         final IPackageManager pm = AppGlobals.getPackageManager();
         for (int i = recentsCount - 1; i >= 0; i--) {
             final TaskRecord task = mTasks.get(i);
-            if (userId != UserHandle.USER_ALL && task.userId != userId) {
+            if (userId != UserHandle.USER_ALL && task.mUserId != userId) {
                 // Only look at tasks for the user ID of interest.
                 continue;
             }
@@ -826,7 +832,7 @@
             if (intent == null || !callingPackage.equals(intent.getComponent().getPackageName())) {
                 continue;
             }
-            AppTaskImpl taskImpl = new AppTaskImpl(mService, tr.taskId, callingUid);
+            AppTaskImpl taskImpl = new AppTaskImpl(mService, tr.mTaskId, callingUid);
             list.add(taskImpl.asBinder());
         }
         return list;
@@ -908,7 +914,7 @@
             }
 
             // Only add calling user or related users recent tasks
-            if (!includedUsers.contains(Integer.valueOf(tr.userId))) {
+            if (!includedUsers.contains(Integer.valueOf(tr.mUserId))) {
                 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + tr);
                 continue;
             }
@@ -972,7 +978,7 @@
             if ((task.isPersistable || task.inRecents)
                     && (stack == null || !stack.isHomeOrRecentsStack())) {
                 if (TaskPersister.DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
-                persistentTaskIds.add(task.taskId);
+                persistentTaskIds.add(task.mTaskId);
             } else {
                 if (TaskPersister.DEBUG) Slog.d(TAG, "omitting from persistentTaskIds task="
                         + task);
@@ -997,7 +1003,7 @@
             if (isVisibleRecentTask(tr)) {
                 numVisibleTasks++;
                 if (isInVisibleRange(tr, i, numVisibleTasks, false /* skipExcludedCheck */)) {
-                    res.put(tr.taskId, true);
+                    res.put(tr.mTaskId, true);
                 }
             }
         }
@@ -1011,7 +1017,7 @@
         final int recentsCount = mTasks.size();
         for (int i = 0; i < recentsCount; i++) {
             TaskRecord tr = mTasks.get(i);
-            if (tr.taskId == id) {
+            if (tr.mTaskId == id) {
                 return tr;
             }
         }
@@ -1024,7 +1030,7 @@
     void add(TaskRecord task) {
         if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "add: task=" + task);
 
-        final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
+        final boolean isAffiliated = task.mAffiliatedTaskId != task.mTaskId
                 || task.mNextAffiliateTaskId != INVALID_TASK_ID
                 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
 
@@ -1138,7 +1144,7 @@
 
         if (needAffiliationFix) {
             if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
-            cleanupLocked(task.userId);
+            cleanupLocked(task.mUserId);
         }
 
         // Trim the set of tasks to the active set
@@ -1248,13 +1254,13 @@
         if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isActiveRecentTask: task=" + task
                 + " globalMax=" + mGlobalMaxNumTasks);
 
-        if (quietProfileUserIds.get(task.userId)) {
+        if (quietProfileUserIds.get(task.mUserId)) {
             // Quiet profile user's tasks are never active
             if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "\tisQuietProfileTask=true");
             return false;
         }
 
-        if (task.mAffiliatedTaskId != INVALID_TASK_ID && task.mAffiliatedTaskId != task.taskId) {
+        if (task.mAffiliatedTaskId != INVALID_TASK_ID && task.mAffiliatedTaskId != task.mTaskId) {
             // Keep the task active if its affiliated task is also active
             final TaskRecord affiliatedTask = getTask(task.mAffiliatedTaskId);
             if (affiliatedTask != null) {
@@ -1430,7 +1436,7 @@
             final TaskRecord tr = mTasks.get(i);
             if (task != tr) {
                 if (!hasCompatibleActivityTypeAndWindowingMode(task, tr)
-                        || task.userId != tr.userId) {
+                        || task.mUserId != tr.mUserId) {
                     continue;
                 }
                 final Intent trIntent = tr.intent;
@@ -1485,7 +1491,7 @@
         final int affiliateId = startTask.mAffiliatedTaskId;
 
         // Quick identification of isolated tasks. I.e. those not launched behind.
-        if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
+        if (startTask.mTaskId == affiliateId && startTask.mPrevAffiliate == null &&
                 startTask.mNextAffiliate == null) {
             // There is still a slim chance that there are other tasks that point to this task
             // and that the chain is so messed up that this task no longer points to them but
@@ -1581,7 +1587,7 @@
             } else {
                 // Verify middle of the chain's next points back to the one before.
                 if (cur.mNextAffiliate != prev
-                        || cur.mNextAffiliateTaskId != prev.taskId) {
+                        || cur.mNextAffiliateTaskId != prev.mTaskId) {
                     Slog.wtf(TAG, "Bad chain @" + endIndex
                             + ": middle task " + cur + " @" + endIndex
                             + " has bad next affiliate "
diff --git a/services/core/java/com/android/server/wm/RecentsAnimation.java b/services/core/java/com/android/server/wm/RecentsAnimation.java
index 5cabbd9..062cdc5 100644
--- a/services/core/java/com/android/server/wm/RecentsAnimation.java
+++ b/services/core/java/com/android/server/wm/RecentsAnimation.java
@@ -28,10 +28,10 @@
 import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
 import static com.android.server.wm.BoundsAnimationController.BOUNDS;
 import static com.android.server.wm.BoundsAnimationController.FADE_IN;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_RECENTS_ANIMATIONS;
 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;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RECENTS_ANIMATIONS;
 
 import android.annotation.Nullable;
 import android.app.ActivityOptions;
@@ -42,6 +42,7 @@
 import android.util.Slog;
 import android.view.IRecentsAnimationRunner;
 
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.RecentsAnimationController.RecentsAnimationCallbacks;
 
 /**
@@ -51,7 +52,6 @@
 class RecentsAnimation implements RecentsAnimationCallbacks,
         ActivityDisplay.OnStackOrderChangedListener {
     private static final String TAG = RecentsAnimation.class.getSimpleName();
-    private static final boolean DEBUG = DEBUG_RECENTS_ANIMATIONS;
 
     private final ActivityTaskManagerService mService;
     private final ActivityStackSupervisor mStackSupervisor;
@@ -101,7 +101,8 @@
      * is updated to the current one.
      */
     void preloadRecentsActivity() {
-        if (DEBUG) Slog.d(TAG, "Preload recents with " + mTargetIntent);
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "Preload recents with %s",
+                mTargetIntent);
         ActivityStack targetStack = mDefaultDisplay.getStack(WINDOWING_MODE_UNDEFINED,
                 mTargetActivityType);
         ActivityRecord targetActivity = getTargetActivity(targetStack);
@@ -116,7 +117,8 @@
                 // keeps the original stopped state.
                 targetActivity.ensureActivityConfiguration(0 /* globalChanges */,
                         false /* preserveWindow */, true /* ignoreVisibility */);
-                if (DEBUG) Slog.d(TAG, "Updated config=" + targetActivity.getConfiguration());
+                ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "Updated config=%s",
+                        targetActivity.getConfiguration());
             }
         } else {
             // Create the activity record. Because the activity is invisible, this doesn't really
@@ -131,13 +133,13 @@
         }
 
         if (!targetActivity.attachedToProcess()) {
-            if (DEBUG) Slog.d(TAG, "Real start recents");
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "Real start recents");
             mStackSupervisor.startSpecificActivityLocked(targetActivity, false /* andResume */,
                     false /* checkConfig */);
             // Make sure the activity won't be involved in transition.
-            if (targetActivity.mAppWindowToken != null) {
-                targetActivity.mAppWindowToken.getDisplayContent().mUnknownAppVisibilityController
-                        .appRemovedOrHidden(targetActivity.mAppWindowToken);
+            if (targetActivity.getDisplayContent() != null) {
+                targetActivity.getDisplayContent().mUnknownAppVisibilityController
+                        .appRemovedOrHidden(targetActivity);
             }
         }
 
@@ -155,7 +157,7 @@
     }
 
     void startRecentsActivity(IRecentsAnimationRunner recentsAnimationRunner) {
-        if (DEBUG) Slog.d(TAG, "startRecentsActivity(): intent=" + mTargetIntent);
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "startRecentsActivity(): intent=%s", mTargetIntent);
         Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "RecentsAnimation#startRecentsActivity");
 
         // TODO(multi-display) currently only support recents animation in default display.
@@ -163,8 +165,9 @@
                 mService.mRootActivityContainer.getDefaultDisplay().mDisplayContent;
         if (!mWindowManager.canStartRecentsAnimation()) {
             notifyAnimationCancelBeforeStart(recentsAnimationRunner);
-            if (DEBUG) Slog.d(TAG, "Can't start recents animation, nextAppTransition="
-                        + dc.mAppTransition.getAppTransition());
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                    "Can't start recents animation, nextAppTransition=%s",
+                        dc.mAppTransition.getAppTransition());
             return;
         }
 
@@ -178,7 +181,8 @@
             mRestoreTargetBehindStack = display.getStackAbove(targetStack);
             if (mRestoreTargetBehindStack == null) {
                 notifyAnimationCancelBeforeStart(recentsAnimationRunner);
-                if (DEBUG) Slog.d(TAG, "No stack above target stack=" + targetStack);
+                ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                        "No stack above target stack=%s", targetStack);
                 return;
             }
         }
@@ -201,8 +205,8 @@
             if (hasExistingActivity) {
                 // Move the recents activity into place for the animation if it is not top most
                 mDefaultDisplay.moveStackBehindBottomMostVisibleStack(targetStack);
-                if (DEBUG) Slog.d(TAG, "Moved stack=" + targetStack + " behind stack="
-                            + mDefaultDisplay.getStackAbove(targetStack));
+                ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "Moved stack=%s behind stack=%s",
+                        targetStack, mDefaultDisplay.getStackAbove(targetStack));
 
                 // If there are multiple tasks in the target stack (ie. the home stack, with 3p
                 // and default launchers coexisting), then move the task to the top as a part of
@@ -220,17 +224,15 @@
                         mTargetActivityType);
                 targetActivity = getTargetActivity(targetStack);
                 mDefaultDisplay.moveStackBehindBottomMostVisibleStack(targetStack);
-                if (DEBUG) {
-                    Slog.d(TAG, "Moved stack=" + targetStack + " behind stack="
-                            + mDefaultDisplay.getStackAbove(targetStack));
-                }
+                ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "Moved stack=%s behind stack=%s",
+                        targetStack, mDefaultDisplay.getStackAbove(targetStack));
 
                 mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
                 mWindowManager.executeAppTransition();
 
                 // TODO: Maybe wait for app to draw in this particular case?
 
-                if (DEBUG) Slog.d(TAG, "Started intent=" + mTargetIntent);
+                ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "Started intent=%s", mTargetIntent);
             }
 
             // Mark the target activity as launch-behind to bump its visibility for the
@@ -268,9 +270,9 @@
     private void finishAnimation(@RecentsAnimationController.ReorderMode int reorderMode,
             boolean sendUserLeaveHint) {
         synchronized (mService.mGlobalLock) {
-            if (DEBUG) Slog.d(TAG, "onAnimationFinished(): controller="
-                    + mWindowManager.getRecentsAnimationController()
-                    + " reorderMode=" + reorderMode);
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                    "onAnimationFinished(): controller=%s reorderMode=%d",
+                            mWindowManager.getRecentsAnimationController(), reorderMode);
 
             // Unregister for stack order changes
             mDefaultDisplay.unregisterStackOrderChangedListener(this);
@@ -308,9 +310,10 @@
                     final ActivityRecord targetActivity = targetStack != null
                             ? targetStack.isInStackLocked(mLaunchedTargetActivity)
                             : null;
-                    if (DEBUG) Slog.d(TAG, "onAnimationFinished(): targetStack=" + targetStack
-                            + " targetActivity=" + targetActivity
-                            + " mRestoreTargetBehindStack=" + mRestoreTargetBehindStack);
+                    ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                            "onAnimationFinished(): targetStack=%s targetActivity=%s "
+                                    + "mRestoreTargetBehindStack=%s",
+                            targetStack, targetActivity, mRestoreTargetBehindStack);
                     if (targetActivity == null) {
                         return;
                     }
@@ -333,25 +336,28 @@
                             targetStack.moveToFront("RecentsAnimation.onAnimationFinished()");
                         }
 
-                        if (DEBUG) {
+                        if (WM_DEBUG_RECENTS_ANIMATIONS.isLogToAny()) {
                             final ActivityStack topStack = getTopNonAlwaysOnTopStack();
                             if (topStack != targetStack) {
-                                Slog.w(TAG, "Expected target stack=" + targetStack
-                                        + " to be top most but found stack=" + topStack);
+                                ProtoLog.w(WM_DEBUG_RECENTS_ANIMATIONS,
+                                        "Expected target stack=%s"
+                                        + " to be top most but found stack=%s",
+                                        targetStack, topStack);
                             }
                         }
                     } else if (reorderMode == REORDER_MOVE_TO_ORIGINAL_POSITION){
                         // Restore the target stack to its previous position
                         final ActivityDisplay display = targetActivity.getDisplay();
                         display.moveStackBehindStack(targetStack, mRestoreTargetBehindStack);
-                        if (DEBUG) {
+                        if (WM_DEBUG_RECENTS_ANIMATIONS.isLogToAny()) {
                             final ActivityStack aboveTargetStack =
                                     mDefaultDisplay.getStackAbove(targetStack);
                             if (mRestoreTargetBehindStack != null
                                     && aboveTargetStack != mRestoreTargetBehindStack) {
-                                Slog.w(TAG, "Expected target stack=" + targetStack
-                                        + " to restored behind stack=" + mRestoreTargetBehindStack
-                                        + " but it is behind stack=" + aboveTargetStack);
+                                ProtoLog.w(WM_DEBUG_RECENTS_ANIMATIONS,
+                                        "Expected target stack=%s to restored behind stack=%s but"
+                                                + " it is behind stack=%s",
+                                        targetStack, mRestoreTargetBehindStack, aboveTargetStack);
                             }
                         }
                     } else {
@@ -402,7 +408,7 @@
 
     @Override
     public void onStackOrderChanged(ActivityStack stack) {
-        if (DEBUG) Slog.d(TAG, "onStackOrderChanged(): stack=" + stack);
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "onStackOrderChanged(): stack=%s", stack);
         if (mDefaultDisplay.getIndexOf(stack) == -1 || !stack.shouldBeVisible(null)) {
             // The stack is not visible, so ignore this change
             return;
@@ -423,7 +429,7 @@
         // 1) The next launching task is not being animated by the recents animation
         // 2) The next task is home activity. (i.e. pressing home key to back home in recents).
         if ((!controller.isAnimatingTask(stack.getTaskStack().getTopChild())
-                || controller.isTargetApp(stack.getTopActivity().mAppWindowToken))
+                || controller.isTargetApp(stack.getTopActivity()))
                 && controller.shouldDeferCancelUntilNextTransition()) {
             // Always prepare an app transition since we rely on the transition callbacks to cleanup
             mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
@@ -486,7 +492,7 @@
 
         for (int i = targetStack.getChildCount() - 1; i >= 0; i--) {
             final TaskRecord task = targetStack.getChildAt(i);
-            if (task.userId == mUserId
+            if (task.mUserId == mUserId
                     && task.getBaseIntent().getComponent().equals(mTargetIntent.getComponent())) {
                 return task.getTopActivity();
             }
diff --git a/services/core/java/com/android/server/wm/RecentsAnimationController.java b/services/core/java/com/android/server/wm/RecentsAnimationController.java
index 795a2ca..bd27905 100644
--- a/services/core/java/com/android/server/wm/RecentsAnimationController.java
+++ b/services/core/java/com/android/server/wm/RecentsAnimationController.java
@@ -29,8 +29,8 @@
 import static com.android.server.wm.ActivityTaskManagerInternal.APP_TRANSITION_RECENTS_ANIM;
 import static com.android.server.wm.AnimationAdapterProto.REMOTE;
 import static com.android.server.wm.BoundsAnimationController.FADE_IN;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_RECENTS_ANIMATIONS;
 import static com.android.server.wm.RemoteAnimationAdapterWrapperProto.TARGET;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RECENTS_ANIMATIONS;
 import static com.android.server.wm.WindowManagerInternal.AppTransitionListener;
 
 import android.annotation.IntDef;
@@ -57,6 +57,7 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.server.LocalServices;
 import com.android.server.inputmethod.InputMethodManagerInternal;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.statusbar.StatusBarManagerInternal;
 import com.android.server.wm.SurfaceAnimator.OnAnimationFinishedCallback;
 import com.android.server.wm.utils.InsetUtils;
@@ -65,6 +66,7 @@
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.stream.Collectors;
 
 /**
  * Controls a single instance of the remote driven recents animation. In particular, this allows
@@ -178,8 +180,8 @@
 
         @Override
         public TaskSnapshot screenshotTask(int taskId) {
-            if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "screenshotTask(" + taskId + "):"
-                    + " mCanceled=" + mCanceled);
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                    "screenshotTask(%d): mCanceled=%b", taskId, mCanceled);
             final long token = Binder.clearCallingIdentity();
             try {
                 synchronized (mService.getWindowManagerLock()) {
@@ -208,8 +210,8 @@
 
         @Override
         public void finish(boolean moveHomeToTop, boolean sendUserLeaveHint) {
-            if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "finish(" + moveHomeToTop + "):"
-                    + " mCanceled=" + mCanceled);
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                    "finish(%b): mCanceled=%b", moveHomeToTop, mCanceled);
             final long token = Binder.clearCallingIdentity();
             try {
                 synchronized (mService.getWindowManagerLock()) {
@@ -250,8 +252,8 @@
 
         @Override
         public void setInputConsumerEnabled(boolean enabled) {
-            if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "setInputConsumerEnabled(" + enabled + "):"
-                    + " mCanceled=" + mCanceled);
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                    "setInputConsumerEnabled(%s): mCanceled=%b", enabled, mCanceled);
             final long token = Binder.clearCallingIdentity();
             try {
                 synchronized (mService.getWindowManagerLock()) {
@@ -392,8 +394,8 @@
         final AppWindowToken recentsComponentAppToken =
                 targetStack.getTopChild().getTopFullscreenAppToken();
         if (recentsComponentAppToken != null) {
-            if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "setHomeApp("
-                    + recentsComponentAppToken.getName() + ")");
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                    "setHomeApp(%s)", recentsComponentAppToken.getName());
             mTargetAppToken = recentsComponentAppToken;
             if (recentsComponentAppToken.windowsCanBeWallpaperTarget()) {
                 mDisplayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
@@ -418,7 +420,7 @@
 
     @VisibleForTesting
     AnimationAdapter addAnimation(Task task, boolean isRecentTaskInvisible) {
-        if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "addAnimation(" + task.getName() + ")");
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "addAnimation(%s)", task.getName());
         final TaskAnimationAdapter taskAdapter = new TaskAnimationAdapter(task,
                 isRecentTaskInvisible);
         task.startAnimation(task.getPendingTransaction(), taskAdapter, false /* hidden */);
@@ -429,8 +431,8 @@
 
     @VisibleForTesting
     void removeAnimation(TaskAnimationAdapter taskAdapter) {
-        if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "removeAnimation("
-                + taskAdapter.mTask.mTaskId + ")");
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                "removeAnimation(%d)", taskAdapter.mTask.mTaskId);
         taskAdapter.mTask.setCanAffectSystemUiFlags(true);
         taskAdapter.mCapturedFinishCallback.onAnimationFinished(taskAdapter);
         mPendingAnimations.remove(taskAdapter);
@@ -438,14 +440,14 @@
 
     @VisibleForTesting
     void removeWallpaperAnimation(WallpaperAnimationAdapter wallpaperAdapter) {
-        if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "removeWallpaperAnimation()");
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "removeWallpaperAnimation()");
         wallpaperAdapter.getLeashFinishedCallback().onAnimationFinished(wallpaperAdapter);
         mPendingWallpaperAnimations.remove(wallpaperAdapter);
     }
 
     void startAnimation() {
-        if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "startAnimation(): mPendingStart=" + mPendingStart
-                + " mCanceled=" + mCanceled);
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                "startAnimation(): mPendingStart=%b mCanceled=%b", mPendingStart, mCanceled);
         if (!mPendingStart || mCanceled) {
             // Skip starting if we've already started or canceled the animation
             return;
@@ -483,13 +485,10 @@
             }
             mRunner.onAnimationStart(mController, appTargets, wallpaperTargets, contentInsets,
                     minimizedHomeBounds);
-            if (DEBUG_RECENTS_ANIMATIONS) {
-                Slog.d(TAG, "startAnimation(): Notify animation start:");
-                for (int i = 0; i < mPendingAnimations.size(); i++) {
-                    final Task task = mPendingAnimations.get(i).mTask;
-                    Slog.d(TAG, "\t" + task.mTaskId);
-                }
-            }
+            ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                    "startAnimation(): Notify animation start: %s",
+                    mPendingAnimations.stream()
+                            .map(anim->anim.mTask.mTaskId).collect(Collectors.toList()));
         } catch (RemoteException e) {
             Slog.e(TAG, "Failed to start recents animation", e);
         }
@@ -513,7 +512,7 @@
     }
 
     private RemoteAnimationTarget[] createWallpaperAnimations() {
-        if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "createWallpaperAnimations()");
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "createWallpaperAnimations()");
         return WallpaperAnimationAdapter.startWallpaperAnimations(mService, 0L, 0L,
                 adapter -> {
                     synchronized (mService.mGlobalLock) {
@@ -533,7 +532,7 @@
     }
 
     private void cancelAnimation(@ReorderMode int reorderMode, boolean screenshot, String reason) {
-        if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG, "cancelAnimation(): reason=" + reason);
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "cancelAnimation(): reason=%s", reason);
         synchronized (mService.getWindowManagerLock()) {
             if (mCanceled) {
                 // We've already canceled the animation
@@ -627,9 +626,7 @@
         mRecentScreenshotAnimator = new SurfaceAnimator(
                 animatable,
                 () -> {
-                    if (DEBUG_RECENTS_ANIMATIONS) {
-                        Slog.d(TAG, "mRecentScreenshotAnimator finish");
-                    }
+                    ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS, "mRecentScreenshotAnimator finish");
                     mCallbacks.onAnimationFinished(reorderMode, false /* sendUserLeaveHint */);
                 }, mService);
         mRecentScreenshotAnimator.transferAnimation(task.mSurfaceAnimator);
@@ -637,9 +634,10 @@
     }
 
     void cleanupAnimation(@ReorderMode int reorderMode) {
-        if (DEBUG_RECENTS_ANIMATIONS) Slog.d(TAG,
-                "cleanupAnimation(): Notify animation finished mPendingAnimations="
-                        + mPendingAnimations.size() + " reorderMode=" + reorderMode);
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                        "cleanupAnimation(): Notify animation finished mPendingAnimations=%d "
+                                + "reorderMode=%d",
+                        mPendingAnimations.size(), reorderMode);
         for (int i = mPendingAnimations.size() - 1; i >= 0; i--) {
             final TaskAnimationAdapter taskAdapter = mPendingAnimations.get(i);
             if (reorderMode == REORDER_MOVE_TO_TOP || reorderMode == REORDER_KEEP_IN_PLACE) {
diff --git a/services/core/java/com/android/server/wm/RemoteAnimationController.java b/services/core/java/com/android/server/wm/RemoteAnimationController.java
index 87bda4a..2b2ae92 100644
--- a/services/core/java/com/android/server/wm/RemoteAnimationController.java
+++ b/services/core/java/com/android/server/wm/RemoteAnimationController.java
@@ -17,9 +17,8 @@
 package com.android.server.wm;
 
 import static com.android.server.wm.AnimationAdapterProto.REMOTE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_REMOTE_ANIMATIONS;
 import static com.android.server.wm.RemoteAnimationAdapterWrapperProto.TARGET;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_REMOTE_ANIMATIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
@@ -39,6 +38,8 @@
 import android.view.SurfaceControl.Transaction;
 
 import com.android.internal.util.FastPrintWriter;
+import com.android.server.protolog.ProtoLogImpl;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.SurfaceAnimator.OnAnimationFinishedCallback;
 import com.android.server.wm.utils.InsetUtils;
 
@@ -51,7 +52,6 @@
  */
 class RemoteAnimationController implements DeathRecipient {
     private static final String TAG = TAG_WITH_CLASS_NAME
-            || (DEBUG_REMOTE_ANIMATIONS && !DEBUG_APP_TRANSITIONS)
                     ? "RemoteAnimationController" : TAG_WM;
     private static final long TIMEOUT_MS = 2000;
 
@@ -86,8 +86,8 @@
      */
     RemoteAnimationRecord createRemoteAnimationRecord(AppWindowToken appWindowToken,
             Point position, Rect stackBounds, Rect startBounds) {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "createAnimationAdapter(): token="
-                + appWindowToken);
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "createAnimationAdapter(): token=%s",
+                appWindowToken);
         final RemoteAnimationRecord adapters =
                 new RemoteAnimationRecord(appWindowToken, position, stackBounds, startBounds);
         mPendingAnimations.add(adapters);
@@ -98,11 +98,11 @@
      * Called when the transition is ready to be started, and all leashes have been set up.
      */
     void goodToGo() {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "goodToGo()");
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "goodToGo()");
         if (mPendingAnimations.isEmpty() || mCanceled) {
-            if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "goodToGo(): Animation finished already,"
-                    + " canceled=" + mCanceled
-                    + " mPendingAnimations=" + mPendingAnimations.size());
+            ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS,
+                    "goodToGo(): Animation finished already, canceled=%s mPendingAnimations=%d",
+                    mCanceled, mPendingAnimations.size());
             onAnimationFinished();
             return;
         }
@@ -115,7 +115,7 @@
         // Create the app targets
         final RemoteAnimationTarget[] appTargets = createAppAnimations();
         if (appTargets.length == 0) {
-            if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "goodToGo(): No apps to animate");
+            ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "goodToGo(): No apps to animate");
             onAnimationFinished();
             return;
         }
@@ -131,8 +131,8 @@
                 Slog.e(TAG, "Failed to start remote animation", e);
                 onAnimationFinished();
             }
-            if (DEBUG_REMOTE_ANIMATIONS) {
-                Slog.d(TAG, "startAnimation(): Notify animation start:");
+            if (ProtoLogImpl.isEnabled(WM_DEBUG_REMOTE_ANIMATIONS)) {
+                ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "startAnimation(): Notify animation start:");
                 writeStartDebugStatement();
             }
         });
@@ -140,7 +140,7 @@
     }
 
     void cancelAnimation(String reason) {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "cancelAnimation(): reason=" + reason);
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "cancelAnimation(): reason=%s", reason);
         synchronized (mService.getWindowManagerLock()) {
             if (mCanceled) {
                 return;
@@ -152,28 +152,28 @@
     }
 
     private void writeStartDebugStatement() {
-        Slog.i(TAG, "Starting remote animation");
+        ProtoLog.i(WM_DEBUG_REMOTE_ANIMATIONS, "Starting remote animation");
         final StringWriter sw = new StringWriter();
         final FastPrintWriter pw = new FastPrintWriter(sw);
         for (int i = mPendingAnimations.size() - 1; i >= 0; i--) {
             mPendingAnimations.get(i).mAdapter.dump(pw, "");
         }
         pw.close();
-        Slog.i(TAG, sw.toString());
+        ProtoLog.i(WM_DEBUG_REMOTE_ANIMATIONS, "%s", sw.toString());
     }
 
     private RemoteAnimationTarget[] createAppAnimations() {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "createAppAnimations()");
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "createAppAnimations()");
         final ArrayList<RemoteAnimationTarget> targets = new ArrayList<>();
         for (int i = mPendingAnimations.size() - 1; i >= 0; i--) {
             final RemoteAnimationRecord wrappers = mPendingAnimations.get(i);
             final RemoteAnimationTarget target = wrappers.createRemoteAnimationTarget();
             if (target != null) {
-                if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "\tAdd token=" + wrappers.mAppWindowToken);
+                ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "\tAdd token=%s", wrappers.mAppWindowToken);
                 targets.add(target);
             } else {
-                if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "\tRemove token="
-                        + wrappers.mAppWindowToken);
+                ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "\tRemove token=%s",
+                        wrappers.mAppWindowToken);
 
                 // We can't really start an animation but we still need to make sure to finish the
                 // pending animation that was started by SurfaceAnimator
@@ -194,7 +194,7 @@
     }
 
     private RemoteAnimationTarget[] createWallpaperAnimations() {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "createWallpaperAnimations()");
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "createWallpaperAnimations()");
         return WallpaperAnimationAdapter.startWallpaperAnimations(mService,
                 mRemoteAnimationAdapter.getDuration(),
                 mRemoteAnimationAdapter.getStatusBarTransitionDelay(),
@@ -207,15 +207,15 @@
     }
 
     private void onAnimationFinished() {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "onAnimationFinished(): mPendingAnimations="
-                + mPendingAnimations.size());
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "onAnimationFinished(): mPendingAnimations=%d",
+                mPendingAnimations.size());
         mHandler.removeCallbacks(mTimeoutRunnable);
         synchronized (mService.mGlobalLock) {
             unlinkToDeathOfRunner();
             releaseFinishedCallback();
             mService.openSurfaceTransaction();
             try {
-                if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG,
+                ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS,
                         "onAnimationFinished(): Notify animation finished:");
                 for (int i = mPendingAnimations.size() - 1; i >= 0; i--) {
                     final RemoteAnimationRecord adapters = mPendingAnimations.get(i);
@@ -228,14 +228,14 @@
                                 .onAnimationFinished(adapters.mThumbnailAdapter);
                     }
                     mPendingAnimations.remove(i);
-                    if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "\tapp=" + adapters.mAppWindowToken);
+                    ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "\tapp=%s", adapters.mAppWindowToken);
                 }
 
                 for (int i = mPendingWallpaperAnimations.size() - 1; i >= 0; i--) {
                     final WallpaperAnimationAdapter adapter = mPendingWallpaperAnimations.get(i);
                     adapter.getLeashFinishedCallback().onAnimationFinished(adapter);
                     mPendingWallpaperAnimations.remove(i);
-                    if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "\twallpaper=" + adapter.getToken());
+                    ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "\twallpaper=%s", adapter.getToken());
                 }
             } catch (Exception e) {
                 Slog.e(TAG, "Failed to finish remote animation", e);
@@ -245,7 +245,7 @@
             }
         }
         setRunningRemoteAnimation(false);
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.i(TAG, "Finishing remote animation");
+        ProtoLog.i(WM_DEBUG_REMOTE_ANIMATIONS, "Finishing remote animation");
     }
 
     private void invokeAnimationCancelled() {
@@ -306,7 +306,7 @@
 
         @Override
         public void onAnimationFinished() throws RemoteException {
-            if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "app-onAnimationFinished(): mOuter=" + mOuter);
+            ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "app-onAnimationFinished(): mOuter=%s", mOuter);
             final long token = Binder.clearCallingIdentity();
             try {
                 if (mOuter != null) {
@@ -326,7 +326,7 @@
          * to prevent memory leak.
          */
         void release() {
-            if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "app-release(): mOuter=" + mOuter);
+            ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "app-release(): mOuter=%s", mOuter);
             mOuter = null;
         }
     };
@@ -420,7 +420,7 @@
         @Override
         public void startAnimation(SurfaceControl animationLeash, Transaction t,
                 OnAnimationFinishedCallback finishCallback) {
-            if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "startAnimation");
+            ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "startAnimation");
 
             // Restore z-layering, position and stack crop until client has a chance to modify it.
             t.setLayer(animationLeash, mRecord.mAppWindowToken.getPrefixOrderIndex());
diff --git a/services/core/java/com/android/server/wm/RootActivityContainer.java b/services/core/java/com/android/server/wm/RootActivityContainer.java
index 734f224..d78d517 100644
--- a/services/core/java/com/android/server/wm/RootActivityContainer.java
+++ b/services/core/java/com/android/server/wm/RootActivityContainer.java
@@ -638,17 +638,23 @@
         if (displayContent != null) {
             config = displayContent.updateOrientation(
                     getDisplayOverrideConfiguration(displayId),
-                    starting != null && starting.mayFreezeScreenLocked(starting.app)
+                    starting != null && starting.mayFreezeScreenLocked()
                             ? starting.appToken : null,
                     true /* forceUpdate */);
         }
+        // Visibilities may change so let the starting activity have a chance to report. Can't do it
+        // when visibility is changed in each AppWindowToken because it may trigger wrong
+        // configuration push because the visibility of some activities may not be updated yet.
+        if (starting != null) {
+            starting.reportDescendantOrientationChangeIfNeeded();
+        }
         if (starting != null && markFrozenIfConfigChanged && config != null) {
             starting.frozenBeforeDestroy = true;
         }
 
-        if (displayContent != null && displayContent.mAcitvityDisplay != null) {
+        if (displayContent != null && displayContent.mActivityDisplay != null) {
             // Update the configuration of the activities on the display.
-            return displayContent.mAcitvityDisplay.updateDisplayOverrideConfigurationLocked(config,
+            return displayContent.mActivityDisplay.updateDisplayOverrideConfigurationLocked(config,
                     starting, deferResume, null /* result */);
         } else {
             return true;
@@ -1097,7 +1103,7 @@
                 }
             }
         }
-        return finishedTask != null ? finishedTask.taskId : INVALID_TASK_ID;
+        return finishedTask != null ? finishedTask.mTaskId : INVALID_TASK_ID;
     }
 
     boolean resumeFocusedStacksTopActivities() {
@@ -1254,14 +1260,14 @@
         int[] taskUserIds = new int[numTasks];
         for (int i = 0; i < numTasks; ++i) {
             final TaskRecord task = tasks.get(i);
-            taskIds[i] = task.taskId;
+            taskIds[i] = task.mTaskId;
             taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString()
                     : task.realActivity != null ? task.realActivity.flattenToString()
                     : task.getTopActivity() != null ? task.getTopActivity().packageName
                     : "unknown";
             taskBounds[i] = new Rect();
             task.getWindowContainerBounds(taskBounds[i]);
-            taskUserIds[i] = task.userId;
+            taskUserIds[i] = task.mUserId;
         }
         info.taskIds = taskIds;
         info.taskNames = taskNames;
@@ -2097,7 +2103,7 @@
                         // picker for personal files, opened by a work app, should still get locked.
                         if (taskTopActivityIsUser(task, userId)) {
                             mService.getTaskChangeNotificationController().notifyTaskProfileLocked(
-                                    task.taskId, userId);
+                                    task.mTaskId, userId);
                         }
                     }
                 }
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index 4365d03..b6a05d1 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -29,20 +29,19 @@
 
 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT;
 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_KEEP_SCREEN_ON;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.RootWindowContainerProto.DISPLAYS;
 import static com.android.server.wm.RootWindowContainerProto.WINDOWS;
 import static com.android.server.wm.RootWindowContainerProto.WINDOW_CONTAINER;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DISPLAY;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_KEEP_SCREEN_ON;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
-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.WINDOW_FREEZE_TIMEOUT;
@@ -50,7 +49,6 @@
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_PLACING_SURFACES;
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_WILL_PLACE_SURFACES;
 import static com.android.server.wm.WindowManagerService.WINDOWS_FREEZING_SCREENS_NONE;
-import static com.android.server.wm.WindowManagerService.logSurface;
 import static com.android.server.wm.WindowSurfacePlacer.SET_ORIENTATION_CHANGE_COMPLETE;
 import static com.android.server.wm.WindowSurfacePlacer.SET_UPDATE_ROTATION;
 import static com.android.server.wm.WindowSurfacePlacer.SET_WALLPAPER_ACTION_PENDING;
@@ -80,6 +78,7 @@
 import android.view.WindowManager;
 
 import com.android.server.EventLogTags;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -195,8 +194,8 @@
             mTopFocusedDisplayId = topFocusedDisplayId;
             mWmService.mInputManager.setFocusedDisplay(topFocusedDisplayId);
             mWmService.mPolicy.setTopFocusedDisplay(topFocusedDisplayId);
-            if (DEBUG_FOCUS_LIGHT) Slog.v(TAG_WM, "New topFocusedDisplayId="
-                    + topFocusedDisplayId);
+            ProtoLog.v(WM_DEBUG_FOCUS_LIGHT, "New topFocusedDisplayId=%d",
+                    topFocusedDisplayId);
         }
         return changed;
     }
@@ -231,7 +230,7 @@
         final DisplayContent existing = getDisplayContent(displayId);
 
         if (existing != null) {
-            existing.mAcitvityDisplay = activityDisplay;
+            existing.mActivityDisplay = activityDisplay;
             existing.initializeDisplayOverrideConfiguration();
             return existing;
         }
@@ -457,13 +456,13 @@
     }
 
     void removeReplacedWindows() {
-        if (SHOW_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION removeReplacedWindows");
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, ">>> OPEN TRANSACTION removeReplacedWindows");
         mWmService.openSurfaceTransaction();
         try {
             forAllWindows(sRemoveReplacedWindowsConsumer, true /* traverseTopToBottom */);
         } finally {
             mWmService.closeSurfaceTransaction("removeReplacedWindows");
-            if (SHOW_TRANSACTIONS) Slog.i(TAG, "<<< CLOSE TRANSACTION removeReplacedWindows");
+            ProtoLog.i(WM_SHOW_TRANSACTIONS, "<<< CLOSE TRANSACTION removeReplacedWindows");
         }
     }
 
@@ -539,8 +538,8 @@
                 Slog.w(TAG_WM,
                         "Looks like we have reclaimed some memory, clearing surface for retry.");
                 if (surfaceController != null) {
-                    if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) logSurface(winAnimator.mWin,
-                            "RECOVER DESTROY", false);
+                    ProtoLog.i(WM_SHOW_SURFACE_ALLOC,
+                            "SURFACE RECOVER DESTROY: %s",  winAnimator.mWin);
                     winAnimator.destroySurface();
                     if (winAnimator.mWin.mAppToken != null) {
                         winAnimator.mWin.mAppToken.removeStartingWindow();
@@ -651,8 +650,11 @@
 
         handleResizingWindows();
 
-        if (DEBUG_ORIENTATION && mWmService.mDisplayFrozen) Slog.v(TAG,
-                "With display frozen, orientationChangeComplete=" + mOrientationChangeComplete);
+        if (mWmService.mDisplayFrozen) {
+            ProtoLog.v(WM_DEBUG_ORIENTATION,
+                    "With display frozen, orientationChangeComplete=%b",
+                    mOrientationChangeComplete);
+        }
         if (mOrientationChangeComplete) {
             if (mWmService.mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_NONE) {
                 mWmService.mWindowsFreezingScreen = WINDOWS_FREEZING_SCREENS_NONE;
@@ -714,11 +716,11 @@
         }
 
         if (mUpdateRotation) {
-            if (DEBUG_ORIENTATION) Slog.d(TAG, "Performing post-rotate rotation");
+            ProtoLog.d(WM_DEBUG_ORIENTATION, "Performing post-rotate rotation");
             mUpdateRotation = updateRotationUnchecked();
         }
 
-        if (mWmService.mWaitingForDrawnCallback != null
+        if (!mWmService.mWaitingForDrawnCallbacks.isEmpty()
                 || (mOrientationChangeComplete && !isLayoutNeeded()
                 && !mUpdateRotation)) {
             mWmService.checkDrawnWindowsLocked();
@@ -811,18 +813,18 @@
         final int defaultDw = defaultInfo.logicalWidth;
         final int defaultDh = defaultInfo.logicalHeight;
         if (mWmService.mWatermark != null) {
-            mWmService.mWatermark.positionSurface(defaultDw, defaultDh);
+            mWmService.mWatermark.positionSurface(defaultDw, defaultDh, mDisplayTransaction);
         }
         if (mWmService.mStrictModeFlash != null) {
-            mWmService.mStrictModeFlash.positionSurface(defaultDw, defaultDh);
+            mWmService.mStrictModeFlash.positionSurface(defaultDw, defaultDh, mDisplayTransaction);
         }
         if (mWmService.mCircularDisplayMask != null) {
             mWmService.mCircularDisplayMask.positionSurface(defaultDw, defaultDh,
-                    mWmService.getDefaultDisplayRotation());
+                    mWmService.getDefaultDisplayRotation(), mDisplayTransaction);
         }
         if (mWmService.mEmulatorDisplayOverlay != null) {
             mWmService.mEmulatorDisplayOverlay.positionSurface(defaultDw, defaultDh,
-                    mWmService.getDefaultDisplayRotation());
+                    mWmService.getDefaultDisplayRotation(), mDisplayTransaction);
         }
 
         final int count = mChildren.size();
@@ -868,29 +870,26 @@
         final int privateflags = attrs.privateFlags;
         boolean displayHasContent = false;
 
-        if (DEBUG_KEEP_SCREEN_ON) {
-            Slog.d(TAG_KEEP_SCREEN_ON, "handleNotObscuredLocked w: " + w
-                + ", w.mHasSurface: " + w.mHasSurface
-                + ", w.isOnScreen(): " + onScreen
-                + ", w.isDisplayedLw(): " + w.isDisplayedLw()
-                + ", w.mAttrs.userActivityTimeout: " + w.mAttrs.userActivityTimeout);
-        }
+        ProtoLog.d(WM_DEBUG_KEEP_SCREEN_ON,
+                    "handleNotObscuredLocked w: %s, w.mHasSurface: %b, w.isOnScreen(): %b, w"
+                            + ".isDisplayedLw(): %b, w.mAttrs.userActivityTimeout: %d",
+                    w, w.mHasSurface, onScreen, w.isDisplayedLw(), w.mAttrs.userActivityTimeout);
         if (w.mHasSurface && onScreen) {
             if (!syswin && w.mAttrs.userActivityTimeout >= 0 && mUserActivityTimeout < 0) {
                 mUserActivityTimeout = w.mAttrs.userActivityTimeout;
-                if (DEBUG_KEEP_SCREEN_ON) {
-                    Slog.d(TAG, "mUserActivityTimeout set to " + mUserActivityTimeout);
-                }
+                ProtoLog.d(WM_DEBUG_KEEP_SCREEN_ON, "mUserActivityTimeout set to %d",
+                        mUserActivityTimeout);
             }
         }
         if (w.mHasSurface && canBeSeen) {
             if ((attrFlags & FLAG_KEEP_SCREEN_ON) != 0) {
                 mHoldScreen = w.mSession;
                 mHoldScreenWindow = w;
-            } else if (DEBUG_KEEP_SCREEN_ON && w == mWmService.mLastWakeLockHoldingWindow) {
-                Slog.d(TAG_KEEP_SCREEN_ON, "handleNotObscuredLocked: " + w + " was holding "
-                        + "screen wakelock but no longer has FLAG_KEEP_SCREEN_ON!!! called by"
-                        + Debug.getCallers(10));
+            } else if (w == mWmService.mLastWakeLockHoldingWindow) {
+                ProtoLog.d(WM_DEBUG_KEEP_SCREEN_ON,
+                        "handleNotObscuredLocked: %s was holding screen wakelock but no longer "
+                                + "has FLAG_KEEP_SCREEN_ON!!! called by%s",
+                        w, Debug.getCallers(10));
             }
             if (!syswin && w.mAttrs.screenBrightness >= 0 && mScreenBrightness < 0) {
                 mScreenBrightness = w.mAttrs.screenBrightness;
@@ -1068,7 +1067,7 @@
     void positionChildAt(int position, DisplayContent child, boolean includingParents) {
         super.positionChildAt(position, child, includingParents);
         if (mRootActivityContainer != null) {
-            mRootActivityContainer.onChildPositionChanged(child.mAcitvityDisplay, position);
+            mRootActivityContainer.onChildPositionChanged(child.mActivityDisplay, position);
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
index cbaf098..157bd3b 100644
--- a/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
+++ b/services/core/java/com/android/server/wm/ScreenRotationAnimation.java
@@ -16,10 +16,9 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_SURFACE_ALLOC;
 import static com.android.server.wm.ScreenRotationAnimationProto.ANIMATION_RUNNING;
 import static com.android.server.wm.ScreenRotationAnimationProto.STARTED;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 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.TYPE_LAYER_MULTIPLIER;
@@ -27,6 +26,7 @@
 
 import android.content.Context;
 import android.graphics.Matrix;
+import android.graphics.Point;
 import android.graphics.Rect;
 import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
@@ -39,8 +39,38 @@
 import android.view.animation.AnimationUtils;
 import android.view.animation.Transformation;
 
+import com.android.server.protolog.common.ProtoLog;
+
 import java.io.PrintWriter;
 
+/**
+ * This class handles the rotation animation when the device is rotated.
+ *
+ * <p>
+ * The screen rotation animation is composed of 4 different part:
+ * <ul>
+ * <li> The screenshot: <p>
+ *     A screenshot of the whole screen prior the change of orientation is taken to hide the
+ *     element resizing below. The screenshot is then animated to rotate and cross-fade to
+ *     the new orientation with the content in the new orientation.
+ *
+ * <li> The windows on the display: <p>y
+ *      Once the device is rotated, the screen and its content are in the new orientation. The
+ *      animation first rotate the new content into the old orientation to then be able to
+ *      animate to the new orientation
+ *
+ * <li> The exiting Blackframe: <p>
+ *     Because the change of orientation might change the width and height of the content (i.e
+ *     when rotating from portrait to landscape) we "crop" the new content using black frames
+ *     around the screenshot so the new content does not go beyond the screenshot's bounds
+ *
+ * <li> The entering Blackframe: <p>
+ *     The enter Blackframe is similar to the exit Blackframe but is only used when a custom
+ *     rotation animation is used and matches the new content size instead of the screenshot.
+ * </ul>
+ *
+ * Each part has its own Surface which are then animated by {@link SurfaceAnimator}s.
+ */
 class ScreenRotationAnimation {
     private static final String TAG = TAG_WITH_CLASS_NAME ? "ScreenRotationAnimation" : TAG_WM;
 
@@ -66,6 +96,8 @@
     private final Matrix mSnapshotFinalMatrix = new Matrix();
     private final Matrix mExitFrameFinalMatrix = new Matrix();
     private final WindowManagerService mService;
+    private SurfaceControl mEnterBlackFrameLayer;
+    private SurfaceControl mRotationLayer;
     private SurfaceControl mSurfaceControl;
     private BlackFrame mEnteringBlackFrame;
     private int mWidth, mHeight;
@@ -81,15 +113,14 @@
     // rotations.
     private Animation mRotateExitAnimation;
     private Animation mRotateEnterAnimation;
+    private Animation mRotateAlphaAnimation;
     private boolean mStarted;
     private boolean mAnimRunning;
     private boolean mFinishAnimReady;
     private long mFinishAnimStartTime;
     private boolean mForceDefaultOrientation;
     private BlackFrame mExitingBlackFrame;
-    private boolean mMoreRotateEnter;
-    private boolean mMoreRotateExit;
-    private long mHalfwayPoint;
+    private SurfaceRotationAnimationController mSurfaceRotationAnimationController;
 
     public ScreenRotationAnimation(Context context, DisplayContent displayContent,
             boolean fixedToUserRotation, boolean isSecure, WindowManagerService service) {
@@ -126,11 +157,23 @@
         mOriginalRotation = originalRotation;
         mOriginalWidth = originalWidth;
         mOriginalHeight = originalHeight;
+        mSurfaceRotationAnimationController = new SurfaceRotationAnimationController();
 
         final SurfaceControl.Transaction t = mService.mTransactionFactory.get();
         try {
-            mSurfaceControl = displayContent.makeOverlay()
+            mRotationLayer = displayContent.makeOverlay()
+                    .setName("RotationLayer")
+                    .setContainerLayer()
+                    .build();
+
+            mEnterBlackFrameLayer = displayContent.makeOverlay()
+                    .setName("EnterBlackFrameLayer")
+                    .setContainerLayer()
+                    .build();
+
+            mSurfaceControl = displayContent.makeSurface(null)
                     .setName("ScreenshotSurface")
+                    .setParent(mRotationLayer)
                     .setBufferSize(mWidth, mHeight)
                     .setSecure(isSecure)
                     .build();
@@ -160,8 +203,10 @@
                 if (gb.containsSecureLayers()) {
                     t.setSecure(mSurfaceControl, true);
                 }
+                t.setLayer(mRotationLayer, SCREEN_FREEZE_LAYER_BASE);
                 t.setLayer(mSurfaceControl, SCREEN_FREEZE_LAYER_SCREENSHOT);
                 t.setAlpha(mSurfaceControl, 0);
+                t.show(mRotationLayer);
                 t.show(mSurfaceControl);
             } else {
                 Slog.w(TAG, "Unable to take screenshot of display " + displayId);
@@ -171,10 +216,8 @@
             Slog.w(TAG, "Unable to allocate freeze surface", e);
         }
 
-        if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
-            Slog.i(TAG_WM,
-                    "  FREEZE " + mSurfaceControl + ": CREATE");
-        }
+        ProtoLog.i(WM_SHOW_SURFACE_ALLOC,
+                    "  FREEZE %s: CREATE", mSurfaceControl);
         setRotation(t, originalRotation);
         t.apply();
     }
@@ -211,22 +254,26 @@
         return mSurfaceControl != null;
     }
 
-    private void setSnapshotTransform(SurfaceControl.Transaction t, Matrix matrix, float alpha) {
-        if (mSurfaceControl != null) {
-            matrix.getValues(mTmpFloats);
-            float x = mTmpFloats[Matrix.MTRANS_X];
-            float y = mTmpFloats[Matrix.MTRANS_Y];
-            if (mForceDefaultOrientation) {
-                mDisplayContent.getBounds(mCurrentDisplayRect);
-                x -= mCurrentDisplayRect.left;
-                y -= mCurrentDisplayRect.top;
-            }
-            t.setPosition(mSurfaceControl, x, y);
-            t.setMatrix(mSurfaceControl,
-                    mTmpFloats[Matrix.MSCALE_X], mTmpFloats[Matrix.MSKEW_Y],
-                    mTmpFloats[Matrix.MSKEW_X], mTmpFloats[Matrix.MSCALE_Y]);
-            t.setAlpha(mSurfaceControl, alpha);
+    private void setRotationTransform(SurfaceControl.Transaction t, Matrix matrix) {
+        if (mRotationLayer == null) {
+            return;
         }
+        matrix.getValues(mTmpFloats);
+        float x = mTmpFloats[Matrix.MTRANS_X];
+        float y = mTmpFloats[Matrix.MTRANS_Y];
+        if (mForceDefaultOrientation) {
+            mDisplayContent.getBounds(mCurrentDisplayRect);
+            x -= mCurrentDisplayRect.left;
+            y -= mCurrentDisplayRect.top;
+        }
+        t.setPosition(mRotationLayer, x, y);
+        t.setMatrix(mRotationLayer,
+                mTmpFloats[Matrix.MSCALE_X], mTmpFloats[Matrix.MSKEW_Y],
+                mTmpFloats[Matrix.MSKEW_X], mTmpFloats[Matrix.MSCALE_Y]);
+
+        t.setAlpha(mSurfaceControl, (float) 1.0);
+        t.setAlpha(mRotationLayer, (float) 1.0);
+        t.show(mRotationLayer);
     }
 
     public void printTo(String prefix, PrintWriter pw) {
@@ -237,7 +284,9 @@
         if (mExitingBlackFrame != null) {
             mExitingBlackFrame.printTo(prefix + "  ", pw);
         }
-        pw.print(prefix); pw.print("mEnteringBlackFrame="); pw.println(mEnteringBlackFrame);
+        pw.print(prefix);
+        pw.print("mEnteringBlackFrame=");
+        pw.println(mEnteringBlackFrame);
         if (mEnteringBlackFrame != null) {
             mEnteringBlackFrame.printTo(prefix + "  ", pw);
         }
@@ -283,7 +332,7 @@
         int delta = DisplayContent.deltaRotation(rotation, Surface.ROTATION_0);
         createRotationMatrix(delta, mWidth, mHeight, mSnapshotInitialMatrix);
 
-        setSnapshotTransform(t, mSnapshotInitialMatrix, 1.0f);
+        setRotationTransform(t, mSnapshotInitialMatrix);
     }
 
     /**
@@ -304,6 +353,9 @@
         // Figure out how the screen has moved from the original rotation.
         int delta = DisplayContent.deltaRotation(mCurRotation, mOriginalRotation);
 
+        mRotateAlphaAnimation = AnimationUtils.loadAnimation(mContext,
+                com.android.internal.R.anim.screen_rotate_alpha);
+
         final boolean customAnim;
         if (exitAnim != 0 && enterAnim != 0) {
             customAnim = true;
@@ -353,6 +405,8 @@
         mRotateExitAnimation.scaleCurrentDuration(animationScale);
         mRotateEnterAnimation.restrictDuration(maxAnimationDuration);
         mRotateEnterAnimation.scaleCurrentDuration(animationScale);
+        mRotateAlphaAnimation.restrictDuration(maxAnimationDuration);
+        mRotateAlphaAnimation.scaleCurrentDuration(animationScale);
 
         if (!customAnim && mExitingBlackFrame == null) {
             try {
@@ -373,13 +427,12 @@
                     outer = mCurrentDisplayRect;
                     inner = mOriginalDisplayRect;
                 } else {
-                    outer = new Rect(-mOriginalWidth * 1, -mOriginalHeight * 1,
-                            mOriginalWidth * 2, mOriginalHeight * 2);
-                    inner = new Rect(0, 0, mOriginalWidth, mOriginalHeight);
+                    outer = new Rect(-mWidth, -mHeight, mWidth * 2, mHeight * 2);
+                    inner = new Rect(0, 0, mWidth, mHeight);
                 }
                 mExitingBlackFrame = new BlackFrame(mService.mTransactionFactory, t, outer, inner,
-                        SCREEN_FREEZE_LAYER_EXIT, mDisplayContent, mForceDefaultOrientation);
-                mExitingBlackFrame.setMatrix(t, mFrameInitialMatrix);
+                        SCREEN_FREEZE_LAYER_EXIT, mDisplayContent, mForceDefaultOrientation,
+                        mRotationLayer);
             } catch (OutOfResourcesException e) {
                 Slog.w(TAG, "Unable to allocate black surface", e);
             }
@@ -387,16 +440,17 @@
 
         if (customAnim && mEnteringBlackFrame == null) {
             try {
-                Rect outer = new Rect(-finalWidth * 1, -finalHeight * 1,
+                Rect outer = new Rect(-finalWidth, -finalHeight,
                         finalWidth * 2, finalHeight * 2);
                 Rect inner = new Rect(0, 0, finalWidth, finalHeight);
                 mEnteringBlackFrame = new BlackFrame(mService.mTransactionFactory, t, outer, inner,
-                        SCREEN_FREEZE_LAYER_ENTER, mDisplayContent, false);
+                        SCREEN_FREEZE_LAYER_ENTER, mDisplayContent, false, mEnterBlackFrameLayer);
             } catch (OutOfResourcesException e) {
                 Slog.w(TAG, "Unable to allocate black surface", e);
             }
         }
 
+        mSurfaceRotationAnimationController.startAnimation();
         return true;
     }
 
@@ -421,14 +475,27 @@
     }
 
     public void kill() {
+        if (mSurfaceRotationAnimationController != null) {
+            mSurfaceRotationAnimationController.cancel();
+            mSurfaceRotationAnimationController = null;
+        }
         if (mSurfaceControl != null) {
-            if (SHOW_TRANSACTIONS ||
-                    SHOW_SURFACE_ALLOC) {
-                Slog.i(TAG_WM,
-                        "  FREEZE " + mSurfaceControl + ": DESTROY");
-            }
-            mService.mTransactionFactory.get().remove(mSurfaceControl).apply();
+            ProtoLog.i(WM_SHOW_SURFACE_ALLOC, "  FREEZE %s: DESTROY", mSurfaceControl);
             mSurfaceControl = null;
+            SurfaceControl.Transaction t = mService.mTransactionFactory.get();
+            if (mRotationLayer != null) {
+                if (mRotationLayer.isValid()) {
+                    t.remove(mRotationLayer);
+                }
+                mRotationLayer = null;
+            }
+            if (mEnterBlackFrameLayer != null) {
+                if (mEnterBlackFrameLayer.isValid()) {
+                    t.remove(mEnterBlackFrameLayer);
+                }
+                mEnterBlackFrameLayer = null;
+            }
+            t.apply();
         }
         if (mExitingBlackFrame != null) {
             mExitingBlackFrame.kill();
@@ -446,124 +513,186 @@
             mRotateEnterAnimation.cancel();
             mRotateEnterAnimation = null;
         }
+        if (mRotateAlphaAnimation != null) {
+            mRotateAlphaAnimation.cancel();
+            mRotateAlphaAnimation = null;
+        }
     }
 
     public boolean isAnimating() {
-        return hasAnimations();
+        return mSurfaceRotationAnimationController != null
+                && mSurfaceRotationAnimationController.isAnimating();
     }
 
     public boolean isRotating() {
         return mCurRotation != mOriginalRotation;
     }
 
-    private boolean hasAnimations() {
-        return mRotateEnterAnimation != null || mRotateExitAnimation != null;
-    }
-
-    private boolean stepAnimation(long now) {
-        if (now > mHalfwayPoint) {
-            mHalfwayPoint = Long.MAX_VALUE;
-        }
-        if (mFinishAnimReady && mFinishAnimStartTime < 0) {
-            mFinishAnimStartTime = now;
-        }
-
-        mMoreRotateExit = false;
-        if (mRotateExitAnimation != null) {
-            mMoreRotateExit = mRotateExitAnimation.getTransformation(now,
-                    mRotateExitTransformation);
-        }
-
-        mMoreRotateEnter = false;
-        if (mRotateEnterAnimation != null) {
-            mMoreRotateEnter = mRotateEnterAnimation.getTransformation(now,
-                    mRotateEnterTransformation);
-        }
-
-        if (!mMoreRotateExit) {
-            if (mRotateExitAnimation != null) {
-                mRotateExitAnimation.cancel();
-                mRotateExitAnimation = null;
-                mRotateExitTransformation.clear();
-            }
-        }
-
-        if (!mMoreRotateEnter) {
-            if (mRotateEnterAnimation != null) {
-                mRotateEnterAnimation.cancel();
-                mRotateEnterAnimation = null;
-                mRotateEnterTransformation.clear();
-            }
-        }
-
-        mExitTransformation.set(mRotateExitTransformation);
-        mEnterTransformation.set(mRotateEnterTransformation);
-
-        final boolean more = mMoreRotateEnter || mMoreRotateExit
-                || !mFinishAnimReady;
-
-        mSnapshotFinalMatrix.setConcat(mExitTransformation.getMatrix(), mSnapshotInitialMatrix);
-
-        return more;
-    }
-
-    void updateSurfaces(SurfaceControl.Transaction t) {
-        if (!mStarted) {
-            return;
-        }
-
-        if (mSurfaceControl != null) {
-            if (!mMoreRotateExit) {
-                t.hide(mSurfaceControl);
-            }
-        }
-
-        if (mExitingBlackFrame != null) {
-            if (!mMoreRotateExit) {
-                mExitingBlackFrame.hide(t);
-            } else {
-                mExitFrameFinalMatrix.setConcat(mExitTransformation.getMatrix(),
-                        mFrameInitialMatrix);
-                mExitingBlackFrame.setMatrix(t, mExitFrameFinalMatrix);
-                if (mForceDefaultOrientation) {
-                    mExitingBlackFrame.setAlpha(t, mExitTransformation.getAlpha());
-                }
-            }
-        }
-
-        if (mEnteringBlackFrame != null) {
-            if (!mMoreRotateEnter) {
-                mEnteringBlackFrame.hide(t);
-            } else {
-                mEnteringBlackFrame.setMatrix(t, mEnterTransformation.getMatrix());
-            }
-        }
-
-        t.setEarlyWakeup();
-        setSnapshotTransform(t, mSnapshotFinalMatrix, mExitTransformation.getAlpha());
-    }
-
-    public boolean stepAnimationLocked(long now) {
-        if (!hasAnimations()) {
-            mFinishAnimReady = false;
-            return false;
-        }
-
-        if (!mAnimRunning) {
-            if (mRotateEnterAnimation != null) {
-                mRotateEnterAnimation.setStartTime(now);
-            }
-            if (mRotateExitAnimation != null) {
-                mRotateExitAnimation.setStartTime(now);
-            }
-            mAnimRunning = true;
-            mHalfwayPoint = now + mRotateEnterAnimation.getDuration() / 2;
-        }
-
-        return stepAnimation(now);
-    }
-
     public Transformation getEnterTransformation() {
         return mEnterTransformation;
     }
+
+    /**
+     * Utility class that runs a {@link ScreenRotationAnimation} on the {@link
+     * SurfaceAnimationRunner}.
+     * <p>
+     * The rotation animation is divided into the following hierarchy:
+     * <ul>
+     * <li> A first rotation layer, containing the blackframes. This layer is animated by the
+     * "screen_rotate_X_exit" that applies a scale and rotate and where X is value of the rotation.
+     *     <ul>
+     *         <li> A child layer containing the screenshot on which is added an animation of it's
+     *     alpha channel ("screen_rotate_alpha") and that will rotate with his parent layer.</li>
+     *     </ul>
+     * <li> A second rotation layer used when custom animations are passed in
+     * {@link ScreenRotationAnimation#startAnimation(
+     *     SurfaceControl.Transaction, long, float, int, int, int, int)}.
+     * </ul>
+     * <p>
+     * Thus an {@link LocalAnimationAdapter.AnimationSpec} is created for each of
+     * this three {@link SurfaceControl}s which then delegates the animation to the
+     * {@link ScreenRotationAnimation}.
+     */
+    class SurfaceRotationAnimationController {
+        private SurfaceAnimator mDisplayAnimator;
+        private SurfaceAnimator mEnterBlackFrameAnimator;
+        private SurfaceAnimator mScreenshotRotationAnimator;
+        private SurfaceAnimator mRotateScreenAnimator;
+        private final Runnable mNoopCallback = () -> { // b/141177184
+        };
+
+        /**
+         * Start the rotation animation of the display and the screenshot on the
+         * {@link SurfaceAnimationRunner}.
+         */
+        void startAnimation() {
+            mRotateScreenAnimator = startScreenshotAlphaAnimation();
+            mDisplayAnimator = startDisplayRotation();
+            if (mExitingBlackFrame != null) {
+                mScreenshotRotationAnimator = startScreenshotRotationAnimation();
+            }
+            if (mEnteringBlackFrame != null) {
+                mEnterBlackFrameAnimator = startEnterBlackFrameAnimation();
+            }
+        }
+
+        private SimpleSurfaceAnimatable.Builder initializeBuilder() {
+            return new SimpleSurfaceAnimatable.Builder()
+                    .setPendingTransactionSupplier(mDisplayContent::getPendingTransaction)
+                    .setCommitTransactionRunnable(mDisplayContent::commitPendingTransaction)
+                    .setAnimationLeashSupplier(mDisplayContent::makeOverlay);
+        }
+
+        private SurfaceAnimator startDisplayRotation() {
+            return startAnimation(initializeBuilder()
+                            .setAnimationLeashParent(mDisplayContent.getSurfaceControl())
+                            .setSurfaceControl(mDisplayContent.getWindowingLayer())
+                            .setParentSurfaceControl(mDisplayContent.getSurfaceControl())
+                            .setWidth(mDisplayContent.getSurfaceWidth())
+                            .setHeight(mDisplayContent.getSurfaceHeight())
+                            .build(),
+                    createWindowAnimationSpec(mRotateEnterAnimation),
+                    this::cancel);
+        }
+
+        private SurfaceAnimator startScreenshotAlphaAnimation() {
+            return startAnimation(initializeBuilder()
+                            .setSurfaceControl(mSurfaceControl)
+                            .setAnimationLeashParent(mRotationLayer)
+                            .setWidth(mWidth)
+                            .setHeight(mHeight)
+                            .build(),
+                    createWindowAnimationSpec(mRotateAlphaAnimation),
+                    mNoopCallback);
+        }
+
+        private SurfaceAnimator startEnterBlackFrameAnimation() {
+            return startAnimation(initializeBuilder()
+                            .setSurfaceControl(mEnterBlackFrameLayer)
+                            .setAnimationLeashParent(mDisplayContent.getOverlayLayer())
+                            .build(),
+                    createWindowAnimationSpec(mRotateEnterAnimation),
+                    mNoopCallback);
+        }
+
+        private SurfaceAnimator startScreenshotRotationAnimation() {
+            return startAnimation(initializeBuilder()
+                            .setSurfaceControl(mRotationLayer)
+                            .setAnimationLeashParent(mDisplayContent.getOverlayLayer())
+                            .build(),
+                    createWindowAnimationSpec(mRotateExitAnimation),
+                    this::onAnimationEnd);
+        }
+
+        private WindowAnimationSpec createWindowAnimationSpec(Animation mAnimation) {
+            return new WindowAnimationSpec(mAnimation, new Point(0, 0) /* position */,
+                    false /* canSkipFirstFrame */, 0 /* WindowCornerRadius */);
+        }
+
+        /**
+         * Start an animation defined by animationSpec on a new {@link SurfaceAnimator}.
+         *
+         * @param animatable The animatable used for the animation.
+         * @param animationSpec                The spec of the animation.
+         * @param animationFinishedCallback    Callback passed to the {@link SurfaceAnimator} and
+         *                                    called when the animation finishes.
+         * @return The newly created {@link SurfaceAnimator} that as been started.
+         */
+        private SurfaceAnimator startAnimation(
+                SurfaceAnimator.Animatable animatable,
+                LocalAnimationAdapter.AnimationSpec animationSpec,
+                Runnable animationFinishedCallback) {
+            SurfaceAnimator animator = new SurfaceAnimator(
+                    animatable, animationFinishedCallback, mService);
+
+            LocalAnimationAdapter localAnimationAdapter = new LocalAnimationAdapter(
+                    animationSpec, mService.mSurfaceAnimationRunner);
+
+            animator.startAnimation(mDisplayContent.getPendingTransaction(),
+                    localAnimationAdapter, false);
+            return animator;
+        }
+
+        private void onAnimationEnd() {
+            mEnterBlackFrameAnimator = null;
+            mScreenshotRotationAnimator = null;
+            mRotateScreenAnimator = null;
+            mService.mAnimator.mBulkUpdateParams |= WindowSurfacePlacer.SET_UPDATE_ROTATION;
+            kill();
+            mService.updateRotation(false, false);
+            AccessibilityController accessibilityController = mService.mAccessibilityController;
+
+            if (accessibilityController != null) {
+                // We just finished rotation animation which means we did not
+                // announce the rotation and waited for it to end, announce now.
+                accessibilityController.onRotationChangedLocked(mDisplayContent);
+            }
+        }
+
+        public void cancel() {
+            if (mEnterBlackFrameAnimator != null) {
+                mEnterBlackFrameAnimator.cancelAnimation();
+            }
+
+            if (mScreenshotRotationAnimator != null) {
+                mScreenshotRotationAnimator.cancelAnimation();
+            }
+
+            if (mRotateScreenAnimator != null) {
+                mRotateScreenAnimator.cancelAnimation();
+            }
+
+            if (mDisplayAnimator != null) {
+                mDisplayAnimator.cancelAnimation();
+            }
+        }
+
+        public boolean isAnimating() {
+            return mDisplayAnimator != null && mDisplayAnimator.isAnimating()
+                    || mEnterBlackFrameAnimator != null && mEnterBlackFrameAnimator.isAnimating()
+                    || mRotateScreenAnimator != null && mRotateScreenAnimator.isAnimating()
+                    || mScreenshotRotationAnimator != null
+                    && mScreenshotRotationAnimator.isAnimating();
+        }
+    }
 }
diff --git a/services/core/java/com/android/server/wm/SeamlessRotator.java b/services/core/java/com/android/server/wm/SeamlessRotator.java
index bcd90a1..ba31818 100644
--- a/services/core/java/com/android/server/wm/SeamlessRotator.java
+++ b/services/core/java/com/android/server/wm/SeamlessRotator.java
@@ -20,9 +20,10 @@
 import static android.view.Surface.ROTATION_90;
 
 import android.graphics.Matrix;
+import android.os.IBinder;
 import android.view.DisplayInfo;
-import android.view.Surface;
 import android.view.Surface.Rotation;
+import android.view.SurfaceControl;
 import android.view.SurfaceControl.Transaction;
 
 import com.android.server.wm.utils.CoordinateTransforms;
@@ -35,7 +36,7 @@
  *
  * Works by transforming the {@link WindowState} back into the old display rotation.
  *
- * Uses {@link android.view.SurfaceControl#deferTransactionUntil(Surface, long)} instead of
+ * Uses {@link Transaction#deferTransactionUntil(SurfaceControl, IBinder, long)} instead of
  * latching on the buffer size to allow for seamless 180 degree rotations.
  */
 public class SeamlessRotator {
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index 72bb355..b047d8f 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -24,9 +24,9 @@
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
 import static android.view.WindowManager.LayoutParams.isSystemAlertWindowType;
 
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_POSITIONING;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.annotation.Nullable;
@@ -56,6 +56,7 @@
 import android.view.WindowManager;
 
 import com.android.internal.os.logging.MetricsLoggerWrapper;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.WindowManagerService.H;
 
 import java.io.PrintWriter;
@@ -478,8 +479,7 @@
                 Slog.v(TAG_WM, "First window added to " + this + ", creating SurfaceSession");
             }
             mSurfaceSession = new SurfaceSession();
-            if (SHOW_TRANSACTIONS) Slog.i(
-                    TAG_WM, "  NEW SURFACE SESSION " + mSurfaceSession);
+            ProtoLog.i(WM_SHOW_TRANSACTIONS, "  NEW SURFACE SESSION %s", mSurfaceSession);
             mService.mSessions.add(this);
             if (mLastReportedAnimatorScale != mService.getCurrentAnimatorScale()) {
                 mService.dispatchNewAnimatorScaleLocked(this);
@@ -570,7 +570,7 @@
             Slog.v(TAG_WM, "Last window removed from " + this
                     + ", destroying " + mSurfaceSession);
         }
-        if (SHOW_TRANSACTIONS) Slog.i(TAG_WM, "  KILL SURFACE SESSION " + mSurfaceSession);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "  KILL SURFACE SESSION %s", mSurfaceSession);
         try {
             mSurfaceSession.kill();
         } catch (Exception e) {
diff --git a/services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java b/services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java
new file mode 100644
index 0000000..bf5d5e2
--- /dev/null
+++ b/services/core/java/com/android/server/wm/SimpleSurfaceAnimatable.java
@@ -0,0 +1,308 @@
+/*
+ * Copyright (C) 2019 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.annotation.NonNull;
+import android.annotation.Nullable;
+import android.view.SurfaceControl;
+
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+/**
+ * An implementation of {@link SurfaceAnimator.Animatable} that is instantiated
+ * using a builder pattern for more convenience over reimplementing the whole interface.
+ * <p>
+ * Use {@link SimpleSurfaceAnimatable.Builder} to create a new instance of this class.
+ *
+ * @see com.android.server.wm.SurfaceAnimator.Animatable
+ */
+public class SimpleSurfaceAnimatable implements SurfaceAnimator.Animatable {
+    private final int mWidth;
+    private final int mHeight;
+    private final boolean mShouldDeferAnimationFinish;
+    private final SurfaceControl mAnimationLeashParent;
+    private final SurfaceControl mSurfaceControl;
+    private final SurfaceControl mParentSurfaceControl;
+    private final Runnable mCommitTransactionRunnable;
+    private final Supplier<SurfaceControl.Builder> mAnimationLeashFactory;
+    private final Supplier<SurfaceControl.Transaction> mPendingTransaction;
+    private final BiConsumer<SurfaceControl.Transaction, SurfaceControl> mOnAnimationLeashCreated;
+    private final Consumer<SurfaceControl.Transaction> mOnAnimationLeashLost;
+    private final Consumer<Runnable> mOnAnimationFinished;
+
+    /**
+     * Use {@link SimpleSurfaceAnimatable.Builder} to create a new instance.
+     */
+    private SimpleSurfaceAnimatable(Builder builder) {
+        mWidth = builder.mWidth;
+        mHeight = builder.mHeight;
+        mShouldDeferAnimationFinish = builder.mShouldDeferAnimationFinish;
+        mAnimationLeashParent = builder.mAnimationLeashParent;
+        mSurfaceControl = builder.mSurfaceControl;
+        mParentSurfaceControl = builder.mParentSurfaceControl;
+        mCommitTransactionRunnable = builder.mCommitTransactionRunnable;
+        mAnimationLeashFactory = builder.mAnimationLeashFactory;
+        mOnAnimationLeashCreated = builder.mOnAnimationLeashCreated;
+        mOnAnimationLeashLost = builder.mOnAnimationLeashLost;
+        mPendingTransaction = builder.mPendingTransactionSupplier;
+        mOnAnimationFinished = builder.mOnAnimationFinished;
+    }
+
+    @NonNull
+    @Override
+    public SurfaceControl.Transaction getPendingTransaction() {
+        return mPendingTransaction.get();
+    }
+
+    @Override
+    public void commitPendingTransaction() {
+        mCommitTransactionRunnable.run();
+    }
+
+    @Override
+    public void onAnimationLeashCreated(SurfaceControl.Transaction t, SurfaceControl leash) {
+        if (mOnAnimationLeashCreated != null) {
+            mOnAnimationLeashCreated.accept(t, leash);
+        }
+
+    }
+
+    @Override
+    public void onAnimationLeashLost(SurfaceControl.Transaction t) {
+        if (mOnAnimationLeashLost != null) {
+            mOnAnimationLeashLost.accept(t);
+        }
+    }
+
+    @Override
+    @NonNull
+    public SurfaceControl.Builder makeAnimationLeash() {
+        return mAnimationLeashFactory.get();
+    }
+
+    @Override
+    public SurfaceControl getAnimationLeashParent() {
+        return mAnimationLeashParent;
+    }
+
+    @Override
+    @Nullable
+    public SurfaceControl getSurfaceControl() {
+        return mSurfaceControl;
+    }
+
+    @Override
+    public SurfaceControl getParentSurfaceControl() {
+        return mParentSurfaceControl;
+    }
+
+    @Override
+    public int getSurfaceWidth() {
+        return mWidth;
+    }
+
+    @Override
+    public int getSurfaceHeight() {
+        return mHeight;
+    }
+
+    @Override
+    public boolean shouldDeferAnimationFinish(Runnable endDeferFinishCallback) {
+        if (mOnAnimationFinished != null) {
+            mOnAnimationFinished.accept(endDeferFinishCallback);
+        }
+        return mShouldDeferAnimationFinish;
+    }
+
+    /**
+     * Builder class to create a {@link SurfaceAnimator.Animatable} without having to
+     * create a new class that implements the interface.
+     */
+    static class Builder {
+        private int mWidth = -1;
+        private int mHeight = -1;
+        private boolean mShouldDeferAnimationFinish = false;
+
+        @Nullable
+        private SurfaceControl mAnimationLeashParent = null;
+
+        @Nullable
+        private SurfaceControl mSurfaceControl = null;
+
+        @Nullable
+        private SurfaceControl mParentSurfaceControl = null;
+        private Runnable mCommitTransactionRunnable;
+
+        @Nullable
+        private BiConsumer<SurfaceControl.Transaction, SurfaceControl> mOnAnimationLeashCreated =
+                null;
+
+        @Nullable
+        private Consumer<SurfaceControl.Transaction> mOnAnimationLeashLost = null;
+
+        @Nullable
+        private Consumer<Runnable> mOnAnimationFinished = null;
+
+        @NonNull
+        private Supplier<SurfaceControl.Transaction> mPendingTransactionSupplier;
+
+        @NonNull
+        private Supplier<SurfaceControl.Builder> mAnimationLeashFactory;
+
+        /**
+         * Set the runnable to be called when
+         * {@link SurfaceAnimator.Animatable#commitPendingTransaction()}
+         * is called.
+         *
+         * @see SurfaceAnimator.Animatable#commitPendingTransaction()
+         */
+        public SimpleSurfaceAnimatable.Builder setCommitTransactionRunnable(
+                @NonNull Runnable commitTransactionRunnable) {
+            mCommitTransactionRunnable = commitTransactionRunnable;
+            return this;
+        }
+
+        /**
+         * Set the callback called when
+         * {@link SurfaceAnimator.Animatable#onAnimationLeashCreated(SurfaceControl.Transaction,
+         * SurfaceControl)} is called
+         *
+         * @see SurfaceAnimator.Animatable#onAnimationLeashCreated(SurfaceControl.Transaction,
+         * SurfaceControl)
+         */
+        public SimpleSurfaceAnimatable.Builder setOnAnimationLeashCreated(
+                @Nullable BiConsumer<SurfaceControl.Transaction, SurfaceControl>
+                        onAnimationLeashCreated) {
+            mOnAnimationLeashCreated = onAnimationLeashCreated;
+            return this;
+        }
+
+        /**
+         * Set the callback called when
+         * {@link SurfaceAnimator.Animatable#onAnimationLeashLost(SurfaceControl.Transaction)}
+         * (SurfaceControl.Transaction, SurfaceControl)} is called
+         *
+         * @see SurfaceAnimator.Animatable#onAnimationLeashLost(SurfaceControl.Transaction)
+         */
+        public SimpleSurfaceAnimatable.Builder setOnAnimationLeashLost(
+                @Nullable Consumer<SurfaceControl.Transaction> onAnimationLeashLost) {
+            mOnAnimationLeashLost = onAnimationLeashLost;
+            return this;
+        }
+
+        /**
+         * @see SurfaceAnimator.Animatable#getPendingTransaction()
+         */
+        public Builder setPendingTransactionSupplier(
+                @NonNull Supplier<SurfaceControl.Transaction> pendingTransactionSupplier) {
+            mPendingTransactionSupplier = pendingTransactionSupplier;
+            return this;
+        }
+
+        /**
+         * Set the {@link Supplier} responsible for creating a new animation leash.
+         *
+         * @see SurfaceAnimator.Animatable#makeAnimationLeash()
+         */
+        public SimpleSurfaceAnimatable.Builder setAnimationLeashSupplier(
+                @NonNull Supplier<SurfaceControl.Builder> animationLeashFactory) {
+            mAnimationLeashFactory = animationLeashFactory;
+            return this;
+        }
+
+        /**
+         * @see SurfaceAnimator.Animatable#getAnimationLeashParent()
+         */
+        public SimpleSurfaceAnimatable.Builder setAnimationLeashParent(
+                SurfaceControl animationLeashParent) {
+            mAnimationLeashParent = animationLeashParent;
+            return this;
+        }
+
+        /**
+         * @see SurfaceAnimator.Animatable#getSurfaceControl()
+         */
+        public SimpleSurfaceAnimatable.Builder setSurfaceControl(
+                @NonNull SurfaceControl surfaceControl) {
+            mSurfaceControl = surfaceControl;
+            return this;
+        }
+
+        /**
+         * @see SurfaceAnimator.Animatable#getParentSurfaceControl()
+         */
+        public SimpleSurfaceAnimatable.Builder setParentSurfaceControl(
+                SurfaceControl parentSurfaceControl) {
+            mParentSurfaceControl = parentSurfaceControl;
+            return this;
+        }
+
+        /**
+         * Default to -1.
+         *
+         * @see SurfaceAnimator.Animatable#getSurfaceWidth()
+         */
+        public SimpleSurfaceAnimatable.Builder setWidth(int width) {
+            mWidth = width;
+            return this;
+        }
+
+        /**
+         * Default to -1.
+         *
+         * @see SurfaceAnimator.Animatable#getSurfaceHeight()
+         */
+        public SimpleSurfaceAnimatable.Builder setHeight(int height) {
+            mHeight = height;
+            return this;
+        }
+
+        /**
+         * Set the value returned by
+         * {@link SurfaceAnimator.Animatable#shouldDeferAnimationFinish(Runnable)}.
+         *
+         * @param onAnimationFinish will be called with the runnable to execute when the animation
+         *                          needs to be finished.
+         * @see SurfaceAnimator.Animatable#shouldDeferAnimationFinish(Runnable)
+         */
+        public SimpleSurfaceAnimatable.Builder setShouldDeferAnimationFinish(
+                boolean shouldDeferAnimationFinish,
+                @Nullable Consumer<Runnable> onAnimationFinish) {
+            mShouldDeferAnimationFinish = shouldDeferAnimationFinish;
+            mOnAnimationFinished = onAnimationFinish;
+            return this;
+        }
+
+        public SurfaceAnimator.Animatable build() {
+            if (mPendingTransactionSupplier == null) {
+                throw new IllegalArgumentException("mPendingTransactionSupplier cannot be null");
+            }
+            if (mAnimationLeashFactory == null) {
+                throw new IllegalArgumentException("mAnimationLeashFactory cannot be null");
+            }
+            if (mCommitTransactionRunnable == null) {
+                throw new IllegalArgumentException("mCommitTransactionRunnable cannot be null");
+            }
+            if (mSurfaceControl == null) {
+                throw new IllegalArgumentException("mSurfaceControl cannot be null");
+            }
+            return new SimpleSurfaceAnimatable(this);
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/wm/StrictModeFlash.java b/services/core/java/com/android/server/wm/StrictModeFlash.java
index 9e5d9ca..f537005 100644
--- a/services/core/java/com/android/server/wm/StrictModeFlash.java
+++ b/services/core/java/com/android/server/wm/StrictModeFlash.java
@@ -39,7 +39,8 @@
     private boolean mDrawNeeded;
     private final int mThickness = 20;
 
-    StrictModeFlash(Supplier<Surface> surfaceFactory, DisplayContent dc) {
+    StrictModeFlash(Supplier<Surface> surfaceFactory, DisplayContent dc,
+            SurfaceControl.Transaction t) {
         mSurface = surfaceFactory.get();
         SurfaceControl ctrl = null;
         try {
@@ -48,9 +49,11 @@
                     .setBufferSize(1, 1)
                     .setFormat(PixelFormat.TRANSLUCENT)
                     .build();
-            ctrl.setLayer(WindowManagerService.TYPE_LAYER_MULTIPLIER * 101);  // one more than Watermark? arbitrary.
-            ctrl.setPosition(0, 0);
-            ctrl.show();
+
+            // one more than Watermark? arbitrary.
+            t.setLayer(ctrl, WindowManagerService.TYPE_LAYER_MULTIPLIER * 101);
+            t.setPosition(ctrl, 0, 0);
+            t.show(ctrl);
             mSurface.copyFrom(ctrl);
         } catch (OutOfResourcesException e) {
         }
@@ -103,25 +106,25 @@
 
     // Note: caller responsible for being inside
     // Surface.openTransaction() / closeTransaction()
-    public void setVisibility(boolean on) {
+    public void setVisibility(boolean on, SurfaceControl.Transaction t) {
         if (mSurfaceControl == null) {
             return;
         }
         drawIfNeeded();
         if (on) {
-            mSurfaceControl.show();
+            t.show(mSurfaceControl);
         } else {
-            mSurfaceControl.hide();
+            t.hide(mSurfaceControl);
         }
     }
 
-    void positionSurface(int dw, int dh) {
+    void positionSurface(int dw, int dh, SurfaceControl.Transaction t) {
         if (mLastDW == dw && mLastDH == dh) {
             return;
         }
         mLastDW = dw;
         mLastDH = dh;
-        mSurfaceControl.setBufferSize(dw, dh);
+        t.setBufferSize(mSurfaceControl, dw, dh);
         mDrawNeeded = true;
     }
 
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 85ba806..a181c18 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -63,7 +63,9 @@
 
     // TODO: Track parent marks like this in WindowContainer.
     TaskStack mStack;
+    /* Unique identifier for this task. */
     final int mTaskId;
+    /* User for which this task was created. */
     final int mUserId;
     private boolean mDeferRemoval = false;
 
@@ -97,6 +99,8 @@
     private boolean mDragResizing;
     private int mDragResizeMode;
 
+    // This represents the last resolved activity values for this task
+    // NOTE: This value needs to be persisted with each task
     private TaskDescription mTaskDescription;
 
     // If set to true, the task will report that it is not in the floating
@@ -114,6 +118,13 @@
     // TODO: remove after unification
     TaskRecord mTaskRecord;
 
+    // TODO: Remove after unification.
+    @Override
+    public void onConfigurationChanged(Configuration newParentConfig) {
+        // Only forward configuration changes in cases where children won't get it from TaskRecord.
+        onConfigurationChanged(newParentConfig, mTaskRecord == null /*forwardToChildren*/);
+    }
+
     Task(int taskId, TaskStack stack, int userId, WindowManagerService service, int resizeMode,
             boolean supportsPictureInPicture, TaskDescription taskDescription,
             TaskRecord taskRecord) {
@@ -124,16 +135,17 @@
         mResizeMode = resizeMode;
         mSupportsPictureInPicture = supportsPictureInPicture;
         mTaskRecord = taskRecord;
-        if (mTaskRecord != null) {
-            // This can be null when we call createTaskInStack in WindowTestUtils. Remove this after
-            // unification.
-            mTaskRecord.registerConfigurationChangeListener(this);
-        }
-        setBounds(getRequestedOverrideBounds());
         mTaskDescription = taskDescription;
 
         // Tasks have no set orientation value (including SCREEN_ORIENTATION_UNSPECIFIED).
         setOrientation(SCREEN_ORIENTATION_UNSET);
+        if (mTaskRecord != null) {
+            // This can be null when we call createTaskInStack in WindowTestUtils. Remove this after
+            // unification.
+            mTaskRecord.registerConfigurationChangeListener(this);
+        } else {
+            setBounds(getResolvedOverrideBounds());
+        }
     }
 
     @Override
@@ -611,7 +623,7 @@
 
     @Override
     public SurfaceControl getAnimationLeashParent() {
-        if (!WindowManagerService.sHierarchicalAnimations) {
+        if (WindowManagerService.sHierarchicalAnimations) {
             return super.getAnimationLeashParent();
         }
         // Currently, only the recents animation will create animation leashes for tasks. In this
diff --git a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
index 5e8831d..a61c908 100644
--- a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
+++ b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
@@ -58,6 +58,7 @@
     private static final int NOTIFY_TASK_DISPLAY_CHANGED_LISTENERS_MSG = 23;
     private static final int NOTIFY_TASK_LIST_UPDATED_LISTENERS_MSG = 24;
     private static final int NOTIFY_SINGLE_TASK_DISPLAY_EMPTY = 25;
+    private static final int NOTIFY_TASK_LIST_FROZEN_UNFROZEN_MSG = 26;
 
     // Delay in notifying task stack change listeners (in millis)
     private static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 100;
@@ -174,6 +175,10 @@
         l.onRecentTaskListUpdated();
     };
 
+    private final TaskStackConsumer mNotifyTaskListFrozen = (l, m) -> {
+        l.onRecentTaskListFrozenChanged(m.arg1 != 0);
+    };
+
     @FunctionalInterface
     public interface TaskStackConsumer {
         void accept(ITaskStackListener t, Message m) throws RemoteException;
@@ -265,6 +270,9 @@
                 case NOTIFY_TASK_LIST_UPDATED_LISTENERS_MSG:
                     forAllRemoteListeners(mNotifyTaskListUpdated, msg);
                     break;
+                case NOTIFY_TASK_LIST_FROZEN_UNFROZEN_MSG:
+                    forAllRemoteListeners(mNotifyTaskListFrozen, msg);
+                    break;
             }
         }
     }
@@ -342,7 +350,7 @@
     void notifyActivityPinned(ActivityRecord r) {
         mHandler.removeMessages(NOTIFY_ACTIVITY_PINNED_LISTENERS_MSG);
         final Message msg = mHandler.obtainMessage(NOTIFY_ACTIVITY_PINNED_LISTENERS_MSG,
-                r.getTaskRecord().taskId, r.getStackId(), r.packageName);
+                r.getTaskRecord().mTaskId, r.getStackId(), r.packageName);
         msg.sendingUid = r.mUserId;
         forAllLocalListeners(mNotifyActivityPinned, msg);
         msg.sendToTarget();
@@ -549,4 +557,12 @@
         forAllLocalListeners(mNotifyTaskListUpdated, msg);
         msg.sendToTarget();
     }
+
+    /** @see ITaskStackListener#onRecentTaskListFrozenChanged(boolean) */
+    void notifyTaskListFrozen(boolean frozen) {
+        final Message msg = mHandler.obtainMessage(NOTIFY_TASK_LIST_FROZEN_UNFROZEN_MSG,
+                frozen ? 1 : 0, 0 /* unused */);
+        forAllLocalListeners(mNotifyTaskListFrozen, msg);
+        msg.sendToTarget();
+    }
 }
diff --git a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
index 1c015d0..9712277 100644
--- a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
+++ b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
@@ -398,9 +398,11 @@
             return;
         }
 
-        final Rect bounds = display.getBounds();
-        final int defaultWidth = bounds.width();
-        final int defaultHeight = bounds.height();
+        // Use stable frame instead of raw frame to avoid launching freeform windows on top of
+        // stable insets, which usually are system widgets such as sysbar & navbar.
+        final Rect displayStableBounds = display.mDisplayContent.mDisplayFrames.mStable;
+        final int defaultWidth = displayStableBounds.width();
+        final int defaultHeight = displayStableBounds.height();
 
         int width;
         int height;
@@ -451,6 +453,7 @@
         }
 
         outBounds.set(0, 0, width, height);
+        outBounds.offset(displayStableBounds.left, displayStableBounds.top);
         final int xOffset = (int) (fractionOfHorizontalOffset * (defaultWidth - width));
         final int yOffset = (int) (fractionOfVerticalOffset * (defaultHeight - height));
         outBounds.offset(xOffset, yOffset);
@@ -627,10 +630,14 @@
             @NonNull ActivityInfo.WindowLayout layout, int orientation, @NonNull Rect bounds) {
         // Default size, which is letterboxing/pillarboxing in display. That's to say the large
         // dimension of default size is the small dimension of display size, and the small dimension
-        // of default size is calculated to keep the same aspect ratio as the display's.
-        Rect displayBounds = display.getBounds();
-        final int portraitHeight = Math.min(displayBounds.width(), displayBounds.height());
-        final int otherDimension = Math.max(displayBounds.width(), displayBounds.height());
+        // of default size is calculated to keep the same aspect ratio as the display's. Here we use
+        // stable bounds of displays because that indicates the area that isn't occupied by system
+        // widgets (e.g. sysbar and navbar).
+        Rect displayStableBounds = display.mDisplayContent.mDisplayFrames.mStable;
+        final int portraitHeight =
+                Math.min(displayStableBounds.width(), displayStableBounds.height());
+        final int otherDimension =
+                Math.max(displayStableBounds.width(), displayStableBounds.height());
         final int portraitWidth = (portraitHeight * portraitHeight) / otherDimension;
         final int defaultWidth = (orientation == SCREEN_ORIENTATION_LANDSCAPE) ? portraitHeight
                 : portraitWidth;
@@ -656,16 +663,17 @@
         final int height = Math.min(defaultHeight, Math.max(phoneHeight, layoutMinHeight));
 
         bounds.set(0, 0, width, height);
+        bounds.offset(displayStableBounds.left, displayStableBounds.top);
     }
 
     /**
      * Gets centered bounds of width x height. If inOutBounds is not empty, the result bounds
-     * centers at its center or display's center if inOutBounds is empty.
+     * centers at its center or display's app bounds center if inOutBounds is empty.
      */
     private void centerBounds(@NonNull ActivityDisplay display, int width, int height,
             @NonNull Rect inOutBounds) {
         if (inOutBounds.isEmpty()) {
-            display.getBounds(inOutBounds);
+            inOutBounds.set(display.mDisplayContent.mDisplayFrames.mStable);
         }
         final int left = inOutBounds.centerX() - width / 2;
         final int top = inOutBounds.centerY() - height / 2;
@@ -674,40 +682,40 @@
 
     private void adjustBoundsToFitInDisplay(@NonNull ActivityDisplay display,
             @NonNull Rect inOutBounds) {
-        final Rect displayBounds = display.getBounds();
+        final Rect displayStableBounds = display.mDisplayContent.mDisplayFrames.mStable;
 
-        if (displayBounds.width() < inOutBounds.width()
-                || displayBounds.height() < inOutBounds.height()) {
+        if (displayStableBounds.width() < inOutBounds.width()
+                || displayStableBounds.height() < inOutBounds.height()) {
             // There is no way for us to fit the bounds in the display without changing width
             // or height. Just move the start to align with the display.
             final int layoutDirection =
                     mSupervisor.mRootActivityContainer.getConfiguration().getLayoutDirection();
             final int left = layoutDirection == View.LAYOUT_DIRECTION_RTL
-                    ? displayBounds.width() - inOutBounds.width()
-                    : 0;
-            inOutBounds.offsetTo(left, 0 /* newTop */);
+                    ? displayStableBounds.right - inOutBounds.right + inOutBounds.left
+                    : displayStableBounds.left;
+            inOutBounds.offsetTo(left, displayStableBounds.top);
             return;
         }
 
         final int dx;
-        if (inOutBounds.right > displayBounds.right) {
+        if (inOutBounds.right > displayStableBounds.right) {
             // Right edge is out of display.
-            dx = displayBounds.right - inOutBounds.right;
-        } else if (inOutBounds.left < displayBounds.left) {
+            dx = displayStableBounds.right - inOutBounds.right;
+        } else if (inOutBounds.left < displayStableBounds.left) {
             // Left edge is out of display.
-            dx = displayBounds.left - inOutBounds.left;
+            dx = displayStableBounds.left - inOutBounds.left;
         } else {
             // Vertical edges are all in display.
             dx = 0;
         }
 
         final int dy;
-        if (inOutBounds.top < displayBounds.top) {
+        if (inOutBounds.top < displayStableBounds.top) {
             // Top edge is out of display.
-            dy = displayBounds.top - inOutBounds.top;
-        } else if (inOutBounds.bottom > displayBounds.bottom) {
+            dy = displayStableBounds.top - inOutBounds.top;
+        } else if (inOutBounds.bottom > displayStableBounds.bottom) {
             // Bottom edge is out of display.
-            dy = displayBounds.bottom - inOutBounds.bottom;
+            dy = displayStableBounds.bottom - inOutBounds.bottom;
         } else {
             // Horizontal edges are all in display.
             dy = 0;
diff --git a/services/core/java/com/android/server/wm/TaskPersister.java b/services/core/java/com/android/server/wm/TaskPersister.java
index 06bdcc0..f9a75d3 100644
--- a/services/core/java/com/android/server/wm/TaskPersister.java
+++ b/services/core/java/com/android/server/wm/TaskPersister.java
@@ -122,7 +122,7 @@
         mPersisterQueue.removeItems(
                 item -> {
                     File file = new File(item.mFilePath);
-                    return file.getName().startsWith(Integer.toString(task.taskId));
+                    return file.getName().startsWith(Integer.toString(task.mTaskId));
                 },
                 ImageWriteQueueItem.class);
     }
@@ -262,7 +262,7 @@
         }
         for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
             final TaskRecord task = tasks.get(taskNdx);
-            if (task.taskId == taskId) {
+            if (task.mTaskId == taskId) {
                 return task;
             }
         }
@@ -329,14 +329,14 @@
                                 // read the same thing again.
                                 // mWriteQueue.add(new TaskWriteQueueItem(task));
 
-                                final int taskId = task.taskId;
+                                final int taskId = task.mTaskId;
                                 if (mService.mRootActivityContainer.anyTaskForId(taskId,
                                         MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) != null) {
                                     // Should not happen.
                                     Slog.wtf(TAG, "Existing task with taskId " + taskId + "found");
-                                } else if (userId != task.userId) {
+                                } else if (userId != task.mUserId) {
                                     // Should not happen.
-                                    Slog.wtf(TAG, "Task with userId " + task.userId + " found in "
+                                    Slog.wtf(TAG, "Task with userId " + task.mUserId + " found in "
                                             + userTasksDir.getAbsolutePath());
                                 } else {
                                     // Looks fine.
@@ -560,14 +560,14 @@
                 FileOutputStream file = null;
                 AtomicFile atomicFile = null;
                 try {
-                    File userTasksDir = getUserTasksDir(task.userId);
+                    File userTasksDir = getUserTasksDir(task.mUserId);
                     if (!userTasksDir.isDirectory() && !userTasksDir.mkdirs()) {
-                        Slog.e(TAG, "Failure creating tasks directory for user " + task.userId
+                        Slog.e(TAG, "Failure creating tasks directory for user " + task.mUserId
                                 + ": " + userTasksDir + " Dropping persistence for task " + task);
                         return;
                     }
                     atomicFile = new AtomicFile(new File(userTasksDir,
-                            String.valueOf(task.taskId) + TASK_FILENAME_SUFFIX));
+                            String.valueOf(task.mTaskId) + TASK_FILENAME_SUFFIX));
                     file = atomicFile.startWrite();
                     file.write(stringWriter.toString().getBytes());
                     file.write('\n');
diff --git a/services/core/java/com/android/server/wm/TaskPositioner.java b/services/core/java/com/android/server/wm/TaskPositioner.java
index 42866f9..b680fa4 100644
--- a/services/core/java/com/android/server/wm/TaskPositioner.java
+++ b/services/core/java/com/android/server/wm/TaskPositioner.java
@@ -21,7 +21,7 @@
 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
 
 import static com.android.server.wm.DragResizeMode.DRAG_RESIZE_MODE_FREEFORM;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_POSITIONING;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
@@ -50,9 +50,11 @@
 import android.view.InputEvent;
 import android.view.InputWindowHandle;
 import android.view.MotionEvent;
+import android.view.SurfaceControl;
 import android.view.WindowManager;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -296,13 +298,12 @@
         mDragWindowHandle.frameBottom = p.y;
 
         // Pause rotations before a drag.
-        if (DEBUG_ORIENTATION) {
-            Slog.d(TAG, "Pausing rotation during re-position");
-        }
+        ProtoLog.d(WM_DEBUG_ORIENTATION, "Pausing rotation during re-position");
         mDisplayContent.getDisplayRotation().pause();
 
         // Notify InputMonitor to take mDragWindowHandle.
-        mDisplayContent.getInputMonitor().updateInputWindowsLw(true /*force*/);
+        mDisplayContent.getInputMonitor().updateInputWindowsImmediately();
+        new SurfaceControl.Transaction().syncInputWindows().apply(true);
 
         mMinVisibleWidth = dipToPixel(MINIMUM_VISIBLE_WIDTH_IN_DP, mDisplayMetrics);
         mMinVisibleHeight = dipToPixel(MINIMUM_VISIBLE_HEIGHT_IN_DP, mDisplayMetrics);
@@ -338,9 +339,7 @@
         mDisplayContent.getInputMonitor().updateInputWindowsLw(true /*force*/);
 
         // Resume rotations after a drag.
-        if (DEBUG_ORIENTATION) {
-            Slog.d(TAG, "Resuming rotation after re-position");
-        }
+        ProtoLog.d(WM_DEBUG_ORIENTATION, "Resuming rotation after re-position");
         mDisplayContent.getDisplayRotation().resume();
         mDisplayContent = null;
         mClientCallback.unlinkToDeath(this, 0 /* flags */);
diff --git a/services/core/java/com/android/server/wm/TaskPositioningController.java b/services/core/java/com/android/server/wm/TaskPositioningController.java
index 2441954..56b3bba 100644
--- a/services/core/java/com/android/server/wm/TaskPositioningController.java
+++ b/services/core/java/com/android/server/wm/TaskPositioningController.java
@@ -24,7 +24,6 @@
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.os.Handler;
-import android.os.IBinder;
 import android.os.Looper;
 import android.os.RemoteException;
 import android.util.Slog;
@@ -51,7 +50,6 @@
     private @Nullable TaskPositioner mTaskPositioner;
 
     private final Rect mTmpClipRect = new Rect();
-    private IBinder mTransferTouchFromToken;
 
     boolean isPositioningLocked() {
         return mTaskPositioner != null;
@@ -104,8 +102,6 @@
 
         mTmpClipRect.set(0, 0, p.x, p.y);
         t.setWindowCrop(mInputSurface, mTmpClipRect);
-        t.transferTouchFocus(mTransferTouchFromToken, h.token);
-        mTransferTouchFromToken = null;
     }
 
     boolean startMovingTask(IWindow window, float startX, float startY) {
@@ -168,6 +164,7 @@
         mPositioningDisplay = displayContent;
 
         mTaskPositioner = TaskPositioner.create(mService);
+        mTaskPositioner.register(displayContent);
 
         // We need to grab the touch focus so that the touch events during the
         // resizing/scrolling are not sent to the app. 'win' is the main window
@@ -178,8 +175,12 @@
                 && displayContent.mCurrentFocus.mAppToken == win.mAppToken) {
             transferFocusFromWin = displayContent.mCurrentFocus;
         }
-        mTransferTouchFromToken = transferFocusFromWin.mInputChannel.getToken();
-        mTaskPositioner.register(displayContent);
+        if (!mInputManager.transferTouchFocus(
+                transferFocusFromWin.mInputChannel, mTaskPositioner.mServerChannel)) {
+            Slog.e(TAG_WM, "startPositioningLocked: Unable to transfer touch focus");
+            cleanUpTaskPositioner();
+            return false;
+        }
 
         mTaskPositioner.startDrag(win, resize, preserveOrientation, startX, startY);
         return true;
diff --git a/services/core/java/com/android/server/wm/TaskRecord.java b/services/core/java/com/android/server/wm/TaskRecord.java
index 0ea108e..75333c7 100644
--- a/services/core/java/com/android/server/wm/TaskRecord.java
+++ b/services/core/java/com/android/server/wm/TaskRecord.java
@@ -208,7 +208,7 @@
      */
     private static TaskRecordFactory sTaskRecordFactory;
 
-    final int taskId;       // Unique identifier for this task.
+    final int mTaskId;      // Unique identifier for this task.
     String affinity;        // The affinity name for this task, or null; may change identity.
     String rootAffinity;    // Initial base affinity, or null; does not change from initial root.
     final IVoiceInteractionSession voiceSession;    // Voice interaction session driving task
@@ -234,7 +234,7 @@
     boolean hasBeenVisible; // Set if any activities in the task have been visible to the user.
 
     String stringName;      // caching of toString() result.
-    int userId;             // user for which this task was created
+    int mUserId;            // user for which this task was created
     boolean mUserSetupComplete; // The user set-up is complete as of the last time the task activity
                                 // was changed.
 
@@ -262,7 +262,7 @@
 
     // This represents the last resolved activity values for this task
     // NOTE: This value needs to be persisted with each task
-    TaskDescription lastTaskDescription = new TaskDescription();
+    TaskDescription mTaskDescription;
 
     /** List of all activities in the task arranged in history order */
     final ArrayList<ActivityRecord> mActivities;
@@ -282,7 +282,7 @@
     /** Only used for persistable tasks, otherwise 0. The last time this task was moved. Used for
      * determining the order when restoring. Sign indicates whether last task movement was to front
      * (positive) or back (negative). Absolute value indicates time. */
-    long mLastTimeMoved = System.currentTimeMillis();
+    long mLastTimeMoved;
 
     /** If original intent did not allow relinquishing task identity, save that information */
     private boolean mNeverRelinquishIdentity = true;
@@ -304,7 +304,7 @@
     int mCallingUid;
     String mCallingPackage;
 
-    final ActivityTaskManagerService mService;
+    final ActivityTaskManagerService mAtmService;
 
     private final Rect mTmpStableBounds = new Rect();
     private final Rect mTmpNonDecorBounds = new Rect();
@@ -342,60 +342,25 @@
      * Don't use constructor directly. Use {@link #create(ActivityTaskManagerService, int,
      * ActivityInfo, Intent, TaskDescription)} instead.
      */
-    TaskRecord(ActivityTaskManagerService service, int _taskId, ActivityInfo info, Intent _intent,
-            IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor) {
-        mService = service;
-        userId = UserHandle.getUserId(info.applicationInfo.uid);
-        taskId = _taskId;
-        lastActiveTime = SystemClock.elapsedRealtime();
-        mAffiliatedTaskId = _taskId;
-        voiceSession = _voiceSession;
-        voiceInteractor = _voiceInteractor;
-        isAvailable = true;
-        mActivities = new ArrayList<>();
-        mCallingUid = info.applicationInfo.uid;
-        mCallingPackage = info.packageName;
-        setIntent(_intent, info);
-        setMinDimensions(info);
-        touchActiveTime();
-        mService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity);
+    TaskRecord(ActivityTaskManagerService atmService, int _taskId, ActivityInfo info,
+            Intent _intent, IVoiceInteractionSession _voiceSession,
+            IVoiceInteractor _voiceInteractor, TaskDescription _taskDescription) {
+        this(atmService, _taskId, _intent,  null /*_affinityIntent*/, null /*_affinity*/,
+                null /*_rootAffinity*/, null /*_realActivity*/, null /*_origActivity*/,
+                false /*_rootWasReset*/, false /*_autoRemoveRecents*/, false /*_askedCompatMode*/,
+                UserHandle.getUserId(info.applicationInfo.uid), 0 /*_effectiveUid*/,
+                null /*_lastDescription*/, new ArrayList<>(), System.currentTimeMillis(),
+                true /*neverRelinquishIdentity*/,
+                _taskDescription != null ? _taskDescription : new TaskDescription(),
+                _taskId, INVALID_TASK_ID, INVALID_TASK_ID, 0 /*taskAffiliationColor*/,
+                info.applicationInfo.uid, info.packageName, info.resizeMode,
+                info.supportsPictureInPicture(), false /*_realActivitySuspended*/,
+                false /*userSetupComplete*/, INVALID_MIN_SIZE, INVALID_MIN_SIZE, info,
+                _voiceSession, _voiceInteractor);
     }
 
-    /**
-     * Don't use constructor directly.
-     * Use {@link #create(ActivityTaskManagerService, int, ActivityInfo,
-     * Intent, IVoiceInteractionSession, IVoiceInteractor)} instead.
-     */
-    TaskRecord(ActivityTaskManagerService service, int _taskId, ActivityInfo info, Intent _intent,
-            TaskDescription _taskDescription) {
-        mService = service;
-        userId = UserHandle.getUserId(info.applicationInfo.uid);
-        taskId = _taskId;
-        lastActiveTime = SystemClock.elapsedRealtime();
-        mAffiliatedTaskId = _taskId;
-        voiceSession = null;
-        voiceInteractor = null;
-        isAvailable = true;
-        mActivities = new ArrayList<>();
-        mCallingUid = info.applicationInfo.uid;
-        mCallingPackage = info.packageName;
-        setIntent(_intent, info);
-        setMinDimensions(info);
-
-        isPersistable = true;
-        // Clamp to [1, max].
-        maxRecents = Math.min(Math.max(info.maxRecents, 1),
-                ActivityTaskManager.getMaxAppRecentsLimitStatic());
-
-        lastTaskDescription = _taskDescription;
-        touchActiveTime();
-        mService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity);
-    }
-
-    /**
-     * Don't use constructor directly. This is only used by XML parser.
-     */
-    TaskRecord(ActivityTaskManagerService service, int _taskId, Intent _intent,
+    /** Don't use constructor directly. This is only used by XML parser. */
+    TaskRecord(ActivityTaskManagerService atmService, int _taskId, Intent _intent,
             Intent _affinityIntent, String _affinity, String _rootAffinity,
             ComponentName _realActivity, ComponentName _origActivity, boolean _rootWasReset,
             boolean _autoRemoveRecents, boolean _askedCompatMode, int _userId,
@@ -404,15 +369,15 @@
             TaskDescription _lastTaskDescription, int taskAffiliation, int prevTaskId,
             int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage,
             int resizeMode, boolean supportsPictureInPicture, boolean _realActivitySuspended,
-            boolean userSetupComplete, int minWidth, int minHeight) {
-        mService = service;
-        taskId = _taskId;
-        intent = _intent;
+            boolean userSetupComplete, int minWidth, int minHeight, ActivityInfo info,
+            IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor) {
+        mAtmService = atmService;
+        mTaskId = _taskId;
         affinityIntent = _affinityIntent;
         affinity = _affinity;
         rootAffinity = _rootAffinity;
-        voiceSession = null;
-        voiceInteractor = null;
+        voiceSession = _voiceSession;
+        voiceInteractor = _voiceInteractor;
         realActivity = _realActivity;
         realActivitySuspended = _realActivitySuspended;
         origActivity = _origActivity;
@@ -420,15 +385,15 @@
         isAvailable = true;
         autoRemoveRecents = _autoRemoveRecents;
         askedCompatMode = _askedCompatMode;
-        userId = _userId;
+        mUserId = _userId;
         mUserSetupComplete = userSetupComplete;
         effectiveUid = _effectiveUid;
-        lastActiveTime = SystemClock.elapsedRealtime();
+        touchActiveTime();
         lastDescription = _lastDescription;
         mActivities = activities;
         mLastTimeMoved = lastTimeMoved;
         mNeverRelinquishIdentity = neverRelinquishIdentity;
-        lastTaskDescription = _lastTaskDescription;
+        mTaskDescription = _lastTaskDescription;
         mAffiliatedTaskId = taskAffiliation;
         mAffiliatedTaskColor = taskAffiliationColor;
         mPrevAffiliateTaskId = prevTaskId;
@@ -437,9 +402,15 @@
         mCallingPackage = callingPackage;
         mResizeMode = resizeMode;
         mSupportsPictureInPicture = supportsPictureInPicture;
-        mMinWidth = minWidth;
-        mMinHeight = minHeight;
-        mService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity);
+        if (info != null) {
+            setIntent(_intent, info);
+            setMinDimensions(info);
+        } else {
+            intent = _intent;
+            mMinWidth = minWidth;
+            mMinHeight = minHeight;
+        }
+        mAtmService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity);
     }
 
     Task getTask() {
@@ -458,9 +429,9 @@
         if (stack == null) {
             throw new IllegalArgumentException("TaskRecord: invalid stack=" + mStack);
         }
-        EventLog.writeEvent(WM_TASK_CREATED, taskId, stack.mStackId);
-        mTask = new Task(taskId, stack, userId, mService.mWindowManager, mResizeMode,
-                mSupportsPictureInPicture, lastTaskDescription, this);
+        EventLog.writeEvent(WM_TASK_CREATED, mTaskId, stack.mStackId);
+        mTask = new Task(mTaskId, stack, mUserId, mAtmService.mWindowManager, mResizeMode,
+                mSupportsPictureInPicture, mTaskDescription, this);
         final int position = onTop ? POSITION_TOP : POSITION_BOTTOM;
 
         if (!mDisplayedBounds.isEmpty()) {
@@ -487,14 +458,14 @@
         final boolean isVoiceSession = voiceSession != null;
         if (isVoiceSession) {
             try {
-                voiceSession.taskFinished(intent, taskId);
+                voiceSession.taskFinished(intent, mTaskId);
             } catch (RemoteException e) {
             }
         }
         if (autoRemoveFromRecents() || isVoiceSession) {
             // Task creator asked to remove this when done, or this task was a voice
             // interaction, so it should not remain on the recent tasks list.
-            mService.mStackSupervisor.mRecentTasks.remove(this);
+            mAtmService.mStackSupervisor.mRecentTasks.remove(this);
         }
 
         removeWindowContainer();
@@ -502,9 +473,9 @@
 
     @VisibleForTesting
     void removeWindowContainer() {
-        mService.getLockTaskController().clearLockedTask(this);
+        mAtmService.getLockTaskController().clearLockedTask(this);
         if (mTask == null) {
-            if (DEBUG_STACK) Slog.i(TAG_WM, "removeTask: could not find taskId=" + taskId);
+            if (DEBUG_STACK) Slog.i(TAG_WM, "removeTask: could not find taskId=" + mTaskId);
             return;
         }
         mTask.removeIfPossible();
@@ -514,11 +485,11 @@
             // default configuration the next time it launches.
             setBounds(null);
         }
-        mService.getTaskChangeNotificationController().notifyTaskRemoved(taskId);
+        mAtmService.getTaskChangeNotificationController().notifyTaskRemoved(mTaskId);
     }
 
-    public void onSnapshotChanged(TaskSnapshot snapshot) {
-        mService.getTaskChangeNotificationController().notifyTaskSnapshotChanged(taskId, snapshot);
+    void onSnapshotChanged(TaskSnapshot snapshot) {
+        mAtmService.getTaskChangeNotificationController().notifyTaskSnapshotChanged(mTaskId, snapshot);
     }
 
     void setResizeMode(int resizeMode) {
@@ -527,13 +498,13 @@
         }
         mResizeMode = resizeMode;
         mTask.setResizeable(resizeMode);
-        mService.mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
-        mService.mRootActivityContainer.resumeFocusedStacksTopActivities();
+        mAtmService.mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
+        mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities();
     }
 
     void setTaskDockedResizing(boolean resizing) {
         if (mTask == null) {
-            Slog.w(TAG_WM, "setTaskDockedResizing: taskId " + taskId + " not found.");
+            Slog.w(TAG_WM, "setTaskDockedResizing: taskId " + mTaskId + " not found.");
             return;
         }
         mTask.setTaskDockedResizing(resizing);
@@ -541,11 +512,11 @@
 
     // TODO: Consolidate this with the resize() method below.
     public void requestResize(Rect bounds, int resizeMode) {
-        mService.resizeTask(taskId, bounds, resizeMode);
+        mAtmService.resizeTask(mTaskId, bounds, resizeMode);
     }
 
     boolean resize(Rect bounds, int resizeMode, boolean preserveWindow, boolean deferResume) {
-        mService.deferWindowLayout();
+        mAtmService.deferWindowLayout();
 
         try {
             if (!isResizeable()) {
@@ -568,7 +539,7 @@
                 setBounds(bounds);
                 if (!inFreeformWindowingMode()) {
                     // re-restore the task so it can have the proper stack association.
-                    mService.mStackSupervisor.restoreRecentTaskLocked(this, null, !ON_TOP);
+                    mAtmService.mStackSupervisor.restoreRecentTaskLocked(this, null, !ON_TOP);
                 }
                 return true;
             }
@@ -582,7 +553,7 @@
             // This method assumes that the task is already placed in the right stack.
             // we do not mess with that decision and we only do the resize!
 
-            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeTask_" + taskId);
+            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeTask_" + mTaskId);
 
             boolean updatedConfig = false;
             mTmpConfig.setTo(getResolvedOverrideConfiguration());
@@ -606,9 +577,9 @@
                     // this won't cause tons of irrelevant windows being preserved because only
                     // activities in this task may experience a bounds change. Configs for other
                     // activities stay the same.
-                    mService.mRootActivityContainer.ensureActivitiesVisible(r, 0, preserveWindow);
+                    mAtmService.mRootActivityContainer.ensureActivitiesVisible(r, 0, preserveWindow);
                     if (!kept) {
-                        mService.mRootActivityContainer.resumeFocusedStacksTopActivities();
+                        mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities();
                     }
                 }
             }
@@ -619,7 +590,7 @@
             Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
             return kept;
         } finally {
-            mService.continueWindowLayout();
+            mAtmService.continueWindowLayout();
         }
     }
 
@@ -687,9 +658,9 @@
     boolean reparent(ActivityStack preferredStack, int position,
             @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume,
             boolean schedulePictureInPictureModeChange, String reason) {
-        final ActivityStackSupervisor supervisor = mService.mStackSupervisor;
-        final RootActivityContainer root = mService.mRootActivityContainer;
-        final WindowManagerService windowManager = mService.mWindowManager;
+        final ActivityStackSupervisor supervisor = mAtmService.mStackSupervisor;
+        final RootActivityContainer root = mAtmService.mRootActivityContainer;
+        final WindowManagerService windowManager = mAtmService.mWindowManager;
         final ActivityStack sourceStack = getStack();
         final ActivityStack toStack = supervisor.getReparentTargetStack(this, preferredStack,
                 position == MAX_VALUE);
@@ -725,7 +696,7 @@
             windowManager.setWillReplaceWindow(topActivity.appToken, animate);
         }
 
-        mService.deferWindowLayout();
+        mAtmService.deferWindowLayout();
         boolean kept = true;
         try {
             final ActivityRecord r = topRunningActivityLocked();
@@ -764,7 +735,7 @@
             // Notify the voice session if required
             if (voiceSession != null) {
                 try {
-                    voiceSession.taskStarted(intent, taskId);
+                    voiceSession.taskStarted(intent, mTaskId);
                 } catch (RemoteException e) {
                 }
             }
@@ -776,7 +747,7 @@
                         wasPaused, reason);
             }
             if (!animate) {
-                mService.mStackSupervisor.mNoAnimActivities.add(topActivity);
+                mAtmService.mStackSupervisor.mNoAnimActivities.add(topActivity);
             }
 
             // We might trigger a configuration change. Save the current task bounds for freezing.
@@ -795,7 +766,7 @@
             } else if (toStackWindowingMode == WINDOWING_MODE_FREEFORM) {
                 Rect bounds = getLaunchBounds();
                 if (bounds == null) {
-                    mService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null);
+                    mAtmService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null);
                     bounds = configBounds;
                 }
                 kept = resize(bounds, RESIZE_MODE_FORCED, !mightReplaceWindow, deferResume);
@@ -803,13 +774,13 @@
                 if (toStackSplitScreenPrimary && moveStackMode == REPARENT_KEEP_STACK_AT_FRONT) {
                     // Move recents to front so it is not behind home stack when going into docked
                     // mode
-                    mService.mStackSupervisor.moveRecentsStackToFront(reason);
+                    mAtmService.mStackSupervisor.moveRecentsStackToFront(reason);
                 }
                 kept = resize(toStack.getRequestedOverrideBounds(), RESIZE_MODE_SYSTEM,
                         !mightReplaceWindow, deferResume);
             }
         } finally {
-            mService.continueWindowLayout();
+            mAtmService.continueWindowLayout();
         }
 
         if (mightReplaceWindow) {
@@ -846,7 +817,7 @@
 
     void cancelWindowTransition() {
         if (mTask == null) {
-            Slog.w(TAG_WM, "cancelWindowTransition: taskId " + taskId + " not found.");
+            Slog.w(TAG_WM, "cancelWindowTransition: taskId " + mTaskId + " not found.");
             return;
         }
         mTask.cancelTaskWindowTransition();
@@ -859,7 +830,7 @@
 
         // TODO: Move this to {@link TaskWindowContainerController} once recent tasks are more
         // synchronized between AM and WM.
-        return mService.mWindowManager.getTaskSnapshot(taskId, userId, reducedResolution,
+        return mAtmService.mWindowManager.getTaskSnapshot(mTaskId, mUserId, reducedResolution,
                 restoreFromDisk);
     }
 
@@ -938,9 +909,9 @@
             // task as having a true root activity.
             rootWasReset = true;
         }
-        userId = UserHandle.getUserId(info.applicationInfo.uid);
-        mUserSetupComplete = Settings.Secure.getIntForUser(mService.mContext.getContentResolver(),
-                USER_SETUP_COMPLETE, 0, userId) != 0;
+        mUserId = UserHandle.getUserId(info.applicationInfo.uid);
+        mUserSetupComplete = Settings.Secure.getIntForUser(
+                mAtmService.mContext.getContentResolver(), USER_SETUP_COMPLETE, 0, mUserId) != 0;
         if ((info.flags & ActivityInfo.FLAG_AUTO_REMOVE_FROM_RECENTS) != 0) {
             // If the activity itself has requested auto-remove, then just always do it.
             autoRemoveRecents = true;
@@ -993,12 +964,12 @@
 
     void setPrevAffiliate(TaskRecord prevAffiliate) {
         mPrevAffiliate = prevAffiliate;
-        mPrevAffiliateTaskId = prevAffiliate == null ? INVALID_TASK_ID : prevAffiliate.taskId;
+        mPrevAffiliateTaskId = prevAffiliate == null ? INVALID_TASK_ID : prevAffiliate.mTaskId;
     }
 
     void setNextAffiliate(TaskRecord nextAffiliate) {
         mNextAffiliate = nextAffiliate;
-        mNextAffiliateTaskId = nextAffiliate == null ? INVALID_TASK_ID : nextAffiliate.taskId;
+        mNextAffiliateTaskId = nextAffiliate == null ? INVALID_TASK_ID : nextAffiliate.mTaskId;
     }
 
     <T extends ActivityStack> T getStack() {
@@ -1061,7 +1032,7 @@
     @Override
     protected void onParentChanged() {
         super.onParentChanged();
-        mService.mRootActivityContainer.updateUIDsPresentOnDisplay();
+        mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay();
     }
 
     // Close up recents linked list.
@@ -1080,13 +1051,13 @@
         closeRecentsChain();
         if (inRecents) {
             inRecents = false;
-            mService.notifyTaskPersisterLocked(this, false);
+            mAtmService.notifyTaskPersisterLocked(this, false);
         }
 
         clearRootProcess();
 
-        mService.mWindowManager.mTaskSnapshotController.notifyTaskRemovedFromRecents(
-                taskId, userId);
+        mAtmService.mWindowManager.mTaskSnapshotController.notifyTaskRemovedFromRecents(
+                mTaskId, mUserId);
     }
 
     void setTaskToAffiliateWith(TaskRecord taskToAffiliateWith) {
@@ -1235,7 +1206,7 @@
     boolean okToShowLocked() {
         // NOTE: If {@link TaskRecord#topRunningActivity} return is not null then it is
         // okay to show the activity when locked.
-        return mService.mStackSupervisor.isCurrentProfileLocked(userId)
+        return mAtmService.mStackSupervisor.isCurrentProfileLocked(mUserId)
                 || topRunningActivityLocked() != null;
     }
 
@@ -1251,7 +1222,7 @@
         mActivities.add(newTop);
 
         // Make sure window manager is aware of the position change.
-        mTask.positionChildAtTop(newTop.mAppWindowToken);
+        mTask.positionChildAtTop(newTop);
         updateEffectiveIntent();
     }
 
@@ -1283,7 +1254,7 @@
         r.setTask(this);
 
         // Remove r first, and if it wasn't already in the list and it's fullscreen, count it.
-        if (!mActivities.remove(r) && r.fullscreen) {
+        if (!mActivities.remove(r) && r.occludesParent()) {
             // Was not previously in list.
             numFullscreen++;
         }
@@ -1324,18 +1295,18 @@
 
         updateEffectiveIntent();
         if (r.isPersistable()) {
-            mService.notifyTaskPersisterLocked(this, false);
+            mAtmService.notifyTaskPersisterLocked(this, false);
         }
 
-        if (r.mAppWindowToken != null) {
+        if (r.getParent() != null) {
             // Only attempt to move in WM if the child has a controller. It is possible we haven't
             // created controller for the activity we are starting yet.
-            mTask.positionChildAt(r.mAppWindowToken, index);
+            mTask.positionChildAt(r, index);
         }
 
         // Make sure the list of display UID whitelists is updated
         // now that this record is in a new task.
-        mService.mRootActivityContainer.updateUIDsPresentOnDisplay();
+        mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay();
     }
 
     /**
@@ -1355,19 +1326,19 @@
 
         r.setTask(null /* task */, reparenting /* reparenting */);
 
-        if (mActivities.remove(r) && r.fullscreen) {
+        if (mActivities.remove(r) && r.occludesParent()) {
             // Was previously in list.
             numFullscreen--;
         }
         if (r.isPersistable()) {
-            mService.notifyTaskPersisterLocked(this, false);
+            mAtmService.notifyTaskPersisterLocked(this, false);
         }
 
         if (inPinnedWindowingMode()) {
             // We normally notify listeners of task stack changes on pause, however pinned stack
             // activities are normally in the paused state so no notification will be sent there
             // before the activity is removed. We send it here so instead.
-            mService.getTaskChangeNotificationController().notifyTaskStackChanged();
+            mAtmService.getTaskChangeNotificationController().notifyTaskStackChanged();
         }
 
         if (mActivities.isEmpty()) {
@@ -1530,10 +1501,10 @@
         }
 
         final String pkg = (realActivity != null) ? realActivity.getPackageName() : null;
-        final LockTaskController lockTaskController = mService.getLockTaskController();
+        final LockTaskController lockTaskController = mAtmService.getLockTaskController();
         switch (r.lockTaskLaunchMode) {
             case LOCK_TASK_LAUNCH_MODE_DEFAULT:
-                mLockTaskAuth = lockTaskController.isPackageWhitelisted(userId, pkg)
+                mLockTaskAuth = lockTaskController.isPackageWhitelisted(mUserId, pkg)
                         ? LOCK_TASK_AUTH_WHITELISTED : LOCK_TASK_AUTH_PINNABLE;
                 break;
 
@@ -1546,7 +1517,7 @@
                 break;
 
             case LOCK_TASK_LAUNCH_MODE_IF_WHITELISTED:
-                mLockTaskAuth = lockTaskController.isPackageWhitelisted(userId, pkg)
+                mLockTaskAuth = lockTaskController.isPackageWhitelisted(mUserId, pkg)
                         ? LOCK_TASK_AUTH_LAUNCHABLE : LOCK_TASK_AUTH_PINNABLE;
                 break;
         }
@@ -1555,7 +1526,7 @@
     }
 
     private boolean isResizeable(boolean checkSupportsPip) {
-        return (mService.mForceResizableActivities || ActivityInfo.isResizeableMode(mResizeMode)
+        return (mAtmService.mForceResizableActivities || ActivityInfo.isResizeableMode(mResizeMode)
                 || (checkSupportsPip && mSupportsPictureInPicture));
     }
 
@@ -1568,8 +1539,8 @@
         // A task can not be docked even if it is considered resizeable because it only supports
         // picture-in-picture mode but has a non-resizeable resizeMode
         return super.supportsSplitScreenWindowingMode()
-                && mService.mSupportsSplitScreenMultiWindow
-                && (mService.mForceResizableActivities
+                && mAtmService.mSupportsSplitScreenMultiWindow
+                && (mAtmService.mForceResizableActivities
                         || (isResizeable(false /* checkSupportsPip */)
                                 && !ActivityInfo.isPreserveOrientationMode(mResizeMode)));
     }
@@ -1582,7 +1553,7 @@
      *         secondary display.
      */
     boolean canBeLaunchedOnDisplay(int displayId) {
-        return mService.mStackSupervisor.canPlaceEntityOnDisplay(displayId,
+        return mAtmService.mStackSupervisor.canPlaceEntityOnDisplay(displayId,
                 -1 /* don't check PID */, -1 /* don't check UID */, null /* activityInfo */);
     }
 
@@ -1700,15 +1671,15 @@
                 }
                 topActivity = false;
             }
-            lastTaskDescription = new TaskDescription(label, null, iconResource, iconFilename,
+            mTaskDescription = new TaskDescription(label, null, iconResource, iconFilename,
                     colorPrimary, colorBackground, statusBarColor, navigationBarColor,
                     statusBarContrastWhenTransparent, navigationBarContrastWhenTransparent);
             if (mTask != null) {
-                mTask.setTaskDescription(lastTaskDescription);
+                mTask.setTaskDescription(mTaskDescription);
             }
             // Update the task affiliation color if we are the parent of the group
-            if (taskId == mAffiliatedTaskId) {
-                mAffiliatedTaskColor = lastTaskDescription.getPrimaryColor();
+            if (mTaskId == mAffiliatedTaskId) {
+                mAffiliatedTaskColor = mTaskDescription.getPrimaryColor();
             }
         }
     }
@@ -1767,9 +1738,9 @@
         // to do this for the pinned stack as the bounds are controlled by the system.
         if (!inPinnedWindowingMode() && mStack != null) {
             final int defaultMinSizeDp =
-                    mService.mRootActivityContainer.mDefaultMinSizeOfResizeableTaskDp;
+                    mAtmService.mRootActivityContainer.mDefaultMinSizeOfResizeableTaskDp;
             final ActivityDisplay display =
-                    mService.mRootActivityContainer.getActivityDisplay(mStack.mDisplayId);
+                    mAtmService.mRootActivityContainer.getActivityDisplay(mStack.mDisplayId);
             final float density =
                     (float) display.getConfiguration().densityDpi / DisplayMetrics.DENSITY_DEFAULT;
             final int defaultMinSize = (int) (defaultMinSizeDp * density);
@@ -1849,7 +1820,7 @@
         final boolean wasInMultiWindowMode = inMultiWindowMode();
         super.onConfigurationChanged(newParentConfig);
         if (wasInMultiWindowMode != inMultiWindowMode()) {
-            mService.mStackSupervisor.scheduleUpdateMultiWindowMode(this);
+            mAtmService.mStackSupervisor.scheduleUpdateMultiWindowMode(this);
         }
 
         // If the configuration supports persistent bounds (eg. Freeform), keep track of the
@@ -1890,7 +1861,7 @@
         }
 
         // Saves the new state so that we can launch the activity at the same location.
-        mService.mStackSupervisor.mLaunchParamsPersister.saveTask(this);
+        mAtmService.mStackSupervisor.mLaunchParamsPersister.saveTask(this);
     }
 
     /**
@@ -2293,7 +2264,7 @@
             if (mLastNonFullscreenBounds != null) {
                 setBounds(mLastNonFullscreenBounds);
             } else {
-                mService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null);
+                mAtmService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null);
             }
         } else {
             setBounds(inStack.getRequestedOverrideBounds());
@@ -2354,9 +2325,9 @@
      */
     void fillTaskInfo(TaskInfo info) {
         getNumRunningActivities(mReuseActivitiesReport);
-        info.userId = userId;
+        info.userId = mUserId;
         info.stackId = getStackId();
-        info.taskId = taskId;
+        info.taskId = mTaskId;
         info.displayId = mStack == null ? Display.INVALID_DISPLAY : mStack.mDisplayId;
         info.isRunning = getTopActivity() != null;
         info.baseIntent = new Intent(getBaseIntent());
@@ -2370,7 +2341,7 @@
         info.realActivity = realActivity;
         info.numActivities = mReuseActivitiesReport.numActivities;
         info.lastActiveTime = lastActiveTime;
-        info.taskDescription = new ActivityManager.TaskDescription(lastTaskDescription);
+        info.taskDescription = new ActivityManager.TaskDescription(mTaskDescription);
         info.supportsSplitScreenMultiWindow = supportsSplitScreenWindowingMode();
         info.resizeMode = mResizeMode;
         info.configuration.setTo(getConfiguration());
@@ -2386,7 +2357,7 @@
     }
 
     void dump(PrintWriter pw, String prefix) {
-        pw.print(prefix); pw.print("userId="); pw.print(userId);
+        pw.print(prefix); pw.print("userId="); pw.print(mUserId);
                 pw.print(" effectiveUid="); UserHandle.formatUid(pw, effectiveUid);
                 pw.print(" mCallingUid="); UserHandle.formatUid(pw, mCallingUid);
                 pw.print(" mUserSetupComplete="); pw.print(mUserSetupComplete);
@@ -2440,7 +2411,7 @@
                     pw.print(" mReuseTask="); pw.print(mReuseTask);
                     pw.print(" mLockTaskAuth="); pw.println(lockTaskAuthToString());
         }
-        if (mAffiliatedTaskId != taskId || mPrevAffiliateTaskId != INVALID_TASK_ID
+        if (mAffiliatedTaskId != mTaskId || mPrevAffiliateTaskId != INVALID_TASK_ID
                 || mPrevAffiliate != null || mNextAffiliateTaskId != INVALID_TASK_ID
                 || mNextAffiliate != null) {
             pw.print(prefix); pw.print("affiliation="); pw.print(mAffiliatedTaskId);
@@ -2487,7 +2458,7 @@
         if (stringName != null) {
             sb.append(stringName);
             sb.append(" U=");
-            sb.append(userId);
+            sb.append(mUserId);
             sb.append(" StackId=");
             sb.append(getStackId());
             sb.append(" sz=");
@@ -2498,7 +2469,7 @@
         sb.append("TaskRecord{");
         sb.append(Integer.toHexString(System.identityHashCode(this)));
         sb.append(" #");
-        sb.append(taskId);
+        sb.append(mTaskId);
         if (affinity != null) {
             sb.append(" A=");
             sb.append(affinity);
@@ -2523,7 +2494,7 @@
 
         final long token = proto.start(fieldId);
         super.writeToProto(proto, CONFIGURATION_CONTAINER, logLevel);
-        proto.write(ID, taskId);
+        proto.write(ID, mTaskId);
         for (int i = mActivities.size() - 1; i >= 0; i--) {
             ActivityRecord activity = mActivities.get(i);
             activity.writeToProto(proto, ACTIVITIES);
@@ -2573,7 +2544,7 @@
     void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException {
         if (DEBUG_RECENTS) Slog.i(TAG_RECENTS, "Saving task=" + this);
 
-        out.attribute(null, ATTR_TASKID, String.valueOf(taskId));
+        out.attribute(null, ATTR_TASKID, String.valueOf(mTaskId));
         if (realActivity != null) {
             out.attribute(null, ATTR_REALACTIVITY, realActivity.flattenToShortString());
         }
@@ -2596,7 +2567,7 @@
         out.attribute(null, ATTR_ROOTHASRESET, String.valueOf(rootWasReset));
         out.attribute(null, ATTR_AUTOREMOVERECENTS, String.valueOf(autoRemoveRecents));
         out.attribute(null, ATTR_ASKEDCOMPATMODE, String.valueOf(askedCompatMode));
-        out.attribute(null, ATTR_USERID, String.valueOf(userId));
+        out.attribute(null, ATTR_USERID, String.valueOf(mUserId));
         out.attribute(null, ATTR_USER_SETUP_COMPLETE, String.valueOf(mUserSetupComplete));
         out.attribute(null, ATTR_EFFECTIVE_UID, String.valueOf(effectiveUid));
         out.attribute(null, ATTR_LASTTIMEMOVED, String.valueOf(mLastTimeMoved));
@@ -2604,8 +2575,8 @@
         if (lastDescription != null) {
             out.attribute(null, ATTR_LASTDESCRIPTION, lastDescription.toString());
         }
-        if (lastTaskDescription != null) {
-            lastTaskDescription.saveToXml(out);
+        if (mTaskDescription != null) {
+            mTaskDescription.saveToXml(out);
         }
         out.attribute(null, ATTR_TASK_AFFILIATION_COLOR, String.valueOf(mAffiliatedTaskColor));
         out.attribute(null, ATTR_TASK_AFFILIATION, String.valueOf(mAffiliatedTaskId));
@@ -2692,13 +2663,14 @@
         TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info,
                 Intent intent, IVoiceInteractionSession voiceSession,
                 IVoiceInteractor voiceInteractor) {
-            return new TaskRecord(
-                    service, taskId, info, intent, voiceSession, voiceInteractor);
+            return new TaskRecord(service, taskId, info, intent, voiceSession, voiceInteractor,
+                    null /*taskDescription*/);
         }
 
         TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info,
                 Intent intent, TaskDescription taskDescription) {
-            return new TaskRecord(service, taskId, info, intent, taskDescription);
+            return new TaskRecord(service, taskId, info, intent, null /*voiceSession*/,
+                    null /*voiceInteractor*/, taskDescription);
         }
 
         /**
@@ -2720,7 +2692,8 @@
                     lastTimeMoved, neverRelinquishIdentity, lastTaskDescription, taskAffiliation,
                     prevTaskId, nextTaskId, taskAffiliationColor, callingUid, callingPackage,
                     resizeMode, supportsPictureInPicture, realActivitySuspended, userSetupComplete,
-                    minWidth, minHeight);
+                    minWidth, minHeight, null /*ActivityInfo*/, null /*_voiceSession*/,
+                    null /*_voiceInteractor*/);
         }
 
         TaskRecord restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor)
diff --git a/services/core/java/com/android/server/wm/TaskScreenshotAnimatable.java b/services/core/java/com/android/server/wm/TaskScreenshotAnimatable.java
index d36ebf0..adecc36 100644
--- a/services/core/java/com/android/server/wm/TaskScreenshotAnimatable.java
+++ b/services/core/java/com/android/server/wm/TaskScreenshotAnimatable.java
@@ -15,14 +15,15 @@
  */
 package com.android.server.wm;
 
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RECENTS_ANIMATIONS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_RECENTS_ANIMATIONS;
 
 import android.graphics.GraphicBuffer;
-import android.util.Slog;
 import android.view.Surface;
 import android.view.SurfaceControl;
 import android.view.SurfaceSession;
 
+import com.android.server.protolog.common.ProtoLog;
+
 import java.util.function.Function;
 
 /**
@@ -38,17 +39,16 @@
     private int mWidth;
     private int mHeight;
 
-    TaskScreenshotAnimatable(Function<SurfaceSession, SurfaceControl.Builder> surfaceControlFactory, Task task,
-            SurfaceControl.ScreenshotGraphicBuffer screenshotBuffer) {
+    TaskScreenshotAnimatable(Function<SurfaceSession, SurfaceControl.Builder> surfaceControlFactory,
+            Task task, SurfaceControl.ScreenshotGraphicBuffer screenshotBuffer) {
         GraphicBuffer buffer = screenshotBuffer == null
                 ? null : screenshotBuffer.getGraphicBuffer();
         mTask = task;
         mWidth = (buffer != null) ? buffer.getWidth() : 1;
         mHeight = (buffer != null) ? buffer.getHeight() : 1;
-        if (DEBUG_RECENTS_ANIMATIONS) {
-            Slog.d(TAG, "Creating TaskScreenshotAnimatable: task: " + task
-                    + "width: " + mWidth + "height: " + mHeight);
-        }
+        ProtoLog.d(WM_DEBUG_RECENTS_ANIMATIONS,
+                "Creating TaskScreenshotAnimatable: task: %s width: %d height: %d",
+                        task, mWidth, mHeight);
         mSurfaceControl = surfaceControlFactory.apply(new SurfaceSession())
                 .setName("RecentTaskScreenshotSurface")
                 .setBufferSize(mWidth, mHeight)
@@ -58,6 +58,8 @@
             surface.copyFrom(mSurfaceControl);
             surface.attachAndQueueBufferWithColorSpace(buffer, screenshotBuffer.getColorSpace());
             surface.release();
+            final float scale = 1.0f * mTask.getBounds().width() / mWidth;
+            mSurfaceControl.setMatrix(scale, 0, 0, scale);
         }
         getPendingTransaction().show(mSurfaceControl);
     }
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
index 7456f0d..172ebce 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
@@ -42,7 +42,7 @@
 import static com.android.internal.policy.DecorView.getColorViewLeftInset;
 import static com.android.internal.policy.DecorView.getColorViewTopInset;
 import static com.android.internal.policy.DecorView.getNavigationBarRect;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_STARTING_WINDOW;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
@@ -79,6 +79,7 @@
 import com.android.internal.policy.DecorView;
 import com.android.internal.view.BaseIWindow;
 import com.android.server.policy.WindowManagerPolicy.StartingSurface;
+import com.android.server.protolog.common.ProtoLog;
 
 /**
  * This class represents a starting window that shows a snapshot.
@@ -133,6 +134,7 @@
     private final int mStatusBarColor;
     @VisibleForTesting final SystemBarBackgroundPainter mSystemBarBackgroundPainter;
     private final int mOrientationOnCreation;
+    private final SurfaceControl.Transaction mTransaction;
 
     static TaskSnapshotSurface create(WindowManagerService service, AppWindowToken token,
             TaskSnapshot snapshot) {
@@ -251,6 +253,7 @@
                 windowPrivateFlags, sysUiVis, taskDescription, 1f);
         mStatusBarColor = taskDescription.getStatusBarColor();
         mOrientationOnCreation = currentOrientation;
+        mTransaction = mService.mTransactionFactory.get();
     }
 
     @Override
@@ -259,14 +262,14 @@
             final long now = SystemClock.uptimeMillis();
             if (mSizeMismatch && now - mShownTime < SIZE_MISMATCH_MINIMUM_TIME_MS) {
                 mHandler.postAtTime(this::remove, mShownTime + SIZE_MISMATCH_MINIMUM_TIME_MS);
-                if (DEBUG_STARTING_WINDOW) {
-                    Slog.v(TAG, "Defer removing snapshot surface in "  + (now - mShownTime) + "ms");
-                }
+                ProtoLog.v(WM_DEBUG_STARTING_WINDOW,
+                        "Defer removing snapshot surface in %dms", (now - mShownTime));
+
                 return;
             }
         }
         try {
-            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Removing snapshot surface");
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Removing snapshot surface");
             mSession.remove(mWindow);
         } catch (RemoteException e) {
             // Local call.
@@ -286,8 +289,8 @@
     private void drawSnapshot() {
         mSurface.copyFrom(mSurfaceControl);
 
-        if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Drawing snapshot surface sizeMismatch="
-                + mSizeMismatch);
+        ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Drawing snapshot surface sizeMismatch=%b",
+                mSizeMismatch);
         if (mSizeMismatch) {
             // The dimensions of the buffer and the window don't match, so attaching the buffer
             // will fail. Better create a child window with the exact dimensions and fill the parent
@@ -335,27 +338,23 @@
         surface.copyFrom(mChildSurfaceControl);
 
         final Rect frame;
-        SurfaceControl.openTransaction();
-        try {
-            // We can just show the surface here as it will still be hidden as the parent is
-            // still hidden.
-            mChildSurfaceControl.show();
-            if (aspectRatioMismatch) {
-                // Clip off ugly navigation bar.
-                final Rect crop = calculateSnapshotCrop();
-                frame = calculateSnapshotFrame(crop);
-                mChildSurfaceControl.setWindowCrop(crop);
-                mChildSurfaceControl.setPosition(frame.left, frame.top);
-            } else {
-                frame = null;
-            }
-
-            // Scale the mismatch dimensions to fill the task bounds
-            final float scale = 1 / mSnapshot.getScale();
-            mChildSurfaceControl.setMatrix(scale, 0, 0, scale);
-        } finally {
-            SurfaceControl.closeTransaction();
+        // We can just show the surface here as it will still be hidden as the parent is
+        // still hidden.
+        mTransaction.show(mChildSurfaceControl);
+        if (aspectRatioMismatch) {
+            // Clip off ugly navigation bar.
+            final Rect crop = calculateSnapshotCrop();
+            frame = calculateSnapshotFrame(crop);
+            mTransaction.setWindowCrop(mChildSurfaceControl, crop);
+            mTransaction.setPosition(mChildSurfaceControl, frame.left, frame.top);
+        } else {
+            frame = null;
         }
+
+        // Scale the mismatch dimensions to fill the task bounds
+        final float scale = 1 / mSnapshot.getScale();
+        mTransaction.setMatrix(mChildSurfaceControl, scale, 0, 0, scale);
+        mTransaction.apply();
         surface.attachAndQueueBufferWithColorSpace(buffer, mSnapshot.getColorSpace());
         surface.release();
 
diff --git a/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java b/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java
index 895350b..513008d 100644
--- a/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java
+++ b/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java
@@ -16,17 +16,17 @@
 package com.android.server.wm;
 
 import static com.android.server.wm.AnimationAdapterProto.REMOTE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_REMOTE_ANIMATIONS;
 import static com.android.server.wm.RemoteAnimationAdapterWrapperProto.TARGET;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RECENTS_ANIMATIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_REMOTE_ANIMATIONS;
 
 import android.graphics.Point;
 import android.os.SystemClock;
-import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
 import android.view.RemoteAnimationTarget;
 import android.view.SurfaceControl;
 
+import com.android.server.protolog.common.ProtoLog;
+
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.function.Consumer;
@@ -68,15 +68,11 @@
         final ArrayList<RemoteAnimationTarget> targets = new ArrayList<>();
         service.mRoot.forAllWallpaperWindows(wallpaperWindow -> {
             if (!wallpaperWindow.getDisplayContent().mWallpaperController.isWallpaperVisible()) {
-                if (DEBUG_REMOTE_ANIMATIONS || DEBUG_RECENTS_ANIMATIONS) {
-                    Slog.d(TAG, "\tNot visible=" + wallpaperWindow);
-                }
+                ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "\tNot visible=%s", wallpaperWindow);
                 return;
             }
 
-            if (DEBUG_REMOTE_ANIMATIONS || DEBUG_RECENTS_ANIMATIONS) {
-                Slog.d(TAG, "\tvisible=" + wallpaperWindow);
-            }
+            ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "\tvisible=%s", wallpaperWindow);
             final WallpaperAnimationAdapter wallpaperAdapter = new WallpaperAnimationAdapter(
                     wallpaperWindow, durationHint, statusBarTransitionDelay,
                     animationCanceledRunnable);
@@ -129,7 +125,7 @@
     @Override
     public void startAnimation(SurfaceControl animationLeash, SurfaceControl.Transaction t,
             SurfaceAnimator.OnAnimationFinishedCallback finishCallback) {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "startAnimation");
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "startAnimation");
 
         // Restore z-layering until client has a chance to modify it.
         t.setLayer(animationLeash, mWallpaperToken.getPrefixOrderIndex());
@@ -139,7 +135,7 @@
 
     @Override
     public void onAnimationCancelled(SurfaceControl animationLeash) {
-        if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "onAnimationCancelled");
+        ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "onAnimationCancelled");
         mAnimationCanceledRunnable.accept(this);
     }
 
diff --git a/services/core/java/com/android/server/wm/WallpaperController.java b/services/core/java/com/android/server/wm/WallpaperController.java
index 13902ee..e7b09db 100644
--- a/services/core/java/com/android/server/wm/WallpaperController.java
+++ b/services/core/java/com/android/server/wm/WallpaperController.java
@@ -24,7 +24,6 @@
 import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_WITH_WALLPAPER;
 
 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREENSHOT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
@@ -607,8 +606,9 @@
     boolean processWallpaperDrawPendingTimeout() {
         if (mWallpaperDrawState == WALLPAPER_DRAW_PENDING) {
             mWallpaperDrawState = WALLPAPER_DRAW_TIMEOUT;
-            if (DEBUG_APP_TRANSITIONS || DEBUG_WALLPAPER) Slog.v(TAG,
-                    "*** WALLPAPER DRAW TIMEOUT");
+            if (DEBUG_WALLPAPER) {
+                Slog.v(TAG, "*** WALLPAPER DRAW TIMEOUT");
+            }
 
             // If there was a pending recents animation, start the animation anyways (it's better
             // to not see the wallpaper than for the animation to not start)
@@ -641,9 +641,11 @@
                                 WALLPAPER_DRAW_PENDING_TIMEOUT_DURATION);
 
                 }
-                if (DEBUG_APP_TRANSITIONS || DEBUG_WALLPAPER) Slog.v(TAG,
-                        "Wallpaper should be visible but has not been drawn yet. " +
-                                "mWallpaperDrawState=" + mWallpaperDrawState);
+                if (DEBUG_WALLPAPER) {
+                    Slog.v(TAG,
+                            "Wallpaper should be visible but has not been drawn yet. "
+                                    + "mWallpaperDrawState=" + mWallpaperDrawState);
+                }
                 break;
             }
         }
diff --git a/services/core/java/com/android/server/wm/Watermark.java b/services/core/java/com/android/server/wm/Watermark.java
index 729cfc0..725aaa48 100644
--- a/services/core/java/com/android/server/wm/Watermark.java
+++ b/services/core/java/com/android/server/wm/Watermark.java
@@ -55,7 +55,7 @@
     private boolean mDrawNeeded;
 
     Watermark(Supplier<Surface> surfaceFactory, DisplayContent dc, DisplayMetrics dm,
-            String[] tokens) {
+            String[] tokens, SurfaceControl.Transaction t) {
         if (false) {
             Log.i(TAG_WM, "*********************** WATERMARK");
             for (int i=0; i<tokens.length; i++) {
@@ -121,21 +121,21 @@
                     .setBufferSize(1, 1)
                     .setFormat(PixelFormat.TRANSLUCENT)
                     .build();
-            ctrl.setLayerStack(mDisplay.getLayerStack());
-            ctrl.setLayer(WindowManagerService.TYPE_LAYER_MULTIPLIER*100);
-            ctrl.setPosition(0, 0);
-            ctrl.show();
+            t.setLayerStack(ctrl, mDisplay.getLayerStack())
+                    .setLayer(ctrl, WindowManagerService.TYPE_LAYER_MULTIPLIER * 100)
+                    .setPosition(ctrl, 0, 0)
+                    .show(ctrl);
             mSurface.copyFrom(ctrl);
         } catch (OutOfResourcesException e) {
         }
         mSurfaceControl = ctrl;
     }
 
-    void positionSurface(int dw, int dh) {
+    void positionSurface(int dw, int dh, SurfaceControl.Transaction t) {
         if (mLastDW != dw || mLastDH != dh) {
             mLastDW = dw;
             mLastDH = dh;
-            mSurfaceControl.setBufferSize(dw, dh);
+            t.setBufferSize(mSurfaceControl, dw, dh);
             mDrawNeeded = true;
         }
     }
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index c7916e8..3a1d6e0 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -16,12 +16,11 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 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.WindowSurfacePlacer.SET_ORIENTATION_CHANGE_COMPLETE;
-import static com.android.server.wm.WindowSurfacePlacer.SET_UPDATE_ROTATION;
 
 import android.content.Context;
 import android.os.Trace;
@@ -33,6 +32,7 @@
 
 import com.android.server.AnimationThread;
 import com.android.server.policy.WindowManagerPolicy;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -108,14 +108,6 @@
     }
 
     void removeDisplayLocked(final int displayId) {
-        final DisplayContentsAnimator displayAnimator = mDisplayContentsAnimators.get(displayId);
-        if (displayAnimator != null) {
-            if (displayAnimator.mScreenRotationAnimation != null) {
-                displayAnimator.mScreenRotationAnimation.kill();
-                displayAnimator.mScreenRotationAnimation = null;
-            }
-        }
-
         mDisplayContentsAnimators.delete(displayId);
     }
 
@@ -147,7 +139,7 @@
                 Slog.i(TAG, "!!! animate: entry time=" + mCurrentTime);
             }
 
-            if (SHOW_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION animate");
+            ProtoLog.i(WM_SHOW_TRANSACTIONS, ">>> OPEN TRANSACTION animate");
             mService.openSurfaceTransaction();
             try {
                 final AccessibilityController accessibilityController =
@@ -156,27 +148,6 @@
                 for (int i = 0; i < numDisplays; i++) {
                     final int displayId = mDisplayContentsAnimators.keyAt(i);
                     final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
-                    DisplayContentsAnimator displayAnimator = mDisplayContentsAnimators.valueAt(i);
-
-                    final ScreenRotationAnimation screenRotationAnimation =
-                            displayAnimator.mScreenRotationAnimation;
-                    if (screenRotationAnimation != null && screenRotationAnimation.isAnimating()) {
-                        if (screenRotationAnimation.stepAnimationLocked(mCurrentTime)) {
-                            setAnimating(true);
-                        } else {
-                            mBulkUpdateParams |= SET_UPDATE_ROTATION;
-                            screenRotationAnimation.kill();
-                            displayAnimator.mScreenRotationAnimation = null;
-
-                            // display.
-                            if (accessibilityController != null) {
-                                // We just finished rotation animation which means we did not
-                                // announce the rotation and waited for it to end, announce now.
-                                accessibilityController.onRotationChangedLocked(dc);
-                            }
-                        }
-                    }
-
                     // Update animations of all applications, including those
                     // associated with exiting/removed apps
                     dc.updateWindowsForAnimator();
@@ -188,15 +159,10 @@
                     final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
 
                     dc.checkAppWindowsReadyToShow();
-
-                    final ScreenRotationAnimation screenRotationAnimation =
-                            mDisplayContentsAnimators.valueAt(i).mScreenRotationAnimation;
-                    if (screenRotationAnimation != null) {
-                        screenRotationAnimation.updateSurfaces(mTransaction);
-                    }
                     orAnimating(dc.getDockedDividerController().animate(mCurrentTime));
                     if (accessibilityController != null) {
-                        accessibilityController.drawMagnifiedRegionBorderIfNeededLocked(displayId);
+                        accessibilityController.drawMagnifiedRegionBorderIfNeededLocked(displayId,
+                                mTransaction);
                     }
                 }
 
@@ -213,7 +179,7 @@
                 Slog.wtf(TAG, "Unhandled exception in Window Manager", e);
             } finally {
                 mService.closeSurfaceTransaction("WindowAnimator");
-                if (SHOW_TRANSACTIONS) Slog.i(TAG, "<<< CLOSE TRANSACTION animate");
+                ProtoLog.i(WM_SHOW_TRANSACTIONS, "<<< CLOSE TRANSACTION animate");
             }
 
             boolean hasPendingLayoutChanges = mService.mRoot.hasPendingLayoutChanges(this);
@@ -273,22 +239,14 @@
 
     public void dumpLocked(PrintWriter pw, String prefix, boolean dumpAll) {
         final String subPrefix = "  " + prefix;
-        final String subSubPrefix = "  " + subPrefix;
 
         for (int i = 0; i < mDisplayContentsAnimators.size(); i++) {
             pw.print(prefix); pw.print("DisplayContentsAnimator #");
                     pw.print(mDisplayContentsAnimators.keyAt(i));
                     pw.println(":");
-            final DisplayContentsAnimator displayAnimator = mDisplayContentsAnimators.valueAt(i);
             final DisplayContent dc =
                     mService.mRoot.getDisplayContent(mDisplayContentsAnimators.keyAt(i));
             dc.dumpWindowAnimators(pw, subPrefix);
-            if (displayAnimator.mScreenRotationAnimation != null) {
-                pw.print(subPrefix); pw.println("mScreenRotationAnimation:");
-                displayAnimator.mScreenRotationAnimation.printTo(subSubPrefix, pw);
-            } else if (dumpAll) {
-                pw.print(subPrefix); pw.println("no ScreenRotationAnimation ");
-            }
             pw.println();
         }
 
@@ -322,23 +280,6 @@
         return displayAnimator;
     }
 
-    void setScreenRotationAnimationLocked(int displayId, ScreenRotationAnimation animation) {
-        final DisplayContentsAnimator animator = getDisplayContentsAnimatorLocked(displayId);
-
-        if (animator != null) {
-            animator.mScreenRotationAnimation = animation;
-        }
-    }
-
-    ScreenRotationAnimation getScreenRotationAnimationLocked(int displayId) {
-        if (displayId < 0) {
-            return null;
-        }
-
-        DisplayContentsAnimator animator = getDisplayContentsAnimatorLocked(displayId);
-        return animator != null? animator.mScreenRotationAnimation : null;
-    }
-
     void requestRemovalOfReplacedWindows(WindowState win) {
         mRemoveReplacedWindows = true;
     }
@@ -358,7 +299,6 @@
     }
 
     private class DisplayContentsAnimator {
-        ScreenRotationAnimation mScreenRotationAnimation = null;
     }
 
     boolean isAnimating() {
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 586375f..a4ab66a 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -19,6 +19,11 @@
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_BEHIND;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
+import static android.content.pm.ActivityInfo.isFixedOrientationLandscape;
+import static android.content.pm.ActivityInfo.isFixedOrientationPortrait;
+import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
+import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
+import static android.content.res.Configuration.ORIENTATION_UNDEFINED;
 import static android.view.SurfaceControl.Transaction;
 
 import static com.android.server.wm.WindowContainerProto.CONFIGURATION_CONTAINER;
@@ -28,14 +33,17 @@
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
 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.WindowStateAnimator.DRAW_PENDING;
 
 import android.annotation.CallSuper;
 import android.annotation.IntDef;
 import android.annotation.Nullable;
 import android.app.WindowConfiguration;
+import android.content.pm.ActivityInfo;
 import android.content.res.Configuration;
 import android.graphics.Point;
 import android.graphics.Rect;
+import android.os.Debug;
 import android.os.IBinder;
 import android.util.Pools;
 import android.util.Slog;
@@ -47,9 +55,11 @@
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.ToBooleanFunction;
+import com.android.server.policy.WindowManagerPolicy;
 import com.android.server.wm.SurfaceAnimator.Animatable;
 
 import java.io.PrintWriter;
+import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.LinkedList;
 import java.util.function.Consumer;
@@ -106,9 +116,6 @@
     private final Pools.SynchronizedPool<ForAllWindowsConsumerWrapper> mConsumerWrapperPool =
             new Pools.SynchronizedPool<>(3);
 
-    // The owner/creator for this container. No controller if null.
-    WindowContainerController mController;
-
     // The display this window container is on.
     protected DisplayContent mDisplayContent;
 
@@ -120,6 +127,11 @@
     private final Transaction mPendingTransaction;
 
     /**
+     * Windows that clients are waiting to have drawn.
+     */
+    final ArrayList<WindowState> mWaitingForDrawn = new ArrayList<>();
+
+    /**
      * Applied as part of the animation pass in "prepareSurfaces".
      */
     protected final SurfaceAnimator mSurfaceAnimator;
@@ -137,6 +149,16 @@
      */
     private boolean mCommittedReparentToAnimationLeash;
 
+    private final Configuration mTmpConfig = new Configuration();
+
+    /**
+     * Callback which is triggered while changing the parent, after setting up the surface but
+     * before asking the parent to assign child layers.
+     */
+    interface PreAssignChildLayersCallback {
+        void onPreAssignChildLayers();
+    }
+
     WindowContainer(WindowManagerService wms) {
         mWmService = wms;
         mPendingTransaction = wms.mTransactionFactory.get();
@@ -176,6 +198,10 @@
      */
     @Override
     void onParentChanged() {
+        onParentChanged(null);
+    }
+
+    void onParentChanged(PreAssignChildLayersCallback callback) {
         super.onParentChanged();
         if (mParent == null) {
             return;
@@ -195,6 +221,10 @@
             reparentSurfaceControl(getPendingTransaction(), mParent.mSurfaceControl);
         }
 
+        if (callback != null) {
+            callback.onPreAssignChildLayers();
+        }
+
         // Either way we need to ask the parent to assign us a Z-order.
         mParent.assignChildLayers();
         scheduleAnimation();
@@ -247,7 +277,8 @@
         if (child.getParent() != null) {
             throw new IllegalArgumentException("addChild: container=" + child.getName()
                     + " is already a child of container=" + child.getParent().getName()
-                    + " can't add to container=" + getName());
+                    + " can't add to container=" + getName()
+                    + "\n callers=" + Debug.getCallers(15, "\n"));
         }
 
         if ((index < 0 && index != POSITION_BOTTOM)
@@ -340,11 +371,6 @@
         if (mParent != null) {
             mParent.removeChild(this);
         }
-
-        if (mController != null) {
-            setController(null);
-        }
-
     }
 
     /**
@@ -743,6 +769,31 @@
     }
 
     /**
+     * Get the configuration orientation by the requested screen orientation
+     * ({@link ActivityInfo.ScreenOrientation}) of this activity.
+     *
+     * @return orientation in ({@link Configuration#ORIENTATION_LANDSCAPE},
+     *         {@link Configuration#ORIENTATION_PORTRAIT},
+     *         {@link Configuration#ORIENTATION_UNDEFINED}).
+     */
+    int getRequestedConfigurationOrientation() {
+        if (mOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
+            // NOSENSOR means the display's "natural" orientation, so return that.
+            if (mDisplayContent != null) {
+                return mDisplayContent.getNaturalOrientation();
+            }
+        } else if (mOrientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
+            // LOCKED means the activity's orientation remains unchanged, so return existing value.
+            return getConfiguration().orientation;
+        } else if (isFixedOrientationLandscape(mOrientation)) {
+            return ORIENTATION_LANDSCAPE;
+        } else if (isFixedOrientationPortrait(mOrientation)) {
+            return ORIENTATION_PORTRAIT;
+        }
+        return ORIENTATION_UNDEFINED;
+    }
+
+    /**
      * Calls {@link #setOrientation(int, IBinder, ActivityRecord)} with {@code null} to the last 2
      * parameters.
      *
@@ -772,6 +823,13 @@
         }
 
         mOrientation = orientation;
+        final int configOrientation = getRequestedConfigurationOrientation();
+        if (getRequestedOverrideConfiguration().orientation != configOrientation) {
+            mTmpConfig.setTo(getRequestedOverrideConfiguration());
+            mTmpConfig.orientation = configOrientation;
+            onRequestedOverrideConfigurationChanged(mTmpConfig);
+        }
+
         final WindowContainer parent = getParent();
         if (parent != null) {
             onDescendantOrientationChanged(freezeDisplayToken, requestingContainer);
@@ -989,23 +1047,6 @@
         } while (current != null);
     }
 
-    WindowContainerController getController() {
-        return mController;
-    }
-
-    void setController(WindowContainerController controller) {
-        if (mController != null && controller != null) {
-            throw new IllegalArgumentException("Can't set controller=" + mController
-                    + " for container=" + this + " Already set to=" + mController);
-        }
-        if (controller != null) {
-            controller.setContainer(this);
-        } else if (mController != null) {
-            mController.setContainer(null);
-        }
-        mController = controller;
-    }
-
     SurfaceControl.Builder makeSurface() {
         final WindowContainer p = getParent();
         return p.makeChildSurface(this);
@@ -1401,6 +1442,19 @@
         }
     }
 
+    void waitForAllWindowsDrawn() {
+        final WindowManagerPolicy policy = mWmService.mPolicy;
+        forAllWindows(w -> {
+            final boolean keyguard = policy.isKeyguardHostWindow(w.mAttrs);
+            if (w.isVisibleLw() && (w.mAppToken != null || keyguard)) {
+                w.mWinAnimator.mDrawState = DRAW_PENDING;
+                // Force add to mResizingWindows.
+                w.resetLastContentInsets();
+                mWaitingForDrawn.add(w);
+            }
+        }, true /* traverseTopToBottom */);
+    }
+
     Dimmer getDimmer() {
         if (mParent == null) {
             return null;
diff --git a/services/core/java/com/android/server/wm/WindowContainerController.java b/services/core/java/com/android/server/wm/WindowContainerController.java
deleted file mode 100644
index 17bc0e2..0000000
--- a/services/core/java/com/android/server/wm/WindowContainerController.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2016 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.content.res.Configuration;
-
-/**
- * Class that allows the owner/creator of a {@link WindowContainer} to communicate directly with the
- * container and make changes.
- * Note that public calls (mostly in sub-classes) into this class are assumed to be originating from
- * outside the window manager so the window manager lock is held and appropriate permissions are
- * checked before calls are allowed to proceed.
- *
- * Test class: {@link WindowContainerControllerTests}
- */
-class WindowContainerController<E extends WindowContainer, I extends WindowContainerListener>
-        implements ConfigurationContainerListener {
-
-    final WindowManagerService mService;
-    final RootWindowContainer mRoot;
-    final WindowManagerGlobalLock mGlobalLock;
-
-    // The window container this controller owns.
-    E mContainer;
-    // Interface for communicating changes back to the owner.
-    final I mListener;
-
-    WindowContainerController(I listener, WindowManagerService service) {
-        mListener = listener;
-        mService = service;
-        mRoot = mService != null ? mService.mRoot : null;
-        mGlobalLock = mService != null ? mService.mGlobalLock : null;
-    }
-
-    void setContainer(E container) {
-        if (mContainer != null && container != null) {
-            throw new IllegalArgumentException("Can't set container=" + container
-                    + " for controller=" + this + " Already set to=" + mContainer);
-        }
-        mContainer = container;
-        if (mContainer != null && mListener != null) {
-            mListener.registerConfigurationChangeListener(this);
-        }
-    }
-
-    void removeContainer() {
-        // TODO: See if most uses cases should support removeIfPossible here.
-        //mContainer.removeIfPossible();
-        if (mContainer == null) {
-            return;
-        }
-
-        mContainer.setController(null);
-        mContainer = null;
-        if (mListener != null) {
-            mListener.unregisterConfigurationChangeListener(this);
-        }
-    }
-
-    @Override
-    public void onRequestedOverrideConfigurationChanged(Configuration overrideConfiguration) {
-        synchronized (mGlobalLock) {
-            if (mContainer == null) {
-                return;
-            }
-            mContainer.onRequestedOverrideConfigurationChanged(overrideConfiguration);
-        }
-    }
-}
diff --git a/services/core/java/com/android/server/wm/WindowContainerListener.java b/services/core/java/com/android/server/wm/WindowContainerListener.java
deleted file mode 100644
index 3d3d2e0..0000000
--- a/services/core/java/com/android/server/wm/WindowContainerListener.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2016 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.content.res.Configuration;
-
-/**
- * Interface used by the owner/creator of the container to listen to changes with the container.
- * @see WindowContainerController
- */
-public interface WindowContainerListener {
-    void registerConfigurationChangeListener(ConfigurationContainerListener listener);
-    void unregisterConfigurationChangeListener(ConfigurationContainerListener listener);
-    default void onInitializeOverrideConfiguration(Configuration config) {}
-}
diff --git a/services/core/java/com/android/server/wm/WindowManagerDebugConfig.java b/services/core/java/com/android/server/wm/WindowManagerDebugConfig.java
index c366e4d..93b0fd9 100644
--- a/services/core/java/com/android/server/wm/WindowManagerDebugConfig.java
+++ b/services/core/java/com/android/server/wm/WindowManagerDebugConfig.java
@@ -33,32 +33,19 @@
     // Default log tag for the window manager package.
     static final String TAG_WM = "WindowManager";
 
-    static final boolean DEBUG_RESIZE = false;
     static final boolean DEBUG = false;
-    static final boolean DEBUG_ADD_REMOVE = false;
-    static final boolean DEBUG_FOCUS = false;
-    static final boolean DEBUG_FOCUS_LIGHT = DEBUG_FOCUS || false;
     static final boolean DEBUG_ANIM = false;
-    static final boolean DEBUG_KEYGUARD = false;
     static final boolean DEBUG_LAYOUT = false;
     static final boolean DEBUG_LAYERS = false;
     static final boolean DEBUG_INPUT = false;
     static final boolean DEBUG_INPUT_METHOD = false;
     static final boolean DEBUG_VISIBILITY = false;
-    static final boolean DEBUG_WINDOW_MOVEMENT = false;
-    static final boolean DEBUG_TOKEN_MOVEMENT = false;
-    static final boolean DEBUG_ORIENTATION = false;
-    static final boolean DEBUG_APP_ORIENTATION = false;
     static final boolean DEBUG_CONFIGURATION = false;
-    static final boolean DEBUG_APP_TRANSITIONS = false;
     static final boolean DEBUG_STARTING_WINDOW_VERBOSE = false;
-    static final boolean DEBUG_STARTING_WINDOW = DEBUG_STARTING_WINDOW_VERBOSE || false;
     static final boolean DEBUG_WALLPAPER = false;
     static final boolean DEBUG_WALLPAPER_LIGHT = false || DEBUG_WALLPAPER;
     static final boolean DEBUG_DRAG = false;
-    static final boolean DEBUG_SCREEN_ON = false;
     static final boolean DEBUG_SCREENSHOT = false;
-    static final boolean DEBUG_BOOT = false;
     static final boolean DEBUG_LAYOUT_REPEATS = false;
     static final boolean DEBUG_WINDOW_TRACE = false;
     static final boolean DEBUG_TASK_MOVEMENT = false;
@@ -66,17 +53,9 @@
     static final boolean DEBUG_STACK = false;
     static final boolean DEBUG_DISPLAY = false;
     static final boolean DEBUG_POWER = false;
-    static final boolean DEBUG_DIM_LAYER = false;
-    static final boolean SHOW_SURFACE_ALLOC = false;
-    static final boolean SHOW_TRANSACTIONS = false;
-    static final boolean SHOW_VERBOSE_TRANSACTIONS = false && SHOW_TRANSACTIONS;
-    static final boolean SHOW_LIGHT_TRANSACTIONS = false || SHOW_TRANSACTIONS;
+    static final boolean SHOW_VERBOSE_TRANSACTIONS = false;
+    static final boolean SHOW_LIGHT_TRANSACTIONS = false;
     static final boolean SHOW_STACK_CRAWLS = false;
     static final boolean DEBUG_WINDOW_CROP = false;
     static final boolean DEBUG_UNKNOWN_APP_VISIBILITY = false;
-    static final boolean DEBUG_RECENTS_ANIMATIONS = false;
-    static final boolean DEBUG_REMOTE_ANIMATIONS = DEBUG_APP_TRANSITIONS || false;
-
-    static final String TAG_KEEP_SCREEN_ON = "DebugKeepScreenOn";
-    static final boolean DEBUG_KEEP_SCREEN_ON = false;
 }
diff --git a/services/core/java/com/android/server/wm/WindowManagerInternal.java b/services/core/java/com/android/server/wm/WindowManagerInternal.java
index 750926f..f4b7672 100644
--- a/services/core/java/com/android/server/wm/WindowManagerInternal.java
+++ b/services/core/java/com/android/server/wm/WindowManagerInternal.java
@@ -30,6 +30,7 @@
 import android.view.MagnificationSpec;
 import android.view.WindowInfo;
 
+import com.android.internal.policy.KeyInterceptionInfo;
 import com.android.server.input.InputManagerService;
 import com.android.server.policy.WindowManagerPolicy;
 
@@ -160,9 +161,8 @@
         default boolean registerInputChannel(
                 DragState state, Display display, InputManagerService service,
                 InputChannel source) {
-            state.mTransferTouchFromToken = source.getToken();
             state.register(display);
-            return true;
+            return service.transferTouchFocus(source, state.getInputChannel());
         }
 
         /**
@@ -313,10 +313,15 @@
     public abstract void showGlobalActions();
 
     /**
-     * Invalidate all visible windows. Then report back on the callback once all windows have
-     * redrawn.
+     * Invalidate all visible windows on a given display, and report back on the callback when all
+     * windows have redrawn.
+     *
+     * @param callback reporting callback to be called when all windows have redrawn.
+     * @param timeout calls the callback anyway after the timeout.
+     * @param displayId waits for the windows on the given display, INVALID_DISPLAY to wait for all
+     *                  windows on all displays.
      */
-    public abstract void waitForAllWindowsDrawn(Runnable callback, long timeout);
+    public abstract void waitForAllWindowsDrawn(Runnable callback, long timeout, int displayId);
 
     /**
      * Overrides the display size.
@@ -502,6 +507,13 @@
     public abstract boolean shouldShowIme(int displayId);
 
     /**
+     * Show IME on imeTargetWindow once IME has finished layout.
+     *
+     * @param imeTargetWindowToken token of the (IME target) window on which IME should be shown.
+     */
+    public abstract void showImePostLayout(IBinder imeTargetWindowToken);
+
+    /**
      * Tell window manager about a package that should not be running with high refresh rate
      * setting until removeNonHighRefreshRatePackage is called for the same package.
      *
@@ -519,4 +531,10 @@
      */
     public abstract boolean isTouchableDisplay(int displayId);
 
+    /**
+     * Returns the info associated with the input token used to determine if a key should be
+     * intercepted. This info can be accessed without holding the global wm lock.
+     */
+    public abstract @Nullable KeyInterceptionInfo
+            getKeyInterceptionInfoFromToken(IBinder inputToken);
 }
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 14214b4..6f9f2c0 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -16,6 +16,7 @@
 
 package com.android.server.wm;
 
+import static android.Manifest.permission.ACCESS_SURFACE_FLINGER;
 import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
 import static android.Manifest.permission.MANAGE_APP_TOKENS;
@@ -81,27 +82,27 @@
 import static com.android.server.LockGuard.installLock;
 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
 import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_BOOT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_KEEP_SCREEN_ON;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_SCREEN_ON;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_STARTING_WINDOW;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_WINDOW_MOVEMENT;
+import static com.android.server.wm.ProtoLogGroup.WM_ERROR;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_BOOT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DISPLAY;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_INPUT_METHOD;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_KEEP_SCREEN_ON;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREENSHOT;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_SCREEN_ON;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_MOVEMENT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_STACK_CRAWLS;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_VERBOSE_TRANSACTIONS;
-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.WindowManagerServiceDumpProto.DISPLAY_FROZEN;
@@ -248,6 +249,7 @@
 import com.android.internal.os.IResultReceiver;
 import com.android.internal.policy.IKeyguardDismissCallback;
 import com.android.internal.policy.IShortcutService;
+import com.android.internal.policy.KeyInterceptionInfo;
 import com.android.internal.util.DumpUtils;
 import com.android.internal.util.FastPrintWriter;
 import com.android.internal.util.LatencyTracker;
@@ -265,6 +267,8 @@
 import com.android.server.policy.WindowManagerPolicy;
 import com.android.server.policy.WindowManagerPolicy.ScreenOffListener;
 import com.android.server.power.ShutdownThread;
+import com.android.server.protolog.ProtoLogImpl;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.utils.PriorityDump;
 
 import java.io.BufferedWriter;
@@ -284,8 +288,11 @@
 import java.text.DateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.function.Function;
 import java.util.function.Supplier;
 
@@ -407,6 +414,14 @@
     int mVr2dDisplayId = INVALID_DISPLAY;
     boolean mVrModeEnabled = false;
 
+    /**
+     * Tracks a map of input tokens to info that is used to decide whether to intercept
+     * a key event.
+     */
+    final Map<IBinder, KeyInterceptionInfo> mKeyInterceptionInfoForToken =
+            Collections.synchronizedMap(new ArrayMap<>());
+
+
     private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
         @Override
         public void onVrStateChanged(boolean enabled) {
@@ -554,13 +569,10 @@
     final ArrayList<WindowState> mForceRemoves = new ArrayList<>();
 
     /**
-     * Windows that clients are waiting to have drawn.
+     * The callbacks to make when the windows all have been drawn for a given
+     * {@link WindowContainer}.
      */
-    ArrayList<WindowState> mWaitingForDrawn = new ArrayList<>();
-    /**
-     * And the callback to make when they've all been drawn.
-     */
-    Runnable mWaitingForDrawnCallback;
+    final HashMap<WindowContainer, Runnable> mWaitingForDrawnCallbacks = new HashMap<>();
 
     /** List of window currently causing non-system overlay windows to be hidden. */
     private ArrayList<WindowState> mHidingNonSystemOverlayWindows = new ArrayList<>();
@@ -961,6 +973,7 @@
             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
         }
     }
+
     /** Listener to notify activity manager about app transitions. */
     final WindowManagerInternal.AppTransitionListener mActivityManagerAppTransitionNotifier
             = new WindowManagerInternal.AppTransitionListener() {
@@ -977,7 +990,13 @@
             if (atoken == null) {
                 return;
             }
-            if (atoken.mLaunchTaskBehind) {
+
+            // While running a recents animation, this will get called early because we show the
+            // recents animation target activity immediately when the animation starts. Defer the
+            // mLaunchTaskBehind updates until recents animation finishes.
+            final boolean isRecentsAnimationTarget = getRecentsAnimationController() != null
+                    && getRecentsAnimationController().isTargetApp(atoken);
+            if (atoken.mLaunchTaskBehind && !isRecentsAnimationTarget) {
                 try {
                     mActivityTaskManager.notifyLaunchTaskBehindComplete(atoken.token);
                 } catch (RemoteException e) {
@@ -985,20 +1004,13 @@
                 atoken.mLaunchTaskBehind = false;
             } else {
                 atoken.updateReportedVisibilityLocked();
-                if (atoken.mEnteringAnimation) {
-                    if (getRecentsAnimationController() != null
-                            && getRecentsAnimationController().isTargetApp(atoken)) {
-                        // Currently running a recents animation, this will get called early because
-                        // we show the recents animation target activity immediately when the
-                        // animation starts. In this case, we should defer sending the finished
-                        // callback until the animation successfully finishes
-                        return;
-                    } else {
-                        atoken.mEnteringAnimation = false;
-                        try {
-                            mActivityTaskManager.notifyEnterAnimationComplete(atoken.token);
-                        } catch (RemoteException e) {
-                        }
+                // We should also defer sending the finished callback until the recents animation
+                // successfully finishes.
+                if (atoken.mEnteringAnimation && !isRecentsAnimationTarget) {
+                    atoken.mEnteringAnimation = false;
+                    try {
+                        mActivityTaskManager.notifyEnterAnimationComplete(atoken.token);
+                    } catch (RemoteException e) {
                     }
                 }
             }
@@ -1257,14 +1269,7 @@
 
         // Add ourself to the Watchdog monitors.
         Watchdog.getInstance().addMonitor(this);
-
-        openSurfaceTransaction();
-        try {
-            createWatermarkInTransaction();
-        } finally {
-            closeSurfaceTransaction("createWatermarkInTransaction");
-        }
-
+        createWatermark();
         showEmulatorDisplayOverlayIfNeeded();
     }
 
@@ -1281,7 +1286,7 @@
             // The window manager only throws security exceptions, so let's
             // log all others.
             if (!(e instanceof SecurityException)) {
-                Slog.wtf(TAG_WM, "Window Manager Crash", e);
+                ProtoLog.wtf(WM_ERROR, "Window Manager Crash %s", e);
             }
             throw e;
         }
@@ -1321,38 +1326,41 @@
             final DisplayContent displayContent = getDisplayContentOrCreate(displayId, attrs.token);
 
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to add window to a display that does not exist: "
-                        + displayId + ".  Aborting.");
+                ProtoLog.w(WM_ERROR, "Attempted to add window to a display that does "
+                        + "not exist: %d. Aborting.", displayId);
                 return WindowManagerGlobal.ADD_INVALID_DISPLAY;
             }
             if (!displayContent.hasAccess(session.mUid)) {
-                Slog.w(TAG_WM, "Attempted to add window to a display for which the application "
-                        + "does not have access: " + displayId + ".  Aborting.");
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to add window to a display for which the application "
+                                + "does not have access: %d.  Aborting.", displayId);
                 return WindowManagerGlobal.ADD_INVALID_DISPLAY;
             }
 
             if (mWindowMap.containsKey(client.asBinder())) {
-                Slog.w(TAG_WM, "Window " + client + " is already added");
+                ProtoLog.w(WM_ERROR, "Window %s is already added", client);
                 return WindowManagerGlobal.ADD_DUPLICATE_ADD;
             }
 
             if (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW) {
                 parentWindow = windowForClientLocked(null, attrs.token, false);
                 if (parentWindow == null) {
-                    Slog.w(TAG_WM, "Attempted to add window with token that is not a window: "
-                          + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add window with token that is not a window: "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN;
                 }
                 if (parentWindow.mAttrs.type >= FIRST_SUB_WINDOW
                         && parentWindow.mAttrs.type <= LAST_SUB_WINDOW) {
-                    Slog.w(TAG_WM, "Attempted to add window with token that is a sub-window: "
-                            + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add window with token that is a sub-window: "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN;
                 }
             }
 
             if (type == TYPE_PRIVATE_PRESENTATION && !displayContent.isPrivate()) {
-                Slog.w(TAG_WM, "Attempted to add private presentation window to a non-private display.  Aborting.");
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to add private presentation window to a non-private display.  "
+                                + "Aborting.");
                 return WindowManagerGlobal.ADD_PERMISSION_DENIED;
             }
 
@@ -1370,46 +1378,48 @@
 
             if (token == null) {
                 if (rootType >= FIRST_APPLICATION_WINDOW && rootType <= LAST_APPLICATION_WINDOW) {
-                    Slog.w(TAG_WM, "Attempted to add application window with unknown token "
-                          + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add application window with unknown token "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (rootType == TYPE_INPUT_METHOD) {
-                    Slog.w(TAG_WM, "Attempted to add input method window with unknown token "
-                          + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add input method window with unknown token "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (rootType == TYPE_VOICE_INTERACTION) {
-                    Slog.w(TAG_WM, "Attempted to add voice interaction window with unknown token "
-                          + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR,
+                            "Attempted to add voice interaction window with unknown token "
+                                    + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (rootType == TYPE_WALLPAPER) {
-                    Slog.w(TAG_WM, "Attempted to add wallpaper window with unknown token "
-                          + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add wallpaper window with unknown token "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (rootType == TYPE_DREAM) {
-                    Slog.w(TAG_WM, "Attempted to add Dream window with unknown token "
-                          + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add Dream window with unknown token "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (rootType == TYPE_QS_DIALOG) {
-                    Slog.w(TAG_WM, "Attempted to add QS dialog window with unknown token "
-                          + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add QS dialog window with unknown token "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (rootType == TYPE_ACCESSIBILITY_OVERLAY) {
-                    Slog.w(TAG_WM, "Attempted to add Accessibility overlay window with unknown token "
-                            + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR,
+                            "Attempted to add Accessibility overlay window with unknown token "
+                                    + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
                 if (type == TYPE_TOAST) {
                     // Apps targeting SDK above N MR1 cannot arbitrary add toast windows.
                     if (doesAddToastWindowRequireToken(attrs.packageName, callingUid,
                             parentWindow)) {
-                        Slog.w(TAG_WM, "Attempted to add a toast window with unknown token "
-                                + attrs.token + ".  Aborting.");
+                        ProtoLog.w(WM_ERROR, "Attempted to add a toast window with unknown token "
+                                + "%s.  Aborting.", attrs.token);
                         return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                     }
                 }
@@ -1418,49 +1428,52 @@
                         (attrs.privateFlags & PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY) != 0;
                 token = new WindowToken(this, binder, type, false, displayContent,
                         session.mCanAddInternalSystemWindow, isRoundedCornerOverlay);
-            } else if (rootType >= FIRST_APPLICATION_WINDOW && rootType <= LAST_APPLICATION_WINDOW) {
+            } else if (rootType >= FIRST_APPLICATION_WINDOW
+                    && rootType <= LAST_APPLICATION_WINDOW) {
                 atoken = token.asAppWindowToken();
                 if (atoken == null) {
-                    Slog.w(TAG_WM, "Attempted to add window with non-application token "
-                          + token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add window with non-application token "
+                            + ".%s Aborting.", token);
                     return WindowManagerGlobal.ADD_NOT_APP_TOKEN;
                 } else if (atoken.removed) {
-                    Slog.w(TAG_WM, "Attempted to add window with exiting application token "
-                          + token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add window with exiting application token "
+                            + ".%s Aborting.", token);
                     return WindowManagerGlobal.ADD_APP_EXITING;
                 } else if (type == TYPE_APPLICATION_STARTING && atoken.startingWindow != null) {
-                    Slog.w(TAG_WM, "Attempted to add starting window to token with already existing"
-                            + " starting window");
+                    ProtoLog.w(WM_ERROR,
+                            "Attempted to add starting window to token with already existing"
+                                    + " starting window");
                     return WindowManagerGlobal.ADD_DUPLICATE_ADD;
                 }
             } else if (rootType == TYPE_INPUT_METHOD) {
                 if (token.windowType != TYPE_INPUT_METHOD) {
-                    Slog.w(TAG_WM, "Attempted to add input method window with bad token "
-                            + attrs.token + ".  Aborting.");
-                      return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
+                    ProtoLog.w(WM_ERROR, "Attempted to add input method window with bad token "
+                            + "%s.  Aborting.", attrs.token);
+                    return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (rootType == TYPE_VOICE_INTERACTION) {
                 if (token.windowType != TYPE_VOICE_INTERACTION) {
-                    Slog.w(TAG_WM, "Attempted to add voice interaction window with bad token "
-                            + attrs.token + ".  Aborting.");
-                      return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
+                    ProtoLog.w(WM_ERROR, "Attempted to add voice interaction window with bad token "
+                            + "%s.  Aborting.", attrs.token);
+                    return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (rootType == TYPE_WALLPAPER) {
                 if (token.windowType != TYPE_WALLPAPER) {
-                    Slog.w(TAG_WM, "Attempted to add wallpaper window with bad token "
-                            + attrs.token + ".  Aborting.");
-                      return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
+                    ProtoLog.w(WM_ERROR, "Attempted to add wallpaper window with bad token "
+                            + "%s.  Aborting.", attrs.token);
+                    return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (rootType == TYPE_DREAM) {
                 if (token.windowType != TYPE_DREAM) {
-                    Slog.w(TAG_WM, "Attempted to add Dream window with bad token "
-                            + attrs.token + ".  Aborting.");
-                      return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
+                    ProtoLog.w(WM_ERROR, "Attempted to add Dream window with bad token "
+                            + "%s.  Aborting.", attrs.token);
+                    return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (rootType == TYPE_ACCESSIBILITY_OVERLAY) {
                 if (token.windowType != TYPE_ACCESSIBILITY_OVERLAY) {
-                    Slog.w(TAG_WM, "Attempted to add Accessibility overlay window with bad token "
-                            + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR,
+                            "Attempted to add Accessibility overlay window with bad token "
+                                    + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (type == TYPE_TOAST) {
@@ -1468,18 +1481,19 @@
                 addToastWindowRequiresToken = doesAddToastWindowRequireToken(attrs.packageName,
                         callingUid, parentWindow);
                 if (addToastWindowRequiresToken && token.windowType != TYPE_TOAST) {
-                    Slog.w(TAG_WM, "Attempted to add a toast window with bad token "
-                            + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add a toast window with bad token "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (type == TYPE_QS_DIALOG) {
                 if (token.windowType != TYPE_QS_DIALOG) {
-                    Slog.w(TAG_WM, "Attempted to add QS dialog window with bad token "
-                            + attrs.token + ".  Aborting.");
+                    ProtoLog.w(WM_ERROR, "Attempted to add QS dialog window with bad token "
+                            + "%s.  Aborting.", attrs.token);
                     return WindowManagerGlobal.ADD_BAD_APP_TOKEN;
                 }
             } else if (token.asAppWindowToken() != null) {
-                Slog.w(TAG_WM, "Non-null appWindowToken for system window of rootType=" + rootType);
+                ProtoLog.w(WM_ERROR, "Non-null appWindowToken for system window of rootType=%d",
+                        rootType);
                 // It is not valid to use an app token with other system types; we will
                 // instead make a new token for it (as if null had been passed in for the token).
                 attrs.token = null;
@@ -1493,13 +1507,13 @@
             if (win.mDeathRecipient == null) {
                 // Client has apparently died, so there is no reason to
                 // continue.
-                Slog.w(TAG_WM, "Adding window client " + client.asBinder()
-                        + " that is dead, aborting.");
+                ProtoLog.w(WM_ERROR, "Adding window client %s"
+                        + " that is dead, aborting.", client.asBinder());
                 return WindowManagerGlobal.ADD_APP_EXITING;
             }
 
             if (win.getDisplayContent() == null) {
-                Slog.w(TAG_WM, "Adding window to Display that has been removed.");
+                ProtoLog.w(WM_ERROR, "Adding window to Display that has been removed.");
                 return WindowManagerGlobal.ADD_INVALID_DISPLAY;
             }
 
@@ -1531,7 +1545,7 @@
             // schedule hiding all of its toast windows.
             if (type == TYPE_TOAST) {
                 if (!displayContent.canAddToastWindowForUid(callingUid)) {
-                    Slog.w(TAG_WM, "Adding more than one toast window for UID at a time.");
+                    ProtoLog.w(WM_ERROR, "Adding more than one toast window for UID at a time.");
                     return WindowManagerGlobal.ADD_DUPLICATE_ADD;
                 }
                 // Make sure this happens before we moved focus as one can make the
@@ -1577,8 +1591,8 @@
             final AppWindowToken aToken = token.asAppWindowToken();
             if (type == TYPE_APPLICATION_STARTING && aToken != null) {
                 aToken.startingWindow = win;
-                if (DEBUG_STARTING_WINDOW) Slog.v (TAG_WM, "addWindow: " + aToken
-                        + " startingWindow=" + win);
+                ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "addWindow: %s startingWindow=%s",
+                        aToken, win);
             }
 
             boolean imMayMove = true;
@@ -1595,7 +1609,7 @@
                 if (type == TYPE_WALLPAPER) {
                     displayContent.mWallpaperController.clearLastWallpaperTimeoutTime();
                     displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
-                } else if ((attrs.flags&FLAG_SHOW_WALLPAPER) != 0) {
+                } else if ((attrs.flags & FLAG_SHOW_WALLPAPER) != 0) {
                     displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
                 } else if (displayContent.mWallpaperController.isBelowWallpaperTarget(win)) {
                     // If there is currently a wallpaper being shown, and
@@ -1680,10 +1694,9 @@
             }
             displayContent.getInputMonitor().updateInputWindowsLw(false /*force*/);
 
-            if (DEBUG || DEBUG_ADD_REMOVE) {
-                Slog.v(TAG_WM, "addWindow: New client " + client.asBinder()
-                        + ": window=" + win + " Callers=" + Debug.getCallers(5));
-            }
+            ProtoLog.v(WM_DEBUG_ADD_REMOVE, "addWindow: New client %s"
+                    + ": window=%s Callers=%s", client.asBinder(), win, Debug.getCallers(5));
+
 
             if (win.isVisibleOrAdding() && displayContent.updateOrientation()) {
                 displayContent.sendNewConfiguration();
@@ -1846,7 +1859,7 @@
      * forgetting to add the wiring when a new parent of WindowState is added.
      */
     void postWindowRemoveCleanupLocked(WindowState win) {
-        if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "postWindowRemoveCleanupLocked: " + win);
+        ProtoLog.v(WM_DEBUG_ADD_REMOVE, "postWindowRemoveCleanupLocked: %s", win);
         mWindowMap.remove(win.mClient.asBinder());
 
         final DisplayContent dc = win.getDisplayContent();
@@ -1861,7 +1874,7 @@
         mResizingWindows.remove(win);
         updateNonSystemOverlayWindowsVisibilityIfNeeded(win, false /* surfaceShown */);
         mWindowsChanged = true;
-        if (DEBUG_WINDOW_MOVEMENT) Slog.v(TAG_WM, "Final remove of window: " + win);
+        ProtoLog.v(WM_DEBUG_WINDOW_MOVEMENT, "Final remove of window: %s", win);
 
         final DisplayContent displayContent = win.getDisplayContent();
         if (displayContent.mInputMethodWindow == win) {
@@ -1870,7 +1883,7 @@
 
         final WindowToken token = win.mToken;
         final AppWindowToken atoken = win.mAppToken;
-        if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Removing " + win + " from " + token);
+        ProtoLog.v(WM_DEBUG_ADD_REMOVE, "Removing %s from %s", win, token);
         // Window will already be removed from token before this post clean-up method is called.
         if (token.isEmpty()) {
             if (!token.mPersistOnEmpty) {
@@ -1930,11 +1943,6 @@
         }
     }
 
-    static void logSurface(SurfaceControl s, String title, String msg) {
-        String str = "  SURFACE " + s + ": " + msg + " / " + title;
-        Slog.i(TAG_WM, str);
-    }
-
     static void logWithStack(String tag, String s) {
         RuntimeException e = null;
         if (SHOW_STACK_CRAWLS) {
@@ -1949,8 +1957,8 @@
         try {
             synchronized (mGlobalLock) {
                 WindowState w = windowForClientLocked(session, client, false);
-                if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
-                        "transparentRegionHint=" + region, false);
+                ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE transparentRegionHint=%s: %s",
+                        region, w);
 
                 if ((w != null) && w.mHasSurface) {
                     w.mWinAnimator.setTransparentRegionHintLocked(region);
@@ -2174,12 +2182,10 @@
             win.mInRelayout = true;
 
             win.mViewVisibility = viewVisibility;
-            if (DEBUG_SCREEN_ON) {
-                RuntimeException stack = new RuntimeException();
-                stack.fillInStackTrace();
-                Slog.i(TAG_WM, "Relayout " + win + ": oldVis=" + oldVisibility
-                        + " newVis=" + viewVisibility, stack);
-            }
+            ProtoLog.i(WM_DEBUG_SCREEN_ON,
+                    "Relayout %s: oldVis=%d newVis=%d. %s", win, oldVisibility,
+                            viewVisibility, new RuntimeException().fillInStackTrace());
+
 
             win.setDisplayLayoutNeeded();
             win.mGivenInsetsPending = (flags & WindowManagerGlobal.RELAYOUT_INSETS_PENDING) != 0;
@@ -2224,9 +2230,9 @@
                 } catch (Exception e) {
                     displayContent.getInputMonitor().updateInputWindowsLw(true /*force*/);
 
-                    Slog.w(TAG_WM, "Exception thrown when creating surface for client "
-                             + client + " (" + win.mAttrs.getTitle() + ")",
-                             e);
+                    ProtoLog.w(WM_ERROR,
+                            "Exception thrown when creating surface for client %s (%s). %s",
+                            client, win.mAttrs.getTitle(), e);
                     Binder.restoreCallingIdentity(origId);
                     return 0;
                 }
@@ -2350,21 +2356,21 @@
             outInsetsState.set(displayContent.getInsetsStateController().getInsetsForDispatch(win));
             if (DEBUG) {
                 Slog.v(TAG_WM, "Relayout given client " + client.asBinder()
-                                + ", requestedWidth=" + requestedWidth
-                                + ", requestedHeight=" + requestedHeight
-                                + ", viewVisibility=" + viewVisibility
-                                + "\nRelayout returning frame=" + outFrame
-                                + ", surface=" + outSurfaceControl);
+                        + ", requestedWidth=" + requestedWidth
+                        + ", requestedHeight=" + requestedHeight
+                        + ", viewVisibility=" + viewVisibility
+                        + "\nRelayout returning frame=" + outFrame
+                        + ", surface=" + outSurfaceControl);
             }
 
-            if (DEBUG || DEBUG_FOCUS) {
-                Slog.v(TAG_WM, "Relayout of " + win + ": focusMayChange=" + focusMayChange);
-            }
+            ProtoLog.v(WM_DEBUG_FOCUS, "Relayout of %s: focusMayChange=%b",
+                    win, focusMayChange);
 
             result |= mInTouchMode ? WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE : 0;
 
             if (DEBUG_LAYOUT) {
-                Slog.v(TAG_WM, "Relayout complete " + win + ": outFrame=" + outFrame.toShortString());
+                Slog.v(TAG_WM,
+                        "Relayout complete " + win + ": outFrame=" + outFrame.toShortString());
             }
             win.mInRelayout = false;
 
@@ -2442,11 +2448,12 @@
         }
         if (surfaceController != null) {
             surfaceController.getSurfaceControl(outSurfaceControl);
-            if (SHOW_TRANSACTIONS) Slog.i(TAG_WM, "  OUT SURFACE " + outSurfaceControl + ": copied");
+            ProtoLog.i(WM_SHOW_TRANSACTIONS, "OUT SURFACE %s: copied", outSurfaceControl);
+
         } else {
             // For some reason there isn't a surface.  Clear the
             // caller's object so they see the same state.
-            Slog.w(TAG_WM, "Failed to create surface control for " + win);
+            ProtoLog.w(WM_ERROR, "Failed to create surface control for %s", win);
             outSurfaceControl.release();
         }
 
@@ -2475,8 +2482,8 @@
         try {
             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"));
+                ProtoLog.d(WM_DEBUG_ADD_REMOVE, "finishDrawingWindow: %s mDrawState=%s",
+                        win, (win != null ? win.mWinAnimator.drawStateToString() : "null"));
                 if (win != null && win.mWinAnimator.finishDrawingLocked(postDrawTransaction)) {
                     if ((win.mAttrs.flags & FLAG_SHOW_WALLPAPER) != 0) {
                         win.getDisplayContent().pendingLayoutChanges |=
@@ -2501,9 +2508,8 @@
                 == PackageManager.PERMISSION_GRANTED) {
             return true;
         }
-        final String msg = "Permission Denial: " + func + " from pid=" + Binder.getCallingPid()
-                + ", uid=" + Binder.getCallingUid() + " requires " + permission;
-        Slog.w(TAG_WM, msg);
+        ProtoLog.w(WM_ERROR, "Permission Denial: %s from pid=%d, uid=%d requires %s",
+                func, Binder.getCallingPid(), Binder.getCallingUid(), permission);
         return false;
     }
 
@@ -2516,16 +2522,16 @@
         synchronized (mGlobalLock) {
             final DisplayContent dc = getDisplayContentOrCreate(displayId, null /* token */);
             if (dc == null) {
-                Slog.w(TAG_WM, "addWindowToken: Attempted to add token: " + binder
-                        + " for non-exiting displayId=" + displayId);
+                ProtoLog.w(WM_ERROR, "addWindowToken: Attempted to add token: %s"
+                        + " for non-exiting displayId=%d", binder, displayId);
                 return;
             }
 
             WindowToken token = dc.getWindowToken(binder);
             if (token != null) {
-                Slog.w(TAG_WM, "addWindowToken: Attempted to add binder token: " + binder
-                        + " for already created window token: " + token
-                        + " displayId=" + displayId);
+                ProtoLog.w(WM_ERROR, "addWindowToken: Attempted to add binder token: %s"
+                        + " for already created window token: %s"
+                        + " displayId=%d", binder, token, displayId);
                 return;
             }
             if (type == TYPE_WALLPAPER) {
@@ -2548,15 +2554,16 @@
             synchronized (mGlobalLock) {
                 final DisplayContent dc = mRoot.getDisplayContent(displayId);
                 if (dc == null) {
-                    Slog.w(TAG_WM, "removeWindowToken: Attempted to remove token: " + binder
-                            + " for non-exiting displayId=" + displayId);
+                    ProtoLog.w(WM_ERROR, "removeWindowToken: Attempted to remove token: %s"
+                            + " for non-exiting displayId=%d", binder, displayId);
                     return;
                 }
 
                 final WindowToken token = dc.removeWindowToken(binder);
                 if (token == null) {
-                    Slog.w(TAG_WM,
-                            "removeWindowToken: Attempted to remove non-existing token: " + binder);
+                    ProtoLog.w(WM_ERROR,
+                            "removeWindowToken: Attempted to remove non-existing token: %s",
+                            binder);
                     return;
                 }
 
@@ -3196,14 +3203,11 @@
 
     public void enableScreenAfterBoot() {
         synchronized (mGlobalLock) {
-            if (DEBUG_BOOT) {
-                RuntimeException here = new RuntimeException("here");
-                here.fillInStackTrace();
-                Slog.i(TAG_WM, "enableScreenAfterBoot: mDisplayEnabled=" + mDisplayEnabled
-                        + " mForceDisplayEnabled=" + mForceDisplayEnabled
-                        + " mShowingBootMessages=" + mShowingBootMessages
-                        + " mSystemBooted=" + mSystemBooted, here);
-            }
+            ProtoLog.i(WM_DEBUG_BOOT, "enableScreenAfterBoot: mDisplayEnabled=%b "
+                            + "mForceDisplayEnabled=%b mShowingBootMessages=%b mSystemBooted=%b. "
+                            + "%s",
+                    mDisplayEnabled, mForceDisplayEnabled, mShowingBootMessages, mSystemBooted,
+                    new RuntimeException("here").fillInStackTrace());
             if (mSystemBooted) {
                 return;
             }
@@ -3227,14 +3231,11 @@
     }
 
     void enableScreenIfNeededLocked() {
-        if (DEBUG_BOOT) {
-            RuntimeException here = new RuntimeException("here");
-            here.fillInStackTrace();
-            Slog.i(TAG_WM, "enableScreenIfNeededLocked: mDisplayEnabled=" + mDisplayEnabled
-                    + " mForceDisplayEnabled=" + mForceDisplayEnabled
-                    + " mShowingBootMessages=" + mShowingBootMessages
-                    + " mSystemBooted=" + mSystemBooted, here);
-        }
+        ProtoLog.i(WM_DEBUG_BOOT, "enableScreenIfNeededLocked: mDisplayEnabled=%b "
+                        + "mForceDisplayEnabled=%b mShowingBootMessages=%b mSystemBooted=%b. "
+                        + "%s",
+                mDisplayEnabled, mForceDisplayEnabled, mShowingBootMessages, mSystemBooted,
+                new RuntimeException("here").fillInStackTrace());
         if (mDisplayEnabled) {
             return;
         }
@@ -3249,7 +3250,7 @@
             if (mDisplayEnabled) {
                 return;
             }
-            Slog.w(TAG_WM, "***** BOOT TIMEOUT: forcing display enabled");
+            ProtoLog.w(WM_ERROR, "***** BOOT TIMEOUT: forcing display enabled");
             mForceDisplayEnabled = true;
         }
         performEnableScreen();
@@ -3264,11 +3265,10 @@
 
     private void performEnableScreen() {
         synchronized (mGlobalLock) {
-            if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: mDisplayEnabled=" + mDisplayEnabled
-                    + " mForceDisplayEnabled=" + mForceDisplayEnabled
-                    + " mShowingBootMessages=" + mShowingBootMessages
-                    + " mSystemBooted=" + mSystemBooted
-                    + " mOnlyCore=" + mOnlyCore,
+            ProtoLog.i(WM_DEBUG_BOOT, "performEnableScreen: mDisplayEnabled=%b"
+                            + " mForceDisplayEnabled=%b" + " mShowingBootMessages=%b"
+                            + " mSystemBooted=%b mOnlyCore=%b. %s", mDisplayEnabled,
+                    mForceDisplayEnabled, mShowingBootMessages, mSystemBooted, mOnlyCore,
                     new RuntimeException("here").fillInStackTrace());
             if (mDisplayEnabled) {
                 return;
@@ -3282,10 +3282,12 @@
             }
 
             // Don't enable the screen until all existing windows have been drawn.
-            if (!mForceDisplayEnabled
-                    // TODO(multidisplay): Expand to all displays?
-                    && getDefaultDisplayContentLocked().checkWaitingForWindows()) {
-                return;
+            if (!mForceDisplayEnabled) {
+                for (int i = mRoot.getChildCount() - 1; i >= 0; i--) {
+                    if (mRoot.getChildAt(i).shouldWaitForSystemDecorWindowsOnBoot()) {
+                        return;
+                    }
+                }
             }
 
             if (!mBootAnimationStopped) {
@@ -3298,14 +3300,14 @@
             }
 
             if (!mForceDisplayEnabled && !checkBootAnimationCompleteLocked()) {
-                if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: Waiting for anim complete");
+                ProtoLog.i(WM_DEBUG_BOOT, "performEnableScreen: Waiting for anim complete");
                 return;
             }
 
             try {
                 IBinder surfaceFlinger = ServiceManager.getService("SurfaceFlinger");
                 if (surfaceFlinger != null) {
-                    Slog.i(TAG_WM, "******* TELLING SURFACE FLINGER WE ARE BOOTED!");
+                    ProtoLog.i(WM_ERROR, "******* TELLING SURFACE FLINGER WE ARE BOOTED!");
                     Parcel data = Parcel.obtain();
                     data.writeInterfaceToken("android.ui.ISurfaceComposer");
                     surfaceFlinger.transact(IBinder.FIRST_CALL_TRANSACTION, // BOOT_FINISHED
@@ -3313,13 +3315,13 @@
                     data.recycle();
                 }
             } catch (RemoteException ex) {
-                Slog.e(TAG_WM, "Boot completed: SurfaceFlinger is dead!");
+                ProtoLog.e(WM_ERROR, "Boot completed: SurfaceFlinger is dead!");
             }
 
             EventLog.writeEvent(EventLogTags.WM_BOOT_ANIMATION_DONE, SystemClock.uptimeMillis());
             Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0);
             mDisplayEnabled = true;
-            if (DEBUG_SCREEN_ON || DEBUG_BOOT) Slog.i(TAG_WM, "******************** ENABLING SCREEN!");
+            ProtoLog.i(WM_DEBUG_SCREEN_ON, "******************** ENABLING SCREEN!");
 
             // Enable input dispatch.
             mInputManagerCallback.setEventDispatchingLw(mEventDispatchingEnabled);
@@ -3341,24 +3343,21 @@
             mH.removeMessages(H.CHECK_IF_BOOT_ANIMATION_FINISHED);
             mH.sendEmptyMessageDelayed(H.CHECK_IF_BOOT_ANIMATION_FINISHED,
                     BOOT_ANIMATION_POLL_INTERVAL);
-            if (DEBUG_BOOT) Slog.i(TAG_WM, "checkBootAnimationComplete: Waiting for anim complete");
+            ProtoLog.i(WM_DEBUG_BOOT, "checkBootAnimationComplete: Waiting for anim complete");
             return false;
         }
-        if (DEBUG_BOOT) Slog.i(TAG_WM, "checkBootAnimationComplete: Animation complete!");
+        ProtoLog.i(WM_DEBUG_BOOT, "checkBootAnimationComplete: Animation complete!");
         return true;
     }
 
     public void showBootMessage(final CharSequence msg, final boolean always) {
         boolean first = false;
         synchronized (mGlobalLock) {
-            if (DEBUG_BOOT) {
-                RuntimeException here = new RuntimeException("here");
-                here.fillInStackTrace();
-                Slog.i(TAG_WM, "showBootMessage: msg=" + msg + " always=" + always
-                        + " mAllowBootMessages=" + mAllowBootMessages
-                        + " mShowingBootMessages=" + mShowingBootMessages
-                        + " mSystemBooted=" + mSystemBooted, here);
-            }
+            ProtoLog.i(WM_DEBUG_BOOT, "showBootMessage: msg=%s always=%b"
+                            + " mAllowBootMessages=%b mShowingBootMessages=%b"
+                            + " mSystemBooted=%b. %s", msg, always, mAllowBootMessages,
+                    mShowingBootMessages, mSystemBooted,
+                    new RuntimeException("here").fillInStackTrace());
             if (!mAllowBootMessages) {
                 return;
             }
@@ -3380,14 +3379,11 @@
     }
 
     public void hideBootMessagesLocked() {
-        if (DEBUG_BOOT) {
-            RuntimeException here = new RuntimeException("here");
-            here.fillInStackTrace();
-            Slog.i(TAG_WM, "hideBootMessagesLocked: mDisplayEnabled=" + mDisplayEnabled
-                    + " mForceDisplayEnabled=" + mForceDisplayEnabled
-                    + " mShowingBootMessages=" + mShowingBootMessages
-                    + " mSystemBooted=" + mSystemBooted, here);
-        }
+        ProtoLog.i(WM_DEBUG_BOOT, "hideBootMessagesLocked: mDisplayEnabled=%b"
+                        + " mForceDisplayEnabled=%b mShowingBootMessages=%b"
+                        + " mSystemBooted=%b. %s", mDisplayEnabled, mForceDisplayEnabled,
+                mShowingBootMessages, mSystemBooted,
+                new RuntimeException("here").fillInStackTrace());
         if (mShowingBootMessages) {
             mShowingBootMessages = false;
             mPolicy.hideBootMessages();
@@ -3432,60 +3428,45 @@
 
     public void showCircularMask(boolean visible) {
         synchronized (mGlobalLock) {
+            if (visible) {
+                // TODO(multi-display): support multiple displays
+                if (mCircularDisplayMask == null) {
+                    int screenOffset = mContext.getResources().getInteger(
+                            com.android.internal.R.integer.config_windowOutsetBottom);
+                    int maskThickness = mContext.getResources().getDimensionPixelSize(
+                            com.android.internal.R.dimen.circular_display_mask_thickness);
 
-            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
-                    ">>> OPEN TRANSACTION showCircularMask(visible=" + visible + ")");
-            openSurfaceTransaction();
-            try {
-                if (visible) {
-                    // TODO(multi-display): support multiple displays
-                    if (mCircularDisplayMask == null) {
-                        int screenOffset = mContext.getResources().getInteger(
-                                com.android.internal.R.integer.config_windowOutsetBottom);
-                        int maskThickness = mContext.getResources().getDimensionPixelSize(
-                                com.android.internal.R.dimen.circular_display_mask_thickness);
 
-                        mCircularDisplayMask = new CircularDisplayMask(mSurfaceFactory,
-                                getDefaultDisplayContentLocked(),
-                                mPolicy.getWindowLayerFromTypeLw(
-                                        WindowManager.LayoutParams.TYPE_POINTER)
-                                        * TYPE_LAYER_MULTIPLIER + 10, screenOffset, maskThickness);
+                    if (SHOW_LIGHT_TRANSACTIONS) {
+                        Slog.i(TAG_WM,
+                                ">>> showCircularMask(visible=" + visible + ")");
                     }
-                    mCircularDisplayMask.setVisibility(true);
-                } else if (mCircularDisplayMask != null) {
-                    mCircularDisplayMask.setVisibility(false);
-                    mCircularDisplayMask = null;
+                    mCircularDisplayMask = new CircularDisplayMask(mSurfaceFactory,
+                            getDefaultDisplayContentLocked(), mPolicy.getWindowLayerFromTypeLw(
+                            WindowManager.LayoutParams.TYPE_POINTER) * TYPE_LAYER_MULTIPLIER
+                            + 10, screenOffset, maskThickness, mTransaction);
                 }
-            } finally {
-                closeSurfaceTransaction("showCircularMask");
-                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
-                        "<<< CLOSE TRANSACTION showCircularMask(visible=" + visible + ")");
+                mCircularDisplayMask.setVisibility(true, mTransaction);
+            } else if (mCircularDisplayMask != null) {
+                mCircularDisplayMask.setVisibility(false, mTransaction);
+                mCircularDisplayMask = null;
             }
+            mTransaction.apply();
         }
     }
 
     public void showEmulatorDisplayOverlay() {
         synchronized (mGlobalLock) {
 
-            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
-                    ">>> OPEN TRANSACTION showEmulatorDisplayOverlay");
-            openSurfaceTransaction();
-            try {
-                if (mEmulatorDisplayOverlay == null) {
-                    mEmulatorDisplayOverlay = new EmulatorDisplayOverlay(
-                            mSurfaceFactory,
-                            mContext,
-                            getDefaultDisplayContentLocked(),
-                            mPolicy.getWindowLayerFromTypeLw(
-                                    WindowManager.LayoutParams.TYPE_POINTER)
-                                    * TYPE_LAYER_MULTIPLIER + 10);
-                }
-                mEmulatorDisplayOverlay.setVisibility(true);
-            } finally {
-                closeSurfaceTransaction("showEmulatorDisplayOverlay");
-                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
-                        "<<< CLOSE TRANSACTION showEmulatorDisplayOverlay");
+            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM, ">>> showEmulatorDisplayOverlay");
+            if (mEmulatorDisplayOverlay == null) {
+                mEmulatorDisplayOverlay = new EmulatorDisplayOverlay(mSurfaceFactory, mContext,
+                        getDefaultDisplayContentLocked(),
+                        mPolicy.getWindowLayerFromTypeLw(WindowManager.LayoutParams.TYPE_POINTER)
+                                * TYPE_LAYER_MULTIPLIER + 10, mTransaction);
             }
+            mEmulatorDisplayOverlay.setVisibility(true, mTransaction);
+            mTransaction.apply();
         }
     }
 
@@ -3514,23 +3495,16 @@
                 return;
             }
 
-            if (SHOW_VERBOSE_TRANSACTIONS) Slog.i(TAG_WM,
-                    ">>> OPEN TRANSACTION showStrictModeViolation");
+            if (SHOW_VERBOSE_TRANSACTIONS) Slog.i(TAG_WM, ">>> showStrictModeViolation");
             // TODO: Modify this to use the surface trace once it is not going crazy.
             // b/31532461
-            SurfaceControl.openTransaction();
-            try {
-                // TODO(multi-display): support multiple displays
-                if (mStrictModeFlash == null) {
-                    mStrictModeFlash = new StrictModeFlash(mSurfaceFactory,
-                            getDefaultDisplayContentLocked());
-                }
-                mStrictModeFlash.setVisibility(on);
-            } finally {
-                SurfaceControl.closeTransaction();
-                if (SHOW_VERBOSE_TRANSACTIONS) Slog.i(TAG_WM,
-                        "<<< CLOSE TRANSACTION showStrictModeViolation");
+            // TODO(multi-display): support multiple displays
+            if (mStrictModeFlash == null) {
+                mStrictModeFlash = new StrictModeFlash(mSurfaceFactory,
+                        getDefaultDisplayContentLocked(), mTransaction);
             }
+            mStrictModeFlash.setVisibility(on, mTransaction);
+            mTransaction.apply();
         }
     }
 
@@ -3679,8 +3653,7 @@
             throw new SecurityException("Requires SET_ORIENTATION permission");
         }
 
-        if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "thawRotation: mRotation="
-                + getDefaultDisplayRotation());
+        ProtoLog.v(WM_DEBUG_ORIENTATION, "thawRotation: mRotation=%d", getDefaultDisplayRotation());
 
         long origId = Binder.clearCallingIdentity();
         try {
@@ -3729,9 +3702,9 @@
     }
 
     private void updateRotationUnchecked(boolean alwaysSendConfiguration, boolean forceRelayout) {
-        if(DEBUG_ORIENTATION) Slog.v(TAG_WM, "updateRotationUnchecked:"
-                + " alwaysSendConfiguration=" + alwaysSendConfiguration
-                + " forceRelayout=" + forceRelayout);
+        ProtoLog.v(WM_DEBUG_ORIENTATION, "updateRotationUnchecked:"
+                        + " alwaysSendConfiguration=%b forceRelayout=%b",
+                alwaysSendConfiguration, forceRelayout);
 
         Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "updateRotation");
 
@@ -3980,7 +3953,7 @@
                 try {
                     return mViewServer.start();
                 } catch (IOException e) {
-                    Slog.w(TAG_WM, "View server did not start");
+                    ProtoLog.w(WM_ERROR, "View server did not start");
                 }
             }
             return false;
@@ -3990,7 +3963,7 @@
             mViewServer = new ViewServer(this, port);
             return mViewServer.start();
         } catch (IOException e) {
-            Slog.w(TAG_WM, "View server did not start");
+            ProtoLog.w(WM_ERROR, "View server did not start");
         }
         return false;
     }
@@ -4220,7 +4193,8 @@
             }
 
         } catch (Exception e) {
-            Slog.w(TAG_WM, "Could not send command " + command + " with parameters " + parameters, e);
+            ProtoLog.w(WM_ERROR, "Could not send command %s with parameters %s. %s", command,
+                    parameters, e);
             success = false;
         } finally {
             if (data != null) {
@@ -4369,9 +4343,9 @@
     public boolean detectSafeMode() {
         if (!mInputManagerCallback.waitForInputDevicesReady(
                 INPUT_DEVICES_READY_FOR_SAFE_MODE_DETECTION_TIMEOUT_MILLIS)) {
-            Slog.w(TAG_WM, "Devices still not ready after waiting "
-                   + INPUT_DEVICES_READY_FOR_SAFE_MODE_DETECTION_TIMEOUT_MILLIS
-                   + " milliseconds before attempting to detect safe mode.");
+            ProtoLog.w(WM_ERROR, "Devices still not ready after waiting %d"
+                            + " milliseconds before attempting to detect safe mode.",
+                    INPUT_DEVICES_READY_FOR_SAFE_MODE_DETECTION_TIMEOUT_MILLIS);
         }
 
         if (Settings.Global.getInt(
@@ -4399,14 +4373,14 @@
         } catch (IllegalArgumentException e) {
         }
         if (mSafeMode) {
-            Log.i(TAG_WM, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
-                    + " dpad=" + dpadState + " trackball=" + trackballState + ")");
+            ProtoLog.i(WM_ERROR, "SAFE MODE ENABLED (menu=%d s=%d dpad=%d"
+                    + " trackball=%d)", menuState, sState, dpadState, trackballState);
             // May already be set if (for instance) this process has crashed
             if (SystemProperties.getInt(ShutdownThread.RO_SAFEMODE_PROPERTY, 0) == 0) {
                 SystemProperties.set(ShutdownThread.RO_SAFEMODE_PROPERTY, "1");
             }
         } else {
-            Log.i(TAG_WM, "SAFE MODE not enabled");
+            ProtoLog.i(WM_ERROR, "SAFE MODE not enabled");
         }
         mPolicy.setSafeMode(mSafeMode);
         return mSafeMode;
@@ -4565,10 +4539,11 @@
                             return;
                         }
                         displayContent.mLastFocus = newFocus;
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Focus moving from " + lastFocus +
-                                " to " + newFocus + " displayId=" + displayContent.getDisplayId());
+                        ProtoLog.i(WM_DEBUG_FOCUS_LIGHT, "Focus moving from %s"
+                                        + " to %s displayId=%d", lastFocus, newFocus,
+                                displayContent.getDisplayId());
                         if (newFocus != null && lastFocus != null && !newFocus.isDisplayedLw()) {
-                            if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Delaying loss of focus...");
+                            ProtoLog.i(WM_DEBUG_FOCUS_LIGHT, "Delaying loss of focus...");
                             displayContent.mLosingFocus.add(lastFocus);
                             lastFocus = null;
                         }
@@ -4582,13 +4557,13 @@
                     }
 
                     if (newFocus != null) {
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Gaining focus: " + newFocus);
+                        ProtoLog.i(WM_DEBUG_FOCUS_LIGHT, "Gaining focus: %s", newFocus);
                         newFocus.reportFocusChangedSerialized(true, mInTouchMode);
                         notifyFocusChanged();
                     }
 
                     if (lastFocus != null) {
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Losing focus: " + lastFocus);
+                        ProtoLog.i(WM_DEBUG_FOCUS_LIGHT, "Losing focus: %s", lastFocus);
                         lastFocus.reportFocusChangedSerialized(false, mInTouchMode);
                     }
                     break;
@@ -4605,7 +4580,7 @@
 
                     final int N = losers.size();
                     for (int i = 0; i < N; i++) {
-                        if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "Losing delayed focus: " +
+                        ProtoLog.i(WM_DEBUG_FOCUS_LIGHT, "Losing delayed focus: %s",
                                 losers.get(i));
                         losers.get(i).reportFocusChangedSerialized(false, mInTouchMode);
                     }
@@ -4688,9 +4663,9 @@
 
                 case APP_FREEZE_TIMEOUT: {
                     synchronized (mGlobalLock) {
-                        Slog.w(TAG_WM, "App freeze timeout expired.");
+                        ProtoLog.w(WM_ERROR, "App freeze timeout expired.");
                         mWindowsFreezingScreen = WINDOWS_FREEZING_SCREENS_TIMEOUT;
-                        for (int i = mAppFreezeListeners.size() - 1; i >=0 ; --i) {
+                        for (int i = mAppFreezeListeners.size() - 1; i >= 0; --i) {
                             mAppFreezeListeners.get(i).onAppFreezeTimeout();
                         }
                     }
@@ -4730,11 +4705,12 @@
 
                 case WAITING_FOR_DRAWN_TIMEOUT: {
                     Runnable callback = null;
+                    final WindowContainer container = (WindowContainer) msg.obj;
                     synchronized (mGlobalLock) {
-                        Slog.w(TAG_WM, "Timeout waiting for drawn: undrawn=" + mWaitingForDrawn);
-                        mWaitingForDrawn.clear();
-                        callback = mWaitingForDrawnCallback;
-                        mWaitingForDrawnCallback = null;
+                        ProtoLog.w(WM_ERROR, "Timeout waiting for drawn: undrawn=%s",
+                                container.mWaitingForDrawn);
+                        container.mWaitingForDrawn.clear();
+                        callback = mWaitingForDrawnCallbacks.remove(container);
                     }
                     if (callback != null) {
                         callback.run();
@@ -4766,9 +4742,9 @@
                 }
                 case ALL_WINDOWS_DRAWN: {
                     Runnable callback;
+                    final WindowContainer container = (WindowContainer) msg.obj;
                     synchronized (mGlobalLock) {
-                        callback = mWaitingForDrawnCallback;
-                        mWaitingForDrawnCallback = null;
+                        callback = mWaitingForDrawnCallbacks.remove(container);
                     }
                     if (callback != null) {
                         callback.run();
@@ -4805,7 +4781,7 @@
                 case CHECK_IF_BOOT_ANIMATION_FINISHED: {
                     final boolean bootAnimationComplete;
                     synchronized (mGlobalLock) {
-                        if (DEBUG_BOOT) Slog.i(TAG_WM, "CHECK_IF_BOOT_ANIMATION_FINISHED:");
+                        ProtoLog.i(WM_DEBUG_BOOT, "CHECK_IF_BOOT_ANIMATION_FINISHED:");
                         bootAnimationComplete = checkBootAnimationCompleteLocked();
                     }
                     if (bootAnimationComplete) {
@@ -5019,10 +4995,10 @@
                 int width, height;
                 try {
                     width = Integer.parseInt(sizeStr.substring(0, pos));
-                    height = Integer.parseInt(sizeStr.substring(pos+1));
+                    height = Integer.parseInt(sizeStr.substring(pos + 1));
                     if (displayContent.mBaseDisplayWidth != width
                             || displayContent.mBaseDisplayHeight != height) {
-                        Slog.i(TAG_WM, "FORCED DISPLAY SIZE: " + width + "x" + height);
+                        ProtoLog.i(WM_ERROR, "FORCED DISPLAY SIZE: %dx%d", width, height);
                         displayContent.updateBaseDisplayMetrics(width, height,
                                 displayContent.mBaseDisplayDensity);
                         changed = true;
@@ -5043,7 +5019,7 @@
         int mode = Settings.Global.getInt(mContext.getContentResolver(),
                 Settings.Global.DISPLAY_SCALING_FORCE, 0);
         if (displayContent.mDisplayScalingDisabled != (mode != 0)) {
-            Slog.i(TAG_WM, "FORCED DISPLAY SCALING DISABLED");
+            ProtoLog.i(WM_ERROR, "FORCED DISPLAY SCALING DISABLED");
             displayContent.mDisplayScalingDisabled = true;
             changed = true;
         }
@@ -5223,7 +5199,7 @@
                 throw new IllegalArgumentException(
                         "Requested window " + client + " does not exist");
             }
-            Slog.w(TAG_WM, "Failed looking up window callers=" + Debug.getCallers(3));
+            ProtoLog.w(WM_ERROR, "Failed looking up window callers=%s", Debug.getCallers(3));
             return null;
         }
         if (session != null && win.mSession != session) {
@@ -5231,7 +5207,7 @@
                 throw new IllegalArgumentException("Requested window " + client + " is in session "
                         + win.mSession + ", not " + session);
             }
-            Slog.w(TAG_WM, "Failed looking up window callers=" + Debug.getCallers(3));
+            ProtoLog.w(WM_ERROR, "Failed looking up window callers=%s", Debug.getCallers(3));
             return null;
         }
 
@@ -5243,7 +5219,7 @@
         // it frozen/off until this window draws at its new
         // orientation.
         if (!w.mToken.okToDisplay() && mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_TIMEOUT) {
-            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Changing surface while display frozen: " + w);
+            ProtoLog.v(WM_DEBUG_ORIENTATION, "Changing surface while display frozen: %s", w);
             w.setOrientationChanging(true);
             w.mLastFreezeDuration = 0;
             mRoot.mOrientationChangeComplete = false;
@@ -5258,30 +5234,32 @@
     }
 
     void checkDrawnWindowsLocked() {
-        if (mWaitingForDrawn.isEmpty() || mWaitingForDrawnCallback == null) {
+        if (mWaitingForDrawnCallbacks.isEmpty()) {
             return;
         }
-        for (int j = mWaitingForDrawn.size() - 1; j >= 0; j--) {
-            WindowState win = mWaitingForDrawn.get(j);
-            if (DEBUG_SCREEN_ON) Slog.i(TAG_WM, "Waiting for drawn " + win +
-                    ": removed=" + win.mRemoved + " visible=" + win.isVisibleLw() +
-                    " mHasSurface=" + win.mHasSurface +
-                    " drawState=" + win.mWinAnimator.mDrawState);
-            if (win.mRemoved || !win.mHasSurface || !win.isVisibleByPolicy()) {
-                // Window has been removed or hidden; no draw will now happen, so stop waiting.
-                if (DEBUG_SCREEN_ON) Slog.w(TAG_WM, "Aborted waiting for drawn: " + win);
-                mWaitingForDrawn.remove(win);
-            } else if (win.hasDrawnLw()) {
-                // Window is now drawn (and shown).
-                if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "Window drawn win=" + win);
-                mWaitingForDrawn.remove(win);
+        mWaitingForDrawnCallbacks.forEach((container, callback) -> {
+            for (int j = container.mWaitingForDrawn.size() - 1; j >= 0; j--) {
+                final WindowState win = (WindowState) container.mWaitingForDrawn.get(j);
+                ProtoLog.i(WM_DEBUG_SCREEN_ON,
+                        "Waiting for drawn %s: removed=%b visible=%b mHasSurface=%b drawState=%d",
+                        win, win.mRemoved, win.isVisibleLw(), win.mHasSurface,
+                        win.mWinAnimator.mDrawState);
+                if (win.mRemoved || !win.mHasSurface || !win.isVisibleByPolicy()) {
+                    // Window has been removed or hidden; no draw will now happen, so stop waiting.
+                    ProtoLog.w(WM_DEBUG_SCREEN_ON, "Aborted waiting for drawn: %s", win);
+                    container.mWaitingForDrawn.remove(win);
+                } else if (win.hasDrawnLw()) {
+                    // Window is now drawn (and shown).
+                    ProtoLog.d(WM_DEBUG_SCREEN_ON, "Window drawn win=%s", win);
+                    container.mWaitingForDrawn.remove(win);
+                }
             }
-        }
-        if (mWaitingForDrawn.isEmpty()) {
-            if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "All windows drawn!");
-            mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT);
-            mH.sendEmptyMessage(H.ALL_WINDOWS_DRAWN);
-        }
+            if (container.mWaitingForDrawn.isEmpty()) {
+                ProtoLog.d(WM_DEBUG_SCREEN_ON, "All windows drawn!");
+                mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT, container);
+                mH.sendMessage(mH.obtainMessage(H.ALL_WINDOWS_DRAWN, container));
+            }
+        });
     }
 
     void setHoldScreenLocked(final Session newHoldScreen) {
@@ -5295,19 +5273,15 @@
         final boolean state = mHoldingScreenWakeLock.isHeld();
         if (hold != state) {
             if (hold) {
-                if (DEBUG_KEEP_SCREEN_ON) {
-                    Slog.d(TAG_KEEP_SCREEN_ON, "Acquiring screen wakelock due to "
-                            + mRoot.mHoldScreenWindow);
-                }
+                ProtoLog.d(WM_DEBUG_KEEP_SCREEN_ON, "Acquiring screen wakelock due to %s",
+                            mRoot.mHoldScreenWindow);
                 mLastWakeLockHoldingWindow = mRoot.mHoldScreenWindow;
                 mLastWakeLockObscuringWindow = null;
                 mHoldingScreenWakeLock.acquire();
                 mPolicy.keepScreenOnStartedLw();
             } else {
-                if (DEBUG_KEEP_SCREEN_ON) {
-                    Slog.d(TAG_KEEP_SCREEN_ON, "Releasing screen wakelock, obscured by "
-                            + mRoot.mObscuringWindow);
-                }
+                ProtoLog.d(WM_DEBUG_KEEP_SCREEN_ON, "Releasing screen wakelock, obscured by %s",
+                            mRoot.mObscuringWindow);
                 mLastWakeLockHoldingWindow = null;
                 mLastWakeLockObscuringWindow = mRoot.mObscuringWindow;
                 mPolicy.keepScreenOnStoppedLw();
@@ -5351,10 +5325,9 @@
             return;
         }
 
-        if (DEBUG_ORIENTATION) Slog.d(TAG_WM,
-                "startFreezingDisplayLocked: exitAnim="
-                + exitAnim + " enterAnim=" + enterAnim
-                + " called by " + Debug.getCallers(8));
+        ProtoLog.d(WM_DEBUG_ORIENTATION,
+                            "startFreezingDisplayLocked: exitAnim=%d enterAnim=%d called by %s",
+                            exitAnim, enterAnim, Debug.getCallers(8));
         mScreenFrozenLock.acquire();
 
         mDisplayFrozen = true;
@@ -5380,7 +5353,7 @@
         mExitAnimId = exitAnim;
         mEnterAnimId = enterAnim;
         ScreenRotationAnimation screenRotationAnimation =
-                mAnimator.getScreenRotationAnimationLocked(mFrozenDisplayId);
+                displayContent.getRotationAnimation();
         if (screenRotationAnimation != null) {
             screenRotationAnimation.kill();
         }
@@ -5392,8 +5365,7 @@
         screenRotationAnimation = new ScreenRotationAnimation(mContext, displayContent,
                 displayContent.getDisplayRotation().isFixedToUserRotation(), isSecure,
                 this);
-        mAnimator.setScreenRotationAnimationLocked(mFrozenDisplayId,
-                screenRotationAnimation);
+        displayContent.setRotationAnimation(screenRotationAnimation);
     }
 
     void stopFreezingDisplayLocked() {
@@ -5407,17 +5379,17 @@
         if (waitingForConfig || mAppsFreezingScreen > 0
                 || mWindowsFreezingScreen == WINDOWS_FREEZING_SCREENS_ACTIVE
                 || mClientFreezingScreen || numOpeningApps > 0) {
-            if (DEBUG_ORIENTATION) Slog.d(TAG_WM,
-                "stopFreezingDisplayLocked: Returning mWaitingForConfig=" + waitingForConfig
-                + ", mAppsFreezingScreen=" + mAppsFreezingScreen
-                + ", mWindowsFreezingScreen=" + mWindowsFreezingScreen
-                + ", mClientFreezingScreen=" + mClientFreezingScreen
-                + ", mOpeningApps.size()=" + numOpeningApps);
+            ProtoLog.d(WM_DEBUG_ORIENTATION,
+                                "stopFreezingDisplayLocked: Returning mWaitingForConfig=%b, "
+                                        + "mAppsFreezingScreen=%d, mWindowsFreezingScreen=%d, "
+                                        + "mClientFreezingScreen=%b, mOpeningApps.size()=%d",
+                                waitingForConfig, mAppsFreezingScreen, mWindowsFreezingScreen,
+                                mClientFreezingScreen, numOpeningApps);
             return;
         }
 
-        if (DEBUG_ORIENTATION) Slog.d(TAG_WM,
-                "stopFreezingDisplayLocked: Unfreezing now");
+        ProtoLog.d(WM_DEBUG_ORIENTATION,
+                    "stopFreezingDisplayLocked: Unfreezing now");
 
 
         // We must make a local copy of the displayId as it can be potentially overwritten later on
@@ -5435,7 +5407,7 @@
             sb.append(" due to ");
             sb.append(mLastFinishedFreezeSource);
         }
-        Slog.i(TAG_WM, sb.toString());
+        ProtoLog.i(WM_ERROR, "%s", sb.toString());
         mH.removeMessages(H.APP_FREEZE_TIMEOUT);
         mH.removeMessages(H.CLIENT_FREEZE_TIMEOUT);
         if (PROFILE_ORIENTATION) {
@@ -5444,10 +5416,10 @@
 
         boolean updateRotation = false;
 
-        ScreenRotationAnimation screenRotationAnimation =
-                mAnimator.getScreenRotationAnimationLocked(displayId);
+        ScreenRotationAnimation screenRotationAnimation = displayContent == null ? null
+                : displayContent.getRotationAnimation();
         if (screenRotationAnimation != null && screenRotationAnimation.hasScreenshot()) {
-            if (DEBUG_ORIENTATION) Slog.i(TAG_WM, "**** Dismissing screen rotation animation");
+            ProtoLog.i(WM_DEBUG_ORIENTATION, "**** Dismissing screen rotation animation");
             DisplayInfo displayInfo = displayContent.getDisplayInfo();
             // Get rotation animation again, with new top window
             if (!displayContent.getDisplayRotation().validateRotationAnimation(
@@ -5458,16 +5430,15 @@
                     getTransitionAnimationScaleLocked(), displayInfo.logicalWidth,
                         displayInfo.logicalHeight, mExitAnimId, mEnterAnimId)) {
                 mTransaction.apply();
-                scheduleAnimationLocked();
             } else {
                 screenRotationAnimation.kill();
-                mAnimator.setScreenRotationAnimationLocked(displayId, null);
+                displayContent.setRotationAnimation(null);
                 updateRotation = true;
             }
         } else {
             if (screenRotationAnimation != null) {
                 screenRotationAnimation.kill();
-                mAnimator.setScreenRotationAnimationLocked(displayId, null);
+                displayContent.setRotationAnimation(null);
             }
             updateRotation = true;
         }
@@ -5491,7 +5462,7 @@
         mScreenFrozenLock.release();
 
         if (updateRotation && displayContent != null) {
-            if (DEBUG_ORIENTATION) Slog.d(TAG_WM, "Performing post-rotate rotation");
+            ProtoLog.d(WM_DEBUG_ORIENTATION, "Performing post-rotate rotation");
             configChanged |= displayContent.updateRotationUnchecked();
         }
 
@@ -5520,7 +5491,7 @@
         return val;
     }
 
-    void createWatermarkInTransaction() {
+    void createWatermark() {
         if (mWatermark != null) {
             return;
         }
@@ -5538,8 +5509,8 @@
                     // TODO(multi-display): Show watermarks on secondary displays.
                     final DisplayContent displayContent = getDefaultDisplayContentLocked();
                     mWatermark = new Watermark(mSurfaceFactory, displayContent,
-                            displayContent.mRealDisplayMetrics,
-                            toks);
+                            displayContent.mRealDisplayMetrics, toks, mTransaction);
+                    mTransaction.apply();
                 }
             }
         } catch (FileNotFoundException e) {
@@ -5582,16 +5553,6 @@
     }
 
     @Override
-    public void setShelfHeight(boolean visible, int shelfHeight) {
-        mAtmInternal.enforceCallerIsRecentsOrHasPermission(android.Manifest.permission.STATUS_BAR,
-                "setShelfHeight()");
-        synchronized (mGlobalLock) {
-            getDefaultDisplayContentLocked().getPinnedStackController().setAdjustedForShelf(visible,
-                    shelfHeight);
-        }
-    }
-
-    @Override
     public void statusBarVisibilityChanged(int displayId, int visibility) {
         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.STATUS_BAR)
                 != PackageManager.PERMISSION_GRANTED) {
@@ -5811,6 +5772,11 @@
         pw.print(mWindowTracing.getStatus() + "\n");
     }
 
+    private void dumpLogStatus(PrintWriter pw) {
+        pw.println("WINDOW MANAGER LOGGING (dumpsys window logging)");
+        pw.println(ProtoLogImpl.getSingleInstance().getStatus());
+    }
+
     private void dumpSessionsLocked(PrintWriter pw, boolean dumpAll) {
         pw.println("WINDOW MANAGER SESSIONS (dumpsys window sessions)");
         for (int i=0; i<mSessions.size(); i++) {
@@ -5939,13 +5905,18 @@
                 }
             }
         }
-        if (mWaitingForDrawn.size() > 0) {
+        if (!mWaitingForDrawnCallbacks.isEmpty()) {
             pw.println();
             pw.println("  Clients waiting for these windows to be drawn:");
-            for (int i=mWaitingForDrawn.size()-1; i>=0; i--) {
-                WindowState win = mWaitingForDrawn.get(i);
-                pw.print("  Waiting #"); pw.print(i); pw.print(' '); pw.print(win);
-            }
+            mWaitingForDrawnCallbacks.forEach((wc, callback) -> {
+                pw.print("  WindowContainer ");
+                pw.println(wc.getName());
+                for (int i = wc.mWaitingForDrawn.size() - 1; i >= 0; i--) {
+                    final WindowState win = (WindowState) wc.mWaitingForDrawn.get(i);
+                    pw.print("  Waiting #"); pw.print(i); pw.print(' '); pw.print(win);
+                }
+            });
+
         }
         pw.println();
         pw.print("  mGlobalConfiguration="); pw.println(mRoot.getConfiguration());
@@ -6206,6 +6177,9 @@
             } else if ("trace".equals(cmd)) {
                 dumpTraceStatus(pw);
                 return;
+            } else if ("logging".equals(cmd)) {
+                dumpLogStatus(pw);
+                return;
             } else if ("refresh".equals(cmd)) {
                 dumpHighRefreshRateBlacklist(pw);
                 return;
@@ -6267,6 +6241,10 @@
             if (dumpAll) {
                 pw.println(separator);
             }
+            dumpLogStatus(pw);
+            if (dumpAll) {
+                pw.println(separator);
+            }
             dumpHighRefreshRateBlacklist(pw);
         }
     }
@@ -6302,17 +6280,20 @@
     /**
      * Hint to a token that its activity will relaunch, which will trigger removal and addition of
      * a window.
+     *
      * @param token Application token for which the activity will be relaunched.
      */
     void setWillReplaceWindow(IBinder token, boolean animate) {
         final AppWindowToken appWindowToken = mRoot.getAppWindowToken(token);
         if (appWindowToken == null) {
-            Slog.w(TAG_WM, "Attempted to set replacing window on non-existing app token " + token);
+            ProtoLog.w(WM_ERROR, "Attempted to set replacing window on non-existing app token %s",
+                    token);
             return;
         }
         if (!appWindowToken.hasContentToDisplay()) {
-            Slog.w(TAG_WM, "Attempted to set replacing window on app token with no content"
-                    + token);
+            ProtoLog.w(WM_ERROR,
+                    "Attempted to set replacing window on app token with no content %s",
+                    token);
             return;
         }
         appWindowToken.setWillReplaceWindows(animate);
@@ -6334,13 +6315,15 @@
         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 "
-                        + token);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to set replacing window on non-existing app token %s",
+                        token);
                 return;
             }
             if (!appWindowToken.hasContentToDisplay()) {
-                Slog.w(TAG_WM, "Attempted to set replacing window on app token with no content"
-                        + token);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to set replacing window on app token with no content %s",
+                        token);
                 return;
             }
 
@@ -6360,14 +6343,14 @@
      *
      * If we're not replacing the window, clear the replace window settings of the app.
      *
-     * @param token Application token for the activity whose window might be replaced.
+     * @param token     Application token for the activity whose window might be replaced.
      * @param replacing Whether the window is being replaced or not.
      */
     void scheduleClearWillReplaceWindows(IBinder token, boolean replacing) {
         final AppWindowToken appWindowToken = mRoot.getAppWindowToken(token);
         if (appWindowToken == null) {
-            Slog.w(TAG_WM, "Attempted to reset replacing window on non-existing app token "
-                    + token);
+            ProtoLog.w(WM_ERROR, "Attempted to reset replacing window on non-existing app token %s",
+                    token);
             return;
         }
         if (replacing) {
@@ -6556,7 +6539,7 @@
             }
             WindowState callingWin = windowForClientLocked(null, client, false);
             if (callingWin == null) {
-                Slog.w(TAG_WM, "Bad requesting window " + client);
+                ProtoLog.w(WM_ERROR, "Bad requesting window %s", client);
                 return;
             }
             final DisplayContent displayContent = callingWin.getDisplayContent();
@@ -6573,7 +6556,7 @@
                         windowUnderPointer.translateToWindowX(mouseX),
                         windowUnderPointer.translateToWindowY(mouseY));
             } catch (RemoteException e) {
-                Slog.w(TAG_WM, "unable to update pointer icon");
+                ProtoLog.w(WM_ERROR, "unable to update pointer icon");
             }
         }
     }
@@ -6590,7 +6573,7 @@
                         windowUnderPointer.translateToWindowX(latestX),
                         windowUnderPointer.translateToWindowY(latestY));
             } catch (RemoteException e) {
-                Slog.w(TAG_WM, "unable to restore pointer icon");
+                ProtoLog.w(WM_ERROR, "unable to restore pointer icon");
             }
         } else {
             InputManager.getInstance().setPointerIconType(PointerIcon.TYPE_DEFAULT);
@@ -6620,7 +6603,7 @@
             try {
                 final WindowState win = windowForClientLocked(null, client, false);
                 if (win == null) {
-                    Slog.w(TAG_WM, "Bad requesting window " + client);
+                    ProtoLog.w(WM_ERROR, "Bad requesting window %s", client);
                     return;
                 }
                 getDisplayContentOrCreate(displayId, null).reparentDisplayContent(win, sc);
@@ -6645,7 +6628,7 @@
             try {
                 final WindowState win = windowForClientLocked(null, client, false);
                 if (win == null) {
-                    Slog.w(TAG_WM, "Bad requesting window " + client);
+                    ProtoLog.w(WM_ERROR, "Bad requesting window %s", client);
                     return;
                 }
                 final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
@@ -6672,7 +6655,7 @@
         synchronized (mGlobalLock) {
             final WindowState callingWin = windowForClientLocked(null, client, false);
             if (callingWin == null) {
-                Slog.w(TAG_WM, "Bad requesting window " + client);
+                ProtoLog.w(WM_ERROR, "Bad requesting window %s", client);
                 return;
             }
             callingWin.updateTapExcludeRegion(regionId, region);
@@ -6711,8 +6694,9 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to get windowing mode of a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to get windowing mode of a display that does not exist: %d",
+                        displayId);
                 return WindowConfiguration.WINDOWING_MODE_UNDEFINED;
             }
             return mDisplayWindowSettings.getWindowingModeLocked(displayContent);
@@ -6728,8 +6712,9 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = getDisplayContentOrCreate(displayId, null);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to set windowing mode to a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to set windowing mode to a display that does not exist: %d",
+                        displayId);
                 return;
             }
 
@@ -6764,8 +6749,9 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to get remove mode of a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to get remove mode of a display that does not exist: %d",
+                        displayId);
                 return REMOVE_CONTENT_MODE_UNDEFINED;
             }
             return mDisplayWindowSettings.getRemoveContentModeLocked(displayContent);
@@ -6781,8 +6767,9 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = getDisplayContentOrCreate(displayId, null);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to set remove mode to a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to set remove mode to a display that does not exist: %d",
+                        displayId);
                 return;
             }
 
@@ -6801,8 +6788,8 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to get flag of a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR, "Attempted to get flag of a display that does not exist: %d",
+                        displayId);
                 return false;
             }
             return mDisplayWindowSettings.shouldShowWithInsecureKeyguardLocked(displayContent);
@@ -6819,8 +6806,8 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = getDisplayContentOrCreate(displayId, null);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to set flag to a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR, "Attempted to set flag to a display that does not exist: %d",
+                        displayId);
                 return;
             }
 
@@ -6840,8 +6827,8 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to get system decors flag of a display that does "
-                        + "not exist: " + displayId);
+                ProtoLog.w(WM_ERROR, "Attempted to get system decors flag of a display that does "
+                        + "not exist: %d", displayId);
                 return false;
             }
             if (displayContent.isUntrustedVirtualDisplay()) {
@@ -6860,8 +6847,8 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = getDisplayContentOrCreate(displayId, null);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to set system decors flag to a display that does "
-                        + "not exist: " + displayId);
+                ProtoLog.w(WM_ERROR, "Attempted to set system decors flag to a display that does "
+                        + "not exist: %d", displayId);
                 return;
             }
             if (displayContent.isUntrustedVirtualDisplay()) {
@@ -6884,8 +6871,9 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to get IME flag of a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to get IME flag of a display that does not exist: %d",
+                        displayId);
                 return false;
             }
             if (displayContent.isUntrustedVirtualDisplay()) {
@@ -6905,8 +6893,9 @@
         synchronized (mGlobalLock) {
             final DisplayContent displayContent = getDisplayContentOrCreate(displayId, null);
             if (displayContent == null) {
-                Slog.w(TAG_WM, "Attempted to set IME flag to a display that does not exist: "
-                        + displayId);
+                ProtoLog.w(WM_ERROR,
+                        "Attempted to set IME flag to a display that does not exist: %d",
+                        displayId);
                 return;
             }
             if (displayContent.isUntrustedVirtualDisplay()) {
@@ -7083,17 +7072,25 @@
         }
 
         @Override
-        public void waitForAllWindowsDrawn(Runnable callback, long timeout) {
+        public void waitForAllWindowsDrawn(Runnable callback, long timeout, int displayId) {
+            final WindowContainer container = displayId == INVALID_DISPLAY
+                    ? mRoot : mRoot.getDisplayContent(displayId);
+            if (container == null) {
+                // The waiting container doesn't exist, no need to wait to run the callback. Run and
+                // return;
+                callback.run();
+                return;
+            }
             boolean allWindowsDrawn = false;
             synchronized (mGlobalLock) {
-                mWaitingForDrawnCallback = callback;
-                getDefaultDisplayContentLocked().waitForAllWindowsDrawn();
+                container.waitForAllWindowsDrawn();
                 mWindowPlacerLocked.requestTraversal();
-                mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT);
-                if (mWaitingForDrawn.isEmpty()) {
+                mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT, container);
+                if (container.mWaitingForDrawn.isEmpty()) {
                     allWindowsDrawn = true;
                 } else {
-                    mH.sendEmptyMessageDelayed(H.WAITING_FOR_DRAWN_TIMEOUT, timeout);
+                    mWaitingForDrawnCallbacks.put(container, callback);
+                    mH.sendNewMessageDelayed(H.WAITING_FOR_DRAWN_TIMEOUT, container, timeout);
                     checkDrawnWindowsLocked();
                 }
             }
@@ -7123,15 +7120,16 @@
                 if (removeWindows) {
                     final DisplayContent dc = mRoot.getDisplayContent(displayId);
                     if (dc == null) {
-                        Slog.w(TAG_WM, "removeWindowToken: Attempted to remove token: " + binder
-                                + " for non-exiting displayId=" + displayId);
+                        ProtoLog.w(WM_ERROR, "removeWindowToken: Attempted to remove token: %s"
+                                + " for non-exiting displayId=%d", binder, displayId);
                         return;
                     }
 
                     final WindowToken token = dc.removeWindowToken(binder);
                     if (token == null) {
-                        Slog.w(TAG_WM, "removeWindowToken: Attempted to remove non-existing token: "
-                                + binder);
+                        ProtoLog.w(WM_ERROR,
+                                "removeWindowToken: Attempted to remove non-existing token: %s",
+                                binder);
                         return;
                     }
 
@@ -7289,6 +7287,29 @@
         }
 
         @Override
+        public void showImePostLayout(IBinder imeTargetWindowToken) {
+            synchronized (mGlobalLock) {
+                final WindowState imeTarget = mWindowMap.get(imeTargetWindowToken);
+                if (imeTarget == null) {
+                    return;
+                }
+                final DisplayContent displayContent = imeTarget.getDisplayContent();
+                if (displayContent == null) {
+                    Slog.w(TAG_WM, "Attempted to show IME on an IME target that does not exist: "
+                            + imeTarget.getName());
+                    return;
+                }
+                if (displayContent.isUntrustedVirtualDisplay()) {
+                    throw new SecurityException("Attempted to show IME on an untrusted "
+                            + "virtual display: " + displayContent.getDisplayId());
+                }
+
+                displayContent.getInsetsStateController().getImeSourceProvider()
+                        .scheduleShowImePostLayout(imeTarget);
+            }
+        }
+
+        @Override
         public boolean isUidAllowedOnDisplay(int displayId, int uid) {
             if (displayId == Display.DEFAULT_DISPLAY) {
                 return true;
@@ -7360,6 +7381,11 @@
                         && configuration.touchscreen == Configuration.TOUCHSCREEN_FINGER;
             }
         }
+
+        @Override
+        public @Nullable KeyInterceptionInfo getKeyInterceptionInfoFromToken(IBinder inputToken) {
+            return mKeyInterceptionInfoForToken.get(inputToken);
+        }
     }
 
     void registerAppFreezeListener(AppFreezeListener listener) {
@@ -7617,7 +7643,7 @@
             // to do so because it seems possible to resume activities as part of a larger
             // transaction and it's too early to resume based on current order when performing
             // updateTopResumedActivityIfNeeded().
-            displayContent.mAcitvityDisplay.ensureActivitiesVisible(null /* starting */,
+            displayContent.mActivityDisplay.ensureActivitiesVisible(null /* starting */,
                     0 /* configChanges */, !PRESERVE_WINDOWS, true /* notifyClients */);
         }
     }
@@ -7729,4 +7755,27 @@
             Binder.restoreCallingIdentity(token);
         }
     }
+
+    @Override
+    public boolean mirrorDisplay(int displayId, SurfaceControl outSurfaceControl) {
+        if (!checkCallingPermission(ACCESS_SURFACE_FLINGER, "mirrorDisplay()")) {
+            throw new SecurityException("Requires ACCESS_SURFACE_FLINGER permission");
+        }
+
+        final SurfaceControl displaySc;
+        synchronized (mGlobalLock) {
+            DisplayContent displayContent = mRoot.getDisplayContent(displayId);
+            if (displayContent == null) {
+                Slog.e(TAG, "Invalid displayId " + displayId + " for mirrorDisplay");
+                return false;
+            }
+
+            displaySc = displayContent.getSurfaceControl();
+        }
+
+        final SurfaceControl mirror = SurfaceControl.mirrorSurface(displaySc);
+        outSurfaceControl.copyFrom(mirror);
+
+        return true;
+    }
 }
diff --git a/services/core/java/com/android/server/wm/WindowManagerShellCommand.java b/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
index 7384bb7..e01cbf2 100644
--- a/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
+++ b/services/core/java/com/android/server/wm/WindowManagerShellCommand.java
@@ -28,6 +28,8 @@
 import android.view.IWindowManager;
 import android.view.Surface;
 
+import com.android.server.protolog.ProtoLogImpl;
+
 import java.io.PrintWriter;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -75,6 +77,8 @@
                     // the output trace file, so the shell gets the correct semantics for where
                     // trace files can be written.
                     return mInternal.mWindowTracing.onShellCommand(this);
+                case "logging":
+                    return ProtoLogImpl.getSingleInstance().onShellCommand(this);
                 case "set-user-rotation":
                     return runSetDisplayUserRotation(pw);
                 case "set-fix-to-user-rotation":
@@ -389,6 +393,8 @@
         if (!IS_USER) {
             pw.println("  tracing (start | stop)");
             pw.println("    Start or stop window tracing.");
+            pw.println("  logging (start | stop | enable | disable | enable-text | disable-text)");
+            pw.println("    Logging settings.");
         }
     }
 }
diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
index d7116d8..1c0d156 100644
--- a/services/core/java/com/android/server/wm/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -702,7 +702,7 @@
         }
         ActivityRecord hist = mActivities.get(0);
         intent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP, hist.packageName);
-        intent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK, hist.getTaskRecord().taskId);
+        intent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK, hist.getTaskRecord().mTaskId);
     }
 
     boolean shouldKillProcessForRemovedTask(TaskRecord tr) {
@@ -713,7 +713,7 @@
                 return false;
             }
             final TaskRecord otherTask = activity.getTaskRecord();
-            if (tr.taskId != otherTask.taskId && otherTask.inRecents) {
+            if (tr.mTaskId != otherTask.mTaskId && otherTask.inRecents) {
                 // Don't kill process(es) that has an activity in a different task that is
                 // also in recents.
                 return false;
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 501a93e..56e08b2 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -90,20 +90,20 @@
 import static com.android.server.wm.MoveAnimationSpecProto.DURATION_MS;
 import static com.android.server.wm.MoveAnimationSpecProto.FROM;
 import static com.android.server.wm.MoveAnimationSpecProto.TO;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_RESIZE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_STARTING_WINDOW;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_CONFIGURATION;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_INPUT_METHOD;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_POWER;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RESIZE;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW_VERBOSE;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
@@ -197,14 +197,17 @@
 import android.view.View;
 import android.view.ViewTreeObserver;
 import android.view.WindowInfo;
+import android.view.WindowInsets.Type.InsetType;
 import android.view.WindowManager;
 import android.view.animation.Animation;
 import android.view.animation.AnimationUtils;
 import android.view.animation.Interpolator;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.policy.KeyInterceptionInfo;
 import com.android.internal.util.ToBooleanFunction;
 import com.android.server.policy.WindowManagerPolicy;
+import com.android.server.protolog.common.ProtoLog;
 import com.android.server.wm.LocalAnimationAdapter.AnimationSpec;
 import com.android.server.wm.utils.InsetUtils;
 import com.android.server.wm.utils.WmDisplayCutout;
@@ -633,6 +636,7 @@
     private @Nullable InsetsSourceProvider mInsetProvider;
 
     private static final float DEFAULT_DIM_AMOUNT_DEAD_WINDOW = 0.5f;
+    private KeyInterceptionInfo mKeyInterceptionInfo;
 
     void seamlesslyRotateIfAllowed(Transaction transaction, @Rotation int oldRotation,
             @Rotation int rotation, boolean requested) {
@@ -779,7 +783,7 @@
             mSubLayer = mPolicy.getSubWindowLayerFromTypeLw(a.type);
             mIsChildWindow = true;
 
-            if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to " + parentWindow);
+            ProtoLog.v(WM_DEBUG_ADD_REMOVE, "Adding %s to %s", this, parentWindow);
             parentWindow.addChild(this, sWindowSubLayerComparator);
 
             mLayoutAttached = mAttrs.type !=
@@ -832,7 +836,7 @@
      */
     boolean inSizeCompatMode() {
         return (mAttrs.privateFlags & PRIVATE_FLAG_COMPATIBLE_WINDOW) != 0
-                || (mAppToken != null && mAppToken.inSizeCompatMode()
+                || (mAppToken != null && mAppToken.hasSizeCompatBounds()
                         // Exclude starting window because it is not displayed by the application.
                         && mAttrs.type != TYPE_APPLICATION_STARTING);
     }
@@ -1292,14 +1296,11 @@
                 || configChanged
                 || dragResizingChanged
                 || mReportOrientationChanged) {
-            if (DEBUG_RESIZE || DEBUG_ORIENTATION) {
-                Slog.v(TAG_WM, "Resize reasons for w=" + this + ": "
-                        + " " + mWindowFrames.getInsetsChangedInfo()
-                        + " surfaceResized=" + winAnimator.mSurfaceResized
-                        + " configChanged=" + configChanged
-                        + " dragResizingChanged=" + dragResizingChanged
-                        + " reportOrientationChanged=" + mReportOrientationChanged);
-            }
+            ProtoLog.v(WM_DEBUG_RESIZE,
+                        "Resize reasons for w=%s:  %s surfaceResized=%b configChanged=%b "
+                                + "dragResizingChanged=%b reportOrientationChanged=%b",
+                        this, mWindowFrames.getInsetsChangedInfo(), winAnimator.mSurfaceResized,
+                        configChanged, dragResizingChanged, mReportOrientationChanged);
 
             // If it's a dead window left on screen, and the configuration changed, there is nothing
             // we can do about it. Remove the window now.
@@ -1316,24 +1317,31 @@
             // redrawn; to do that, we need to go through the process of getting informed by the
             // application when it has finished drawing.
             if (getOrientationChanging() || dragResizingChanged) {
-                if (DEBUG_ANIM || DEBUG_ORIENTATION || DEBUG_RESIZE) {
-                    Slog.v(TAG_WM, "Orientation or resize start waiting for draw"
+                if (getOrientationChanging()) {
+                    Slog.v(TAG_WM, "Orientation start waiting for draw"
                             + ", mDrawState=DRAW_PENDING in " + this
                             + ", surfaceController " + winAnimator.mSurfaceController);
                 }
+                if (dragResizingChanged) {
+                    ProtoLog.v(WM_DEBUG_RESIZE,
+                            "Resize start waiting for draw, "
+                                    + "mDrawState=DRAW_PENDING in %s, surfaceController %s",
+                            this, winAnimator.mSurfaceController);
+                }
                 winAnimator.mDrawState = DRAW_PENDING;
                 if (mAppToken != null) {
                     mAppToken.clearAllDrawn();
                 }
             }
             if (!mWmService.mResizingWindows.contains(this)) {
-                if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG_WM, "Resizing window " + this);
+                ProtoLog.v(WM_DEBUG_RESIZE, "Resizing window %s", this);
                 mWmService.mResizingWindows.add(this);
             }
         } else if (getOrientationChanging()) {
             if (isDrawnLw()) {
-                if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "Orientation not waiting for draw in "
-                        + this + ", surfaceController " + winAnimator.mSurfaceController);
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
+                        "Orientation not waiting for draw in %s, surfaceController %s", this,
+                        winAnimator.mSurfaceController);
                 setOrientationChanging(false);
                 mLastFreezeDuration = (int)(SystemClock.elapsedRealtime()
                         - mWmService.mDisplayFreezeTime);
@@ -1703,7 +1711,7 @@
 
     @Override
     void onMovedByResize() {
-        if (DEBUG_RESIZE) Slog.d(TAG, "onMovedByResize: Moving " + this);
+        ProtoLog.d(WM_DEBUG_RESIZE, "onMovedByResize: Moving %s", this);
         mMovedByResize = true;
         super.onMovedByResize();
     }
@@ -1777,7 +1785,7 @@
     void onResize() {
         final ArrayList<WindowState> resizingWindows = mWmService.mResizingWindows;
         if (mHasSurface && !isGoneForLayoutLw() && !resizingWindows.contains(this)) {
-            if (DEBUG_RESIZE) Slog.d(TAG, "onResize: Resizing " + this);
+            ProtoLog.d(WM_DEBUG_RESIZE, "onResize: Resizing %s", this);
             resizingWindows.add(this);
         }
         if (isGoneForLayoutLw()) {
@@ -1920,8 +1928,8 @@
 
         if (mRemoved) {
             // Nothing to do.
-            if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
-                    "WS.removeImmediately: " + this + " Already removed...");
+            ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                    "WS.removeImmediately: %s Already removed...", this);
             return;
         }
 
@@ -1971,39 +1979,35 @@
 
     private void removeIfPossible(boolean keepVisibleDeadWindow) {
         mWindowRemovalAllowed = true;
-        if (DEBUG_ADD_REMOVE) Slog.v(TAG,
-                "removeIfPossible: " + this + " callers=" + Debug.getCallers(5));
+        ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                "removeIfPossible: %s callers=%s", this, Debug.getCallers(5));
 
         final boolean startingWindow = mAttrs.type == TYPE_APPLICATION_STARTING;
-        if (startingWindow && DEBUG_STARTING_WINDOW) Slog.d(TAG_WM,
-                "Starting window removed " + this);
-
-        if (DEBUG || DEBUG_FOCUS || DEBUG_FOCUS_LIGHT && isFocused()) {
-            Slog.v(TAG_WM, "Remove " + this + " client="
-                    + Integer.toHexString(System.identityHashCode(mClient.asBinder()))
-                    + ", surfaceController=" + mWinAnimator.mSurfaceController + " Callers="
-                    + Debug.getCallers(5));
+        if (startingWindow) {
+            ProtoLog.d(WM_DEBUG_STARTING_WINDOW, "Starting window removed %s", this);
         }
 
+        ProtoLog.v(WM_DEBUG_FOCUS, "Remove client=%x, surfaceController=%s Callers=%s",
+                    System.identityHashCode(mClient.asBinder()),
+                    mWinAnimator.mSurfaceController,
+                    Debug.getCallers(5));
+
+
         final long origId = Binder.clearCallingIdentity();
 
         try {
             disposeInputChannel();
 
-            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG_WM, "Remove " + this
-                    + ": mSurfaceController=" + mWinAnimator.mSurfaceController
-                    + " mAnimatingExit=" + mAnimatingExit
-                    + " mRemoveOnExit=" + mRemoveOnExit
-                    + " mHasSurface=" + mHasSurface
-                    + " surfaceShowing=" + mWinAnimator.getShown()
-                    + " animating=" + isAnimating()
-                    + " app-animation="
-                    + (mAppToken != null ? mAppToken.isSelfAnimating() : "false")
-                    + " mWillReplaceWindow=" + mWillReplaceWindow
-                    + " inPendingTransaction="
-                    + (mAppToken != null ? mAppToken.inPendingTransaction : false)
-                    + " mDisplayFrozen=" + mWmService.mDisplayFrozen
-                    + " callers=" + Debug.getCallers(6));
+            ProtoLog.v(WM_DEBUG_APP_TRANSITIONS,
+                    "Remove %s: mSurfaceController=%s mAnimatingExit=%b mRemoveOnExit=%b "
+                            + "mHasSurface=%b surfaceShowing=%b animating=%b app-animation=%b "
+                            + "mWillReplaceWindow=%b inPendingTransaction=%b mDisplayFrozen=%b "
+                            + "callers=%s",
+                    this, mWinAnimator.mSurfaceController, mAnimatingExit, mRemoveOnExit,
+                    mHasSurface, mWinAnimator.getShown(), isAnimating(),
+                    mAppToken != null && mAppToken.isSelfAnimating(), mWillReplaceWindow,
+                    mAppToken != null && mAppToken.inPendingTransaction,
+                    mWmService.mDisplayFrozen, Debug.getCallers(6));
 
             // Visibility of the removed window. Will be used later to update orientation later on.
             boolean wasVisible = false;
@@ -2015,8 +2019,8 @@
                 if (mWillReplaceWindow) {
                     // This window is going to be replaced. We need to keep it around until the new one
                     // gets added, then we will get rid of this one.
-                    if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
-                            "Preserving " + this + " until the new one is " + "added");
+                    ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                            "Preserving %s until the new one is added", this);
                     // TODO: We are overloading mAnimatingExit flag to prevent the window state from
                     // been removed. We probably need another flag to indicate that window removal
                     // should be deffered vs. overloading the flag that says we are playing an exit
@@ -2030,8 +2034,8 @@
                 wasVisible = isWinVisibleLw();
 
                 if (keepVisibleDeadWindow) {
-                    if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
-                            "Not removing " + this + " because app died while it's visible");
+                    ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                            "Not removing %s because app died while it's visible", this);
 
                     mAppDied = true;
                     setDisplayLayoutNeeded();
@@ -2072,8 +2076,8 @@
                 if (mWinAnimator.getShown() && mAnimatingExit
                         && (!lastWindowIsStartingWindow || isAnimating)) {
                     // The exit animation is running or should run... wait for it!
-                    if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM,
-                            "Not removing " + this + " due to exit animation ");
+                    ProtoLog.v(WM_DEBUG_ADD_REMOVE,
+                            "Not removing %s due to exit animation", this);
                     setupWindowForRemoveOnExit();
                     if (mAppToken != null) {
                         mAppToken.updateReportedVisibilityLocked();
@@ -2218,6 +2222,7 @@
             mClientChannel.dispose();
             mClientChannel = null;
         }
+        mWmService.mKeyInterceptionInfoForToken.remove(mInputWindowHandle.token);
         mInputWindowHandle.token = null;
     }
 
@@ -2239,7 +2244,7 @@
     }
 
     private void removeReplacedWindow() {
-        if (DEBUG_ADD_REMOVE) Slog.d(TAG, "Removing replaced window: " + this);
+        ProtoLog.d(WM_DEBUG_ADD_REMOVE, "Removing replaced window: %s", this);
         mWillReplaceWindow = false;
         mAnimateReplacingWindow = false;
         mReplacingRemoveRequested = false;
@@ -2315,7 +2320,7 @@
             }
             // The offset of compatibility bounds is applied to surface of {@link #AppWindowToken}
             // and frame, so it is unnecessary to translate twice in surface based coordinates.
-            final int surfaceOffsetX = mAppToken.inSizeCompatMode()
+            final int surfaceOffsetX = mAppToken.hasSizeCompatBounds()
                     ? mAppToken.getBounds().left : 0;
             mTmpRect.offset(surfaceOffsetX - mWindowFrames.mFrame.left, -mWindowFrames.mFrame.top);
             region.set(mTmpRect);
@@ -2395,7 +2400,7 @@
             if (!isVisibleByPolicy()) {
                 mWinAnimator.hide("checkPolicyVisibilityChange");
                 if (isFocused()) {
-                    if (DEBUG_FOCUS_LIGHT) Slog.i(TAG,
+                    ProtoLog.i(WM_DEBUG_FOCUS_LIGHT,
                             "setAnimationLocked: setting mFocusMayChange true");
                     mWmService.mFocusMayChange = true;
                 }
@@ -2419,15 +2424,15 @@
     void prepareWindowToDisplayDuringRelayout(boolean wasVisible) {
         // We need to turn on screen regardless of visibility.
         final boolean hasTurnScreenOnFlag = (mAttrs.flags & FLAG_TURN_SCREEN_ON) != 0
-                || (mAppToken != null && mAppToken.mActivityRecord.canTurnScreenOn());
+                || (mAppToken != null && mAppToken.canTurnScreenOn());
 
         // The screen will turn on if the following conditions are met
         // 1. The window has the flag FLAG_TURN_SCREEN_ON or ActivityRecord#canTurnScreenOn.
         // 2. The WMS allows theater mode.
         // 3. No AWT or the AWT allows the screen to be turned on. This should only be true once
         // per resume to prevent the screen getting getting turned on for each relayout. Set
-        // canTurnScreenOn will be set to false so the window doesn't turn the screen on again
-        // during this resume.
+        // currentLaunchCanTurnScreenOn will be set to false so the window doesn't turn the screen
+        // on again during this resume.
         // 4. When the screen is not interactive. This is because when the screen is already
         // interactive, the value may persist until the next animation, which could potentially
         // be occurring while turning off the screen. This would lead to the screen incorrectly
@@ -2612,15 +2617,31 @@
     @Override
     public boolean canShowWhenLocked() {
         final boolean showBecauseOfActivity =
-                mAppToken != null && mAppToken.mActivityRecord.canShowWhenLocked();
+                mAppToken != null && mAppToken.canShowWhenLocked();
         final boolean showBecauseOfWindow = (getAttrs().flags & FLAG_SHOW_WHEN_LOCKED) != 0;
         return showBecauseOfActivity || showBecauseOfWindow;
     }
 
     /** @return false if this window desires touch events. */
     boolean cantReceiveTouchInput() {
-        return mAppToken != null && mAppToken.getTask() != null
-                && (mAppToken.getTask().mStack.shouldIgnoreInput() || mAppToken.hiddenRequested);
+        if (mAppToken == null || mAppToken.getTask() == null) {
+            return false;
+        }
+
+        return mAppToken.getTask().mStack.shouldIgnoreInput()
+                || mAppToken.hiddenRequested
+                || isAnimatingToRecents();
+    }
+
+    /**
+     * Returns {@code true} if the window is animating to home as part of the recents animation.
+     */
+    private boolean isAnimatingToRecents() {
+        final RecentsAnimationController recentsAnimationController =
+                mWmService.getRecentsAnimationController();
+        return recentsAnimationController != null
+                && recentsAnimationController.isAnimatingTask(getTask())
+                && !recentsAnimationController.isTargetApp(mAppToken);
     }
 
     @Override
@@ -2718,7 +2739,7 @@
             // we allow the display to be enabled now.
             mWmService.enableScreenIfNeededLocked();
             if (isFocused) {
-                if (DEBUG_FOCUS_LIGHT) Slog.i(TAG,
+                ProtoLog.i(WM_DEBUG_FOCUS_LIGHT,
                         "WindowState.hideLw: setting mFocusMayChange true");
                 mWmService.mFocusMayChange = true;
             }
@@ -2924,7 +2945,8 @@
 
         if (mHasSurface && !getOrientationChanging()
                 && mWmService.mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_TIMEOUT) {
-            if (DEBUG_ORIENTATION) Slog.v(TAG_WM, "set mOrientationChanging of " + this);
+            ProtoLog.v(WM_DEBUG_ORIENTATION,
+                    "set mOrientationChanging of %s", this);
             setOrientationChanging(true);
             mWmService.mRoot.mOrientationChangeComplete = false;
         }
@@ -2952,10 +2974,11 @@
         }
 
         if (mDestroying) {
-            if (DEBUG_ADD_REMOVE) Slog.e(TAG_WM, "win=" + this
-                    + " destroySurfaces: appStopped=" + appStopped
-                    + " win.mWindowRemovalAllowed=" + mWindowRemovalAllowed
-                    + " win.mRemoveOnExit=" + mRemoveOnExit);
+            ProtoLog.e(WM_DEBUG_ADD_REMOVE, "win=%s"
+                    + " destroySurfaces: appStopped=%b"
+                    + " win.mWindowRemovalAllowed=%b"
+                    + " win.mRemoveOnExit=%b", this, appStopped,
+                    mWindowRemovalAllowed, mRemoveOnExit);
             if (!cleanupOnResume || mRemoveOnExit) {
                 destroySurfaceUnchecked();
             }
@@ -3223,16 +3246,19 @@
     void reportResized() {
         Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "wm.reportResized_" + getWindowTag());
         try {
-            if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG, "Reporting new frame to " + this
-                    + ": " + mWindowFrames.mCompatFrame);
+            ProtoLog.v(WM_DEBUG_RESIZE,
+                    "Reporting new frame to %s: %s", this,
+                            mWindowFrames.mCompatFrame);
             final MergedConfiguration mergedConfiguration =
                     new MergedConfiguration(mWmService.mRoot.getConfiguration(),
                     getMergedOverrideConfiguration());
 
             setLastReportedMergedConfiguration(mergedConfiguration);
 
-            if (DEBUG_ORIENTATION && mWinAnimator.mDrawState == DRAW_PENDING)
-                Slog.i(TAG, "Resizing " + this + " WITH DRAW PENDING");
+            if (mWinAnimator.mDrawState == DRAW_PENDING) {
+                ProtoLog.i(WM_DEBUG_ORIENTATION,
+                        "Resizing %s WITH DRAW PENDING", this);
+            }
 
             final Rect frame = mWindowFrames.mCompatFrame;
             final Rect overscanInsets = mWindowFrames.mLastOverscanInsets;
@@ -3340,6 +3366,15 @@
         }
     }
 
+    @Override
+    public void showInsets(@InsetType int types, boolean fromIme) {
+        try {
+            mClient.showInsets(types, fromIme);
+        } catch (RemoteException e) {
+            Slog.w(TAG, "Failed to deliver showInsets", e);
+        }
+    }
+
     Rect getBackdropFrame(Rect frame) {
         // When the task is docked, we send fullscreen sized backDropFrame as soon as resizing
         // start even if we haven't received the relayout window, so that the client requests
@@ -3462,7 +3497,7 @@
     @Override
     void setWaitingForDrawnIfResizingChanged() {
         if (isDragResizeChanged()) {
-            mWmService.mWaitingForDrawn.add(this);
+            mWmService.mRoot.mWaitingForDrawn.add(this);
         }
         super.setWaitingForDrawnIfResizingChanged();
     }
@@ -4375,9 +4410,8 @@
             return;
         }
 
-        if (DEBUG || DEBUG_ADD_REMOVE) {
-            Slog.v(TAG, "Exit animation finished in " + this + ": remove=" + mRemoveOnExit);
-        }
+        ProtoLog.v(WM_DEBUG_ADD_REMOVE, "Exit animation finished in %s: remove=%b",
+                this, mRemoveOnExit);
 
         mDestroying = true;
 
@@ -5327,4 +5361,15 @@
             proto.end(token);
         }
     }
+
+    KeyInterceptionInfo getKeyInterceptionInfo() {
+        if (mKeyInterceptionInfo == null
+                || mKeyInterceptionInfo.layoutParamsPrivateFlags != getAttrs().privateFlags
+                || mKeyInterceptionInfo.layoutParamsType != getAttrs().type
+                || mKeyInterceptionInfo.windowTitle != getWindowTag()) {
+            mKeyInterceptionInfo = new KeyInterceptionInfo(getAttrs().type, getAttrs().privateFlags,
+                    getWindowTag().toString());
+        }
+        return mKeyInterceptionInfo;
+    }
 }
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index c676e72..1328273 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -27,17 +27,18 @@
 
 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM;
 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_DRAW;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_STARTING_WINDOW;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW_VERBOSE;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_CROP;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 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.TYPE_LAYER_MULTIPLIER;
@@ -67,6 +68,7 @@
 import android.view.animation.AnimationUtils;
 
 import com.android.server.policy.WindowManagerPolicy;
+import com.android.server.protolog.common.ProtoLog;
 
 import java.io.PrintWriter;
 
@@ -312,19 +314,19 @@
     boolean finishDrawingLocked(SurfaceControl.Transaction postDrawTransaction) {
         final boolean startingWindow =
                 mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
-        if (DEBUG_STARTING_WINDOW && startingWindow) {
-            Slog.v(TAG, "Finishing drawing window " + mWin + ": mDrawState="
-                    + drawStateToString());
+        if (startingWindow) {
+            ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Finishing drawing window %s: mDrawState=%s",
+                    mWin, drawStateToString());
         }
 
         boolean layoutNeeded = false;
 
         if (mDrawState == DRAW_PENDING) {
-            if (DEBUG_ANIM || SHOW_TRANSACTIONS || DEBUG_ORIENTATION)
-                Slog.v(TAG, "finishDrawingLocked: mDrawState=COMMIT_DRAW_PENDING " + mWin + " in "
-                        + mSurfaceController);
-            if (DEBUG_STARTING_WINDOW && startingWindow) {
-                Slog.v(TAG, "Draw state now committed in " + mWin);
+            ProtoLog.v(WM_DEBUG_DRAW,
+                    "finishDrawingLocked: mDrawState=COMMIT_DRAW_PENDING %s in %s", mWin,
+                    mSurfaceController);
+            if (startingWindow) {
+                ProtoLog.v(WM_DEBUG_STARTING_WINDOW, "Draw state now committed in %s", mWin);
             }
             mDrawState = COMMIT_DRAW_PENDING;
             layoutNeeded = true;
@@ -385,7 +387,7 @@
             mSurfaceDestroyDeferred = true;
             return;
         }
-        if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin, "SET FREEZE LAYER", false);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE SET FREEZE LAYER: %s", mWin);
         if (mSurfaceController != null) {
             // Our SurfaceControl is always at layer 0 within the parent Surface managed by
             // window-state. We want this old Surface to stay on top of the new one
@@ -456,8 +458,9 @@
 
         w.setHasSurface(false);
 
-        if (DEBUG_ANIM || DEBUG_ORIENTATION) Slog.i(TAG,
-                "createSurface " + this + ": mDrawState=DRAW_PENDING");
+        if (DEBUG_ANIM) {
+            Slog.i(TAG, "createSurface " + this + ": mDrawState=DRAW_PENDING");
+        }
 
         resetDrawState();
 
@@ -503,9 +506,8 @@
                 flags |= SurfaceControl.OPAQUE;
             }
 
-            mSurfaceController = new WindowSurfaceController(mSession.mSurfaceSession,
-                    attrs.getTitle().toString(), width, height, format, flags, this,
-                    windowType, ownerUid);
+            mSurfaceController = new WindowSurfaceController(attrs.getTitle().toString(), width,
+                    height, format, flags, this, windowType, ownerUid);
             mSurfaceController.setColorSpaceAgnostic((attrs.privateFlags
                     & WindowManager.LayoutParams.PRIVATE_FLAG_COLOR_SPACE_AGNOSTIC) != 0);
 
@@ -514,15 +516,10 @@
 
             w.setHasSurface(true);
 
-            if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
-                Slog.i(TAG, "  CREATE SURFACE "
-                        + mSurfaceController + " IN SESSION "
-                        + mSession.mSurfaceSession
-                        + ": pid=" + mSession.mPid + " format="
-                        + attrs.format + " flags=0x"
-                        + Integer.toHexString(flags)
-                        + " / " + this);
-            }
+            ProtoLog.i(WM_SHOW_SURFACE_ALLOC,
+                        "  CREATE SURFACE %s IN SESSION %s: pid=%d format=%d flags=0x%x / %s",
+                        mSurfaceController, mSession.mSurfaceSession, mSession.mPid, attrs.format,
+                        flags, this);
         } catch (OutOfResourcesException e) {
             Slog.w(TAG, "OutOfResourcesException creating surface");
             mService.mRoot.reclaimSomeSurfaceMemory(this, "create", true);
@@ -616,17 +613,15 @@
             if (mSurfaceDestroyDeferred) {
                 if (mSurfaceController != null && mPendingDestroySurface != mSurfaceController) {
                     if (mPendingDestroySurface != null) {
-                        if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
-                            WindowManagerService.logSurface(mWin, "DESTROY PENDING", true);
-                        }
+                        ProtoLog.i(WM_SHOW_SURFACE_ALLOC, "SURFACE DESTROY PENDING: %s. %s",
+                                mWin, new RuntimeException().fillInStackTrace());
                         mPendingDestroySurface.destroyNotInTransaction();
                     }
                     mPendingDestroySurface = mSurfaceController;
                 }
             } else {
-                if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
-                    WindowManagerService.logSurface(mWin, "DESTROY", true);
-                }
+                ProtoLog.i(WM_SHOW_SURFACE_ALLOC, "SURFACE DESTROY: %s. %s",
+                        mWin, new RuntimeException().fillInStackTrace());
                 destroySurface();
             }
             // Don't hide wallpaper if we're deferring the surface destroy
@@ -653,9 +648,8 @@
     void destroyDeferredSurfaceLocked() {
         try {
             if (mPendingDestroySurface != null) {
-                if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
-                    WindowManagerService.logSurface(mWin, "DESTROY PENDING", true);
-                }
+                ProtoLog.i(WM_SHOW_SURFACE_ALLOC, "SURFACE DESTROY PENDING: %s. %s",
+                        mWin, new RuntimeException().fillInStackTrace());
                 mPendingDestroySurface.destroyNotInTransaction();
                 // Don't hide wallpaper if we're destroying a deferred surface
                 // after a surface mode change.
@@ -673,9 +667,8 @@
     }
 
     void computeShownFrameLocked() {
-        final int displayId = mWin.getDisplayId();
         final ScreenRotationAnimation screenRotationAnimation =
-                mAnimator.getScreenRotationAnimationLocked(displayId);
+                mWin.getDisplayContent().getRotationAnimation();
         final boolean windowParticipatesInScreenRotationAnimation =
                 !mWin.mForceSeamlesslyRotate;
         final boolean screenAnimation = screenRotationAnimation != null
@@ -1089,9 +1082,7 @@
             // There is no need to wait for an animation change if our window is gone for layout
             // already as we'll never be visible.
             if (w.getOrientationChanging() && w.isGoneForLayoutLw()) {
-                if (DEBUG_ORIENTATION) {
-                    Slog.v(TAG, "Orientation change skips hidden " + w);
-                }
+                ProtoLog.v(WM_DEBUG_ORIENTATION, "Orientation change skips hidden %s", w);
                 w.setOrientationChanging(false);
             }
             return;
@@ -1116,8 +1107,8 @@
             // before it has drawn for the new orientation.
             if (w.getOrientationChanging() && w.isGoneForLayoutLw()) {
                 w.setOrientationChanging(false);
-                if (DEBUG_ORIENTATION) Slog.v(TAG,
-                        "Orientation change skips hidden " + w);
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
+                        "Orientation change skips hidden %s", w);
             }
         } else if (mLastAlpha != mShownAlpha
                 || mLastDsDx != mDsDx
@@ -1135,13 +1126,10 @@
             mLastDtDy = mDtDy;
             w.mLastHScale = w.mHScale;
             w.mLastVScale = w.mVScale;
-            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
-                    "controller=" + mSurfaceController +
-                    "alpha=" + mShownAlpha
-                    + " matrix=[" + mDsDx + "*" + w.mHScale
-                    + "," + mDtDx + "*" + w.mVScale
-                    + "][" + mDtDy + "*" + w.mHScale
-                    + "," + mDsDy + "*" + w.mVScale + "]", false);
+            ProtoLog.i(WM_SHOW_TRANSACTIONS,
+                    "SURFACE controller=%s alpha=%f matrix=[%f*%f,%f*%f][%f*%f,%f*%f]: %s",
+                            mSurfaceController, mShownAlpha, mDsDx, w.mHScale, mDtDx, w.mVScale,
+                            mDtDy, w.mHScale, mDsDy, w.mVScale, w);
 
             boolean prepared =
                 mSurfaceController.prepareToShowInTransaction(mShownAlpha,
@@ -1191,11 +1179,11 @@
             if (!w.isDrawnLw()) {
                 mAnimator.mBulkUpdateParams &= ~SET_ORIENTATION_CHANGE_COMPLETE;
                 mAnimator.mLastWindowFreezeSource = w;
-                if (DEBUG_ORIENTATION) Slog.v(TAG,
-                        "Orientation continue waiting for draw in " + w);
+                ProtoLog.v(WM_DEBUG_ORIENTATION,
+                        "Orientation continue waiting for draw in %s", w);
             } else {
                 w.setOrientationChanging(false);
-                if (DEBUG_ORIENTATION) Slog.v(TAG, "Orientation change complete in " + w);
+                ProtoLog.v(WM_DEBUG_ORIENTATION, "Orientation change complete in %s", w);
             }
         }
 
diff --git a/services/core/java/com/android/server/wm/WindowSurfaceController.java b/services/core/java/com/android/server/wm/WindowSurfaceController.java
index 6d813d1..7f68c48 100644
--- a/services/core/java/com/android/server/wm/WindowSurfaceController.java
+++ b/services/core/java/com/android/server/wm/WindowSurfaceController.java
@@ -21,10 +21,10 @@
 import static android.view.SurfaceControl.METADATA_OWNER_UID;
 import static android.view.SurfaceControl.METADATA_WINDOW_TYPE;
 
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_SURFACE_ALLOC;
+import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_SURFACE_ALLOC;
-import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
 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.WindowSurfaceControllerProto.LAYER;
@@ -37,9 +37,10 @@
 import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
 import android.view.SurfaceControl;
-import android.view.SurfaceSession;
 import android.view.WindowContentFrameStats;
 
+import com.android.server.protolog.common.ProtoLog;
+
 import java.io.PrintWriter;
 
 class WindowSurfaceController {
@@ -83,7 +84,7 @@
 
     private final SurfaceControl.Transaction mTmpTransaction;
 
-    public WindowSurfaceController(SurfaceSession s, String name, int w, int h, int format,
+    WindowSurfaceController(String name, int w, int h, int format,
             int flags, WindowStateAnimator animator, int windowType, int ownerUid) {
         mAnimator = animator;
 
@@ -111,31 +112,22 @@
         Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
     }
 
-    private void logSurface(String msg, RuntimeException where) {
-        String str = "  SURFACE " + msg + ": " + title;
-        if (where != null) {
-            Slog.i(TAG, str, where);
-        } else {
-            Slog.i(TAG, str);
-        }
-    }
-
     void reparentChildrenInTransaction(WindowSurfaceController other) {
-        if (SHOW_TRANSACTIONS) Slog.i(TAG, "REPARENT from: " + this + " to: " + other);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "REPARENT from: %s to: %s", this, other);
         if ((mSurfaceControl != null) && (other.mSurfaceControl != null)) {
             mSurfaceControl.reparentChildren(other.mSurfaceControl);
         }
     }
 
     void detachChildren() {
-        if (SHOW_TRANSACTIONS) Slog.i(TAG, "SEVER CHILDREN");
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SEVER CHILDREN");
         if (mSurfaceControl != null) {
             mSurfaceControl.detachChildren();
         }
     }
 
     void hide(SurfaceControl.Transaction transaction, String reason) {
-        if (SHOW_TRANSACTIONS) logSurface("HIDE ( " + reason + " )", null);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE HIDE ( %s ): %s", reason, title);
         mHiddenForOtherReasons = true;
 
         mAnimator.destroyPreservedSurfaceLocked();
@@ -157,9 +149,8 @@
     }
 
     void destroyNotInTransaction() {
-        if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
-            Slog.i(TAG, "Destroying surface " + this + " called by " + Debug.getCallers(8));
-        }
+        ProtoLog.i(WM_SHOW_SURFACE_ALLOC,
+                    "Destroying surface %s called by %s", this, Debug.getCallers(8));
         try {
             if (mSurfaceControl != null) {
                 mTmpTransaction.remove(mSurfaceControl).apply();
@@ -173,8 +164,7 @@
     }
 
     void setCropInTransaction(Rect clipRect, boolean recoveringMemory) {
-        if (SHOW_TRANSACTIONS) logSurface(
-                "CROP " + clipRect.toShortString(), null);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE CROP %s: %s", clipRect.toShortString(), title);
         try {
             if (clipRect.width() > 0 && clipRect.height() > 0) {
                 if (!clipRect.equals(mSurfaceCrop)) {
@@ -198,8 +188,7 @@
     }
 
     void clearCropInTransaction(boolean recoveringMemory) {
-        if (SHOW_TRANSACTIONS) logSurface(
-                "CLEAR CROP", null);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE CLEAR CROP: %s", title);
         try {
             Rect clipRect = new Rect(0, 0, -1, -1);
             if (mSurfaceCrop.equals(clipRect)) {
@@ -227,8 +216,8 @@
             mSurfaceY = top;
 
             try {
-                if (SHOW_TRANSACTIONS) logSurface(
-                        "POS (setPositionInTransaction) @ (" + left + "," + top + ")", null);
+                ProtoLog.i(WM_SHOW_TRANSACTIONS,
+                        "SURFACE POS (setPositionInTransaction) @ (%f,%f): %s", left, top, title);
 
                 if (t == null) {
                     mSurfaceControl.setPosition(left, top);
@@ -264,8 +253,8 @@
         mLastDsdy = dsdy;
 
         try {
-            if (SHOW_TRANSACTIONS) logSurface(
-                    "MATRIX [" + dsdx + "," + dtdx + "," + dtdy + "," + dsdy + "]", null);
+            ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE MATRIX [%f,%f,%f,%f]: %s",
+                    dsdx, dtdx, dtdy, dsdy, title);
             if (t == null) {
                 mSurfaceControl.setMatrix(dsdx, dtdx, dtdy, dsdy);
             } else {
@@ -290,8 +279,7 @@
             mSurfaceH = height;
 
             try {
-                if (SHOW_TRANSACTIONS) logSurface(
-                        "SIZE " + width + "x" + height, null);
+                ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE SIZE %dx%d: %s", width, height, title);
                 mSurfaceControl.setBufferSize(width, height);
             } catch (RuntimeException e) {
                 // If something goes wrong with the surface (such
@@ -350,8 +338,7 @@
     }
 
     void setOpaque(boolean isOpaque) {
-        if (SHOW_TRANSACTIONS) logSurface("isOpaque=" + isOpaque,
-                null);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE isOpaque=%b: %s", isOpaque, title);
 
         if (mSurfaceControl == null) {
             return;
@@ -367,8 +354,7 @@
     }
 
     void setSecure(boolean isSecure) {
-        if (SHOW_TRANSACTIONS) logSurface("isSecure=" + isSecure,
-                null);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE isSecure=%b: %s", isSecure, title);
 
         if (mSurfaceControl == null) {
             return;
@@ -384,9 +370,7 @@
     }
 
     void setColorSpaceAgnostic(boolean agnostic) {
-        if (SHOW_TRANSACTIONS) {
-            logSurface("isColorSpaceAgnostic=" + agnostic, null);
-        }
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE isColorSpaceAgnostic=%b: %s", agnostic, title);
 
         if (mSurfaceControl == null) {
             return;
@@ -410,8 +394,7 @@
     }
 
     boolean showRobustlyInTransaction() {
-        if (SHOW_TRANSACTIONS) logSurface(
-                "SHOW (performLayout)", null);
+        ProtoLog.i(WM_SHOW_TRANSACTIONS, "SURFACE SHOW (performLayout): %s", title);
         if (DEBUG_VISIBILITY) Slog.v(TAG, "Showing " + this
                 + " during relayout");
         mHiddenForOtherReasons = false;
diff --git a/services/core/java/com/android/server/wm/WindowToken.java b/services/core/java/com/android/server/wm/WindowToken.java
index 8aee0f2..5b362c3 100644
--- a/services/core/java/com/android/server/wm/WindowToken.java
+++ b/services/core/java/com/android/server/wm/WindowToken.java
@@ -19,9 +19,9 @@
 import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
 import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR;
 
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_MOVEMENT;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_FOCUS;
+import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_WINDOW_MOVEMENT;
 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.UPDATE_FOCUS_NORMAL;
@@ -35,9 +35,10 @@
 import android.annotation.CallSuper;
 import android.os.Debug;
 import android.os.IBinder;
-import android.util.Slog;
 import android.util.proto.ProtoOutputStream;
 
+import com.android.server.protolog.common.ProtoLog;
+
 import java.io.PrintWriter;
 import java.util.Comparator;
 
@@ -119,7 +120,9 @@
         mPersistOnEmpty = persistOnEmpty;
         mOwnerCanManageAppTokens = ownerCanManageAppTokens;
         mRoundedCornerOverlay = roundedCornerOverlay;
-        onDisplayChanged(dc);
+        if (dc != null) {
+            onDisplayChanged(dc);
+        }
     }
 
     void setHidden(boolean hidden) {
@@ -135,8 +138,8 @@
     void removeAllWindowsIfPossible() {
         for (int i = mChildren.size() - 1; i >= 0; --i) {
             final WindowState win = mChildren.get(i);
-            if (DEBUG_WINDOW_MOVEMENT) Slog.w(TAG_WM,
-                    "removeAllWindowsIfPossible: removing win=" + win);
+            ProtoLog.w(WM_DEBUG_WINDOW_MOVEMENT,
+                    "removeAllWindowsIfPossible: removing win=%s", win);
             win.removeIfPossible();
         }
     }
@@ -197,15 +200,15 @@
     }
 
     void addWindow(final WindowState win) {
-        if (DEBUG_FOCUS) Slog.d(TAG_WM,
-                "addWindow: win=" + win + " Callers=" + Debug.getCallers(5));
+        ProtoLog.d(WM_DEBUG_FOCUS,
+                "addWindow: win=%s Callers=%s", win, Debug.getCallers(5));
 
         if (win.isChildWindow()) {
             // Child windows are added to their parent windows.
             return;
         }
         if (!mChildren.contains(win)) {
-            if (DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "Adding " + win + " to " + this);
+            ProtoLog.v(WM_DEBUG_ADD_REMOVE, "Adding %s to %s", win, this);
             addChild(win, mWindowComparator);
             mWmService.mWindowsChanged = true;
             // TODO: Should we also be setting layout needed here and other places?
diff --git a/services/core/java/com/android/server/wm/WindowTraceBuffer.java b/services/core/java/com/android/server/wm/WindowTraceBuffer.java
deleted file mode 100644
index 8c65884..0000000
--- a/services/core/java/com/android/server/wm/WindowTraceBuffer.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2019 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 com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER;
-import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER_H;
-import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER_L;
-
-import android.util.proto.ProtoOutputStream;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayDeque;
-import java.util.Arrays;
-import java.util.Queue;
-
-/**
- * Buffer used for window tracing.
- */
-class WindowTraceBuffer {
-    private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
-
-    private final Object mBufferLock = new Object();
-
-    private final Queue<ProtoOutputStream> mBuffer = new ArrayDeque<>();
-    private int mBufferUsedSize;
-    private int mBufferCapacity;
-
-    WindowTraceBuffer(int bufferCapacity) {
-        mBufferCapacity = bufferCapacity;
-        resetBuffer();
-    }
-
-    int getAvailableSpace() {
-        return mBufferCapacity - mBufferUsedSize;
-    }
-
-    int size() {
-        return mBuffer.size();
-    }
-
-    void setCapacity(int capacity) {
-        mBufferCapacity = capacity;
-    }
-
-    /**
-     * Inserts the specified element into this buffer.
-     *
-     * @param proto the element to add
-     * @throws IllegalStateException if the element cannot be added because it is larger
-     *                               than the buffer size.
-     */
-    void add(ProtoOutputStream proto) {
-        int protoLength = proto.getRawSize();
-        if (protoLength > mBufferCapacity) {
-            throw new IllegalStateException("Trace object too large for the buffer. Buffer size:"
-                    + mBufferCapacity + " Object size: " + protoLength);
-        }
-        synchronized (mBufferLock) {
-            discardOldest(protoLength);
-            mBuffer.add(proto);
-            mBufferUsedSize += protoLength;
-            mBufferLock.notify();
-        }
-    }
-
-    boolean contains(byte[] other) {
-        return mBuffer.stream()
-                .anyMatch(p -> Arrays.equals(p.getBytes(), other));
-    }
-
-    /**
-     * Writes the trace buffer to disk.
-     */
-    void writeTraceToFile(File traceFile) throws IOException {
-        synchronized (mBufferLock) {
-            traceFile.delete();
-            try (OutputStream os = new FileOutputStream(traceFile)) {
-                traceFile.setReadable(true /* readable */, false /* ownerOnly */);
-                ProtoOutputStream proto = new ProtoOutputStream();
-                proto.write(MAGIC_NUMBER, MAGIC_NUMBER_VALUE);
-                os.write(proto.getBytes());
-                for (ProtoOutputStream protoOutputStream : mBuffer) {
-                    proto = protoOutputStream;
-                    byte[] protoBytes = proto.getBytes();
-                    os.write(protoBytes);
-                }
-                os.flush();
-            }
-        }
-    }
-
-    /**
-     * Checks if the element can be added to the buffer. The element is already certain to be
-     * smaller than the overall buffer size.
-     *
-     * @param protoLength byte array representation of the Proto object to add
-     */
-    private void discardOldest(int protoLength) {
-        long availableSpace = getAvailableSpace();
-
-        while (availableSpace < protoLength) {
-
-            ProtoOutputStream item = mBuffer.poll();
-            if (item == null) {
-                throw new IllegalStateException("No element to discard from buffer");
-            }
-            mBufferUsedSize -= item.getRawSize();
-            availableSpace = getAvailableSpace();
-        }
-    }
-
-    /**
-     * Removes all elements form the buffer
-     */
-    void resetBuffer() {
-        synchronized (mBufferLock) {
-            mBuffer.clear();
-            mBufferUsedSize = 0;
-        }
-    }
-
-    @VisibleForTesting
-    int getBufferSize() {
-        return mBufferUsedSize;
-    }
-
-    String getStatus() {
-        synchronized (mBufferLock) {
-            return "Buffer size: "
-                    + mBufferCapacity
-                    + " bytes"
-                    + "\n"
-                    + "Buffer usage: "
-                    + mBufferUsedSize
-                    + " bytes"
-                    + "\n"
-                    + "Elements in the buffer: "
-                    + mBuffer.size();
-        }
-    }
-}
diff --git a/services/core/java/com/android/server/wm/WindowTracing.java b/services/core/java/com/android/server/wm/WindowTracing.java
index 765e347..bb66530 100644
--- a/services/core/java/com/android/server/wm/WindowTracing.java
+++ b/services/core/java/com/android/server/wm/WindowTracing.java
@@ -19,6 +19,9 @@
 import static android.os.Build.IS_USER;
 
 import static com.android.server.wm.WindowManagerTraceFileProto.ENTRY;
+import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER;
+import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER_H;
+import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER_L;
 import static com.android.server.wm.WindowManagerTraceProto.ELAPSED_REALTIME_NANOS;
 import static com.android.server.wm.WindowManagerTraceProto.WHERE;
 import static com.android.server.wm.WindowManagerTraceProto.WINDOW_MANAGER_SERVICE;
@@ -31,6 +34,9 @@
 import android.util.proto.ProtoOutputStream;
 import android.view.Choreographer;
 
+import com.android.server.protolog.ProtoLogImpl;
+import com.android.server.utils.TraceBuffer;
+
 import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -50,6 +56,7 @@
     private static final int BUFFER_CAPACITY_ALL = 4096 * 1024;
     private static final String TRACE_FILENAME = "/data/misc/wmtrace/wm_trace.pb";
     private static final String TAG = "WindowTracing";
+    private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
 
     private final WindowManagerService mService;
     private final Choreographer mChoreographer;
@@ -57,7 +64,7 @@
 
     private final Object mEnabledLock = new Object();
     private final File mTraceFile;
-    private final WindowTraceBuffer mBuffer;
+    private final com.android.server.utils.TraceBuffer mBuffer;
     private final Choreographer.FrameCallback mFrameCallback = (frameTimeNanos) ->
             log("onFrame" /* where */);
 
@@ -84,7 +91,7 @@
         mService = service;
         mGlobalLock = globalLock;
         mTraceFile = file;
-        mBuffer = new WindowTraceBuffer(bufferCapacity);
+        mBuffer = new TraceBuffer(bufferCapacity);
         setLogLevel(WindowTraceLogLevel.TRIM, null /* pw */);
     }
 
@@ -94,6 +101,7 @@
             return;
         }
         synchronized (mEnabledLock) {
+            ProtoLogImpl.getSingleInstance().startProtoLog(pw);
             logAndPrintln(pw, "Start tracing to " + mTraceFile + ".");
             mBuffer.resetBuffer();
             mEnabled = mEnabledLockFree = true;
@@ -132,6 +140,7 @@
                 logAndPrintln(pw, "Trace written to " + mTraceFile + ".");
             }
         }
+        ProtoLogImpl.getSingleInstance().stopProtoLog(pw, writeToFile);
     }
 
     private void setLogLevel(@WindowTraceLogLevel int logLevel, PrintWriter pw) {
@@ -317,6 +326,7 @@
         synchronized (mEnabledLock) {
             writeTraceToFileLocked();
         }
+        ProtoLogImpl.getSingleInstance().writeProtoLogToFile();
     }
 
     private void logAndPrintln(@Nullable PrintWriter pw, String msg) {
@@ -334,11 +344,13 @@
     private void writeTraceToFileLocked() {
         try {
             Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "writeTraceToFileLocked");
-            mBuffer.writeTraceToFile(mTraceFile);
+            ProtoOutputStream proto = new ProtoOutputStream();
+            proto.write(MAGIC_NUMBER, MAGIC_NUMBER_VALUE);
+            mBuffer.writeTraceToFile(mTraceFile, proto);
         } catch (IOException e) {
             Log.e(TAG, "Unable to write buffer to file", e);
         } finally {
             Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
         }
     }
-}
\ No newline at end of file
+}
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index d9c7fed..bcd1713 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -141,6 +141,7 @@
         "android.hardware.vibrator@1.1",
         "android.hardware.vibrator@1.2",
         "android.hardware.vibrator@1.3",
+        "android.hardware.vibrator@1.4",
         "android.hardware.vr@1.0",
         "android.frameworks.schedulerservice@1.0",
         "android.frameworks.sensorservice@1.0",
diff --git a/services/core/jni/com_android_server_VibratorService.cpp b/services/core/jni/com_android_server_VibratorService.cpp
index d5fbd2b..a8c7682 100644
--- a/services/core/jni/com_android_server_VibratorService.cpp
+++ b/services/core/jni/com_android_server_VibratorService.cpp
@@ -16,17 +16,12 @@
 
 #define LOG_TAG "VibratorService"
 
-#include <android/hardware/vibrator/1.0/IVibrator.h>
-#include <android/hardware/vibrator/1.0/types.h>
-#include <android/hardware/vibrator/1.0/IVibrator.h>
-#include <android/hardware/vibrator/1.1/types.h>
-#include <android/hardware/vibrator/1.2/IVibrator.h>
-#include <android/hardware/vibrator/1.2/types.h>
-#include <android/hardware/vibrator/1.3/IVibrator.h>
+#include <android/hardware/vibrator/1.4/IVibrator.h>
 
 #include "jni.h"
 #include <nativehelper/JNIHelp.h>
 #include "android_runtime/AndroidRuntime.h"
+#include "core_jni_helpers.h"
 
 #include <utils/misc.h>
 #include <utils/Log.h>
@@ -36,6 +31,7 @@
 #include <stdio.h>
 
 using android::hardware::Return;
+using android::hardware::Void;
 using android::hardware::vibrator::V1_0::EffectStrength;
 using android::hardware::vibrator::V1_0::Status;
 using android::hardware::vibrator::V1_1::Effect_1_1;
@@ -44,9 +40,32 @@
 namespace V1_1 = android::hardware::vibrator::V1_1;
 namespace V1_2 = android::hardware::vibrator::V1_2;
 namespace V1_3 = android::hardware::vibrator::V1_3;
+namespace V1_4 = android::hardware::vibrator::V1_4;
 
 namespace android {
 
+static jmethodID sMethodIdOnComplete;
+
+class VibratorCallback : public V1_4::IVibratorCallback {
+    public:
+        VibratorCallback(JNIEnv *env, jobject vibration) :
+        mVibration(MakeGlobalRefOrDie(env, vibration)) {}
+
+        ~VibratorCallback() {
+            JNIEnv *env = AndroidRuntime::getJNIEnv();
+            env->DeleteGlobalRef(mVibration);
+        }
+
+        Return<void> onComplete() override {
+            auto env = AndroidRuntime::getJNIEnv();
+            env->CallVoidMethod(mVibration, sMethodIdOnComplete);
+            return Void();
+        }
+
+    private:
+        jobject mVibration;
+};
+
 static constexpr int NUM_TRIES = 2;
 
 // Creates a Return<R> with STATUS::EX_NULL_POINTER.
@@ -56,37 +75,57 @@
     return Return<R>{Status::fromExceptionCode(Status::EX_NULL_POINTER)};
 }
 
-// Helper used to transparently deal with the vibrator HAL becoming unavailable.
+template <typename I>
+class HalWrapper {
+  public:
+    static std::unique_ptr<HalWrapper> Create() {
+        // Assume that if getService returns a nullptr, HAL is not available on the
+        // device.
+        auto hal = I::getService();
+        return hal ? std::unique_ptr<HalWrapper>(new HalWrapper(std::move(hal))) : nullptr;
+    }
+
+    // Helper used to transparently deal with the vibrator HAL becoming unavailable.
+    template<class R, class... Args0, class... Args1>
+    Return<R> call(Return<R> (I::* fn)(Args0...), Args1&&... args1) {
+        // Return<R> doesn't have a default constructor, so make a Return<R> with
+        // STATUS::EX_NONE.
+        using ::android::hardware::Status;
+        Return<R> ret{Status::fromExceptionCode(Status::EX_NONE)};
+
+        // Note that ret is guaranteed to be changed after this loop.
+        for (int i = 0; i < NUM_TRIES; ++i) {
+            ret = (mHal == nullptr) ? NullptrStatus<R>()
+                    : (*mHal.*fn)(std::forward<Args1>(args1)...);
+
+            if (ret.isOk()) {
+                break;
+            }
+
+            ALOGE("Failed to issue command to vibrator HAL. Retrying.");
+            // Restoring connection to the HAL.
+            mHal = I::tryGetService();
+        }
+        return ret;
+    }
+
+  private:
+    HalWrapper(sp<I> &&hal) : mHal(std::move(hal)) {}
+
+  private:
+    sp<I> mHal;
+};
+
+template <typename I>
+static auto getHal() {
+    static auto sHalWrapper = HalWrapper<I>::Create();
+    return sHalWrapper.get();
+}
+
 template<class R, class I, class... Args0, class... Args1>
 Return<R> halCall(Return<R> (I::* fn)(Args0...), Args1&&... args1) {
-    // Assume that if getService returns a nullptr, HAL is not available on the
-    // device.
-    static sp<I> sHal = I::getService();
-    static bool sAvailable = sHal != nullptr;
-
-    if (!sAvailable) {
-        return NullptrStatus<R>();
-    }
-
-    // Return<R> doesn't have a default constructor, so make a Return<R> with
-    // STATUS::EX_NONE.
-    using ::android::hardware::Status;
-    Return<R> ret{Status::fromExceptionCode(Status::EX_NONE)};
-
-    // Note that ret is guaranteed to be changed after this loop.
-    for (int i = 0; i < NUM_TRIES; ++i) {
-        ret = (sHal == nullptr) ? NullptrStatus<R>()
-                : (*sHal.*fn)(std::forward<Args1>(args1)...);
-
-        if (ret.isOk()) {
-            break;
-        }
-
-        ALOGE("Failed to issue command to vibrator HAL. Retrying.");
-        // Restoring connection to the HAL.
-        sHal = I::tryGetService();
-    }
-    return ret;
+    auto hal = getHal<I>();
+    return hal ? hal->call(fn, std::forward<Args1>(args1)...) : NullptrStatus<R>();
 }
 
 template<class R>
@@ -99,17 +138,17 @@
     return val >= *iter.begin() && val <= *std::prev(iter.end());
 }
 
-static void vibratorInit(JNIEnv /* env */, jobject /* clazz */)
+static void vibratorInit(JNIEnv *env, jclass clazz)
 {
     halCall(&V1_0::IVibrator::ping).isOk();
 }
 
-static jboolean vibratorExists(JNIEnv* /* env */, jobject /* clazz */)
+static jboolean vibratorExists(JNIEnv* /* env */, jclass /* clazz */)
 {
     return halCall(&V1_0::IVibrator::ping).isOk() ? JNI_TRUE : JNI_FALSE;
 }
 
-static void vibratorOn(JNIEnv* /* env */, jobject /* clazz */, jlong timeout_ms)
+static void vibratorOn(JNIEnv* /* env */, jclass /* clazz */, jlong timeout_ms)
 {
     Status retStatus = halCall(&V1_0::IVibrator::on, timeout_ms).withDefault(Status::UNKNOWN_ERROR);
     if (retStatus != Status::OK) {
@@ -117,7 +156,7 @@
     }
 }
 
-static void vibratorOff(JNIEnv* /* env */, jobject /* clazz */)
+static void vibratorOff(JNIEnv* /* env */, jclass /* clazz */)
 {
     Status retStatus = halCall(&V1_0::IVibrator::off).withDefault(Status::UNKNOWN_ERROR);
     if (retStatus != Status::OK) {
@@ -125,11 +164,11 @@
     }
 }
 
-static jlong vibratorSupportsAmplitudeControl(JNIEnv*, jobject) {
+static jlong vibratorSupportsAmplitudeControl(JNIEnv*, jclass) {
     return halCall(&V1_0::IVibrator::supportsAmplitudeControl).withDefault(false);
 }
 
-static void vibratorSetAmplitude(JNIEnv*, jobject, jint amplitude) {
+static void vibratorSetAmplitude(JNIEnv*, jclass, jint amplitude) {
     Status status = halCall(&V1_0::IVibrator::setAmplitude, static_cast<uint32_t>(amplitude))
         .withDefault(Status::UNKNOWN_ERROR);
     if (status != Status::OK) {
@@ -138,11 +177,11 @@
     }
 }
 
-static jboolean vibratorSupportsExternalControl(JNIEnv*, jobject) {
+static jboolean vibratorSupportsExternalControl(JNIEnv*, jclass) {
     return halCall(&V1_3::IVibrator::supportsExternalControl).withDefault(false);
 }
 
-static void vibratorSetExternalControl(JNIEnv*, jobject, jboolean enabled) {
+static void vibratorSetExternalControl(JNIEnv*, jclass, jboolean enabled) {
     Status status = halCall(&V1_3::IVibrator::setExternalControl, static_cast<uint32_t>(enabled))
         .withDefault(Status::UNKNOWN_ERROR);
     if (status != Status::OK) {
@@ -151,7 +190,8 @@
     }
 }
 
-static jlong vibratorPerformEffect(JNIEnv*, jobject, jlong effect, jint strength) {
+static jlong vibratorPerformEffect(JNIEnv* env, jclass, jlong effect, jint strength,
+                                   jobject vibration) {
     Status status;
     uint32_t lengthMs;
     auto callback = [&status, &lengthMs](Status retStatus, uint32_t retLengthMs) {
@@ -161,7 +201,11 @@
     EffectStrength effectStrength(static_cast<EffectStrength>(strength));
 
     Return<void> ret;
-    if (isValidEffect<V1_0::Effect>(effect)) {
+    if (auto hal = getHal<V1_4::IVibrator>(); hal && isValidEffect<V1_3::Effect>(effect)) {
+        sp<VibratorCallback> effectCallback = new VibratorCallback(env, vibration);
+        ret = hal->call(&V1_4::IVibrator::perform_1_4, static_cast<V1_3::Effect>(effect),
+                effectStrength, effectCallback, callback);
+    } else if (isValidEffect<V1_0::Effect>(effect)) {
         ret = halCall(&V1_0::IVibrator::perform, static_cast<V1_0::Effect>(effect),
                 effectStrength, callback);
     } else if (isValidEffect<Effect_1_1>(effect)) {
@@ -198,6 +242,10 @@
     return -1;
 }
 
+static jlong vibratorGetCapabilities(JNIEnv*, jclass) {
+    return halCall(&V1_4::IVibrator::getCapabilities).withDefault(0);
+}
+
 static const JNINativeMethod method_table[] = {
     { "vibratorExists", "()Z", (void*)vibratorExists },
     { "vibratorInit", "()V", (void*)vibratorInit },
@@ -205,13 +253,18 @@
     { "vibratorOff", "()V", (void*)vibratorOff },
     { "vibratorSupportsAmplitudeControl", "()Z", (void*)vibratorSupportsAmplitudeControl},
     { "vibratorSetAmplitude", "(I)V", (void*)vibratorSetAmplitude},
-    { "vibratorPerformEffect", "(JJ)J", (void*)vibratorPerformEffect},
+    { "vibratorPerformEffect", "(JJLcom/android/server/VibratorService$Vibration;)J",
+        (void*)vibratorPerformEffect},
     { "vibratorSupportsExternalControl", "()Z", (void*)vibratorSupportsExternalControl},
     { "vibratorSetExternalControl", "(Z)V", (void*)vibratorSetExternalControl},
+    { "vibratorGetCapabilities", "()J", (void*)vibratorGetCapabilities},
 };
 
 int register_android_server_VibratorService(JNIEnv *env)
 {
+    sMethodIdOnComplete = GetMethodIDOrDie(env,
+            FindClassOrDie(env, "com/android/server/VibratorService$Vibration"),
+            "onComplete", "()V");
     return jniRegisterNativeMethods(env, "com/android/server/VibratorService",
             method_table, NELEM(method_table));
 }
diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index 03f4755..fb2fdab 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -159,12 +159,7 @@
     status_t status = android_view_PointerIcon_loadSystemIcon(env,
             contextObj, style, outPointerIcon);
     if (!status) {
-        SkBitmap* bitmapCopy = &outSpriteIcon->bitmap;
-        SkImageInfo bitmapCopyInfo = outPointerIcon->bitmap.info().makeColorType(kN32_SkColorType);
-        if (bitmapCopy->tryAllocPixels(bitmapCopyInfo)) {
-            outPointerIcon->bitmap.readPixels(bitmapCopy->info(), bitmapCopy->getPixels(),
-                    bitmapCopy->rowBytes(), 0, 0);
-        }
+        outSpriteIcon->bitmap = outPointerIcon->bitmap.copy(ANDROID_BITMAP_FORMAT_RGBA_8888);
         outSpriteIcon->style = outPointerIcon->style;
         outSpriteIcon->hotSpotX = outPointerIcon->hotSpotX;
         outSpriteIcon->hotSpotY = outPointerIcon->hotSpotY;
@@ -1575,6 +1570,27 @@
     im->setSystemUiVisibility(visibility);
 }
 
+static jboolean nativeTransferTouchFocus(JNIEnv* env,
+        jclass /* clazz */, jlong ptr, jobject fromChannelObj, jobject toChannelObj) {
+    NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
+
+    sp<InputChannel> fromChannel =
+            android_view_InputChannel_getInputChannel(env, fromChannelObj);
+    sp<InputChannel> toChannel =
+            android_view_InputChannel_getInputChannel(env, toChannelObj);
+
+    if (fromChannel == nullptr || toChannel == nullptr) {
+        return JNI_FALSE;
+    }
+
+    if (im->getInputManager()->getDispatcher()->
+            transferTouchFocus(fromChannel->getToken(), toChannel->getToken())) {
+        return JNI_TRUE;
+    } else {
+        return JNI_FALSE;
+    }
+}
+
 static void nativeSetPointerSpeed(JNIEnv* /* env */,
         jclass /* clazz */, jlong ptr, jint speed) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
@@ -1709,15 +1725,8 @@
         return;
     }
 
-    SpriteIcon spriteIcon;
-    SkImageInfo spriteInfo = pointerIcon.bitmap.info().makeColorType(kN32_SkColorType);
-    if (spriteIcon.bitmap.tryAllocPixels(spriteInfo)) {
-        pointerIcon.bitmap.readPixels(spriteInfo, spriteIcon.bitmap.getPixels(),
-                spriteIcon.bitmap.rowBytes(), 0, 0);
-    }
-    spriteIcon.style = pointerIcon.style;
-    spriteIcon.hotSpotX = pointerIcon.hotSpotX;
-    spriteIcon.hotSpotY = pointerIcon.hotSpotY;
+    SpriteIcon spriteIcon(pointerIcon.bitmap.copy(ANDROID_BITMAP_FORMAT_RGBA_8888),
+                          pointerIcon.style, pointerIcon.hotSpotX, pointerIcon.hotSpotY);
     im->setCustomPointerIcon(spriteIcon);
 }
 
@@ -1775,6 +1784,8 @@
             (void*) nativeSetInputDispatchMode },
     { "nativeSetSystemUiVisibility", "(JI)V",
             (void*) nativeSetSystemUiVisibility },
+    { "nativeTransferTouchFocus", "(JLandroid/view/InputChannel;Landroid/view/InputChannel;)Z",
+            (void*) nativeTransferTouchFocus },
     { "nativeSetPointerSpeed", "(JI)V",
             (void*) nativeSetPointerSpeed },
     { "nativeSetShowTouches", "(JZ)V",
diff --git a/services/devicepolicy/TEST_MAPPING b/services/devicepolicy/TEST_MAPPING
index a5ee3e2..3d86cf3 100644
--- a/services/devicepolicy/TEST_MAPPING
+++ b/services/devicepolicy/TEST_MAPPING
@@ -1,5 +1,5 @@
 {
-  "presubmit": [
+  "presubmit-devicepolicy": [
     {
       "name": "CtsDevicePolicyManagerTestCases",
       "options": [
@@ -12,7 +12,7 @@
       ]
     }
   ],
-  "postsubmit": [
+  "postsubmit-devicepolicy": [
     {
       "name": "CtsDevicePolicyManagerTestCases"
     }
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index 704c808..47291cb 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -50,6 +50,7 @@
 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
+import static android.app.admin.DevicePolicyManager.ID_TYPE_INDIVIDUAL_ATTESTATION;
 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
@@ -125,6 +126,7 @@
 import android.app.admin.DevicePolicyManager;
 import android.app.admin.DevicePolicyManager.PasswordComplexity;
 import android.app.admin.DevicePolicyManagerInternal;
+import android.app.admin.DeviceStateCache;
 import android.app.admin.NetworkEvent;
 import android.app.admin.PasswordMetrics;
 import android.app.admin.SecurityLog;
@@ -506,6 +508,7 @@
     private final OverlayPackagesProvider mOverlayPackagesProvider;
 
     private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl();
+    private final DeviceStateCacheImpl mStateCache = new DeviceStateCacheImpl();
 
     /**
      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
@@ -2294,6 +2297,9 @@
                 policy = new DevicePolicyData(userHandle);
                 mUserData.append(userHandle, policy);
                 loadSettingsLocked(policy, userHandle);
+                if (userHandle == UserHandle.USER_SYSTEM) {
+                    mStateCache.setDeviceProvisioned(policy.mUserSetupComplete);
+                }
             }
             return policy;
         }
@@ -4132,6 +4138,7 @@
                 final PasswordMetrics metrics = ap.minimumPasswordMetrics;
                 if (metrics.quality != quality) {
                     metrics.quality = quality;
+                    resetInactivePasswordRequirementsIfRPlus(userId, ap);
                     updatePasswordValidityCheckpointLocked(userId, parent);
                     updatePasswordQualityCacheForUserGroup(userId);
                     saveSettingsLocked(userId);
@@ -4150,6 +4157,27 @@
     }
 
     /**
+     * For admins targeting R+ reset various password constraints to default values when quality is
+     * set to a value that makes those constraints that have no effect.
+     */
+    private void resetInactivePasswordRequirementsIfRPlus(int userId, ActiveAdmin admin) {
+        if (getTargetSdk(admin.info.getPackageName(), userId) > Build.VERSION_CODES.Q) {
+            final PasswordMetrics metrics = admin.minimumPasswordMetrics;
+            if (metrics.quality < PASSWORD_QUALITY_NUMERIC) {
+                metrics.length = ActiveAdmin.DEF_MINIMUM_PASSWORD_LENGTH;
+            }
+            if (metrics.quality < PASSWORD_QUALITY_COMPLEX) {
+                metrics.letters = ActiveAdmin.DEF_MINIMUM_PASSWORD_LETTERS;
+                metrics.upperCase = ActiveAdmin.DEF_MINIMUM_PASSWORD_UPPER_CASE;
+                metrics.lowerCase = ActiveAdmin.DEF_MINIMUM_PASSWORD_LOWER_CASE;
+                metrics.numeric = ActiveAdmin.DEF_MINIMUM_PASSWORD_NUMERIC;
+                metrics.symbols = ActiveAdmin.DEF_MINIMUM_PASSWORD_SYMBOLS;
+                metrics.nonLetter = ActiveAdmin.DEF_MINIMUM_PASSWORD_NON_LETTER;
+            }
+        }
+    }
+
+    /**
      * Updates a flag that tells us whether the user's password currently satisfies the
      * requirements set by all of the user's active admins. The flag is updated both in memory
      * and persisted to disk by calling {@link #saveSettingsLocked}, for the value of the flag
@@ -4280,6 +4308,7 @@
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
+            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_NUMERIC, "setPasswordMinimumLength");
             if (metrics.length != length) {
                 metrics.length = length;
                 updatePasswordValidityCheckpointLocked(userId, parent);
@@ -4294,10 +4323,19 @@
                 .write();
     }
 
+    private void ensureMinimumQuality(
+            int userId, ActiveAdmin admin, int minimumQuality, String operation) {
+        if (admin.minimumPasswordMetrics.quality < minimumQuality
+                && getTargetSdk(admin.info.getPackageName(), userId) > Build.VERSION_CODES.Q) {
+            throw new IllegalStateException(String.format(
+                    "password quality should be at least %d for %s", minimumQuality, operation));
+        }
+    }
+
     @Override
     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
         return getStrictestPasswordRequirement(who, userHandle, parent,
-                admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED);
+                admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_NUMERIC);
     }
 
     @Override
@@ -4524,6 +4562,8 @@
         synchronized (getLockObject()) {
             final ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
+            ensureMinimumQuality(
+                    userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumUpperCase");
             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
             if (metrics.upperCase != length) {
                 metrics.upperCase = length;
@@ -4552,6 +4592,8 @@
         synchronized (getLockObject()) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
+            ensureMinimumQuality(
+                    userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLowerCase");
             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
             if (metrics.lowerCase != length) {
                 metrics.lowerCase = length;
@@ -4583,6 +4625,7 @@
         synchronized (getLockObject()) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
+            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLetters");
             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
             if (metrics.letters != length) {
                 metrics.letters = length;
@@ -4614,6 +4657,7 @@
         synchronized (getLockObject()) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
+            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNumeric");
             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
             if (metrics.numeric != length) {
                 metrics.numeric = length;
@@ -4645,6 +4689,7 @@
         synchronized (getLockObject()) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
+            ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumSymbols");
             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
             if (metrics.symbols != length) {
                 ap.minimumPasswordMetrics.symbols = length;
@@ -4676,6 +4721,8 @@
         synchronized (getLockObject()) {
             ActiveAdmin ap = getActiveAdminForCallerLocked(
                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
+            ensureMinimumQuality(
+                    userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNonLetter");
             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
             if (metrics.nonLetter != length) {
                 ap.minimumPasswordMetrics.nonLetter = length;
@@ -5816,6 +5863,8 @@
         idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
         idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
         idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
+        idTypeToAttestationFlag.put(
+                ID_TYPE_INDIVIDUAL_ATTESTATION, AttestationUtils.USE_INDIVIDUAL_ATTESTATION);
 
         int numFlagsSet = Integer.bitCount(idAttestationFlags);
         // No flags are set - return null to indicate no device ID attestation information should
@@ -7389,8 +7438,7 @@
 
         final long callingIdentity = mInjector.binderClearCallingIdentity();
         try {
-            mInjector.getIActivityManager().requestBugReport(
-                    ActivityManager.BUGREPORT_OPTION_REMOTE);
+            mInjector.getIActivityManager().requestRemoteBugReport();
 
             mRemoteBugreportServiceIsActive.set(true);
             mRemoteBugreportSharingAccepted.set(false);
@@ -8009,6 +8057,10 @@
                         "clearDeviceOwner can only be called by the device owner");
             }
             enforceUserUnlocked(deviceOwnerUserId);
+            DevicePolicyData policy = getUserData(deviceOwnerUserId);
+            if (policy.mPasswordTokenHandle != 0) {
+                mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, deviceOwnerUserId);
+            }
 
             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
             long ident = mInjector.binderClearCallingIdentity();
@@ -8911,6 +8963,8 @@
             pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
             pw.println();
             mPolicyCache.dump(pw);
+            pw.println();
+            mStateCache.dump(pw);
         }
     }
 
@@ -11122,6 +11176,9 @@
                 DevicePolicyData policy = getUserData(userHandle);
                 if (!policy.mUserSetupComplete) {
                     policy.mUserSetupComplete = true;
+                    if (userHandle == UserHandle.USER_SYSTEM) {
+                        mStateCache.setDeviceProvisioned(true);
+                    }
                     synchronized (getLockObject()) {
                         saveSettingsLocked(userHandle);
                     }
@@ -11263,6 +11320,28 @@
             }
         }
 
+        @Override
+        public boolean isActiveSupervisionApp(int uid) {
+            synchronized (getLockObject()) {
+                final ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
+                        null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, uid);
+                if (admin == null) {
+                    return false;
+                }
+
+                final String supervisionString = mContext.getResources().getString(
+                        com.android.internal.R.string
+                                .config_defaultSupervisionProfileOwnerComponent);
+                if (supervisionString == null) {
+                    return false;
+                }
+
+                final ComponentName supervisorComponent = ComponentName.unflattenFromString(
+                        supervisionString);
+                return admin.info.getComponent().equals(supervisorComponent);
+            }
+        }
+
         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
             synchronized (getLockObject()) {
@@ -11434,6 +11513,12 @@
         protected DevicePolicyCache getDevicePolicyCache() {
             return mPolicyCache;
         }
+
+        @Override
+        protected DeviceStateCache getDeviceStateCache() {
+            return mStateCache;
+        }
+
     }
 
     private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
@@ -11839,10 +11924,13 @@
                     try {
                         int uid = packageManager.getPackageUidAsUser(packageName,
                                 user.getIdentifier());
-
-                        // TODO: Prevent noting the app-op
-                        granted = PermissionChecker.checkPermission(mContext, permission, -1,
-                                uid, packageName);
+                        if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
+                                PermissionChecker.PID_UNKNOWN, uid, packageName)
+                                        != PermissionChecker.PERMISSION_GRANTED) {
+                            granted = PackageManager.PERMISSION_DENIED;
+                        } else {
+                            granted = PackageManager.PERMISSION_GRANTED;
+                        }
                     } catch (NameNotFoundException e) {
                         throw new RemoteException(
                                 "Cannot check if " + permission + "is a runtime permission", e,
@@ -12974,6 +13062,7 @@
                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
         DevicePolicyData policy = getUserData(userId);
         policy.mUserSetupComplete = isUserCompleted;
+        mStateCache.setDeviceProvisioned(isUserCompleted);
         synchronized (getLockObject()) {
             saveSettingsLocked(userId);
         }
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DeviceStateCacheImpl.java b/services/devicepolicy/java/com/android/server/devicepolicy/DeviceStateCacheImpl.java
new file mode 100644
index 0000000..c3cb9b0
--- /dev/null
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DeviceStateCacheImpl.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2019 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.devicepolicy;
+
+import android.app.admin.DeviceStateCache;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.internal.util.IndentingPrintWriter;
+
+/**
+ * Implementation of {@link DeviceStateCache}, to which {@link DevicePolicyManagerService} pushes
+ * device state.
+ *
+ */
+public class DeviceStateCacheImpl extends DeviceStateCache {
+    /**
+     * Lock object. For simplicity we just always use this as the lock. We could use each object
+     * as a lock object to make it more fine-grained, but that'd make copy-paste error-prone.
+     */
+    private final Object mLock = new Object();
+
+    @GuardedBy("mLock")
+    private boolean mIsDeviceProvisioned = false;
+
+    @Override
+    public boolean isDeviceProvisioned() {
+        return mIsDeviceProvisioned;
+    }
+
+    /** Update the device provisioned flag for USER_SYSTEM */
+    public void setDeviceProvisioned(boolean provisioned) {
+        synchronized (mLock) {
+            mIsDeviceProvisioned = provisioned;
+        }
+    }
+
+    /** Dump content */
+    public void dump(IndentingPrintWriter pw) {
+        pw.println("Device state cache:");
+        pw.increaseIndent();
+        pw.println("Device provisioned: " + mIsDeviceProvisioned);
+        pw.decreaseIndent();
+    }
+}
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 90d0c30..a453164 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -141,7 +141,6 @@
 import com.android.server.security.KeyChainSystemService;
 import com.android.server.signedconfig.SignedConfigService;
 import com.android.server.soundtrigger.SoundTriggerService;
-import com.android.server.stats.StatsCompanionService;
 import com.android.server.statusbar.StatusBarManagerService;
 import com.android.server.storage.DeviceStorageMonitorService;
 import com.android.server.telecom.TelecomLoaderService;
@@ -202,6 +201,8 @@
             "com.android.server.print.PrintManagerService";
     private static final String COMPANION_DEVICE_MANAGER_SERVICE_CLASS =
             "com.android.server.companion.CompanionDeviceManagerService";
+    private static final String STATS_COMPANION_SERVICE_LIFECYCLE_CLASS =
+            "com.android.server.stats.StatsCompanionService$Lifecycle";
     private static final String USB_SERVICE_CLASS =
             "com.android.server.usb.UsbService$Lifecycle";
     private static final String MIDI_SERVICE_CLASS =
@@ -500,7 +501,7 @@
                     mRuntimeStartElapsedTime, mRuntimeStartUptime);
             LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
             // Prepare the thread pool for init tasks that can be parallelized
-            SystemServerInitThreadPool.get();
+            SystemServerInitThreadPool.start();
         } finally {
             t.traceEnd();  // InitBeforeStartServices
         }
@@ -803,7 +804,7 @@
 
         // Manages Overlay packages
         t.traceBegin("StartOverlayManagerService");
-        mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
+        mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
         t.traceEnd();
 
         t.traceBegin("StartSensorPrivacyService");
@@ -1875,7 +1876,7 @@
 
         // Statsd helper
         t.traceBegin("StartStatsCompanionService");
-        mSystemServiceManager.startService(StatsCompanionService.Lifecycle.class);
+        mSystemServiceManager.startService(STATS_COMPANION_SERVICE_LIFECYCLE_CLASS);
         t.traceEnd();
 
         // Incidentd and dumpstated helper
diff --git a/services/net/Android.bp b/services/net/Android.bp
index 8f8f9f9..1ca96ed 100644
--- a/services/net/Android.bp
+++ b/services/net/Android.bp
@@ -1,87 +1,10 @@
-// AIDL interfaces between the core system and the networking mainline module.
-aidl_interface {
-    name: "ipmemorystore-aidl-interfaces",
-    local_include_dir: "java",
-    srcs: [
-        "java/android/net/IIpMemoryStore.aidl",
-        "java/android/net/IIpMemoryStoreCallbacks.aidl",
-        "java/android/net/ipmemorystore/**/*.aidl",
-    ],
-    backend: {
-        ndk: {
-            enabled: false,
-        },
-        cpp: {
-            enabled: false,
-        },
-    },
-    api_dir: "aidl/ipmemorystore",
-    versions: [
-        "1",
-        "2",
-        "3",
-    ],
-}
-
-aidl_interface {
-    name: "networkstack-aidl-interfaces",
-    local_include_dir: "java",
-    include_dirs: ["frameworks/base/core/java"], // For framework parcelables.
-    srcs: [
-        "java/android/net/DhcpResultsParcelable.aidl",
-        "java/android/net/INetworkMonitor.aidl",
-        "java/android/net/INetworkMonitorCallbacks.aidl",
-        "java/android/net/INetworkStackConnector.aidl",
-        "java/android/net/INetworkStackStatusCallback.aidl",
-        "java/android/net/InitialConfigurationParcelable.aidl",
-        "java/android/net/NattKeepalivePacketDataParcelable.aidl",
-        "java/android/net/PrivateDnsConfigParcel.aidl",
-        "java/android/net/ProvisioningConfigurationParcelable.aidl",
-        "java/android/net/TcpKeepalivePacketDataParcelable.aidl",
-        "java/android/net/dhcp/DhcpServingParamsParcel.aidl",
-        "java/android/net/dhcp/IDhcpServer.aidl",
-        "java/android/net/dhcp/IDhcpServerCallbacks.aidl",
-        "java/android/net/ip/IIpClient.aidl",
-        "java/android/net/ip/IIpClientCallbacks.aidl",
-    ],
-    backend: {
-        ndk: {
-            enabled: false,
-        },
-        cpp: {
-            enabled: false,
-        },
-    },
-    api_dir: "aidl/networkstack",
-    imports: ["ipmemorystore-aidl-interfaces"],
-    versions: [
-        "1",
-        "2",
-        "3",
-    ],
-}
-
 java_library_static {
     name: "services.net",
     srcs: ["java/**/*.java"],
     static_libs: [
         "dnsresolver_aidl_interface-V2-java",
-        "ipmemorystore-client",
         "netd_aidl_interface-java",
-        "networkstack-aidl-interfaces-V3-java",
-    ],
-}
-
-java_library_static {
-    name: "ipmemorystore-client",
-    sdk_version: "system_current",
-    srcs: [
-        ":framework-annotations",
-        "java/android/net/IpMemoryStoreClient.java",
-        "java/android/net/ipmemorystore/**/*.java",
-    ],
-    static_libs: [
-        "ipmemorystore-aidl-interfaces-V3-java",
+        "networkstack-client",
     ],
 }
 
diff --git a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStore.aidl b/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index a8cbab2..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,9 +0,0 @@
-package android.net;
-interface IIpMemoryStore {
-  oneway void storeNetworkAttributes(String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnStatusListener listener);
-  oneway void storeBlob(String l2Key, String clientId, String name, in android.net.ipmemorystore.Blob data, android.net.ipmemorystore.IOnStatusListener listener);
-  oneway void findL2Key(in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnL2KeyResponseListener listener);
-  oneway void isSameNetwork(String l2Key1, String l2Key2, android.net.ipmemorystore.IOnSameL3NetworkResponseListener listener);
-  oneway void retrieveNetworkAttributes(String l2Key, android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener listener);
-  oneway void retrieveBlob(String l2Key, String clientId, String name, android.net.ipmemorystore.IOnBlobRetrievedListener listener);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStoreCallbacks.aidl
deleted file mode 100644
index cf02c26..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/IIpMemoryStoreCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface IIpMemoryStoreCallbacks {
-  oneway void onIpMemoryStoreFetched(in android.net.IIpMemoryStore ipMemoryStore);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/Blob.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 291dbef..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable Blob {
-  byte[] data;
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 52f40d4..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnBlobRetrievedListener {
-  oneway void onBlobRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in String name, in android.net.ipmemorystore.Blob data);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index 7853514..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnL2KeyResponseListener {
-  oneway void onL2KeyResponse(in android.net.ipmemorystore.StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index 3dd2ae6..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnNetworkAttributesRetrievedListener {
-  oneway void onNetworkAttributesRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index 46d4ecb..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnSameL3NetworkResponseListener {
-  oneway void onSameL3NetworkResponse(in android.net.ipmemorystore.StatusParcelable status, in android.net.ipmemorystore.SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 54e654b..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnStatusListener {
-  oneway void onComplete(in android.net.ipmemorystore.StatusParcelable status);
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 9531ea3..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net.ipmemorystore;
-parcelable NetworkAttributesParcelable {
-  byte[] assignedV4Address;
-  long assignedV4AddressExpiry;
-  String groupHint;
-  android.net.ipmemorystore.Blob[] dnsAddresses;
-  int mtu;
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 414272b..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,6 +0,0 @@
-package android.net.ipmemorystore;
-parcelable SameL3NetworkResponseParcelable {
-  String l2Key1;
-  String l2Key2;
-  float confidence;
-}
diff --git a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index 92c6779..0000000
--- a/services/net/aidl/ipmemorystore/1/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable StatusParcelable {
-  int resultCode;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStore.aidl b/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index a8cbab2..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,9 +0,0 @@
-package android.net;
-interface IIpMemoryStore {
-  oneway void storeNetworkAttributes(String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnStatusListener listener);
-  oneway void storeBlob(String l2Key, String clientId, String name, in android.net.ipmemorystore.Blob data, android.net.ipmemorystore.IOnStatusListener listener);
-  oneway void findL2Key(in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnL2KeyResponseListener listener);
-  oneway void isSameNetwork(String l2Key1, String l2Key2, android.net.ipmemorystore.IOnSameL3NetworkResponseListener listener);
-  oneway void retrieveNetworkAttributes(String l2Key, android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener listener);
-  oneway void retrieveBlob(String l2Key, String clientId, String name, android.net.ipmemorystore.IOnBlobRetrievedListener listener);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStoreCallbacks.aidl
deleted file mode 100644
index cf02c26..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/IIpMemoryStoreCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface IIpMemoryStoreCallbacks {
-  oneway void onIpMemoryStoreFetched(in android.net.IIpMemoryStore ipMemoryStore);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/Blob.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 291dbef..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable Blob {
-  byte[] data;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 52f40d4..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnBlobRetrievedListener {
-  oneway void onBlobRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in String name, in android.net.ipmemorystore.Blob data);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index 7853514..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnL2KeyResponseListener {
-  oneway void onL2KeyResponse(in android.net.ipmemorystore.StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index 3dd2ae6..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnNetworkAttributesRetrievedListener {
-  oneway void onNetworkAttributesRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index 46d4ecb..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnSameL3NetworkResponseListener {
-  oneway void onSameL3NetworkResponse(in android.net.ipmemorystore.StatusParcelable status, in android.net.ipmemorystore.SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 54e654b..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-interface IOnStatusListener {
-  oneway void onComplete(in android.net.ipmemorystore.StatusParcelable status);
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 9531ea3..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net.ipmemorystore;
-parcelable NetworkAttributesParcelable {
-  byte[] assignedV4Address;
-  long assignedV4AddressExpiry;
-  String groupHint;
-  android.net.ipmemorystore.Blob[] dnsAddresses;
-  int mtu;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 414272b..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,6 +0,0 @@
-package android.net.ipmemorystore;
-parcelable SameL3NetworkResponseParcelable {
-  String l2Key1;
-  String l2Key2;
-  float confidence;
-}
diff --git a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index 92c6779..0000000
--- a/services/net/aidl/ipmemorystore/2/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.ipmemorystore;
-parcelable StatusParcelable {
-  int resultCode;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStore.aidl b/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index 30893b2..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface IIpMemoryStore {
-  oneway void storeNetworkAttributes(String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnStatusListener listener);
-  oneway void storeBlob(String l2Key, String clientId, String name, in android.net.ipmemorystore.Blob data, android.net.ipmemorystore.IOnStatusListener listener);
-  oneway void findL2Key(in android.net.ipmemorystore.NetworkAttributesParcelable attributes, android.net.ipmemorystore.IOnL2KeyResponseListener listener);
-  oneway void isSameNetwork(String l2Key1, String l2Key2, android.net.ipmemorystore.IOnSameL3NetworkResponseListener listener);
-  oneway void retrieveNetworkAttributes(String l2Key, android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener listener);
-  oneway void retrieveBlob(String l2Key, String clientId, String name, android.net.ipmemorystore.IOnBlobRetrievedListener listener);
-  oneway void factoryReset();
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStoreCallbacks.aidl
deleted file mode 100644
index 535ae2c..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/IIpMemoryStoreCallbacks.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface IIpMemoryStoreCallbacks {
-  oneway void onIpMemoryStoreFetched(in android.net.IIpMemoryStore ipMemoryStore);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/Blob.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 6d2dc0c..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable Blob {
-  byte[] data;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 48c1fb8..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnBlobRetrievedListener {
-  oneway void onBlobRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in String name, in android.net.ipmemorystore.Blob data);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index aebc724..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnL2KeyResponseListener {
-  oneway void onL2KeyResponse(in android.net.ipmemorystore.StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index b66db5a..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnNetworkAttributesRetrievedListener {
-  oneway void onNetworkAttributesRetrieved(in android.net.ipmemorystore.StatusParcelable status, in String l2Key, in android.net.ipmemorystore.NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index e9f2db4..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnSameL3NetworkResponseListener {
-  oneway void onSameL3NetworkResponse(in android.net.ipmemorystore.StatusParcelable status, in android.net.ipmemorystore.SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 49172ce..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-interface IOnStatusListener {
-  oneway void onComplete(in android.net.ipmemorystore.StatusParcelable status);
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 188db20..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,25 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable NetworkAttributesParcelable {
-  byte[] assignedV4Address;
-  long assignedV4AddressExpiry;
-  String groupHint;
-  android.net.ipmemorystore.Blob[] dnsAddresses;
-  int mtu;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 7a2ed48..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,23 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable SameL3NetworkResponseParcelable {
-  String l2Key1;
-  String l2Key2;
-  float confidence;
-}
diff --git a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index d9b0678..0000000
--- a/services/net/aidl/ipmemorystore/3/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ipmemorystore;
-parcelable StatusParcelable {
-  int resultCode;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/DhcpResultsParcelable.aidl b/services/net/aidl/networkstack/1/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index 92b5345..0000000
--- a/services/net/aidl/networkstack/1/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net;
-parcelable DhcpResultsParcelable {
-  android.net.StaticIpConfiguration baseConfiguration;
-  int leaseDuration;
-  int mtu;
-  String serverAddress;
-  String vendorInfo;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkMonitor.aidl b/services/net/aidl/networkstack/1/android/net/INetworkMonitor.aidl
deleted file mode 100644
index b19f522..0000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,17 +0,0 @@
-package android.net;
-interface INetworkMonitor {
-  oneway void start();
-  oneway void launchCaptivePortalApp();
-  oneway void notifyCaptivePortalAppFinished(int response);
-  oneway void setAcceptPartialConnectivity();
-  oneway void forceReevaluation(int uid);
-  oneway void notifyPrivateDnsChanged(in android.net.PrivateDnsConfigParcel config);
-  oneway void notifyDnsResponse(int returnCode);
-  oneway void notifyNetworkConnected(in android.net.LinkProperties lp, in android.net.NetworkCapabilities nc);
-  oneway void notifyNetworkDisconnected();
-  oneway void notifyLinkPropertiesChanged(in android.net.LinkProperties lp);
-  oneway void notifyNetworkCapabilitiesChanged(in android.net.NetworkCapabilities nc);
-  const int NETWORK_TEST_RESULT_VALID = 0;
-  const int NETWORK_TEST_RESULT_INVALID = 1;
-  const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkMonitorCallbacks.aidl b/services/net/aidl/networkstack/1/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index ee9871d..0000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net;
-interface INetworkMonitorCallbacks {
-  oneway void onNetworkMonitorCreated(in android.net.INetworkMonitor networkMonitor);
-  oneway void notifyNetworkTested(int testResult, @nullable String redirectUrl);
-  oneway void notifyPrivateDnsConfigResolved(in android.net.PrivateDnsConfigParcel config);
-  oneway void showProvisioningNotification(String action, String packageName);
-  oneway void hideProvisioningNotification();
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkStackConnector.aidl b/services/net/aidl/networkstack/1/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index 7da11e4..0000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-interface INetworkStackConnector {
-  oneway void makeDhcpServer(in String ifName, in android.net.dhcp.DhcpServingParamsParcel params, in android.net.dhcp.IDhcpServerCallbacks cb);
-  oneway void makeNetworkMonitor(in android.net.Network network, String name, in android.net.INetworkMonitorCallbacks cb);
-  oneway void makeIpClient(in String ifName, in android.net.ip.IIpClientCallbacks callbacks);
-  oneway void fetchIpMemoryStore(in android.net.IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/INetworkStackStatusCallback.aidl b/services/net/aidl/networkstack/1/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index f6ca6f7..0000000
--- a/services/net/aidl/networkstack/1/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface INetworkStackStatusCallback {
-  oneway void onStatusAvailable(int statusCode);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/InitialConfigurationParcelable.aidl b/services/net/aidl/networkstack/1/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index c80a787..0000000
--- a/services/net/aidl/networkstack/1/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-parcelable InitialConfigurationParcelable {
-  android.net.LinkAddress[] ipAddresses;
-  android.net.IpPrefix[] directlyConnectedRoutes;
-  String[] dnsServers;
-  String gateway;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/PrivateDnsConfigParcel.aidl b/services/net/aidl/networkstack/1/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index 2de790b..0000000
--- a/services/net/aidl/networkstack/1/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,5 +0,0 @@
-package android.net;
-parcelable PrivateDnsConfigParcel {
-  String hostname;
-  String[] ips;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/aidl/networkstack/1/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index 3a6c304..0000000
--- a/services/net/aidl/networkstack/1/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,15 +0,0 @@
-package android.net;
-parcelable ProvisioningConfigurationParcelable {
-  boolean enableIPv4;
-  boolean enableIPv6;
-  boolean usingMultinetworkPolicyTracker;
-  boolean usingIpReachabilityMonitor;
-  int requestedPreDhcpActionMs;
-  android.net.InitialConfigurationParcelable initialConfig;
-  android.net.StaticIpConfiguration staticIpConfig;
-  android.net.apf.ApfCapabilities apfCapabilities;
-  int provisioningTimeoutMs;
-  int ipv6AddrGenMode;
-  android.net.Network network;
-  String displayName;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/1/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index e121c06..0000000
--- a/services/net/aidl/networkstack/1/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,13 +0,0 @@
-package android.net;
-parcelable TcpKeepalivePacketDataParcelable {
-  byte[] srcAddress;
-  int srcPort;
-  byte[] dstAddress;
-  int dstPort;
-  int seq;
-  int ack;
-  int rcvWnd;
-  int rcvWndScale;
-  int tos;
-  int ttl;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/aidl/networkstack/1/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 67193ae..0000000
--- a/services/net/aidl/networkstack/1/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,11 +0,0 @@
-package android.net.dhcp;
-parcelable DhcpServingParamsParcel {
-  int serverAddr;
-  int serverAddrPrefixLength;
-  int[] defaultRouters;
-  int[] dnsServers;
-  int[] excludedAddrs;
-  long dhcpLeaseTimeSecs;
-  int linkMtu;
-  boolean metered;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServer.aidl b/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index 9143158..0000000
--- a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,10 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServer {
-  oneway void start(in android.net.INetworkStackStatusCallback cb);
-  oneway void updateParams(in android.net.dhcp.DhcpServingParamsParcel params, in android.net.INetworkStackStatusCallback cb);
-  oneway void stop(in android.net.INetworkStackStatusCallback cb);
-  const int STATUS_UNKNOWN = 0;
-  const int STATUS_SUCCESS = 1;
-  const int STATUS_INVALID_ARGUMENT = 2;
-  const int STATUS_UNKNOWN_ERROR = 3;
-}
diff --git a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index dcc4489..0000000
--- a/services/net/aidl/networkstack/1/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServerCallbacks {
-  oneway void onDhcpServerCreated(int statusCode, in android.net.dhcp.IDhcpServer server);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/ip/IIpClient.aidl b/services/net/aidl/networkstack/1/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 95a1574..0000000
--- a/services/net/aidl/networkstack/1/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,14 +0,0 @@
-package android.net.ip;
-interface IIpClient {
-  oneway void completedPreDhcpAction();
-  oneway void confirmConfiguration();
-  oneway void readPacketFilterComplete(in byte[] data);
-  oneway void shutdown();
-  oneway void startProvisioning(in android.net.ProvisioningConfigurationParcelable req);
-  oneway void stop();
-  oneway void setTcpBufferSizes(in String tcpBufferSizes);
-  oneway void setHttpProxy(in android.net.ProxyInfo proxyInfo);
-  oneway void setMulticastFilter(boolean enabled);
-  oneway void addKeepalivePacketFilter(int slot, in android.net.TcpKeepalivePacketDataParcelable pkt);
-  oneway void removeKeepalivePacketFilter(int slot);
-}
diff --git a/services/net/aidl/networkstack/1/android/net/ip/IIpClientCallbacks.aidl b/services/net/aidl/networkstack/1/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index d6bc808..0000000
--- a/services/net/aidl/networkstack/1/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,16 +0,0 @@
-package android.net.ip;
-interface IIpClientCallbacks {
-  oneway void onIpClientCreated(in android.net.ip.IIpClient ipClient);
-  oneway void onPreDhcpAction();
-  oneway void onPostDhcpAction();
-  oneway void onNewDhcpResults(in android.net.DhcpResultsParcelable dhcpResults);
-  oneway void onProvisioningSuccess(in android.net.LinkProperties newLp);
-  oneway void onProvisioningFailure(in android.net.LinkProperties newLp);
-  oneway void onLinkPropertiesChange(in android.net.LinkProperties newLp);
-  oneway void onReachabilityLost(in String logMsg);
-  oneway void onQuit();
-  oneway void installPacketFilter(in byte[] filter);
-  oneway void startReadPacketFilter();
-  oneway void setFallbackMulticastFilter(boolean enabled);
-  oneway void setNeighborDiscoveryOffload(boolean enable);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/DhcpResultsParcelable.aidl b/services/net/aidl/networkstack/2/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index 31891de..0000000
--- a/services/net/aidl/networkstack/2/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,9 +0,0 @@
-package android.net;
-parcelable DhcpResultsParcelable {
-  android.net.StaticIpConfiguration baseConfiguration;
-  int leaseDuration;
-  int mtu;
-  String serverAddress;
-  String vendorInfo;
-  String serverHostName;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkMonitor.aidl b/services/net/aidl/networkstack/2/android/net/INetworkMonitor.aidl
deleted file mode 100644
index 029968b..0000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-package android.net;
-interface INetworkMonitor {
-  oneway void start();
-  oneway void launchCaptivePortalApp();
-  oneway void notifyCaptivePortalAppFinished(int response);
-  oneway void setAcceptPartialConnectivity();
-  oneway void forceReevaluation(int uid);
-  oneway void notifyPrivateDnsChanged(in android.net.PrivateDnsConfigParcel config);
-  oneway void notifyDnsResponse(int returnCode);
-  oneway void notifyNetworkConnected(in android.net.LinkProperties lp, in android.net.NetworkCapabilities nc);
-  oneway void notifyNetworkDisconnected();
-  oneway void notifyLinkPropertiesChanged(in android.net.LinkProperties lp);
-  oneway void notifyNetworkCapabilitiesChanged(in android.net.NetworkCapabilities nc);
-  const int NETWORK_TEST_RESULT_VALID = 0;
-  const int NETWORK_TEST_RESULT_INVALID = 1;
-  const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
-  const int NETWORK_VALIDATION_RESULT_VALID = 1;
-  const int NETWORK_VALIDATION_RESULT_PARTIAL = 2;
-  const int NETWORK_VALIDATION_PROBE_DNS = 4;
-  const int NETWORK_VALIDATION_PROBE_HTTP = 8;
-  const int NETWORK_VALIDATION_PROBE_HTTPS = 16;
-  const int NETWORK_VALIDATION_PROBE_FALLBACK = 32;
-  const int NETWORK_VALIDATION_PROBE_PRIVDNS = 64;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkMonitorCallbacks.aidl b/services/net/aidl/networkstack/2/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index ee9871d..0000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,8 +0,0 @@
-package android.net;
-interface INetworkMonitorCallbacks {
-  oneway void onNetworkMonitorCreated(in android.net.INetworkMonitor networkMonitor);
-  oneway void notifyNetworkTested(int testResult, @nullable String redirectUrl);
-  oneway void notifyPrivateDnsConfigResolved(in android.net.PrivateDnsConfigParcel config);
-  oneway void showProvisioningNotification(String action, String packageName);
-  oneway void hideProvisioningNotification();
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkStackConnector.aidl b/services/net/aidl/networkstack/2/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index 7da11e4..0000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-interface INetworkStackConnector {
-  oneway void makeDhcpServer(in String ifName, in android.net.dhcp.DhcpServingParamsParcel params, in android.net.dhcp.IDhcpServerCallbacks cb);
-  oneway void makeNetworkMonitor(in android.net.Network network, String name, in android.net.INetworkMonitorCallbacks cb);
-  oneway void makeIpClient(in String ifName, in android.net.ip.IIpClientCallbacks callbacks);
-  oneway void fetchIpMemoryStore(in android.net.IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/INetworkStackStatusCallback.aidl b/services/net/aidl/networkstack/2/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index f6ca6f7..0000000
--- a/services/net/aidl/networkstack/2/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net;
-interface INetworkStackStatusCallback {
-  oneway void onStatusAvailable(int statusCode);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/InitialConfigurationParcelable.aidl b/services/net/aidl/networkstack/2/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index c80a787..0000000
--- a/services/net/aidl/networkstack/2/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-parcelable InitialConfigurationParcelable {
-  android.net.LinkAddress[] ipAddresses;
-  android.net.IpPrefix[] directlyConnectedRoutes;
-  String[] dnsServers;
-  String gateway;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/NattKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/2/android/net/NattKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index 65de883..0000000
--- a/services/net/aidl/networkstack/2/android/net/NattKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.net;
-parcelable NattKeepalivePacketDataParcelable {
-  byte[] srcAddress;
-  int srcPort;
-  byte[] dstAddress;
-  int dstPort;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/PrivateDnsConfigParcel.aidl b/services/net/aidl/networkstack/2/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index 2de790b..0000000
--- a/services/net/aidl/networkstack/2/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,5 +0,0 @@
-package android.net;
-parcelable PrivateDnsConfigParcel {
-  String hostname;
-  String[] ips;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/aidl/networkstack/2/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index 3a6c304..0000000
--- a/services/net/aidl/networkstack/2/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,15 +0,0 @@
-package android.net;
-parcelable ProvisioningConfigurationParcelable {
-  boolean enableIPv4;
-  boolean enableIPv6;
-  boolean usingMultinetworkPolicyTracker;
-  boolean usingIpReachabilityMonitor;
-  int requestedPreDhcpActionMs;
-  android.net.InitialConfigurationParcelable initialConfig;
-  android.net.StaticIpConfiguration staticIpConfig;
-  android.net.apf.ApfCapabilities apfCapabilities;
-  int provisioningTimeoutMs;
-  int ipv6AddrGenMode;
-  android.net.Network network;
-  String displayName;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/2/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index e121c06..0000000
--- a/services/net/aidl/networkstack/2/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,13 +0,0 @@
-package android.net;
-parcelable TcpKeepalivePacketDataParcelable {
-  byte[] srcAddress;
-  int srcPort;
-  byte[] dstAddress;
-  int dstPort;
-  int seq;
-  int ack;
-  int rcvWnd;
-  int rcvWndScale;
-  int tos;
-  int ttl;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/aidl/networkstack/2/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 67193ae..0000000
--- a/services/net/aidl/networkstack/2/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,11 +0,0 @@
-package android.net.dhcp;
-parcelable DhcpServingParamsParcel {
-  int serverAddr;
-  int serverAddrPrefixLength;
-  int[] defaultRouters;
-  int[] dnsServers;
-  int[] excludedAddrs;
-  long dhcpLeaseTimeSecs;
-  int linkMtu;
-  boolean metered;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServer.aidl b/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index 9143158..0000000
--- a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,10 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServer {
-  oneway void start(in android.net.INetworkStackStatusCallback cb);
-  oneway void updateParams(in android.net.dhcp.DhcpServingParamsParcel params, in android.net.INetworkStackStatusCallback cb);
-  oneway void stop(in android.net.INetworkStackStatusCallback cb);
-  const int STATUS_UNKNOWN = 0;
-  const int STATUS_SUCCESS = 1;
-  const int STATUS_INVALID_ARGUMENT = 2;
-  const int STATUS_UNKNOWN_ERROR = 3;
-}
diff --git a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index dcc4489..0000000
--- a/services/net/aidl/networkstack/2/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,4 +0,0 @@
-package android.net.dhcp;
-interface IDhcpServerCallbacks {
-  oneway void onDhcpServerCreated(int statusCode, in android.net.dhcp.IDhcpServer server);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/ip/IIpClient.aidl b/services/net/aidl/networkstack/2/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 77d5917..0000000
--- a/services/net/aidl/networkstack/2/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,15 +0,0 @@
-package android.net.ip;
-interface IIpClient {
-  oneway void completedPreDhcpAction();
-  oneway void confirmConfiguration();
-  oneway void readPacketFilterComplete(in byte[] data);
-  oneway void shutdown();
-  oneway void startProvisioning(in android.net.ProvisioningConfigurationParcelable req);
-  oneway void stop();
-  oneway void setTcpBufferSizes(in String tcpBufferSizes);
-  oneway void setHttpProxy(in android.net.ProxyInfo proxyInfo);
-  oneway void setMulticastFilter(boolean enabled);
-  oneway void addKeepalivePacketFilter(int slot, in android.net.TcpKeepalivePacketDataParcelable pkt);
-  oneway void removeKeepalivePacketFilter(int slot);
-  oneway void setL2KeyAndGroupHint(in String l2Key, in String groupHint);
-}
diff --git a/services/net/aidl/networkstack/2/android/net/ip/IIpClientCallbacks.aidl b/services/net/aidl/networkstack/2/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index d6bc808..0000000
--- a/services/net/aidl/networkstack/2/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,16 +0,0 @@
-package android.net.ip;
-interface IIpClientCallbacks {
-  oneway void onIpClientCreated(in android.net.ip.IIpClient ipClient);
-  oneway void onPreDhcpAction();
-  oneway void onPostDhcpAction();
-  oneway void onNewDhcpResults(in android.net.DhcpResultsParcelable dhcpResults);
-  oneway void onProvisioningSuccess(in android.net.LinkProperties newLp);
-  oneway void onProvisioningFailure(in android.net.LinkProperties newLp);
-  oneway void onLinkPropertiesChange(in android.net.LinkProperties newLp);
-  oneway void onReachabilityLost(in String logMsg);
-  oneway void onQuit();
-  oneway void installPacketFilter(in byte[] filter);
-  oneway void startReadPacketFilter();
-  oneway void setFallbackMulticastFilter(boolean enabled);
-  oneway void setNeighborDiscoveryOffload(boolean enable);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/DhcpResultsParcelable.aidl b/services/net/aidl/networkstack/3/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index 07ff321..0000000
--- a/services/net/aidl/networkstack/3/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,26 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable DhcpResultsParcelable {
-  android.net.StaticIpConfiguration baseConfiguration;
-  int leaseDuration;
-  int mtu;
-  String serverAddress;
-  String vendorInfo;
-  String serverHostName;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkMonitor.aidl b/services/net/aidl/networkstack/3/android/net/INetworkMonitor.aidl
deleted file mode 100644
index 8aa68bd..0000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,41 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkMonitor {
-  oneway void start();
-  oneway void launchCaptivePortalApp();
-  oneway void notifyCaptivePortalAppFinished(int response);
-  oneway void setAcceptPartialConnectivity();
-  oneway void forceReevaluation(int uid);
-  oneway void notifyPrivateDnsChanged(in android.net.PrivateDnsConfigParcel config);
-  oneway void notifyDnsResponse(int returnCode);
-  oneway void notifyNetworkConnected(in android.net.LinkProperties lp, in android.net.NetworkCapabilities nc);
-  oneway void notifyNetworkDisconnected();
-  oneway void notifyLinkPropertiesChanged(in android.net.LinkProperties lp);
-  oneway void notifyNetworkCapabilitiesChanged(in android.net.NetworkCapabilities nc);
-  const int NETWORK_TEST_RESULT_VALID = 0;
-  const int NETWORK_TEST_RESULT_INVALID = 1;
-  const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
-  const int NETWORK_VALIDATION_RESULT_VALID = 1;
-  const int NETWORK_VALIDATION_RESULT_PARTIAL = 2;
-  const int NETWORK_VALIDATION_PROBE_DNS = 4;
-  const int NETWORK_VALIDATION_PROBE_HTTP = 8;
-  const int NETWORK_VALIDATION_PROBE_HTTPS = 16;
-  const int NETWORK_VALIDATION_PROBE_FALLBACK = 32;
-  const int NETWORK_VALIDATION_PROBE_PRIVDNS = 64;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkMonitorCallbacks.aidl b/services/net/aidl/networkstack/3/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index ea93729..0000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,25 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkMonitorCallbacks {
-  oneway void onNetworkMonitorCreated(in android.net.INetworkMonitor networkMonitor);
-  oneway void notifyNetworkTested(int testResult, @nullable String redirectUrl);
-  oneway void notifyPrivateDnsConfigResolved(in android.net.PrivateDnsConfigParcel config);
-  oneway void showProvisioningNotification(String action, String packageName);
-  oneway void hideProvisioningNotification();
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkStackConnector.aidl b/services/net/aidl/networkstack/3/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index e3a83d1..0000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkStackConnector {
-  oneway void makeDhcpServer(in String ifName, in android.net.dhcp.DhcpServingParamsParcel params, in android.net.dhcp.IDhcpServerCallbacks cb);
-  oneway void makeNetworkMonitor(in android.net.Network network, String name, in android.net.INetworkMonitorCallbacks cb);
-  oneway void makeIpClient(in String ifName, in android.net.ip.IIpClientCallbacks callbacks);
-  oneway void fetchIpMemoryStore(in android.net.IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/INetworkStackStatusCallback.aidl b/services/net/aidl/networkstack/3/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index 3112a08..0000000
--- a/services/net/aidl/networkstack/3/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-interface INetworkStackStatusCallback {
-  oneway void onStatusAvailable(int statusCode);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/InitialConfigurationParcelable.aidl b/services/net/aidl/networkstack/3/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index f846b26..0000000
--- a/services/net/aidl/networkstack/3/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable InitialConfigurationParcelable {
-  android.net.LinkAddress[] ipAddresses;
-  android.net.IpPrefix[] directlyConnectedRoutes;
-  String[] dnsServers;
-  String gateway;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/NattKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/3/android/net/NattKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index de75940..0000000
--- a/services/net/aidl/networkstack/3/android/net/NattKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable NattKeepalivePacketDataParcelable {
-  byte[] srcAddress;
-  int srcPort;
-  byte[] dstAddress;
-  int dstPort;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/PrivateDnsConfigParcel.aidl b/services/net/aidl/networkstack/3/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index cf0fbce9..0000000
--- a/services/net/aidl/networkstack/3/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,22 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable PrivateDnsConfigParcel {
-  String hostname;
-  String[] ips;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/aidl/networkstack/3/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index c0f2d4d..0000000
--- a/services/net/aidl/networkstack/3/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,32 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable ProvisioningConfigurationParcelable {
-  boolean enableIPv4;
-  boolean enableIPv6;
-  boolean usingMultinetworkPolicyTracker;
-  boolean usingIpReachabilityMonitor;
-  int requestedPreDhcpActionMs;
-  android.net.InitialConfigurationParcelable initialConfig;
-  android.net.StaticIpConfiguration staticIpConfig;
-  android.net.apf.ApfCapabilities apfCapabilities;
-  int provisioningTimeoutMs;
-  int ipv6AddrGenMode;
-  android.net.Network network;
-  String displayName;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/aidl/networkstack/3/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index 5926794..0000000
--- a/services/net/aidl/networkstack/3/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net;
-parcelable TcpKeepalivePacketDataParcelable {
-  byte[] srcAddress;
-  int srcPort;
-  byte[] dstAddress;
-  int dstPort;
-  int seq;
-  int ack;
-  int rcvWnd;
-  int rcvWndScale;
-  int tos;
-  int ttl;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/aidl/networkstack/3/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 7ab156f..0000000
--- a/services/net/aidl/networkstack/3/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,28 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.dhcp;
-parcelable DhcpServingParamsParcel {
-  int serverAddr;
-  int serverAddrPrefixLength;
-  int[] defaultRouters;
-  int[] dnsServers;
-  int[] excludedAddrs;
-  long dhcpLeaseTimeSecs;
-  int linkMtu;
-  boolean metered;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServer.aidl b/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index d281ecf..0000000
--- a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.dhcp;
-interface IDhcpServer {
-  oneway void start(in android.net.INetworkStackStatusCallback cb);
-  oneway void updateParams(in android.net.dhcp.DhcpServingParamsParcel params, in android.net.INetworkStackStatusCallback cb);
-  oneway void stop(in android.net.INetworkStackStatusCallback cb);
-  const int STATUS_UNKNOWN = 0;
-  const int STATUS_SUCCESS = 1;
-  const int STATUS_INVALID_ARGUMENT = 2;
-  const int STATUS_UNKNOWN_ERROR = 3;
-}
diff --git a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index 98be0ab..0000000
--- a/services/net/aidl/networkstack/3/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.dhcp;
-interface IDhcpServerCallbacks {
-  oneway void onDhcpServerCreated(int statusCode, in android.net.dhcp.IDhcpServer server);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/ip/IIpClient.aidl b/services/net/aidl/networkstack/3/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 85c8676..0000000
--- a/services/net/aidl/networkstack/3/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,33 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ip;
-interface IIpClient {
-  oneway void completedPreDhcpAction();
-  oneway void confirmConfiguration();
-  oneway void readPacketFilterComplete(in byte[] data);
-  oneway void shutdown();
-  oneway void startProvisioning(in android.net.ProvisioningConfigurationParcelable req);
-  oneway void stop();
-  oneway void setTcpBufferSizes(in String tcpBufferSizes);
-  oneway void setHttpProxy(in android.net.ProxyInfo proxyInfo);
-  oneway void setMulticastFilter(boolean enabled);
-  oneway void addKeepalivePacketFilter(int slot, in android.net.TcpKeepalivePacketDataParcelable pkt);
-  oneway void removeKeepalivePacketFilter(int slot);
-  oneway void setL2KeyAndGroupHint(in String l2Key, in String groupHint);
-  oneway void addNattKeepalivePacketFilter(int slot, in android.net.NattKeepalivePacketDataParcelable pkt);
-}
diff --git a/services/net/aidl/networkstack/3/android/net/ip/IIpClientCallbacks.aidl b/services/net/aidl/networkstack/3/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index 7fe39ed..0000000
--- a/services/net/aidl/networkstack/3/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,33 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////
-// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
-///////////////////////////////////////////////////////////////////////////////
-
-// This file is a frozen snapshot of an AIDL interface (or parcelable). Do not
-// try to edit this file. It looks like you are doing that because you have
-// modified an AIDL interface in a backward-incompatible way, e.g., deleting a
-// function from an interface or a field from a parcelable and it broke the
-// build. That breakage is intended.
-//
-// You must not make a backward incompatible changes to the AIDL files built
-// with the aidl_interface module type with versions property set. The module
-// type is used to build AIDL files in a way that they can be used across
-// independently updatable components of the system. If a device is shipped
-// with such a backward incompatible change, it has a high risk of breaking
-// later when a module using the interface is updated, e.g., Mainline modules.
-
-package android.net.ip;
-interface IIpClientCallbacks {
-  oneway void onIpClientCreated(in android.net.ip.IIpClient ipClient);
-  oneway void onPreDhcpAction();
-  oneway void onPostDhcpAction();
-  oneway void onNewDhcpResults(in android.net.DhcpResultsParcelable dhcpResults);
-  oneway void onProvisioningSuccess(in android.net.LinkProperties newLp);
-  oneway void onProvisioningFailure(in android.net.LinkProperties newLp);
-  oneway void onLinkPropertiesChange(in android.net.LinkProperties newLp);
-  oneway void onReachabilityLost(in String logMsg);
-  oneway void onQuit();
-  oneway void installPacketFilter(in byte[] filter);
-  oneway void startReadPacketFilter();
-  oneway void setFallbackMulticastFilter(boolean enabled);
-  oneway void setNeighborDiscoveryOffload(boolean enable);
-}
diff --git a/services/net/java/android/net/DhcpResultsParcelable.aidl b/services/net/java/android/net/DhcpResultsParcelable.aidl
deleted file mode 100644
index c98d9c2..0000000
--- a/services/net/java/android/net/DhcpResultsParcelable.aidl
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Copyright (c) 2019, 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 perNmissions and
- * limitations under the License.
- */
-
-package android.net;
-
-import android.net.StaticIpConfiguration;
-
-parcelable DhcpResultsParcelable {
-    StaticIpConfiguration baseConfiguration;
-    int leaseDuration;
-    int mtu;
-    String serverAddress;
-    String vendorInfo;
-    String serverHostName;
-}
diff --git a/services/net/java/android/net/IIpMemoryStore.aidl b/services/net/java/android/net/IIpMemoryStore.aidl
deleted file mode 100644
index add221a..0000000
--- a/services/net/java/android/net/IIpMemoryStore.aidl
+++ /dev/null
@@ -1,118 +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 android.net;
-
-import android.net.ipmemorystore.Blob;
-import android.net.ipmemorystore.NetworkAttributesParcelable;
-import android.net.ipmemorystore.IOnBlobRetrievedListener;
-import android.net.ipmemorystore.IOnL2KeyResponseListener;
-import android.net.ipmemorystore.IOnNetworkAttributesRetrievedListener;
-import android.net.ipmemorystore.IOnSameL3NetworkResponseListener;
-import android.net.ipmemorystore.IOnStatusListener;
-
-/** {@hide} */
-oneway interface IIpMemoryStore {
-    /**
-     * Store network attributes for a given L2 key.
-     * If L2Key is null, choose automatically from the attributes ; passing null is equivalent to
-     * calling findL2Key with the attributes and storing in the returned value.
-     *
-     * @param l2Key The L2 key for the L2 network. Clients that don't know or care about the L2
-     *              key and only care about grouping can pass a unique ID here like the ones
-     *              generated by {@code java.util.UUID.randomUUID()}, but keep in mind the low
-     *              relevance of such a network will lead to it being evicted soon if it's not
-     *              refreshed. Use findL2Key to try and find a similar L2Key to these attributes.
-     * @param attributes The attributes for this network.
-     * @param listener A listener that will be invoked to inform of the completion of this call,
-     *                 or null if the client is not interested in learning about success/failure.
-     * @return (through the listener) The L2 key. This is useful if the L2 key was not specified.
-     *         If the call failed, the L2 key will be null.
-     */
-    void storeNetworkAttributes(String l2Key, in NetworkAttributesParcelable attributes,
-            IOnStatusListener listener);
-
-    /**
-     * Store a binary blob associated with an L2 key and a name.
-     *
-     * @param l2Key The L2 key for this network.
-     * @param clientId The ID of the client.
-     * @param name The name of this data.
-     * @param data The data to store.
-     * @param listener A listener to inform of the completion of this call, or null if the client
-     *        is not interested in learning about success/failure.
-     * @return (through the listener) A status to indicate success or failure.
-     */
-    void storeBlob(String l2Key, String clientId, String name, in Blob data,
-            IOnStatusListener listener);
-
-    /**
-     * Returns the best L2 key associated with the attributes.
-     *
-     * This will find a record that would be in the same group as the passed attributes. This is
-     * useful to choose the key for storing a sample or private data when the L2 key is not known.
-     * If multiple records are group-close to these attributes, the closest match is returned.
-     * If multiple records have the same closeness, the one with the smaller (unicode codepoint
-     * order) L2 key is returned.
-     * If no record matches these attributes, null is returned.
-     *
-     * @param attributes The attributes of the network to find.
-     * @param listener The listener that will be invoked to return the answer.
-     * @return (through the listener) The L2 key if one matched, or null.
-     */
-    void findL2Key(in NetworkAttributesParcelable attributes, IOnL2KeyResponseListener listener);
-
-    /**
-     * Returns whether, to the best of the store's ability to tell, the two specified L2 keys point
-     * to the same L3 network. Group-closeness is used to determine this.
-     *
-     * @param l2Key1 The key for the first network.
-     * @param l2Key2 The key for the second network.
-     * @param listener The listener that will be invoked to return the answer.
-     * @return (through the listener) A SameL3NetworkResponse containing the answer and confidence.
-     */
-    void isSameNetwork(String l2Key1, String l2Key2, IOnSameL3NetworkResponseListener listener);
-
-    /**
-     * Retrieve the network attributes for a key.
-     * If no record is present for this key, this will return null attributes.
-     *
-     * @param l2Key The key of the network to query.
-     * @param listener The listener that will be invoked to return the answer.
-     * @return (through the listener) The network attributes and the L2 key associated with
-     *         the query.
-     */
-    void retrieveNetworkAttributes(String l2Key, IOnNetworkAttributesRetrievedListener listener);
-
-    /**
-     * Retrieve previously stored private data.
-     * If no data was stored for this L2 key and name this will return null.
-     *
-     * @param l2Key The L2 key.
-     * @param clientId The id of the client that stored this data.
-     * @param name The name of the data.
-     * @param listener The listener that will be invoked to return the answer.
-     * @return (through the listener) The private data (or null), with the L2 key
-     *         and the name of the data associated with the query.
-     */
-    void retrieveBlob(String l2Key, String clientId, String name,
-            IOnBlobRetrievedListener listener);
-
-    /**
-     * Delete all data because a factory reset operation is in progress.
-     */
-    void factoryReset();
-}
diff --git a/services/net/java/android/net/IIpMemoryStoreCallbacks.aidl b/services/net/java/android/net/IIpMemoryStoreCallbacks.aidl
deleted file mode 100644
index 53108db..0000000
--- a/services/net/java/android/net/IIpMemoryStoreCallbacks.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-import android.net.IIpMemoryStore;
-
-/** {@hide} */
-oneway interface IIpMemoryStoreCallbacks {
-    void onIpMemoryStoreFetched(in IIpMemoryStore ipMemoryStore);
-}
diff --git a/services/net/java/android/net/INetworkMonitor.aidl b/services/net/java/android/net/INetworkMonitor.aidl
deleted file mode 100644
index 3fc81a3..0000000
--- a/services/net/java/android/net/INetworkMonitor.aidl
+++ /dev/null
@@ -1,68 +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 perNmissions and
- * limitations under the License.
- */
-package android.net;
-
-import android.net.LinkProperties;
-import android.net.NetworkCapabilities;
-import android.net.PrivateDnsConfigParcel;
-
-/** @hide */
-oneway interface INetworkMonitor {
-    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
-    // The network should be used as a default internet connection.  It was found to be:
-    // 1. a functioning network providing internet access, or
-    // 2. a captive portal and the user decided to use it as is.
-    const int NETWORK_TEST_RESULT_VALID = 0;
-
-    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
-    // The network should not be used as a default internet connection.  It was found to be:
-    // 1. a captive portal and the user is prompted to sign-in, or
-    // 2. a captive portal and the user did not want to use it, or
-    // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
-    const int NETWORK_TEST_RESULT_INVALID = 1;
-
-    // After a network has been tested, this result can be sent with EVENT_NETWORK_TESTED.
-    // The network may be used as a default internet connection, but it was found to be a partial
-    // connectivity network which can get the pass result for http probe but get the failed result
-    // for https probe.
-    const int NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY = 2;
-
-    // Network validation flags indicate probe result and types. If no NETWORK_VALIDATION_RESULT_*
-    // are set, then it's equal to NETWORK_TEST_RESULT_INVALID. If NETWORK_VALIDATION_RESULT_VALID
-    // is set, then the network validates and equal to NETWORK_TEST_RESULT_VALID. If
-    // NETWORK_VALIDATION_RESULT_PARTIAL is set, then the network has partial connectivity which
-    // is equal to NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY. NETWORK_VALIDATION_PROBE_* is set
-    // when the specific probe result of the network is resolved.
-    const int NETWORK_VALIDATION_RESULT_VALID = 0x01;
-    const int NETWORK_VALIDATION_RESULT_PARTIAL = 0x02;
-    const int NETWORK_VALIDATION_PROBE_DNS = 0x04;
-    const int NETWORK_VALIDATION_PROBE_HTTP = 0x08;
-    const int NETWORK_VALIDATION_PROBE_HTTPS = 0x10;
-    const int NETWORK_VALIDATION_PROBE_FALLBACK = 0x20;
-    const int NETWORK_VALIDATION_PROBE_PRIVDNS = 0x40;
-
-    void start();
-    void launchCaptivePortalApp();
-    void notifyCaptivePortalAppFinished(int response);
-    void setAcceptPartialConnectivity();
-    void forceReevaluation(int uid);
-    void notifyPrivateDnsChanged(in PrivateDnsConfigParcel config);
-    void notifyDnsResponse(int returnCode);
-    void notifyNetworkConnected(in LinkProperties lp, in NetworkCapabilities nc);
-    void notifyNetworkDisconnected();
-    void notifyLinkPropertiesChanged(in LinkProperties lp);
-    void notifyNetworkCapabilitiesChanged(in NetworkCapabilities nc);
-}
diff --git a/services/net/java/android/net/INetworkMonitorCallbacks.aidl b/services/net/java/android/net/INetworkMonitorCallbacks.aidl
deleted file mode 100644
index 2c61511..0000000
--- a/services/net/java/android/net/INetworkMonitorCallbacks.aidl
+++ /dev/null
@@ -1,29 +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 android.net;
-
-import android.net.INetworkMonitor;
-import android.net.PrivateDnsConfigParcel;
-
-/** @hide */
-oneway interface INetworkMonitorCallbacks {
-    void onNetworkMonitorCreated(in INetworkMonitor networkMonitor);
-    void notifyNetworkTested(int testResult, @nullable String redirectUrl);
-    void notifyPrivateDnsConfigResolved(in PrivateDnsConfigParcel config);
-    void showProvisioningNotification(String action, String packageName);
-    void hideProvisioningNotification();
-}
\ No newline at end of file
diff --git a/services/net/java/android/net/INetworkStackConnector.aidl b/services/net/java/android/net/INetworkStackConnector.aidl
deleted file mode 100644
index 3751c36..0000000
--- a/services/net/java/android/net/INetworkStackConnector.aidl
+++ /dev/null
@@ -1,32 +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 perNmissions and
- * limitations under the License.
- */
-package android.net;
-
-import android.net.IIpMemoryStoreCallbacks;
-import android.net.INetworkMonitorCallbacks;
-import android.net.Network;
-import android.net.dhcp.DhcpServingParamsParcel;
-import android.net.dhcp.IDhcpServerCallbacks;
-import android.net.ip.IIpClientCallbacks;
-
-/** @hide */
-oneway interface INetworkStackConnector {
-    void makeDhcpServer(in String ifName, in DhcpServingParamsParcel params,
-        in IDhcpServerCallbacks cb);
-    void makeNetworkMonitor(in Network network, String name, in INetworkMonitorCallbacks cb);
-    void makeIpClient(in String ifName, in IIpClientCallbacks callbacks);
-    void fetchIpMemoryStore(in IIpMemoryStoreCallbacks cb);
-}
diff --git a/services/net/java/android/net/INetworkStackStatusCallback.aidl b/services/net/java/android/net/INetworkStackStatusCallback.aidl
deleted file mode 100644
index 51032d8..0000000
--- a/services/net/java/android/net/INetworkStackStatusCallback.aidl
+++ /dev/null
@@ -1,22 +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 android.net;
-
-/** @hide */
-oneway interface INetworkStackStatusCallback {
-    void onStatusAvailable(int statusCode);
-}
\ No newline at end of file
diff --git a/services/net/java/android/net/InitialConfigurationParcelable.aidl b/services/net/java/android/net/InitialConfigurationParcelable.aidl
deleted file mode 100644
index 3fa88c3..0000000
--- a/services/net/java/android/net/InitialConfigurationParcelable.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-import android.net.IpPrefix;
-import android.net.LinkAddress;
-
-parcelable InitialConfigurationParcelable {
-    LinkAddress[] ipAddresses;
-    IpPrefix[] directlyConnectedRoutes;
-    String[] dnsServers;
-    String gateway;
-}
\ No newline at end of file
diff --git a/services/net/java/android/net/IpMemoryStoreClient.java b/services/net/java/android/net/IpMemoryStoreClient.java
deleted file mode 100644
index 014b528..0000000
--- a/services/net/java/android/net/IpMemoryStoreClient.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.Context;
-import android.net.ipmemorystore.Blob;
-import android.net.ipmemorystore.NetworkAttributes;
-import android.net.ipmemorystore.OnBlobRetrievedListener;
-import android.net.ipmemorystore.OnL2KeyResponseListener;
-import android.net.ipmemorystore.OnNetworkAttributesRetrievedListener;
-import android.net.ipmemorystore.OnSameL3NetworkResponseListener;
-import android.net.ipmemorystore.OnStatusListener;
-import android.net.ipmemorystore.Status;
-import android.os.RemoteException;
-import android.util.Log;
-
-import java.util.concurrent.ExecutionException;
-import java.util.function.Consumer;
-
-/**
- * service used to communicate with the ip memory store service in network stack,
- * which is running in a separate module.
- * @hide
- */
-public abstract class IpMemoryStoreClient {
-    private static final String TAG = IpMemoryStoreClient.class.getSimpleName();
-    private final Context mContext;
-
-    public IpMemoryStoreClient(@NonNull final Context context) {
-        if (context == null) throw new IllegalArgumentException("missing context");
-        mContext = context;
-    }
-
-    protected abstract void runWhenServiceReady(Consumer<IIpMemoryStore> cb)
-            throws ExecutionException;
-
-    @FunctionalInterface
-    private interface ThrowingRunnable {
-        void run() throws RemoteException;
-    }
-
-    private void ignoringRemoteException(ThrowingRunnable r) {
-        ignoringRemoteException("Failed to execute remote procedure call", r);
-    }
-
-    private void ignoringRemoteException(String message, ThrowingRunnable r) {
-        try {
-            r.run();
-        } catch (RemoteException e) {
-            Log.e(TAG, message, e);
-        }
-    }
-
-    /**
-     * Store network attributes for a given L2 key.
-     * If L2Key is null, choose automatically from the attributes ; passing null is equivalent to
-     * calling findL2Key with the attributes and storing in the returned value.
-     *
-     * @param l2Key The L2 key for the L2 network. Clients that don't know or care about the L2
-     *              key and only care about grouping can pass a unique ID here like the ones
-     *              generated by {@code java.util.UUID.randomUUID()}, but keep in mind the low
-     *              relevance of such a network will lead to it being evicted soon if it's not
-     *              refreshed. Use findL2Key to try and find a similar L2Key to these attributes.
-     * @param attributes The attributes for this network.
-     * @param listener A listener that will be invoked to inform of the completion of this call,
-     *                 or null if the client is not interested in learning about success/failure.
-     * Through the listener, returns the L2 key. This is useful if the L2 key was not specified.
-     * If the call failed, the L2 key will be null.
-     */
-    public void storeNetworkAttributes(@NonNull final String l2Key,
-            @NonNull final NetworkAttributes attributes,
-            @Nullable final OnStatusListener listener) {
-        try {
-            runWhenServiceReady(service -> ignoringRemoteException(
-                    () -> service.storeNetworkAttributes(l2Key, attributes.toParcelable(),
-                            OnStatusListener.toAIDL(listener))));
-        } catch (ExecutionException m) {
-            ignoringRemoteException("Error storing network attributes",
-                    () -> listener.onComplete(new Status(Status.ERROR_UNKNOWN)));
-        }
-    }
-
-    /**
-     * Store a binary blob associated with an L2 key and a name.
-     *
-     * @param l2Key The L2 key for this network.
-     * @param clientId The ID of the client.
-     * @param name The name of this data.
-     * @param data The data to store.
-     * @param listener A listener to inform of the completion of this call, or null if the client
-     *        is not interested in learning about success/failure.
-     * Through the listener, returns a status to indicate success or failure.
-     */
-    public void storeBlob(@NonNull final String l2Key, @NonNull final String clientId,
-            @NonNull final String name, @NonNull final Blob data,
-            @Nullable final OnStatusListener listener) {
-        try {
-            runWhenServiceReady(service -> ignoringRemoteException(
-                    () -> service.storeBlob(l2Key, clientId, name, data,
-                            OnStatusListener.toAIDL(listener))));
-        } catch (ExecutionException m) {
-            ignoringRemoteException("Error storing blob",
-                    () -> listener.onComplete(new Status(Status.ERROR_UNKNOWN)));
-        }
-    }
-
-    /**
-     * Returns the best L2 key associated with the attributes.
-     *
-     * This will find a record that would be in the same group as the passed attributes. This is
-     * useful to choose the key for storing a sample or private data when the L2 key is not known.
-     * If multiple records are group-close to these attributes, the closest match is returned.
-     * If multiple records have the same closeness, the one with the smaller (unicode codepoint
-     * order) L2 key is returned.
-     * If no record matches these attributes, null is returned.
-     *
-     * @param attributes The attributes of the network to find.
-     * @param listener The listener that will be invoked to return the answer.
-     * Through the listener, returns the L2 key if one matched, or null.
-     */
-    public void findL2Key(@NonNull final NetworkAttributes attributes,
-            @NonNull final OnL2KeyResponseListener listener) {
-        try {
-            runWhenServiceReady(service -> ignoringRemoteException(
-                    () -> service.findL2Key(attributes.toParcelable(),
-                            OnL2KeyResponseListener.toAIDL(listener))));
-        } catch (ExecutionException m) {
-            ignoringRemoteException("Error finding L2 Key",
-                    () -> listener.onL2KeyResponse(new Status(Status.ERROR_UNKNOWN), null));
-        }
-    }
-
-    /**
-     * Returns whether, to the best of the store's ability to tell, the two specified L2 keys point
-     * to the same L3 network. Group-closeness is used to determine this.
-     *
-     * @param l2Key1 The key for the first network.
-     * @param l2Key2 The key for the second network.
-     * @param listener The listener that will be invoked to return the answer.
-     * Through the listener, a SameL3NetworkResponse containing the answer and confidence.
-     */
-    public void isSameNetwork(@NonNull final String l2Key1, @NonNull final String l2Key2,
-            @NonNull final OnSameL3NetworkResponseListener listener) {
-        try {
-            runWhenServiceReady(service -> ignoringRemoteException(
-                    () -> service.isSameNetwork(l2Key1, l2Key2,
-                            OnSameL3NetworkResponseListener.toAIDL(listener))));
-        } catch (ExecutionException m) {
-            ignoringRemoteException("Error checking for network sameness",
-                    () -> listener.onSameL3NetworkResponse(new Status(Status.ERROR_UNKNOWN), null));
-        }
-    }
-
-    /**
-     * Retrieve the network attributes for a key.
-     * If no record is present for this key, this will return null attributes.
-     *
-     * @param l2Key The key of the network to query.
-     * @param listener The listener that will be invoked to return the answer.
-     * Through the listener, returns the network attributes and the L2 key associated with
-     *         the query.
-     */
-    public void retrieveNetworkAttributes(@NonNull final String l2Key,
-            @NonNull final OnNetworkAttributesRetrievedListener listener) {
-        try {
-            runWhenServiceReady(service -> ignoringRemoteException(
-                    () -> service.retrieveNetworkAttributes(l2Key,
-                            OnNetworkAttributesRetrievedListener.toAIDL(listener))));
-        } catch (ExecutionException m) {
-            ignoringRemoteException("Error retrieving network attributes",
-                    () -> listener.onNetworkAttributesRetrieved(new Status(Status.ERROR_UNKNOWN),
-                            null, null));
-        }
-    }
-
-    /**
-     * Retrieve previously stored private data.
-     * If no data was stored for this L2 key and name this will return null.
-     *
-     * @param l2Key The L2 key.
-     * @param clientId The id of the client that stored this data.
-     * @param name The name of the data.
-     * @param listener The listener that will be invoked to return the answer.
-     * Through the listener, returns the private data (or null), with the L2 key
-     *         and the name of the data associated with the query.
-     */
-    public void retrieveBlob(@NonNull final String l2Key, @NonNull final String clientId,
-            @NonNull final String name, @NonNull final OnBlobRetrievedListener listener) {
-        try {
-            runWhenServiceReady(service -> ignoringRemoteException(
-                    () -> service.retrieveBlob(l2Key, clientId, name,
-                            OnBlobRetrievedListener.toAIDL(listener))));
-        } catch (ExecutionException m) {
-            ignoringRemoteException("Error retrieving blob",
-                    () -> listener.onBlobRetrieved(new Status(Status.ERROR_UNKNOWN),
-                            null, null, null));
-        }
-    }
-
-    /**
-     * Wipe the data in the database upon network factory reset.
-     */
-    public void factoryReset() {
-        try {
-            runWhenServiceReady(service -> ignoringRemoteException(
-                    () -> service.factoryReset()));
-        } catch (ExecutionException m) {
-            Log.e(TAG, "Error executing factory reset", m);
-        }
-    }
-}
diff --git a/services/net/java/android/net/NattKeepalivePacketDataParcelable.aidl b/services/net/java/android/net/NattKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index 6f006d4..0000000
--- a/services/net/java/android/net/NattKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-parcelable NattKeepalivePacketDataParcelable {
-    byte[] srcAddress;
-    int srcPort;
-    byte[] dstAddress;
-    int dstPort;
-}
-
diff --git a/services/net/java/android/net/PrivateDnsConfigParcel.aidl b/services/net/java/android/net/PrivateDnsConfigParcel.aidl
deleted file mode 100644
index b52fce6..0000000
--- a/services/net/java/android/net/PrivateDnsConfigParcel.aidl
+++ /dev/null
@@ -1,22 +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 android.net;
-
-parcelable PrivateDnsConfigParcel {
-    String hostname;
-    String[] ips;
-}
diff --git a/services/net/java/android/net/ProvisioningConfigurationParcelable.aidl b/services/net/java/android/net/ProvisioningConfigurationParcelable.aidl
deleted file mode 100644
index 99606fb..0000000
--- a/services/net/java/android/net/ProvisioningConfigurationParcelable.aidl
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
-**
-** Copyright (C) 2019 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.net;
-
-import android.net.InitialConfigurationParcelable;
-import android.net.Network;
-import android.net.StaticIpConfiguration;
-import android.net.apf.ApfCapabilities;
-
-parcelable ProvisioningConfigurationParcelable {
-    boolean enableIPv4;
-    boolean enableIPv6;
-    boolean usingMultinetworkPolicyTracker;
-    boolean usingIpReachabilityMonitor;
-    int requestedPreDhcpActionMs;
-    InitialConfigurationParcelable initialConfig;
-    StaticIpConfiguration staticIpConfig;
-    ApfCapabilities apfCapabilities;
-    int provisioningTimeoutMs;
-    int ipv6AddrGenMode;
-    Network network;
-    String displayName;
-}
diff --git a/services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl b/services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl
deleted file mode 100644
index e25168d..0000000
--- a/services/net/java/android/net/TcpKeepalivePacketDataParcelable.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-parcelable TcpKeepalivePacketDataParcelable {
-    byte[] srcAddress;
-    int srcPort;
-    byte[] dstAddress;
-    int dstPort;
-    int seq;
-    int ack;
-    int rcvWnd;
-    int rcvWndScale;
-    int tos;
-    int ttl;
-}
diff --git a/services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl b/services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl
deleted file mode 100644
index 7b8b9ee..0000000
--- a/services/net/java/android/net/dhcp/DhcpServingParamsParcel.aidl
+++ /dev/null
@@ -1,30 +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 android.net.dhcp;
-
-parcelable DhcpServingParamsParcel {
-    int serverAddr;
-    int serverAddrPrefixLength;
-    int[] defaultRouters;
-    int[] dnsServers;
-    int[] excludedAddrs;
-    long dhcpLeaseTimeSecs;
-    int linkMtu;
-    boolean metered;
-}
-
diff --git a/services/net/java/android/net/dhcp/IDhcpServer.aidl b/services/net/java/android/net/dhcp/IDhcpServer.aidl
deleted file mode 100644
index 559433b..0000000
--- a/services/net/java/android/net/dhcp/IDhcpServer.aidl
+++ /dev/null
@@ -1,32 +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 perNmissions and
- * limitations under the License.
- */
-
-package android.net.dhcp;
-
-import android.net.INetworkStackStatusCallback;
-import android.net.dhcp.DhcpServingParamsParcel;
-
-/** @hide */
-oneway interface IDhcpServer {
-    const int STATUS_UNKNOWN = 0;
-    const int STATUS_SUCCESS = 1;
-    const int STATUS_INVALID_ARGUMENT = 2;
-    const int STATUS_UNKNOWN_ERROR = 3;
-
-    void start(in INetworkStackStatusCallback cb);
-    void updateParams(in DhcpServingParamsParcel params, in INetworkStackStatusCallback cb);
-    void stop(in INetworkStackStatusCallback cb);
-}
diff --git a/services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl b/services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl
deleted file mode 100644
index 7ab4dcd..0000000
--- a/services/net/java/android/net/dhcp/IDhcpServerCallbacks.aidl
+++ /dev/null
@@ -1,24 +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 perNmissions and
- * limitations under the License.
- */
-
-package android.net.dhcp;
-
-import android.net.dhcp.IDhcpServer;
-
-/** @hide */
-oneway interface IDhcpServerCallbacks {
-    void onDhcpServerCreated(int statusCode, in IDhcpServer server);
-}
diff --git a/services/net/java/android/net/ip/IIpClient.aidl b/services/net/java/android/net/ip/IIpClient.aidl
deleted file mode 100644
index 9989c52..0000000
--- a/services/net/java/android/net/ip/IIpClient.aidl
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Copyright (c) 2019, 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 perNmissions and
- * limitations under the License.
- */
-package android.net.ip;
-
-import android.net.ProxyInfo;
-import android.net.ProvisioningConfigurationParcelable;
-import android.net.NattKeepalivePacketDataParcelable;
-import android.net.TcpKeepalivePacketDataParcelable;
-
-/** @hide */
-oneway interface IIpClient {
-    void completedPreDhcpAction();
-    void confirmConfiguration();
-    void readPacketFilterComplete(in byte[] data);
-    void shutdown();
-    void startProvisioning(in ProvisioningConfigurationParcelable req);
-    void stop();
-    void setTcpBufferSizes(in String tcpBufferSizes);
-    void setHttpProxy(in ProxyInfo proxyInfo);
-    void setMulticastFilter(boolean enabled);
-    void addKeepalivePacketFilter(int slot, in TcpKeepalivePacketDataParcelable pkt);
-    void removeKeepalivePacketFilter(int slot);
-    void setL2KeyAndGroupHint(in String l2Key, in String groupHint);
-    void addNattKeepalivePacketFilter(int slot, in NattKeepalivePacketDataParcelable pkt);
-}
diff --git a/services/net/java/android/net/ip/IIpClientCallbacks.aidl b/services/net/java/android/net/ip/IIpClientCallbacks.aidl
deleted file mode 100644
index 3681416..0000000
--- a/services/net/java/android/net/ip/IIpClientCallbacks.aidl
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Copyright (c) 2019, 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 perNmissions and
- * limitations under the License.
- */
-package android.net.ip;
-
-import android.net.LinkProperties;
-import android.net.ip.IIpClient;
-import android.net.DhcpResultsParcelable;
-
-/** @hide */
-oneway interface IIpClientCallbacks {
-    void onIpClientCreated(in IIpClient ipClient);
-
-    void onPreDhcpAction();
-    void onPostDhcpAction();
-
-    // This is purely advisory and not an indication of provisioning
-    // success or failure.  This is only here for callers that want to
-    // expose DHCPv4 results to other APIs (e.g., WifiInfo#setInetAddress).
-    // DHCPv4 or static IPv4 configuration failure or success can be
-    // determined by whether or not the passed-in DhcpResults object is
-    // null or not.
-    void onNewDhcpResults(in DhcpResultsParcelable dhcpResults);
-
-    void onProvisioningSuccess(in LinkProperties newLp);
-    void onProvisioningFailure(in LinkProperties newLp);
-
-    // Invoked on LinkProperties changes.
-    void onLinkPropertiesChange(in LinkProperties newLp);
-
-    // Called when the internal IpReachabilityMonitor (if enabled) has
-    // detected the loss of a critical number of required neighbors.
-    void onReachabilityLost(in String logMsg);
-
-    // Called when the IpClient state machine terminates.
-    void onQuit();
-
-    // Install an APF program to filter incoming packets.
-    void installPacketFilter(in byte[] filter);
-
-    // Asynchronously read back the APF program & data buffer from the wifi driver.
-    // Due to Wifi HAL limitations, the current implementation only supports dumping the entire
-    // buffer. In response to this request, the driver returns the data buffer asynchronously
-    // by sending an IpClient#EVENT_READ_PACKET_FILTER_COMPLETE message.
-    void startReadPacketFilter();
-
-    // If multicast filtering cannot be accomplished with APF, this function will be called to
-    // actuate multicast filtering using another means.
-    void setFallbackMulticastFilter(boolean enabled);
-
-    // Enabled/disable Neighbor Discover offload functionality. This is
-    // called, for example, whenever 464xlat is being started or stopped.
-    void setNeighborDiscoveryOffload(boolean enable);
-}
\ No newline at end of file
diff --git a/services/net/java/android/net/ipmemorystore/Blob.aidl b/services/net/java/android/net/ipmemorystore/Blob.aidl
deleted file mode 100644
index 9dbef11..0000000
--- a/services/net/java/android/net/ipmemorystore/Blob.aidl
+++ /dev/null
@@ -1,26 +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 android.net.ipmemorystore;
-
-/**
- * A blob of data opaque to the memory store. The client mutates this at its own risk,
- * and it is strongly suggested to never do it at all and treat this as immutable.
- * {@hide}
- */
-parcelable Blob {
-    byte[] data;
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl b/services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
deleted file mode 100644
index 4926feb..0000000
--- a/services/net/java/android/net/ipmemorystore/IOnBlobRetrievedListener.aidl
+++ /dev/null
@@ -1,30 +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 android.net.ipmemorystore;
-
-import android.net.ipmemorystore.Blob;
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnBlobRetrievedListener {
-    /**
-     * Private data was retrieved for the L2 key and name specified.
-     * Note this does not return the client ID, as clients are expected to only ever use one ID.
-     */
-     void onBlobRetrieved(in StatusParcelable status, in String l2Key, in String name,
-             in Blob data);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl b/services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
deleted file mode 100644
index dea0cc4..0000000
--- a/services/net/java/android/net/ipmemorystore/IOnL2KeyResponseListener.aidl
+++ /dev/null
@@ -1,27 +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 android.net.ipmemorystore;
-
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnL2KeyResponseListener {
-    /**
-     * The operation completed with the specified L2 key.
-     */
-     void onL2KeyResponse(in StatusParcelable status, in String l2Key);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl b/services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
deleted file mode 100644
index 870e217..0000000
--- a/services/net/java/android/net/ipmemorystore/IOnNetworkAttributesRetrievedListener.aidl
+++ /dev/null
@@ -1,30 +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 android.net.ipmemorystore;
-
-import android.net.ipmemorystore.NetworkAttributesParcelable;
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnNetworkAttributesRetrievedListener {
-    /**
-     * Network attributes were fetched for the specified L2 key. While the L2 key will never
-     * be null, the attributes may be if no data is stored about this L2 key.
-     */
-     void onNetworkAttributesRetrieved(in StatusParcelable status, in String l2Key,
-             in NetworkAttributesParcelable attributes);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl b/services/net/java/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
deleted file mode 100644
index b8ccfb9..0000000
--- a/services/net/java/android/net/ipmemorystore/IOnSameL3NetworkResponseListener.aidl
+++ /dev/null
@@ -1,29 +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 android.net.ipmemorystore;
-
-import android.net.ipmemorystore.SameL3NetworkResponseParcelable;
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnSameL3NetworkResponseListener {
-    /**
-     * The memory store has come up with the answer to a query that was sent.
-     */
-     void onSameL3NetworkResponse(in StatusParcelable status,
-             in SameL3NetworkResponseParcelable response);
-}
diff --git a/services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl b/services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl
deleted file mode 100644
index 5d07504..0000000
--- a/services/net/java/android/net/ipmemorystore/IOnStatusListener.aidl
+++ /dev/null
@@ -1,27 +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 android.net.ipmemorystore;
-
-import android.net.ipmemorystore.StatusParcelable;
-
-/** {@hide} */
-oneway interface IOnStatusListener {
-    /**
-     * The operation has completed with the specified status.
-     */
-     void onComplete(in StatusParcelable status);
-}
diff --git a/services/net/java/android/net/ipmemorystore/NetworkAttributes.java b/services/net/java/android/net/ipmemorystore/NetworkAttributes.java
deleted file mode 100644
index 818515a..0000000
--- a/services/net/java/android/net/ipmemorystore/NetworkAttributes.java
+++ /dev/null
@@ -1,371 +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 android.net.ipmemorystore;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import java.util.StringJoiner;
-
-/**
- * A POD object to represent attributes of a single L2 network entry.
- * @hide
- */
-public class NetworkAttributes {
-    private static final boolean DBG = true;
-
-    // Weight cutoff for grouping. To group, a similarity score is computed with the following
-    // algorithm : if both fields are non-null and equals() then add their assigned weight, else if
-    // both are null then add a portion of their assigned weight (see NULL_MATCH_WEIGHT),
-    // otherwise add nothing.
-    // As a guideline, this should be something like 60~75% of the total weights in this class. The
-    // design states "in essence a reader should imagine that if two important columns don't match,
-    // or one important and several unimportant columns don't match then the two records are
-    // considered a different group".
-    private static final float TOTAL_WEIGHT_CUTOFF = 520.0f;
-    // The portion of the weight that is earned when scoring group-sameness by having both columns
-    // being null. This is because some networks rightfully don't have some attributes (e.g. a
-    // V6-only network won't have an assigned V4 address) and both being null should count for
-    // something, but attributes may also be null just because data is unavailable.
-    private static final float NULL_MATCH_WEIGHT = 0.25f;
-
-    // The v4 address that was assigned to this device the last time it joined this network.
-    // This typically comes from DHCP but could be something else like static configuration.
-    // This does not apply to IPv6.
-    // TODO : add a list of v6 prefixes for the v6 case.
-    @Nullable
-    public final Inet4Address assignedV4Address;
-    private static final float WEIGHT_ASSIGNEDV4ADDR = 300.0f;
-
-    // The lease expiry timestamp of v4 address allocated from DHCP server, in milliseconds.
-    @Nullable
-    public final Long assignedV4AddressExpiry;
-    // lease expiry doesn't imply any correlation between "the same lease expiry value" and "the
-    // same L3 network".
-    private static final float WEIGHT_ASSIGNEDV4ADDREXPIRY = 0.0f;
-
-    // Optionally supplied by the client if it has an opinion on L3 network. For example, this
-    // could be a hash of the SSID + security type on WiFi.
-    @Nullable
-    public final String groupHint;
-    private static final float WEIGHT_GROUPHINT = 300.0f;
-
-    // The list of DNS server addresses.
-    @Nullable
-    public final List<InetAddress> dnsAddresses;
-    private static final float WEIGHT_DNSADDRESSES = 200.0f;
-
-    // The mtu on this network.
-    @Nullable
-    public final Integer mtu;
-    private static final float WEIGHT_MTU = 50.0f;
-
-    // The sum of all weights in this class. Tests ensure that this stays equal to the total of
-    // all weights.
-    /** @hide */
-    @VisibleForTesting
-    public static final float TOTAL_WEIGHT = WEIGHT_ASSIGNEDV4ADDR
-            + WEIGHT_ASSIGNEDV4ADDREXPIRY
-            + WEIGHT_GROUPHINT
-            + WEIGHT_DNSADDRESSES
-            + WEIGHT_MTU;
-
-    /** @hide */
-    @VisibleForTesting
-    public NetworkAttributes(
-            @Nullable final Inet4Address assignedV4Address,
-            @Nullable final Long assignedV4AddressExpiry,
-            @Nullable final String groupHint,
-            @Nullable final List<InetAddress> dnsAddresses,
-            @Nullable final Integer mtu) {
-        if (mtu != null && mtu < 0) throw new IllegalArgumentException("MTU can't be negative");
-        if (assignedV4AddressExpiry != null && assignedV4AddressExpiry <= 0) {
-            throw new IllegalArgumentException("lease expiry can't be negative or zero");
-        }
-        this.assignedV4Address = assignedV4Address;
-        this.assignedV4AddressExpiry = assignedV4AddressExpiry;
-        this.groupHint = groupHint;
-        this.dnsAddresses = null == dnsAddresses ? null :
-                Collections.unmodifiableList(new ArrayList<>(dnsAddresses));
-        this.mtu = mtu;
-    }
-
-    @VisibleForTesting
-    public NetworkAttributes(@NonNull final NetworkAttributesParcelable parcelable) {
-        // The call to the other constructor must be the first statement of this constructor,
-        // so everything has to be inline
-        this((Inet4Address) getByAddressOrNull(parcelable.assignedV4Address),
-                parcelable.assignedV4AddressExpiry > 0
-                        ? parcelable.assignedV4AddressExpiry : null,
-                parcelable.groupHint,
-                blobArrayToInetAddressList(parcelable.dnsAddresses),
-                parcelable.mtu >= 0 ? parcelable.mtu : null);
-    }
-
-    @Nullable
-    private static InetAddress getByAddressOrNull(@Nullable final byte[] address) {
-        if (null == address) return null;
-        try {
-            return InetAddress.getByAddress(address);
-        } catch (UnknownHostException e) {
-            return null;
-        }
-    }
-
-    @Nullable
-    private static List<InetAddress> blobArrayToInetAddressList(@Nullable final Blob[] blobs) {
-        if (null == blobs) return null;
-        final ArrayList<InetAddress> list = new ArrayList<>(blobs.length);
-        for (final Blob b : blobs) {
-            final InetAddress addr = getByAddressOrNull(b.data);
-            if (null != addr) list.add(addr);
-        }
-        return list;
-    }
-
-    @Nullable
-    private static Blob[] inetAddressListToBlobArray(@Nullable final List<InetAddress> addresses) {
-        if (null == addresses) return null;
-        final ArrayList<Blob> blobs = new ArrayList<>();
-        for (int i = 0; i < addresses.size(); ++i) {
-            final InetAddress addr = addresses.get(i);
-            if (null == addr) continue;
-            final Blob b = new Blob();
-            b.data = addr.getAddress();
-            blobs.add(b);
-        }
-        return blobs.toArray(new Blob[0]);
-    }
-
-    /** Converts this NetworkAttributes to a parcelable object */
-    @NonNull
-    public NetworkAttributesParcelable toParcelable() {
-        final NetworkAttributesParcelable parcelable = new NetworkAttributesParcelable();
-        parcelable.assignedV4Address =
-                (null == assignedV4Address) ? null : assignedV4Address.getAddress();
-        parcelable.assignedV4AddressExpiry =
-                (null == assignedV4AddressExpiry) ? 0 : assignedV4AddressExpiry;
-        parcelable.groupHint = groupHint;
-        parcelable.dnsAddresses = inetAddressListToBlobArray(dnsAddresses);
-        parcelable.mtu = (null == mtu) ? -1 : mtu;
-        return parcelable;
-    }
-
-    private float samenessContribution(final float weight,
-            @Nullable final Object o1, @Nullable final Object o2) {
-        if (null == o1) {
-            return (null == o2) ? weight * NULL_MATCH_WEIGHT : 0f;
-        }
-        return Objects.equals(o1, o2) ? weight : 0f;
-    }
-
-    /** @hide */
-    public float getNetworkGroupSamenessConfidence(@NonNull final NetworkAttributes o) {
-        final float samenessScore =
-                samenessContribution(WEIGHT_ASSIGNEDV4ADDR, assignedV4Address, o.assignedV4Address)
-                + samenessContribution(WEIGHT_ASSIGNEDV4ADDREXPIRY, assignedV4AddressExpiry,
-                      o.assignedV4AddressExpiry)
-                + samenessContribution(WEIGHT_GROUPHINT, groupHint, o.groupHint)
-                + samenessContribution(WEIGHT_DNSADDRESSES, dnsAddresses, o.dnsAddresses)
-                + samenessContribution(WEIGHT_MTU, mtu, o.mtu);
-        // The minimum is 0, the max is TOTAL_WEIGHT and should be represented by 1.0, and
-        // TOTAL_WEIGHT_CUTOFF should represent 0.5, but there is no requirement that
-        // TOTAL_WEIGHT_CUTOFF would be half of TOTAL_WEIGHT (indeed, it should not be).
-        // So scale scores under the cutoff between 0 and 0.5, and the scores over the cutoff
-        // between 0.5 and 1.0.
-        if (samenessScore < TOTAL_WEIGHT_CUTOFF) {
-            return samenessScore / (TOTAL_WEIGHT_CUTOFF * 2);
-        } else {
-            return (samenessScore - TOTAL_WEIGHT_CUTOFF) / (TOTAL_WEIGHT - TOTAL_WEIGHT_CUTOFF) / 2
-                    + 0.5f;
-        }
-    }
-
-    /** @hide */
-    public static class Builder {
-        @Nullable
-        private Inet4Address mAssignedAddress;
-        @Nullable
-        private Long mAssignedAddressExpiry;
-        @Nullable
-        private String mGroupHint;
-        @Nullable
-        private List<InetAddress> mDnsAddresses;
-        @Nullable
-        private Integer mMtu;
-
-        /**
-         * Set the assigned address.
-         * @param assignedV4Address The assigned address.
-         * @return This builder.
-         */
-        public Builder setAssignedV4Address(@Nullable final Inet4Address assignedV4Address) {
-            mAssignedAddress = assignedV4Address;
-            return this;
-        }
-
-        /**
-         * Set the lease expiry timestamp of assigned v4 address. Long.MAX_VALUE is used
-         * to represent "infinite lease".
-         *
-         * @param assignedV4AddressExpiry The lease expiry timestamp of assigned v4 address.
-         * @return This builder.
-         */
-        public Builder setAssignedV4AddressExpiry(
-                @Nullable final Long assignedV4AddressExpiry) {
-            if (null != assignedV4AddressExpiry && assignedV4AddressExpiry <= 0) {
-                throw new IllegalArgumentException("lease expiry can't be negative or zero");
-            }
-            mAssignedAddressExpiry = assignedV4AddressExpiry;
-            return this;
-        }
-
-        /**
-         * Set the group hint.
-         * @param groupHint The group hint.
-         * @return This builder.
-         */
-        public Builder setGroupHint(@Nullable final String groupHint) {
-            mGroupHint = groupHint;
-            return this;
-        }
-
-        /**
-         * Set the DNS addresses.
-         * @param dnsAddresses The DNS addresses.
-         * @return This builder.
-         */
-        public Builder setDnsAddresses(@Nullable final List<InetAddress> dnsAddresses) {
-            if (DBG && null != dnsAddresses) {
-                // Parceling code crashes if one of the addresses is null, therefore validate
-                // them when running in debug.
-                for (final InetAddress address : dnsAddresses) {
-                    if (null == address) throw new IllegalArgumentException("Null DNS address");
-                }
-            }
-            this.mDnsAddresses = dnsAddresses;
-            return this;
-        }
-
-        /**
-         * Set the MTU.
-         * @param mtu The MTU.
-         * @return This builder.
-         */
-        public Builder setMtu(@Nullable final Integer mtu) {
-            if (null != mtu && mtu < 0) throw new IllegalArgumentException("MTU can't be negative");
-            mMtu = mtu;
-            return this;
-        }
-
-        /**
-         * Return the built NetworkAttributes object.
-         * @return The built NetworkAttributes object.
-         */
-        public NetworkAttributes build() {
-            return new NetworkAttributes(mAssignedAddress, mAssignedAddressExpiry,
-                  mGroupHint, mDnsAddresses, mMtu);
-        }
-    }
-
-    /** @hide */
-    public boolean isEmpty() {
-        return (null == assignedV4Address) && (null == assignedV4AddressExpiry)
-                && (null == groupHint) && (null == dnsAddresses) && (null == mtu);
-    }
-
-    @Override
-    public boolean equals(@Nullable final Object o) {
-        if (!(o instanceof NetworkAttributes)) return false;
-        final NetworkAttributes other = (NetworkAttributes) o;
-        return Objects.equals(assignedV4Address, other.assignedV4Address)
-                && Objects.equals(assignedV4AddressExpiry, other.assignedV4AddressExpiry)
-                && Objects.equals(groupHint, other.groupHint)
-                && Objects.equals(dnsAddresses, other.dnsAddresses)
-                && Objects.equals(mtu, other.mtu);
-    }
-
-    @Override
-    public int hashCode() {
-        return Objects.hash(assignedV4Address, assignedV4AddressExpiry,
-                groupHint, dnsAddresses, mtu);
-    }
-
-    /** Pretty print */
-    @Override
-    public String toString() {
-        final StringJoiner resultJoiner = new StringJoiner(" ", "{", "}");
-        final ArrayList<String> nullFields = new ArrayList<>();
-
-        if (null != assignedV4Address) {
-            resultJoiner.add("assignedV4Addr :");
-            resultJoiner.add(assignedV4Address.toString());
-        } else {
-            nullFields.add("assignedV4Addr");
-        }
-
-        if (null != assignedV4AddressExpiry) {
-            resultJoiner.add("assignedV4AddressExpiry :");
-            resultJoiner.add(assignedV4AddressExpiry.toString());
-        } else {
-            nullFields.add("assignedV4AddressExpiry");
-        }
-
-        if (null != groupHint) {
-            resultJoiner.add("groupHint :");
-            resultJoiner.add(groupHint);
-        } else {
-            nullFields.add("groupHint");
-        }
-
-        if (null != dnsAddresses) {
-            resultJoiner.add("dnsAddr : [");
-            for (final InetAddress addr : dnsAddresses) {
-                resultJoiner.add(addr.getHostAddress());
-            }
-            resultJoiner.add("]");
-        } else {
-            nullFields.add("dnsAddr");
-        }
-
-        if (null != mtu) {
-            resultJoiner.add("mtu :");
-            resultJoiner.add(mtu.toString());
-        } else {
-            nullFields.add("mtu");
-        }
-
-        if (!nullFields.isEmpty()) {
-            resultJoiner.add("; Null fields : [");
-            for (final String field : nullFields) {
-                resultJoiner.add(field);
-            }
-            resultJoiner.add("]");
-        }
-
-        return resultJoiner.toString();
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl b/services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
deleted file mode 100644
index 997eb2b..0000000
--- a/services/net/java/android/net/ipmemorystore/NetworkAttributesParcelable.aidl
+++ /dev/null
@@ -1,37 +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 android.net.ipmemorystore;
-
-// Blob[] is used to represent an array of byte[], as structured AIDL does not support arrays
-// of arrays.
-import android.net.ipmemorystore.Blob;
-
-/**
- * An object to represent attributes of a single L2 network entry.
- * See NetworkAttributes.java for a description of each field. The types used in this class
- * are structured parcelable types instead of the richer types of the NetworkAttributes object,
- * but they have the same purpose. The NetworkAttributes.java file also contains the code
- * to convert the richer types to the parcelable types and back.
- * @hide
- */
-parcelable NetworkAttributesParcelable {
-    byte[] assignedV4Address;
-    long assignedV4AddressExpiry;
-    String groupHint;
-    Blob[] dnsAddresses;
-    int mtu;
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnBlobRetrievedListener.java b/services/net/java/android/net/ipmemorystore/OnBlobRetrievedListener.java
deleted file mode 100644
index a17483a..0000000
--- a/services/net/java/android/net/ipmemorystore/OnBlobRetrievedListener.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return a blob.
- * @hide
- */
-public interface OnBlobRetrievedListener {
-    /**
-     * The memory store has come up with the answer to a query that was sent.
-     */
-    void onBlobRetrieved(Status status, String l2Key, String name, Blob blob);
-
-    /** Converts this OnBlobRetrievedListener to a parcelable object */
-    @NonNull
-    static IOnBlobRetrievedListener toAIDL(@NonNull final OnBlobRetrievedListener listener) {
-        return new IOnBlobRetrievedListener.Stub() {
-            @Override
-            public void onBlobRetrieved(final StatusParcelable statusParcelable, final String l2Key,
-                    final String name, final Blob blob) {
-                // NonNull, but still don't crash the system server if null
-                if (null != listener) {
-                    listener.onBlobRetrieved(new Status(statusParcelable), l2Key, name, blob);
-                }
-            }
-
-            @Override
-            public int getInterfaceVersion() {
-                return this.VERSION;
-            }
-        };
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnL2KeyResponseListener.java b/services/net/java/android/net/ipmemorystore/OnL2KeyResponseListener.java
deleted file mode 100644
index e608aec..0000000
--- a/services/net/java/android/net/ipmemorystore/OnL2KeyResponseListener.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return a L2 key.
- * @hide
- */
-public interface OnL2KeyResponseListener {
-    /**
-     * The operation has completed with the specified status.
-     */
-    void onL2KeyResponse(Status status, String l2Key);
-
-    /** Converts this OnL2KeyResponseListener to a parcelable object */
-    @NonNull
-    static IOnL2KeyResponseListener toAIDL(@NonNull final OnL2KeyResponseListener listener) {
-        return new IOnL2KeyResponseListener.Stub() {
-            @Override
-            public void onL2KeyResponse(final StatusParcelable statusParcelable,
-                    final String l2Key) {
-                // NonNull, but still don't crash the system server if null
-                if (null != listener) {
-                    listener.onL2KeyResponse(new Status(statusParcelable), l2Key);
-                }
-            }
-
-            @Override
-            public int getInterfaceVersion() {
-                return this.VERSION;
-            }
-        };
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnNetworkAttributesRetrievedListener.java b/services/net/java/android/net/ipmemorystore/OnNetworkAttributesRetrievedListener.java
deleted file mode 100644
index 395ad98..0000000
--- a/services/net/java/android/net/ipmemorystore/OnNetworkAttributesRetrievedListener.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return network attributes.
- * @hide
- */
-public interface OnNetworkAttributesRetrievedListener {
-    /**
-     * The memory store has come up with the answer to a query that was sent.
-     */
-    void onNetworkAttributesRetrieved(Status status, String l2Key, NetworkAttributes attributes);
-
-    /** Converts this OnNetworkAttributesRetrievedListener to a parcelable object */
-    @NonNull
-    static IOnNetworkAttributesRetrievedListener toAIDL(
-            @NonNull final OnNetworkAttributesRetrievedListener listener) {
-        return new IOnNetworkAttributesRetrievedListener.Stub() {
-            @Override
-            public void onNetworkAttributesRetrieved(final StatusParcelable statusParcelable,
-                    final String l2Key,
-                    final NetworkAttributesParcelable networkAttributesParcelable) {
-                // NonNull, but still don't crash the system server if null
-                if (null != listener) {
-                    listener.onNetworkAttributesRetrieved(
-                            new Status(statusParcelable), l2Key, null == networkAttributesParcelable
-                                ? null : new NetworkAttributes(networkAttributesParcelable));
-                }
-            }
-
-            @Override
-            public int getInterfaceVersion() {
-                return this.VERSION;
-            }
-        };
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnSameL3NetworkResponseListener.java b/services/net/java/android/net/ipmemorystore/OnSameL3NetworkResponseListener.java
deleted file mode 100644
index 67f8da8..0000000
--- a/services/net/java/android/net/ipmemorystore/OnSameL3NetworkResponseListener.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-/**
- * A listener for the IpMemoryStore to return a response about network sameness.
- * @hide
- */
-public interface OnSameL3NetworkResponseListener {
-    /**
-     * The memory store has come up with the answer to a query that was sent.
-     */
-    void onSameL3NetworkResponse(Status status, SameL3NetworkResponse response);
-
-    /** Converts this OnSameL3NetworkResponseListener to a parcelable object */
-    @NonNull
-    static IOnSameL3NetworkResponseListener toAIDL(
-            @NonNull final OnSameL3NetworkResponseListener listener) {
-        return new IOnSameL3NetworkResponseListener.Stub() {
-            @Override
-            public void onSameL3NetworkResponse(final StatusParcelable statusParcelable,
-                    final SameL3NetworkResponseParcelable sameL3NetworkResponseParcelable) {
-                // NonNull, but still don't crash the system server if null
-                if (null != listener) {
-                    listener.onSameL3NetworkResponse(
-                            new Status(statusParcelable),
-                            new SameL3NetworkResponse(sameL3NetworkResponseParcelable));
-                }
-            }
-
-            @Override
-            public int getInterfaceVersion() {
-                return this.VERSION;
-            }
-        };
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/OnStatusListener.java b/services/net/java/android/net/ipmemorystore/OnStatusListener.java
deleted file mode 100644
index 4262efd..0000000
--- a/services/net/java/android/net/ipmemorystore/OnStatusListener.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2019 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.net.ipmemorystore;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-
-/**
- * A listener for the IpMemoryStore to return a status to a client.
- * @hide
- */
-public interface OnStatusListener {
-    /**
-     * The operation has completed with the specified status.
-     */
-    void onComplete(Status status);
-
-    /** Converts this OnStatusListener to a parcelable object */
-    @NonNull
-    static IOnStatusListener toAIDL(@Nullable final OnStatusListener listener) {
-        return new IOnStatusListener.Stub() {
-            @Override
-            public void onComplete(final StatusParcelable statusParcelable) {
-                if (null != listener) {
-                    listener.onComplete(new Status(statusParcelable));
-                }
-            }
-
-            @Override
-            public int getInterfaceVersion() {
-                return this.VERSION;
-            }
-        };
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponse.java b/services/net/java/android/net/ipmemorystore/SameL3NetworkResponse.java
deleted file mode 100644
index 291aca8..0000000
--- a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponse.java
+++ /dev/null
@@ -1,147 +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 android.net.ipmemorystore;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Objects;
-
-/**
- * An object representing the answer to a query whether two given L2 networks represent the
- * same L3 network. Parcels as a SameL3NetworkResponseParceled object.
- * @hide
- */
-public class SameL3NetworkResponse {
-    @IntDef(prefix = "NETWORK_",
-            value = {NETWORK_SAME, NETWORK_DIFFERENT, NETWORK_NEVER_CONNECTED})
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface NetworkSameness {}
-
-    /**
-     * Both L2 networks represent the same L3 network.
-     */
-    public static final int NETWORK_SAME = 1;
-
-    /**
-     * The two L2 networks represent a different L3 network.
-     */
-    public static final int NETWORK_DIFFERENT = 2;
-
-    /**
-     * The device has never connected to at least one of these two L2 networks, or data
-     * has been wiped. Therefore the device has never seen the L3 network behind at least
-     * one of these two L2 networks, and can't evaluate whether it's the same as the other.
-     */
-    public static final int NETWORK_NEVER_CONNECTED = 3;
-
-    /**
-     * The first L2 key specified in the query.
-     */
-    @NonNull
-    public final String l2Key1;
-
-    /**
-     * The second L2 key specified in the query.
-     */
-    @NonNull
-    public final String l2Key2;
-
-    /**
-     * A confidence value indicating whether the two L2 networks represent the same L3 network.
-     *
-     * If both L2 networks were known, this value will be between 0.0 and 1.0, with 0.0
-     * representing complete confidence that the given L2 networks represent a different
-     * L3 network, and 1.0 representing complete confidence that the given L2 networks
-     * represent the same L3 network.
-     * If at least one of the L2 networks was not known, this value will be outside of the
-     * 0.0~1.0 range.
-     *
-     * Most apps should not be interested in this, and are encouraged to use the collapsing
-     * {@link #getNetworkSameness()} function below.
-     */
-    public final float confidence;
-
-    /**
-     * @return whether the two L2 networks represent the same L3 network. Either
-     *     {@code NETWORK_SAME}, {@code NETWORK_DIFFERENT} or {@code NETWORK_NEVER_CONNECTED}.
-     */
-    @NetworkSameness
-    public final int getNetworkSameness() {
-        if (confidence > 1.0 || confidence < 0.0) return NETWORK_NEVER_CONNECTED;
-        return confidence > 0.5 ? NETWORK_SAME : NETWORK_DIFFERENT;
-    }
-
-    /** @hide */
-    public SameL3NetworkResponse(@NonNull final String l2Key1, @NonNull final String l2Key2,
-            final float confidence) {
-        this.l2Key1 = l2Key1;
-        this.l2Key2 = l2Key2;
-        this.confidence = confidence;
-    }
-
-    /** Builds a SameL3NetworkResponse from a parcelable object */
-    @VisibleForTesting
-    public SameL3NetworkResponse(@NonNull final SameL3NetworkResponseParcelable parceled) {
-        this(parceled.l2Key1, parceled.l2Key2, parceled.confidence);
-    }
-
-    /** Converts this SameL3NetworkResponse to a parcelable object */
-    @NonNull
-    public SameL3NetworkResponseParcelable toParcelable() {
-        final SameL3NetworkResponseParcelable parcelable = new SameL3NetworkResponseParcelable();
-        parcelable.l2Key1 = l2Key1;
-        parcelable.l2Key2 = l2Key2;
-        parcelable.confidence = confidence;
-        return parcelable;
-    }
-
-    // Note key1 and key2 have to match each other for this to return true. If
-    // key1 matches o.key2 and the other way around this returns false.
-    @Override
-    public boolean equals(@Nullable final Object o) {
-        if (!(o instanceof SameL3NetworkResponse)) return false;
-        final SameL3NetworkResponse other = (SameL3NetworkResponse) o;
-        return l2Key1.equals(other.l2Key1) && l2Key2.equals(other.l2Key2)
-                && confidence == other.confidence;
-    }
-
-    @Override
-    public int hashCode() {
-        return Objects.hash(l2Key1, l2Key2, confidence);
-    }
-
-    @Override
-    /** Pretty print */
-    public String toString() {
-        switch (getNetworkSameness()) {
-            case NETWORK_SAME:
-                return "\"" + l2Key1 + "\" same L3 network as \"" + l2Key2 + "\"";
-            case NETWORK_DIFFERENT:
-                return "\"" + l2Key1 + "\" different L3 network from \"" + l2Key2 + "\"";
-            case NETWORK_NEVER_CONNECTED:
-                return "\"" + l2Key1 + "\" can't be tested against \"" + l2Key2 + "\"";
-            default:
-                return "Buggy sameness value ? \"" + l2Key1 + "\", \"" + l2Key2 + "\"";
-        }
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl b/services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
deleted file mode 100644
index 7196699..0000000
--- a/services/net/java/android/net/ipmemorystore/SameL3NetworkResponseParcelable.aidl
+++ /dev/null
@@ -1,24 +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 android.net.ipmemorystore;
-
-/** {@hide} */
-parcelable SameL3NetworkResponseParcelable {
-    String l2Key1;
-    String l2Key2;
-    float confidence;
-}
diff --git a/services/net/java/android/net/ipmemorystore/Status.java b/services/net/java/android/net/ipmemorystore/Status.java
deleted file mode 100644
index 13242c0..0000000
--- a/services/net/java/android/net/ipmemorystore/Status.java
+++ /dev/null
@@ -1,74 +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 android.net.ipmemorystore;
-
-import android.annotation.NonNull;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-/**
- * A parcelable status representing the result of an operation.
- * Parcels as StatusParceled.
- * @hide
- */
-public class Status {
-    public static final int SUCCESS = 0;
-
-    public static final int ERROR_GENERIC = -1;
-    public static final int ERROR_ILLEGAL_ARGUMENT = -2;
-    public static final int ERROR_DATABASE_CANNOT_BE_OPENED = -3;
-    public static final int ERROR_STORAGE = -4;
-    public static final int ERROR_UNKNOWN = -5;
-
-    public final int resultCode;
-
-    public Status(final int resultCode) {
-        this.resultCode = resultCode;
-    }
-
-    @VisibleForTesting
-    public Status(@NonNull final StatusParcelable parcelable) {
-        this(parcelable.resultCode);
-    }
-
-    /** Converts this Status to a parcelable object */
-    @NonNull
-    public StatusParcelable toParcelable() {
-        final StatusParcelable parcelable = new StatusParcelable();
-        parcelable.resultCode = resultCode;
-        return parcelable;
-    }
-
-    public boolean isSuccess() {
-        return SUCCESS == resultCode;
-    }
-
-    /** Pretty print */
-    @Override
-    public String toString() {
-        switch (resultCode) {
-            case SUCCESS: return "SUCCESS";
-            case ERROR_GENERIC: return "GENERIC ERROR";
-            case ERROR_ILLEGAL_ARGUMENT: return "ILLEGAL ARGUMENT";
-            case ERROR_DATABASE_CANNOT_BE_OPENED: return "DATABASE CANNOT BE OPENED";
-            // "DB storage error" is not very helpful but SQLite does not provide specific error
-            // codes upon store failure. Thus this indicates SQLite returned some error upon store
-            case ERROR_STORAGE: return "DATABASE STORAGE ERROR";
-            default: return "Unknown value ?!";
-        }
-    }
-}
diff --git a/services/net/java/android/net/ipmemorystore/StatusParcelable.aidl b/services/net/java/android/net/ipmemorystore/StatusParcelable.aidl
deleted file mode 100644
index fb36ef4..0000000
--- a/services/net/java/android/net/ipmemorystore/StatusParcelable.aidl
+++ /dev/null
@@ -1,22 +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 android.net.ipmemorystore;
-
-/** {@hide} */
-parcelable StatusParcelable {
-  int resultCode;
-}
diff --git a/services/net/java/android/net/netlink/InetDiagMessage.java b/services/net/java/android/net/netlink/InetDiagMessage.java
index af9e601..31a2556 100644
--- a/services/net/java/android/net/netlink/InetDiagMessage.java
+++ b/services/net/java/android/net/netlink/InetDiagMessage.java
@@ -16,26 +16,23 @@
 
 package android.net.netlink;
 
-import static android.os.Process.INVALID_UID;
 import static android.net.netlink.NetlinkConstants.SOCK_DIAG_BY_FAMILY;
 import static android.net.netlink.NetlinkSocket.DEFAULT_RECV_BUFSIZE;
 import static android.net.netlink.StructNlMsgHdr.NLM_F_DUMP;
 import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
+import static android.os.Process.INVALID_UID;
 import static android.system.OsConstants.AF_INET;
 import static android.system.OsConstants.AF_INET6;
 import static android.system.OsConstants.IPPROTO_UDP;
 import static android.system.OsConstants.NETLINK_INET_DIAG;
 
-import android.os.Build;
-import android.os.Process;
+import android.net.util.SocketUtils;
 import android.system.ErrnoException;
 import android.util.Log;
 
 import java.io.FileDescriptor;
+import java.io.IOException;
 import java.io.InterruptedIOException;
-import java.net.DatagramSocket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetSocketAddress;
@@ -163,17 +160,25 @@
      */
     public static int getConnectionOwnerUid(int protocol, InetSocketAddress local,
                                             InetSocketAddress remote) {
+        int uid = INVALID_UID;
+        FileDescriptor fd = null;
         try {
-            final FileDescriptor fd = NetlinkSocket.forProto(NETLINK_INET_DIAG);
+            fd = NetlinkSocket.forProto(NETLINK_INET_DIAG);
             NetlinkSocket.connectToKernel(fd);
-
-            return lookupUid(protocol, local, remote, fd);
-
+            uid = lookupUid(protocol, local, remote, fd);
         } catch (ErrnoException | SocketException | IllegalArgumentException
                 | InterruptedIOException e) {
             Log.e(TAG, e.toString());
+        } finally {
+            if (fd != null) {
+                try {
+                    SocketUtils.closeSocket(fd);
+                } catch (IOException e) {
+                    Log.e(TAG, e.toString());
+                }
+            }
         }
-        return INVALID_UID;
+        return uid;
     }
 
     @Override
diff --git a/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
index 108b017..2aa625a 100644
--- a/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/DeviceIdleControllerTest.java
@@ -108,7 +108,7 @@
     @Mock
     private AlarmManager mAlarmManager;
     @Mock
-    private ConnectivityService mConnectivityService;
+    private ConnectivityManager mConnectivityManager;
     @Mock
     private ContentResolver mContentResolver;
     @Mock
@@ -127,7 +127,7 @@
     private SensorManager mSensorManager;
 
     class InjectorForTest extends DeviceIdleController.Injector {
-        ConnectivityService connectivityService;
+        ConnectivityManager connectivityManager;
         LocationManager locationManager;
         ConstraintController constraintController;
         // Freeze time for testing.
@@ -155,8 +155,8 @@
         }
 
         @Override
-        ConnectivityService getConnectivityService() {
-            return connectivityService;
+        ConnectivityManager getConnectivityManager() {
+            return connectivityManager;
         }
 
         @Override
@@ -347,19 +347,19 @@
     public void testUpdateConnectivityState() {
         // No connectivity service
         final boolean isConnected = mDeviceIdleController.isNetworkConnected();
-        mInjector.connectivityService = null;
+        mInjector.connectivityManager = null;
         mDeviceIdleController.updateConnectivityState(null);
         assertEquals(isConnected, mDeviceIdleController.isNetworkConnected());
 
         // No active network info
-        mInjector.connectivityService = mConnectivityService;
-        doReturn(null).when(mConnectivityService).getActiveNetworkInfo();
+        mInjector.connectivityManager = mConnectivityManager;
+        doReturn(null).when(mConnectivityManager).getActiveNetworkInfo();
         mDeviceIdleController.updateConnectivityState(null);
         assertFalse(mDeviceIdleController.isNetworkConnected());
 
         // Active network info says connected.
         final NetworkInfo ani = mock(NetworkInfo.class);
-        doReturn(ani).when(mConnectivityService).getActiveNetworkInfo();
+        doReturn(ani).when(mConnectivityManager).getActiveNetworkInfo();
         doReturn(true).when(ani).isConnected();
         mDeviceIdleController.updateConnectivityState(null);
         assertTrue(mDeviceIdleController.isNetworkConnected());
@@ -1827,10 +1827,10 @@
     }
 
     private void setNetworkConnected(boolean connected) {
-        mInjector.connectivityService = mConnectivityService;
+        mInjector.connectivityManager = mConnectivityManager;
         final NetworkInfo ani = mock(NetworkInfo.class);
         doReturn(connected).when(ani).isConnected();
-        doReturn(ani).when(mConnectivityService).getActiveNetworkInfo();
+        doReturn(ani).when(mConnectivityManager).getActiveNetworkInfo();
         mDeviceIdleController.updateConnectivityState(null);
     }
 
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java b/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
index 1685b04..8b3c85e 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
@@ -82,6 +82,7 @@
 import android.os.IBinder;
 import android.os.PowerManagerInternal;
 import android.os.SystemClock;
+import android.platform.test.annotations.Presubmit;
 import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.SparseArray;
@@ -103,6 +104,7 @@
  * Build/Install/Run:
  * atest MockingOomAdjusterTests
  */
+@Presubmit
 public class MockingOomAdjusterTests {
     private static final int MOCKAPP_PID = 12345;
     private static final int MOCKAPP_UID = 12345;
diff --git a/services/tests/mockingservicestests/src/com/android/server/display/color/DisplayWhiteBalanceTintControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/display/color/DisplayWhiteBalanceTintControllerTest.java
index 4538cac..5c2b8ce 100644
--- a/services/tests/mockingservicestests/src/com/android/server/display/color/DisplayWhiteBalanceTintControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/display/color/DisplayWhiteBalanceTintControllerTest.java
@@ -20,6 +20,8 @@
 
 import static com.google.common.truth.Truth.assertWithMessage;
 
+import static org.junit.Assert.assertArrayEquals;
+
 import android.content.Context;
 import android.content.res.Resources;
 import android.os.Binder;
@@ -184,8 +186,56 @@
                 .isFalse();
     }
 
+    /**
+     * Matrix should match the precalculated one for given cct and display primaries.
+     */
+    @Test
+    public void displayWhiteBalance_validateTransformMatrix() {
+        DisplayPrimaries displayPrimaries = new DisplayPrimaries();
+        displayPrimaries.red = new CieXyz();
+        displayPrimaries.red.X = 0.412315f;
+        displayPrimaries.red.Y = 0.212600f;
+        displayPrimaries.red.Z = 0.019327f;
+        displayPrimaries.green = new CieXyz();
+        displayPrimaries.green.X = 0.357600f;
+        displayPrimaries.green.Y = 0.715200f;
+        displayPrimaries.green.Z = 0.119200f;
+        displayPrimaries.blue = new CieXyz();
+        displayPrimaries.blue.X = 0.180500f;
+        displayPrimaries.blue.Y = 0.072200f;
+        displayPrimaries.blue.Z = 0.950633f;
+        displayPrimaries.white = new CieXyz();
+        displayPrimaries.white.X = 0.950456f;
+        displayPrimaries.white.Y = 1.000000f;
+        displayPrimaries.white.Z = 1.089058f;
+        doReturn(displayPrimaries)
+                .when(() -> SurfaceControl.getDisplayNativePrimaries(mDisplayToken));
+
+        setUpTintController();
+        assertWithMessage("Setup with valid SurfaceControl failed")
+                .that(mDisplayWhiteBalanceTintController.mSetUp)
+                .isTrue();
+
+        final int cct = 6500;
+        mDisplayWhiteBalanceTintController.setMatrix(cct);
+        assertWithMessage("Failed to set temperature")
+                .that(mDisplayWhiteBalanceTintController.mCurrentColorTemperature)
+                .isEqualTo(cct);
+
+        float[] matrixDwb = mDisplayWhiteBalanceTintController.getMatrix();
+        final float[] expectedMatrixDwb = {
+            0.962880f,  -0.001780f, -0.000158f, 0.0f,
+            0.035765f,   0.929988f,  0.000858f, 0.0f,
+            0.001354f,  -0.000470f,  0.948327f, 0.0f,
+            0.0f,        0.0f,       0.0f,      1.0f
+        };
+        assertArrayEquals("Unexpected DWB matrix", matrixDwb, expectedMatrixDwb,
+            1e-6f /* tolerance */);
+    }
+
     private void setUpTintController() {
         mDisplayWhiteBalanceTintController = new DisplayWhiteBalanceTintController();
         mDisplayWhiteBalanceTintController.setUp(mMockedContext, true);
+        mDisplayWhiteBalanceTintController.setActivated(true);
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/SystemConfigTest.java b/services/tests/servicestests/src/com/android/server/SystemConfigTest.java
new file mode 100644
index 0000000..ff03391
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/SystemConfigTest.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2019 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;
+
+import static org.junit.Assert.assertEquals;
+
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.util.Log;
+
+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.TemporaryFolder;
+import org.junit.runner.RunWith;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.Set;
+
+/**
+ * Tests for {@link SystemConfig}.
+ *
+ * Build/Install/Run:
+ *  atest FrameworksServicesTests:SystemConfigTest
+ */
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class SystemConfigTest {
+    private static final String LOG_TAG = "SystemConfigTest";
+
+    private SystemConfig mSysConfig;
+
+    @Rule public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
+
+    @Before
+    public void setUp() throws Exception {
+        mSysConfig = new SystemConfigTestClass();
+    }
+
+    /**
+     * Subclass of SystemConfig without running the constructor.
+     */
+    private class SystemConfigTestClass extends SystemConfig {
+        SystemConfigTestClass() {
+            super(false);
+        }
+    }
+
+    /**
+     * Tests that readPermissions works correctly for the tag: install-in-user-type
+     */
+    @Test
+    public void testInstallInUserType() throws Exception {
+        final String contents1 =
+                  "<permissions>\n"
+                + "    <install-in-user-type package=\"com.android.package1\">\n"
+                + "        <install-in user-type=\"FULL\" />\n"
+                + "        <install-in user-type=\"PROFILE\" />\n"
+                + "    </install-in-user-type>\n"
+                + "    <install-in-user-type package=\"com.android.package2\">\n"
+                + "        <install-in user-type=\"FULL\" />\n"
+                + "        <install-in user-type=\"PROFILE\" />\n"
+                + "        <do-not-install-in user-type=\"GUEST\" />\n"
+                + "    </install-in-user-type>\n"
+                + "</permissions>";
+
+        final String contents2 =
+                  "<permissions>\n"
+                + "    <install-in-user-type package=\"com.android.package2\">\n"
+                + "        <install-in user-type=\"SYSTEM\" />\n"
+                + "        <do-not-install-in user-type=\"PROFILE\" />\n"
+                + "    </install-in-user-type>\n"
+                + "</permissions>";
+
+        final String contents3 =
+                  "<permissions>\n"
+                + "    <install-in-user-type package=\"com.android.package2\">\n"
+                + "        <install-in invalid-attribute=\"ADMIN\" />\n" // Ignore invalid attribute
+                + "    </install-in-user-type>\n"
+                + "    <install-in-user-type package=\"com.android.package2\">\n"
+                + "        <install-in user-type=\"RESTRICTED\" />\n"  // Valid
+                + "    </install-in-user-type>\n"
+                + "    <install-in-user-type>\n" // Ignored since missing package name
+                + "        <install-in user-type=\"ADMIN\" />\n"
+                + "    </install-in-user-type>\n"
+                + "</permissions>";
+
+        Map<String, Set<String>> expectedWhite = new ArrayMap<>();
+        expectedWhite.put("com.android.package1",
+                new ArraySet<>(Arrays.asList("FULL", "PROFILE")));
+        expectedWhite.put("com.android.package2",
+                new ArraySet<>(Arrays.asList("FULL", "PROFILE", "RESTRICTED", "SYSTEM")));
+
+        Map<String, Set<String>> expectedBlack = new ArrayMap<>();
+        expectedBlack.put("com.android.package2",
+                new ArraySet<>(Arrays.asList("GUEST", "PROFILE")));
+
+        final File folder1 = createTempSubfolder("folder1");
+        createTempFile(folder1, "permFile1.xml", contents1);
+
+        final File folder2 = createTempSubfolder("folder2");
+        createTempFile(folder2, "permFile2.xml", contents2);
+
+        // Also, make a third file, but with the name folder1/permFile2.xml, to prove no conflicts.
+        createTempFile(folder1, "permFile2.xml", contents3);
+
+        mSysConfig.readPermissions(folder1, /* No permission needed anyway */ 0);
+        mSysConfig.readPermissions(folder2, /* No permission needed anyway */ 0);
+
+        Map<String, Set<String>> actualWhite = mSysConfig.getAndClearPackageToUserTypeWhitelist();
+        Map<String, Set<String>> actualBlack = mSysConfig.getAndClearPackageToUserTypeBlacklist();
+
+        assertEquals("Whitelist was not cleared", 0,
+                mSysConfig.getAndClearPackageToUserTypeWhitelist().size());
+        assertEquals("Blacklist was not cleared", 0,
+                mSysConfig.getAndClearPackageToUserTypeBlacklist().size());
+
+        assertEquals("Incorrect whitelist.", expectedWhite, actualWhite);
+        assertEquals("Incorrect blacklist", expectedBlack, actualBlack);
+    }
+
+    /**
+     * Creates folderName/fileName in the mTemporaryFolder and fills it with the contents.
+     * @param folderName subdirectory of mTemporaryFolder to put the file, creating if needed
+     * @return the folder
+     */
+    private File createTempSubfolder(String folderName)
+            throws IOException {
+        File folder = new File(mTemporaryFolder.getRoot(), folderName);
+        folder.mkdir();
+        return folder;
+    }
+
+    /**
+     * Creates folderName/fileName in the mTemporaryFolder and fills it with the contents.
+     * @param folder pre-existing subdirectory of mTemporaryFolder to put the file
+     * @param fileName name of the file (e.g. filename.xml) to create
+     * @param contents contents to write to the file
+     * @return the folder containing the newly created file (not the file itself!)
+     */
+    private File createTempFile(File folder, String fileName, String contents)
+            throws IOException {
+        File file = new File(folder, fileName);
+        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
+        bw.write(contents);
+        bw.close();
+
+        // Print to logcat for test debugging.
+        Log.d(LOG_TAG, "Contents of file " + file.getAbsolutePath());
+        Scanner input = new Scanner(file);
+        while (input.hasNextLine()) {
+            Log.d(LOG_TAG, input.nextLine());
+        }
+
+        return folder;
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AbstractAccessibilityServiceConnectionTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AbstractAccessibilityServiceConnectionTest.java
index 73dcb98..43f251a 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AbstractAccessibilityServiceConnectionTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AbstractAccessibilityServiceConnectionTest.java
@@ -46,6 +46,7 @@
 import static org.hamcrest.Matchers.hasItems;
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.nullValue;
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
@@ -140,6 +141,8 @@
     private final List<AccessibilityWindowInfo> mA11yWindowInfosOnSecondDisplay = new ArrayList<>();
     private Callable[] mFindA11yNodesFunctions;
     private Callable<Boolean> mPerformA11yAction;
+    private ArrayList<Integer> mDisplayList = new ArrayList<>(Arrays.asList(
+            Display.DEFAULT_DISPLAY, SECONDARY_DISPLAY_ID));
 
     // To mock package-private class.
     @Rule public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
@@ -184,6 +187,7 @@
         addA11yWindowInfo(mA11yWindowInfos, PIP_WINDOWID, true, Display.DEFAULT_DISPLAY);
         addA11yWindowInfo(mA11yWindowInfosOnSecondDisplay, WINDOWID_ONSECONDDISPLAY, false,
                 SECONDARY_DISPLAY_ID);
+        when(mMockA11yWindowManager.getDisplayListLocked()).thenReturn(mDisplayList);
         when(mMockA11yWindowManager.getWindowListLocked(Display.DEFAULT_DISPLAY))
                 .thenReturn(mA11yWindowInfos);
         when(mMockA11yWindowManager.findA11yWindowInfoByIdLocked(WINDOWID))
@@ -285,7 +289,14 @@
 
     @Test
     public void getWindows() {
-        assertThat(mServiceConnection.getWindows(), is(mA11yWindowInfos));
+        final AccessibilityWindowInfo.WindowListSparseArray allWindows =
+                mServiceConnection.getWindows();
+
+        assertEquals(2, allWindows.size());
+        assertThat(allWindows.get(Display.DEFAULT_DISPLAY), is(mA11yWindowInfos));
+        assertEquals(2, allWindows.get(Display.DEFAULT_DISPLAY).size());
+        assertThat(allWindows.get(SECONDARY_DISPLAY_ID), is(mA11yWindowInfosOnSecondDisplay));
+        assertEquals(1, allWindows.get(SECONDARY_DISPLAY_ID).size());
     }
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
index b7b5a4e..b5e5deb 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/AccessibilityWindowManagerTest.java
@@ -67,6 +67,7 @@
 import org.mockito.MockitoAnnotations;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 
 /**
@@ -104,6 +105,9 @@
     // List of callback, mapping from displayId -> callback.
     private final SparseArray<WindowsForAccessibilityCallback> mCallbackOfWindows =
             new SparseArray<>();
+    // List of display ID.
+    private final ArrayList<Integer> mExpectedDisplayList = new ArrayList<>(Arrays.asList(
+            Display.DEFAULT_DISPLAY, SECONDARY_DISPLAY_ID));
 
     private final MessageCapturingHandler mHandler = new MessageCapturingHandler(null);
 
@@ -692,6 +696,15 @@
         assertTrue(windowId >= 0);
     }
 
+    @Test
+    public void getDisplayList() throws RemoteException {
+        // Starts tracking window of second display.
+        startTrackingPerDisplay(SECONDARY_DISPLAY_ID);
+
+        final ArrayList<Integer> displayList = mA11yWindowManager.getDisplayListLocked();
+        assertTrue(displayList.equals(mExpectedDisplayList));
+    }
+
     private void startTrackingPerDisplay(int displayId) throws RemoteException {
         ArrayList<WindowInfo> windowInfosForDisplay = new ArrayList<>();
         // Adds RemoteAccessibilityConnection into AccessibilityWindowManager, and copy
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/KeyboardInterceptorTest.java b/services/tests/servicestests/src/com/android/server/accessibility/KeyboardInterceptorTest.java
index 9926a09..322653b 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/KeyboardInterceptorTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/KeyboardInterceptorTest.java
@@ -28,12 +28,12 @@
 import static org.mockito.Mockito.when;
 import static org.mockito.hamcrest.MockitoHamcrest.argThat;
 
+import android.os.IBinder;
 import android.view.KeyEvent;
 
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.server.policy.WindowManagerPolicy;
-import com.android.server.policy.WindowManagerPolicy.WindowState;
 
 import org.hamcrest.Description;
 import org.hamcrest.TypeSafeMatcher;
@@ -79,7 +79,7 @@
     @Test
     public void whenVolumeKeyArrives_andPolicySaysUseIt_eventGoesToAms() {
         KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_DOWN);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(event)), eq(0))).thenReturn(0L);
         mInterceptor.onKeyEvent(event, 0);
         verify(mMockAms).notifyKeyEvent(argThat(matchesKeyEvent(event)), eq(0));
@@ -88,7 +88,7 @@
     @Test
     public void whenVolumeKeyArrives_andPolicySaysDropIt_eventDropped() {
         KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_UP);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(event)), eq(0))).thenReturn(-1L);
         mInterceptor.onKeyEvent(event, 0);
         verify(mMockAms, times(0)).notifyKeyEvent(anyObject(), anyInt());
@@ -98,14 +98,14 @@
     @Test
     public void whenVolumeKeyArrives_andPolicySaysDelayThenUse_eventQueuedThenSentToAms() {
         KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_UP);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(event)), eq(0))).thenReturn(150L);
         mInterceptor.onKeyEvent(event, 0);
 
         assertTrue(mHandler.hasMessages());
         verify(mMockAms, times(0)).notifyKeyEvent(anyObject(), anyInt());
 
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(event)), eq(0))).thenReturn(0L);
         mHandler.sendAllMessages();
 
@@ -115,14 +115,14 @@
     @Test
     public void whenVolumeKeyArrives_andPolicySaysDelayThenDrop_eventQueuedThenDropped() {
         KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_DOWN);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(event)), eq(0))).thenReturn(150L);
         mInterceptor.onKeyEvent(event, 0);
 
         assertTrue(mHandler.hasMessages());
         verify(mMockAms, times(0)).notifyKeyEvent(anyObject(), anyInt());
 
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(event)), eq(0))).thenReturn(-1L);
         mHandler.sendAllMessages();
 
@@ -137,18 +137,18 @@
                 new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_VOLUME_UP),
                 new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_0)};
 
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[1])), eq(0))).thenReturn(150L);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[3])), eq(0))).thenReturn(75L);
 
         for (KeyEvent event : events) {
             mInterceptor.onKeyEvent(event, 0);
         }
 
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[1])), eq(0))).thenReturn(0L);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[3])), eq(0))).thenReturn(0L);
 
         mHandler.sendAllMessages();
@@ -167,18 +167,18 @@
                 new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_VOLUME_UP),
                 new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_0)};
 
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[1])), eq(0))).thenReturn(150L);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[3])), eq(0))).thenReturn(75L);
 
         for (KeyEvent event : events) {
             mInterceptor.onKeyEvent(event, 0);
         }
 
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[1])), eq(0))).thenReturn(-1L);
-        when(mMockPolicy.interceptKeyBeforeDispatching((WindowState) argThat(nullValue()),
+        when(mMockPolicy.interceptKeyBeforeDispatching((IBinder) argThat(nullValue()),
                 argThat(matchesKeyEvent(events[3])), eq(0))).thenReturn(-1L);
 
         mHandler.sendAllMessages();
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/MotionEventInjectorTest.java b/services/tests/servicestests/src/com/android/server/accessibility/MotionEventInjectorTest.java
index f1142fd..36e854c 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/MotionEventInjectorTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/MotionEventInjectorTest.java
@@ -46,7 +46,6 @@
 import android.os.Handler;
 import android.os.Message;
 import android.os.RemoteException;
-import android.util.Log;
 import android.view.Display;
 import android.view.InputDevice;
 import android.view.KeyEvent;
@@ -55,6 +54,8 @@
 
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.server.accessibility.utils.MotionEventMatcher;
+
 import org.hamcrest.Description;
 import org.hamcrest.Matcher;
 import org.hamcrest.TypeSafeMatcher;
@@ -761,56 +762,6 @@
         return next;
     }
 
-    static class MotionEventMatcher extends TypeSafeMatcher<MotionEvent> {
-        long mDownTime;
-        long mEventTime;
-        long mActionMasked;
-        int mX;
-        int mY;
-
-        MotionEventMatcher(long downTime, long eventTime, int actionMasked, int x, int y) {
-            mDownTime = downTime;
-            mEventTime = eventTime;
-            mActionMasked = actionMasked;
-            mX = x;
-            mY = y;
-        }
-
-        MotionEventMatcher(MotionEvent event) {
-            this(event.getDownTime(), event.getEventTime(), event.getActionMasked(),
-                    (int) event.getX(), (int) event.getY());
-        }
-
-        void offsetTimesBy(long timeOffset) {
-            mDownTime += timeOffset;
-            mEventTime += timeOffset;
-        }
-
-        @Override
-        public boolean matchesSafely(MotionEvent event) {
-            if ((event.getDownTime() == mDownTime) && (event.getEventTime() == mEventTime)
-                    && (event.getActionMasked() == mActionMasked) && ((int) event.getX() == mX)
-                    && ((int) event.getY() == mY)) {
-                return true;
-            }
-            Log.e(LOG_TAG, "MotionEvent match failed");
-            Log.e(LOG_TAG, "event.getDownTime() = " + event.getDownTime()
-                    + ", expected " + mDownTime);
-            Log.e(LOG_TAG, "event.getEventTime() = " + event.getEventTime()
-                    + ", expected " + mEventTime);
-            Log.e(LOG_TAG, "event.getActionMasked() = " + event.getActionMasked()
-                    + ", expected " + mActionMasked);
-            Log.e(LOG_TAG, "event.getX() = " + event.getX() + ", expected " + mX);
-            Log.e(LOG_TAG, "event.getY() = " + event.getY() + ", expected " + mY);
-            return false;
-        }
-
-        @Override
-        public void describeTo(Description description) {
-            description.appendText("Motion event matcher");
-        }
-    }
-
     private static class MotionEventActionMatcher extends TypeSafeMatcher<MotionEvent> {
         int mAction;
 
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java
index 104aacb..4b1ec6f 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/gestures/TouchExplorerTest.java
@@ -21,6 +21,7 @@
 import static com.android.server.accessibility.gestures.TouchState.STATE_DRAGGING;
 import static com.android.server.accessibility.gestures.TouchState.STATE_TOUCH_EXPLORING;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.junit.Assert.assertEquals;
 import static org.mockito.Mockito.mock;
 
@@ -36,6 +37,7 @@
 
 import com.android.server.accessibility.AccessibilityManagerService;
 import com.android.server.accessibility.EventStreamTransformation;
+import com.android.server.accessibility.utils.MotionEventMatcher;
 
 import org.junit.Before;
 import org.junit.Rule;
@@ -49,6 +51,7 @@
 @RunWith(AndroidJUnit4.class)
 public class TouchExplorerTest {
 
+    private static final String LOG_TAG = "TouchExplorerTest";
     private static final int FLAG_1FINGER = 0x8000;
     private static final int FLAG_2FINGERS = 0x0100;
     private static final int FLAG_3FINGERS = 0x0200;
@@ -86,7 +89,9 @@
 
         @Override
         public void onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+            MotionEventMatcher lastEventMatcher = new MotionEventMatcher(mLastEvent);
             mEvents.add(0, event.copy());
+            assertThat(rawEvent, lastEventMatcher);
         }
 
         @Override
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/utils/MotionEventMatcher.java b/services/tests/servicestests/src/com/android/server/accessibility/utils/MotionEventMatcher.java
new file mode 100644
index 0000000..2b6d385
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/accessibility/utils/MotionEventMatcher.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2019 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.accessibility.utils;
+
+import android.util.Log;
+import android.view.MotionEvent;
+
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeMatcher;
+
+/**
+ * This class compares two motion events using a subset of their attributes: actionMasked, downTime,
+ * eventTime, and location. If two events match they are considered to be effectively equal.
+ */
+public class MotionEventMatcher extends TypeSafeMatcher<MotionEvent> {
+    private static final String LOG_TAG = "MotionEventMatcher";
+    long mDownTime;
+    long mEventTime;
+    long mActionMasked;
+    int mX;
+    int mY;
+
+    MotionEventMatcher(long downTime, long eventTime, int actionMasked, int x, int y) {
+        mDownTime = downTime;
+        mEventTime = eventTime;
+        mActionMasked = actionMasked;
+        mX = x;
+        mY = y;
+    }
+
+    public MotionEventMatcher(MotionEvent event) {
+        this(
+                event.getDownTime(),
+                event.getEventTime(),
+                event.getActionMasked(),
+                (int) event.getX(),
+                (int) event.getY());
+    }
+
+    void offsetTimesBy(long timeOffset) {
+        mDownTime += timeOffset;
+        mEventTime += timeOffset;
+    }
+
+    @Override
+    public boolean matchesSafely(MotionEvent event) {
+        if ((event.getDownTime() == mDownTime)
+                && (event.getEventTime() == mEventTime)
+                && (event.getActionMasked() == mActionMasked)
+                && ((int) event.getX() == mX)
+                && ((int) event.getY() == mY)) {
+            return true;
+        }
+        Log.e(LOG_TAG, "MotionEvent match failed");
+        Log.e(LOG_TAG, "event.getDownTime() = " + event.getDownTime() + ", expected " + mDownTime);
+        Log.e(
+                LOG_TAG,
+                "event.getEventTime() = " + event.getEventTime() + ", expected " + mEventTime);
+        Log.e(
+                LOG_TAG,
+                "event.getActionMasked() = "
+                        + event.getActionMasked()
+                        + ", expected "
+                        + mActionMasked);
+        Log.e(LOG_TAG, "event.getX() = " + event.getX() + ", expected " + mX);
+        Log.e(LOG_TAG, "event.getY() = " + event.getY() + ", expected " + mY);
+        return false;
+    }
+
+    @Override
+    public void describeTo(Description description) {
+        description.appendText("Motion event matcher");
+    }
+}
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 9e3b54d..c3a1243 100644
--- a/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java
@@ -16,10 +16,8 @@
 
 package com.android.server.am;
 
-import static com.android.server.am.MemoryStatUtil.BYTES_IN_KILOBYTE;
-import static com.android.server.am.MemoryStatUtil.JIFFY_NANOS;
 import static com.android.server.am.MemoryStatUtil.MemoryStat;
-import static com.android.server.am.MemoryStatUtil.parseCmdlineFromProcfs;
+import static com.android.server.am.MemoryStatUtil.PAGE_SIZE;
 import static com.android.server.am.MemoryStatUtil.parseMemoryStatFromMemcg;
 import static com.android.server.am.MemoryStatUtil.parseMemoryStatFromProcfs;
 
@@ -30,7 +28,6 @@
 
 import org.junit.Test;
 
-import java.io.ByteArrayOutputStream;
 import java.util.Collections;
 
 /**
@@ -99,7 +96,7 @@
             "0",
             "2222", // this in start time (in ticks per second)
             "1257177088",
-            "3",
+            "3", // this is RSS in pages
             "4294967295",
             "2936971264",
             "2936991289",
@@ -129,53 +126,6 @@
             "3198889956",
             "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-water mark
-            + "VmRSS:\t  126776 kB\n" // RSS
-            + "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      22 kB\n" // Swap
-            + "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() {
         MemoryStat stat = parseMemoryStatFromMemcg(MEMORY_STAT_CONTENTS);
@@ -197,71 +147,26 @@
 
     @Test
     public void testParseMemoryStatFromProcfs_parsesCorrectValues() {
-        MemoryStat stat = parseMemoryStatFromProcfs(PROC_STAT_CONTENTS, PROC_STATUS_CONTENTS);
+        MemoryStat stat = parseMemoryStatFromProcfs(PROC_STAT_CONTENTS);
         assertEquals(1, stat.pgfault);
         assertEquals(2, stat.pgmajfault);
-        assertEquals(126776 * BYTES_IN_KILOBYTE, stat.rssInBytes);
+        assertEquals(3 * PAGE_SIZE, stat.rssInBytes);
         assertEquals(0, stat.cacheInBytes);
-        assertEquals(22 * BYTES_IN_KILOBYTE, stat.swapInBytes);
-        assertEquals(2222 * JIFFY_NANOS, stat.startTimeNanos);
-        assertEquals(37860 * BYTES_IN_KILOBYTE, stat.anonRssInBytes);
+        assertEquals(0, stat.swapInBytes);
     }
 
     @Test
     public void testParseMemoryStatFromProcfs_emptyContents() {
-        MemoryStat stat = parseMemoryStatFromProcfs("", PROC_STATUS_CONTENTS);
+        MemoryStat stat = parseMemoryStatFromProcfs("");
         assertNull(stat);
 
-        stat = parseMemoryStatFromProcfs(null, PROC_STATUS_CONTENTS);
-        assertNull(stat);
-
-        stat = parseMemoryStatFromProcfs(PROC_STAT_CONTENTS, "");
-        assertNull(stat);
-
-        stat = parseMemoryStatFromProcfs(PROC_STAT_CONTENTS, null);
+        stat = parseMemoryStatFromProcfs(null);
         assertNull(stat);
     }
 
     @Test
     public void testParseMemoryStatFromProcfs_invalidValue() {
         String contents = String.join(" ", Collections.nCopies(24, "memory"));
-        assertNull(parseMemoryStatFromProcfs(contents, PROC_STATUS_CONTENTS));
-    }
-
-    @Test
-    public void testParseCmdlineFromProcfs_invalidValue() {
-        byte[] nothing = new byte[] {0x00, 0x74, 0x65, 0x73, 0x74}; // \0test
-
-        assertEquals("", parseCmdlineFromProcfs(bytesToString(nothing)));
-    }
-
-    @Test
-    public void testParseCmdlineFromProcfs_correctValue_noNullBytes() {
-        assertEquals("com.google.app", parseCmdlineFromProcfs("com.google.app"));
-    }
-
-    @Test
-    public void testParseCmdlineFromProcfs_correctValue_withNullBytes() {
-        byte[] trailing = new byte[] {0x74, 0x65, 0x73, 0x74, 0x00, 0x00, 0x00}; // test\0\0\0
-
-        assertEquals("test", parseCmdlineFromProcfs(bytesToString(trailing)));
-
-        // test\0\0test
-        byte[] inside = new byte[] {0x74, 0x65, 0x73, 0x74, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74};
-
-        assertEquals("test", parseCmdlineFromProcfs(bytesToString(trailing)));
-    }
-
-    @Test
-    public void testParseCmdlineFromProcfs_emptyContents() {
-        assertEquals("", parseCmdlineFromProcfs(""));
-
-        assertEquals("", parseCmdlineFromProcfs(null));
-    }
-
-    private static String bytesToString(byte[] bytes) {
-        ByteArrayOutputStream output = new ByteArrayOutputStream();
-        output.write(bytes, 0, bytes.length);
-        return output.toString();
+        assertNull(parseMemoryStatFromProcfs(contents));
     }
 }
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 d4b7e7e9..79cc3db 100644
--- a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
@@ -25,8 +25,8 @@
 import static com.android.server.am.UserController.REPORT_LOCKED_BOOT_COMPLETE_MSG;
 import static com.android.server.am.UserController.REPORT_USER_SWITCH_COMPLETE_MSG;
 import static com.android.server.am.UserController.REPORT_USER_SWITCH_MSG;
-import static com.android.server.am.UserController.SYSTEM_USER_CURRENT_MSG;
-import static com.android.server.am.UserController.SYSTEM_USER_START_MSG;
+import static com.android.server.am.UserController.USER_CURRENT_MSG;
+import static com.android.server.am.UserController.USER_START_MSG;
 import static com.android.server.am.UserController.USER_SWITCH_TIMEOUT_MSG;
 
 import static com.google.android.collect.Lists.newArrayList;
@@ -53,11 +53,13 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.annotation.UserIdInt;
 import android.app.IUserSwitchObserver;
 import android.content.Context;
 import android.content.IIntentReceiver;
 import android.content.Intent;
 import android.content.pm.UserInfo;
+import android.content.pm.UserInfo.UserInfoFlag;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
@@ -106,6 +108,10 @@
     private static final int TEST_USER_ID1 = 101;
     private static final int TEST_USER_ID2 = 102;
     private static final int NONEXIST_USER_ID = 2;
+    private static final int TEST_PRE_CREATED_USER_ID = 103;
+
+    private static final int NO_USERINFO_FLAGS = 0;
+
     private static final String TAG = UserControllerTest.class.getSimpleName();
 
     private static final long HANDLER_WAIT_TIME_MS = 100;
@@ -127,11 +133,11 @@
     private static final Set<Integer> START_FOREGROUND_USER_MESSAGE_CODES = newHashSet(
             REPORT_USER_SWITCH_MSG,
             USER_SWITCH_TIMEOUT_MSG,
-            SYSTEM_USER_START_MSG,
-            SYSTEM_USER_CURRENT_MSG);
+            USER_START_MSG,
+            USER_CURRENT_MSG);
 
     private static final Set<Integer> START_BACKGROUND_USER_MESSAGE_CODES = newHashSet(
-            SYSTEM_USER_START_MSG,
+            USER_START_MSG,
             REPORT_LOCKED_BOOT_COMPLETE_MSG);
 
     @Before
@@ -148,7 +154,8 @@
             doNothing().when(mInjector).clearBroadcastQueueForUser(anyInt());
             doNothing().when(mInjector).stackSupervisorRemoveUser(anyInt());
             mUserController = new UserController(mInjector);
-            setUpUser(TEST_USER_ID, 0);
+            setUpUser(TEST_USER_ID, NO_USERINFO_FLAGS);
+            setUpUser(TEST_PRE_CREATED_USER_ID, NO_USERINFO_FLAGS, /* preCreated=*/ true);
         });
     }
 
@@ -188,6 +195,31 @@
         startForegroundUserAssertions();
     }
 
+    @Test
+    public void testStartPreCreatedUser_foreground() {
+        assertFalse(mUserController.startUser(TEST_PRE_CREATED_USER_ID, /* foreground= */ true));
+    }
+
+    @Test
+    public void testStartPreCreatedUser_background() throws Exception {
+        assertTrue(mUserController.startUser(TEST_PRE_CREATED_USER_ID, /* foreground= */ false));
+
+        verify(mInjector.getWindowManager(), never()).startFreezingScreen(anyInt(), anyInt());
+        verify(mInjector.getWindowManager(), never()).setSwitchingUser(anyBoolean());
+        verify(mInjector, never()).clearAllLockedTasks(anyString());
+
+        assertWithMessage("should not have received intents")
+                .that(getActions(mInjector.mSentIntents)).isEmpty();
+        // TODO(b/140868593): should have received a USER_UNLOCK_MSG message as well, but it doesn't
+        // because StorageManager.isUserKeyUnlocked(TEST_PRE_CREATED_USER_ID) returns false - to
+        // properly fix it, we'd need to move this class to FrameworksMockingServicesTests so we can
+        // mock static methods (but moving this class would involve changing the presubmit tests,
+        // and the cascade effect goes on...). In fact, a better approach would to not assert the
+        // binder calls, but their side effects (in this case, that the user is stopped right away)
+        assertWithMessage("wrong binder message calls").that(mInjector.mHandler.getMessageCodes())
+                .containsExactly(USER_START_MSG);
+    }
+
     private void startUserAssertions(
             List<String> expectedActions, Set<Integer> expectedMessageCodes) {
         assertEquals(expectedActions, getActions(mInjector.mSentIntents));
@@ -467,9 +499,15 @@
         continueUserSwitchAssertions(newUserId, expectOldUserStopping);
     }
 
-    private void setUpUser(int userId, int flags) {
+    private void setUpUser(@UserIdInt int userId, @UserInfoFlag int flags) {
+        setUpUser(userId, flags, /* preCreated= */ false);
+    }
+
+    private void setUpUser(@UserIdInt int userId, @UserInfoFlag int flags, boolean preCreated) {
         UserInfo userInfo = new UserInfo(userId, "User" + userId, flags);
+        userInfo.preCreated = preCreated;
         when(mInjector.mUserManagerMock.getUserInfo(eq(userId))).thenReturn(userInfo);
+        when(mInjector.mUserManagerMock.isPreCreated(userId)).thenReturn(preCreated);
     }
 
     private static List<String> getActions(List<Intent> intents) {
diff --git a/services/tests/servicestests/src/com/android/server/appop/AppOpsUpgradeTest.java b/services/tests/servicestests/src/com/android/server/appop/AppOpsUpgradeTest.java
index 70650de..66d2bab 100644
--- a/services/tests/servicestests/src/com/android/server/appop/AppOpsUpgradeTest.java
+++ b/services/tests/servicestests/src/com/android/server/appop/AppOpsUpgradeTest.java
@@ -89,11 +89,13 @@
         final int defaultModeOp2 = AppOpsManager.opToDefaultMode(op2);
         for(int i = 0; i < uidStates.size(); i++) {
             final AppOpsService.UidState uidState = uidStates.valueAt(i);
-            final int uidMode1 = uidState.hasOpMode(op1) ? uidState.getOpMode(op1) : defaultModeOp1;
-            final int uidMode2 = uidState.hasOpMode(op2) ? uidState.getOpMode(op2) : defaultModeOp2;
-            assertEquals(uidMode1, uidMode2);
-            if (uidMode1 != defaultModeOp1) {
-                numberOfNonDefaultOps++;
+            if (uidState.opModes != null) {
+                final int uidMode1 = uidState.opModes.get(op1, defaultModeOp1);
+                final int uidMode2 = uidState.opModes.get(op2, defaultModeOp2);
+                assertEquals(uidMode1, uidMode2);
+                if (uidMode1 != defaultModeOp1) {
+                    numberOfNonDefaultOps++;
+                }
             }
             if (uidState.pkgOps == null) {
                 continue;
diff --git a/services/tests/servicestests/src/com/android/server/backup/transport/DelegatingTransportTest.java b/services/tests/servicestests/src/com/android/server/backup/transport/DelegatingTransportTest.java
new file mode 100644
index 0000000..bae11eb
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/backup/transport/DelegatingTransportTest.java
@@ -0,0 +1,386 @@
+/*
+ * Copyright (C) 2019 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.backup.transport;
+
+import static junit.framework.Assert.assertEquals;
+
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.app.backup.RestoreDescription;
+import android.app.backup.RestoreSet;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.backup.IBackupTransport;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@Presubmit
+@RunWith(AndroidJUnit4.class)
+public class DelegatingTransportTest {
+    @Mock private IBackupTransport mBackupTransport;
+    @Mock private PackageInfo mPackageInfo;
+    @Mock private ParcelFileDescriptor mFd;
+
+    private final String mPackageName = "testpackage";
+    private final RestoreSet mRestoreSet = new RestoreSet();
+    private final int mFlags = 1;
+    private final long mRestoreToken = 10;
+    private final long mSize = 100;
+    private final int mNumBytes = 1000;
+    private DelegatingTransport mDelegatingTransport;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        mDelegatingTransport = new DelegatingTransport() {
+            @Override
+            protected IBackupTransport getDelegate() {
+                return mBackupTransport;
+            }
+        };
+    }
+
+    @Test
+    public void testName() throws RemoteException {
+        String exp = "dummy";
+        when(mBackupTransport.name()).thenReturn(exp);
+
+        String ret = mDelegatingTransport.name();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).name();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testConfigurationIntent() throws RemoteException {
+        Intent exp = new Intent("dummy");
+        when(mBackupTransport.configurationIntent()).thenReturn(exp);
+
+        Intent ret = mDelegatingTransport.configurationIntent();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).configurationIntent();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testCurrentDestinationString() throws RemoteException {
+        String exp = "dummy";
+        when(mBackupTransport.currentDestinationString()).thenReturn(exp);
+
+        String ret = mDelegatingTransport.currentDestinationString();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).currentDestinationString();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testDataManagementIntent() throws RemoteException {
+        Intent exp = new Intent("dummy");
+        when(mBackupTransport.dataManagementIntent()).thenReturn(exp);
+
+        Intent ret = mDelegatingTransport.dataManagementIntent();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).dataManagementIntent();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testDataManagementIntentLabel() throws RemoteException {
+        String exp = "dummy";
+        when(mBackupTransport.dataManagementIntentLabel()).thenReturn(exp);
+
+        CharSequence ret = mDelegatingTransport.dataManagementIntentLabel();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).dataManagementIntentLabel();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testTransportDirName() throws RemoteException {
+        String exp = "dummy";
+        when(mBackupTransport.transportDirName()).thenReturn(exp);
+
+        String ret = mDelegatingTransport.transportDirName();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).transportDirName();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testRequestBackupTime() throws RemoteException {
+        long exp = 1000L;
+        when(mBackupTransport.requestBackupTime()).thenReturn(exp);
+
+        long ret = mDelegatingTransport.requestBackupTime();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).requestBackupTime();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testInitializeDevice() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.initializeDevice()).thenReturn(exp);
+
+        long ret = mDelegatingTransport.initializeDevice();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).initializeDevice();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testPerformBackup() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.performBackup(mPackageInfo, mFd, mFlags)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.performBackup(mPackageInfo, mFd, mFlags);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).performBackup(mPackageInfo, mFd, mFlags);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testClearBackupData() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.clearBackupData(mPackageInfo)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.clearBackupData(mPackageInfo);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).clearBackupData(mPackageInfo);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testFinishBackup() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.finishBackup()).thenReturn(exp);
+
+        int ret = mDelegatingTransport.finishBackup();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).finishBackup();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testGetAvailableRestoreSets() throws RemoteException {
+        RestoreSet[] exp = new RestoreSet[] {mRestoreSet};
+        when(mBackupTransport.getAvailableRestoreSets()).thenReturn(exp);
+
+        RestoreSet[] ret = mDelegatingTransport.getAvailableRestoreSets();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).getAvailableRestoreSets();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testGetCurrentRestoreSet() throws RemoteException {
+        long exp = 1000;
+        when(mBackupTransport.getCurrentRestoreSet()).thenReturn(exp);
+
+        long ret = mDelegatingTransport.getCurrentRestoreSet();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).getCurrentRestoreSet();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testStartRestore() throws RemoteException {
+        int exp = 1000;
+        PackageInfo[] packageInfos = {mPackageInfo};
+        when(mBackupTransport.startRestore(mRestoreToken, packageInfos)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.startRestore(mRestoreToken, packageInfos);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).startRestore(mRestoreToken, packageInfos);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testNextRestorePackage() throws RemoteException {
+        RestoreDescription exp = new RestoreDescription(mPackageName, 1);
+        when(mBackupTransport.nextRestorePackage()).thenReturn(exp);
+
+        RestoreDescription ret = mDelegatingTransport.nextRestorePackage();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).nextRestorePackage();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testGetRestoreData() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.getRestoreData(mFd)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.getRestoreData(mFd);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).getRestoreData(mFd);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void tesFinishRestore() throws RemoteException {
+        mDelegatingTransport.finishRestore();
+
+        verify(mBackupTransport, times(1)).finishRestore();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testRequestFullBackupTime() throws RemoteException {
+        long exp = 1000L;
+        when(mBackupTransport.requestFullBackupTime()).thenReturn(exp);
+
+        long ret = mDelegatingTransport.requestFullBackupTime();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).requestFullBackupTime();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testPerformFullBackup() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.performFullBackup(mPackageInfo, mFd, mFlags)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.performFullBackup(mPackageInfo, mFd, mFlags);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).performFullBackup(mPackageInfo, mFd, mFlags);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testCheckFullBackupSize() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.checkFullBackupSize(mSize)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.checkFullBackupSize(mSize);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).checkFullBackupSize(mSize);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testSendBackupData() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.sendBackupData(mNumBytes)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.sendBackupData(mNumBytes);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).sendBackupData(mNumBytes);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testCancelFullBackup() throws RemoteException {
+        mDelegatingTransport.cancelFullBackup();
+
+        verify(mBackupTransport, times(1)).cancelFullBackup();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testIsAppEligibleForBackup() throws RemoteException {
+        boolean exp = true;
+        when(mBackupTransport.isAppEligibleForBackup(mPackageInfo, true)).thenReturn(exp);
+
+        boolean ret = mDelegatingTransport.isAppEligibleForBackup(mPackageInfo, true);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).isAppEligibleForBackup(mPackageInfo, true);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testGetBackupQuota() throws RemoteException {
+        long exp = 1000;
+        when(mBackupTransport.getBackupQuota(mPackageName, true)).thenReturn(exp);
+
+        long ret = mDelegatingTransport.getBackupQuota(mPackageName, true);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).getBackupQuota(mPackageName, true);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testGetNextFullRestoreDataChunk() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.getNextFullRestoreDataChunk(mFd)).thenReturn(exp);
+
+        int ret = mDelegatingTransport.getNextFullRestoreDataChunk(mFd);
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).getNextFullRestoreDataChunk(mFd);
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testAbortFullRestore() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.abortFullRestore()).thenReturn(exp);
+
+        int ret = mDelegatingTransport.abortFullRestore();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).abortFullRestore();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+
+    @Test
+    public void testGetTransportFlags() throws RemoteException {
+        int exp = 1000;
+        when(mBackupTransport.getTransportFlags()).thenReturn(exp);
+
+        int ret = mDelegatingTransport.getTransportFlags();
+
+        assertEquals(exp, ret);
+        verify(mBackupTransport, times(1)).getTransportFlags();
+        verifyNoMoreInteractions(mBackupTransport);
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
index ccf3a90..4aeeb0a 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
@@ -39,6 +39,7 @@
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.content.res.Resources;
+import android.hardware.biometrics.Authenticator;
 import android.hardware.biometrics.BiometricAuthenticator;
 import android.hardware.biometrics.BiometricConstants;
 import android.hardware.biometrics.BiometricPrompt;
@@ -55,6 +56,9 @@
 import android.os.IBinder;
 import android.security.KeyStore;
 
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+
 import com.android.internal.R;
 import com.android.internal.statusbar.IStatusBarService;
 
@@ -66,9 +70,6 @@
 
 import java.util.List;
 
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-
 @SmallTest
 public class BiometricServiceTest {
 
@@ -82,6 +83,7 @@
     private static final String ERROR_CANCELED = "error_canceled";
     private static final String ERROR_UNABLE_TO_PROCESS = "error_unable_to_process";
     private static final String ERROR_USER_CANCELED = "error_user_canceled";
+    private static final String ERROR_LOCKOUT = "error_lockout";
 
     private static final String FINGERPRINT_ACQUIRED_SENSOR_DIRTY = "sensor_dirty";
 
@@ -179,7 +181,8 @@
         mBiometricService = new BiometricService(mContext, new MockInjector());
         mBiometricService.onStart();
 
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricConstants.BIOMETRIC_ERROR_HW_NOT_PRESENT), eq(ERROR_HW_UNAVAILABLE));
@@ -193,7 +196,8 @@
         mBiometricService = new BiometricService(mContext, new MockInjector());
         mBiometricService.onStart();
 
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricConstants.BIOMETRIC_ERROR_NO_BIOMETRICS), any());
@@ -208,7 +212,8 @@
         mBiometricService = new BiometricService(mContext, new MockInjector());
         mBiometricService.onStart();
 
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE), eq(ERROR_HW_UNAVAILABLE));
@@ -226,7 +231,8 @@
 
         // Disabled in user settings receives onError
         when(mBiometricService.mSettingObserver.getFaceEnabledForApps(anyInt())).thenReturn(false);
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
         verify(mReceiver1).onError(
                 eq(BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE), eq(ERROR_HW_UNAVAILABLE));
@@ -236,7 +242,8 @@
         when(mBiometricService.mSettingObserver.getFaceEnabledForApps(anyInt())).thenReturn(true);
         when(mBiometricService.mSettingObserver.getFaceAlwaysRequireConfirmation(anyInt()))
                 .thenReturn(true);
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
         verify(mReceiver1, never()).onError(anyInt(), any(String.class));
         verify(mBiometricService.mFaceService).prepareForAuthentication(
@@ -255,7 +262,8 @@
         resetReceiver();
         when(mBiometricService.mSettingObserver.getFaceAlwaysRequireConfirmation(anyInt()))
                 .thenReturn(false);
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
         verify(mBiometricService.mFaceService).prepareForAuthentication(
                 eq(false) /* requireConfirmation */,
@@ -277,7 +285,8 @@
         mBiometricService.onStart();
 
         // Start testing the happy path
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
 
         // Creates a pending auth session with the correct initial states
@@ -311,7 +320,7 @@
                 .startPreparedClient(cookieCaptor.getValue());
 
         // StatusBar showBiometricDialog invoked
-        verify(mBiometricService.mStatusBarService).showBiometricDialog(
+        verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
                 eq(mBiometricService.mCurrentAuthSession.mBundle),
                 any(IBiometricServiceReceiverInternal.class),
                 eq(BiometricAuthenticator.TYPE_FINGERPRINT),
@@ -333,7 +342,7 @@
 
         // SystemUI sends callback with dismissed reason
         mBiometricService.mInternalReceiver.onDialogDismissed(
-                BiometricPrompt.DISMISSED_REASON_CONFIRM_NOT_REQUIRED);
+                BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED);
         waitForIdle();
         // HAT sent to keystore
         verify(mBiometricService.mKeyStore).addAuthToken(any(byte[].class));
@@ -344,10 +353,32 @@
     }
 
     @Test
+    public void testAuthenticate_noBiometrics_credentialAllowed() throws Exception {
+        setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
+        when(mFaceManager.hasEnrolledTemplates(anyInt())).thenReturn(false);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
+                true /* requireConfirmation */, true /* allowDeviceCredential */);
+        waitForIdle();
+
+        assertEquals(BiometricService.STATE_SHOWING_DEVICE_CREDENTIAL,
+                mBiometricService.mCurrentAuthSession.mState);
+        assertEquals(Authenticator.TYPE_CREDENTIAL,
+                mBiometricService.mCurrentAuthSession.mBundle
+                        .getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+        verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
+                eq(mBiometricService.mCurrentAuthSession.mBundle),
+                any(IBiometricServiceReceiverInternal.class),
+                eq(0 /* biometricModality */),
+                anyBoolean() /* requireConfirmation */,
+                anyInt() /* userId */,
+                eq(TEST_PACKAGE_NAME));
+    }
+
+    @Test
     public void testAuthenticate_happyPathWithConfirmation() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                true /* requireConfirmation */);
+                true /* requireConfirmation */, false /* allowDeviceCredential */);
 
         // Test authentication succeeded goes to PENDING_CONFIRMATION and that the HAT is not
         // sent to KeyStore yet
@@ -362,7 +393,7 @@
 
         // SystemUI sends confirm, HAT is sent to keystore and client is notified.
         mBiometricService.mInternalReceiver.onDialogDismissed(
-                BiometricPrompt.DISMISSED_REASON_CONFIRMED);
+                BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED);
         waitForIdle();
         verify(mBiometricService.mKeyStore).addAuthToken(any(byte[].class));
         verify(mReceiver1).onAuthenticationSucceeded();
@@ -373,7 +404,7 @@
             throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onAuthenticationFailed();
         waitForIdle();
@@ -390,7 +421,7 @@
             throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onAuthenticationFailed();
         waitForIdle();
@@ -406,13 +437,14 @@
     public void testErrorCanceled_whenAuthenticating_notifiesSystemUIAndClient() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         // Create a new pending auth session but don't start it yet. HAL contract is that previous
         // one must get ERROR_CANCELED. Simulate that here by creating the pending auth session,
         // sending ERROR_CANCELED to the current auth session, and then having the second one
         // onReadyForAuthentication.
-        invokeAuthenticate(mBiometricService.mImpl, mReceiver2, false /* requireConfirmation */);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver2, false /* requireConfirmation */,
+                false /* allowDeviceCredential */);
         waitForIdle();
 
         assertEquals(mBiometricService.mCurrentAuthSession.mState,
@@ -430,7 +462,7 @@
         verify(mReceiver2, never()).onError(anyInt(), any(String.class));
 
         // SystemUI dialog closed
-        verify(mBiometricService.mStatusBarService).hideBiometricDialog();
+        verify(mBiometricService.mStatusBarService).hideAuthenticationDialog();
 
         // After SystemUI notifies that the animation has completed
         mBiometricService.mInternalReceiver
@@ -446,7 +478,7 @@
     public void testErrorHalTimeout_whenAuthenticating_entersPausedState() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onError(
                 getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -479,7 +511,7 @@
         resetStatusBar();
         startPendingAuthSession(mBiometricService);
         waitForIdle();
-        verify(mBiometricService.mStatusBarService, never()).showBiometricDialog(
+        verify(mBiometricService.mStatusBarService, never()).showAuthenticationDialog(
                 any(Bundle.class),
                 any(IBiometricServiceReceiverInternal.class),
                 anyInt(),
@@ -492,7 +524,7 @@
     public void testErrorFromHal_whenPaused_notifiesSystemUIAndClient() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireCOnfirmation */);
+                false /* requireCOnfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onError(
                 getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -509,7 +541,7 @@
                 eq(BiometricConstants.BIOMETRIC_ERROR_CANCELED),
                 eq(ERROR_CANCELED));
         // Dialog is hidden immediately
-        verify(mBiometricService.mStatusBarService).hideBiometricDialog();
+        verify(mBiometricService.mStatusBarService).hideAuthenticationDialog();
         // Auth session is over
         assertNull(mBiometricService.mCurrentAuthSession);
     }
@@ -522,7 +554,7 @@
         // session is done.
         setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onError(
                 getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -533,9 +565,10 @@
         // Sends error to SystemUI and does not notify client yet
         assertEquals(mBiometricService.mCurrentAuthSession.mState,
                 BiometricService.STATE_ERROR_PENDING_SYSUI);
-        verify(mBiometricService.mStatusBarService)
-                .onBiometricError(eq(ERROR_UNABLE_TO_PROCESS));
-        verify(mBiometricService.mStatusBarService, never()).hideBiometricDialog();
+        verify(mBiometricService.mStatusBarService).onBiometricError(
+                eq(BiometricConstants.BIOMETRIC_ERROR_UNABLE_TO_PROCESS),
+                eq(ERROR_UNABLE_TO_PROCESS));
+        verify(mBiometricService.mStatusBarService, never()).hideAuthenticationDialog();
         verify(mReceiver1, never()).onError(anyInt(), anyString());
 
         // SystemUI animation completed, client is notified, auth session is over
@@ -549,11 +582,177 @@
     }
 
     @Test
+    public void testErrorFromHal_whilePreparingAuthentication_credentialAllowed() throws Exception {
+        setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
+                false /* requireConfirmation */, true /* allowDeviceCredential */);
+        waitForIdle();
+
+        mBiometricService.mInternalReceiver.onError(
+                getCookieForPendingSession(mBiometricService.mPendingAuthSession),
+                BiometricConstants.BIOMETRIC_ERROR_LOCKOUT,
+                ERROR_LOCKOUT);
+        waitForIdle();
+
+        // Pending auth session becomes current auth session, since device credential should
+        // be shown now.
+        assertNull(mBiometricService.mPendingAuthSession);
+        assertNotNull(mBiometricService.mCurrentAuthSession);
+        assertEquals(BiometricService.STATE_SHOWING_DEVICE_CREDENTIAL,
+                mBiometricService.mCurrentAuthSession.mState);
+        assertEquals(Authenticator.TYPE_CREDENTIAL,
+                mBiometricService.mCurrentAuthSession.mBundle.getInt(
+                        BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+        verify(mBiometricService.mStatusBarService).showAuthenticationDialog(
+                eq(mBiometricService.mCurrentAuthSession.mBundle),
+                any(IBiometricServiceReceiverInternal.class),
+                eq(0 /* biometricModality */),
+                anyBoolean() /* requireConfirmation */,
+                anyInt() /* userId */,
+                eq(TEST_PACKAGE_NAME));
+    }
+
+    @Test
+    public void testErrorFromHal_whilePreparingAuthentication_credentialNotAllowed()
+            throws Exception {
+        setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+        invokeAuthenticate(mBiometricService.mImpl, mReceiver1,
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
+        waitForIdle();
+
+        mBiometricService.mInternalReceiver.onError(
+                getCookieForPendingSession(mBiometricService.mPendingAuthSession),
+                BiometricConstants.BIOMETRIC_ERROR_LOCKOUT,
+                ERROR_LOCKOUT);
+        waitForIdle();
+
+        // Error is sent to client
+        assertNull(mBiometricService.mPendingAuthSession);
+        assertNull(mBiometricService.mCurrentAuthSession);
+    }
+
+    @Test
+    public void testCombineAuthenticatorBundle_keyAllowDeviceCredentialAlwaysRemoved() {
+        Bundle bundle;
+        int authenticators;
+
+        // In:
+        // KEY_ALLOW_DEVICE_CREDENTIAL = true
+        // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
+        // Out:
+        // KEY_ALLOW_DEVICE_CREDENTIAL = null
+        // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
+        bundle = new Bundle();
+        bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, true);
+        authenticators = Authenticator.TYPE_CREDENTIAL | Authenticator.TYPE_BIOMETRIC;
+        bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+        Utils.combineAuthenticatorBundles(bundle);
+        assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+        assertEquals(authenticators, bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+
+        // In:
+        // KEY_ALLOW_DEVICE_CREDENTIAL = true
+        // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC
+        // Out:
+        // KEY_ALLOW_DEVICE_CREDENTIAL = null
+        // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
+        bundle = new Bundle();
+        bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, true);
+        authenticators = Authenticator.TYPE_BIOMETRIC;
+        bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+        Utils.combineAuthenticatorBundles(bundle);
+        assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+        assertEquals(authenticators, bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+
+        // In:
+        // KEY_ALLOW_DEVICE_CREDENTIAL = null
+        // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
+        // Out:
+        // KEY_ALLOW_DEVICE_CREDENTIAL = null
+        // KEY_AUTHENTICATORS_ALLOWED = TYPE_BIOMETRIC | TYPE_CREDENTIAL
+        bundle = new Bundle();
+        authenticators = Authenticator.TYPE_BIOMETRIC | Authenticator.TYPE_CREDENTIAL;
+        bundle.putInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED, authenticators);
+        Utils.combineAuthenticatorBundles(bundle);
+        assertNull(bundle.get(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL));
+        assertEquals(authenticators, bundle.getInt(BiometricPrompt.KEY_AUTHENTICATORS_ALLOWED));
+    }
+
+    @Test
+    public void testErrorFromHal_whileShowingDeviceCredential_doesntNotifySystemUI()
+            throws Exception {
+        setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+        invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
+                false /* requireConfirmation */, true /* allowDeviceCredential */);
+
+        mBiometricService.mInternalReceiver.onDeviceCredentialPressed();
+        waitForIdle();
+
+        assertEquals(BiometricService.STATE_SHOWING_DEVICE_CREDENTIAL,
+                mBiometricService.mCurrentAuthSession.mState);
+        verify(mReceiver1, never()).onError(anyInt(), anyString());
+
+        mBiometricService.mInternalReceiver.onError(
+                getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
+                BiometricConstants.BIOMETRIC_ERROR_CANCELED,
+                ERROR_CANCELED);
+        waitForIdle();
+
+        assertEquals(BiometricService.STATE_SHOWING_DEVICE_CREDENTIAL,
+                mBiometricService.mCurrentAuthSession.mState);
+        verify(mReceiver1, never()).onError(anyInt(), anyString());
+    }
+
+    @Test
+    public void testLockout_whileAuthenticating_credentialAllowed() throws Exception {
+        setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+        invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
+                false /* requireConfirmation */, true /* allowDeviceCredential */);
+
+        assertEquals(BiometricService.STATE_AUTH_STARTED,
+                mBiometricService.mCurrentAuthSession.mState);
+
+        mBiometricService.mInternalReceiver.onError(
+                getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
+                BiometricConstants.BIOMETRIC_ERROR_LOCKOUT,
+                ERROR_LOCKOUT);
+        waitForIdle();
+
+        assertEquals(BiometricService.STATE_SHOWING_DEVICE_CREDENTIAL,
+                mBiometricService.mCurrentAuthSession.mState);
+        verify(mBiometricService.mStatusBarService).onBiometricError(
+                eq(BiometricConstants.BIOMETRIC_ERROR_LOCKOUT),
+                eq(ERROR_LOCKOUT));
+    }
+
+    @Test
+    public void testLockout_whenAuthenticating_credentialNotAllowed() throws Exception {
+        setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
+        invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
+
+        assertEquals(BiometricService.STATE_AUTH_STARTED,
+                mBiometricService.mCurrentAuthSession.mState);
+
+        mBiometricService.mInternalReceiver.onError(
+                getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
+                BiometricConstants.BIOMETRIC_ERROR_UNABLE_TO_PROCESS,
+                ERROR_UNABLE_TO_PROCESS);
+        waitForIdle();
+
+        assertEquals(BiometricService.STATE_ERROR_PENDING_SYSUI,
+                mBiometricService.mCurrentAuthSession.mState);
+        verify(mBiometricService.mStatusBarService).onBiometricError(
+                eq(BiometricConstants.BIOMETRIC_ERROR_UNABLE_TO_PROCESS),
+                eq(ERROR_UNABLE_TO_PROCESS));
+    }
+
+    @Test
     public void testDismissedReasonUserCancel_whileAuthenticating_cancelsHalAuthentication()
             throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver
                 .onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
@@ -575,7 +774,7 @@
     public void testDismissedReasonNegative_whilePaused_doesntInvokeHalCancel() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onError(
                 getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -598,7 +797,7 @@
     public void testDismissedReasonUserCancel_whilePaused_doesntInvokeHalCancel() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onError(
                 getCookieForCurrentSession(mBiometricService.mCurrentAuthSession),
@@ -621,7 +820,7 @@
     public void testDismissedReasonUserCancel_whenPendingConfirmation() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FACE);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                true /* requireConfirmation */);
+                true /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onAuthenticationSucceeded(
                 true /* requireConfirmation */,
@@ -648,7 +847,7 @@
     public void testAcquire_whenAuthenticating_sentToSystemUI() throws Exception {
         setupAuthForOnly(BiometricAuthenticator.TYPE_FINGERPRINT);
         invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
-                false /* requireConfirmation */);
+                false /* requireConfirmation */, false /* allowDeviceCredential */);
 
         mBiometricService.mInternalReceiver.onAcquired(
                 FingerprintManager.FINGERPRINT_ACQUIRED_IMAGER_DIRTY,
@@ -698,9 +897,10 @@
     }
 
     private void invokeAuthenticateAndStart(IBiometricService.Stub service,
-            IBiometricServiceReceiver receiver, boolean requireConfirmation) throws Exception {
+            IBiometricServiceReceiver receiver, boolean requireConfirmation,
+            boolean allowDeviceCredential) throws Exception {
         // Request auth, creates a pending session
-        invokeAuthenticate(service, receiver, requireConfirmation);
+        invokeAuthenticate(service, receiver, requireConfirmation, allowDeviceCredential);
         waitForIdle();
 
         startPendingAuthSession(mBiometricService);
@@ -720,20 +920,25 @@
     }
 
     private static void invokeAuthenticate(IBiometricService.Stub service,
-            IBiometricServiceReceiver receiver, boolean requireConfirmation) throws Exception {
+            IBiometricServiceReceiver receiver, boolean requireConfirmation,
+            boolean allowDeviceCredential) throws Exception {
         service.authenticate(
                 new Binder() /* token */,
                 0 /* sessionId */,
                 0 /* userId */,
                 receiver,
                 TEST_PACKAGE_NAME /* packageName */,
-                createTestBiometricPromptBundle(requireConfirmation),
-                null /* IBiometricConfirmDeviceCredentialCallback */);
+                createTestBiometricPromptBundle(requireConfirmation, allowDeviceCredential));
     }
 
-    private static Bundle createTestBiometricPromptBundle(boolean requireConfirmation) {
+    private static Bundle createTestBiometricPromptBundle(boolean requireConfirmation,
+            boolean allowDeviceCredential) {
         final Bundle bundle = new Bundle();
         bundle.putBoolean(BiometricPrompt.KEY_REQUIRE_CONFIRMATION, requireConfirmation);
+
+        if (allowDeviceCredential) {
+            bundle.putBoolean(BiometricPrompt.KEY_ALLOW_DEVICE_CREDENTIAL, true);
+        }
         return bundle;
     }
 
@@ -742,6 +947,11 @@
         return session.mModalitiesMatched.values().iterator().next();
     }
 
+    private static int getCookieForPendingSession(BiometricService.AuthSession session) {
+        assertEquals(session.mModalitiesWaiting.values().size(), 1);
+        return session.mModalitiesWaiting.values().iterator().next();
+    }
+
     private static void waitForIdle() {
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
     }
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index d900910..9a1fd9c 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -1212,6 +1212,45 @@
         assertTrue(dpm.isDeviceManaged());
     }
 
+    /**
+     * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
+     *
+     * Validates that when the device owner is removed, the reset password token is cleared
+     */
+    public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
+        mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
+        mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
+        mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
+
+        // Install admin1 on system user
+        setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
+
+        // Set admin1 to active admin and device owner
+        dpm.setActiveAdmin(admin1, /* replace =*/ false);
+        dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
+
+        // Add reset password token
+        final long handle = 12000;
+        final byte[] token = new byte[32];
+        when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
+                nullable(EscrowTokenStateChangeCallback.class)))
+                .thenReturn(handle);
+        assertTrue(dpm.setResetPasswordToken(admin1, token));
+
+        // Assert reset password token is active
+        when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
+                eq(UserHandle.USER_SYSTEM)))
+                .thenReturn(true);
+        assertTrue(dpm.isResetPasswordTokenActive(admin1));
+
+        // Remove the device owner
+        dpm.clearDeviceOwnerApp(admin1.getPackageName());
+
+        // Verify password reset password token was removed
+        verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
+                eq(UserHandle.USER_SYSTEM));
+    }
+
     public void testSetProfileOwner() throws Exception {
         setAsProfileOwner(admin1);
 
@@ -2611,6 +2650,21 @@
         verifyStayOnWhilePluggedCleared(false);
     }
 
+    public void testIsActiveSupervisionApp() throws Exception {
+        when(mServiceContext.resources
+                .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
+                .thenReturn(admin1.flattenToString());
+
+        final int PROFILE_USER = 15;
+        final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
+        addManagedProfile(admin1, PROFILE_ADMIN, admin1);
+        mContext.binder.callingUid = PROFILE_ADMIN;
+
+        final DevicePolicyManagerInternal dpmi =
+                LocalServices.getService(DevicePolicyManagerInternal.class);
+        assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
+    }
+
     // Test if lock timeout on managed profile is handled correctly depending on whether profile
     // uses separate challenge.
     public void testSetMaximumTimeToLockProfile() throws Exception {
diff --git a/services/tests/servicestests/src/com/android/server/display/utils/AmbientFilterTest.java b/services/tests/servicestests/src/com/android/server/display/utils/AmbientFilterTest.java
new file mode 100644
index 0000000..9b76b13
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/display/utils/AmbientFilterTest.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2019 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.display.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import android.content.ContextWrapper;
+import android.content.res.Resources;
+import android.util.TypedValue;
+
+import androidx.test.InstrumentationRegistry;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public final class AmbientFilterTest {
+    private ContextWrapper mContextSpy;
+    private Resources mResourcesSpy;
+    private static String TAG = "AmbientFilterTest";
+
+    @Before
+    public void setUp() throws Exception {
+        mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext()));
+        mResourcesSpy = spy(mContextSpy.getResources());
+        when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
+    }
+
+    @Test
+    public void testBrightnessFilter_ZeroIntercept() throws Exception {
+        final int horizon = 5 * 1000;
+        final int time_start = 30 * 1000;
+        final float intercept = 0.0f;
+        final int prediction_time = 100;  // Hardcoded in AmbientFilter: prediction of how long the
+                                          // latest prediction will last before a new prediction.
+        setMockValues(mResourcesSpy, horizon, intercept);
+        AmbientFilter filter = AmbientFilterFactory.createBrightnessFilter(TAG, mResourcesSpy);
+
+        // Add first value and verify
+        filter.addValue(time_start, 30);
+        assertEquals(30, filter.getEstimate(time_start + prediction_time), 0.001);
+
+        // Add second value and verify that they are being averaged:
+        filter.addValue(time_start + prediction_time, 40);
+        // We check immediately after the value is added to verify that the weight of the
+        // prediction time is being correctly applied to the recent value correctly.
+        // In this case (time is in seconds so 100ms = 0.1s):
+        //    weight 1 (w1) = (0.5*0.1^2 - 0.5*0^2) = 0.005
+        //    weight 2 (w2) = (0.5*0.2^2 - 0.5*0.1^2) = 0.015
+        //    w_t = w1 + w2 = 0.02
+        //    total = w1 * 30 + w2 * 40 = 0.75
+        //    estimate = total / w_t = 0.75 / 0.02 = 37.5
+        assertEquals(37.5, filter.getEstimate(time_start + prediction_time), 0.001);
+
+        // Add a third value to push the first value off of the buffer.
+        filter.addValue(time_start + horizon + prediction_time, 50);
+        assertEquals(40.38846f, filter.getEstimate(time_start + horizon + prediction_time), 0.001);
+    }
+
+    @Test
+    public void testBrightnessFilter_WithIntercept() throws Exception {
+        final int horizon = 5 * 1000;
+        final int time_start = 30 * 1000;
+        final float intercept = 10f;
+        final int prediction_time = 100;
+
+        setMockValues(mResourcesSpy, horizon, intercept);
+        AmbientFilter filter = AmbientFilterFactory.createBrightnessFilter(TAG, mResourcesSpy);
+
+        // Add first value and verify
+        filter.addValue(time_start, 30);
+        assertEquals(30, filter.getEstimate(time_start + prediction_time), 0.001);
+
+        // Add second value and verify that they are being averaged:
+        filter.addValue(time_start + prediction_time, 40);
+        // We check immediately after the value is added to verify that the weight of the
+        // prediction time is being correctly applied to the recent value correctly.
+        // In this case (time is in seconds so 100ms = 0.1s):
+        //    weight 1 (w1) = (0.5*0.1^2 + 0.1*100) - (0.5*0^2 + 0*100) = 1.005
+        //    weight 2 (w2) = (0.5*0.2^2 + 0.2*100) - (0.5*0.1^2 + 0.1*100) = 1.015
+        //    w_t = w1 + w2 = 2.02
+        //    total = w1 * 30 + w2 * 40 = 70.75
+        //    estimate = total / w_t = 70.75 / 2.02 = 35.024752475
+        assertEquals(35.02475f, filter.getEstimate(time_start + prediction_time), 0.001);
+
+        // Add a third value to push the first value off of the buffer.
+        filter.addValue(time_start + horizon + prediction_time, 50);
+        assertEquals(40.23513f, filter.getEstimate(time_start + horizon + prediction_time), 0.001);
+    }
+
+    private void setMockValues(Resources resources, int horizon, float intercept) {
+        doAnswer(invocation -> {
+            TypedValue value = (TypedValue) invocation.getArguments()[1];
+            value.type = TypedValue.TYPE_FLOAT;
+            value.data = Float.floatToRawIntBits(intercept);
+            return null;
+        }).when(mResourcesSpy).getValue(
+                eq(com.android.internal.R.dimen
+                .config_displayWhiteBalanceBrightnessFilterIntercept),
+                any(TypedValue.class), eq(true));
+        when(mResourcesSpy.getInteger(
+                com.android.internal.R.integer
+                .config_displayWhiteBalanceBrightnessFilterHorizon)).thenReturn(horizon);
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterStubber.java b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterStubber.java
new file mode 100644
index 0000000..4d25510
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterStubber.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2019 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.display.utils;
+
+public class AmbientFilterStubber extends AmbientFilter {
+    public AmbientFilterStubber() {
+        super(null, 1);
+    }
+
+    protected float filter(long time, RollingBuffer buffer) {
+        return 0f;
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterTest.java b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterTest.java
deleted file mode 100644
index 7816493..0000000
--- a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientFilterTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2019 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.display.whitebalance;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import android.content.ContextWrapper;
-import android.content.res.Resources;
-import android.util.TypedValue;
-
-import androidx.test.InstrumentationRegistry;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public final class AmbientFilterTest {
-    private ContextWrapper mContextSpy;
-    private Resources mResourcesSpy;
-
-    @Before
-    public void setUp() throws Exception {
-        mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext()));
-        mResourcesSpy = spy(mContextSpy.getResources());
-        when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
-    }
-
-    @Test
-    public void testBrightnessFilter_ZeroIntercept() throws Exception {
-        final int horizon = 5 * 1000;
-        final int time_start = 30 * 1000;
-        final float intercept = 0.0f;
-        final int prediction_time = 100;  // Hardcoded in AmbientFilter: prediction of how long the
-                                          // latest prediction will last before a new prediction.
-        setMockValues(mResourcesSpy, horizon, intercept);
-        AmbientFilter filter = DisplayWhiteBalanceFactory.createBrightnessFilter(mResourcesSpy);
-
-        // Add first value and verify
-        filter.addValue(time_start, 30);
-        assertEquals(30, filter.getEstimate(time_start + prediction_time), 0.001);
-
-        // Add second value and verify that they are being averaged:
-        filter.addValue(time_start + prediction_time, 40);
-        // We check immediately after the value is added to verify that the weight of the
-        // prediction time is being correctly applied to the recent value correctly.
-        // In this case (time is in seconds so 100ms = 0.1s):
-        //    weight 1 (w1) = (0.5*0.1^2 - 0.5*0^2) = 0.005
-        //    weight 2 (w2) = (0.5*0.2^2 - 0.5*0.1^2) = 0.015
-        //    w_t = w1 + w2 = 0.02
-        //    total = w1 * 30 + w2 * 40 = 0.75
-        //    estimate = total / w_t = 0.75 / 0.02 = 37.5
-        assertEquals(37.5, filter.getEstimate(time_start + prediction_time), 0.001);
-
-        // Add a third value to push the first value off of the buffer.
-        filter.addValue(time_start + horizon + prediction_time, 50);
-        assertEquals(40.38846f, filter.getEstimate(time_start + horizon + prediction_time), 0.001);
-    }
-
-    @Test
-    public void testBrightnessFilter_WithIntercept() throws Exception {
-        final int horizon = 5 * 1000;
-        final int time_start = 30 * 1000;
-        final float intercept = 10f;
-        final int prediction_time = 100;
-
-        setMockValues(mResourcesSpy, horizon, intercept);
-        AmbientFilter filter = DisplayWhiteBalanceFactory.createBrightnessFilter(mResourcesSpy);
-
-        // Add first value and verify
-        filter.addValue(time_start, 30);
-        assertEquals(30, filter.getEstimate(time_start + prediction_time), 0.001);
-
-        // Add second value and verify that they are being averaged:
-        filter.addValue(time_start + prediction_time, 40);
-        // We check immediately after the value is added to verify that the weight of the
-        // prediction time is being correctly applied to the recent value correctly.
-        // In this case (time is in seconds so 100ms = 0.1s):
-        //    weight 1 (w1) = (0.5*0.1^2 + 0.1*100) - (0.5*0^2 + 0*100) = 1.005
-        //    weight 2 (w2) = (0.5*0.2^2 + 0.2*100) - (0.5*0.1^2 + 0.1*100) = 1.015
-        //    w_t = w1 + w2 = 2.02
-        //    total = w1 * 30 + w2 * 40 = 70.75
-        //    estimate = total / w_t = 70.75 / 2.02 = 35.024752475
-        assertEquals(35.02475f, filter.getEstimate(time_start + prediction_time), 0.001);
-
-        // Add a third value to push the first value off of the buffer.
-        filter.addValue(time_start + horizon + prediction_time, 50);
-        assertEquals(40.23513f, filter.getEstimate(time_start + horizon + prediction_time), 0.001);
-    }
-
-    private void setMockValues(Resources resources, int horizon, float intercept) {
-        doAnswer(invocation -> {
-            TypedValue value = (TypedValue) invocation.getArguments()[1];
-            value.type = TypedValue.TYPE_FLOAT;
-            value.data = Float.floatToRawIntBits(intercept);
-            return null;
-        }).when(mResourcesSpy).getValue(
-                eq(com.android.internal.R.dimen
-                .config_displayWhiteBalanceBrightnessFilterIntercept),
-                any(TypedValue.class), eq(true));
-        when(mResourcesSpy.getInteger(
-                com.android.internal.R.integer
-                .config_displayWhiteBalanceBrightnessFilterHorizon)).thenReturn(horizon);
-    }
-}
diff --git a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
index 6b0798b..acf2d0e 100644
--- a/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/whitebalance/AmbientLuxTest.java
@@ -17,6 +17,8 @@
 package com.android.server.display.whitebalance;
 
 import com.android.internal.R;
+import com.android.server.display.utils.AmbientFilter;
+import com.android.server.display.utils.AmbientFilterStubber;
 import com.google.common.collect.ImmutableList;
 
 import static org.junit.Assert.assertEquals;
@@ -76,6 +78,8 @@
     @Mock private TypedArray mBiases;
     @Mock private TypedArray mHighLightBrightnesses;
     @Mock private TypedArray mHighLightBiases;
+    @Mock private TypedArray mAmbientColorTemperatures;
+    @Mock private TypedArray mDisplayColorTemperatures;
 
     @Before
     public void setUp() throws Exception {
@@ -103,10 +107,10 @@
                 HIGH_LIGHT_AMBIENT_COLOR_TEMPERATURE);
         when(mResourcesSpy.obtainTypedArray(
                 R.array.config_displayWhiteBalanceAmbientColorTemperatures))
-                .thenReturn(createTypedArray());
+                .thenReturn(mAmbientColorTemperatures);
         when(mResourcesSpy.obtainTypedArray(
                 R.array.config_displayWhiteBalanceDisplayColorTemperatures))
-                .thenReturn(createTypedArray());
+                .thenReturn(mDisplayColorTemperatures);
 
         when(mResourcesSpy.obtainTypedArray(
                 R.array.config_displayWhiteBalanceLowLightAmbientBrightnesses))
@@ -132,7 +136,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 8000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
             setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -152,7 +156,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 8000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
             setEstimatedBrightnessAndUpdate(controller,
@@ -184,7 +188,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 8000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
             float luxOverride = mix(brightness0, brightness1, t);
@@ -221,7 +225,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 8000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         setEstimatedBrightnessAndUpdate(controller, 0.0f);
         assertEquals(controller.mPendingAmbientColorTemperature,
@@ -240,7 +244,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 8000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
         setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -258,7 +262,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 8000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
         setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -278,7 +282,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 8000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
             setEstimatedBrightnessAndUpdate(controller,
@@ -311,7 +315,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = 6000.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
             float luxOverride = mix(brightness0, brightness1, t);
@@ -350,7 +354,7 @@
                     DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
             final float ambientColorTemperature = 8000.0f;
             setEstimatedColorTemperature(controller, ambientColorTemperature);
-            controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+            controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
             for (float luxOverride = 0.1f; luxOverride <= 10000; luxOverride *= 10) {
                 setEstimatedBrightnessAndUpdate(controller, luxOverride);
@@ -370,7 +374,7 @@
                 DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
         final float ambientColorTemperature = -1.0f;
         setEstimatedColorTemperature(controller, ambientColorTemperature);
-        controller.mBrightnessFilter = spy(controller.mBrightnessFilter);
+        controller.mBrightnessFilter = spy(new AmbientFilterStubber());
 
         for (float t = 0.0f; t <= 1.0f; t += 0.1f) {
             setEstimatedBrightnessAndUpdate(controller,
@@ -386,6 +390,16 @@
         assertEquals(controller.mPendingAmbientColorTemperature, ambientColorTemperature, 0.001);
     }
 
+    @Test
+    public void testWhiteBalance_updateWithEmptyFilter() throws Exception {
+        setAmbientColorTemperatures(5300.0f, 6000.0f, 7000.0f, 8000.0f);
+        setDisplayColorTemperatures(6300.0f, 6400.0f, 6850.0f, 7450.0f);
+        DisplayWhiteBalanceController controller =
+                DisplayWhiteBalanceFactory.create(mHandler, mSensorManagerMock, mResourcesSpy);
+        controller.updateAmbientColorTemperature();
+        assertEquals(-1.0f, controller.mPendingAmbientColorTemperature, 0);
+    }
+
     void mockThrottler() {
         when(mResourcesSpy.getInteger(
                 R.integer.config_displayWhiteBalanceDecreaseDebounce)).thenReturn(0);
@@ -426,7 +440,7 @@
 
     private void setEstimatedColorTemperature(DisplayWhiteBalanceController controller,
                                               float ambientColorTemperature) {
-        AmbientFilter colorTemperatureFilter = spy(controller.mColorTemperatureFilter);
+        AmbientFilter colorTemperatureFilter = spy(new AmbientFilterStubber());
         controller.mColorTemperatureFilter = colorTemperatureFilter;
         when(colorTemperatureFilter.getEstimate(anyLong())).thenReturn(ambientColorTemperature);
     }
@@ -453,6 +467,14 @@
         setFloatArrayResource(mHighLightBiases, vals);
     }
 
+    private void setAmbientColorTemperatures(float... vals) {
+        setFloatArrayResource(mAmbientColorTemperatures, vals);
+    }
+
+    private void setDisplayColorTemperatures(float... vals) {
+        setFloatArrayResource(mDisplayColorTemperatures, vals);
+    }
+
     private void setFloatArrayResource(TypedArray array, float[] vals) {
         when(array.length()).thenReturn(vals.length);
         for (int i = 0; i < vals.length; i++) {
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/ArcTerminationActionFromAvrTest.java b/services/tests/servicestests/src/com/android/server/hdmi/ArcTerminationActionFromAvrTest.java
index 11bd29d..ad3e040 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/ArcTerminationActionFromAvrTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/ArcTerminationActionFromAvrTest.java
@@ -28,6 +28,7 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.JUnit4;
@@ -114,6 +115,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void testSendMessage_notSuccess() {
         mSendCecCommandSuccess = false;
         mShouldDispatchReportArcTerminated = false;
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
index a89198a..0a1899b 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
@@ -232,6 +232,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleGiveSystemAudioModeStatus_originalOff() throws Exception {
         HdmiCecMessage expectedMessage =
                 HdmiCecMessageBuilder.buildReportSystemAudioMode(
@@ -301,6 +302,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleSetSystemAudioMode_setOn_orignalOff() throws Exception {
         mMusicMute = true;
         HdmiCecMessage messageSet =
@@ -328,6 +330,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleSystemAudioModeRequest_turnOffByTv() throws Exception {
         assertThat(mMusicMute).isFalse();
         // Check if feature correctly turned off
@@ -497,6 +500,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleRequestArcTerminate_arcIsNotOn() throws Exception {
         assertThat(mHdmiCecLocalDeviceAudioSystem.isArcEnabled()).isFalse();
         HdmiCecMessage message =
@@ -671,6 +675,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleReportPhysicalAddress_differentPath_addDevice() {
         assertThat(mInvokeDeviceEventState).isNotEqualTo(DEVICE_EVENT_ADD_DEVICE);
         HdmiDeviceInfo oldDevice = new HdmiDeviceInfo(
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
index b8799c3..0062a17 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
@@ -99,6 +99,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleSetSystemAudioModeOn_audioSystemBroadcast() {
         mHdmiControlService.setSystemAudioActivated(false);
         assertThat(mHdmiCecLocalDevicePlayback.mService.isSystemAudioActivated()).isFalse();
@@ -110,6 +111,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleSetSystemAudioModeOff_audioSystemToPlayback() {
         mHdmiCecLocalDevicePlayback.mService.setSystemAudioActivated(true);
         assertThat(mHdmiCecLocalDevicePlayback.mService.isSystemAudioActivated()).isTrue();
@@ -123,6 +125,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void handleSystemAudioModeStatusOn_DirectltToLocalDeviceFromAudioSystem() {
         mHdmiControlService.setSystemAudioActivated(false);
         assertThat(mHdmiCecLocalDevicePlayback.mService.isSystemAudioActivated()).isFalse();
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiControlServiceBinderAPITest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiControlServiceBinderAPITest.java
new file mode 100644
index 0000000..c6cf9b1
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiControlServiceBinderAPITest.java
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2019 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.hdmi;
+
+import static android.os.SystemClock.sleep;
+import static com.android.server.hdmi.HdmiControlService.INITIATED_BY_ENABLE_CEC;
+import static com.google.common.truth.Truth.assertThat;
+import static junit.framework.Assert.assertEquals;
+
+import android.hardware.hdmi.HdmiControlManager;
+import android.hardware.hdmi.HdmiPortInfo;
+import android.hardware.hdmi.IHdmiControlCallback;
+import android.os.Looper;
+import android.os.SystemProperties;
+import android.os.test.TestLooper;
+import android.util.Slog;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+
+import java.util.ArrayList;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * Tests for {@link HdmiControlServiceBinderAPITest} class.
+ */
+@SmallTest
+@RunWith(JUnit4.class)
+public class HdmiControlServiceBinderAPITest {
+
+    private class HdmiCecLocalDeviceMyDevice extends HdmiCecLocalDevice {
+
+        private boolean mCanGoToStandby;
+        private boolean mIsStandby;
+        private boolean mIsDisabled;
+
+        protected HdmiCecLocalDeviceMyDevice(HdmiControlService service, int deviceType) {
+            super(service, deviceType);
+        }
+
+        @Override
+        protected void onAddressAllocated(int logicalAddress, int reason) {
+        }
+
+        @Override
+        protected int getPreferredAddress() {
+            return 0;
+        }
+
+        @Override
+        protected void setPreferredAddress(int addr) {
+        }
+
+        @Override
+        protected boolean canGoToStandby() {
+            return mCanGoToStandby;
+        }
+
+        @Override
+        protected void disableDevice(
+            boolean initiatedByCec, final PendingActionClearedCallback originalCallback) {
+            mIsDisabled = true;
+            originalCallback.onCleared(this);
+        }
+
+        @Override
+        protected void onStandby(boolean initiatedByCec, int standbyAction) {
+            mIsStandby = true;
+        }
+
+        protected boolean isStandby() {
+            return mIsStandby;
+        }
+
+        protected boolean isDisabled() {
+            return mIsDisabled;
+        }
+
+        protected void setCanGoToStandby(boolean canGoToStandby) {
+            mCanGoToStandby = canGoToStandby;
+        }
+    }
+
+    private static final String TAG = "HdmiControlServiceBinderAPITest";
+    private HdmiControlService mHdmiControlService;
+    private HdmiCecController mHdmiCecController;
+    private HdmiCecLocalDevicePlayback mPlaybackDevice;
+    private FakeNativeWrapper mNativeWrapper;
+    private Looper mMyLooper;
+    private TestLooper mTestLooper = new TestLooper();
+    private ArrayList<HdmiCecLocalDevice> mLocalDevices = new ArrayList<>();
+    private HdmiPortInfo[] mHdmiPortInfo;
+    private int mResult;
+    private int mPowerStatus;
+
+    @Before
+    public void SetUp() {
+        mHdmiControlService =
+            new HdmiControlService(InstrumentationRegistry.getTargetContext()) {
+                @Override
+                void sendCecCommand(HdmiCecMessage command) {
+                    switch (command.getOpcode()) {
+                        case Constants.MESSAGE_GIVE_DEVICE_POWER_STATUS:
+                            HdmiCecMessage message =
+                                HdmiCecMessageBuilder.buildReportPowerStatus(
+                                    Constants.ADDR_TV,
+                                    Constants.ADDR_PLAYBACK_1,
+                                    HdmiControlManager.POWER_STATUS_ON);
+                            handleCecCommand(message);
+                            break;
+                        default:
+                            return;
+                    }
+                }
+
+                @Override
+                boolean isPowerStandby() {
+                    return mPowerStatus == HdmiControlManager.POWER_STATUS_STANDBY;
+                }
+            };
+        mMyLooper = mTestLooper.getLooper();
+
+        mPlaybackDevice = new HdmiCecLocalDevicePlayback(mHdmiControlService) {
+            @Override
+            void setIsActiveSource(boolean on) {
+                mIsActiveSource = on;
+            }
+
+            @Override
+            protected void wakeUpIfActiveSource() {}
+
+            @Override
+            protected void setPreferredAddress(int addr) {}
+
+            @Override
+            protected int getPreferredAddress() {
+                return Constants.ADDR_PLAYBACK_1;
+            }
+        };
+        mPlaybackDevice.init();
+
+        mHdmiControlService.setIoLooper(mMyLooper);
+
+        mNativeWrapper = new FakeNativeWrapper();
+        mHdmiCecController =
+            HdmiCecController.createWithNativeWrapper(mHdmiControlService, mNativeWrapper);
+        mHdmiControlService.setCecController(mHdmiCecController);
+        mHdmiControlService.setHdmiMhlController(HdmiMhlControllerStub.create(mHdmiControlService));
+        mHdmiControlService.setMessageValidator(new HdmiCecMessageValidator(mHdmiControlService));
+
+        mLocalDevices.add(mPlaybackDevice);
+        mHdmiPortInfo = new HdmiPortInfo[1];
+        mHdmiPortInfo[0] =
+            new HdmiPortInfo(1, HdmiPortInfo.PORT_INPUT, 0x2100, true, false, false);
+        mNativeWrapper.setPortInfo(mHdmiPortInfo);
+        mHdmiControlService.initPortInfo();
+        mResult = -1;
+        mPowerStatus = HdmiControlManager.POWER_STATUS_ON;
+
+        mTestLooper.dispatchAll();
+    }
+
+    @Test
+    public void oneTouchPlay_addressNotAllocated() {
+        assertThat(mHdmiControlService.isAddressAllocated()).isFalse();
+        mHdmiControlService.oneTouchPlay(new IHdmiControlCallback.Stub() {
+            @Override
+            public void onComplete(int result) {
+                mResult = result;
+            }
+        });
+        assertEquals(mResult, -1);
+        assertThat(mPlaybackDevice.mIsActiveSource).isFalse();
+
+        mHdmiControlService.allocateLogicalAddress(mLocalDevices, INITIATED_BY_ENABLE_CEC);
+        mTestLooper.dispatchAll();
+        assertThat(mHdmiControlService.isAddressAllocated()).isTrue();
+        assertEquals(mResult, HdmiControlManager.RESULT_SUCCESS);
+        assertThat(mPlaybackDevice.mIsActiveSource).isTrue();
+    }
+
+    @Test
+    public void oneTouchPlay_addressAllocated() {
+        mHdmiControlService.allocateLogicalAddress(mLocalDevices, INITIATED_BY_ENABLE_CEC);
+        mTestLooper.dispatchAll();
+        assertThat(mHdmiControlService.isAddressAllocated()).isTrue();
+        mHdmiControlService.oneTouchPlay(new IHdmiControlCallback.Stub() {
+            @Override
+            public void onComplete(int result) {
+                mResult = result;
+            }
+        });
+        assertEquals(mResult, HdmiControlManager.RESULT_SUCCESS);
+        assertThat(mPlaybackDevice.mIsActiveSource).isTrue();
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/SystemAudioInitiationActionFromAvrTest.java b/services/tests/servicestests/src/com/android/server/hdmi/SystemAudioInitiationActionFromAvrTest.java
index 440a49a..6dcff35 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/SystemAudioInitiationActionFromAvrTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/SystemAudioInitiationActionFromAvrTest.java
@@ -221,6 +221,7 @@
     }
 
     @Test
+    @Ignore("b/120845532")
     public void testTvSupport() {
         resetTestVariables();
         mShouldDispatchActiveSource = true;
diff --git a/services/tests/servicestests/src/com/android/server/integrity/model/AtomicFormulaTest.java b/services/tests/servicestests/src/com/android/server/integrity/model/AtomicFormulaTest.java
new file mode 100644
index 0000000..1cb2fb3
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/integrity/model/AtomicFormulaTest.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+import static com.android.server.testutils.TestUtils.assertExpectException;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class AtomicFormulaTest {
+
+    @Test
+    public void testValidAtomicFormula_stringValue() {
+        AtomicFormula atomicFormula = new AtomicFormula(AtomicFormula.Key.PACKAGE_NAME,
+                AtomicFormula.Operator.EQ, "com.test.app");
+
+        assertEquals(AtomicFormula.Key.PACKAGE_NAME, atomicFormula.getKey());
+        assertEquals(AtomicFormula.Operator.EQ, atomicFormula.getOperator());
+        assertEquals("com.test.app", atomicFormula.getStringValue());
+    }
+
+    @Test
+    public void testValidAtomicFormula_intValue() {
+        AtomicFormula atomicFormula = new AtomicFormula(AtomicFormula.Key.VERSION_CODE,
+                AtomicFormula.Operator.LE, 1);
+
+        assertEquals(AtomicFormula.Key.VERSION_CODE, atomicFormula.getKey());
+        assertEquals(AtomicFormula.Operator.LE, atomicFormula.getOperator());
+        assertEquals(1, atomicFormula.getIntValue().intValue());
+    }
+
+    @Test
+    public void testValidAtomicFormula_boolValue() {
+        AtomicFormula atomicFormula = new AtomicFormula(AtomicFormula.Key.PRE_INSTALLED,
+                AtomicFormula.Operator.EQ, true);
+
+        assertEquals(AtomicFormula.Key.PRE_INSTALLED, atomicFormula.getKey());
+        assertEquals(AtomicFormula.Operator.EQ, atomicFormula.getOperator());
+        assertEquals(true, atomicFormula.getBoolValue());
+    }
+
+    @Test
+    public void testInvalidAtomicFormula_stringValue() {
+        assertExpectException(
+                IllegalArgumentException.class,
+                /* expectedExceptionMessageRegex */
+                String.format("Key %s cannot have string value", AtomicFormula.Key.VERSION_CODE),
+                () -> new AtomicFormula(AtomicFormula.Key.VERSION_CODE, AtomicFormula.Operator.EQ,
+                        "test-value"));
+    }
+
+    @Test
+    public void testInvalidAtomicFormula_intValue() {
+        assertExpectException(
+                IllegalArgumentException.class,
+                /* expectedExceptionMessageRegex */
+                String.format("Key %s cannot have integer value", AtomicFormula.Key.PACKAGE_NAME),
+                () -> new AtomicFormula(AtomicFormula.Key.PACKAGE_NAME, AtomicFormula.Operator.EQ,
+                        1));
+    }
+
+    @Test
+    public void testInvalidAtomicFormula_boolValue() {
+        assertExpectException(
+                IllegalArgumentException.class,
+                /* expectedExceptionMessageRegex */
+                String.format("Key %s cannot have boolean value", AtomicFormula.Key.PACKAGE_NAME),
+                () -> new AtomicFormula(AtomicFormula.Key.PACKAGE_NAME, AtomicFormula.Operator.EQ,
+                        true));
+    }
+
+    @Test
+    public void testValidateOperator_invalidKeyOperatorPair() {
+        assertExpectException(
+                IllegalArgumentException.class,
+                /* expectedExceptionMessageRegex */
+                String.format("Invalid operator %s used for key %s",
+                        AtomicFormula.Operator.LE, AtomicFormula.Key.PACKAGE_NAME),
+                () -> new AtomicFormula(AtomicFormula.Key.PACKAGE_NAME, AtomicFormula.Operator.LE,
+                        "test-value"));
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/integrity/model/OpenFormulaTest.java b/services/tests/servicestests/src/com/android/server/integrity/model/OpenFormulaTest.java
new file mode 100644
index 0000000..2133a7d
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/integrity/model/OpenFormulaTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+import static com.android.server.testutils.TestUtils.assertExpectException;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+@RunWith(JUnit4.class)
+public class OpenFormulaTest {
+
+    private static final AtomicFormula ATOMIC_FORMULA_1 = new AtomicFormula(
+            AtomicFormula.Key.PACKAGE_NAME, AtomicFormula.Operator.EQ, "test1");
+    private static final AtomicFormula ATOMIC_FORMULA_2 = new AtomicFormula(
+            AtomicFormula.Key.VERSION_CODE, AtomicFormula.Operator.EQ, 1);
+
+    @Test
+    public void testValidOpenFormula() {
+        OpenFormula openFormula = new OpenFormula(OpenFormula.Connector.AND,
+                Arrays.asList(ATOMIC_FORMULA_1, ATOMIC_FORMULA_2));
+
+        assertEquals(OpenFormula.Connector.AND, openFormula.getConnector());
+        assertEquals(Arrays.asList(ATOMIC_FORMULA_1, ATOMIC_FORMULA_2), openFormula.getFormulas());
+    }
+
+    @Test
+    public void testValidateAuxiliaryFormula_binaryConnectors() {
+        assertExpectException(
+                IllegalArgumentException.class,
+                /* expectedExceptionMessageRegex */
+                String.format("Connector %s must have at least 2 formulas",
+                        OpenFormula.Connector.AND),
+                () -> new OpenFormula(OpenFormula.Connector.AND,
+                        Collections.singletonList(ATOMIC_FORMULA_1)));
+    }
+
+    @Test
+    public void testValidateAuxiliaryFormula_unaryConnectors() {
+        assertExpectException(
+                IllegalArgumentException.class,
+                /* expectedExceptionMessageRegex */
+                String.format("Connector %s must have 1 formula only", OpenFormula.Connector.NOT),
+                () -> new OpenFormula(OpenFormula.Connector.NOT,
+                        Arrays.asList(ATOMIC_FORMULA_1, ATOMIC_FORMULA_2)));
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/integrity/model/RuleTest.java b/services/tests/servicestests/src/com/android/server/integrity/model/RuleTest.java
new file mode 100644
index 0000000..cf001be
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/integrity/model/RuleTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 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.integrity.model;
+
+import static com.android.server.testutils.TestUtils.assertExpectException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class RuleTest {
+
+    private static final Rule.Effect DENY_EFFECT = Rule.Effect.DENY;
+    private static final Formula SIMPLE_FORMULA =
+            new AtomicFormula(AtomicFormula.Key.PACKAGE_NAME, AtomicFormula.Operator.EQ,
+                    "com.test.app");
+
+    @Test
+    public void testEmptyRule() {
+        Rule emptyRule = Rule.EMPTY;
+
+        assertNull(emptyRule.getFormula());
+        assertNull(emptyRule.getEffect());
+    }
+
+    @Test
+    public void testValidRule() {
+        Rule validRule = new Rule(SIMPLE_FORMULA, DENY_EFFECT);
+
+        assertEquals(SIMPLE_FORMULA, validRule.getFormula());
+        assertEquals(DENY_EFFECT, validRule.getEffect());
+    }
+
+    @Test
+    public void testInvalidRule_invalidEffect() {
+        assertExpectException(
+                NullPointerException.class,
+                /* expectedExceptionMessageRegex */ null,
+                () -> new Rule(SIMPLE_FORMULA, null));
+    }
+
+    @Test
+    public void testInvalidRule_invalidFormula() {
+        assertExpectException(
+                NullPointerException.class,
+                /* expectedExceptionMessageRegex */ null,
+                () -> new Rule(null, DENY_EFFECT));
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
index 1f5ebe4..f9ac022 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
@@ -29,14 +29,19 @@
 import android.app.NotificationManager;
 import android.app.admin.DevicePolicyManager;
 import android.app.admin.DevicePolicyManagerInternal;
+import android.app.admin.DeviceStateCache;
 import android.app.trust.TrustManager;
 import android.content.ComponentName;
+import android.content.pm.PackageManager;
 import android.content.pm.UserInfo;
 import android.hardware.authsecret.V1_0.IAuthSecret;
+import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.FingerprintManager;
 import android.os.FileUtils;
 import android.os.IProgressListener;
 import android.os.RemoteException;
 import android.os.UserManager;
+import android.os.UserManagerInternal;
 import android.os.storage.IStorageManager;
 import android.os.storage.StorageManager;
 import android.security.KeyStore;
@@ -91,6 +96,11 @@
     FakeGsiService mGsiService;
     PasswordSlotManagerTestable mPasswordSlotManager;
     RecoverableKeyStoreManager mRecoverableKeyStoreManager;
+    UserManagerInternal mUserManagerInternal;
+    DeviceStateCache mDeviceStateCache;
+    FingerprintManager mFingerprintManager;
+    FaceManager mFaceManager;
+    PackageManager mPackageManager;
     protected boolean mHasSecureLockScreen;
 
     @Override
@@ -108,6 +118,11 @@
         mGsiService = new FakeGsiService();
         mPasswordSlotManager = new PasswordSlotManagerTestable();
         mRecoverableKeyStoreManager = mock(RecoverableKeyStoreManager.class);
+        mUserManagerInternal = mock(UserManagerInternal.class);
+        mDeviceStateCache = mock(DeviceStateCache.class);
+        mFingerprintManager = mock(FingerprintManager.class);
+        mFaceManager = mock(FaceManager.class);
+        mPackageManager = mock(PackageManager.class);
 
         LocalServices.removeServiceForTest(LockSettingsInternal.class);
         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
@@ -117,7 +132,7 @@
 
         mContext = new MockLockSettingsContext(getContext(), mUserManager, mNotificationManager,
                 mDevicePolicyManager, mock(StorageManager.class), mock(TrustManager.class),
-                mock(KeyguardManager.class));
+                mock(KeyguardManager.class), mFingerprintManager, mFaceManager, mPackageManager);
         mStorage = new LockSettingsStorageTestable(mContext,
                 new File(getContext().getFilesDir(), "locksettings"));
         File storageDir = mStorage.mStorageDir;
@@ -144,7 +159,8 @@
         mAuthSecretService = mock(IAuthSecret.class);
         mService = new LockSettingsServiceTestable(mContext, mLockPatternUtils, mStorage,
                 mGateKeeperService, mKeyStore, setUpStorageManagerMock(), mActivityManager,
-                mSpManager, mAuthSecretService, mGsiService, mRecoverableKeyStoreManager);
+                mSpManager, mAuthSecretService, mGsiService, mRecoverableKeyStoreManager,
+                mUserManagerInternal, mDeviceStateCache);
         when(mUserManager.getUserInfo(eq(PRIMARY_USER_ID))).thenReturn(PRIMARY_USER_INFO);
         mPrimaryUserProfiles.add(PRIMARY_USER_INFO);
         installChildProfile(MANAGED_PROFILE_USER_ID);
@@ -172,6 +188,11 @@
         // Adding a fake Device Owner app which will enable escrow token support in LSS.
         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(
                 new ComponentName("com.dummy.package", ".FakeDeviceOwner"));
+        when(mUserManagerInternal.isDeviceManaged()).thenReturn(true);
+        when(mDeviceStateCache.isDeviceProvisioned()).thenReturn(true);
+        mockBiometricsHardwareFingerprintsAndTemplates(PRIMARY_USER_ID);
+        mockBiometricsHardwareFingerprintsAndTemplates(MANAGED_PROFILE_USER_ID);
+
         mLocalService = LocalServices.getService(LockSettingsInternal.class);
     }
 
@@ -184,6 +205,7 @@
         when(mUserManager.getProfileParent(eq(profileId))).thenReturn(PRIMARY_USER_INFO);
         when(mUserManager.isUserRunning(eq(profileId))).thenReturn(true);
         when(mUserManager.isUserUnlocked(eq(profileId))).thenReturn(true);
+        when(mUserManagerInternal.isUserManaged(eq(profileId))).thenReturn(true);
         return userInfo;
     }
 
@@ -222,6 +244,18 @@
         return sm;
     }
 
+    private void mockBiometricsHardwareFingerprintsAndTemplates(int userId) {
+        // Hardware must be detected and fingerprints must be enrolled
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)).thenReturn(true);
+        when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
+        when(mFingerprintManager.hasEnrolledFingerprints(userId)).thenReturn(true);
+
+        // Hardware must be detected and templates must be enrolled
+        when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE)).thenReturn(true);
+        when(mFaceManager.isHardwareDetected()).thenReturn(true);
+        when(mFaceManager.hasEnrolledTemplates(userId)).thenReturn(true);
+    }
+
     @Override
     protected void tearDown() throws Exception {
         super.tearDown();
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
index 5c67d04..fcd98e0 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
@@ -19,17 +19,19 @@
 import static org.mockito.Mockito.mock;
 
 import android.app.IActivityManager;
+import android.app.admin.DeviceStateCache;
 import android.content.Context;
 import android.hardware.authsecret.V1_0.IAuthSecret;
 import android.os.Handler;
-import android.os.Looper;
 import android.os.Process;
 import android.os.RemoteException;
+import android.os.UserManagerInternal;
 import android.os.storage.IStorageManager;
 import android.security.KeyStore;
 import android.security.keystore.KeyPermanentlyInvalidatedException;
 
 import com.android.internal.widget.LockPatternUtils;
+import com.android.server.ServiceThread;
 import com.android.server.locksettings.recoverablekeystore.RecoverableKeyStoreManager;
 
 import java.io.FileNotFoundException;
@@ -44,15 +46,16 @@
         private LockPatternUtils mLockPatternUtils;
         private IStorageManager mStorageManager;
         private SyntheticPasswordManager mSpManager;
-        private IAuthSecret mAuthSecretService;
         private FakeGsiService mGsiService;
         private RecoverableKeyStoreManager mRecoverableKeyStoreManager;
+        private UserManagerInternal mUserManagerInternal;
+        private DeviceStateCache mDeviceStateCache;
 
         public MockInjector(Context context, LockSettingsStorage storage, KeyStore keyStore,
                 IActivityManager activityManager, LockPatternUtils lockPatternUtils,
                 IStorageManager storageManager, SyntheticPasswordManager spManager,
-                IAuthSecret authSecretService, FakeGsiService gsiService,
-                RecoverableKeyStoreManager recoverableKeyStoreManager) {
+                FakeGsiService gsiService, RecoverableKeyStoreManager recoverableKeyStoreManager,
+                UserManagerInternal userManagerInternal, DeviceStateCache deviceStateCache) {
             super(context);
             mLockSettingsStorage = storage;
             mKeyStore = keyStore;
@@ -62,11 +65,13 @@
             mSpManager = spManager;
             mGsiService = gsiService;
             mRecoverableKeyStoreManager = recoverableKeyStoreManager;
+            mUserManagerInternal = userManagerInternal;
+            mDeviceStateCache = deviceStateCache;
         }
 
         @Override
-        public Handler getHandler() {
-            return new Handler(Looper.getMainLooper());
+        public Handler getHandler(ServiceThread handlerThread) {
+            return new Handler(handlerThread.getLooper());
         }
 
         @Override
@@ -93,6 +98,10 @@
         public LockPatternUtils getLockPatternUtils() {
             return mLockPatternUtils;
         }
+        @Override
+        public DeviceStateCache getDeviceStateCache() {
+            return mDeviceStateCache;
+        }
 
         @Override
         public KeyStore getKeyStore() {
@@ -110,6 +119,11 @@
         }
 
         @Override
+        public UserManagerInternal getUserManagerInternal() {
+            return mUserManagerInternal;
+        }
+
+        @Override
         public boolean hasEnrolledBiometrics(int userId) {
             return false;
         }
@@ -134,10 +148,11 @@
             LockSettingsStorage storage, FakeGateKeeperService gatekeeper, KeyStore keystore,
             IStorageManager storageManager, IActivityManager mActivityManager,
             SyntheticPasswordManager spManager, IAuthSecret authSecretService,
-            FakeGsiService gsiService, RecoverableKeyStoreManager recoverableKeyStoreManager) {
+            FakeGsiService gsiService, RecoverableKeyStoreManager recoverableKeyStoreManager,
+            UserManagerInternal userManagerInternal, DeviceStateCache deviceStateCache) {
         super(new MockInjector(context, storage, keystore, mActivityManager, lockPatternUtils,
-                storageManager, spManager, authSecretService, gsiService,
-                recoverableKeyStoreManager));
+                storageManager, spManager, gsiService,
+                recoverableKeyStoreManager, userManagerInternal, deviceStateCache));
         mGateKeeperService = gatekeeper;
         mAuthSecretService = authSecretService;
     }
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
index 7354ad4..5818133 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
@@ -330,6 +330,27 @@
                 .lockScreenSecretChanged(CREDENTIAL_TYPE_NONE, null, MANAGED_PROFILE_USER_ID);
     }
 
+    public void testSetLockCredential_nullCredential_removeBiometrics() throws RemoteException {
+        final String oldCredential = "oldPassword";
+
+        initializeStorageWithCredential(
+                PRIMARY_USER_ID,
+                oldCredential,
+                CREDENTIAL_TYPE_PATTERN,
+                PASSWORD_QUALITY_SOMETHING);
+        mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
+
+        mService.setLockCredential(null, CREDENTIAL_TYPE_NONE, oldCredential.getBytes(),
+                PASSWORD_QUALITY_UNSPECIFIED, PRIMARY_USER_ID, false);
+
+        // Verify fingerprint is removed
+        verify(mFingerprintManager).remove(any(), eq(PRIMARY_USER_ID), any());
+        verify(mFaceManager).remove(any(), eq(PRIMARY_USER_ID), any());
+
+        verify(mFingerprintManager).remove(any(), eq(MANAGED_PROFILE_USER_ID), any());
+        verify(mFaceManager).remove(any(), eq(MANAGED_PROFILE_USER_ID), any());
+    }
+
     public void testSetLockCredential_forUnifiedToSeparateChallengeProfile_sendsNewCredentials()
             throws Exception {
         final String parentPassword = "parentPassword";
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsStorageTests.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsStorageTests.java
index 8e0d7be..2a169b7 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsStorageTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsStorageTests.java
@@ -24,8 +24,11 @@
 import android.app.NotificationManager;
 import android.app.admin.DevicePolicyManager;
 import android.app.trust.TrustManager;
+import android.content.pm.PackageManager;
 import android.content.pm.UserInfo;
 import android.database.sqlite.SQLiteDatabase;
+import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.FingerprintManager;
 import android.os.FileUtils;
 import android.os.SystemClock;
 import android.os.UserManager;
@@ -86,7 +89,9 @@
 
         MockLockSettingsContext context = new MockLockSettingsContext(getContext(), mockUserManager,
                 mock(NotificationManager.class), mock(DevicePolicyManager.class),
-                mock(StorageManager.class), mock(TrustManager.class), mock(KeyguardManager.class));
+                mock(StorageManager.class), mock(TrustManager.class), mock(KeyguardManager.class),
+                mock(FingerprintManager.class), mock(FaceManager.class),
+                mock(PackageManager.class));
         mStorage = new LockSettingsStorageTestable(context,
                 new File(getContext().getFilesDir(), "locksettings"));
         mStorage.setDatabaseOnCreateCallback(new LockSettingsStorage.Callback() {
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/MockLockSettingsContext.java b/services/tests/servicestests/src/com/android/server/locksettings/MockLockSettingsContext.java
index b332532..2b9a05c 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/MockLockSettingsContext.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/MockLockSettingsContext.java
@@ -23,6 +23,8 @@
 import android.content.Context;
 import android.content.ContextWrapper;
 import android.content.pm.PackageManager;
+import android.hardware.face.FaceManager;
+import android.hardware.fingerprint.FingerprintManager;
 import android.os.UserManager;
 import android.os.storage.StorageManager;
 
@@ -34,11 +36,15 @@
     private StorageManager mStorageManager;
     private TrustManager mTrustManager;
     private KeyguardManager mKeyguardManager;
+    private FingerprintManager mFingerprintManager;
+    private FaceManager mFaceManager;
+    private PackageManager mPackageManager;
 
     public MockLockSettingsContext(Context base, UserManager userManager,
             NotificationManager notificationManager, DevicePolicyManager devicePolicyManager,
             StorageManager storageManager, TrustManager trustManager,
-            KeyguardManager keyguardManager) {
+            KeyguardManager keyguardManager, FingerprintManager fingerprintManager,
+            FaceManager faceManager, PackageManager packageManager) {
         super(base);
         mUserManager = userManager;
         mNotificationManager = notificationManager;
@@ -46,6 +52,9 @@
         mStorageManager = storageManager;
         mTrustManager = trustManager;
         mKeyguardManager = keyguardManager;
+        mFingerprintManager = fingerprintManager;
+        mFaceManager = faceManager;
+        mPackageManager = packageManager;
     }
 
     @Override
@@ -62,12 +71,21 @@
             return mTrustManager;
         } else if (KEYGUARD_SERVICE.equals(name)) {
             return mKeyguardManager;
+        } else if (FINGERPRINT_SERVICE.equals(name)) {
+            return mFingerprintManager;
+        } else if (FACE_SERVICE.equals(name)) {
+            return mFaceManager;
         } else {
             throw new RuntimeException("System service not mocked: " + name);
         }
     }
 
     @Override
+    public PackageManager getPackageManager() {
+        return mPackageManager;
+    }
+
+    @Override
     public void enforceCallingOrSelfPermission(String permission, String message) {
         // Skip permission checks for unit tests.
     }
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
index 127cf49..0776589 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java
@@ -29,6 +29,7 @@
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import android.app.admin.PasswordMetrics;
 import android.os.RemoteException;
@@ -468,6 +469,18 @@
         assertTrue(mLocalService.isEscrowTokenActive(handle, PRIMARY_USER_ID));
     }
 
+    public void testEscrowTokenCannotBeActivatedOnUnmanagedUser() {
+        final byte[] token = "some-high-entropy-secure-token".getBytes();
+        when(mUserManagerInternal.isDeviceManaged()).thenReturn(false);
+        when(mUserManagerInternal.isUserManaged(PRIMARY_USER_ID)).thenReturn(false);
+        when(mDeviceStateCache.isDeviceProvisioned()).thenReturn(true);
+
+        try {
+            mLocalService.addEscrowToken(token, PRIMARY_USER_ID, null);
+            fail("Escrow token should not be possible on unmanaged device");
+        } catch (SecurityException expected) { }
+    }
+
     public void testSetLockCredentialWithTokenFailsWithoutLockScreen() throws Exception {
         final byte[] password = "password".getBytes();
         final byte[] pattern = "123654".getBytes();
diff --git a/services/tests/servicestests/src/com/android/server/om/OverlayManagerServiceImplTests.java b/services/tests/servicestests/src/com/android/server/om/OverlayManagerServiceImplTests.java
index 3cdadd5..c566dfc 100644
--- a/services/tests/servicestests/src/com/android/server/om/OverlayManagerServiceImplTests.java
+++ b/services/tests/servicestests/src/com/android/server/om/OverlayManagerServiceImplTests.java
@@ -444,7 +444,7 @@
         private Set<String> mIdmapFiles = new ArraySet<>();
 
         DummyIdmapManager(DummyDeviceState state, DummyPackageManagerHelper packageManagerHelper) {
-            super(null, packageManagerHelper);
+            super(packageManagerHelper);
             mState = state;
         }
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/PackageManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/pm/PackageManagerServiceTest.java
index fc7cfec..0a310d1 100644
--- a/services/tests/servicestests/src/com/android/server/pm/PackageManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/PackageManagerServiceTest.java
@@ -118,17 +118,20 @@
         String[] partitions = { "system", "vendor", "odm", "oem", "product", "system_ext" };
         String[] appdir = { "app", "priv-app" };
         for (int i = 0; i < partitions.length; i++) {
+            final PackageManagerService.SystemPartition systemPartition =
+                    PackageManagerService.SYSTEM_PARTITIONS.get(i);
             for (int j = 0; j < appdir.length; j++) {
                 String canonical = new File("/" + partitions[i]).getCanonicalPath();
                 String path = String.format("%s/%s/A.apk", canonical, appdir[j]);
 
-                Assert.assertEquals(j == 1 && i != 3,
-                    PackageManagerService.locationIsPrivileged(path));
+                Assert.assertEquals(j == 1 && i != 3, systemPartition.containsPrivPath(path));
 
-                Assert.assertEquals(i == 1 || i == 2, PackageManagerService.locationIsVendor(path));
-                Assert.assertEquals(i == 3, PackageManagerService.locationIsOem(path));
-                Assert.assertEquals(i == 4, PackageManagerService.locationIsProduct(path));
-                Assert.assertEquals(i == 5, PackageManagerService.locationIsSystemExt(path));
+                final int scanFlag = systemPartition.scanFlag;
+                Assert.assertEquals(i == 1, scanFlag == PackageManagerService.SCAN_AS_VENDOR);
+                Assert.assertEquals(i == 2, scanFlag == PackageManagerService.SCAN_AS_ODM);
+                Assert.assertEquals(i == 3, scanFlag == PackageManagerService.SCAN_AS_OEM);
+                Assert.assertEquals(i == 4, scanFlag == PackageManagerService.SCAN_AS_PRODUCT);
+                Assert.assertEquals(i == 5, scanFlag == PackageManagerService.SCAN_AS_SYSTEM_EXT);
             }
         }
     }
diff --git a/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java b/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java
index 3fe9b52..15032c5 100644
--- a/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java
+++ b/services/tests/servicestests/src/com/android/server/pm/PackageManagerSettingsTests.java
@@ -20,8 +20,8 @@
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
+import static android.content.res.Resources.ID_NULL;
 
-import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.CoreMatchers.notNullValue;
@@ -75,10 +75,11 @@
 @RunWith(AndroidJUnit4.class)
 @SmallTest
 public class PackageManagerSettingsTests {
+    private static final String TAG = "PackageManagerSettingsTests";
+    private static final String PACKAGE_NAME_1 = "com.android.app1";
     private static final String PACKAGE_NAME_2 = "com.android.app2";
     private static final String PACKAGE_NAME_3 = "com.android.app3";
-    private static final String PACKAGE_NAME_1 = "com.android.app1";
-    public static final String TAG = "PackageManagerSettingsTests";
+    private static final int TEST_RESOURCE_ID = 2131231283;
 
     @Mock
     PermissionSettings mPermissionSettings;
@@ -158,7 +159,7 @@
         assertThat(ps.getEnabled(1), is(COMPONENT_ENABLED_STATE_DEFAULT));
     }
 
-    private PersistableBundle getPersistableBundle(String packageName, long longVal,
+    private static PersistableBundle createPersistableBundle(String packageName, long longVal,
             double doubleVal, boolean boolVal, String textVal) {
         final PersistableBundle bundle = new PersistableBundle();
         bundle.putString(packageName + ".TEXT_VALUE", textVal);
@@ -169,8 +170,8 @@
     }
 
     @Test
-    public void testReadPackageRestrictions_oldSuspendInfo() {
-        writePackageRestrictions_oldSuspendInfoXml(0);
+    public void testReadPackageRestrictions_noSuspendingPackage() {
+        writePackageRestrictions_noSuspendingPackageXml(0);
         final Object lock = new Object();
         final Context context = InstrumentationRegistry.getTargetContext();
         final Settings settingsUnderTest = new Settings(context.getFilesDir(), null, lock);
@@ -181,26 +182,61 @@
         final PackageSetting ps1 = settingsUnderTest.mPackages.get(PACKAGE_NAME_1);
         final PackageUserState packageUserState1 = ps1.readUserState(0);
         assertThat(packageUserState1.suspended, is(true));
-        assertThat("android".equals(packageUserState1.suspendingPackage), is(true));
+        assertThat(packageUserState1.suspendParams.size(), is(1));
+        assertThat(packageUserState1.suspendParams.keyAt(0), is("android"));
+        assertThat(packageUserState1.suspendParams.valueAt(0), is(nullValue()));
 
         final PackageSetting ps2 = settingsUnderTest.mPackages.get(PACKAGE_NAME_2);
         final PackageUserState packageUserState2 = ps2.readUserState(0);
         assertThat(packageUserState2.suspended, is(false));
-        assertThat(packageUserState2.suspendingPackage, is(nullValue()));
+        assertThat(packageUserState2.suspendParams, is(nullValue()));
     }
 
     @Test
-    public void testReadWritePackageRestrictions_newSuspendInfo() {
+    public void testReadPackageRestrictions_noSuspendParamsMap() {
+        writePackageRestrictions_noSuspendParamsMapXml(0);
+        final Object lock = new Object();
+        final Context context = InstrumentationRegistry.getTargetContext();
+        final Settings settingsUnderTest = new Settings(context.getFilesDir(), null, lock);
+        settingsUnderTest.mPackages.put(PACKAGE_NAME_1, createPackageSetting(PACKAGE_NAME_1));
+        settingsUnderTest.readPackageRestrictionsLPr(0);
+
+        final PackageSetting ps1 = settingsUnderTest.mPackages.get(PACKAGE_NAME_1);
+        final PackageUserState packageUserState1 = ps1.readUserState(0);
+        assertThat(packageUserState1.suspended, is(true));
+        assertThat(packageUserState1.suspendParams.size(), is(1));
+        assertThat(packageUserState1.suspendParams.keyAt(0), is(PACKAGE_NAME_3));
+        final PackageUserState.SuspendParams params = packageUserState1.suspendParams.valueAt(0);
+        assertThat(params, is(notNullValue()));
+        assertThat(params.appExtras.size(), is(1));
+        assertThat(params.appExtras.getString("app_extra_string"), is("value"));
+        assertThat(params.launcherExtras.size(), is(1));
+        assertThat(params.launcherExtras.getLong("launcher_extra_long"), is(4L));
+        assertThat(params.dialogInfo, is(notNullValue()));
+        assertThat(params.dialogInfo.getDialogMessage(), is("Dialog Message"));
+        assertThat(params.dialogInfo.getTitleResId(), is(ID_NULL));
+        assertThat(params.dialogInfo.getIconResId(), is(TEST_RESOURCE_ID));
+        assertThat(params.dialogInfo.getNeutralButtonTextResId(), is(ID_NULL));
+        assertThat(params.dialogInfo.getDialogMessageResId(), is(ID_NULL));
+    }
+
+    @Test
+    public void testReadWritePackageRestrictions_suspendInfo() {
         final Context context = InstrumentationRegistry.getTargetContext();
         final Settings settingsUnderTest = new Settings(context.getFilesDir(), null, new Object());
         final PackageSetting ps1 = createPackageSetting(PACKAGE_NAME_1);
         final PackageSetting ps2 = createPackageSetting(PACKAGE_NAME_2);
         final PackageSetting ps3 = createPackageSetting(PACKAGE_NAME_3);
 
-        final PersistableBundle appExtras1 = getPersistableBundle(
+        final PersistableBundle appExtras1 = createPersistableBundle(
                 PACKAGE_NAME_1, 1L, 0.01, true, "appString1");
-        final PersistableBundle launcherExtras1 = getPersistableBundle(
+        final PersistableBundle appExtras2 = createPersistableBundle(
+                PACKAGE_NAME_2, 2L, 0.02, true, "appString2");
+
+        final PersistableBundle launcherExtras1 = createPersistableBundle(
                 PACKAGE_NAME_1, 10L, 0.1, false, "launcherString1");
+        final PersistableBundle launcherExtras2 = createPersistableBundle(
+                PACKAGE_NAME_2, 20L, 0.2, false, "launcherString2");
 
         final SuspendDialogInfo dialogInfo1 = new SuspendDialogInfo.Builder()
                 .setIcon(0x11220001)
@@ -208,14 +244,23 @@
                 .setMessage("1st message")
                 .setNeutralButtonText(0x11220003)
                 .build();
+        final SuspendDialogInfo dialogInfo2 = new SuspendDialogInfo.Builder()
+                .setIcon(0x22220001)
+                .setTitle(0x22220002)
+                .setMessage("2nd message")
+                .setNeutralButtonText(0x22220003)
+                .build();
 
-        ps1.setSuspended(true, "suspendingPackage1", dialogInfo1, appExtras1, launcherExtras1, 0);
+        ps1.addOrUpdateSuspension("suspendingPackage1", dialogInfo1, appExtras1, launcherExtras1,
+                0);
+        ps1.addOrUpdateSuspension("suspendingPackage2", dialogInfo2, appExtras2, launcherExtras2,
+                0);
         settingsUnderTest.mPackages.put(PACKAGE_NAME_1, ps1);
 
-        ps2.setSuspended(true, "suspendingPackage2", null, null, null, 0);
+        ps2.addOrUpdateSuspension("suspendingPackage3", null, appExtras1, null, 0);
         settingsUnderTest.mPackages.put(PACKAGE_NAME_2, ps2);
 
-        ps3.setSuspended(false, "irrelevant", dialogInfo1, null, null, 0);
+        ps3.removeSuspension("irrelevant", 0);
         settingsUnderTest.mPackages.put(PACKAGE_NAME_3, ps3);
 
         settingsUnderTest.writePackageRestrictionsLPr(0);
@@ -229,27 +274,39 @@
         final PackageUserState readPus1 = settingsUnderTest.mPackages.get(PACKAGE_NAME_1)
                 .readUserState(0);
         assertThat(readPus1.suspended, is(true));
-        assertThat(readPus1.suspendingPackage, equalTo("suspendingPackage1"));
-        assertThat(readPus1.dialogInfo, equalTo(dialogInfo1));
-        assertThat(BaseBundle.kindofEquals(readPus1.suspendedAppExtras, appExtras1), is(true));
-        assertThat(BaseBundle.kindofEquals(readPus1.suspendedLauncherExtras, launcherExtras1),
+        assertThat(readPus1.suspendParams.size(), is(2));
+
+        assertThat(readPus1.suspendParams.keyAt(0), is("suspendingPackage1"));
+        final PackageUserState.SuspendParams params11 = readPus1.suspendParams.valueAt(0);
+        assertThat(params11, is(notNullValue()));
+        assertThat(params11.dialogInfo, is(dialogInfo1));
+        assertThat(BaseBundle.kindofEquals(params11.appExtras, appExtras1), is(true));
+        assertThat(BaseBundle.kindofEquals(params11.launcherExtras, launcherExtras1),
+                is(true));
+
+        assertThat(readPus1.suspendParams.keyAt(1), is("suspendingPackage2"));
+        final PackageUserState.SuspendParams params12 = readPus1.suspendParams.valueAt(1);
+        assertThat(params12, is(notNullValue()));
+        assertThat(params12.dialogInfo, is(dialogInfo2));
+        assertThat(BaseBundle.kindofEquals(params12.appExtras, appExtras2), is(true));
+        assertThat(BaseBundle.kindofEquals(params12.launcherExtras, launcherExtras2),
                 is(true));
 
         final PackageUserState readPus2 = settingsUnderTest.mPackages.get(PACKAGE_NAME_2)
                 .readUserState(0);
         assertThat(readPus2.suspended, is(true));
-        assertThat(readPus2.suspendingPackage, equalTo("suspendingPackage2"));
-        assertThat(readPus2.dialogInfo, is(nullValue()));
-        assertThat(readPus2.suspendedAppExtras, is(nullValue()));
-        assertThat(readPus2.suspendedLauncherExtras, is(nullValue()));
+        assertThat(readPus2.suspendParams.size(), is(1));
+        assertThat(readPus2.suspendParams.keyAt(0), is("suspendingPackage3"));
+        final PackageUserState.SuspendParams params21 = readPus2.suspendParams.valueAt(0);
+        assertThat(params21, is(notNullValue()));
+        assertThat(params21.dialogInfo, is(nullValue()));
+        assertThat(BaseBundle.kindofEquals(params21.appExtras, appExtras1), is(true));
+        assertThat(params21.launcherExtras, is(nullValue()));
 
         final PackageUserState readPus3 = settingsUnderTest.mPackages.get(PACKAGE_NAME_3)
                 .readUserState(0);
         assertThat(readPus3.suspended, is(false));
-        assertThat(readPus3.suspendingPackage, is(nullValue()));
-        assertThat(readPus3.dialogInfo, is(nullValue()));
-        assertThat(readPus3.suspendedAppExtras, is(nullValue()));
-        assertThat(readPus3.suspendedLauncherExtras, is(nullValue()));
+        assertThat(readPus3.suspendParams, is(nullValue()));
     }
 
     @Test
@@ -940,10 +997,10 @@
                 + "</packages>").getBytes());
     }
 
-    private void writePackageRestrictions_oldSuspendInfoXml(final int userId) {
+    private void writePackageRestrictions_noSuspendingPackageXml(final int userId) {
         writeFile(new File(InstrumentationRegistry.getContext().getFilesDir(), "system/users/"
                         + userId + "/package-restrictions.xml"),
-                ( "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n"
+                ("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n"
                         + "<package-restrictions>\n"
                         + "    <pkg name=\"" + PACKAGE_NAME_1 + "\" suspended=\"true\" />"
                         + "    <pkg name=\"" + PACKAGE_NAME_2 + "\" suspended=\"false\" />"
@@ -955,6 +1012,30 @@
                         .getBytes());
     }
 
+    private void writePackageRestrictions_noSuspendParamsMapXml(final int userId) {
+        writeFile(new File(InstrumentationRegistry.getContext().getFilesDir(), "system/users/"
+                        + userId + "/package-restrictions.xml"),
+                ("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n"
+                        + "<package-restrictions>\n"
+                        + "    <pkg name=\"" + PACKAGE_NAME_1 + "\" "
+                        + "     suspended=\"true\" suspending-package=\"" + PACKAGE_NAME_3 + "\">\n"
+                        + "        <suspended-dialog-info dialogMessage=\"Dialog Message\""
+                        + "         iconResId=\"" + TEST_RESOURCE_ID + "\"/>\n"
+                        + "        <suspended-app-extras>\n"
+                        + "            <string name=\"app_extra_string\">value</string>\n"
+                        + "        </suspended-app-extras>\n"
+                        + "        <suspended-launcher-extras>\n"
+                        + "            <long name=\"launcher_extra_long\" value=\"4\" />\n"
+                        + "        </suspended-launcher-extras>\n"
+                        + "    </pkg>\n"
+                        + "    <preferred-activities />\n"
+                        + "    <persistent-preferred-activities />\n"
+                        + "    <crossProfile-intent-filters />\n"
+                        + "    <default-apps />\n"
+                        + "</package-restrictions>\n")
+                        .getBytes());
+    }
+
     private void writeStoppedPackagesXml() {
         writeFile(new File(InstrumentationRegistry.getContext().getFilesDir(), "system/packages-stopped.xml"),
                 ( "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>"
diff --git a/services/tests/servicestests/src/com/android/server/pm/PackageUserStateTest.java b/services/tests/servicestests/src/com/android/server/pm/PackageUserStateTest.java
index 8eaf35f..fc5a0ba 100644
--- a/services/tests/servicestests/src/com/android/server/pm/PackageUserStateTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/PackageUserStateTest.java
@@ -26,6 +26,7 @@
 import android.content.pm.PackageUserState;
 import android.content.pm.SuspendDialogInfo;
 import android.os.PersistableBundle;
+import android.util.ArrayMap;
 import android.util.ArraySet;
 
 import androidx.test.filters.SmallTest;
@@ -175,18 +176,43 @@
         assertThat(testUserState03.equals(oldUserState), is(false));
     }
 
+    private static PackageUserState.SuspendParams createSuspendParams(SuspendDialogInfo dialogInfo,
+            PersistableBundle appExtras, PersistableBundle launcherExtras) {
+        PackageUserState.SuspendParams obj = PackageUserState.SuspendParams.getInstanceOrNull(
+                dialogInfo, appExtras, launcherExtras);
+        return obj;
+    }
+
+    private static PersistableBundle createPersistableBundle(String lKey, long lValue, String sKey,
+            String sValue, String dKey, double dValue) {
+        final PersistableBundle result = new PersistableBundle(3);
+        if (lKey != null) {
+            result.putLong("com.unit_test." + lKey, lValue);
+        }
+        if (sKey != null) {
+            result.putString("com.unit_test." + sKey, sValue);
+        }
+        if (dKey != null) {
+            result.putDouble("com.unit_test." + dKey, dValue);
+        }
+        return result;
+    }
+
     @Test
     public void testPackageUserState05() {
-        PersistableBundle appExtras1 = new PersistableBundle();
-        PersistableBundle appExtras2 = new PersistableBundle();
-        appExtras1.putInt("appExtraId", 1);
-        appExtras2.putInt("appExtraId", 2);
-        PersistableBundle launcherExtras1 = new PersistableBundle();
-        PersistableBundle launcherExtras2 = new PersistableBundle();
-        launcherExtras1.putString("name", "launcherExtras1");
-        launcherExtras2.putString("name", "launcherExtras2");
+        final PersistableBundle appExtras1 = createPersistableBundle("appExtraId", 1, null, null,
+                null, 0);
+        final PersistableBundle appExtras2 = createPersistableBundle("appExtraId", 2, null, null,
+                null, 0);
+
+        final PersistableBundle launcherExtras1 = createPersistableBundle(null, 0, "name",
+                "launcherExtras1", null, 0);
+        final PersistableBundle launcherExtras2 = createPersistableBundle(null, 0, "name",
+                "launcherExtras2", null, 0);
+
         final String suspendingPackage1 = "package1";
         final String suspendingPackage2 = "package2";
+
         final SuspendDialogInfo dialogInfo1 = new SuspendDialogInfo.Builder()
                 .setMessage("dialogMessage1")
                 .build();
@@ -194,38 +220,23 @@
                 .setMessage("dialogMessage2")
                 .build();
 
+        final ArrayMap<String, PackageUserState.SuspendParams> paramsMap1 = new ArrayMap<>();
+        paramsMap1.put(suspendingPackage1, createSuspendParams(dialogInfo1, appExtras1,
+                launcherExtras1));
+        final ArrayMap<String, PackageUserState.SuspendParams> paramsMap2 = new ArrayMap<>();
+        paramsMap2.put(suspendingPackage2, createSuspendParams(dialogInfo2,
+                appExtras2, launcherExtras2));
+
+
         final PackageUserState testUserState1 = new PackageUserState();
         testUserState1.suspended = true;
-        testUserState1.suspendedAppExtras = appExtras1;
-        testUserState1.suspendedLauncherExtras = launcherExtras1;
-        testUserState1.suspendingPackage = suspendingPackage1;
-        testUserState1.dialogInfo = dialogInfo1;
+        testUserState1.suspendParams = paramsMap1;
 
         PackageUserState testUserState2 = new PackageUserState(testUserState1);
         assertThat(testUserState1.equals(testUserState2), is(true));
-        testUserState2.suspendingPackage = suspendingPackage2;
+        testUserState2.suspendParams = paramsMap2;
+        // Should not be equal since suspendParams maps are different
         assertThat(testUserState1.equals(testUserState2), is(false));
-
-        testUserState2 = new PackageUserState(testUserState1);
-        testUserState2.suspendedAppExtras = appExtras2;
-        assertThat(testUserState1.equals(testUserState2), is(false));
-
-        testUserState2 = new PackageUserState(testUserState1);
-        testUserState2.suspendedLauncherExtras = launcherExtras2;
-        assertThat(testUserState1.equals(testUserState2), is(false));
-
-        testUserState2 = new PackageUserState(testUserState1);
-        testUserState2.dialogInfo = dialogInfo2;
-        assertThat(testUserState1.equals(testUserState2), is(false));
-
-        testUserState2 = new PackageUserState(testUserState1);
-        testUserState2.suspended = testUserState1.suspended = false;
-        // Everything is different but irrelevant if suspended is false
-        testUserState2.suspendingPackage = suspendingPackage2;
-        testUserState2.dialogInfo = dialogInfo2;
-        testUserState2.suspendedAppExtras = appExtras2;
-        testUserState2.suspendedLauncherExtras = launcherExtras2;
-        assertThat(testUserState1.equals(testUserState2), is(true));
     }
 
     @Test
@@ -243,4 +254,46 @@
         assertThat(userState1.equals(userState2), is(false));
     }
 
+    @Test
+    public void testPackageUserState07() {
+        final PersistableBundle appExtras1 = createPersistableBundle("appExtraId", 1, null, null,
+                null, 0);
+        final PersistableBundle appExtras2 = createPersistableBundle("appExtraId", 2, null, null,
+                null, 0);
+
+        final PersistableBundle launcherExtras1 = createPersistableBundle(null, 0, "name",
+                "launcherExtras1", null, 0);
+        final PersistableBundle launcherExtras2 = createPersistableBundle(null, 0, "name",
+                "launcherExtras2", null, 0);
+
+        final SuspendDialogInfo dialogInfo1 = new SuspendDialogInfo.Builder()
+                .setMessage("dialogMessage1")
+                .build();
+        final SuspendDialogInfo dialogInfo2 = new SuspendDialogInfo.Builder()
+                .setMessage("dialogMessage2")
+                .build();
+
+        final PackageUserState.SuspendParams params1;
+        PackageUserState.SuspendParams params2;
+        params1 = createSuspendParams(dialogInfo1, appExtras1, launcherExtras1);
+        params2 = createSuspendParams(dialogInfo1, appExtras1, launcherExtras1);
+        // Everything is same
+        assertThat(params1.equals(params2), is(true));
+
+        params2 = createSuspendParams(dialogInfo2, appExtras1, launcherExtras1);
+        // DialogInfo is different
+        assertThat(params1.equals(params2), is(false));
+
+        params2 = createSuspendParams(dialogInfo1, appExtras2, launcherExtras1);
+        // app extras are different
+        assertThat(params1.equals(params2), is(false));
+
+        params2 = createSuspendParams(dialogInfo1, appExtras1, launcherExtras2);
+        // Launcher extras are different
+        assertThat(params1.equals(params2), is(false));
+
+        params2 = createSuspendParams(dialogInfo2, appExtras2, launcherExtras2);
+        // Everything is different
+        assertThat(params1.equals(params2), is(false));
+    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserInfoTest.java b/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserInfoTest.java
index 806c71a..6d5b994 100644
--- a/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserInfoTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/UserManagerServiceUserInfoTest.java
@@ -132,6 +132,7 @@
         user.profileBadge = 2;
         user.partial = true;
         user.guestToRemove = true;
+        user.preCreated = true;
         return user;
     }
 
@@ -147,5 +148,6 @@
         assertEquals("profile badge not preseved", one.profileBadge, two.profileBadge);
         assertEquals("partial not preseved", one.partial, two.partial);
         assertEquals("guestToRemove not preseved", one.guestToRemove, two.guestToRemove);
+        assertEquals("preCreated not preseved", one.preCreated, two.preCreated);
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java b/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
new file mode 100644
index 0000000..f0b0328
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
@@ -0,0 +1,396 @@
+/*
+ * Copyright (C) 2019 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.pm;
+
+import static android.content.pm.UserInfo.FLAG_FULL;
+import static android.content.pm.UserInfo.FLAG_GUEST;
+import static android.content.pm.UserInfo.FLAG_MANAGED_PROFILE;
+import static android.content.pm.UserInfo.FLAG_SYSTEM;
+
+import static com.android.server.pm.UserSystemPackageInstaller.PACKAGE_WHITELIST_MODE_PROP;
+import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT;
+import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE;
+import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE;
+import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST;
+import static com.android.server.pm.UserSystemPackageInstaller.USER_TYPE_PACKAGE_WHITELIST_MODE_LOG;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageParser;
+import android.content.pm.UserInfo;
+import android.os.Looper;
+import android.os.SystemProperties;
+import android.os.UserManager;
+import android.os.UserManagerInternal;
+import android.support.test.uiautomator.UiDevice;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.MediumTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.LocalServices;
+import com.android.server.SystemConfig;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Tests for UserSystemPackageInstaller.
+ *
+ * <p>Run with:<pre>
+ * atest com.android.server.pm.UserSystemPackageInstallerTest
+ * </pre>
+ */
+@RunWith(AndroidJUnit4.class)
+@MediumTest
+public class UserSystemPackageInstallerTest {
+    private static final String TAG = "UserSystemPackageInstallerTest";
+
+    private UserSystemPackageInstaller mUserSystemPackageInstaller;
+
+    private Context mContext;
+
+    /** Any users created during this test, for them to be removed when it's done. */
+    private final List<Integer> mRemoveUsers = new ArrayList<>();
+    /** Original value of PACKAGE_WHITELIST_MODE_PROP before the test, to reset at end. */
+    private final int mOriginalWhitelistMode = SystemProperties.getInt(
+            PACKAGE_WHITELIST_MODE_PROP, USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT);
+
+    @Before
+    public void setup() {
+        // Currently UserManagerService cannot be instantiated twice inside a VM without a cleanup
+        // TODO: Remove once UMS supports proper dependency injection
+        if (Looper.myLooper() == null) {
+            Looper.prepare();
+        }
+        LocalServices.removeServiceForTest(UserManagerInternal.class);
+        UserManagerService ums = new UserManagerService(InstrumentationRegistry.getContext());
+
+        mUserSystemPackageInstaller = new UserSystemPackageInstaller(ums);
+        mContext = InstrumentationRegistry.getTargetContext();
+    }
+
+    @After
+    public void tearDown() {
+        UserManager um = UserManager.get(mContext);
+        for (int userId : mRemoveUsers) {
+            um.removeUser(userId);
+        }
+        setUserTypePackageWhitelistMode(mOriginalWhitelistMode);
+    }
+
+    /**
+     * Subclass of SystemConfig without running the constructor.
+     */
+    private class SystemConfigTestClass extends SystemConfig {
+        SystemConfigTestClass(boolean readPermissions) {
+            super(readPermissions);
+        }
+    }
+
+    /**
+     * Test that determineWhitelistedPackagesForUserTypes reads SystemConfig information properly.
+     */
+    @Test
+    public void testDetermineWhitelistedPackagesForUserTypes() {
+        SystemConfig sysConfig = new SystemConfigTestClass(false) {
+            @Override
+            public ArrayMap<String, Set<String>> getAndClearPackageToUserTypeWhitelist() {
+                ArrayMap<String, Set<String>> r = new ArrayMap<>();
+                r.put("com.android.package1", new ArraySet<>(Arrays.asList(
+                        "PROFILE", "SYSTEM", "GUEST", "FULL", "invalid-garbage1")));
+                r.put("com.android.package2", new ArraySet<>(Arrays.asList(
+                        "MANAGED_PROFILE")));
+                return r;
+            }
+
+            @Override
+            public ArrayMap<String, Set<String>> getAndClearPackageToUserTypeBlacklist() {
+                ArrayMap<String, Set<String>> r = new ArrayMap<>();
+                r.put("com.android.package1", new ArraySet<>(Arrays.asList(
+                        "FULL", "RESTRICTED", "invalid-garbage2")));
+                return r;
+            }
+        };
+
+        final ArrayMap<String, Integer> expectedOutput = getNewPackageToWhitelistedFlagsMap();
+        expectedOutput.put("com.android.package1",
+                UserInfo.PROFILE_FLAGS_MASK | FLAG_SYSTEM | FLAG_GUEST);
+        expectedOutput.put("com.android.package2",
+                UserInfo.FLAG_MANAGED_PROFILE);
+
+        final ArrayMap<String, Integer> actualOutput =
+                mUserSystemPackageInstaller.determineWhitelistedPackagesForUserTypes(sysConfig);
+
+        assertEquals("Incorrect package-to-user mapping.", expectedOutput, actualOutput);
+    }
+
+    /**
+     * Test that determineWhitelistedPackagesForUserTypes does not include packages that were never
+     * whitelisted properly, but does include packages that were whitelisted but then blacklisted.
+     */
+    @Test
+    public void testDetermineWhitelistedPackagesForUserTypes_noNetWhitelisting() {
+        SystemConfig sysConfig = new SystemConfigTestClass(false) {
+            @Override
+            public ArrayMap<String, Set<String>> getAndClearPackageToUserTypeWhitelist() {
+                ArrayMap<String, Set<String>> r = new ArrayMap<>();
+                r.put("com.android.package1", new ArraySet<>(Arrays.asList("invalid1")));
+                // com.android.package2 has no whitelisting
+                r.put("com.android.package3", new ArraySet<>(Arrays.asList("PROFILE", "FULL")));
+                r.put("com.android.package4", new ArraySet<>(Arrays.asList("PROFILE")));
+                r.put("com.android.package5", new ArraySet<>());
+                // com.android.package6 has no whitelisting
+                return r;
+            }
+
+            @Override
+            public ArrayMap<String, Set<String>> getAndClearPackageToUserTypeBlacklist() {
+                ArrayMap<String, Set<String>> r = new ArrayMap<>();
+                // com.android.package1 has no blacklisting
+                r.put("com.android.package2", new ArraySet<>(Arrays.asList("FULL")));
+                r.put("com.android.package3", new ArraySet<>(Arrays.asList("PROFILE", "FULL")));
+                r.put("com.android.package4", new ArraySet<>(Arrays.asList("PROFILE", "invalid4")));
+                // com.android.package5 has no blacklisting
+                r.put("com.android.package6", new ArraySet<>(Arrays.asList("invalid6")));
+                return r;
+            }
+        };
+
+        final ArrayMap<String, Integer> expectedOutput = getNewPackageToWhitelistedFlagsMap();
+        expectedOutput.put("com.android.package3", 0);
+        expectedOutput.put("com.android.package4", 0);
+
+        final ArrayMap<String, Integer> actualOutput =
+                mUserSystemPackageInstaller.determineWhitelistedPackagesForUserTypes(sysConfig);
+
+        assertEquals("Incorrect package-to-user mapping.", expectedOutput, actualOutput);
+    }
+
+    /**
+     * Tests that shouldInstallPackage correctly determines which packages should be installed.
+     */
+    @Test
+    public void testShouldInstallPackage() {
+        final String packageName1 = "pkg1"; // whitelisted
+        final String packageName2 = "pkg2"; // whitelisted and blacklisted
+        final String packageName3 = "pkg3"; // whitelisted for a different user type
+        final String packageName4 = "pkg4"; // not whitelisted nor blacklisted at all
+
+        final ArrayMap<String, Integer> pkgFlgMap = new ArrayMap<>(); // Whitelist: pkgs per flags
+        pkgFlgMap.put(packageName1, FLAG_FULL);
+        pkgFlgMap.put(packageName2, 0);
+        pkgFlgMap.put(packageName3, FLAG_MANAGED_PROFILE);
+
+        // Whitelist of pkgs for this specific user, i.e. subset of pkgFlagMap for this user.
+        final Set<String> userWhitelist = new ArraySet<>();
+        userWhitelist.add(packageName1);
+
+        final UserSystemPackageInstaller uspi = new UserSystemPackageInstaller(null, pkgFlgMap);
+
+        final PackageParser.Package pkg1 = new PackageParser.Package(packageName1);
+        final PackageParser.Package pkg2 = new PackageParser.Package(packageName2);
+        final PackageParser.Package pkg3 = new PackageParser.Package(packageName3);
+        final PackageParser.Package pkg4 = new PackageParser.Package(packageName4);
+
+        // No implicit whitelist, so only install pkg1.
+        boolean implicit = false;
+        boolean isSysUser = false;
+        assertTrue(uspi.shouldInstallPackage(pkg1, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertFalse(uspi.shouldInstallPackage(pkg2, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertFalse(uspi.shouldInstallPackage(pkg3, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertFalse(uspi.shouldInstallPackage(pkg4, pkgFlgMap, userWhitelist, implicit, isSysUser));
+
+        // Use implicit whitelist, so install pkg1 and pkg4
+        implicit = true;
+        isSysUser = false;
+        assertTrue(uspi.shouldInstallPackage(pkg1, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertFalse(uspi.shouldInstallPackage(pkg2, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertFalse(uspi.shouldInstallPackage(pkg3, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertTrue(uspi.shouldInstallPackage(pkg4, pkgFlgMap, userWhitelist, implicit, isSysUser));
+
+        // For user 0 specifically, we always implicitly whitelist.
+        implicit = false;
+        isSysUser = true;
+        assertTrue(uspi.shouldInstallPackage(pkg1, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertFalse(uspi.shouldInstallPackage(pkg2, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertFalse(uspi.shouldInstallPackage(pkg3, pkgFlgMap, userWhitelist, implicit, isSysUser));
+        assertTrue(uspi.shouldInstallPackage(pkg4, pkgFlgMap, userWhitelist, implicit, isSysUser));
+    }
+
+    /**
+     * Tests that getWhitelistedPackagesForUserType works properly, assuming that
+     * mWhitelistedPackagesForUserTypes (i.e. determineWhitelistedPackagesForUserTypes) is correct.
+     */
+    @Test
+    public void testGetWhitelistedPackagesForUserType() {
+        final String packageName1 = "pkg1"; // whitelisted for FULL
+        final String packageName2 = "pkg2"; // blacklisted whenever whitelisted
+        final String packageName3 = "pkg3"; // whitelisted for SYSTEM
+        final String packageName4 = "pkg4"; // whitelisted for FULL
+
+        final ArrayMap<String, Integer> pkgFlagMap = new ArrayMap<>(); // Whitelist: pkgs per flags
+        pkgFlagMap.put(packageName1, FLAG_FULL);
+        pkgFlagMap.put(packageName2, 0);
+        pkgFlagMap.put(packageName3, FLAG_SYSTEM);
+        pkgFlagMap.put(packageName4, FLAG_FULL);
+
+        // Whitelist of pkgs for this specific user, i.e. subset of pkgFlagMap for this user.
+        final Set<String> expectedUserWhitelist = new ArraySet<>();
+        expectedUserWhitelist.add(packageName1);
+
+        UserSystemPackageInstaller uspi = new UserSystemPackageInstaller(null, pkgFlagMap);
+
+        Set<String> output = uspi.getWhitelistedPackagesForUserType(FLAG_FULL);
+        assertEquals("Whitelist for FULL is the wrong size", 2, output.size());
+        assertTrue("Whitelist for FULL doesn't contain pkg1", output.contains(packageName1));
+        assertTrue("Whitelist for FULL doesn't contain pkg4", output.contains(packageName4));
+
+        output = uspi.getWhitelistedPackagesForUserType(FLAG_SYSTEM);
+        assertEquals("Whitelist for SYSTEM is the wrong size", 1, output.size());
+        assertTrue("Whitelist for SYSTEM doesn't contain pkg1", output.contains(packageName3));
+    }
+
+    /**
+     * Test that a newly created FULL user has the expected system packages.
+     *
+     * Assumes that SystemConfig and UserManagerService.determineWhitelistedPackagesForUserTypes
+     * work correctly (they are tested separately).
+     */
+    @Test
+    public void testPackagesForCreateUser_full() {
+        final int userFlags = UserInfo.FLAG_FULL;
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
+        PackageManager pm = mContext.getPackageManager();
+
+        final SystemConfig sysConfig = new SystemConfigTestClass(true);
+        final ArrayMap<String, Integer> packageMap =
+                mUserSystemPackageInstaller.determineWhitelistedPackagesForUserTypes(sysConfig);
+        final Set<String> expectedPackages = new ArraySet<>(packageMap.size());
+        for (int i = 0; i < packageMap.size(); i++) {
+            if ((userFlags & packageMap.valueAt(i)) != 0) {
+                expectedPackages.add(packageMap.keyAt(i));
+            }
+        }
+
+        final UserManager um = UserManager.get(mContext);
+        final UserInfo user = um.createUser("Test User", userFlags);
+        assertNotNull(user);
+        mRemoveUsers.add(user.id);
+
+        final List<PackageInfo> packageInfos = pm.getInstalledPackagesAsUser(
+                PackageManager.MATCH_SYSTEM_ONLY
+                        | PackageManager.MATCH_DISABLED_COMPONENTS
+                        | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS,
+                user.id);
+        final Set<String> actualPackages = new ArraySet<>(packageInfos.size());
+        for (PackageInfo p : packageInfos) {
+            actualPackages.add(p.packageName);
+        }
+        checkPackageDifferences(expectedPackages, actualPackages);
+    }
+
+    /** Asserts that actual is a subset of expected. */
+    private void checkPackageDifferences(Set<String> expected, Set<String> actual) {
+        final Set<String> uniqueToExpected = new ArraySet<>(expected);
+        uniqueToExpected.removeAll(actual);
+        final Set<String> uniqueToActual = new ArraySet<>(actual);
+        uniqueToActual.removeAll(expected);
+
+        Log.v(TAG, "Expected list uniquely has " + uniqueToExpected);
+        Log.v(TAG, "Actual list uniquely has " + uniqueToActual);
+
+        assertTrue("User's system packages includes non-whitelisted packages: " + uniqueToActual,
+                uniqueToActual.isEmpty());
+    }
+
+    /**
+     * Test that setEnableUserTypePackageWhitelist() has the correct effect.
+     */
+    @Test
+    public void testSetWhitelistEnabledMode() {
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE);
+        assertFalse(mUserSystemPackageInstaller.isLogMode());
+        assertFalse(mUserSystemPackageInstaller.isEnforceMode());
+        assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_LOG);
+        assertTrue(mUserSystemPackageInstaller.isLogMode());
+        assertFalse(mUserSystemPackageInstaller.isEnforceMode());
+        assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
+        assertFalse(mUserSystemPackageInstaller.isLogMode());
+        assertTrue(mUserSystemPackageInstaller.isEnforceMode());
+        assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST);
+        assertFalse(mUserSystemPackageInstaller.isLogMode());
+        assertFalse(mUserSystemPackageInstaller.isEnforceMode());
+        assertTrue(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+
+        setUserTypePackageWhitelistMode(
+                USER_TYPE_PACKAGE_WHITELIST_MODE_LOG | USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
+        assertTrue(mUserSystemPackageInstaller.isLogMode());
+        assertTrue(mUserSystemPackageInstaller.isEnforceMode());
+        assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+
+        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST
+                | USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
+        assertFalse(mUserSystemPackageInstaller.isLogMode());
+        assertTrue(mUserSystemPackageInstaller.isEnforceMode());
+        assertTrue(mUserSystemPackageInstaller.isImplicitWhitelistMode());
+    }
+
+    /** Sets the whitelist mode to the desired value via adb's setprop. */
+    private void setUserTypePackageWhitelistMode(int mode) {
+        UiDevice mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+        try {
+            String result = mUiDevice.executeShellCommand(String.format("setprop %s %d",
+                    PACKAGE_WHITELIST_MODE_PROP, mode));
+            assertFalse("Failed to set sysprop " + PACKAGE_WHITELIST_MODE_PROP + ": " + result,
+                    result != null && result.contains("Failed"));
+        } catch (IOException e) {
+            fail("Failed to set sysprop " + PACKAGE_WHITELIST_MODE_PROP + ":\n" + e);
+        }
+    }
+
+    private ArrayMap<String, Integer> getNewPackageToWhitelistedFlagsMap() {
+        final ArrayMap<String, Integer> pkgFlagMap = new ArrayMap<>();
+        // "android" is always treated as whitelisted, regardless of the xml file.
+        pkgFlagMap.put("android", FLAG_SYSTEM | UserInfo.FLAG_FULL | UserInfo.PROFILE_FLAGS_MASK);
+        return pkgFlagMap;
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java b/services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java
new file mode 100644
index 0000000..3e9f625
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/protolog/ProtoLogImplTest.java
@@ -0,0 +1,462 @@
+/*
+ * Copyright (C) 2019 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.protolog;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.android.server.protolog.ProtoLogImpl.PROTOLOG_VERSION;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.SystemClock;
+import android.platform.test.annotations.Presubmit;
+import android.util.proto.ProtoInputStream;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.server.protolog.common.IProtoLogGroup;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.util.LinkedList;
+
+/**
+ * Test class for {@link ProtoLogImpl}.
+ */
+@SuppressWarnings("ConstantConditions")
+@SmallTest
+@Presubmit
+@RunWith(JUnit4.class)
+public class ProtoLogImplTest {
+
+    private static final byte[] MAGIC_HEADER = new byte[]{
+            0x9, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x4c, 0x4f, 0x47
+    };
+
+    private ProtoLogImpl mProtoLog;
+    private File mFile;
+
+    @Mock
+    private ProtoLogViewerConfigReader mReader;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        final Context testContext = getInstrumentation().getContext();
+        mFile = testContext.getFileStreamPath("tracing_test.dat");
+        //noinspection ResultOfMethodCallIgnored
+        mFile.delete();
+        mProtoLog = new ProtoLogImpl(mFile, 1024 * 1024, mReader);
+    }
+
+    @After
+    public void tearDown() {
+        if (mFile != null) {
+            //noinspection ResultOfMethodCallIgnored
+            mFile.delete();
+        }
+        ProtoLogImpl.setSingleInstance(null);
+    }
+
+    @Test
+    public void isEnabled_returnsFalseByDefault() {
+        assertFalse(mProtoLog.isProtoEnabled());
+    }
+
+    @Test
+    public void isEnabled_returnsTrueAfterStart() {
+        mProtoLog.startProtoLog(mock(PrintWriter.class));
+        assertTrue(mProtoLog.isProtoEnabled());
+    }
+
+    @Test
+    public void isEnabled_returnsFalseAfterStop() {
+        mProtoLog.startProtoLog(mock(PrintWriter.class));
+        mProtoLog.stopProtoLog(mock(PrintWriter.class), true);
+        assertFalse(mProtoLog.isProtoEnabled());
+    }
+
+    @Test
+    public void logFile_startsWithMagicHeader() throws Exception {
+        mProtoLog.startProtoLog(mock(PrintWriter.class));
+        mProtoLog.stopProtoLog(mock(PrintWriter.class), true);
+
+        assertTrue("Log file should exist", mFile.exists());
+
+        byte[] header = new byte[MAGIC_HEADER.length];
+        try (InputStream is = new FileInputStream(mFile)) {
+            assertEquals(MAGIC_HEADER.length, is.read(header));
+            assertArrayEquals(MAGIC_HEADER, header);
+        }
+    }
+
+    @Test
+    public void getSingleInstance() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        assertSame(mockedProtoLog, ProtoLogImpl.getSingleInstance());
+    }
+
+    @Test
+    public void d_logCalled() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        ProtoLogImpl.d(TestProtoLogGroup.TEST_GROUP, 1234, 4321, "test %d");
+        verify(mockedProtoLog).log(eq(ProtoLogImpl.LogLevel.DEBUG), eq(
+                TestProtoLogGroup.TEST_GROUP),
+                eq(1234), eq(4321), eq("test %d"), eq(new Object[]{}));
+    }
+
+    @Test
+    public void v_logCalled() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        ProtoLogImpl.v(TestProtoLogGroup.TEST_GROUP, 1234, 4321, "test %d");
+        verify(mockedProtoLog).log(eq(ProtoLogImpl.LogLevel.VERBOSE), eq(
+                TestProtoLogGroup.TEST_GROUP),
+                eq(1234), eq(4321), eq("test %d"), eq(new Object[]{}));
+    }
+
+    @Test
+    public void i_logCalled() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        ProtoLogImpl.i(TestProtoLogGroup.TEST_GROUP, 1234, 4321, "test %d");
+        verify(mockedProtoLog).log(eq(ProtoLogImpl.LogLevel.INFO), eq(
+                TestProtoLogGroup.TEST_GROUP),
+                eq(1234), eq(4321), eq("test %d"), eq(new Object[]{}));
+    }
+
+    @Test
+    public void w_logCalled() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        ProtoLogImpl.w(TestProtoLogGroup.TEST_GROUP, 1234,
+                4321, "test %d");
+        verify(mockedProtoLog).log(eq(ProtoLogImpl.LogLevel.WARN), eq(
+                TestProtoLogGroup.TEST_GROUP),
+                eq(1234), eq(4321), eq("test %d"), eq(new Object[]{}));
+    }
+
+    @Test
+    public void e_logCalled() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        ProtoLogImpl.e(TestProtoLogGroup.TEST_GROUP, 1234, 4321, "test %d");
+        verify(mockedProtoLog).log(eq(ProtoLogImpl.LogLevel.ERROR), eq(
+                TestProtoLogGroup.TEST_GROUP),
+                eq(1234), eq(4321), eq("test %d"), eq(new Object[]{}));
+    }
+
+    @Test
+    public void wtf_logCalled() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        ProtoLogImpl.wtf(TestProtoLogGroup.TEST_GROUP,
+                1234, 4321, "test %d");
+        verify(mockedProtoLog).log(eq(ProtoLogImpl.LogLevel.WTF), eq(
+                TestProtoLogGroup.TEST_GROUP),
+                eq(1234), eq(4321), eq("test %d"), eq(new Object[]{}));
+    }
+
+    @Test
+    public void log_logcatEnabledExternalMessage() {
+        when(mReader.getViewerString(anyInt())).thenReturn("test %b %d %% %o %x %e %g %s %f");
+        ProtoLogImpl implSpy = Mockito.spy(mProtoLog);
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(true);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(false);
+
+        implSpy.log(
+                ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234, 4321, null,
+                new Object[]{true, 10000, 20000, 30000, 0.0001, 0.00002, "test", 0.000003});
+
+        verify(implSpy).passToLogcat(eq(TestProtoLogGroup.TEST_GROUP.getTag()), eq(
+                ProtoLogImpl.LogLevel.INFO),
+                eq("test true 10000 % 47040 7530 1.000000e-04 2.00000e-05 test 0.000003"));
+        verify(mReader).getViewerString(eq(1234));
+    }
+
+    @Test
+    public void log_logcatEnabledInvalidMessage() {
+        when(mReader.getViewerString(anyInt())).thenReturn("test %b %d %% %o %x %e %g %s %f");
+        ProtoLogImpl implSpy = Mockito.spy(mProtoLog);
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(true);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(false);
+
+        implSpy.log(
+                ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234, 4321, null,
+                new Object[]{true, 10000, 0.0001, 0.00002, "test"});
+
+        verify(implSpy).passToLogcat(eq(TestProtoLogGroup.TEST_GROUP.getTag()), eq(
+                ProtoLogImpl.LogLevel.INFO),
+                eq("UNKNOWN MESSAGE (1234) true 10000 1.0E-4 2.0E-5 test"));
+        verify(mReader).getViewerString(eq(1234));
+    }
+
+    @Test
+    public void log_logcatEnabledInlineMessage() {
+        when(mReader.getViewerString(anyInt())).thenReturn("test %d");
+        ProtoLogImpl implSpy = Mockito.spy(mProtoLog);
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(true);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(false);
+
+        implSpy.log(
+                ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234, 4321, "test %d",
+                new Object[]{5});
+
+        verify(implSpy).passToLogcat(eq(TestProtoLogGroup.TEST_GROUP.getTag()), eq(
+                ProtoLogImpl.LogLevel.INFO), eq("test 5"));
+        verify(mReader, never()).getViewerString(anyInt());
+    }
+
+    @Test
+    public void log_logcatEnabledNoMessage() {
+        when(mReader.getViewerString(anyInt())).thenReturn(null);
+        ProtoLogImpl implSpy = Mockito.spy(mProtoLog);
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(true);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(false);
+
+        implSpy.log(
+                ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234, 4321, null,
+                new Object[]{5});
+
+        verify(implSpy).passToLogcat(eq(TestProtoLogGroup.TEST_GROUP.getTag()), eq(
+                ProtoLogImpl.LogLevel.INFO), eq("UNKNOWN MESSAGE (1234) 5"));
+        verify(mReader).getViewerString(eq(1234));
+    }
+
+    @Test
+    public void log_logcatDisabled() {
+        when(mReader.getViewerString(anyInt())).thenReturn("test %d");
+        ProtoLogImpl implSpy = Mockito.spy(mProtoLog);
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(false);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(false);
+
+        implSpy.log(
+                ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234, 4321, "test %d",
+                new Object[]{5});
+
+        verify(implSpy, never()).passToLogcat(any(), any(), any());
+        verify(mReader, never()).getViewerString(anyInt());
+    }
+
+    private static class ProtoLogData {
+        Integer mMessageHash = null;
+        Long mElapsedTime = null;
+        LinkedList<String> mStrParams = new LinkedList<>();
+        LinkedList<Long> mSint64Params = new LinkedList<>();
+        LinkedList<Double> mDoubleParams = new LinkedList<>();
+        LinkedList<Boolean> mBooleanParams = new LinkedList<>();
+    }
+
+    private ProtoLogData readProtoLogSingle(ProtoInputStream ip) throws IOException {
+        while (ip.nextField() != ProtoInputStream.NO_MORE_FIELDS) {
+            if (ip.getFieldNumber() == (int) ProtoLogFileProto.VERSION) {
+                assertEquals(PROTOLOG_VERSION, ip.readString(ProtoLogFileProto.VERSION));
+                continue;
+            }
+            if (ip.getFieldNumber() != (int) ProtoLogFileProto.LOG) {
+                continue;
+            }
+            long token = ip.start(ProtoLogFileProto.LOG);
+            ProtoLogData data = new ProtoLogData();
+            while (ip.nextField() != ProtoInputStream.NO_MORE_FIELDS) {
+                switch (ip.getFieldNumber()) {
+                    case (int) ProtoLogMessage.MESSAGE_HASH: {
+                        data.mMessageHash = ip.readInt(ProtoLogMessage.MESSAGE_HASH);
+                        break;
+                    }
+                    case (int) ProtoLogMessage.ELAPSED_REALTIME_NANOS: {
+                        data.mElapsedTime = ip.readLong(ProtoLogMessage.ELAPSED_REALTIME_NANOS);
+                        break;
+                    }
+                    case (int) ProtoLogMessage.STR_PARAMS: {
+                        data.mStrParams.add(ip.readString(ProtoLogMessage.STR_PARAMS));
+                        break;
+                    }
+                    case (int) ProtoLogMessage.SINT64_PARAMS: {
+                        data.mSint64Params.add(ip.readLong(ProtoLogMessage.SINT64_PARAMS));
+                        break;
+                    }
+                    case (int) ProtoLogMessage.DOUBLE_PARAMS: {
+                        data.mDoubleParams.add(ip.readDouble(ProtoLogMessage.DOUBLE_PARAMS));
+                        break;
+                    }
+                    case (int) ProtoLogMessage.BOOLEAN_PARAMS: {
+                        data.mBooleanParams.add(ip.readBoolean(ProtoLogMessage.BOOLEAN_PARAMS));
+                        break;
+                    }
+                }
+            }
+            ip.end(token);
+            return data;
+        }
+        return null;
+    }
+
+    @Test
+    public void log_protoEnabled() throws Exception {
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(false);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(true);
+        mProtoLog.startProtoLog(mock(PrintWriter.class));
+        long before = SystemClock.elapsedRealtimeNanos();
+        mProtoLog.log(
+                ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234,
+                0b1110101001010100, null,
+                new Object[]{"test", 1, 2, 3, 0.4, 0.5, 0.6, true});
+        long after = SystemClock.elapsedRealtimeNanos();
+        mProtoLog.stopProtoLog(mock(PrintWriter.class), true);
+        try (InputStream is = new FileInputStream(mFile)) {
+            ProtoInputStream ip = new ProtoInputStream(is);
+            ProtoLogData data = readProtoLogSingle(ip);
+            assertNotNull(data);
+            assertEquals(1234, data.mMessageHash.longValue());
+            assertTrue(before <= data.mElapsedTime && data.mElapsedTime <= after);
+            assertArrayEquals(new String[]{"test"}, data.mStrParams.toArray());
+            assertArrayEquals(new Long[]{1L, 2L, 3L}, data.mSint64Params.toArray());
+            assertArrayEquals(new Double[]{0.4, 0.5, 0.6}, data.mDoubleParams.toArray());
+            assertArrayEquals(new Boolean[]{true}, data.mBooleanParams.toArray());
+        }
+    }
+
+    @Test
+    public void log_invalidParamsMask() throws Exception {
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(false);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(true);
+        mProtoLog.startProtoLog(mock(PrintWriter.class));
+        long before = SystemClock.elapsedRealtimeNanos();
+        mProtoLog.log(
+                ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234,
+                0b01100100, null,
+                new Object[]{"test", 1, 0.1, true});
+        long after = SystemClock.elapsedRealtimeNanos();
+        mProtoLog.stopProtoLog(mock(PrintWriter.class), true);
+        try (InputStream is = new FileInputStream(mFile)) {
+            ProtoInputStream ip = new ProtoInputStream(is);
+            ProtoLogData data = readProtoLogSingle(ip);
+            assertNotNull(data);
+            assertEquals(1234, data.mMessageHash.longValue());
+            assertTrue(before <= data.mElapsedTime && data.mElapsedTime <= after);
+            assertArrayEquals(new String[]{"test", "(INVALID PARAMS_MASK) true"},
+                    data.mStrParams.toArray());
+            assertArrayEquals(new Long[]{1L}, data.mSint64Params.toArray());
+            assertArrayEquals(new Double[]{0.1}, data.mDoubleParams.toArray());
+            assertArrayEquals(new Boolean[]{}, data.mBooleanParams.toArray());
+        }
+    }
+
+    @Test
+    public void log_protoDisabled() throws Exception {
+        TestProtoLogGroup.TEST_GROUP.setLogToLogcat(false);
+        TestProtoLogGroup.TEST_GROUP.setLogToProto(false);
+        mProtoLog.startProtoLog(mock(PrintWriter.class));
+        mProtoLog.log(ProtoLogImpl.LogLevel.INFO, TestProtoLogGroup.TEST_GROUP, 1234,
+                0b11, null, new Object[]{true});
+        mProtoLog.stopProtoLog(mock(PrintWriter.class), true);
+        try (InputStream is = new FileInputStream(mFile)) {
+            ProtoInputStream ip = new ProtoInputStream(is);
+            ProtoLogData data = readProtoLogSingle(ip);
+            assertNull(data);
+        }
+    }
+
+    private enum TestProtoLogGroup implements IProtoLogGroup {
+        TEST_GROUP(true, true, false, "WindowManagetProtoLogTest");
+
+        private final boolean mEnabled;
+        private volatile boolean mLogToProto;
+        private volatile boolean mLogToLogcat;
+        private final String mTag;
+
+        /**
+         * @param enabled     set to false to exclude all log statements for this group from
+         *                    compilation,
+         *                    they will not be available in runtime.
+         * @param logToProto  enable binary logging for the group
+         * @param logToLogcat enable text logging for the group
+         * @param tag         name of the source of the logged message
+         */
+        TestProtoLogGroup(boolean enabled, boolean logToProto, boolean logToLogcat, String tag) {
+            this.mEnabled = enabled;
+            this.mLogToProto = logToProto;
+            this.mLogToLogcat = logToLogcat;
+            this.mTag = tag;
+        }
+
+        @Override
+        public boolean isEnabled() {
+            return mEnabled;
+        }
+
+        @Override
+        public boolean isLogToProto() {
+            return mLogToProto;
+        }
+
+        @Override
+        public boolean isLogToLogcat() {
+            return mLogToLogcat;
+        }
+
+        @Override
+        public boolean isLogToAny() {
+            return mLogToLogcat || mLogToProto;
+        }
+
+        @Override
+        public String getTag() {
+            return mTag;
+        }
+
+        @Override
+        public void setLogToProto(boolean logToProto) {
+            this.mLogToProto = logToProto;
+        }
+
+        @Override
+        public void setLogToLogcat(boolean logToLogcat) {
+            this.mLogToLogcat = logToLogcat;
+        }
+
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/protolog/ProtoLogViewerConfigReaderTest.java b/services/tests/servicestests/src/com/android/server/protolog/ProtoLogViewerConfigReaderTest.java
new file mode 100644
index 0000000..0254055
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/protolog/ProtoLogViewerConfigReaderTest.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2019 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.protolog;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.zip.GZIPOutputStream;
+
+@SmallTest
+@Presubmit
+@RunWith(JUnit4.class)
+public class ProtoLogViewerConfigReaderTest {
+    private static final String TEST_VIEWER_CONFIG = "{\n"
+            + "  \"version\": \"1.0.0\",\n"
+            + "  \"messages\": {\n"
+            + "    \"70933285\": {\n"
+            + "      \"message\": \"Test completed successfully: %b\",\n"
+            + "      \"level\": \"ERROR\",\n"
+            + "      \"group\": \"GENERIC_WM\"\n"
+            + "    },\n"
+            + "    \"1792430067\": {\n"
+            + "      \"message\": \"Attempted to add window to a display that does not exist: %d."
+            + "  Aborting.\",\n"
+            + "      \"level\": \"WARN\",\n"
+            + "      \"group\": \"GENERIC_WM\"\n"
+            + "    },\n"
+            + "    \"1352021864\": {\n"
+            + "      \"message\": \"Test 2\",\n"
+            + "      \"level\": \"WARN\",\n"
+            + "      \"group\": \"GENERIC_WM\"\n"
+            + "    },\n"
+            + "    \"409412266\": {\n"
+            + "      \"message\": \"Window %s is already added\",\n"
+            + "      \"level\": \"WARN\",\n"
+            + "      \"group\": \"GENERIC_WM\"\n"
+            + "    }\n"
+            + "  },\n"
+            + "  \"groups\": {\n"
+            + "    \"GENERIC_WM\": {\n"
+            + "      \"tag\": \"WindowManager\"\n"
+            + "    }\n"
+            + "  }\n"
+            + "}\n";
+
+
+    private ProtoLogViewerConfigReader
+            mConfig = new ProtoLogViewerConfigReader();
+    private File mTestViewerConfig;
+
+    @Before
+    public void setUp() throws IOException {
+        mTestViewerConfig = File.createTempFile("testConfig", ".json.gz");
+        OutputStreamWriter writer = new OutputStreamWriter(
+                new GZIPOutputStream(new FileOutputStream(mTestViewerConfig)));
+        writer.write(TEST_VIEWER_CONFIG);
+        writer.close();
+    }
+
+    @After
+    public void tearDown() {
+        //noinspection ResultOfMethodCallIgnored
+        mTestViewerConfig.delete();
+    }
+
+    @Test
+    public void getViewerString_notLoaded() {
+        assertNull(mConfig.getViewerString(1));
+    }
+
+    @Test
+    public void loadViewerConfig() {
+        mConfig.loadViewerConfig(null, mTestViewerConfig.getAbsolutePath());
+        assertEquals("Test completed successfully: %b", mConfig.getViewerString(70933285));
+        assertEquals("Test 2", mConfig.getViewerString(1352021864));
+        assertEquals("Window %s is already added", mConfig.getViewerString(409412266));
+        assertNull(mConfig.getViewerString(1));
+    }
+
+    @Test
+    public void loadViewerConfig_invalidFile() {
+        mConfig.loadViewerConfig(null, "/tmp/unknown/file/does/not/exist");
+        // No exception is thrown.
+        assertNull(mConfig.getViewerString(1));
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/protolog/common/LogDataTypeTest.java b/services/tests/servicestests/src/com/android/server/protolog/common/LogDataTypeTest.java
new file mode 100644
index 0000000..4c7f5fd
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/protolog/common/LogDataTypeTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2019 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.protolog.common;
+
+import static org.junit.Assert.assertEquals;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@SmallTest
+@Presubmit
+@RunWith(JUnit4.class)
+public class LogDataTypeTest {
+    @Test
+    public void parseFormatString() {
+        String str = "%b %d %o %x %f %e %g %s %%";
+        List<Integer> out = LogDataType.parseFormatString(str);
+        assertEquals(Arrays.asList(
+                LogDataType.BOOLEAN,
+                LogDataType.LONG,
+                LogDataType.LONG,
+                LogDataType.LONG,
+                LogDataType.DOUBLE,
+                LogDataType.DOUBLE,
+                LogDataType.DOUBLE,
+                LogDataType.STRING
+        ), out);
+    }
+
+    @Test(expected = InvalidFormatStringException.class)
+    public void parseFormatString_invalid() {
+        String str = "%q";
+        LogDataType.parseFormatString(str);
+    }
+
+    @Test
+    public void logDataTypesToBitMask() {
+        List<Integer> types = Arrays.asList(LogDataType.STRING, LogDataType.DOUBLE,
+                LogDataType.LONG, LogDataType.BOOLEAN);
+        int mask = LogDataType.logDataTypesToBitMask(types);
+        assertEquals(0b11011000, mask);
+    }
+
+    @Test(expected = BitmaskConversionException.class)
+    public void logDataTypesToBitMask_toManyParams() {
+        ArrayList<Integer> types = new ArrayList<>();
+        for (int i = 0; i <= 16; i++) {
+            types.add(LogDataType.STRING);
+        }
+        LogDataType.logDataTypesToBitMask(types);
+    }
+
+    @Test
+    public void bitmaskToLogDataTypes() {
+        int bitmask = 0b11011000;
+        List<Integer> types = Arrays.asList(LogDataType.STRING, LogDataType.DOUBLE,
+                LogDataType.LONG, LogDataType.BOOLEAN);
+        for (int i = 0; i < types.size(); i++) {
+            assertEquals(types.get(i).intValue(), LogDataType.bitmaskToLogDataType(bitmask, i));
+        }
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java b/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java
index 8cb5197..0c5451f 100644
--- a/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java
+++ b/services/tests/servicestests/src/com/android/server/rollback/AppDataRollbackHelperTest.java
@@ -16,7 +16,6 @@
 
 package com.android.server.rollback;
 
-import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNull;
@@ -45,8 +44,6 @@
 
 import java.io.File;
 import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Set;
 
 @RunWith(JUnit4.class)
 public class AppDataRollbackHelperTest {
@@ -250,28 +247,22 @@
         dataForRestore.info.getPackages().add(pendingRestore);
         dataForRestore.info.getPackages().add(wasRecentlyRestored);
 
-        Set<Rollback> changed = helper.commitPendingBackupAndRestoreForUser(37,
-                Arrays.asList(dataWithPendingBackup, dataWithRecentRestore, dataForDifferentUser,
-                    dataForRestore));
         InOrder inOrder = Mockito.inOrder(installer);
 
         // Check that pending backup and restore for the same package mutually destroyed each other.
+        assertTrue(helper.commitPendingBackupAndRestoreForUser(37, dataWithRecentRestore));
         assertEquals(-1, wasRecentlyRestored.getPendingBackups().indexOf(37));
         assertNull(wasRecentlyRestored.getRestoreInfo(37));
 
         // Check that backup was performed.
+        assertTrue(helper.commitPendingBackupAndRestoreForUser(37, dataWithPendingBackup));
         inOrder.verify(installer).snapshotAppData(eq("com.foo"), eq(37), eq(101),
                 eq(Installer.FLAG_STORAGE_CE));
         assertEquals(-1, pendingBackup.getPendingBackups().indexOf(37));
         assertEquals(53, pendingBackup.getCeSnapshotInodes().get(37));
 
-        // Check that changed returns correct Rollback.
-        assertEquals(3, changed.size());
-        assertTrue(changed.contains(dataWithPendingBackup));
-        assertTrue(changed.contains(dataWithRecentRestore));
-        assertTrue(changed.contains(dataForRestore));
-
         // Check that restore was performed.
+        assertTrue(helper.commitPendingBackupAndRestoreForUser(37, dataForRestore));
         inOrder.verify(installer).restoreAppDataSnapshot(
                 eq("com.abc"), eq(57) /* appId */, eq("seInfo"), eq(37) /* userId */,
                 eq(17239) /* rollbackId */, eq(Installer.FLAG_STORAGE_CE));
@@ -279,15 +270,4 @@
 
         inOrder.verifyNoMoreInteractions();
     }
-
-    @Test
-    public void snapshotAddDataSavesSnapshottedUsersToInfo() {
-        Installer installer = mock(Installer.class);
-        AppDataRollbackHelper helper = new AppDataRollbackHelper(installer);
-
-        PackageRollbackInfo info = createPackageRollbackInfo("com.foo.bar");
-        helper.snapshotAppData(5, info, new int[]{10, 11});
-
-        assertArrayEquals(info.getSnapshottedUsers().toArray(), new int[]{10, 11});
-    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/rollback/RollbackStoreTest.java b/services/tests/servicestests/src/com/android/server/rollback/RollbackStoreTest.java
new file mode 100644
index 0000000..ee3b15a
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/rollback/RollbackStoreTest.java
@@ -0,0 +1,318 @@
+/*
+ * Copyright (C) 2019 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.rollback;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.pm.VersionedPackage;
+import android.content.rollback.PackageRollbackInfo;
+import android.util.IntArray;
+import android.util.SparseLongArray;
+
+import com.google.common.truth.Correspondence;
+
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.io.File;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+@RunWith(JUnit4.class)
+public class RollbackStoreTest {
+
+    private static final int ID = 123;
+
+    private static final Correspondence<VersionedPackage, VersionedPackage> VER_PKG_CORR =
+            new Correspondence<VersionedPackage, VersionedPackage>() {
+                @Override
+                public boolean compare(VersionedPackage a, VersionedPackage b) {
+                    if (a == null || b == null) {
+                        return a == b;
+                    }
+                    return a.getLongVersionCode() == b.getLongVersionCode()
+                            && Objects.equals(a.getPackageName(), b.getPackageName());
+                }
+
+                @Override
+                public String toString() {
+                    return "is the same as";
+                }
+            };
+
+    private static final Correspondence<PackageRollbackInfo.RestoreInfo,
+            PackageRollbackInfo.RestoreInfo>
+            RESTORE_INFO_CORR =
+            new Correspondence<PackageRollbackInfo.RestoreInfo, PackageRollbackInfo.RestoreInfo>() {
+                @Override
+                public boolean compare(PackageRollbackInfo.RestoreInfo a,
+                        PackageRollbackInfo.RestoreInfo b) {
+                    if (a == null || b == null) {
+                        return a == b;
+                    }
+                    return a.userId == b.userId
+                            && a.appId == b.appId
+                            && Objects.equals(a.seInfo, b.seInfo);
+                }
+
+                @Override
+                public String toString() {
+                    return "is the same as";
+                }
+            };
+
+    private static final String JSON_ROLLBACK = "{'info':{'rollbackId':123,'packages':"
+            + "[{'versionRolledBackFrom':{'packageName':'blah','longVersionCode':55},"
+            + "'versionRolledBackTo':{'packageName':'blah1','longVersionCode':50},'pendingBackups':"
+            + "[59,1245,124544],'pendingRestores':[{'userId':498,'appId':32322,'seInfo':'wombles'},"
+            + "{'userId':-895,'appId':1,'seInfo':'pingu'}],'isApex':false,'installedUsers':"
+            + "[498468432,1111,98464],'ceSnapshotInodes':[{'userId':1,'ceSnapshotInode':-6},"
+            + "{'userId':2222,'ceSnapshotInode':81641654445},{'userId':546546,"
+            + "'ceSnapshotInode':345689375}]},{'versionRolledBackFrom':{'packageName':'chips',"
+            + "'longVersionCode':28},'versionRolledBackTo':{'packageName':'com.chips.test',"
+            + "'longVersionCode':48},'pendingBackups':[5],'pendingRestores':[{'userId':18,"
+            + "'appId':-12,'seInfo':''}],'isApex':false,'installedUsers':[55,79],"
+            + "'ceSnapshotInodes':[]}],'isStaged':false,'causePackages':[{'packageName':'hello',"
+            + "'longVersionCode':23},{'packageName':'something','longVersionCode':999}],"
+            + "'committedSessionId':45654465},'timestamp':'2019-10-01T12:29:08.855Z',"
+            + "'stagedSessionId':-1,'state':'enabling','apkSessionId':-1,"
+            + "'restoreUserDataInProgress':true}";
+
+    @Rule
+    public TemporaryFolder mFolder = new TemporaryFolder();
+
+    private File mRollbackDir;
+
+    private RollbackStore mRollbackStore;
+
+    @Before
+    public void setUp() throws Exception {
+        mRollbackStore = new RollbackStore(mFolder.getRoot());
+        mRollbackDir = mFolder.newFolder(ID + "");
+        mFolder.newFile("rollback.json");
+    }
+
+    @Test
+    public void createNonStaged() {
+        Rollback rollback = mRollbackStore.createNonStagedRollback(ID);
+
+        assertThat(rollback.getBackupDir().getAbsolutePath())
+                .isEqualTo(mFolder.getRoot().getAbsolutePath() + "/" + ID);
+
+        assertThat(rollback.isStaged()).isFalse();
+        assertThat(rollback.info.getRollbackId()).isEqualTo(ID);
+        assertThat(rollback.info.getPackages()).isEmpty();
+        assertThat(rollback.isEnabling()).isTrue();
+    }
+
+    @Test
+    public void createStaged() {
+        Rollback rollback = mRollbackStore.createStagedRollback(ID, 897);
+
+        assertThat(rollback.getBackupDir().getAbsolutePath())
+                .isEqualTo(mFolder.getRoot().getAbsolutePath() + "/" + ID);
+
+        assertThat(rollback.isStaged()).isTrue();
+        assertThat(rollback.getStagedSessionId()).isEqualTo(897);
+
+        assertThat(rollback.info.getRollbackId()).isEqualTo(ID);
+        assertThat(rollback.info.getPackages()).isEmpty();
+        assertThat(rollback.isEnabling()).isTrue();
+    }
+
+    @Test
+    public void saveAndLoadRollback() {
+        Rollback origRb = mRollbackStore.createNonStagedRollback(ID);
+
+        origRb.setRestoreUserDataInProgress(true);
+        origRb.info.getCausePackages().add(new VersionedPackage("com.made.up", 2));
+        origRb.info.getCausePackages().add(new VersionedPackage("com.pack.age", 99));
+        origRb.info.setCommittedSessionId(123456);
+
+        PackageRollbackInfo pkgInfo1 =
+                new PackageRollbackInfo(new VersionedPackage("com.made.up", 18),
+                        new VersionedPackage("com.something.else", 5), new IntArray(),
+                        new ArrayList<>(), false, new IntArray(), new SparseLongArray());
+        pkgInfo1.getPendingBackups().add(8);
+        pkgInfo1.getPendingBackups().add(888);
+        pkgInfo1.getPendingBackups().add(88885);
+        pkgInfo1.getCeSnapshotInodes().put(12, 424);
+        pkgInfo1.getCeSnapshotInodes().put(222772, 10000000000L);
+        pkgInfo1.getCeSnapshotInodes().put(10, -67);
+
+        pkgInfo1.getPendingRestores().add(
+                new PackageRollbackInfo.RestoreInfo(4980, 3442322, "seInfo"));
+        pkgInfo1.getPendingRestores().add(
+                new PackageRollbackInfo.RestoreInfo(-89, 15, "otherSeInfo"));
+
+        pkgInfo1.getSnapshottedUsers().add(11);
+        pkgInfo1.getSnapshottedUsers().add(1);
+        pkgInfo1.getSnapshottedUsers().add(0);
+
+        PackageRollbackInfo pkgInfo2 = new PackageRollbackInfo(
+                new VersionedPackage("another.package", 2),
+                new VersionedPackage("com.test.ing", 48888), new IntArray(), new ArrayList<>(),
+                false, new IntArray(), new SparseLongArray());
+        pkgInfo2.getPendingBackups().add(57);
+
+        pkgInfo2.getPendingRestores().add(
+                new PackageRollbackInfo.RestoreInfo(180, -120, ""));
+
+        origRb.info.getPackages().add(pkgInfo1);
+        origRb.info.getPackages().add(pkgInfo2);
+
+        RollbackStore.saveRollback(origRb);
+
+        List<Rollback> loadedRollbacks = mRollbackStore.loadRollbacks();
+        assertThat(loadedRollbacks).hasSize(1);
+        Rollback loadedRb = loadedRollbacks.get(0);
+
+        assertRollbacksAreEquivalent(loadedRb, origRb);
+    }
+
+    @Test
+    public void loadFromJson() throws Exception {
+        Rollback expectedRb = mRollbackStore.createNonStagedRollback(ID);
+
+        expectedRb.setTimestamp(Instant.parse("2019-10-01T12:29:08.855Z"));
+        expectedRb.setRestoreUserDataInProgress(true);
+        expectedRb.info.getCausePackages().add(new VersionedPackage("hello", 23));
+        expectedRb.info.getCausePackages().add(new VersionedPackage("something", 999));
+        expectedRb.info.setCommittedSessionId(45654465);
+
+        PackageRollbackInfo pkgInfo1 = new PackageRollbackInfo(new VersionedPackage("blah", 55),
+                new VersionedPackage("blah1", 50), new IntArray(), new ArrayList<>(),
+                false, new IntArray(), new SparseLongArray());
+        pkgInfo1.getPendingBackups().add(59);
+        pkgInfo1.getPendingBackups().add(1245);
+        pkgInfo1.getPendingBackups().add(124544);
+        pkgInfo1.getCeSnapshotInodes().put(546546, 345689375);
+        pkgInfo1.getCeSnapshotInodes().put(2222, 81641654445L);
+        pkgInfo1.getCeSnapshotInodes().put(1, -6);
+
+        pkgInfo1.getPendingRestores().add(
+                new PackageRollbackInfo.RestoreInfo(498, 32322, "wombles"));
+        pkgInfo1.getPendingRestores().add(
+                new PackageRollbackInfo.RestoreInfo(-895, 1, "pingu"));
+
+        pkgInfo1.getSnapshottedUsers().add(498468432);
+        pkgInfo1.getSnapshottedUsers().add(1111);
+        pkgInfo1.getSnapshottedUsers().add(98464);
+
+        PackageRollbackInfo pkgInfo2 = new PackageRollbackInfo(new VersionedPackage("chips", 28),
+                new VersionedPackage("com.chips.test", 48), new IntArray(), new ArrayList<>(),
+                false, new IntArray(), new SparseLongArray());
+        pkgInfo2.getPendingBackups().add(5);
+
+        pkgInfo2.getPendingRestores().add(
+                new PackageRollbackInfo.RestoreInfo(18, -12, ""));
+
+        pkgInfo2.getSnapshottedUsers().add(55);
+        pkgInfo2.getSnapshottedUsers().add(79);
+
+        expectedRb.info.getPackages().add(pkgInfo1);
+        expectedRb.info.getPackages().add(pkgInfo2);
+
+        Rollback parsedRb = RollbackStore.rollbackFromJson(
+                new JSONObject(JSON_ROLLBACK), expectedRb.getBackupDir());
+
+        assertRollbacksAreEquivalent(parsedRb, expectedRb);
+    }
+
+    @Test
+    public void saveAndDelete() {
+        Rollback rollback = mRollbackStore.createNonStagedRollback(ID);
+
+        RollbackStore.saveRollback(rollback);
+
+        File expectedFile = new File(mRollbackDir.getAbsolutePath() + "/rollback.json");
+
+        assertThat(expectedFile.exists()).isTrue();
+
+        RollbackStore.deleteRollback(rollback);
+
+        assertThat(expectedFile.exists()).isFalse();
+    }
+
+    private void assertRollbacksAreEquivalent(Rollback b, Rollback a) {
+        assertThat(b.info.getRollbackId()).isEqualTo(ID);
+
+        assertThat(b.getBackupDir()).isEqualTo(a.getBackupDir());
+
+        assertThat(b.isRestoreUserDataInProgress())
+                .isEqualTo(a.isRestoreUserDataInProgress());
+
+        assertThat(b.getTimestamp()).isEqualTo(a.getTimestamp());
+
+        assertThat(b.isEnabling()).isEqualTo(a.isEnabling());
+        assertThat(b.isAvailable()).isEqualTo(a.isAvailable());
+        assertThat(b.isCommitted()).isEqualTo(a.isCommitted());
+
+        assertThat(b.isStaged()).isEqualTo(a.isStaged());
+
+        assertThat(b.getApexPackageNames())
+                .containsExactlyElementsIn(a.getApexPackageNames());
+
+        assertThat(b.getStagedSessionId()).isEqualTo(a.getStagedSessionId());
+
+        assertThat(b.info.getCommittedSessionId()).isEqualTo(a.info.getCommittedSessionId());
+
+        assertThat(b.info.getCausePackages()).comparingElementsUsing(VER_PKG_CORR)
+                .containsExactlyElementsIn(a.info.getCausePackages());
+
+        assertThat(b.info.getPackages()).hasSize(a.info.getPackages().size());
+
+        for (int i = 0; i < b.info.getPackages().size(); i++) {
+            assertPackageRollbacksAreEquivalent(
+                    b.info.getPackages().get(i), a.info.getPackages().get(i));
+        }
+    }
+
+    private void assertPackageRollbacksAreEquivalent(PackageRollbackInfo b, PackageRollbackInfo a) {
+        assertThat(b.getPackageName()).isEqualTo(a.getPackageName());
+
+        assertThat(b.getVersionRolledBackFrom().getLongVersionCode())
+                .isEqualTo(a.getVersionRolledBackFrom().getLongVersionCode());
+        assertThat(b.getVersionRolledBackFrom().getPackageName())
+                .isEqualTo(a.getVersionRolledBackFrom().getPackageName());
+
+        assertThat(b.getVersionRolledBackTo().getLongVersionCode())
+                .isEqualTo(a.getVersionRolledBackTo().getLongVersionCode());
+        assertThat(b.getVersionRolledBackTo().getPackageName())
+                .isEqualTo(a.getVersionRolledBackTo().getPackageName());
+
+        assertThat(b.getPendingBackups().toArray()).isEqualTo(a.getPendingBackups().toArray());
+
+        assertThat(b.getPendingRestores()).comparingElementsUsing(RESTORE_INFO_CORR)
+                .containsExactlyElementsIn(a.getPendingRestores());
+
+        assertThat(b.isApex()).isEqualTo(a.isApex());
+
+        assertThat(b.getSnapshottedUsers().toArray()).isEqualTo(a.getSnapshottedUsers().toArray());
+
+        assertThat(b.getCeSnapshotInodes().toString())
+                .isEqualTo(a.getCeSnapshotInodes().toString());
+    }
+
+}
diff --git a/services/tests/servicestests/src/com/android/server/rollback/RollbackUnitTest.java b/services/tests/servicestests/src/com/android/server/rollback/RollbackUnitTest.java
index d27f1c7..151b6e2 100644
--- a/services/tests/servicestests/src/com/android/server/rollback/RollbackUnitTest.java
+++ b/services/tests/servicestests/src/com/android/server/rollback/RollbackUnitTest.java
@@ -18,15 +18,48 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import android.content.pm.VersionedPackage;
+import android.content.rollback.PackageRollbackInfo;
+import android.util.IntArray;
+import android.util.SparseLongArray;
+
+import com.google.common.collect.Range;
+
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.JUnit4;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 
 import java.io.File;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
 
 @RunWith(JUnit4.class)
 public class RollbackUnitTest {
 
+    private static final String PKG_1 = "test.testpackage.pkg1";
+    private static final String PKG_2 = "test.testpackage.pkg2";
+    private static final String PKG_3 = "com.blah.hello.three";
+    private static final String PKG_4 = "com.something.4pack";
+
+    @Mock private AppDataRollbackHelper mMockDataHelper;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+    }
+
     @Test
     public void newEmptyStagedRollbackDefaults() {
         int rollbackId = 123;
@@ -54,24 +87,229 @@
     }
 
     @Test
-    public void rollbackStateChanges() {
+    public void rollbackMadeAvailable() {
         Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
 
         assertThat(rollback.isEnabling()).isTrue();
         assertThat(rollback.isAvailable()).isFalse();
         assertThat(rollback.isCommitted()).isFalse();
 
-        rollback.setAvailable();
+        Instant availableTime = Instant.now();
+        rollback.makeAvailable();
 
         assertThat(rollback.isEnabling()).isFalse();
         assertThat(rollback.isAvailable()).isTrue();
         assertThat(rollback.isCommitted()).isFalse();
 
-        rollback.setCommitted();
-
-        assertThat(rollback.isEnabling()).isFalse();
-        assertThat(rollback.isAvailable()).isFalse();
-        assertThat(rollback.isCommitted()).isTrue();
+        assertThat(rollback.getTimestamp()).isIn(Range.closed(availableTime, Instant.now()));
     }
 
+    @Test
+    public void deletedRollbackCannotBeMadeAvailable() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+
+        rollback.delete(mMockDataHelper);
+
+        assertThat(rollback.isDeleted()).isTrue();
+
+        rollback.makeAvailable();
+
+        assertThat(rollback.isAvailable()).isFalse();
+        assertThat(rollback.isDeleted()).isTrue();
+    }
+
+    @Test
+    public void getPackageNamesAllAndJustApex() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 11, true);
+        PackageRollbackInfo pkgInfo3 = newPkgInfoFor(PKG_3, 19, 1, false);
+        PackageRollbackInfo pkgInfo4 = newPkgInfoFor(PKG_4, 12, 1, true);
+
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2, pkgInfo3, pkgInfo4));
+
+        assertThat(rollback.getPackageNames()).containsExactly(PKG_1, PKG_2, PKG_3, PKG_4);
+        assertThat(rollback.getApexPackageNames()).containsExactly(PKG_2, PKG_4);
+    }
+
+    @Test
+    public void includesPackagesAfterEnable() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        PackageRollbackInfo pkgInfo3 = newPkgInfoFor(PKG_3, 157, 156, false);
+        PackageRollbackInfo pkgInfo4 = newPkgInfoFor(PKG_4, 99, 1, true);
+
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2, pkgInfo3, pkgInfo4));
+
+        assertThat(rollback.includesPackage(PKG_2)).isTrue();
+        assertThat(rollback.includesPackage(PKG_3)).isTrue();
+        assertThat(rollback.includesPackage("com.something.else")).isFalse();
+
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_1, 12)).isFalse();
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_1, 1)).isTrue();
+
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_2, 18)).isFalse();
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_2, 12)).isTrue();
+
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_3, 157)).isFalse();
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_3, 156)).isTrue();
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_3, 15)).isTrue();
+
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_4, 99)).isFalse();
+        assertThat(rollback.includesPackageWithDifferentVersion(PKG_4, 100)).isTrue();
+    }
+
+    @Test
+    public void snapshotWhenEnabling() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2));
+
+        assertThat(rollback.isEnabling()).isTrue();
+
+        int[] userIds = {4, 77};
+        rollback.snapshotUserData(PKG_2, userIds, mMockDataHelper);
+
+        // Data is snapshotted for the specified package.
+        verify(mMockDataHelper).snapshotAppData(eq(123), pkgRollbackInfoFor(PKG_2), eq(userIds));
+        verify(mMockDataHelper, never())
+                .snapshotAppData(anyInt(), pkgRollbackInfoFor(PKG_1), any());
+    }
+
+    @Test
+    public void snapshotWhenAvailable() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2));
+
+        rollback.makeAvailable();
+
+        assertThat(rollback.isAvailable()).isTrue();
+
+        int[] userIds = {4, 77};
+        rollback.snapshotUserData(PKG_2, userIds, mMockDataHelper);
+
+        // No data is snapshotted as rollback was not in the enabling state.
+        verify(mMockDataHelper, never())
+                .snapshotAppData(anyInt(), pkgRollbackInfoFor(PKG_1), any());
+        verify(mMockDataHelper, never())
+                .snapshotAppData(anyInt(), pkgRollbackInfoFor(PKG_2), any());
+    }
+
+    @Test
+    public void snapshotWhenDeleted() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2));
+
+        rollback.delete(mMockDataHelper);
+
+        assertThat(rollback.isDeleted()).isTrue();
+
+        int[] userIds = {4, 77};
+        rollback.snapshotUserData(PKG_2, userIds, mMockDataHelper);
+
+        // No data is snapshotted as rollback was not in the enabling state.
+        verify(mMockDataHelper, never())
+                .snapshotAppData(anyInt(), pkgRollbackInfoFor(PKG_1), any());
+        verify(mMockDataHelper, never())
+                .snapshotAppData(anyInt(), pkgRollbackInfoFor(PKG_2), any());
+    }
+
+    @Test
+    public void snapshotThenDelete() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2));
+
+        int[] userIds = {12, 18};
+        rollback.snapshotUserData(PKG_2, userIds, mMockDataHelper);
+
+        verify(mMockDataHelper).snapshotAppData(eq(123), pkgRollbackInfoFor(PKG_2), eq(userIds));
+
+        rollback.delete(mMockDataHelper);
+
+        verify(mMockDataHelper).destroyAppDataSnapshot(eq(123), pkgRollbackInfoFor(PKG_2), eq(12));
+        verify(mMockDataHelper).destroyAppDataSnapshot(eq(123), pkgRollbackInfoFor(PKG_2), eq(18));
+
+        assertThat(rollback.isDeleted()).isTrue();
+    }
+
+    @Test
+    public void restoreUserDataDoesNothingIfNotInProgress() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2));
+
+        assertThat(rollback.isRestoreUserDataInProgress()).isFalse();
+
+        assertThat(rollback.restoreUserDataForPackageIfInProgress(
+                PKG_1, new int[] { 5 }, 333, "", mMockDataHelper)).isFalse();
+
+        verify(mMockDataHelper, never()).restoreAppData(anyInt(), any(), anyInt(), anyInt(), any());
+    }
+
+    @Test
+    public void restoreUserDataDoesNothingIfPackageNotFound() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2));
+
+        rollback.setRestoreUserDataInProgress(true);
+        assertThat(rollback.isRestoreUserDataInProgress()).isTrue();
+
+        assertThat(rollback.restoreUserDataForPackageIfInProgress(
+                PKG_3, new int[] { 5 }, 333, "", mMockDataHelper)).isFalse();
+
+        verify(mMockDataHelper, never()).restoreAppData(anyInt(), any(), anyInt(), anyInt(), any());
+    }
+
+    @Test
+    public void restoreUserDataRestoresIfInProgressAndPackageFound() {
+        Rollback rollback = new Rollback(123, new File("/test/testing"), -1);
+        PackageRollbackInfo pkgInfo1 = newPkgInfoFor(PKG_1, 12, 10, false);
+        PackageRollbackInfo pkgInfo2 = newPkgInfoFor(PKG_2, 18, 12, true);
+        rollback.info.getPackages().addAll(Arrays.asList(pkgInfo1, pkgInfo2));
+
+        rollback.setRestoreUserDataInProgress(true);
+        assertThat(rollback.isRestoreUserDataInProgress()).isTrue();
+
+        assertThat(rollback.restoreUserDataForPackageIfInProgress(
+                PKG_1, new int[] { 5, 7 }, 333, "blah", mMockDataHelper)).isTrue();
+
+        verify(mMockDataHelper).restoreAppData(123, pkgInfo1, 5, 333, "blah");
+        verify(mMockDataHelper).restoreAppData(123, pkgInfo1, 7, 333, "blah");
+    }
+
+    private static PackageRollbackInfo newPkgInfoFor(
+            String packageName, long fromVersion, long toVersion, boolean isApex) {
+        return new PackageRollbackInfo(new VersionedPackage(packageName, fromVersion),
+                new VersionedPackage(packageName, toVersion),
+                new IntArray(), new ArrayList<>(), isApex, new IntArray(), new SparseLongArray());
+    }
+
+    private static class PackageRollbackInfoForPackage implements
+            ArgumentMatcher<PackageRollbackInfo> {
+        private final String mPkg;
+
+        PackageRollbackInfoForPackage(String pkg) {
+            mPkg = pkg;
+        }
+
+        @Override
+        public boolean matches(PackageRollbackInfo pkgRollbackInfo) {
+            return pkgRollbackInfo.getPackageName().equals(mPkg);
+        }
+    }
+
+    private static PackageRollbackInfo pkgRollbackInfoFor(String pkg) {
+        return argThat(new PackageRollbackInfoForPackage(pkg));
+    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java b/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java
index 4fb533f..d1ac19c 100644
--- a/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java
+++ b/services/tests/servicestests/src/com/android/server/stats/ProcfsMemoryUtilTest.java
@@ -15,14 +15,19 @@
  */
 package com.android.server.stats;
 
-import static com.android.server.stats.ProcfsMemoryUtil.parseVmHWMFromStatus;
+import static com.android.server.stats.ProcfsMemoryUtil.parseCmdline;
+import static com.android.server.stats.ProcfsMemoryUtil.parseMemorySnapshotFromStatus;
 
 import static com.google.common.truth.Truth.assertThat;
 
 import androidx.test.filters.SmallTest;
 
+import com.android.server.stats.ProcfsMemoryUtil.MemorySnapshot;
+
 import org.junit.Test;
 
+import java.io.ByteArrayOutputStream;
+
 /**
  * Build/Install/Run:
  *  atest FrameworksServicesTests:ProcfsMemoryUtilTest
@@ -77,17 +82,60 @@
             + "nonvoluntary_ctxt_switches:\t104\n";
 
     @Test
-    public void testParseVmHWMFromStatus_parsesCorrectValue() {
-        assertThat(parseVmHWMFromStatus(STATUS_CONTENTS)).isEqualTo(137668);
+    public void testParseMemorySnapshotFromStatus_parsesCorrectValue() {
+        MemorySnapshot snapshot = parseMemorySnapshotFromStatus(STATUS_CONTENTS);
+        assertThat(snapshot.uid).isEqualTo(10083);
+        assertThat(snapshot.rssHighWaterMarkInKilobytes).isEqualTo(137668);
+        assertThat(snapshot.rssInKilobytes).isEqualTo(126776);
+        assertThat(snapshot.anonRssInKilobytes).isEqualTo(37860);
+        assertThat(snapshot.swapInKilobytes).isEqualTo(22);
     }
 
     @Test
-    public void testParseVmHWMFromStatus_invalidValue() {
-        assertThat(parseVmHWMFromStatus("test\nVmHWM: x0x0x\ntest")).isEqualTo(0);
+    public void testParseMemorySnapshotFromStatus_invalidValue() {
+        MemorySnapshot snapshot =
+                parseMemorySnapshotFromStatus("test\nVmRSS:\tx0x0x\nVmSwap:\t1 kB\ntest");
+        assertThat(snapshot).isNull();
     }
 
     @Test
-    public void testParseVmHWMFromStatus_emptyContents() {
-        assertThat(parseVmHWMFromStatus("")).isEqualTo(0);
+    public void testParseMemorySnapshotFromStatus_emptyContents() {
+        MemorySnapshot snapshot = parseMemorySnapshotFromStatus("");
+        assertThat(snapshot).isNull();
+    }
+
+    @Test
+    public void testParseCmdline_invalidValue() {
+        byte[] nothing = new byte[] {0x00, 0x74, 0x65, 0x73, 0x74}; // \0test
+
+        assertThat(parseCmdline(bytesToString(nothing))).isEmpty();
+    }
+
+    @Test
+    public void testParseCmdline_correctValue_noNullBytes() {
+        assertThat(parseCmdline("com.google.app")).isEqualTo("com.google.app");
+    }
+
+    @Test
+    public void testParseCmdline_correctValue_withNullBytes() {
+        byte[] trailing = new byte[] {0x74, 0x65, 0x73, 0x74, 0x00, 0x00, 0x00}; // test\0\0\0
+
+        assertThat(parseCmdline(bytesToString(trailing))).isEqualTo("test");
+
+        // test\0\0test
+        byte[] inside = new byte[] {0x74, 0x65, 0x73, 0x74, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74};
+
+        assertThat(parseCmdline(bytesToString(trailing))).isEqualTo("test");
+    }
+
+    @Test
+    public void testParseCmdline_emptyContents() {
+        assertThat(parseCmdline("")).isEmpty();
+    }
+
+    private static String bytesToString(byte[] bytes) {
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        output.write(bytes, 0, bytes.length);
+        return output.toString();
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/utils/TraceBufferTest.java b/services/tests/servicestests/src/com/android/server/utils/TraceBufferTest.java
new file mode 100644
index 0000000..09b75e7
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/utils/TraceBufferTest.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (C) 2019 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.utils;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import android.content.Context;
+import android.platform.test.annotations.Presubmit;
+import android.util.proto.ProtoOutputStream;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.internal.util.Preconditions;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+
+
+/**
+ * Test class for {@link TraceBuffer}.
+ *
+ * Build/Install/Run:
+ *  atest WmTests:TraceBufferTest
+ */
+@SmallTest
+@Presubmit
+public class TraceBufferTest {
+    private File mFile;
+    private TraceBuffer mBuffer;
+
+    @Before
+    public void setUp() throws Exception {
+        final Context testContext = getInstrumentation().getContext();
+        mFile = testContext.getFileStreamPath("tracing_test.dat");
+        mFile.delete();
+
+        mBuffer = new TraceBuffer(10);
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        mFile.delete();
+    }
+
+    @Test
+    public void test_addItem() {
+        ProtoOutputStream toWrite = getDummy(1);
+        final int objectSize = toWrite.getRawSize();
+        mBuffer.setCapacity(objectSize);
+        mBuffer.resetBuffer();
+
+        Preconditions.checkArgument(mBuffer.size() == 0);
+
+        mBuffer.add(toWrite);
+
+        assertEquals("Item was not added to the buffer", 1, mBuffer.size());
+        assertEquals("Total buffer getSize differs from inserted object",
+                mBuffer.getBufferSize(), objectSize);
+        assertEquals("Available buffer space does not match used one", 0,
+                mBuffer.getAvailableSpace());
+    }
+
+    @Test
+    public void test_addItemMustOverwriteOne() {
+        ProtoOutputStream toWrite1 = getDummy(1);
+        ProtoOutputStream toWrite2 = getDummy(2);
+        ProtoOutputStream toWrite3 = getDummy(3);
+        final int objectSize = toWrite1.getRawSize();
+        final int bufferCapacity = objectSize * 2 + 1;
+        mBuffer.setCapacity(bufferCapacity);
+        mBuffer.resetBuffer();
+
+        mBuffer.add(toWrite1);
+        byte[] toWrite1Bytes = toWrite1.getBytes();
+        assertTrue("First element should be in the list",
+                mBuffer.contains(toWrite1Bytes));
+
+        mBuffer.add(toWrite2);
+        byte[] toWrite2Bytes = toWrite2.getBytes();
+        assertTrue("First element should be in the list",
+                mBuffer.contains(toWrite1Bytes));
+        assertTrue("Second element should be in the list",
+                mBuffer.contains(toWrite2Bytes));
+
+        mBuffer.add(toWrite3);
+        byte[] toWrite3Bytes = toWrite3.getBytes();
+        assertTrue("First element should not be in the list",
+                !mBuffer.contains(toWrite1Bytes));
+        assertTrue("Second element should be in the list",
+                mBuffer.contains(toWrite2Bytes));
+        assertTrue("Third element should be in the list",
+                mBuffer.contains(toWrite3Bytes));
+        assertEquals("Buffer should have 2 elements", 2, mBuffer.size());
+        assertEquals(String.format("Buffer is full, used space should be %d", bufferCapacity),
+                mBuffer.getBufferSize(), bufferCapacity - 1);
+        assertEquals(" Buffer is full, available space should be 0", 1,
+                mBuffer.getAvailableSpace());
+    }
+
+    @Test
+    public void test_addItemMustOverwriteMultiple() {
+        ProtoOutputStream toWriteSmall1 = getDummy(1);
+        ProtoOutputStream toWriteSmall2 = getDummy(2);
+        final int objectSize = toWriteSmall1.getRawSize();
+        final int bufferCapacity = objectSize * 2;
+        mBuffer.setCapacity(bufferCapacity);
+        mBuffer.resetBuffer();
+
+        ProtoOutputStream toWriteBig = new ProtoOutputStream();
+        toWriteBig.write(MAGIC_NUMBER, 1);
+        toWriteBig.write(MAGIC_NUMBER, 2);
+
+        mBuffer.add(toWriteSmall1);
+        byte[] toWriteSmall1Bytes = toWriteSmall1.getBytes();
+        assertTrue("First element should be in the list",
+                mBuffer.contains(toWriteSmall1Bytes));
+
+        mBuffer.add(toWriteSmall2);
+        byte[] toWriteSmall2Bytes = toWriteSmall2.getBytes();
+        assertTrue("First element should be in the list",
+                mBuffer.contains(toWriteSmall1Bytes));
+        assertTrue("Second element should be in the list",
+                mBuffer.contains(toWriteSmall2Bytes));
+
+        mBuffer.add(toWriteBig);
+        byte[] toWriteBigBytes = toWriteBig.getBytes();
+        assertTrue("Third element should overwrite all others",
+                !mBuffer.contains(toWriteSmall1Bytes));
+        assertTrue("Third element should overwrite all others",
+                !mBuffer.contains(toWriteSmall2Bytes));
+        assertTrue("Third element should overwrite all others",
+                mBuffer.contains(toWriteBigBytes));
+
+        assertEquals(" Buffer should have only 1 big element", 1, mBuffer.size());
+        assertEquals(String.format(" Buffer is full, used space should be %d", bufferCapacity),
+                mBuffer.getBufferSize(), bufferCapacity);
+        assertEquals(" Buffer is full, available space should be 0", 0,
+                mBuffer.getAvailableSpace());
+    }
+
+    @Test
+    public void test_startResetsBuffer() {
+        ProtoOutputStream toWrite = getDummy(1);
+        mBuffer.resetBuffer();
+        Preconditions.checkArgument(mBuffer.size() == 0);
+
+        mBuffer.add(toWrite);
+        assertEquals("Item was not added to the buffer", 1, mBuffer.size());
+        mBuffer.resetBuffer();
+        assertEquals("Buffer should be empty after reset", 0, mBuffer.size());
+        assertEquals("Buffer size should be 0 after reset", 0, mBuffer.getBufferSize());
+    }
+
+    private ProtoOutputStream getDummy(int value) {
+        ProtoOutputStream toWrite = new ProtoOutputStream();
+        toWrite.write(MAGIC_NUMBER, value);
+        toWrite.flush();
+
+        return toWrite;
+    }
+
+}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
index f652c5a..721641a 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/GroupHelperTest.java
@@ -15,6 +15,8 @@
  */
 package com.android.server.notification;
 
+import static com.android.server.notification.GroupHelper.AUTOGROUP_KEY;
+
 import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertNotNull;
 
@@ -155,6 +157,196 @@
     }
 
     @Test
+    public void testAutoGroupCount_addingNoGroupSBN() {
+        final String pkg = "package";
+        ArrayList<StatusBarNotification>  notifications = new ArrayList<>();
+        for (int i = 0; i < AUTOGROUP_AT_COUNT + 1; i++) {
+            notifications.add(getSbn(pkg, i, String.valueOf(i), UserHandle.SYSTEM));
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            sbn.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+            sbn.setOverrideGroupKey(AUTOGROUP_KEY);
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            mGroupHelper.onNotificationPosted(sbn, true);
+        }
+
+        verify(mCallback, times(AUTOGROUP_AT_COUNT + 1))
+            .updateAutogroupSummary(anyString(), eq(true));
+
+        int userId = UserHandle.SYSTEM.getIdentifier();
+        assertEquals(mGroupHelper.getOngoingGroupCount(
+                userId, pkg, AUTOGROUP_KEY), AUTOGROUP_AT_COUNT + 1);
+    }
+
+    @Test
+    public void testAutoGroupCount_UpdateNotification() {
+        final String pkg = "package";
+        ArrayList<StatusBarNotification>  notifications = new ArrayList<>();
+        for (int i = 0; i < AUTOGROUP_AT_COUNT + 1; i++) {
+            notifications.add(getSbn(pkg, i, String.valueOf(i), UserHandle.SYSTEM));
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            sbn.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+            sbn.setOverrideGroupKey(AUTOGROUP_KEY);
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            mGroupHelper.onNotificationPosted(sbn, true);
+        }
+
+        notifications.get(0).getNotification().flags &= ~Notification.FLAG_ONGOING_EVENT;
+
+        mGroupHelper.onNotificationUpdated(notifications.get(0), true);
+
+        verify(mCallback, times(AUTOGROUP_AT_COUNT + 2))
+                .updateAutogroupSummary(anyString(), eq(true));
+
+        int userId = UserHandle.SYSTEM.getIdentifier();
+        assertEquals(mGroupHelper.getOngoingGroupCount(
+                userId, pkg, AUTOGROUP_KEY), AUTOGROUP_AT_COUNT);
+    }
+
+    @Test
+    public void testAutoGroupCount_UpdateNotificationAfterChanges() {
+        final String pkg = "package";
+        ArrayList<StatusBarNotification>  notifications = new ArrayList<>();
+        for (int i = 0; i < AUTOGROUP_AT_COUNT + 1; i++) {
+            notifications.add(getSbn(pkg, i, String.valueOf(i), UserHandle.SYSTEM));
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            sbn.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+            sbn.setOverrideGroupKey(AUTOGROUP_KEY);
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            mGroupHelper.onNotificationPosted(sbn, true);
+        }
+
+        notifications.get(0).getNotification().flags &= ~Notification.FLAG_ONGOING_EVENT;
+
+        mGroupHelper.onNotificationUpdated(notifications.get(0), true);
+
+        notifications.get(0).getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+
+        mGroupHelper.onNotificationUpdated(notifications.get(0), true);
+
+        verify(mCallback, times(AUTOGROUP_AT_COUNT + 3))
+                .updateAutogroupSummary(anyString(), eq(true));
+
+        int userId = UserHandle.SYSTEM.getIdentifier();
+        assertEquals(mGroupHelper.getOngoingGroupCount(
+                userId, pkg, AUTOGROUP_KEY), AUTOGROUP_AT_COUNT + 1);
+    }
+
+    @Test
+    public void testAutoGroupCount_RemoveNotification() {
+        final String pkg = "package";
+        ArrayList<StatusBarNotification>  notifications = new ArrayList<>();
+        for (int i = 0; i < AUTOGROUP_AT_COUNT + 1; i++) {
+            notifications.add(getSbn(pkg, i, String.valueOf(i), UserHandle.SYSTEM));
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            sbn.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+            sbn.setOverrideGroupKey(AUTOGROUP_KEY);
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            mGroupHelper.onNotificationPosted(sbn, true);
+        }
+
+        mGroupHelper.onNotificationRemoved(notifications.get(0));
+
+        verify(mCallback, times(AUTOGROUP_AT_COUNT + 2))
+                .updateAutogroupSummary(anyString(), eq(true));
+
+        int userId = UserHandle.SYSTEM.getIdentifier();
+        assertEquals(mGroupHelper.getOngoingGroupCount(
+                userId, pkg, AUTOGROUP_KEY), AUTOGROUP_AT_COUNT);
+    }
+
+
+    @Test
+    public void testAutoGroupCount_UpdateToNoneOngoingNotification() {
+        final String pkg = "package";
+        ArrayList<StatusBarNotification>  notifications = new ArrayList<>();
+        for (int i = 0; i < AUTOGROUP_AT_COUNT + 1; i++) {
+            notifications.add(getSbn(pkg, i, String.valueOf(i), UserHandle.SYSTEM));
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            sbn.setOverrideGroupKey(AUTOGROUP_KEY);
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            mGroupHelper.onNotificationPosted(sbn, true);
+        }
+
+        notifications.get(0).getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+        mGroupHelper.onNotificationUpdated(notifications.get(0), true);
+
+        verify(mCallback, times(1))
+                .updateAutogroupSummary(anyString(), eq(true));
+
+        int userId = UserHandle.SYSTEM.getIdentifier();
+        assertEquals(mGroupHelper.getOngoingGroupCount(
+                userId, pkg, AUTOGROUP_KEY), 1);
+    }
+
+    @Test
+    public void testAutoGroupCount_AddOneOngoingNotification() {
+        final String pkg = "package";
+        ArrayList<StatusBarNotification>  notifications = new ArrayList<>();
+        for (int i = 0; i < AUTOGROUP_AT_COUNT + 1; i++) {
+            notifications.add(getSbn(pkg, i, String.valueOf(i), UserHandle.SYSTEM));
+        }
+        StatusBarNotification sbn = notifications.get(0);
+        sbn.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+        sbn.setOverrideGroupKey(AUTOGROUP_KEY);
+
+
+        for (StatusBarNotification current: notifications) {
+            mGroupHelper.onNotificationPosted(current, true);
+        }
+
+        verify(mCallback, times(1))
+                .updateAutogroupSummary(anyString(), eq(true));
+
+        int userId = UserHandle.SYSTEM.getIdentifier();
+        assertEquals(mGroupHelper.getOngoingGroupCount(
+                userId, pkg, AUTOGROUP_KEY), 1);
+    }
+
+    @Test
+    public void testAutoGroupCount_UpdateNoneOngoing() {
+        final String pkg = "package";
+        ArrayList<StatusBarNotification>  notifications = new ArrayList<>();
+        for (int i = 0; i < AUTOGROUP_AT_COUNT + 1; i++) {
+            notifications.add(getSbn(pkg, i, String.valueOf(i), UserHandle.SYSTEM));
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            sbn.setOverrideGroupKey(AUTOGROUP_KEY);
+        }
+
+        for (StatusBarNotification sbn: notifications) {
+            mGroupHelper.onNotificationPosted(sbn, true);
+        }
+
+        verify(mCallback, times(0))
+                .updateAutogroupSummary(anyString(), eq(true));
+
+        int userId = UserHandle.SYSTEM.getIdentifier();
+        assertEquals(mGroupHelper.getOngoingGroupCount(userId, pkg, AUTOGROUP_KEY), 0);
+    }
+
+
+    @Test
     public void testDropToZeroRemoveGroup() throws Exception {
         final String pkg = "package";
         List<StatusBarNotification> posted = new ArrayList<>();
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
old mode 100644
new mode 100755
index 2de8d05..4ea2fc0
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -44,6 +44,7 @@
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.os.Build.VERSION_CODES.O_MR1;
 import static android.os.Build.VERSION_CODES.P;
+import static android.os.UserHandle.USER_SYSTEM;
 import static android.service.notification.Adjustment.KEY_IMPORTANCE;
 import static android.service.notification.Adjustment.KEY_USER_SENTIMENT;
 import static android.service.notification.NotificationListenerService.Ranking.USER_SENTIMENT_NEGATIVE;
@@ -129,6 +130,7 @@
 import android.testing.TestableLooper;
 import android.testing.TestableLooper.RunWithLooper;
 import android.testing.TestablePermissions;
+import android.testing.TestableResources;
 import android.text.Html;
 import android.util.ArrayMap;
 import android.util.ArraySet;
@@ -1180,6 +1182,36 @@
     }
 
     @Test
+    public void testAutobundledSummary_notificationAdded() {
+        NotificationRecord summary =
+                generateNotificationRecord(mTestNotificationChannel, 0, "pkg", true);
+        summary.getNotification().flags |= Notification.FLAG_AUTOGROUP_SUMMARY;
+        mService.addNotification(summary);
+        mService.mSummaryByGroupKey.put("pkg", summary);
+        mService.mAutobundledSummaries.put(0, new ArrayMap<>());
+        mService.mAutobundledSummaries.get(0).put("pkg", summary.getKey());
+        mService.updateAutobundledSummaryFlags(0, "pkg", true);
+
+        assertTrue(summary.sbn.isOngoing());
+    }
+
+    @Test
+    public void testAutobundledSummary_notificationRemoved() {
+        NotificationRecord summary =
+                generateNotificationRecord(mTestNotificationChannel, 0, "pkg", true);
+        summary.getNotification().flags |= Notification.FLAG_AUTOGROUP_SUMMARY;
+        summary.getNotification().flags |= Notification.FLAG_ONGOING_EVENT;
+        mService.addNotification(summary);
+        mService.mAutobundledSummaries.put(0, new ArrayMap<>());
+        mService.mAutobundledSummaries.get(0).put("pkg", summary.getKey());
+        mService.mSummaryByGroupKey.put("pkg", summary);
+
+        mService.updateAutobundledSummaryFlags(0, "pkg", false);
+
+        assertFalse(summary.sbn.isOngoing());
+    }
+
+    @Test
     public void testCancelAllNotifications_IgnoreForegroundService() throws Exception {
         final StatusBarNotification sbn = generateNotificationRecord(null).sbn;
         sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
@@ -3278,7 +3310,7 @@
     @Test
     public void testRestore() throws Exception {
         int systemChecks = mService.countSystemChecks;
-        mBinderService.applyRestore(null, UserHandle.USER_SYSTEM);
+        mBinderService.applyRestore(null, USER_SYSTEM);
         assertEquals(1, mService.countSystemChecks - systemChecks);
     }
 
@@ -3347,7 +3379,7 @@
         reset(mUgmInternal);
         when(mUgmInternal.newUriPermissionOwner(any())).thenReturn(new Binder());
         mService.updateUriPermissions(recordA, null, mContext.getPackageName(),
-                UserHandle.USER_SYSTEM);
+                USER_SYSTEM);
         verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
                 eq(message1.getDataUri()), anyInt(), anyInt(), anyInt());
         verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
@@ -3363,21 +3395,21 @@
         // Update means we drop access to first
         reset(mUgmInternal);
         mService.updateUriPermissions(recordB, recordA, mContext.getPackageName(),
-                UserHandle.USER_SYSTEM);
+                USER_SYSTEM);
         verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(any(),
                 eq(message1.getDataUri()), anyInt(), anyInt());
 
         // Update back means we grant access to first again
         reset(mUgm);
         mService.updateUriPermissions(recordA, recordB, mContext.getPackageName(),
-                UserHandle.USER_SYSTEM);
+                USER_SYSTEM);
         verify(mUgm, times(1)).grantUriPermissionFromOwner(any(), anyInt(), any(),
                 eq(message1.getDataUri()), anyInt(), anyInt(), anyInt());
 
         // And update to empty means we drop everything
         reset(mUgmInternal);
         mService.updateUriPermissions(null, recordB, mContext.getPackageName(),
-                UserHandle.USER_SYSTEM);
+                USER_SYSTEM);
         verify(mUgmInternal, times(1)).revokeUriPermissionFromOwner(any(), eq(null),
                 anyInt(), anyInt());
     }
@@ -3864,7 +3896,9 @@
         mService.simulatePackageDistractionBroadcast(
                 PackageManager.RESTRICTION_HIDE_NOTIFICATIONS, new String[] {"a", "b"});
         ArgumentCaptor<List<NotificationRecord>> captorHide = ArgumentCaptor.forClass(List.class);
-        verify(mListeners, times(2)).notifyHiddenLocked(captorHide.capture());
+
+        // should be called only once.
+        verify(mListeners, times(1)).notifyHiddenLocked(captorHide.capture());
         assertEquals(2, captorHide.getValue().size());
         assertEquals("a", captorHide.getValue().get(0).sbn.getPackageName());
         assertEquals("b", captorHide.getValue().get(1).sbn.getPackageName());
@@ -3873,7 +3907,9 @@
         mService.simulatePackageDistractionBroadcast(
                 PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS, new String[] {"a", "b"});
         ArgumentCaptor<List<NotificationRecord>> captorUnhide = ArgumentCaptor.forClass(List.class);
-        verify(mListeners, times(2)).notifyUnhiddenLocked(captorUnhide.capture());
+
+        // should be called only once.
+        verify(mListeners, times(1)).notifyUnhiddenLocked(captorUnhide.capture());
         assertEquals(2, captorUnhide.getValue().size());
         assertEquals("a", captorUnhide.getValue().get(0).sbn.getPackageName());
         assertEquals("b", captorUnhide.getValue().get(1).sbn.getPackageName());
@@ -4073,7 +4109,7 @@
     public void testIsCallerInstantApp_userAllNotification() throws Exception {
         ApplicationInfo info = new ApplicationInfo();
         info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
-        when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(UserHandle.USER_SYSTEM)))
+        when(mPackageManager.getApplicationInfo(anyString(), anyInt(), eq(USER_SYSTEM)))
                 .thenReturn(info);
         when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{"any"});
 
@@ -5662,4 +5698,33 @@
         StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
         assertEquals(1, notifsAfter.length);
     }
+
+    @Test
+    public void testLoadDefaultApprovedServices_emptyResources() {
+        TestableResources tr = mContext.getOrCreateTestableResources();
+        tr.addOverride(com.android.internal.R.string.config_defaultListenerAccessPackages, "");
+        tr.addOverride(com.android.internal.R.string.config_defaultDndAccessPackages, "");
+        tr.addOverride(com.android.internal.R.string.config_defaultAssistantAccessComponent, "");
+        setDefaultAssistantInDeviceConfig("");
+
+        mService.loadDefaultApprovedServices(USER_SYSTEM);
+
+        verify(mListeners, never()).addDefaultComponentOrPackage(anyString());
+        verify(mConditionProviders, never()).addDefaultComponentOrPackage(anyString());
+        verify(mAssistants, never()).addDefaultComponentOrPackage(anyString());
+    }
+
+    @Test
+    public void testLoadDefaultApprovedServices_dnd() {
+        TestableResources tr = mContext.getOrCreateTestableResources();
+        tr.addOverride(com.android.internal.R.string.config_defaultDndAccessPackages, "test");
+        when(mListeners.queryPackageForServices(anyString(), anyInt(), anyInt()))
+                .thenReturn(new ArraySet<>());
+
+        mService.loadDefaultApprovedServices(USER_SYSTEM);
+
+        verify(mConditionProviders, times(1)).addDefaultComponentOrPackage("test");
+    }
+
+    // TODO: add tests for the rest of the non-empty cases
 }
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
index dcab78e..3d87223 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeConfigTest.java
@@ -16,9 +16,10 @@
 
 package com.android.server.notification;
 
-import static junit.framework.Assert.assertEquals;
+import static junit.framework.TestCase.assertEquals;
 import static junit.framework.TestCase.assertFalse;
 import static junit.framework.TestCase.assertNull;
+import static junit.framework.TestCase.assertTrue;
 
 import android.app.NotificationManager.Policy;
 import android.content.ComponentName;
@@ -52,18 +53,18 @@
 
     @Test
     public void testPriorityOnlyMutingAllNotifications() {
-        ZenModeConfig config = getMutedNotificationsConfig();
-        assertEquals(true, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
+        ZenModeConfig config = getMutedRingerConfig();
+        assertTrue(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
 
         config.allowReminders = true;
-        assertEquals(false, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
+        assertFalse(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
         config.allowReminders = false;
 
         config.areChannelsBypassingDnd = true;
-        assertEquals(false, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
+        assertFalse(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
         config.areChannelsBypassingDnd = false;
 
-        assertEquals(true, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
+        assertTrue(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
     }
 
     @Test
@@ -106,26 +107,26 @@
     @Test
     public void testPriorityOnlyMutingAll() {
         ZenModeConfig config = getMutedAllConfig();
-        assertEquals(true, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
-        assertEquals(true, ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
+        assertTrue(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
+        assertTrue(ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
 
         config.allowReminders = true;
-        assertEquals(false, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
-        assertEquals(false, ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
+        assertFalse(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
+        assertFalse(ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
         config.allowReminders = false;
 
         config.areChannelsBypassingDnd = true;
-        assertEquals(false, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
-        assertEquals(false, ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
+        assertFalse(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
+        assertFalse(ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
         config.areChannelsBypassingDnd = false;
 
         config.allowAlarms = true;
-        assertEquals(true, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
-        assertEquals(false, ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
+        assertTrue(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
+        assertFalse(ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
         config.allowAlarms = false;
 
-        assertEquals(true, ZenModeConfig.areAllPriorityOnlyNotificationZenSoundsMuted(config));
-        assertEquals(true, ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
+        assertTrue(ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(config));
+        assertTrue(ZenModeConfig.areAllZenBehaviorSoundsMuted(config));
     }
 
     @Test
@@ -200,14 +201,14 @@
         assertEquals(rule.zenMode, fromXml.zenMode);
     }
 
-    private ZenModeConfig getMutedNotificationsConfig() {
+    private ZenModeConfig getMutedRingerConfig() {
         ZenModeConfig config = new ZenModeConfig();
-        // Allow alarms, media, and system
+        // Allow alarms, media
         config.allowAlarms = true;
         config.allowMedia = true;
-        config.allowSystem = true;
 
-        // All notification sounds are not allowed
+        // All sounds that respect the ringer are not allowed
+        config.allowSystem = false;
         config.allowCalls = false;
         config.allowRepeatCallers = false;
         config.allowMessages = false;
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 8936450..99771b9 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
@@ -487,7 +487,6 @@
     public void testRingerAffectedStreamsPriorityOnly() {
         // in priority only mode:
         // ringtone, notification and system streams are affected by ringer mode
-        // UNLESS ringer is muted due to all the other priority only dnd sounds being muted
         mZenModeHelperSpy.mConfig.allowAlarms = true;
         mZenModeHelperSpy.mConfig.allowReminders = true;
         mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
@@ -503,8 +502,9 @@
         assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_ALARM)) == 0);
         assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_MUSIC)) == 0);
 
-        // special case: if ringer is muted (since all notification sounds cannot bypass)
-        // then system stream is not affected by ringer mode
+        // even when ringer is muted (since all ringer sounds cannot bypass DND),
+        // system stream is still affected by ringer mode
+        mZenModeHelperSpy.mConfig.allowSystem = false;
         mZenModeHelperSpy.mConfig.allowReminders = false;
         mZenModeHelperSpy.mConfig.allowCalls = false;
         mZenModeHelperSpy.mConfig.allowMessages = false;
@@ -519,7 +519,7 @@
         assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_NOTIFICATION))
                 != 0);
         assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_SYSTEM))
-                == 0);
+                != 0);
         assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_ALARM)) == 0);
         assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_MUSIC)) == 0);
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
index 6c78f6f..fff3221 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
@@ -24,11 +24,9 @@
 import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
 import static android.content.pm.ActivityInfo.FLAG_SHOW_WHEN_LOCKED;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.clearInvocations;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.never;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.reset;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
 import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
 
@@ -49,6 +47,7 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.concurrent.CompletableFuture;
@@ -62,6 +61,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class ActivityDisplayTests extends ActivityTestsBase {
 
     @Test
@@ -142,30 +142,24 @@
         // Create a display which supports system decoration and allows reparenting stacks to
         // another display when the display is removed.
         final ActivityDisplay display = createNewActivityDisplay();
-        spyOn(display);
         doReturn(false).when(display).shouldDestroyContentOnRemove();
         doReturn(true).when(display).supportsSystemDecorations();
         mRootActivityContainer.addChild(display, ActivityDisplay.POSITION_TOP);
 
         // Put home stack on the display.
-        final ActivityStack homeStack = display.createStack(
-                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
-        final TaskRecord task = new TaskBuilder(mSupervisor).setStack(homeStack).build();
-        new ActivityBuilder(mService).setTask(task).build();
-        display.removeChild(homeStack);
-        final ActivityStack spiedHomeStack = spy(homeStack);
-        display.addChild(spiedHomeStack, ActivityDisplay.POSITION_TOP);
-        reset(spiedHomeStack);
+        final ActivityStack homeStack = new StackBuilder(mRootActivityContainer)
+                .setDisplay(display).setActivityType(ACTIVITY_TYPE_HOME).build();
 
         // Put a finishing standard activity which will be reparented.
         final ActivityStack stack = createFullscreenStackWithSimpleActivityAt(display);
         stack.topRunningActivityLocked().makeFinishingLocked();
 
+        clearInvocations(homeStack);
         display.remove();
 
         // The removed display should have no focused stack and its home stack should never resume.
         assertNull(display.getFocusedStack());
-        verify(spiedHomeStack, never()).resumeTopActivityUncheckedLocked(any(), any());
+        verify(homeStack, never()).resumeTopActivityUncheckedLocked(any(), any());
     }
 
     private ActivityStack createFullscreenStackWithSimpleActivityAt(ActivityDisplay display) {
@@ -323,24 +317,24 @@
         doAnswer(invocation -> {
             display.positionChildAtTop(stack3, false);
             return true;
-        }).when(mSupervisor).removeTaskByIdLocked(eq(task4.taskId), anyBoolean(), anyBoolean(),
+        }).when(mSupervisor).removeTaskByIdLocked(eq(task4.mTaskId), anyBoolean(), anyBoolean(),
                 any());
 
         // Removing stacks from the display while removing stacks.
         doAnswer(invocation -> {
             display.removeChild(stack2);
             return true;
-        }).when(mSupervisor).removeTaskByIdLocked(eq(task2.taskId), anyBoolean(), anyBoolean(),
+        }).when(mSupervisor).removeTaskByIdLocked(eq(task2.mTaskId), anyBoolean(), anyBoolean(),
                 any());
 
         runnable.run();
-        verify(mSupervisor).removeTaskByIdLocked(eq(task4.taskId), anyBoolean(), anyBoolean(),
+        verify(mSupervisor).removeTaskByIdLocked(eq(task4.mTaskId), anyBoolean(), anyBoolean(),
                 any());
-        verify(mSupervisor).removeTaskByIdLocked(eq(task3.taskId), anyBoolean(), anyBoolean(),
+        verify(mSupervisor).removeTaskByIdLocked(eq(task3.mTaskId), anyBoolean(), anyBoolean(),
                 any());
-        verify(mSupervisor).removeTaskByIdLocked(eq(task2.taskId), anyBoolean(), anyBoolean(),
+        verify(mSupervisor).removeTaskByIdLocked(eq(task2.mTaskId), anyBoolean(), anyBoolean(),
                 any());
-        verify(mSupervisor).removeTaskByIdLocked(eq(task1.taskId), anyBoolean(), anyBoolean(),
+        verify(mSupervisor).removeTaskByIdLocked(eq(task1.mTaskId), anyBoolean(), anyBoolean(),
                 any());
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 30c8eb3..bf1508a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -103,8 +103,6 @@
 import org.junit.runner.RunWith;
 import org.mockito.invocation.InvocationOnMock;
 
-import java.util.concurrent.TimeUnit;
-
 /**
  * Tests for the {@link ActivityRecord} class.
  *
@@ -289,22 +287,6 @@
     }
 
     @Test
-    public void testNotifiesSeqIncrementToAppToken() {
-        final Configuration appWindowTokenRequestedOrientation = mock(Configuration.class);
-        mActivity.mAppWindowToken = mock(AppWindowToken.class);
-        doReturn(appWindowTokenRequestedOrientation).when(mActivity.mAppWindowToken)
-                .getRequestedOverrideConfiguration();
-
-        final Configuration newConfig = new Configuration();
-        newConfig.orientation = ORIENTATION_PORTRAIT;
-
-        final int prevSeq = mActivity.getMergedOverrideConfiguration().seq;
-        mActivity.onRequestedOverrideConfigurationChanged(newConfig);
-        assertEquals(prevSeq + 1, appWindowTokenRequestedOrientation.seq);
-        verify(mActivity.mAppWindowToken).onMergedOverrideConfigurationChanged();
-    }
-
-    @Test
     public void testSetsRelaunchReason_NotDragResizing() {
         mActivity.setState(ActivityStack.ActivityState.RESUMED, "Testing");
 
@@ -521,7 +503,7 @@
                 anyInt() /* height */, any() /* displayCutout */, any() /* outInsets */);
 
         doReturn(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
-                .when(mActivity.mAppWindowToken).getOrientationIgnoreVisibility();
+                .when(mActivity).getRequestedOrientation();
         mActivity.info.resizeMode = RESIZE_MODE_UNRESIZEABLE;
         mActivity.info.minAspectRatio = mActivity.info.maxAspectRatio = 1;
         ensureActivityConfiguration();
@@ -573,7 +555,7 @@
         // Move the non-resizable activity to the new display.
         mStack.reparent(newDisplay, true /* onTop */, false /* displayRemoved */);
 
-        assertEquals(originalBounds, mActivity.getBounds());
+        assertEquals(originalBounds, mActivity.getWindowConfiguration().getBounds());
         assertEquals(originalDpi, mActivity.getConfiguration().densityDpi);
         assertTrue(mActivity.inSizeCompatMode());
     }
@@ -581,7 +563,7 @@
     @Test
     public void testSizeCompatMode_FixedScreenBoundsWhenDisplaySizeChanged() {
         setupDisplayContentForCompatDisplayInsets();
-        when(mActivity.mAppWindowToken.getOrientationIgnoreVisibility()).thenReturn(
+        when(mActivity.getRequestedOrientation()).thenReturn(
                 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
         mTask.getWindowConfiguration().setAppBounds(mStack.getDisplay().getBounds());
         mTask.getConfiguration().orientation = ORIENTATION_PORTRAIT;
@@ -594,7 +576,7 @@
         setupDisplayAndParentSize(1000, 2000);
         ensureActivityConfiguration();
 
-        assertEquals(originalBounds, mActivity.getBounds());
+        assertEquals(originalBounds, mActivity.getWindowConfiguration().getBounds());
         assertTrue(mActivity.inSizeCompatMode());
     }
 
@@ -629,7 +611,7 @@
         mActivity.visible = false;
         mActivity.app.setReportedProcState(ActivityManager.PROCESS_STATE_CACHED_ACTIVITY);
         // Make the parent bounds to be different so the activity is in size compatibility mode.
-        mTask.getWindowConfiguration().setAppBounds(new Rect(0, 0, 600, 1200));
+        setupDisplayAndParentSize(600, 1200);
 
         // Simulate the display changes orientation.
         doReturn(ActivityInfo.CONFIG_SCREEN_SIZE | CONFIG_ORIENTATION
@@ -646,7 +628,7 @@
         // The override configuration should be reset and the activity's process will be killed.
         assertFalse(mActivity.inSizeCompatMode());
         verify(mActivity).restartProcessIfVisible();
-        mLockRule.runWithScissors(mService.mH, () -> { }, TimeUnit.SECONDS.toMillis(3));
+        waitHandlerIdle(mService.mH);
         verify(mService.mAmInternal).killProcess(
                 eq(mActivity.app.mName), eq(mActivity.app.mUid), anyString());
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
index 9583b8ac..1eeca91 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
@@ -44,6 +44,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link ActivityStackSupervisor} class.
@@ -53,6 +54,7 @@
  */
 @MediumTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class ActivityStackSupervisorTests extends ActivityTestsBase {
     private ActivityStack mFullscreenStack;
 
@@ -79,32 +81,28 @@
     /**
      * Ensures that waiting results are notified of launches.
      */
-    @SuppressWarnings("SynchronizeOnNonFinalField")
     @Test
     public void testReportWaitingActivityLaunchedIfNeeded() {
         final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true)
                 .setStack(mFullscreenStack).build();
 
-        // #notifyAll will be called on the ActivityManagerService. we must hold the object lock
-        // when this happens.
-        synchronized (mService.mGlobalLock) {
-            final WaitResult taskToFrontWait = new WaitResult();
-            mSupervisor.mWaitingActivityLaunched.add(taskToFrontWait);
-            mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity, START_TASK_TO_FRONT);
+        final WaitResult taskToFrontWait = new WaitResult();
+        mSupervisor.mWaitingActivityLaunched.add(taskToFrontWait);
+        // #notifyAll will be called on the ActivityTaskManagerService#mGlobalLock. The lock is hold
+        // implicitly by WindowManagerGlobalLockRule.
+        mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity, START_TASK_TO_FRONT);
 
-            assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty();
-            assertEquals(taskToFrontWait.result, START_TASK_TO_FRONT);
-            assertNull(taskToFrontWait.who);
+        assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty();
+        assertEquals(taskToFrontWait.result, START_TASK_TO_FRONT);
+        assertNull(taskToFrontWait.who);
 
-            final WaitResult deliverToTopWait = new WaitResult();
-            mSupervisor.mWaitingActivityLaunched.add(deliverToTopWait);
-            mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity,
-                    START_DELIVERED_TO_TOP);
+        final WaitResult deliverToTopWait = new WaitResult();
+        mSupervisor.mWaitingActivityLaunched.add(deliverToTopWait);
+        mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity, START_DELIVERED_TO_TOP);
 
-            assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty();
-            assertEquals(deliverToTopWait.result, START_DELIVERED_TO_TOP);
-            assertEquals(deliverToTopWait.who, firstActivity.mActivityComponent);
-        }
+        assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty();
+        assertEquals(deliverToTopWait.result, START_DELIVERED_TO_TOP);
+        assertEquals(deliverToTopWait.who, firstActivity.mActivityComponent);
     }
 
     /**
@@ -129,7 +127,7 @@
         mSupervisor.handleNonResizableTaskIfNeeded(task, newDisplay.getWindowingMode(),
                 newDisplay.mDisplayId, stack);
         // The top activity is unresizable, so it should notify the activity is forced resizing.
-        verify(taskChangeNotifier).notifyActivityForcedResizable(eq(task.taskId),
+        verify(taskChangeNotifier).notifyActivityForcedResizable(eq(task.mTaskId),
                 eq(FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY),
                 eq(unresizableActivity.packageName));
         reset(taskChangeNotifier);
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
index 2a8b4c8..c2a05c24 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
@@ -67,6 +67,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link ActivityStack} class.
@@ -76,6 +77,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class ActivityStackTests extends ActivityTestsBase {
     private ActivityDisplay mDefaultDisplay;
     private ActivityStack mStack;
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
index a7bbe6e..11aac3c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
@@ -38,6 +38,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.util.Random;
 
@@ -49,6 +50,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class ActivityStartControllerTests extends ActivityTestsBase {
     private ActivityStartController mController;
     private Factory mFactory;
@@ -71,7 +73,9 @@
         final Random random = new Random();
 
         final ActivityRecord activity = new ActivityBuilder(mService).build();
-        final ActivityRecord source = new ActivityBuilder(mService).build();
+        final ActivityRecord source = new ActivityBuilder(mService)
+                .setCreateTask(true)
+                .build();
         final int startFlags = random.nextInt();
         final ActivityStack stack = mService.mRootActivityContainer.getDefaultDisplay().createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStartInterceptorTest.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStartInterceptorTest.java
index 350114c..4165052 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStartInterceptorTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStartInterceptorTest.java
@@ -175,8 +175,8 @@
                 .build();
         when(mPackageManagerInternal.getSuspendingPackage(TEST_PACKAGE_NAME, TEST_USER_ID))
                 .thenReturn(suspendingPackage);
-        when(mPackageManagerInternal.getSuspendedDialogInfo(TEST_PACKAGE_NAME, TEST_USER_ID))
-                .thenReturn(dialogInfo);
+        when(mPackageManagerInternal.getSuspendedDialogInfo(TEST_PACKAGE_NAME, suspendingPackage,
+                TEST_USER_ID)).thenReturn(dialogInfo);
         // THEN calling intercept returns true
         assertTrue(mInterceptor.intercept(null, null, mAInfo, null, null, 0, 0, null));
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
index 1f672c0..8a9423a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
@@ -57,6 +57,7 @@
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyObject;
+import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
 
 import android.app.ActivityOptions;
@@ -368,6 +369,7 @@
         doReturn(false).when(mockPackageManager).isPermissionsReviewRequired(any(), anyInt());
         doNothing().when(mockPackageManager).grantImplicitAccess(
                 anyInt(), any(), anyInt(), anyInt());
+        doNothing().when(mockPackageManager).notifyPackageUse(anyString(), anyInt());
 
         final Intent intent = new Intent();
         intent.addFlags(launchFlags);
@@ -753,7 +755,7 @@
                 false /* mockGetLaunchStack */);
 
         // Create a secondary display at bottom.
-        final TestActivityDisplay secondaryDisplay = spy(createNewActivityDisplay());
+        final TestActivityDisplay secondaryDisplay = createNewActivityDisplay();
         mRootActivityContainer.addChild(secondaryDisplay, POSITION_BOTTOM);
         final ActivityStack stack = secondaryDisplay.createStack(WINDOWING_MODE_FULLSCREEN,
                 ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -791,7 +793,7 @@
                 false /* mockGetLaunchStack */);
 
         // Create a secondary display with an activity.
-        final TestActivityDisplay secondaryDisplay = spy(createNewActivityDisplay());
+        final TestActivityDisplay secondaryDisplay = createNewActivityDisplay();
         mRootActivityContainer.addChild(secondaryDisplay, POSITION_TOP);
         final ActivityRecord singleTaskActivity = createSingleTaskActivityOn(
                 secondaryDisplay.createStack(WINDOWING_MODE_FULLSCREEN,
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
index 297aa7e..7b7e6e7 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java
@@ -26,6 +26,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link ActivityTaskManagerService} class.
@@ -34,6 +35,7 @@
  *  atest WmTests:ActivityTaskManagerServiceTests
  */
 @MediumTest
+@RunWith(WindowTestRunner.class)
 public class ActivityTaskManagerServiceTests extends ActivityTestsBase {
 
     @Before
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
index d311dfc..77fbdcf 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
@@ -27,6 +27,7 @@
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyBoolean;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 
@@ -38,33 +39,21 @@
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.res.Configuration;
+import android.os.Build;
 import android.os.UserHandle;
 import android.service.voice.IVoiceInteractionSession;
-import android.testing.DexmakerShareClassLoaderRule;
+import android.util.Pair;
 import android.view.DisplayInfo;
 
 import com.android.server.AttributeCache;
 
 import org.junit.Before;
 import org.junit.BeforeClass;
-import org.junit.Rule;
 
 /**
  * A base class to handle common operations in activity related unit tests.
  */
-class ActivityTestsBase {
-
-    @Rule
-    public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
-            new DexmakerShareClassLoaderRule();
-
-    @Rule
-    public final SystemServicesTestRule mSystemServicesTestRule = new SystemServicesTestRule();
-
-    @WindowTestRunner.MethodWrapperRule
-    public final WindowManagerGlobalLockRule mLockRule =
-            new WindowManagerGlobalLockRule(mSystemServicesTestRule);
-
+class ActivityTestsBase extends SystemServiceTestsBase {
     final Context mContext = getInstrumentation().getTargetContext();
 
     ActivityTaskManagerService mService;
@@ -226,6 +215,23 @@
             return this;
         }
 
+        static Pair<Intent, ActivityInfo> createIntentAndActivityInfo() {
+            // TODO: Look into consolidating with dup. code in build() method below.
+            final int id = sCurrentActivityId++;
+            final ComponentName component = ComponentName.createRelative(
+                    DEFAULT_COMPONENT_PACKAGE_NAME, DEFAULT_COMPONENT_CLASS_NAME + id);
+
+            final Intent intent = new Intent();
+            intent.setComponent(component);
+
+            final ActivityInfo aInfo = new ActivityInfo();
+            aInfo.applicationInfo = new ApplicationInfo();
+            aInfo.applicationInfo.packageName = component.getPackageName();
+            aInfo.applicationInfo.targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT;
+            aInfo.packageName = component.getPackageName();
+            return new Pair<>(intent, aInfo);
+        }
+
         ActivityRecord build() {
             if (mComponent == null) {
                 final int id = sCurrentActivityId++;
@@ -271,12 +277,10 @@
             if (mTaskRecord != null) {
                 // fullscreen value is normally read from resources in ctor, so for testing we need
                 // to set it somewhere else since we can't mock resources.
-                activity.fullscreen = true;
+                doReturn(true).when(activity).occludesParent();
                 activity.setTask(mTaskRecord);
-                activity.createAppWindowToken();
-                spyOn(activity.mAppWindowToken);
                 // Make visible by default...
-                activity.mAppWindowToken.setHidden(false);
+                activity.setHidden(false);
             }
 
             final WindowProcessController wpc = new WindowProcessController(mService,
@@ -285,6 +289,8 @@
                     mock(WindowProcessListener.class));
             wpc.setThread(mock(IApplicationThread.class));
             activity.setProcess(wpc);
+            doReturn(wpc).when(mService).getProcessController(
+                    activity.processName, activity.info.applicationInfo.uid);
 
             // Resume top activities to make sure all other signals in the system are connected.
             mService.mRootActivityContainer.resumeFocusedStacksTopActivities();
@@ -378,9 +384,10 @@
             intent.setFlags(mFlags);
 
             final TaskRecord task = new TaskRecord(mSupervisor.mService, mTaskId, aInfo,
-                    intent /*intent*/, mVoiceSession, null /*_voiceInteractor*/);
+                    intent /*intent*/, mVoiceSession, null /*_voiceInteractor*/,
+                    null /*taskDescription*/);
             spyOn(task);
-            task.userId = mUserId;
+            task.mUserId = mUserId;
 
             if (mStack != null) {
                 mStack.moveToFront("test");
@@ -389,8 +396,6 @@
                 spyOn(task.mTask);
             }
 
-            task.touchActiveTime();
-
             return task;
         }
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java
index 629a954..650a911 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java
@@ -42,6 +42,7 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for change transitions
@@ -51,11 +52,12 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class AppChangeTransitionTests extends WindowTestsBase {
 
     private TaskStack mStack;
     private Task mTask;
-    private WindowTestUtils.TestAppWindowToken mToken;
+    private AppWindowToken mToken;
 
     public void setUpOnDisplay(DisplayContent dc) {
         mStack = createTaskStackOnDisplay(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, dc);
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java
index e71c8f4..605d520 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppTransitionControllerTest.java
@@ -36,6 +36,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Build/Install/Run:
@@ -43,6 +44,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class AppTransitionControllerTest extends WindowTestsBase {
 
     private AppTransitionController mAppTransitionController;
@@ -55,73 +57,63 @@
     @Test
     @FlakyTest(bugId = 131005232)
     public void testTranslucentOpen() {
-        synchronized (mWm.mGlobalLock) {
-            final AppWindowToken behind = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-            final AppWindowToken translucentOpening = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-            translucentOpening.setOccludesParent(false);
-            translucentOpening.setHidden(true);
-            mDisplayContent.mOpeningApps.add(behind);
-            mDisplayContent.mOpeningApps.add(translucentOpening);
-            assertEquals(WindowManager.TRANSIT_TRANSLUCENT_ACTIVITY_OPEN,
-                    mAppTransitionController.maybeUpdateTransitToTranslucentAnim(
-                            TRANSIT_TASK_OPEN));
-        }
+        final AppWindowToken behind = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
+        final AppWindowToken translucentOpening = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
+        translucentOpening.setOccludesParent(false);
+        translucentOpening.setHidden(true);
+        mDisplayContent.mOpeningApps.add(behind);
+        mDisplayContent.mOpeningApps.add(translucentOpening);
+        assertEquals(WindowManager.TRANSIT_TRANSLUCENT_ACTIVITY_OPEN,
+                mAppTransitionController.maybeUpdateTransitToTranslucentAnim(TRANSIT_TASK_OPEN));
     }
 
     @Test
     @FlakyTest(bugId = 131005232)
     public void testTranslucentClose() {
-        synchronized (mWm.mGlobalLock) {
-            final AppWindowToken behind = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-            final AppWindowToken translucentClosing = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-            translucentClosing.setOccludesParent(false);
-            mDisplayContent.mClosingApps.add(translucentClosing);
-            assertEquals(WindowManager.TRANSIT_TRANSLUCENT_ACTIVITY_CLOSE,
-                    mAppTransitionController.maybeUpdateTransitToTranslucentAnim(
-                            TRANSIT_TASK_CLOSE));
-        }
+        final AppWindowToken behind = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
+        final AppWindowToken translucentClosing = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
+        translucentClosing.setOccludesParent(false);
+        mDisplayContent.mClosingApps.add(translucentClosing);
+        assertEquals(WindowManager.TRANSIT_TRANSLUCENT_ACTIVITY_CLOSE,
+                mAppTransitionController.maybeUpdateTransitToTranslucentAnim(TRANSIT_TASK_CLOSE));
     }
 
     @Test
     @FlakyTest(bugId = 131005232)
     public void testChangeIsNotOverwritten() {
-        synchronized (mWm.mGlobalLock) {
-            final AppWindowToken behind = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-            final AppWindowToken translucentOpening = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-            translucentOpening.setOccludesParent(false);
-            translucentOpening.setHidden(true);
-            mDisplayContent.mOpeningApps.add(behind);
-            mDisplayContent.mOpeningApps.add(translucentOpening);
-            assertEquals(TRANSIT_TASK_CHANGE_WINDOWING_MODE,
-                    mAppTransitionController.maybeUpdateTransitToTranslucentAnim(
-                            TRANSIT_TASK_CHANGE_WINDOWING_MODE));
-        }
+        final AppWindowToken behind = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
+        final AppWindowToken translucentOpening = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
+        translucentOpening.setOccludesParent(false);
+        translucentOpening.setHidden(true);
+        mDisplayContent.mOpeningApps.add(behind);
+        mDisplayContent.mOpeningApps.add(translucentOpening);
+        assertEquals(TRANSIT_TASK_CHANGE_WINDOWING_MODE,
+                mAppTransitionController.maybeUpdateTransitToTranslucentAnim(
+                        TRANSIT_TASK_CHANGE_WINDOWING_MODE));
     }
 
     @Test
     @FlakyTest(bugId = 131005232)
     public void testTransitWithinTask() {
-        synchronized (mWm.mGlobalLock) {
-            final AppWindowToken opening = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD);
-            opening.setOccludesParent(false);
-            final AppWindowToken closing = createAppWindowToken(mDisplayContent,
-                    WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD);
-            closing.setOccludesParent(false);
-            Task task = opening.getTask();
-            mDisplayContent.mOpeningApps.add(opening);
-            mDisplayContent.mClosingApps.add(closing);
-            assertFalse(mAppTransitionController.isTransitWithinTask(TRANSIT_ACTIVITY_OPEN, task));
-            closing.getTask().removeChild(closing);
-            task.addChild(closing, 0);
-            assertTrue(mAppTransitionController.isTransitWithinTask(TRANSIT_ACTIVITY_OPEN, task));
-            assertFalse(mAppTransitionController.isTransitWithinTask(TRANSIT_TASK_OPEN, task));
-        }
+        final AppWindowToken opening = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD);
+        opening.setOccludesParent(false);
+        final AppWindowToken closing = createAppWindowToken(mDisplayContent,
+                WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD);
+        closing.setOccludesParent(false);
+        final Task task = opening.getTask();
+        mDisplayContent.mOpeningApps.add(opening);
+        mDisplayContent.mClosingApps.add(closing);
+        assertFalse(mAppTransitionController.isTransitWithinTask(TRANSIT_ACTIVITY_OPEN, task));
+        closing.getTask().removeChild(closing);
+        task.addChild(closing, 0);
+        assertTrue(mAppTransitionController.isTransitWithinTask(TRANSIT_ACTIVITY_OPEN, task));
+        assertFalse(mAppTransitionController.isTransitWithinTask(TRANSIT_TASK_OPEN, task));
     }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppTransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/AppTransitionTests.java
index 45e6890..72d9bd0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppTransitionTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppTransitionTests.java
@@ -31,7 +31,6 @@
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyBoolean;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -55,6 +54,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Test class for {@link AppTransition}.
@@ -64,16 +64,13 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class AppTransitionTests extends WindowTestsBase {
     private DisplayContent mDc;
 
     @Before
     public void setUp() throws Exception {
-        synchronized (mWm.mGlobalLock) {
-            // Hold the lock to protect the stubbing from being accessed by other threads.
-            spyOn(mWm.mRoot);
-            doNothing().when(mWm.mRoot).performSurfacePlacement(anyBoolean());
-        }
+        doNothing().when(mWm.mRoot).performSurfacePlacement(anyBoolean());
         mDc = mWm.getDefaultDisplayContentLocked();
     }
 
@@ -125,9 +122,9 @@
         final DisplayContent dc2 = createNewDisplay(Display.STATE_ON);
 
         // Create 2 app window tokens to represent 2 activity window.
-        final WindowTestUtils.TestAppWindowToken token1 = createTestAppWindowToken(dc1,
+        final AppWindowToken token1 = createTestAppWindowToken(dc1,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
-        final WindowTestUtils.TestAppWindowToken token2 = createTestAppWindowToken(dc2,
+        final AppWindowToken token2 = createTestAppWindowToken(dc2,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
 
         token1.allDrawn = true;
@@ -162,7 +159,7 @@
 
         final TaskStack stack1 = createTaskStackOnDisplay(dc1);
         final Task task1 = createTaskInStack(stack1, 0 /* userId */);
-        final WindowTestUtils.TestAppWindowToken token1 =
+        final AppWindowToken token1 =
                 WindowTestUtils.createTestAppWindowToken(dc1);
         task1.addChild(token1, 0);
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowThumbnailTest.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowThumbnailTest.java
index b8f8e21..aacdeb2 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppWindowThumbnailTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowThumbnailTest.java
@@ -17,8 +17,8 @@
 package com.android.server.wm;
 
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
-
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
+
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 
@@ -26,12 +26,12 @@
 import android.graphics.PixelFormat;
 import android.platform.test.annotations.Presubmit;
 import android.view.Surface;
-import android.view.SurfaceControl;
 
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Test class for {@link TaskSnapshotSurface}.
@@ -42,6 +42,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class AppWindowThumbnailTest extends WindowTestsBase {
     private AppWindowThumbnail buildThumbnail() {
         final GraphicBuffer buffer = GraphicBuffer.create(1, 1, PixelFormat.RGBA_8888,
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java
index 70d9b5f..66ba81d 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenAnimationTests.java
@@ -33,10 +33,9 @@
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SmallTest;
 
-import com.android.server.wm.WindowTestUtils.TestAppWindowToken;
-
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
@@ -50,9 +49,10 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class AppWindowTokenAnimationTests extends WindowTestsBase {
 
-    private TestAppWindowToken mToken;
+    private AppWindowToken mToken;
 
     @Mock
     private AnimationAdapter mSpec;
diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
index 1f634b1..2661735 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java
@@ -53,7 +53,6 @@
 import android.content.res.Configuration;
 import android.graphics.Rect;
 import android.platform.test.annotations.Presubmit;
-import android.view.Display;
 import android.view.Surface;
 import android.view.WindowManager;
 
@@ -62,6 +61,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.Mockito;
 
 /**
@@ -72,11 +72,12 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class AppWindowTokenTests extends WindowTestsBase {
 
     TaskStack mStack;
     Task mTask;
-    WindowTestUtils.TestAppWindowToken mToken;
+    AppWindowToken mToken;
 
     private final String mPackageName = getInstrumentation().getTargetContext().getPackageName();
 
@@ -92,7 +93,7 @@
     @Test
     @Presubmit
     public void testAddWindow_Order() {
-        assertEquals(0, mToken.getWindowsCount());
+        assertEquals(0, mToken.getChildCount());
 
         final WindowState win1 = createWindow(null, TYPE_APPLICATION, mToken, "win1");
         final WindowState startingWin = createWindow(null, TYPE_APPLICATION_STARTING, mToken,
@@ -101,17 +102,17 @@
         final WindowState win4 = createWindow(null, TYPE_APPLICATION, mToken, "win4");
 
         // Should not contain the windows that were added above.
-        assertEquals(4, mToken.getWindowsCount());
-        assertTrue(mToken.hasWindow(win1));
-        assertTrue(mToken.hasWindow(startingWin));
-        assertTrue(mToken.hasWindow(baseWin));
-        assertTrue(mToken.hasWindow(win4));
+        assertEquals(4, mToken.getChildCount());
+        assertTrue(mToken.mChildren.contains(win1));
+        assertTrue(mToken.mChildren.contains(startingWin));
+        assertTrue(mToken.mChildren.contains(baseWin));
+        assertTrue(mToken.mChildren.contains(win4));
 
         // The starting window should be on-top of all other windows.
-        assertEquals(startingWin, mToken.getLastChild());
+        assertEquals(startingWin, mToken.mChildren.peekLast());
 
         // The base application window should be below all other windows.
-        assertEquals(baseWin, mToken.getFirstChild());
+        assertEquals(baseWin, mToken.mChildren.peekFirst());
         mToken.removeImmediately();
     }
 
@@ -220,7 +221,7 @@
         containerBounds.set(0, 0, 600, 800);
         mToken.onConfigurationChanged(newParentConfig);
 
-        assertTrue(mToken.inSizeCompatMode());
+        assertTrue(mToken.hasSizeCompatBounds());
         assertEquals(containerAppBounds, mToken.getBounds());
         assertEquals((float) containerAppBounds.width() / fixedBounds.width(),
                 mToken.getSizeCompatScale(), 0.0001f /* delta */);
@@ -230,7 +231,7 @@
         containerBounds.set(containerAppBounds);
         mToken.onConfigurationChanged(newParentConfig);
 
-        assertTrue(mToken.inSizeCompatMode());
+        assertTrue(mToken.hasSizeCompatBounds());
         // Don't scale up, so the bounds keep the same as the fixed width.
         assertEquals(fixedBounds.width(), mToken.getBounds().width());
         // Assert the position is horizontal center.
@@ -242,7 +243,7 @@
         containerBounds.set(0, 0, 1200, 2000);
         mToken.onConfigurationChanged(newParentConfig);
         // Assert don't use fixed bounds because the region is enough.
-        assertFalse(mToken.inSizeCompatMode());
+        assertFalse(mToken.hasSizeCompatBounds());
     }
 
     @Test
@@ -323,41 +324,14 @@
     }
 
     @Test
-    public void testReportOrientationChangeOnVisibilityChange() {
-        synchronized (mWm.mGlobalLock) {
-            mToken.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
+    public void testReportOrientationChange() {
+        mToken.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
-            mDisplayContent.getDisplayRotation().setFixedToUserRotation(
-                    DisplayRotation.FIXED_TO_USER_ROTATION_ENABLED);
+        mDisplayContent.getDisplayRotation().setFixedToUserRotation(
+                DisplayRotation.FIXED_TO_USER_ROTATION_ENABLED);
 
-            doReturn(Configuration.ORIENTATION_LANDSCAPE).when(mToken.mActivityRecord)
-                    .getRequestedConfigurationOrientation();
-
-            mTask.mTaskRecord = Mockito.mock(TaskRecord.class, RETURNS_DEEP_STUBS);
-            mToken.commitVisibility(null, false /* visible */, TRANSIT_UNSET,
-                    true /* performLayout */, false /* isVoiceInteraction */);
-        }
-
-        verify(mTask.mTaskRecord).onConfigurationChanged(any(Configuration.class));
-    }
-
-    @Test
-    public void testReportOrientationChangeOnOpeningClosingAppChange() {
-        synchronized (mWm.mGlobalLock) {
-            mToken.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
-
-            mDisplayContent.getDisplayRotation().setFixedToUserRotation(
-                    DisplayRotation.FIXED_TO_USER_ROTATION_ENABLED);
-            mDisplayContent.getDisplayInfo().state = Display.STATE_ON;
-            mDisplayContent.prepareAppTransition(WindowManager.TRANSIT_ACTIVITY_CLOSE,
-                    false /* alwaysKeepCurrent */, 0 /* flags */, true /* forceOverride */);
-
-            doReturn(Configuration.ORIENTATION_LANDSCAPE).when(mToken.mActivityRecord)
-                    .getRequestedConfigurationOrientation();
-
-            mTask.mTaskRecord = Mockito.mock(TaskRecord.class, RETURNS_DEEP_STUBS);
-            mToken.setVisibility(false, false);
-        }
+        mTask.mTaskRecord = Mockito.mock(TaskRecord.class, RETURNS_DEEP_STUBS);
+        mToken.reportDescendantOrientationChangeIfNeeded();
 
         verify(mTask.mTaskRecord).onConfigurationChanged(any(Configuration.class));
     }
@@ -380,7 +354,7 @@
     public void testAddRemoveRace() {
         // There was once a race condition between adding and removing starting windows
         for (int i = 0; i < 1000; i++) {
-            final WindowTestUtils.TestAppWindowToken appToken = createIsolatedTestAppWindowToken();
+            final AppWindowToken appToken = createIsolatedTestAppWindowToken();
 
             appToken.addStartingWindow(mPackageName,
                     android.R.style.Theme, null, "Test", 0, 0, 0, 0, null, true, true, false, true,
@@ -395,8 +369,8 @@
 
     @Test
     public void testTransferStartingWindow() {
-        final WindowTestUtils.TestAppWindowToken token1 = createIsolatedTestAppWindowToken();
-        final WindowTestUtils.TestAppWindowToken token2 = createIsolatedTestAppWindowToken();
+        final AppWindowToken token1 = createIsolatedTestAppWindowToken();
+        final AppWindowToken token2 = createIsolatedTestAppWindowToken();
         token1.addStartingWindow(mPackageName,
                 android.R.style.Theme, null, "Test", 0, 0, 0, 0, null, true, true, false, true,
                 false, false);
@@ -411,8 +385,8 @@
 
     @Test
     public void testTransferStartingWindowWhileCreating() {
-        final WindowTestUtils.TestAppWindowToken token1 = createIsolatedTestAppWindowToken();
-        final WindowTestUtils.TestAppWindowToken token2 = createIsolatedTestAppWindowToken();
+        final AppWindowToken token1 = createIsolatedTestAppWindowToken();
+        final AppWindowToken token2 = createIsolatedTestAppWindowToken();
         ((TestWindowManagerPolicy) token1.mWmService.mPolicy).setRunnableWhenAddingSplashScreen(
                 () -> {
                     // Surprise, ...! Transfer window in the middle of the creation flow.
@@ -429,14 +403,14 @@
         assertHasStartingWindow(token2);
     }
 
-    private WindowTestUtils.TestAppWindowToken createIsolatedTestAppWindowToken() {
+    private AppWindowToken createIsolatedTestAppWindowToken() {
         final TaskStack taskStack = createTaskStackOnDisplay(mDisplayContent);
         final Task task = createTaskInStack(taskStack, 0 /* userId */);
         return createTestAppWindowTokenForGivenTask(task);
     }
 
-    private WindowTestUtils.TestAppWindowToken createTestAppWindowTokenForGivenTask(Task task) {
-        final WindowTestUtils.TestAppWindowToken appToken =
+    private AppWindowToken createTestAppWindowTokenForGivenTask(Task task) {
+        final AppWindowToken appToken =
                 WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task.addChild(appToken, 0);
         waitUntilHandlersIdle();
@@ -446,8 +420,8 @@
     @Test
     public void testTryTransferStartingWindowFromHiddenAboveToken() {
         // Add two tasks on top of each other.
-        final WindowTestUtils.TestAppWindowToken tokenTop = createIsolatedTestAppWindowToken();
-        final WindowTestUtils.TestAppWindowToken tokenBottom =
+        final AppWindowToken tokenTop = createIsolatedTestAppWindowToken();
+        final AppWindowToken tokenBottom =
                 createTestAppWindowTokenForGivenTask(tokenTop.getTask());
 
         // Add a starting window.
diff --git a/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java b/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
index bb574ce..2e85897 100644
--- a/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
@@ -22,6 +22,8 @@
 import static android.app.AppOpsManager.OP_ASSIST_STRUCTURE;
 import static android.graphics.Bitmap.Config.ARGB_8888;
 
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
@@ -71,7 +73,7 @@
  */
 @MediumTest
 @Presubmit
-public class AssistDataRequesterTest extends ActivityTestsBase {
+public class AssistDataRequesterTest {
 
     private static final String TAG = AssistDataRequesterTest.class.getSimpleName();
 
@@ -111,8 +113,9 @@
         mHandler = new Handler(Looper.getMainLooper());
         mCallbacksLock = new Object();
         mCallbacks = new Callbacks();
-        mDataRequester = new AssistDataRequester(mContext, mWm, mAppOpsManager, mCallbacks,
-                mCallbacksLock, OP_ASSIST_STRUCTURE, OP_ASSIST_SCREENSHOT);
+        mDataRequester = new AssistDataRequester(getInstrumentation().getTargetContext(), mWm,
+                mAppOpsManager, mCallbacks, mCallbacksLock, OP_ASSIST_STRUCTURE,
+                OP_ASSIST_SCREENSHOT);
         mDataRequester.mActivityTaskManager = mAtm;
         // Gate the continuation of the assist data callbacks until we are ready within the tests
         mGate = new CountDownLatch(1);
diff --git a/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java b/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java
index a98f79c..73420a0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DimmerTests.java
@@ -46,7 +46,7 @@
 
     private static class TestWindowContainer extends WindowContainer<TestWindowContainer> {
         final SurfaceControl mControl = mock(SurfaceControl.class);
-        final SurfaceControl.Transaction mTransaction = mock(SurfaceControl.Transaction.class);
+        final SurfaceControl.Transaction mTransaction = spy(StubTransaction.class);
 
         TestWindowContainer(WindowManagerService wm) {
             super(wm);
@@ -66,7 +66,7 @@
     private static class MockSurfaceBuildingContainer extends WindowContainer<TestWindowContainer> {
         final SurfaceSession mSession = new SurfaceSession();
         final SurfaceControl mHostControl = mock(SurfaceControl.class);
-        final SurfaceControl.Transaction mHostTransaction = mock(SurfaceControl.Transaction.class);
+        final SurfaceControl.Transaction mHostTransaction = spy(StubTransaction.class);
 
         MockSurfaceBuildingContainer(WindowManagerService wm) {
             super(wm);
@@ -118,7 +118,7 @@
     public void setUp() throws Exception {
         mHost = new MockSurfaceBuildingContainer(mWm);
         mSurfaceAnimatorStarter = spy(new SurfaceAnimatorStarterImpl());
-        mTransaction = mock(SurfaceControl.Transaction.class);
+        mTransaction = spy(StubTransaction.class);
         mDimmer = new Dimmer(mHost, mSurfaceAnimatorStarter);
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
index 44f3ee41..2ba3cbd 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayContentTests.java
@@ -39,6 +39,7 @@
 import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
 import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
 import static android.view.WindowManager.LayoutParams.TYPE_VOICE_INTERACTION;
+import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
 
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyBoolean;
@@ -46,8 +47,8 @@
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.never;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.reset;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.same;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.times;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
@@ -72,7 +73,6 @@
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 import android.util.DisplayMetrics;
-import android.util.MutableBoolean;
 import android.view.DisplayCutout;
 import android.view.Gravity;
 import android.view.ISystemGestureExclusionListener;
@@ -88,6 +88,7 @@
 import com.android.server.wm.utils.WmDisplayCutout;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 
@@ -105,6 +106,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class DisplayContentTests extends WindowTestsBase {
 
     @Test
@@ -239,8 +241,7 @@
         assertEquals(dc, stack.getDisplayContent());
 
         final Task task = createTaskInStack(stack, 0 /* userId */);
-        final WindowTestUtils.TestAppWindowToken token = WindowTestUtils.createTestAppWindowToken(
-                dc);
+        final AppWindowToken token = WindowTestUtils.createTestAppWindowToken(dc);
         task.addChild(token, 0);
         assertEquals(dc, task.getDisplayContent());
         assertEquals(dc, token.getDisplayContent());
@@ -312,7 +313,7 @@
         // Add stack with activity.
         final TaskStack stack0 = createTaskStackOnDisplay(dc0);
         final Task task0 = createTaskInStack(stack0, 0 /* userId */);
-        final WindowTestUtils.TestAppWindowToken token =
+        final AppWindowToken token =
                 WindowTestUtils.createTestAppWindowToken(dc0);
         task0.addChild(token, 0);
         dc0.configureDisplayPolicy();
@@ -320,7 +321,7 @@
 
         final TaskStack stack1 = createTaskStackOnDisplay(dc1);
         final Task task1 = createTaskInStack(stack1, 0 /* userId */);
-        final WindowTestUtils.TestAppWindowToken token1 =
+        final AppWindowToken token1 =
                 WindowTestUtils.createTestAppWindowToken(dc0);
         task1.addChild(token1, 0);
         dc1.configureDisplayPolicy();
@@ -396,6 +397,59 @@
                 mWm.mRoot.getTopFocusedDisplayContent().getDisplayId());
     }
 
+    @Test
+    public void testShouldWaitForSystemDecorWindowsOnBoot_OnDefaultDisplay() {
+        mWm.mSystemBooted = true;
+        final DisplayContent defaultDisplay = mWm.getDefaultDisplayContentLocked();
+        final WindowState[] windows = createNotDrawnWindowsOn(defaultDisplay,
+                TYPE_WALLPAPER, TYPE_APPLICATION);
+
+        // Verify waiting for windows to be drawn.
+        assertTrue(defaultDisplay.shouldWaitForSystemDecorWindowsOnBoot());
+
+        // Verify not waiting for drawn windows.
+        makeWindowsDrawn(windows);
+        assertFalse(defaultDisplay.shouldWaitForSystemDecorWindowsOnBoot());
+    }
+
+    @Test
+    public void testShouldWaitForSystemDecorWindowsOnBoot_OnSecondaryDisplay() {
+        mWm.mSystemBooted = true;
+        final DisplayContent secondaryDisplay = createNewDisplay();
+        final WindowState[] windows = createNotDrawnWindowsOn(secondaryDisplay,
+                TYPE_WALLPAPER, TYPE_APPLICATION);
+
+        // Verify not waiting for display without system decorations.
+        doReturn(false).when(secondaryDisplay).supportsSystemDecorations();
+        assertFalse(secondaryDisplay.shouldWaitForSystemDecorWindowsOnBoot());
+
+        // Verify waiting for non-drawn windows on display with system decorations.
+        reset(secondaryDisplay);
+        doReturn(true).when(secondaryDisplay).supportsSystemDecorations();
+        assertTrue(secondaryDisplay.shouldWaitForSystemDecorWindowsOnBoot());
+
+        // Verify not waiting for drawn windows on display with system decorations.
+        makeWindowsDrawn(windows);
+        assertFalse(secondaryDisplay.shouldWaitForSystemDecorWindowsOnBoot());
+    }
+
+    private WindowState[] createNotDrawnWindowsOn(DisplayContent displayContent, int... types) {
+        final WindowState[] windows = new WindowState[types.length];
+        for (int i = 0; i < types.length; i++) {
+            final int type = types[i];
+            windows[i] = createWindow(null /* parent */, type, displayContent, "window-" + type);
+            windows[i].mHasSurface = false;
+        }
+        return windows;
+    }
+
+    private static void makeWindowsDrawn(WindowState[] windows) {
+        for (WindowState window : windows) {
+            window.mHasSurface = true;
+            window.mWinAnimator.mDrawState = WindowStateAnimator.HAS_DRAWN;
+        }
+    }
+
     /**
      * This tests setting the maximum ui width on a display.
      */
@@ -435,78 +489,70 @@
 
     @Test
     public void testDisplayCutout_rot0() {
-        synchronized (mWm.getWindowManagerLock()) {
-            final DisplayContent dc = createNewDisplay();
-            dc.mInitialDisplayWidth = 200;
-            dc.mInitialDisplayHeight = 400;
-            Rect r = new Rect(80, 0, 120, 10);
-            final DisplayCutout cutout = new WmDisplayCutout(
-                    fromBoundingRect(r.left, r.top, r.right, r.bottom, BOUNDS_POSITION_TOP), null)
-                    .computeSafeInsets(200, 400).getDisplayCutout();
+        final DisplayContent dc = createNewDisplay();
+        dc.mInitialDisplayWidth = 200;
+        dc.mInitialDisplayHeight = 400;
+        final Rect r = new Rect(80, 0, 120, 10);
+        final DisplayCutout cutout = new WmDisplayCutout(
+                fromBoundingRect(r.left, r.top, r.right, r.bottom, BOUNDS_POSITION_TOP), null)
+                        .computeSafeInsets(200, 400).getDisplayCutout();
 
-            dc.mInitialDisplayCutout = cutout;
-            dc.getDisplayRotation().setRotation(Surface.ROTATION_0);
-            dc.computeScreenConfiguration(new Configuration()); // recomputes dc.mDisplayInfo.
+        dc.mInitialDisplayCutout = cutout;
+        dc.getDisplayRotation().setRotation(Surface.ROTATION_0);
+        dc.computeScreenConfiguration(new Configuration()); // recomputes dc.mDisplayInfo.
 
-            assertEquals(cutout, dc.getDisplayInfo().displayCutout);
-        }
+        assertEquals(cutout, dc.getDisplayInfo().displayCutout);
     }
 
     @Test
     public void testDisplayCutout_rot90() {
-        synchronized (mWm.getWindowManagerLock()) {
-            // Prevent mInitialDisplayCutout from being updated from real display (e.g. null
-            // if the device has no cutout).
-            final DisplayContent dc = createDisplayNoUpdateDisplayInfo();
-            // Rotation may use real display info to compute bound, so here also uses the
-            // same width and height.
-            final int displayWidth = dc.mInitialDisplayWidth;
-            final int displayHeight = dc.mInitialDisplayHeight;
-            final int cutoutWidth = 40;
-            final int cutoutHeight = 10;
-            final int left = (displayWidth - cutoutWidth) / 2;
-            final int top = 0;
-            final int right = (displayWidth + cutoutWidth) / 2;
-            final int bottom = cutoutHeight;
+        // Prevent mInitialDisplayCutout from being updated from real display (e.g. null
+        // if the device has no cutout).
+        final DisplayContent dc = createDisplayNoUpdateDisplayInfo();
+        // Rotation may use real display info to compute bound, so here also uses the
+        // same width and height.
+        final int displayWidth = dc.mInitialDisplayWidth;
+        final int displayHeight = dc.mInitialDisplayHeight;
+        final int cutoutWidth = 40;
+        final int cutoutHeight = 10;
+        final int left = (displayWidth - cutoutWidth) / 2;
+        final int top = 0;
+        final int right = (displayWidth + cutoutWidth) / 2;
+        final int bottom = cutoutHeight;
 
-            final Rect r1 = new Rect(left, top, right, bottom);
-            final DisplayCutout cutout = new WmDisplayCutout(
-                    fromBoundingRect(r1.left, r1.top, r1.right, r1.bottom, BOUNDS_POSITION_TOP),
-                    null)
-                    .computeSafeInsets(displayWidth, displayHeight).getDisplayCutout();
+        final Rect r1 = new Rect(left, top, right, bottom);
+        final DisplayCutout cutout = new WmDisplayCutout(
+                fromBoundingRect(r1.left, r1.top, r1.right, r1.bottom, BOUNDS_POSITION_TOP), null)
+                        .computeSafeInsets(displayWidth, displayHeight).getDisplayCutout();
 
-            dc.mInitialDisplayCutout = cutout;
-            dc.getDisplayRotation().setRotation(Surface.ROTATION_90);
-            dc.computeScreenConfiguration(new Configuration()); // recomputes dc.mDisplayInfo.
+        dc.mInitialDisplayCutout = cutout;
+        dc.getDisplayRotation().setRotation(Surface.ROTATION_90);
+        dc.computeScreenConfiguration(new Configuration()); // recomputes dc.mDisplayInfo.
 
-            // ----o----------      -------------
-            // |   |     |   |      |
-            // |   ------o   |      o---
-            // |             |      |  |
-            // |             |  ->  |  |
-            // |             |      ---o
-            // |             |      |
-            // |             |      -------------
-            final Rect r = new Rect(top, left, bottom, right);
-            assertEquals(new WmDisplayCutout(
-                    fromBoundingRect(r.left, r.top, r.right, r.bottom, BOUNDS_POSITION_LEFT), null)
-                    .computeSafeInsets(displayHeight, displayWidth)
-                    .getDisplayCutout(), dc.getDisplayInfo().displayCutout);
-        }
+        // ----o----------      -------------
+        // |   |     |   |      |
+        // |   ------o   |      o---
+        // |             |      |  |
+        // |             |  ->  |  |
+        // |             |      ---o
+        // |             |      |
+        // |             |      -------------
+        final Rect r = new Rect(top, left, bottom, right);
+        assertEquals(new WmDisplayCutout(
+                fromBoundingRect(r.left, r.top, r.right, r.bottom, BOUNDS_POSITION_LEFT), null)
+                        .computeSafeInsets(displayHeight, displayWidth).getDisplayCutout(),
+                dc.getDisplayInfo().displayCutout);
     }
 
     @Test
     public void testLayoutSeq_assignedDuringLayout() {
-        synchronized (mWm.getWindowManagerLock()) {
+        final DisplayContent dc = createNewDisplay();
+        final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION, dc, "w");
 
-            final DisplayContent dc = createNewDisplay();
-            final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION, dc, "w");
+        dc.setLayoutNeeded();
+        dc.performLayout(true /* initial */, false /* updateImeWindows */);
 
-            dc.setLayoutNeeded();
-            dc.performLayout(true /* initial */, false /* updateImeWindows */);
-
-            assertThat(win.mLayoutSeq, is(dc.mLayoutSeq));
-        }
+        assertThat(win.mLayoutSeq, is(dc.mLayoutSeq));
     }
 
     @Test
@@ -660,13 +706,13 @@
 
         final ActivityStack stack =
                 new ActivityTestsBase.StackBuilder(mWm.mAtmService.mRootActivityContainer)
-                        .setDisplay(dc.mAcitvityDisplay).build();
+                        .setDisplay(dc.mActivityDisplay).build();
         final ActivityRecord activity = stack.topTask().getTopActivity();
 
         activity.setRequestedOrientation(newOrientation);
 
         final ArgumentCaptor<Configuration> captor = ArgumentCaptor.forClass(Configuration.class);
-        verify(dc.mAcitvityDisplay).updateDisplayOverrideConfigurationLocked(captor.capture(),
+        verify(dc.mActivityDisplay).updateDisplayOverrideConfigurationLocked(captor.capture(),
                 same(activity), anyBoolean(), same(null));
         final Configuration newDisplayConfig = captor.getValue();
         final int expectedOrientation = newOrientation == SCREEN_ORIENTATION_PORTRAIT
@@ -686,12 +732,12 @@
 
         final ActivityStack stack =
                 new ActivityTestsBase.StackBuilder(mWm.mAtmService.mRootActivityContainer)
-                        .setDisplay(dc.mAcitvityDisplay).build();
+                        .setDisplay(dc.mActivityDisplay).build();
         final ActivityRecord activity = stack.topTask().getTopActivity();
 
         activity.setRequestedOrientation(newOrientation);
 
-        verify(dc.mAcitvityDisplay, never()).updateDisplayOverrideConfigurationLocked(any(),
+        verify(dc.mActivityDisplay, never()).updateDisplayOverrideConfigurationLocked(any(),
                 eq(activity), anyBoolean(), same(null));
         assertEquals(dc.getDisplayRotation().getUserRotation(), dc.getRotation());
     }
@@ -751,7 +797,7 @@
         win.setHasSurface(true);
         dc.updateSystemGestureExclusion();
 
-        final MutableBoolean invoked = new MutableBoolean(false);
+        final boolean[] invoked = { false };
         final ISystemGestureExclusionListener.Stub verifier =
                 new ISystemGestureExclusionListener.Stub() {
             @Override
@@ -760,7 +806,7 @@
                 Region expected = Region.obtain();
                 expected.set(10, 20, 30, 40);
                 assertEquals(expected, actual);
-                invoked.value = true;
+                invoked[0] = true;
             }
         };
         try {
@@ -768,7 +814,7 @@
         } finally {
             dc.unregisterSystemGestureExclusionListener(verifier);
         }
-        assertTrue("SystemGestureExclusionListener was not invoked", invoked.value);
+        assertTrue("SystemGestureExclusionListener was not invoked", invoked[0]);
     }
 
     @Test
@@ -826,30 +872,28 @@
 
     @Test
     public void testCalculateSystemGestureExclusion_immersiveStickyLegacyWindow() throws Exception {
-        synchronized (mWm.mGlobalLock) {
-            mWm.mSystemGestureExcludedByPreQStickyImmersive = true;
+        mWm.mSystemGestureExcludedByPreQStickyImmersive = true;
 
-            final DisplayContent dc = createNewDisplay();
-            final WindowState win = createWindow(null, TYPE_BASE_APPLICATION, dc, "win");
-            win.getAttrs().flags |= FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR;
-            win.getAttrs().layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
-            win.getAttrs().privateFlags |= PRIVATE_FLAG_NO_MOVE_ANIMATION;
-            win.getAttrs().subtreeSystemUiVisibility = win.mSystemUiVisibility =
-                    SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION
-                            | SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
-            win.mAppToken.mTargetSdk = P;
+        final DisplayContent dc = createNewDisplay();
+        final WindowState win = createWindow(null, TYPE_BASE_APPLICATION, dc, "win");
+        win.getAttrs().flags |= FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR;
+        win.getAttrs().layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
+        win.getAttrs().privateFlags |= PRIVATE_FLAG_NO_MOVE_ANIMATION;
+        win.getAttrs().subtreeSystemUiVisibility = win.mSystemUiVisibility =
+                SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION
+                        | SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
+        win.mAppToken.mTargetSdk = P;
 
-            dc.setLayoutNeeded();
-            dc.performLayout(true /* initial */, false /* updateImeWindows */);
+        dc.setLayoutNeeded();
+        dc.performLayout(true /* initial */, false /* updateImeWindows */);
 
-            win.setHasSurface(true);
+        win.setHasSurface(true);
 
-            final Region expected = Region.obtain();
-            expected.set(dc.getBounds());
-            assertEquals(expected, calculateSystemGestureExclusion(dc));
+        final Region expected = Region.obtain();
+        expected.set(dc.getBounds());
+        assertEquals(expected, calculateSystemGestureExclusion(dc));
 
-            win.setHasSurface(false);
-        }
+        win.setHasSurface(false);
     }
 
     @Test
@@ -860,7 +904,7 @@
 
         Configuration newConfig = new Configuration();
         newConfig.orientation = Configuration.ORIENTATION_PORTRAIT;
-        final DisplayContent displayContent = spy(createNewDisplay());
+        final DisplayContent displayContent = createNewDisplay();
         Mockito.doReturn(mockLogger).when(displayContent).getMetricsLogger();
         Mockito.doReturn(oldConfig).doReturn(newConfig).when(displayContent).getConfiguration();
 
@@ -886,9 +930,7 @@
     }
 
     private void updateFocusedWindow() {
-        synchronized (mWm.mGlobalLock) {
-            mWm.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, false);
-        }
+        mWm.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, false /* updateInputWindows */);
     }
 
     /**
@@ -896,7 +938,7 @@
      * the values set by test.
      */
     private DisplayContent createDisplayNoUpdateDisplayInfo() {
-        final DisplayContent displayContent = spy(createNewDisplay());
+        final DisplayContent displayContent = createNewDisplay();
         doNothing().when(displayContent).updateDisplayInfo();
         return displayContent;
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java
index de184b8..2a3731a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyLayoutTests.java
@@ -63,9 +63,11 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class DisplayPolicyLayoutTests extends DisplayPolicyTestsBase {
 
     private DisplayFrames mFrames;
@@ -118,458 +120,415 @@
 
     @Test
     public void layoutWindowLw_appDrawsBars() {
-        synchronized (mWm.mGlobalLock) {
-            mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
-            addWindow(mWindow);
+        mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
     }
 
     @Test
     public void layoutWindowLw_appWontDrawBars() {
-        synchronized (mWm.mGlobalLock) {
-            mWindow.mAttrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
-            addWindow(mWindow);
+        mWindow.mAttrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, NAV_BAR_HEIGHT);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, NAV_BAR_HEIGHT);
     }
 
     @Test
     public void layoutWindowLw_appWontDrawBars_forceStatusAndNav() throws Exception {
-        synchronized (mWm.mGlobalLock) {
-            mWindow.mAttrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
-            mWindow.mAttrs.privateFlags |= PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS;
-            addWindow(mWindow);
+        mWindow.mAttrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+        mWindow.mAttrs.privateFlags |= PRIVATE_FLAG_FORCE_DRAW_BAR_BACKGROUNDS;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
     }
 
     @Test
     public void layoutWindowLw_keyguardDialog_hideNav() {
-        synchronized (mWm.mGlobalLock) {
-            mWindow.mAttrs.type = TYPE_KEYGUARD_DIALOG;
-            mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
-            mWindow.mAttrs.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
-            addWindow(mWindow);
+        mWindow.mAttrs.type = TYPE_KEYGUARD_DIALOG;
+        mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+        mWindow.mAttrs.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* uiMode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null /* attached */, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* uiMode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null /* attached */, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
+        addDisplayCutout();
 
-            addWindow(mWindow);
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_never() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
+        addDisplayCutout();
 
-            mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
-            addWindow(mWindow);
+        mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_layoutFullscreen() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
+        addDisplayCutout();
 
-            mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
-            addWindow(mWindow);
+        mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_fullscreen() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
+        addDisplayCutout();
 
-            mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_FULLSCREEN;
-            addWindow(mWindow);
+        mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_FULLSCREEN;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), STATUS_BAR_HEIGHT, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_fullscreenInCutout() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
+        addDisplayCutout();
 
-            mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_FULLSCREEN;
-            mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
-            addWindow(mWindow);
+        mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_FULLSCREEN;
+        mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDecorFrame(), 0, 0);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), 0, 0);
     }
 
 
     @Test
     public void layoutWindowLw_withDisplayCutout_landscape() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
-            setRotation(ROTATION_90);
-            addWindow(mWindow);
+        addDisplayCutout();
+        setRotation(ROTATION_90);
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetBy(mWindow.getParentFrame(), DISPLAY_CUTOUT_HEIGHT, 0, 0, 0);
-            assertInsetBy(mWindow.getStableFrameLw(), 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
-            assertInsetBy(mWindow.getContentFrameLw(),
-                    DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
-            assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
-            assertInsetBy(mWindow.getDisplayFrameLw(), DISPLAY_CUTOUT_HEIGHT, 0, 0, 0);
-        }
+        assertInsetBy(mWindow.getParentFrame(), DISPLAY_CUTOUT_HEIGHT, 0, 0, 0);
+        assertInsetBy(mWindow.getStableFrameLw(), 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
+        assertInsetBy(mWindow.getContentFrameLw(),
+                DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
+        assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
+        assertInsetBy(mWindow.getDisplayFrameLw(), DISPLAY_CUTOUT_HEIGHT, 0, 0, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_seascape() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
-            setRotation(ROTATION_270);
-            addWindow(mWindow);
+        addDisplayCutout();
+        setRotation(ROTATION_270);
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetBy(mWindow.getParentFrame(), 0, 0, DISPLAY_CUTOUT_HEIGHT, 0);
-            assertInsetBy(mWindow.getStableFrameLw(), NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, 0, 0);
-            assertInsetBy(mWindow.getContentFrameLw(),
-                    NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, DISPLAY_CUTOUT_HEIGHT, 0);
-            assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
-            assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, DISPLAY_CUTOUT_HEIGHT, 0);
-        }
+        assertInsetBy(mWindow.getParentFrame(), 0, 0, DISPLAY_CUTOUT_HEIGHT, 0);
+        assertInsetBy(mWindow.getStableFrameLw(), NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, 0, 0);
+        assertInsetBy(mWindow.getContentFrameLw(),
+                NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, DISPLAY_CUTOUT_HEIGHT, 0);
+        assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
+        assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, DISPLAY_CUTOUT_HEIGHT, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_fullscreen_landscape() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
-            setRotation(ROTATION_90);
+        addDisplayCutout();
+        setRotation(ROTATION_90);
 
-            mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
-            addWindow(mWindow);
+        mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetBy(mWindow.getParentFrame(), DISPLAY_CUTOUT_HEIGHT, 0, 0, 0);
-            assertInsetBy(mWindow.getStableFrameLw(), 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
-            assertInsetBy(mWindow.getContentFrameLw(),
-                    DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
-            assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
-        }
+        assertInsetBy(mWindow.getParentFrame(), DISPLAY_CUTOUT_HEIGHT, 0, 0, 0);
+        assertInsetBy(mWindow.getStableFrameLw(), 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
+        assertInsetBy(mWindow.getContentFrameLw(),
+                DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
+        assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_floatingInScreen() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
+        addDisplayCutout();
 
-            mWindow.mAttrs.flags = FLAG_LAYOUT_IN_SCREEN;
-            mWindow.mAttrs.type = TYPE_APPLICATION_OVERLAY;
-            mWindow.mAttrs.width = DISPLAY_WIDTH;
-            mWindow.mAttrs.height = DISPLAY_HEIGHT;
-            addWindow(mWindow);
+        mWindow.mAttrs.flags = FLAG_LAYOUT_IN_SCREEN;
+        mWindow.mAttrs.type = TYPE_APPLICATION_OVERLAY;
+        mWindow.mAttrs.width = DISPLAY_WIDTH;
+        mWindow.mAttrs.height = DISPLAY_HEIGHT;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetByTopBottom(mWindow.getParentFrame(), 0, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-        }
+        assertInsetByTopBottom(mWindow.getParentFrame(), 0, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getDisplayFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
     }
 
     @Test
     public void layoutWindowLw_withDisplayCutout_fullscreenInCutout_landscape() {
-        synchronized (mWm.mGlobalLock) {
-            addDisplayCutout();
-            setRotation(ROTATION_90);
+        addDisplayCutout();
+        setRotation(ROTATION_90);
 
-            mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
-            mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
-            addWindow(mWindow);
+        mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+        mWindow.mAttrs.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetBy(mWindow.getParentFrame(), 0, 0, 0, 0);
-            assertInsetBy(mWindow.getStableFrameLw(), 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
-            assertInsetBy(mWindow.getContentFrameLw(),
-                    DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
-            assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
-        }
+        assertInsetBy(mWindow.getParentFrame(), 0, 0, 0, 0);
+        assertInsetBy(mWindow.getStableFrameLw(), 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
+        assertInsetBy(mWindow.getContentFrameLw(),
+                DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
+        assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
     }
 
     @Test
     public void layoutWindowLw_withForwardInset_SoftInputAdjustResize() {
-        synchronized (mWm.mGlobalLock) {
-            mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_RESIZE;
-            addWindow(mWindow);
+        mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_RESIZE;
+        addWindow(mWindow);
 
-            final int forwardedInsetBottom = 50;
-            mDisplayPolicy.setForwardedInsets(Insets.of(0, 0, 0, forwardedInsetBottom));
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        final int forwardedInsetBottom = 50;
+        mDisplayPolicy.setForwardedInsets(Insets.of(0, 0, 0, forwardedInsetBottom));
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetBy(mWindow.getParentFrame(), 0, 0, 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(),
-                    STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT + forwardedInsetBottom);
-            assertInsetByTopBottom(mWindow.getVisibleFrameLw(),
-                    STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT + forwardedInsetBottom);
-            assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
-            assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
-        }
+        assertInsetBy(mWindow.getParentFrame(), 0, 0, 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(),
+                STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT + forwardedInsetBottom);
+        assertInsetByTopBottom(mWindow.getVisibleFrameLw(),
+                STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT + forwardedInsetBottom);
+        assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
+        assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
     }
 
     @Test
     public void layoutWindowLw_withForwardInset_SoftInputAdjustNothing() {
-        synchronized (mWm.mGlobalLock) {
-            mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_NOTHING;
-            addWindow(mWindow);
+        mWindow.mAttrs.softInputMode = SOFT_INPUT_ADJUST_NOTHING;
+        addWindow(mWindow);
 
-            final int forwardedInsetBottom = 50;
-            mDisplayPolicy.setForwardedInsets(Insets.of(0, 0, 0, forwardedInsetBottom));
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        final int forwardedInsetBottom = 50;
+        mDisplayPolicy.setForwardedInsets(Insets.of(0, 0, 0, forwardedInsetBottom));
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
 
-            assertInsetBy(mWindow.getParentFrame(), 0, 0, 0, 0);
-            assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-            assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
-            assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
-        }
+        assertInsetBy(mWindow.getParentFrame(), 0, 0, 0, 0);
+        assertInsetByTopBottom(mWindow.getStableFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetByTopBottom(mWindow.getVisibleFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
+        assertInsetBy(mWindow.getDecorFrame(), 0, 0, 0, 0);
+        assertInsetBy(mWindow.getDisplayFrameLw(), 0, 0, 0, 0);
     }
 
     @Test
     public void layoutHint_appWindow() {
-        synchronized (mWm.mGlobalLock) {
-            // Initialize DisplayFrames
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        // Initialize DisplayFrames
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
 
-            final Rect outFrame = new Rect();
-            final Rect outContentInsets = new Rect();
-            final Rect outStableInsets = new Rect();
-            final Rect outOutsets = new Rect();
-            final DisplayCutout.ParcelableWrapper outDisplayCutout =
-                    new DisplayCutout.ParcelableWrapper();
+        final Rect outFrame = new Rect();
+        final Rect outContentInsets = new Rect();
+        final Rect outStableInsets = new Rect();
+        final Rect outOutsets = new Rect();
+        final DisplayCutout.ParcelableWrapper outDisplayCutout =
+                new DisplayCutout.ParcelableWrapper();
 
-            mDisplayPolicy.getLayoutHintLw(mWindow.mAttrs, null, mFrames,
-                    false /* floatingStack */, outFrame, outContentInsets, outStableInsets,
-                    outOutsets, outDisplayCutout);
+        mDisplayPolicy.getLayoutHintLw(mWindow.mAttrs, null, mFrames,
+                false /* floatingStack */, outFrame, outContentInsets, outStableInsets,
+                outOutsets, outDisplayCutout);
 
-            assertThat(outFrame, is(mFrames.mUnrestricted));
-            assertThat(outContentInsets, is(new Rect(0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT)));
-            assertThat(outStableInsets, is(new Rect(0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT)));
-            assertThat(outOutsets, is(new Rect()));
-            assertThat(outDisplayCutout, is(new DisplayCutout.ParcelableWrapper()));
-        }
+        assertThat(outFrame, is(mFrames.mUnrestricted));
+        assertThat(outContentInsets, is(new Rect(0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT)));
+        assertThat(outStableInsets, is(new Rect(0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT)));
+        assertThat(outOutsets, is(new Rect()));
+        assertThat(outDisplayCutout, is(new DisplayCutout.ParcelableWrapper()));
     }
 
     @Test
     public void layoutHint_appWindowInTask() {
-        synchronized (mWm.mGlobalLock) {
-            // Initialize DisplayFrames
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        // Initialize DisplayFrames
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
 
-            final Rect taskBounds = new Rect(100, 100, 200, 200);
+        final Rect taskBounds = new Rect(100, 100, 200, 200);
 
-            final Rect outFrame = new Rect();
-            final Rect outContentInsets = new Rect();
-            final Rect outStableInsets = new Rect();
-            final Rect outOutsets = new Rect();
-            final DisplayCutout.ParcelableWrapper outDisplayCutout =
-                    new DisplayCutout.ParcelableWrapper();
+        final Rect outFrame = new Rect();
+        final Rect outContentInsets = new Rect();
+        final Rect outStableInsets = new Rect();
+        final Rect outOutsets = new Rect();
+        final DisplayCutout.ParcelableWrapper outDisplayCutout =
+                new DisplayCutout.ParcelableWrapper();
 
-            mDisplayPolicy.getLayoutHintLw(mWindow.mAttrs, taskBounds, mFrames,
-                    false /* floatingStack */, outFrame, outContentInsets, outStableInsets,
-                    outOutsets, outDisplayCutout);
+        mDisplayPolicy.getLayoutHintLw(mWindow.mAttrs, taskBounds, mFrames,
+                false /* floatingStack */, outFrame, outContentInsets, outStableInsets,
+                outOutsets, outDisplayCutout);
 
-            assertThat(outFrame, is(taskBounds));
-            assertThat(outContentInsets, is(new Rect()));
-            assertThat(outStableInsets, is(new Rect()));
-            assertThat(outOutsets, is(new Rect()));
-            assertThat(outDisplayCutout, is(new DisplayCutout.ParcelableWrapper()));
-        }
+        assertThat(outFrame, is(taskBounds));
+        assertThat(outContentInsets, is(new Rect()));
+        assertThat(outStableInsets, is(new Rect()));
+        assertThat(outOutsets, is(new Rect()));
+        assertThat(outDisplayCutout, is(new DisplayCutout.ParcelableWrapper()));
     }
 
     @Test
     public void layoutHint_appWindowInTask_outsideContentFrame() {
-        synchronized (mWm.mGlobalLock) {
-            // Initialize DisplayFrames
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        // Initialize DisplayFrames
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
 
-            // Task is in the nav bar area (usually does not happen, but this is similar enough to
-            // the possible overlap with the IME)
-            final Rect taskBounds = new Rect(100, mFrames.mContent.bottom + 1,
-                    200, mFrames.mContent.bottom + 10);
+        // Task is in the nav bar area (usually does not happen, but this is similar enough to
+        // the possible overlap with the IME)
+        final Rect taskBounds = new Rect(100, mFrames.mContent.bottom + 1,
+                200, mFrames.mContent.bottom + 10);
 
-            final Rect outFrame = new Rect();
-            final Rect outContentInsets = new Rect();
-            final Rect outStableInsets = new Rect();
-            final Rect outOutsets = new Rect();
-            final DisplayCutout.ParcelableWrapper outDisplayCutout =
-                    new DisplayCutout.ParcelableWrapper();
+        final Rect outFrame = new Rect();
+        final Rect outContentInsets = new Rect();
+        final Rect outStableInsets = new Rect();
+        final Rect outOutsets = new Rect();
+        final DisplayCutout.ParcelableWrapper outDisplayCutout =
+                new DisplayCutout.ParcelableWrapper();
 
-            mDisplayPolicy.getLayoutHintLw(mWindow.mAttrs, taskBounds, mFrames,
-                    true /* floatingStack */, outFrame, outContentInsets, outStableInsets,
-                    outOutsets, outDisplayCutout);
+        mDisplayPolicy.getLayoutHintLw(mWindow.mAttrs, taskBounds, mFrames,
+                true /* floatingStack */, outFrame, outContentInsets, outStableInsets,
+                outOutsets, outDisplayCutout);
 
-            assertThat(outFrame, is(taskBounds));
-            assertThat(outContentInsets, is(new Rect()));
-            assertThat(outStableInsets, is(new Rect()));
-            assertThat(outOutsets, is(new Rect()));
-            assertThat(outDisplayCutout, is(new DisplayCutout.ParcelableWrapper()));
-        }
+        assertThat(outFrame, is(taskBounds));
+        assertThat(outContentInsets, is(new Rect()));
+        assertThat(outStableInsets, is(new Rect()));
+        assertThat(outOutsets, is(new Rect()));
+        assertThat(outDisplayCutout, is(new DisplayCutout.ParcelableWrapper()));
     }
 
     @Test
     public void forceShowSystemBars_clearsSystemUIFlags() {
-        synchronized (mWm.mGlobalLock) {
-            mDisplayPolicy.mLastSystemUiFlags |= SYSTEM_UI_FLAG_FULLSCREEN;
-            mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
-            mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
-            mWindow.mSystemUiVisibility = SYSTEM_UI_FLAG_FULLSCREEN;
-            mDisplayPolicy.setForceShowSystemBars(true);
-            addWindow(mWindow);
+        mDisplayPolicy.mLastSystemUiFlags |= SYSTEM_UI_FLAG_FULLSCREEN;
+        mWindow.mAttrs.subtreeSystemUiVisibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
+        mWindow.mAttrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+        mWindow.mSystemUiVisibility = SYSTEM_UI_FLAG_FULLSCREEN;
+        mDisplayPolicy.setForceShowSystemBars(true);
+        addWindow(mWindow);
 
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
-            // triggers updateSystemUiVisibilityLw which will reset the flags as needed
-            int finishPostLayoutPolicyLw = mDisplayPolicy.focusChangedLw(mWindow, mWindow);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        // triggers updateSystemUiVisibilityLw which will reset the flags as needed
+        int finishPostLayoutPolicyLw = mDisplayPolicy.focusChangedLw(mWindow, mWindow);
 
-            assertEquals(WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT, finishPostLayoutPolicyLw);
-            assertEquals(0, mDisplayPolicy.mLastSystemUiFlags);
-            assertEquals(0, mWindow.mAttrs.systemUiVisibility);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-        }
+        assertEquals(WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT, finishPostLayoutPolicyLw);
+        assertEquals(0, mDisplayPolicy.mLastSystemUiFlags);
+        assertEquals(0, mWindow.mAttrs.systemUiVisibility);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
     }
 
     @Test
     public void testScreenDecorWindows() {
-        synchronized (mWm.mGlobalLock) {
-            final WindowState decorWindow = createWindow(null, TYPE_APPLICATION_OVERLAY,
-                    "decorWindow");
-            decorWindow.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
-            decorWindow.mAttrs.privateFlags |= PRIVATE_FLAG_IS_SCREEN_DECOR;
-            addWindow(decorWindow);
-            addWindow(mWindow);
+        final WindowState decorWindow = createWindow(null, TYPE_APPLICATION_OVERLAY, "decorWindow");
+        decorWindow.mAttrs.flags |= FLAG_NOT_FOCUSABLE;
+        decorWindow.mAttrs.privateFlags |= PRIVATE_FLAG_IS_SCREEN_DECOR;
+        addWindow(decorWindow);
+        addWindow(mWindow);
 
-            // Decor on top
-            updateDecorWindow(decorWindow, MATCH_PARENT, DECOR_WINDOW_INSET, TOP);
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), DECOR_WINDOW_INSET, NAV_BAR_HEIGHT);
+        // Decor on top
+        updateDecorWindow(decorWindow, MATCH_PARENT, DECOR_WINDOW_INSET, TOP);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), DECOR_WINDOW_INSET, NAV_BAR_HEIGHT);
 
-            // Decor on bottom
-            updateDecorWindow(decorWindow, MATCH_PARENT, DECOR_WINDOW_INSET, BOTTOM);
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT,
-                    DECOR_WINDOW_INSET);
+        // Decor on bottom
+        updateDecorWindow(decorWindow, MATCH_PARENT, DECOR_WINDOW_INSET, BOTTOM);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT,
+                DECOR_WINDOW_INSET);
 
-            // Decor on the left
-            updateDecorWindow(decorWindow, DECOR_WINDOW_INSET, MATCH_PARENT, LEFT);
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
-            assertInsetBy(mWindow.getContentFrameLw(), DECOR_WINDOW_INSET, STATUS_BAR_HEIGHT, 0,
-                    NAV_BAR_HEIGHT);
+        // Decor on the left
+        updateDecorWindow(decorWindow, DECOR_WINDOW_INSET, MATCH_PARENT, LEFT);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        assertInsetBy(mWindow.getContentFrameLw(), DECOR_WINDOW_INSET, STATUS_BAR_HEIGHT, 0,
+                NAV_BAR_HEIGHT);
 
-            // Decor on the right
-            updateDecorWindow(decorWindow, DECOR_WINDOW_INSET, MATCH_PARENT, RIGHT);
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
-            assertInsetBy(mWindow.getContentFrameLw(), 0, STATUS_BAR_HEIGHT, DECOR_WINDOW_INSET,
-                    NAV_BAR_HEIGHT);
+        // Decor on the right
+        updateDecorWindow(decorWindow, DECOR_WINDOW_INSET, MATCH_PARENT, RIGHT);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        assertInsetBy(mWindow.getContentFrameLw(), 0, STATUS_BAR_HEIGHT, DECOR_WINDOW_INSET,
+                NAV_BAR_HEIGHT);
 
-            // Decor not allowed as inset
-            updateDecorWindow(decorWindow, DECOR_WINDOW_INSET, DECOR_WINDOW_INSET, TOP);
-            mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
-            mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
-            assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
-        }
+        // Decor not allowed as inset
+        updateDecorWindow(decorWindow, DECOR_WINDOW_INSET, DECOR_WINDOW_INSET, TOP);
+        mDisplayPolicy.beginLayoutLw(mFrames, 0 /* UI mode */);
+        mDisplayPolicy.layoutWindowLw(mWindow, null, mFrames);
+        assertInsetByTopBottom(mWindow.getContentFrameLw(), STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT);
     }
 
     private void updateDecorWindow(WindowState decorWindow, int width, int height, int gravity) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java
index 3ead977..e699b52 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyTests.java
@@ -54,9 +54,11 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class DisplayPolicyTests extends WindowTestsBase {
 
     private WindowState createOpaqueFullscreen(boolean hasLightNavBar) {
@@ -225,13 +227,10 @@
         final WindowState activity = createApplicationWindow();
         final WindowState toast = createToastWindow();
 
-        synchronized (mWm.mGlobalLock) {
-            policy.adjustWindowParamsLw(
-                    toast, toast.mAttrs, 0 /* callingPid */, 0 /* callingUid */);
+        policy.adjustWindowParamsLw(toast, toast.mAttrs, 0 /* callingPid */, 0 /* callingUid */);
 
-            assertTrue(policy.canToastShowWhenLocked(0 /* callingUid */));
-            assertNotEquals(0, toast.getAttrs().flags & FLAG_SHOW_WHEN_LOCKED);
-        }
+        assertTrue(policy.canToastShowWhenLocked(0 /* callingUid */));
+        assertNotEquals(0, toast.getAttrs().flags & FLAG_SHOW_WHEN_LOCKED);
     }
 
     private WindowState createToastWindow() {
diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java
index 059ff3d..480c468 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DisplayRotationTests.java
@@ -68,6 +68,7 @@
 import com.android.server.wm.utils.WmDisplayCutout;
 
 import org.junit.After;
+import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -122,6 +123,12 @@
         sMockWm.mPolicy = mock(WindowManagerPolicy.class);
     }
 
+    @AfterClass
+    public static void tearDownOnce() {
+        // Make sure the fake settings are cleared after the last test method.
+        FakeSettingsProvider.clearSettingsProvider();
+    }
+
     @Before
     public void setUp() {
         FakeSettingsProvider.clearSettingsProvider();
@@ -238,15 +245,55 @@
     }
 
     @Test
-    public void testReturnsUserRotation_UserRotationLocked_CompatibleAppRequest()
+    public void testReturnsLandscape_UserRotationLockedSeascape_AppRequestsLandscape()
             throws Exception {
         mBuilder.build();
-        configureDisplayRotation(SCREEN_ORIENTATION_LANDSCAPE, false, false);
+        configureDisplayRotation(SCREEN_ORIENTATION_LANDSCAPE, false /* isCar */,
+                false /* isTv */);
+
+        freezeRotation(Surface.ROTATION_180);
+
+        assertEquals(Surface.ROTATION_0, mTarget.rotationForOrientation(
+                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, Surface.ROTATION_90));
+    }
+
+    @Test
+    public void testReturnsSeascape_UserRotationLockedSeascape_AppRequestsSeascape()
+            throws Exception {
+        mBuilder.build();
+        configureDisplayRotation(SCREEN_ORIENTATION_LANDSCAPE, false /* isCar */,
+                false /* isTv */);
 
         freezeRotation(Surface.ROTATION_180);
 
         assertEquals(Surface.ROTATION_180, mTarget.rotationForOrientation(
-                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, Surface.ROTATION_90));
+                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, Surface.ROTATION_90));
+    }
+
+    @Test
+    public void testReturnsPortrait_UserRotationLockedPortrait_AppRequestsPortrait()
+            throws Exception {
+        mBuilder.build();
+        configureDisplayRotation(SCREEN_ORIENTATION_LANDSCAPE, false /* isCar */,
+                false /* isTv */);
+
+        freezeRotation(Surface.ROTATION_270);
+
+        assertEquals(Surface.ROTATION_270, mTarget.rotationForOrientation(
+                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, Surface.ROTATION_0));
+    }
+
+    @Test
+    public void testReturnsUpsideDown_UserRotationLockedUpsideDown_AppRequestsUpsideDown()
+            throws Exception {
+        mBuilder.build();
+        configureDisplayRotation(SCREEN_ORIENTATION_LANDSCAPE, false /* isCar */,
+                false /* isTv */);
+
+        freezeRotation(Surface.ROTATION_90);
+
+        assertEquals(Surface.ROTATION_90, mTarget.rotationForOrientation(
+                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT, Surface.ROTATION_0));
     }
 
     @Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
index 0110e94..304df22 100644
--- a/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/DragDropControllerTests.java
@@ -20,9 +20,10 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
@@ -49,6 +50,7 @@
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -57,10 +59,11 @@
  * Tests for the {@link DragDropController} class.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:DragDropControllerTests
+ *  atest WmTests:DragDropControllerTests
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class DragDropControllerTests extends WindowTestsBase {
     private static final int TIMEOUT_MS = 3000;
     private TestDragDropController mTarget;
@@ -93,7 +96,7 @@
      * Creates a window state which can be used as a drop target.
      */
     private WindowState createDropTargetWindow(String name, int ownerId) {
-        final WindowTestUtils.TestAppWindowToken token = WindowTestUtils.createTestAppWindowToken(
+        final AppWindowToken token = WindowTestUtils.createTestAppWindowToken(
                 mDisplayContent);
         final TaskStack stack = createTaskStackOnDisplay(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, mDisplayContent);
@@ -121,29 +124,25 @@
     @Before
     public void setUp() throws Exception {
         mTarget = new TestDragDropController(mWm, mWm.mH.getLooper());
-        mDisplayContent = spy(mDisplayContent);
         mWindow = createDropTargetWindow("Drag test window", 0);
         doReturn(mWindow).when(mDisplayContent).getTouchableWinAtPointLocked(0, 0);
+        when(mWm.mInputManager.transferTouchFocus(any(), any())).thenReturn(true);
 
-        synchronized (mWm.mGlobalLock) {
-            mWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow);
-        }
+        mWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow);
     }
 
     @After
     public void tearDown() throws Exception {
         final CountDownLatch latch;
-        synchronized (mWm.mGlobalLock) {
-            if (!mTarget.dragDropActiveLocked()) {
-                return;
-            }
-            if (mToken != null) {
-                mTarget.cancelDragAndDrop(mToken, false);
-            }
-            latch = new CountDownLatch(1);
-            mTarget.setOnClosedCallbackLocked(latch::countDown);
+        if (!mTarget.dragDropActiveLocked()) {
+            return;
         }
-        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+        if (mToken != null) {
+            mTarget.cancelDragAndDrop(mToken, false);
+        }
+        latch = new CountDownLatch(1);
+        mTarget.setOnClosedCallbackLocked(latch::countDown);
+        assertTrue(awaitInWmLock(() -> latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)));
     }
 
     @Test
@@ -177,6 +176,7 @@
                     .setFormat(PixelFormat.TRANSLUCENT)
                     .build();
 
+            assertTrue(mWm.mInputManager.transferTouchFocus(null, null));
             mToken = mTarget.performDrag(
                     new SurfaceSession(), 0, 0, mWindow.mClient, flag, surface, 0, 0, 0, 0, 0,
                     data);
diff --git a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java
index be2ee29..46435eb 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java
@@ -422,7 +422,7 @@
 
         @Override
         void saveTask(TaskRecord task) {
-            final int userId = task.userId;
+            final int userId = task.mUserId;
             final ComponentName realActivity = task.realActivity;
             mTmpParams.mPreferredDisplayId = task.getStack().mDisplayId;
             mTmpParams.mWindowingMode = task.getWindowingMode();
@@ -436,7 +436,7 @@
 
         @Override
         void getLaunchParams(TaskRecord task, ActivityRecord activity, LaunchParams params) {
-            final int userId = task != null ? task.userId : activity.mUserId;
+            final int userId = task != null ? task.mUserId : activity.mUserId;
             final ComponentName name = task != null
                     ? task.realActivity : activity.mActivityComponent;
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
index 49d778f..b9fef4b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
@@ -32,7 +32,6 @@
 import static org.mockito.Matchers.any;
 
 import android.content.ComponentName;
-import android.content.pm.PackageList;
 import android.content.pm.PackageManagerInternal;
 import android.graphics.Rect;
 import android.os.UserHandle;
@@ -43,6 +42,7 @@
 import androidx.test.filters.MediumTest;
 
 import com.android.server.LocalServices;
+import com.android.server.pm.PackageList;
 import com.android.server.wm.LaunchParamsController.LaunchParams;
 
 import org.junit.Before;
@@ -115,16 +115,16 @@
                 ACTIVITY_TYPE_STANDARD, /* onTop */ true);
         mTestTask = new TaskBuilder(mSupervisor).setComponent(TEST_COMPONENT).setStack(stack)
                 .build();
-        mTestTask.userId = TEST_USER_ID;
+        mTestTask.mUserId = TEST_USER_ID;
         mTestTask.mLastNonFullscreenBounds = TEST_BOUNDS;
         mTestTask.hasBeenVisible = true;
 
         mTaskWithDifferentComponent = new TaskBuilder(mSupervisor)
                 .setComponent(ALTERNATIVE_COMPONENT).build();
-        mTaskWithDifferentComponent.userId = TEST_USER_ID;
+        mTaskWithDifferentComponent.mUserId = TEST_USER_ID;
 
         mTaskWithDifferentUser = new TaskBuilder(mSupervisor).setComponent(TEST_COMPONENT).build();
-        mTaskWithDifferentUser.userId = ALTERNATIVE_USER_ID;
+        mTaskWithDifferentUser.mUserId = ALTERNATIVE_USER_ID;
 
         mTarget = new LaunchParamsPersister(mPersisterQueue, mSupervisor, mUserFolderGetter);
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java b/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java
index 2d0416d..15417d7 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LetterboxTest.java
@@ -21,6 +21,7 @@
 import static org.mockito.Mockito.clearInvocations;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -48,8 +49,8 @@
     @Before
     public void setUp() throws Exception {
         mSurfaces = new SurfaceControlMocker();
-        mLetterbox = new Letterbox(mSurfaces, () -> mock(SurfaceControl.Transaction.class));
-        mTransaction = mock(SurfaceControl.Transaction.class);
+        mLetterbox = new Letterbox(mSurfaces, StubTransaction::new);
+        mTransaction = spy(StubTransaction.class);
     }
 
     @Test
diff --git a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
index 47c76fc..05e173c 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
@@ -707,7 +707,7 @@
         TaskRecord tr = mock(TaskRecord.class);
         tr.mLockTaskAuth = lockTaskAuth;
         tr.intent = intent;
-        tr.userId = TEST_USER_ID;
+        tr.mUserId = TEST_USER_ID;
         return tr;
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/PinnedStackControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/PinnedStackControllerTest.java
deleted file mode 100644
index e9c2263..0000000
--- a/services/tests/wmtests/src/com/android/server/wm/PinnedStackControllerTest.java
+++ /dev/null
@@ -1,82 +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 static android.view.Display.DEFAULT_DISPLAY;
-
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.never;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.reset;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.eq;
-
-import android.os.RemoteException;
-import android.platform.test.annotations.Presubmit;
-import android.view.IPinnedStackListener;
-
-import androidx.test.filters.SmallTest;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-/**
- * Build/Install/Run:
- *  atest FrameworksServicesTests:PinnedStackControllerTest
- */
-@SmallTest
-@Presubmit
-public class PinnedStackControllerTest extends WindowTestsBase {
-
-    private static final int SHELF_HEIGHT = 300;
-
-    @Mock private IPinnedStackListener mIPinnedStackListener;
-    @Mock private IPinnedStackListener.Stub mIPinnedStackListenerStub;
-
-    @Before
-    public void setUp() throws Exception {
-        MockitoAnnotations.initMocks(this);
-
-        when(mIPinnedStackListener.asBinder()).thenReturn(mIPinnedStackListenerStub);
-    }
-
-    @Test
-    public void setShelfHeight_shelfVisibilityChangedTriggered() throws RemoteException {
-        mWm.mAtmService.mSupportsPictureInPicture = true;
-        mWm.registerPinnedStackListener(DEFAULT_DISPLAY, mIPinnedStackListener);
-
-        verify(mIPinnedStackListener).onImeVisibilityChanged(false, 0);
-        verify(mIPinnedStackListener).onShelfVisibilityChanged(false, 0);
-        verify(mIPinnedStackListener).onMovementBoundsChanged(any(), eq(false),
-                eq(false));
-        verify(mIPinnedStackListener).onActionsChanged(any());
-        verify(mIPinnedStackListener).onMinimizedStateChanged(anyBoolean());
-
-        reset(mIPinnedStackListener);
-
-        mWm.setShelfHeight(true, SHELF_HEIGHT);
-        verify(mIPinnedStackListener).onShelfVisibilityChanged(true, SHELF_HEIGHT);
-        verify(mIPinnedStackListener).onMovementBoundsChanged(any(), eq(false),
-                eq(true));
-        verify(mIPinnedStackListener, never()).onImeVisibilityChanged(anyBoolean(), anyInt());
-    }
-}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ProtoLogIntegrationTest.java b/services/tests/wmtests/src/com/android/server/wm/ProtoLogIntegrationTest.java
new file mode 100644
index 0000000..acbbc46
--- /dev/null
+++ b/services/tests/wmtests/src/com/android/server/wm/ProtoLogIntegrationTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2019 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.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.server.protolog.ProtoLogImpl;
+
+import org.junit.After;
+import org.junit.Test;
+
+/**
+ * Check if the ProtoLogTools is used to process the WindowManager source code.
+ */
+@SmallTest
+@Presubmit
+public class ProtoLogIntegrationTest {
+    @After
+    public void tearDown() {
+        ProtoLogImpl.setSingleInstance(null);
+    }
+
+    @Test
+    public void testProtoLogToolIntegration() {
+        ProtoLogImpl mockedProtoLog = mock(ProtoLogImpl.class);
+        ProtoLogImpl.setSingleInstance(mockedProtoLog);
+        ProtoLogGroup.testProtoLog();
+        verify(mockedProtoLog).log(eq(ProtoLogImpl.LogLevel.ERROR), eq(
+                ProtoLogGroup.TEST_GROUP),
+                anyInt(), eq(0b0010101001010111),
+                eq(ProtoLogGroup.TEST_GROUP.isLogToLogcat()
+                        ? "Test completed successfully: %b %d %o %x %e %g %f %% %s"
+                        : null),
+                eq(new Object[]{true, 1L, 2L, 3L, 0.4, 0.5, 0.6, "ok"}));
+    }
+}
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
index 94abd34..cc598ff 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
@@ -63,7 +63,6 @@
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 import android.util.ArraySet;
-import android.util.MutableLong;
 import android.util.SparseBooleanArray;
 
 import androidx.test.filters.MediumTest;
@@ -72,6 +71,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.io.File;
 import java.util.ArrayList;
@@ -86,6 +86,7 @@
  */
 @MediumTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class RecentTasksTest extends ActivityTestsBase {
     private static final int TEST_USER_0_ID = 0;
     private static final int TEST_USER_1_ID = 10;
@@ -95,10 +96,7 @@
     private static final int INVALID_STACK_ID = 999;
 
     private ActivityDisplay mDisplay;
-    private ActivityDisplay mOtherDisplay;
-    private ActivityDisplay mSingleTaskDisplay;
     private ActivityStack mStack;
-    private ActivityStack mHomeStack;
     private TestTaskPersister mTaskPersister;
     private TestRecentTasks mRecentTasks;
     private TestRunningTasks mRunningTasks;
@@ -111,15 +109,7 @@
     @Before
     public void setUp() throws Exception {
         mTaskPersister = new TestTaskPersister(mContext.getFilesDir());
-
-        // Set testing displays
         mDisplay = mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
-        mOtherDisplay = createNewActivityDisplay();
-        mSingleTaskDisplay = createNewActivityDisplay();
-        mSingleTaskDisplay.setDisplayToSingleTaskInstance();
-        mRootActivityContainer.addChild(mOtherDisplay, ActivityDisplay.POSITION_TOP);
-        mRootActivityContainer.addChild(mDisplay, ActivityDisplay.POSITION_TOP);
-        mRootActivityContainer.addChild(mSingleTaskDisplay, ActivityDisplay.POSITION_TOP);
 
         // Set the recent tasks we should use for testing in this class.
         mRecentTasks = new TestRecentTasks(mService, mTaskPersister);
@@ -131,8 +121,6 @@
         mRunningTasks = new TestRunningTasks();
         mService.mStackSupervisor.setRunningTasks(mRunningTasks);
 
-        mHomeStack = mDisplay.getOrCreateStack(
-                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
         mStack = mDisplay.createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
         mCallbacksRecorder = new CallbacksRecorder();
@@ -269,7 +257,7 @@
         // other task
         TaskRecord task1 = createTaskBuilder(".Task1")
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
-                .setStack(mHomeStack).build();
+                .setStack(mDisplay.getHomeStack()).build();
         TaskRecord task2 = createTaskBuilder(".Task1")
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .setStack(mStack).build();
@@ -446,12 +434,12 @@
         mRecentTasks.add(task3);
         mRecentTasks.add(task4);
 
-        MutableLong prevLastActiveTime = new MutableLong(0);
+        long prevLastActiveTime = 0;
         final ArrayList<TaskRecord> tasks = mRecentTasks.getRawTasks();
         for (int i = 0; i < tasks.size(); i++) {
             final TaskRecord task = tasks.get(i);
-            assertThat(prevLastActiveTime.value).isLessThan(task.lastActiveTime);
-            prevLastActiveTime.value = task.lastActiveTime;
+            assertThat(prevLastActiveTime).isLessThan(task.lastActiveTime);
+            prevLastActiveTime = task.lastActiveTime;
         }
     }
 
@@ -618,7 +606,10 @@
         mRecentTasks.setOnlyTestVisibleRange();
         mRecentTasks.setParameters(-1 /* min */, 3 /* max */, -1 /* ms */);
 
-        ActivityStack singleTaskStack = mSingleTaskDisplay.createStack(
+        final ActivityDisplay singleTaskDisplay =
+                addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+        singleTaskDisplay.setDisplayToSingleTaskInstance();
+        ActivityStack singleTaskStack = singleTaskDisplay.createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
 
         TaskRecord excludedTask1 = createTaskBuilder(".ExcludedTask1")
@@ -795,7 +786,8 @@
         mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */);
 
         final ActivityStack homeStack = mDisplay.getHomeStack();
-        final ActivityStack otherDisplayStack = mOtherDisplay.createStack(
+        final ActivityDisplay otherDisplay = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
+        final ActivityStack otherDisplayStack = otherDisplay.createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
 
         // Add a number of tasks (beyond the max) on each display, ensure that the tasks are not
@@ -890,7 +882,7 @@
     @Test
     public void testNotRestoreRecentTaskApis() {
         final TaskRecord task = createTaskBuilder(".Task").build();
-        final int taskId = task.taskId;
+        final int taskId = task.mTaskId;
         mRecentTasks.add(task);
         // Only keep the task in RecentTasks.
         task.removeWindowContainer();
@@ -976,7 +968,7 @@
                 TEST_USER_0_ID, 0).getList();
         assertTrue(expectedTasks.length == infos.size());
         for (int i = 0; i < infos.size(); i++)  {
-            assertTrue(expectedTasks[i].taskId == infos.get(i).taskId);
+            assertTrue(expectedTasks[i].mTaskId == infos.get(i).taskId);
         }
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
index f792b0d..f353846 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java
@@ -66,15 +66,17 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
 /**
  * Build/Install/Run:
- *  atest FrameworksServicesTests:RecentsAnimationControllerTest
+ *  atest WmTests:RecentsAnimationControllerTest
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class RecentsAnimationControllerTest extends WindowTestsBase {
 
     @Mock SurfaceControl mMockLeash;
@@ -88,12 +90,8 @@
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        synchronized (mWm.mGlobalLock) {
-            // Hold the lock to protect the stubbing from being accessed by other threads.
-            spyOn(mWm.mRoot);
-            doNothing().when(mWm.mRoot).performSurfacePlacement(anyBoolean());
-            doReturn(mDisplayContent).when(mWm.mRoot).getDisplayContent(anyInt());
-        }
+        doNothing().when(mWm.mRoot).performSurfacePlacement(anyBoolean());
+        doReturn(mDisplayContent).when(mWm.mRoot).getDisplayContent(anyInt());
         when(mMockRunner.asBinder()).thenReturn(new Binder());
         mController = spy(new RecentsAnimationController(mWm, mMockRunner, mAnimationCallbacks,
                 DEFAULT_DISPLAY));
@@ -140,14 +138,13 @@
     @Test
     public void testIncludedApps_expectTargetAndVisible() {
         mWm.setRecentsAnimationController(mController);
-        final ActivityStack homeStack = mDisplayContent.mAcitvityDisplay.getOrCreateStack(
+        final ActivityStack homeStack = mDisplayContent.mActivityDisplay.getOrCreateStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
         final AppWindowToken homeAppWindow =
                 new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
                         .setStack(homeStack)
                         .setCreateTask(true)
-                        .build()
-                        .mAppWindowToken;
+                        .build();
         final AppWindowToken appWindow = createAppWindowToken(mDisplayContent,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
         final AppWindowToken hiddenAppWindow = createAppWindowToken(mDisplayContent,
@@ -166,14 +163,13 @@
     @Test
     public void testWallpaperIncluded_expectTarget() throws Exception {
         mWm.setRecentsAnimationController(mController);
-        final ActivityStack homeStack = mDisplayContent.mAcitvityDisplay.getOrCreateStack(
+        final ActivityStack homeStack = mDisplayContent.mActivityDisplay.getOrCreateStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
         final AppWindowToken homeAppWindow =
                 new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
                         .setStack(homeStack)
                         .setCreateTask(true)
-                        .build()
-                        .mAppWindowToken;
+                        .build();
         final AppWindowToken appWindow = createAppWindowToken(mDisplayContent,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
         final WindowState win1 = createWindow(null, TYPE_BASE_APPLICATION, appWindow, "win1");
@@ -196,14 +192,13 @@
     @Test
     public void testWallpaperAnimatorCanceled_expectAnimationKeepsRunning() throws Exception {
         mWm.setRecentsAnimationController(mController);
-        final ActivityStack homeStack = mDisplayContent.mAcitvityDisplay.getOrCreateStack(
+        final ActivityStack homeStack = mDisplayContent.mActivityDisplay.getOrCreateStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
         final AppWindowToken homeAppWindow =
                 new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
                         .setStack(homeStack)
                         .setCreateTask(true)
-                        .build()
-                        .mAppWindowToken;
+                        .build();
         final AppWindowToken appWindow = createAppWindowToken(mDisplayContent,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
         final WindowState win1 = createWindow(null, TYPE_BASE_APPLICATION, appWindow, "win1");
@@ -228,14 +223,13 @@
     @Test
     public void testFinish_expectTargetAndWallpaperAdaptersRemoved() {
         mWm.setRecentsAnimationController(mController);
-        final ActivityStack homeStack = mDisplayContent.mAcitvityDisplay.getOrCreateStack(
+        final ActivityStack homeStack = mDisplayContent.mActivityDisplay.getOrCreateStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, ON_TOP);
         final AppWindowToken homeAppWindow =
                 new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
                         .setStack(homeStack)
                         .setCreateTask(true)
-                        .build()
-                        .mAppWindowToken;
+                        .build();
         final WindowState hwin1 = createWindow(null, TYPE_BASE_APPLICATION, homeAppWindow, "hwin1");
         homeAppWindow.addWindow(hwin1);
         final AppWindowToken appWindow = createAppWindowToken(mDisplayContent,
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
index b4ccd50..ebedde7 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
@@ -97,7 +97,6 @@
                 .setStack(recentsStack)
                 .build();
         ActivityRecord topActivity = new ActivityBuilder(mService).setCreateTask(true).build();
-        topActivity.fullscreen = true;
         topActivity.getActivityStack().moveToFront("testRecentsActivityVisiblility");
 
         doCallRealMethod().when(mRootActivityContainer).ensureActivitiesVisible(
@@ -346,7 +345,7 @@
                 .setCreateTask(true)
                 .setComponent(new ComponentName(mContext.getPackageName(), "Home2"))
                 .build();
-        otherUserHomeActivity.getTaskRecord().userId = TEST_USER_ID;
+        otherUserHomeActivity.getTaskRecord().mUserId = TEST_USER_ID;
 
         ActivityStack fullscreenStack = display.createStack(WINDOWING_MODE_FULLSCREEN,
                 ACTIVITY_TYPE_STANDARD, true /* onTop */);
diff --git a/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java
index db105dd..afe18c3 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java
@@ -31,6 +31,7 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for RootWindowContainer.
@@ -40,6 +41,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class RootWindowContainerTests extends WindowTestsBase {
 
     private static final int FAKE_CALLING_UID = 667;
@@ -91,18 +93,16 @@
 
     @Test
     public void testUpdateDefaultDisplayWindowingModeOnSettingsRetrieved() {
-        synchronized (mWm.mGlobalLock) {
-            assertEquals(WindowConfiguration.WINDOWING_MODE_FULLSCREEN,
-                    mWm.getDefaultDisplayContentLocked().getWindowingMode());
+        assertEquals(WindowConfiguration.WINDOWING_MODE_FULLSCREEN,
+                mWm.getDefaultDisplayContentLocked().getWindowingMode());
 
-            mWm.mIsPc = true;
-            mWm.mAtmService.mSupportsFreeformWindowManagement = true;
+        mWm.mIsPc = true;
+        mWm.mAtmService.mSupportsFreeformWindowManagement = true;
 
-            mWm.mRoot.onSettingsRetrieved();
+        mWm.mRoot.onSettingsRetrieved();
 
-            assertEquals(WindowConfiguration.WINDOWING_MODE_FREEFORM,
-                    mWm.getDefaultDisplayContentLocked().getWindowingMode());
-        }
+        assertEquals(WindowConfiguration.WINDOWING_MODE_FREEFORM,
+                mWm.getDefaultDisplayContentLocked().getWindowingMode());
     }
 }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
index 3e316f6..8326ad8 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
@@ -35,6 +35,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 
@@ -44,6 +45,7 @@
  */
 @MediumTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class RunningTasksTest extends ActivityTestsBase {
 
     private static final ArraySet<Integer> PROFILE_IDS = new ArraySet<>();
diff --git a/services/tests/wmtests/src/com/android/server/wm/StubTransaction.java b/services/tests/wmtests/src/com/android/server/wm/StubTransaction.java
index 8d2a79b..f5d08dc 100644
--- a/services/tests/wmtests/src/com/android/server/wm/StubTransaction.java
+++ b/services/tests/wmtests/src/com/android/server/wm/StubTransaction.java
@@ -97,11 +97,6 @@
     }
 
     @Override
-    public SurfaceControl.Transaction transferTouchFocus(IBinder fromToken, IBinder toToken) {
-        return this;
-    }
-
-    @Override
     public SurfaceControl.Transaction setGeometry(SurfaceControl sc, Rect sourceCrop,
             Rect destFrame, @Surface.Rotation int orientation) {
         return this;
@@ -244,4 +239,15 @@
     public SurfaceControl.Transaction remove(SurfaceControl sc) {
         return this;
     }
+
+    @Override
+    public SurfaceControl.Transaction syncInputWindows() {
+        return this;
+    }
+
+    @Override
+    public SurfaceControl.Transaction setColorSpaceAgnostic(SurfaceControl sc, boolean agnostic) {
+        return this;
+    }
+
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/SystemServiceTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/SystemServiceTestsBase.java
new file mode 100644
index 0000000..d1b6f6f
--- /dev/null
+++ b/services/tests/wmtests/src/com/android/server/wm/SystemServiceTestsBase.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2019 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.os.Handler;
+import android.testing.DexmakerShareClassLoaderRule;
+
+import org.junit.Rule;
+
+import java.util.concurrent.Callable;
+
+/** The base class which provides the common rule for test classes under wm package. */
+class SystemServiceTestsBase {
+    @Rule
+    public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
+            new DexmakerShareClassLoaderRule();
+    @Rule
+    public final SystemServicesTestRule mSystemServicesTestRule = new SystemServicesTestRule();
+
+    @WindowTestRunner.MethodWrapperRule
+    public final WindowManagerGlobalLockRule mLockRule =
+            new WindowManagerGlobalLockRule(mSystemServicesTestRule);
+
+    /** Waits until the main handler for WM has processed all messages. */
+    void waitUntilHandlersIdle() {
+        mLockRule.waitForLocked(mSystemServicesTestRule::waitUntilWindowManagerHandlersIdle);
+    }
+
+    boolean waitHandlerIdle(Handler handler) {
+        return waitHandlerIdle(handler, 0 /* timeout */);
+    }
+
+    boolean waitHandlerIdle(Handler handler, long timeout) {
+        return runWithScissors(handler, () -> { }, timeout);
+    }
+
+    boolean runWithScissors(Handler handler, Runnable r, long timeout) {
+        return mLockRule.runWithScissors(handler, r, timeout);
+    }
+
+    /** It is used when we want to wait for a result inside {@link WindowManagerGlobalLock}. */
+    <T> T awaitInWmLock(Callable<T> callable) {
+        return mLockRule.waitForLocked(callable);
+    }
+}
diff --git a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
index 5a4d399..ef9821b 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
@@ -18,7 +18,6 @@
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
-import static android.os.Process.THREAD_PRIORITY_DEFAULT;
 import static android.testing.DexmakerShareClassLoaderRule.runWithDexmakerShareClassLoader;
 import static android.view.Display.DEFAULT_DISPLAY;
 
@@ -36,7 +35,6 @@
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.nullable;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
-import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.app.ActivityManagerInternal;
 import android.app.AppOpsManager;
@@ -68,11 +66,12 @@
 import com.android.server.DisplayThread;
 import com.android.server.LocalServices;
 import com.android.server.LockGuard;
-import com.android.server.ServiceThread;
+import com.android.server.UiThread;
 import com.android.server.Watchdog;
 import com.android.server.am.ActivityManagerService;
 import com.android.server.appop.AppOpsService;
 import com.android.server.display.color.ColorDisplayService;
+import com.android.server.firewall.IntentFirewall;
 import com.android.server.input.InputManagerService;
 import com.android.server.pm.UserManagerService;
 import com.android.server.policy.PermissionPolicyInternal;
@@ -105,13 +104,13 @@
 
     private Context mContext;
     private StaticMockitoSession mMockitoSession;
-    ServiceThread mHandlerThread;
     private ActivityManagerService mAmService;
     private ActivityTaskManagerService mAtmService;
     private WindowManagerService mWmService;
     private TestWindowManagerPolicy mWMPolicy;
     private WindowState.PowerManagerWrapper mPowerManagerWrapper;
     private InputManagerService mImService;
+    private InputChannel mInputChannel;
     /**
      * Spied {@link SurfaceControl.Transaction} class than can be used to verify calls.
      */
@@ -147,10 +146,6 @@
     }
 
     private void setUpSystemCore() {
-        mHandlerThread = new ServiceThread(
-                "WmTestsThread", THREAD_PRIORITY_DEFAULT, true /* allowIo */);
-        mHandlerThread.start();
-
         doReturn(mock(Watchdog.class)).when(Watchdog::getInstance);
 
         mContext = getInstrumentation().getTargetContext();
@@ -181,6 +176,11 @@
         final AppOpsManager aom = mock(AppOpsManager.class);
         doReturn(aom).when(mContext).getSystemService(eq(Context.APP_OPS_SERVICE));
 
+        // Prevent "WakeLock finalized while still held: SCREEN_FROZEN".
+        final PowerManager pm = mock(PowerManager.class);
+        doReturn(pm).when(mContext).getSystemService(eq(Context.POWER_SERVICE));
+        doReturn(mock(PowerManager.WakeLock.class)).when(pm).newWakeLock(anyInt(), anyString());
+
         // DisplayManagerInternal
         final DisplayManagerInternal dmi = mock(DisplayManagerInternal.class);
         doReturn(dmi).when(() -> LocalServices.getService(eq(DisplayManagerInternal.class)));
@@ -214,11 +214,11 @@
 
         // InputManagerService
         mImService = mock(InputManagerService.class);
-        // InputChannel is final and can't be mocked.
-        final InputChannel[] input = InputChannel.openInputChannelPair(TAG_WM);
-        if (input != null && input.length > 1) {
-            doReturn(input[1]).when(mImService).monitorInput(anyString(), anyInt());
-        }
+        // InputChannel cannot be mocked because it may pass to InputEventReceiver.
+        final InputChannel[] inputChannels = InputChannel.openInputChannelPair(TAG);
+        inputChannels[0].dispose();
+        mInputChannel = inputChannels[1];
+        doReturn(mInputChannel).when(mImService).monitorInput(anyString(), anyInt());
 
         // StatusBarManagerInternal
         final StatusBarManagerInternal sbmi = mock(StatusBarManagerInternal.class);
@@ -227,8 +227,7 @@
 
     private void setUpActivityTaskManagerService() {
         // ActivityManagerService
-        mAmService = new ActivityManagerService(
-                new AMTestInjector(mContext, mHandlerThread), mHandlerThread);
+        mAmService = new ActivityManagerService(new AMTestInjector(mContext), null /* thread */);
         spyOn(mAmService);
         doReturn(mock(IPackageManager.class)).when(mAmService).getPackageManager();
         doNothing().when(mAmService).grantImplicitAccess(
@@ -246,6 +245,15 @@
         doNothing().when(amInternal).startProcess(
                 any(), any(), anyBoolean(), anyBoolean(), any(), any());
         doNothing().when(amInternal).updateOomLevelsForDisplay(anyInt());
+        doNothing().when(amInternal).broadcastGlobalConfigurationChanged(anyInt(), anyBoolean());
+        doNothing().when(amInternal).cleanUpServices(anyInt(), any(), any());
+        doReturn(UserHandle.USER_SYSTEM).when(amInternal).getCurrentUserId();
+        doReturn(TEST_USER_PROFILE_IDS).when(amInternal).getCurrentProfileIds();
+        doReturn(true).when(amInternal).isCurrentProfile(anyInt());
+        doReturn(true).when(amInternal).isUserRunning(anyInt(), anyInt());
+        doReturn(true).when(amInternal).hasStartedUserState(anyInt());
+        doReturn(false).when(amInternal).shouldConfirmCredentials(anyInt());
+        doReturn(false).when(amInternal).isActivityStartsLoggingEnabled();
         LocalServices.addService(ActivityManagerInternal.class, amInternal);
 
         mAtmService = new TestActivityTaskManagerService(mContext, mAmService);
@@ -289,7 +297,6 @@
     }
 
     private void tearDown() {
-        waitUntilWindowManagerHandlersIdle();
         // Unregister display listener from root to avoid issues with subsequent tests.
         mContext.getSystemService(DisplayManager.class)
                 .unregisterDisplayListener(mAtmService.mRootActivityContainer);
@@ -297,37 +304,23 @@
         // a static object, so we need to clean it up in tearDown(), even though we didn't set up
         // in tests.
         DeviceConfig.removeOnPropertiesChangedListener(mWmService.mPropertiesChangedListener);
-        mWmService = null;
-        mWMPolicy = null;
-        mPowerManagerWrapper = null;
 
-        tearDownLocalServices();
-        tearDownSystemCore();
-
+        waitUntilWindowManagerHandlersIdle();
         // Needs to explicitly dispose current static threads because there could be messages
         // scheduled at a later time, and all mocks are invalid when it's executed.
         DisplayThread.dispose();
         AnimationThread.dispose();
+        UiThread.dispose();
+        mInputChannel.dispose();
+
+        tearDownLocalServices();
         // Reset priority booster because animation thread has been changed.
         WindowManagerService.sThreadPriorityBooster = new WindowManagerThreadPriorityBooster();
 
+        mMockitoSession.finishMocking();
         Mockito.framework().clearInlineMocks();
     }
 
-    private void tearDownSystemCore() {
-        if (mMockitoSession != null) {
-            mMockitoSession.finishMocking();
-            mMockitoSession = null;
-        }
-
-        if (mHandlerThread != null) {
-            // Make sure there are no running messages and then quit the thread so the next test
-            // won't be affected.
-            mHandlerThread.getThreadHandler().runWithScissors(mHandlerThread::quit,
-                    0 /* timeout */);
-        }
-    }
-
     private static void tearDownLocalServices() {
         LocalServices.removeServiceForTest(DisplayManagerInternal.class);
         LocalServices.removeServiceForTest(PowerManagerInternal.class);
@@ -375,7 +368,6 @@
         waitHandlerIdle(wm.mH);
         waitHandlerIdle(wm.mAnimationHandler);
         waitHandlerIdle(SurfaceAnimationThread.getHandler());
-        waitHandlerIdle(mHandlerThread.getThreadHandler());
     }
 
     private void waitHandlerIdle(Handler handler) {
@@ -435,8 +427,12 @@
             ams.mActivityTaskManager = this;
             ams.mAtmInternal = mInternal;
             onActivityManagerInternalAdded();
-            initialize(
-                    ams.mIntentFirewall, ams.mPendingIntentController, mHandlerThread.getLooper());
+
+            final IntentFirewall intentFirewall = mock(IntentFirewall.class);
+            doReturn(true).when(intentFirewall).checkStartActivity(
+                    any(), anyInt(), anyInt(), nullable(String.class), any());
+            initialize(intentFirewall, null /* intentController */,
+                    DisplayThread.getHandler().getLooper());
             spyOn(getLifecycleManager());
             spyOn(getLockTaskController());
             spyOn(getTaskChangeNotificationController());
@@ -493,11 +489,9 @@
 
     // TODO: Can we just mock this?
     private static class AMTestInjector extends ActivityManagerService.Injector {
-        private ServiceThread mHandlerThread;
 
-        AMTestInjector(Context context, ServiceThread handlerThread) {
+        AMTestInjector(Context context) {
             super(context);
-            mHandlerThread = handlerThread;
         }
 
         @Override
@@ -512,7 +506,7 @@
 
         @Override
         public Handler getUiHandler(ActivityManagerService service) {
-            return mHandlerThread.getThreadHandler();
+            return UiThread.getHandler();
         }
 
         @Override
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
index e6c9b9f..dd85f69 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
@@ -29,6 +29,8 @@
 import static android.util.DisplayMetrics.DENSITY_DEFAULT;
 import static android.view.Display.DEFAULT_DISPLAY;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
 import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
 
@@ -65,6 +67,10 @@
 @SmallTest
 @Presubmit
 public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
+    private static final Rect DISPLAY_BOUNDS = new Rect(/* left */ 0, /* top */ 0,
+            /* right */ 1920, /* bottom */ 1080);
+    private static final Rect DISPLAY_STABLE_BOUNDS = new Rect(/* left */ 100,
+            /* top */ 200, /* right */ 1620, /* bottom */ 680);
 
     private ActivityRecord mActivity;
 
@@ -614,7 +620,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(0, mResult.mBounds.left);
+        assertEquals(DISPLAY_STABLE_BOUNDS.left, mResult.mBounds.left);
     }
 
     @Test
@@ -630,7 +636,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(0, mResult.mBounds.top);
+        assertEquals(DISPLAY_STABLE_BOUNDS.top, mResult.mBounds.top);
     }
 
     @Test
@@ -646,8 +652,8 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(0, mResult.mBounds.left);
-        assertEquals(0, mResult.mBounds.top);
+        assertEquals(DISPLAY_STABLE_BOUNDS.left, mResult.mBounds.left);
+        assertEquals(DISPLAY_STABLE_BOUNDS.top, mResult.mBounds.top);
     }
 
     @Test
@@ -663,7 +669,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(1920, mResult.mBounds.right);
+        assertEquals(DISPLAY_STABLE_BOUNDS.right, mResult.mBounds.right);
     }
 
     @Test
@@ -679,7 +685,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(1080, mResult.mBounds.bottom);
+        assertEquals(DISPLAY_STABLE_BOUNDS.bottom, mResult.mBounds.bottom);
     }
 
     @Test
@@ -695,8 +701,8 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(1920, mResult.mBounds.right);
-        assertEquals(1080, mResult.mBounds.bottom);
+        assertEquals(DISPLAY_STABLE_BOUNDS.right, mResult.mBounds.right);
+        assertEquals(DISPLAY_STABLE_BOUNDS.bottom, mResult.mBounds.bottom);
     }
 
     @Test
@@ -712,7 +718,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(900, 500, 1020, 580), mResult.mBounds);
+        assertEquals(new Rect(800, 400, 920, 480), mResult.mBounds);
     }
 
     @Test
@@ -728,7 +734,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(0, 500, 120, 580), mResult.mBounds);
+        assertEquals(new Rect(100, 400, 220, 480), mResult.mBounds);
     }
 
     @Test
@@ -744,7 +750,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(900, 0, 1020, 80), mResult.mBounds);
+        assertEquals(new Rect(800, 200, 920, 280), mResult.mBounds);
     }
 
     @Test
@@ -760,7 +766,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(0, 0, 120, 80), mResult.mBounds);
+        assertEquals(new Rect(100, 200, 220, 280), mResult.mBounds);
     }
 
     @Test
@@ -776,7 +782,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(1800, 500, 1920, 580), mResult.mBounds);
+        assertEquals(new Rect(1500, 400, 1620, 480), mResult.mBounds);
     }
 
     @Test
@@ -792,7 +798,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(900, 1000, 1020, 1080), mResult.mBounds);
+        assertEquals(new Rect(800, 600, 920, 680), mResult.mBounds);
     }
 
     @Test
@@ -808,7 +814,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(1800, 1000, 1920, 1080), mResult.mBounds);
+        assertEquals(new Rect(1500, 600, 1620, 680), mResult.mBounds);
     }
 
     @Test
@@ -819,12 +825,12 @@
         mCurrent.mPreferredDisplayId = freeformDisplay.mDisplayId;
 
         final ActivityInfo.WindowLayout layout = new WindowLayoutBuilder()
-                .setWidthFraction(0.0625f).setHeightFraction(0.1f).build();
+                .setWidthFraction(0.125f).setHeightFraction(0.1f).build();
 
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, layout, mActivity,
                 /* source */ null, /* options */ null, mCurrent, mResult));
 
-        assertEquals(new Rect(900, 486, 1020, 594), mResult.mBounds);
+        assertEquals(new Rect(765, 416, 955, 464), mResult.mBounds);
     }
 
     @Test
@@ -952,13 +958,12 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null,
                 mActivity, /* source */ null, options, mCurrent, mResult));
 
-        final Rect displayBounds = freeformDisplay.getBounds();
         assertEquals("Distance to left and right should be equal.",
-                mResult.mBounds.left - displayBounds.left,
-                displayBounds.right - mResult.mBounds.right);
+                mResult.mBounds.left - DISPLAY_STABLE_BOUNDS.left,
+                DISPLAY_STABLE_BOUNDS.right - mResult.mBounds.right, /* delta */ 1);
         assertEquals("Distance to top and bottom should be equal.",
-                mResult.mBounds.top - displayBounds.top,
-                displayBounds.bottom - mResult.mBounds.bottom);
+                mResult.mBounds.top - DISPLAY_STABLE_BOUNDS.top,
+                DISPLAY_STABLE_BOUNDS.bottom - mResult.mBounds.bottom, /* delta */ 1);
     }
 
     @Test
@@ -1041,15 +1046,16 @@
         options.setLaunchDisplayId(freeformDisplay.mDisplayId);
 
         mCurrent.mWindowingMode = WINDOWING_MODE_FREEFORM;
-        mCurrent.mBounds.set(100, 200, 2120, 1380);
+        mCurrent.mBounds.set(100, 300, 1820, 1380);
 
         mActivity.info.applicationInfo.targetSdkVersion = Build.VERSION_CODES.LOLLIPOP;
 
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null,
                 mActivity, /* source */ null, options, mCurrent, mResult));
 
-        assertTrue("Result bounds should start from origin, but it's " + mResult.mBounds,
-                mResult.mBounds.left == 0 && mResult.mBounds.top == 0);
+        assertTrue("Result bounds should start from app bounds's origin, but it's "
+                        + mResult.mBounds,
+                mResult.mBounds.left == 100 && mResult.mBounds.top == 200);
     }
 
     @Test
@@ -1067,15 +1073,16 @@
         options.setLaunchDisplayId(freeformDisplay.mDisplayId);
 
         mCurrent.mWindowingMode = WINDOWING_MODE_FREEFORM;
-        mCurrent.mBounds.set(100, 200, 2120, 1380);
+        mCurrent.mBounds.set(100, 300, 1820, 1380);
 
         mActivity.info.applicationInfo.targetSdkVersion = Build.VERSION_CODES.LOLLIPOP;
 
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null,
                 mActivity, /* source */ null, options, mCurrent, mResult));
 
-        assertTrue("Result bounds should start from origin, but it's " + mResult.mBounds,
-                mResult.mBounds.left == -100 && mResult.mBounds.top == 0);
+        assertTrue("Result bounds should start from top-right corner of app bounds, but "
+                        + "it's " + mResult.mBounds,
+                mResult.mBounds.left == -100 && mResult.mBounds.top == 200);
     }
 
     @Test
@@ -1083,6 +1090,11 @@
         final TestActivityDisplay freeformDisplay = createNewActivityDisplay(
                 WINDOWING_MODE_FREEFORM);
 
+        // This test case requires a relatively big app bounds to ensure the default size calculated
+        // by letterbox won't be too small to hold the minimum width/height.
+        freeformDisplay.mDisplayContent.mDisplayFrames.mStable.set(/* left */ 10, /* top */ 10,
+                /* right */ 1910, /* top */ 1070);
+
         final ActivityOptions options = ActivityOptions.makeBasic();
         options.setLaunchDisplayId(freeformDisplay.mDisplayId);
 
@@ -1245,7 +1257,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null,
                 mActivity, /* source */ null, options, mCurrent, mResult));
 
-        assertEquals(new Rect(0, 0, 300, 300), mResult.mBounds);
+        assertEquals(new Rect(100, 200, 400, 500), mResult.mBounds);
     }
 
     @Test
@@ -1301,9 +1313,15 @@
     private TestActivityDisplay createNewActivityDisplay(int windowingMode) {
         final TestActivityDisplay display = addNewActivityDisplayAt(ActivityDisplay.POSITION_TOP);
         display.setWindowingMode(windowingMode);
-        display.setBounds(/* left */ 0, /* top */ 0, /* right */ 1920, /* bottom */ 1080);
+        display.setBounds(DISPLAY_BOUNDS);
         display.getConfiguration().densityDpi = DENSITY_DEFAULT;
         display.getConfiguration().orientation = ORIENTATION_LANDSCAPE;
+        display.mDisplayContent.mDisplayFrames.mStable.set(DISPLAY_STABLE_BOUNDS);
+        spyOn(display.mDisplayContent.mDisplayFrames);
+
+        // We didn't set up the overall environment for this test, so we need to mute the side
+        // effect of layout passes that loosen the stable frame.
+        doNothing().when(display.mDisplayContent.mDisplayFrames).onBeginLayout();
         return display;
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java
index 714d2f2..dc89f50 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java
@@ -18,10 +18,10 @@
 
 import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyInt;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
 
 import static org.junit.Assert.assertFalse;
@@ -37,6 +37,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link TaskPositioningController} class.
@@ -46,6 +47,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class TaskPositioningControllerTests extends WindowTestsBase {
     private static final int TIMEOUT_MS = 1000;
 
@@ -57,32 +59,29 @@
         assertNotNull(mWm.mTaskPositioningController);
         mTarget = mWm.mTaskPositioningController;
 
+        when(mWm.mInputManager.transferTouchFocus(
+                any(InputChannel.class),
+                any(InputChannel.class))).thenReturn(true);
+
         mWindow = createWindow(null, TYPE_BASE_APPLICATION, "window");
         mWindow.mInputChannel = new InputChannel();
-        synchronized (mWm.mGlobalLock) {
-            mWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow);
-            spyOn(mDisplayContent);
-            doReturn(mock(InputMonitor.class)).when(mDisplayContent).getInputMonitor();
-        }
+        mWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow);
+        doReturn(mock(InputMonitor.class)).when(mDisplayContent).getInputMonitor();
     }
 
     @Test
     public void testStartAndFinishPositioning() {
-        synchronized (mWm.mGlobalLock) {
-            assertFalse(mTarget.isPositioningLocked());
-            assertNull(mTarget.getDragWindowHandleLocked());
-        }
+        assertFalse(mTarget.isPositioningLocked());
+        assertNull(mTarget.getDragWindowHandleLocked());
 
         assertTrue(mTarget.startMovingTask(mWindow.mClient, 0, 0));
 
-        synchronized (mWm.mGlobalLock) {
-            assertTrue(mTarget.isPositioningLocked());
-            assertNotNull(mTarget.getDragWindowHandleLocked());
-        }
+        assertTrue(mTarget.isPositioningLocked());
+        assertNotNull(mTarget.getDragWindowHandleLocked());
 
         mTarget.finishTaskPositioning();
         // Wait until the looper processes finishTaskPositioning.
-        assertTrue(mWm.mH.runWithScissors(() -> { }, TIMEOUT_MS));
+        assertTrue(waitHandlerIdle(mWm.mH, TIMEOUT_MS));
 
         assertFalse(mTarget.isPositioningLocked());
         assertNull(mTarget.getDragWindowHandleLocked());
@@ -91,21 +90,17 @@
     @FlakyTest(bugId = 129507487)
     @Test
     public void testFinishPositioningWhenAppRequested() {
-        synchronized (mWm.mGlobalLock) {
-            assertFalse(mTarget.isPositioningLocked());
-            assertNull(mTarget.getDragWindowHandleLocked());
-        }
+        assertFalse(mTarget.isPositioningLocked());
+        assertNull(mTarget.getDragWindowHandleLocked());
 
         assertTrue(mTarget.startMovingTask(mWindow.mClient, 0, 0));
 
-        synchronized (mWm.mGlobalLock) {
-            assertTrue(mTarget.isPositioningLocked());
-            assertNotNull(mTarget.getDragWindowHandleLocked());
-        }
+        assertTrue(mTarget.isPositioningLocked());
+        assertNotNull(mTarget.getDragWindowHandleLocked());
 
         mTarget.finishTaskPositioning(mWindow.mClient);
         // Wait until the looper processes finishTaskPositioning.
-        assertTrue(mWm.mH.runWithScissors(() -> { }, TIMEOUT_MS));
+        assertTrue(waitHandlerIdle(mWm.mH, TIMEOUT_MS));
 
         assertFalse(mTarget.isPositioningLocked());
         assertNull(mTarget.getDragWindowHandleLocked());
@@ -113,27 +108,23 @@
 
     @Test
     public void testHandleTapOutsideTask() {
-        synchronized (mWm.mGlobalLock) {
-            assertFalse(mTarget.isPositioningLocked());
-            assertNull(mTarget.getDragWindowHandleLocked());
-        }
+        assertFalse(mTarget.isPositioningLocked());
+        assertNull(mTarget.getDragWindowHandleLocked());
 
         final DisplayContent content = mock(DisplayContent.class);
-        when(content.findTaskForResizePoint(anyInt(), anyInt())).thenReturn(mWindow.getTask());
+        doReturn(mWindow.getTask()).when(content).findTaskForResizePoint(anyInt(), anyInt());
         assertNotNull(mWindow.getTask().getTopVisibleAppMainWindow());
 
         mTarget.handleTapOutsideTask(content, 0, 0);
         // Wait until the looper processes finishTaskPositioning.
-        assertTrue(mWm.mH.runWithScissors(() -> { }, TIMEOUT_MS));
+        assertTrue(waitHandlerIdle(mWm.mH, TIMEOUT_MS));
 
-        synchronized (mWm.mGlobalLock) {
-            assertTrue(mTarget.isPositioningLocked());
-            assertNotNull(mTarget.getDragWindowHandleLocked());
-        }
+        assertTrue(mTarget.isPositioningLocked());
+        assertNotNull(mTarget.getDragWindowHandleLocked());
 
         mTarget.finishTaskPositioning();
         // Wait until the looper processes finishTaskPositioning.
-        assertTrue(mWm.mH.runWithScissors(() -> { }, TIMEOUT_MS));
+        assertTrue(waitHandlerIdle(mWm.mH, TIMEOUT_MS));
 
         assertFalse(mTarget.isPositioningLocked());
         assertNull(mTarget.getDragWindowHandleLocked());
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
index c83401b..0f8fb04 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
@@ -51,7 +51,6 @@
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 
 import android.app.ActivityManager;
@@ -78,6 +77,7 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.Mockito;
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
@@ -98,6 +98,7 @@
  */
 @MediumTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class TaskRecordTests extends ActivityTestsBase {
 
     private static final String TASK_TAG = "task";
@@ -118,7 +119,7 @@
 
         final byte[] serializedBytes = serializeToBytes(expected);
         final TaskRecord actual = restoreFromBytes(serializedBytes);
-        assertEquals(expected.taskId, actual.taskId);
+        assertEquals(expected.mTaskId, actual.mTaskId);
         assertEquals(expected.mLastNonFullscreenBounds, actual.mLastNonFullscreenBounds);
     }
 
@@ -131,7 +132,7 @@
     @Test
     public void testCopyBaseIntentForTaskInfo() {
         final TaskRecord task = createTaskRecord(1);
-        task.lastTaskDescription = new ActivityManager.TaskDescription();
+        task.mTaskDescription = new ActivityManager.TaskDescription();
         final TaskInfo info = task.getTaskInfo();
 
         // The intent of info should be a copy so assert that they are different instances.
@@ -237,7 +238,7 @@
         ActivityStack stack = new StackBuilder(mRootActivityContainer).setDisplay(display)
                 .setWindowingMode(WINDOWING_MODE_FREEFORM).build();
         TaskRecord task = stack.getChildAt(0);
-        task.getRootActivity().mAppWindowToken.setOrientation(SCREEN_ORIENTATION_UNSPECIFIED);
+        task.getRootActivity().setOrientation(SCREEN_ORIENTATION_UNSPECIFIED);
         DisplayInfo info = new DisplayInfo();
         display.mDisplay.getDisplayInfo(info);
         final Rect fullScreenBounds = new Rect(0, 0, info.logicalWidth, info.logicalHeight);
@@ -647,9 +648,9 @@
         final TaskRecord task1 = getTestTask();
         final ActivityRecord activity1 = task1.getChildAt(0);
 
-        assertEquals(task0.taskId,
+        assertEquals(task0.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity0.appToken, false /* onlyRoot */));
-        assertEquals(task1.taskId,
+        assertEquals(task1.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity1.appToken,  false /* onlyRoot */));
     }
 
@@ -668,9 +669,9 @@
         // Add one more on top
         final ActivityRecord activity2 = new ActivityBuilder(mService).setTask(task).build();
 
-        assertEquals(task.taskId,
+        assertEquals(task.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity0.appToken, true /* onlyRoot */));
-        assertEquals(task.taskId,
+        assertEquals(task.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity1.appToken, true /* onlyRoot */));
         assertEquals("No task must be reported for activity that is above root", INVALID_TASK_ID,
                 ActivityRecord.getTaskForActivityLocked(activity2.appToken, true /* onlyRoot */));
@@ -691,9 +692,9 @@
         // Add one more on top
         final ActivityRecord activity2 = new ActivityBuilder(mService).setTask(task).build();
 
-        assertEquals(task.taskId,
+        assertEquals(task.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity0.appToken, true /* onlyRoot */));
-        assertEquals(task.taskId,
+        assertEquals(task.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity1.appToken, true /* onlyRoot */));
         assertEquals("No task must be reported for activity that is above root", INVALID_TASK_ID,
                 ActivityRecord.getTaskForActivityLocked(activity2.appToken, true /* onlyRoot */));
@@ -717,11 +718,11 @@
         // Add one more activity on top
         final ActivityRecord activity2 = new ActivityBuilder(mService).setTask(task).build();
 
-        assertEquals(task.taskId,
+        assertEquals(task.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity0.appToken, false /* onlyRoot */));
-        assertEquals(task.taskId,
+        assertEquals(task.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity1.appToken, false /* onlyRoot */));
-        assertEquals(task.taskId,
+        assertEquals(task.mTaskId,
                 ActivityRecord.getTaskForActivityLocked(activity2.appToken, false /* onlyRoot */));
     }
 
@@ -831,8 +832,8 @@
     private TaskRecord createTaskRecord(int taskId) {
         return new TaskRecord(mService, taskId, new Intent(), null, null, null,
                 ActivityBuilder.getDefaultComponent(), null, false, false, false, 0, 10050, null,
-                new ArrayList<>(), 0, false, null, 0, 0, 0, 0, 0, null, 0, false, false, false, 0, 0
-        );
+                new ArrayList<>(), 0, false, null, 0, 0, 0, 0, 0, null, 0, false, false, false, 0,
+                0, null /*ActivityInfo*/, null /*_voiceSession*/, null /*_voiceInteractor*/);
     }
 
     private static class TestTaskRecordFactory extends TaskRecordFactory {
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java
index 74ccccc..92ddb35 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java
@@ -32,15 +32,17 @@
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link DisplayContent.TaskStackContainers} container in {@link DisplayContent}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:TaskStackContainersTests
+ *  atest WmTests:TaskStackContainersTests
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class TaskStackContainersTests extends WindowTestsBase {
 
     private TaskStack mPinnedStack;
@@ -52,7 +54,7 @@
         // Stack should contain visible app window to be considered visible.
         final Task pinnedTask = createTaskInStack(mPinnedStack, 0 /* userId */);
         assertFalse(mPinnedStack.isVisible());
-        final WindowTestUtils.TestAppWindowToken pinnedApp =
+        final AppWindowToken pinnedApp =
                 WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         pinnedTask.addChild(pinnedApp, 0 /* addPos */);
         assertTrue(mPinnedStack.isVisible());
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java
index 70ed62a..2eb6ea4 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java
@@ -34,15 +34,17 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link TaskStack} class.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:TaskStackTests
+ *  atest WmTests:TaskStackTests
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class TaskStackTests extends WindowTestsBase {
 
     @Test
@@ -66,13 +68,13 @@
     public void testClosingAppDifferentStackOrientation() {
         final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task1 = createTaskInStack(stack, 0 /* userId */);
-        WindowTestUtils.TestAppWindowToken appWindowToken1 =
+        AppWindowToken appWindowToken1 =
                 WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task1.addChild(appWindowToken1, 0);
         appWindowToken1.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
         final Task task2 = createTaskInStack(stack, 1 /* userId */);
-        WindowTestUtils.TestAppWindowToken appWindowToken2 =
+        AppWindowToken appWindowToken2 =
                 WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task2.addChild(appWindowToken2, 0);
         appWindowToken2.setOrientation(SCREEN_ORIENTATION_PORTRAIT);
@@ -86,13 +88,13 @@
     public void testMoveTaskToBackDifferentStackOrientation() {
         final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final Task task1 = createTaskInStack(stack, 0 /* userId */);
-        WindowTestUtils.TestAppWindowToken appWindowToken1 =
+        AppWindowToken appWindowToken1 =
                 WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task1.addChild(appWindowToken1, 0);
         appWindowToken1.setOrientation(SCREEN_ORIENTATION_LANDSCAPE);
 
         final Task task2 = createTaskInStack(stack, 1 /* userId */);
-        WindowTestUtils.TestAppWindowToken appWindowToken2 =
+        AppWindowToken appWindowToken2 =
                 WindowTestUtils.createTestAppWindowToken(mDisplayContent);
         task2.addChild(appWindowToken2, 0);
         appWindowToken2.setOrientation(SCREEN_ORIENTATION_PORTRAIT);
@@ -149,7 +151,6 @@
         // After removing, the task will be isolated.
         assertNull(task.getParent());
         assertEquals(0, task.getChildCount());
-        assertNull(task.getController());
     }
 
     @Test
@@ -176,13 +177,8 @@
     public void testStackOutset() {
         final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
         final int stackOutset = 10;
-        // Clear the handler and hold the lock for mock, to prevent multi-thread issue.
-        waitUntilHandlersIdle();
-        synchronized (mWm.mGlobalLock) {
-            spyOn(stack);
-
-            doReturn(stackOutset).when(stack).getStackOutset();
-        }
+        spyOn(stack);
+        doReturn(stackOutset).when(stack).getStackOutset();
 
         final Rect stackBounds = new Rect(200, 200, 800, 1000);
         // Update surface position and size by the given bounds.
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java
index 4184201..f117ff0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java
@@ -29,22 +29,24 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Test class for {@link Task}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:TaskTests
+ *  atest WmTests:TaskTests
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class TaskTests extends WindowTestsBase {
 
     @Test
     public void testRemoveContainer() {
         final TaskStack stackController1 = createTaskStackOnDisplay(mDisplayContent);
         final WindowTestUtils.TestTask task = WindowTestUtils.createTestTask(stackController1);
-        final WindowTestUtils.TestAppWindowToken appToken =
+        final AppWindowToken appToken =
                 WindowTestUtils.createAppWindowTokenInTask(mDisplayContent, task);
 
         task.removeIfPossible();
@@ -58,7 +60,7 @@
     public void testRemoveContainer_deferRemoval() {
         final TaskStack stackController1 = createTaskStackOnDisplay(mDisplayContent);
         final WindowTestUtils.TestTask task = WindowTestUtils.createTestTask(stackController1);
-        final WindowTestUtils.TestAppWindowToken appToken =
+        final AppWindowToken appToken =
                 WindowTestUtils.createAppWindowTokenInTask(mDisplayContent, task);
 
         task.mShouldDeferRemoval = true;
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestActivityDisplay.java b/services/tests/wmtests/src/com/android/server/wm/TestActivityDisplay.java
index 778f0ca..9c3ff65 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestActivityDisplay.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestActivityDisplay.java
@@ -22,8 +22,11 @@
 
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyBoolean;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
 
+import static org.mockito.ArgumentMatchers.any;
+
 import android.hardware.display.DisplayManagerGlobal;
 import android.view.Display;
 import android.view.DisplayInfo;
@@ -85,6 +88,10 @@
             displayRotation.setRotation(rotation);
             return true;
         }).when(displayRotation).updateRotationUnchecked(anyBoolean());
+
+        final InputMonitor inputMonitor = mDisplayContent.getInputMonitor();
+        spyOn(inputMonitor);
+        doNothing().when(inputMonitor).resumeDispatchingLw(any());
     }
 
     @SuppressWarnings("TypeParameterUnusedInFormals")
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java b/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java
index a758681..09e5027 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java
@@ -111,4 +111,8 @@
     @Override
     public void dispatchPointerCaptureChanged(boolean hasCapture) {
     }
+
+    @Override
+    public void showInsets(int types, boolean fromIme) throws RemoteException {
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
index bb89446..761f73e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java
@@ -167,12 +167,13 @@
     }
 
     @Override
-    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
+    public long interceptKeyBeforeDispatching(IBinder focusedToken, KeyEvent event,
+            int policyFlags) {
         return 0;
     }
 
     @Override
-    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
+    public KeyEvent dispatchUnhandledKey(IBinder focusedToken, KeyEvent event, int policyFlags) {
         return null;
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
index a91daf0..2e86178 100644
--- a/services/tests/wmtests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/UnknownAppVisibilityControllerTest.java
@@ -24,15 +24,17 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Test class for {@link AppTransition}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:UnknownAppVisibilityControllerTest
+ *  atest WmTests:UnknownAppVisibilityControllerTest
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class UnknownAppVisibilityControllerTest extends WindowTestsBase {
 
     @Before
@@ -48,7 +50,7 @@
         mDisplayContent.mUnknownAppVisibilityController.notifyRelayouted(token);
 
         // Make sure our handler processed the message.
-        mWm.mH.runWithScissors(() -> { }, 0);
+        waitHandlerIdle(mWm.mH);
         assertTrue(mDisplayContent.mUnknownAppVisibilityController.allResolved());
     }
 
@@ -64,7 +66,7 @@
         mDisplayContent.mUnknownAppVisibilityController.notifyRelayouted(token2);
 
         // Make sure our handler processed the message.
-        mWm.mH.runWithScissors(() -> { }, 0);
+        waitHandlerIdle(mWm.mH);
         assertTrue(mDisplayContent.mUnknownAppVisibilityController.allResolved());
     }
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
index 6249bde..14d8a9d 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
@@ -30,6 +30,7 @@
 import androidx.test.filters.SmallTest;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link WallpaperController} class.
@@ -39,37 +40,36 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class WallpaperControllerTests extends WindowTestsBase {
     @Test
     public void testWallpaperScreenshot() {
         WindowSurfaceController windowSurfaceController = mock(WindowSurfaceController.class);
 
-        synchronized (mWm.mGlobalLock) {
-            // No wallpaper
-            final DisplayContent dc = createNewDisplay();
-            assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
+        // No wallpaper
+        final DisplayContent dc = createNewDisplay();
+        assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
 
-            // No wallpaper WSA Surface
-            WindowToken wallpaperWindowToken = new WallpaperWindowToken(mWm, mock(IBinder.class),
-                    true, dc, true /* ownerCanManageAppTokens */);
-            WindowState wallpaperWindow = createWindow(null /* parent */, TYPE_WALLPAPER,
-                    wallpaperWindowToken, "wallpaperWindow");
-            assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
+        // No wallpaper WSA Surface
+        WindowToken wallpaperWindowToken = new WallpaperWindowToken(mWm, mock(IBinder.class),
+                true, dc, true /* ownerCanManageAppTokens */);
+        WindowState wallpaperWindow = createWindow(null /* parent */, TYPE_WALLPAPER,
+                wallpaperWindowToken, "wallpaperWindow");
+        assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
 
-            // Wallpaper with not visible WSA surface.
-            wallpaperWindow.mWinAnimator.mSurfaceController = windowSurfaceController;
-            wallpaperWindow.mWinAnimator.mLastAlpha = 1;
-            assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
+        // Wallpaper with not visible WSA surface.
+        wallpaperWindow.mWinAnimator.mSurfaceController = windowSurfaceController;
+        wallpaperWindow.mWinAnimator.mLastAlpha = 1;
+        assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
 
-            when(windowSurfaceController.getShown()).thenReturn(true);
+        when(windowSurfaceController.getShown()).thenReturn(true);
 
-            // Wallpaper with WSA alpha set to 0.
-            wallpaperWindow.mWinAnimator.mLastAlpha = 0;
-            assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
+        // Wallpaper with WSA alpha set to 0.
+        wallpaperWindow.mWinAnimator.mLastAlpha = 0;
+        assertFalse(dc.mWallpaperController.canScreenshotWallpaper());
 
-            // Wallpaper window with WSA Surface
-            wallpaperWindow.mWinAnimator.mLastAlpha = 1;
-            assertTrue(dc.mWallpaperController.canScreenshotWallpaper());
-        }
+        // Wallpaper window with WSA Surface
+        wallpaperWindow.mWinAnimator.mLastAlpha = 1;
+        assertTrue(dc.mWallpaperController.canScreenshotWallpaper());
     }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java b/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
index 0330de8..bfc0741 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
@@ -27,6 +27,7 @@
 import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 
 import android.graphics.Point;
@@ -50,7 +51,7 @@
 @Presubmit
 public class WindowAnimationSpecTest {
     private final SurfaceControl mSurfaceControl = mock(SurfaceControl.class);
-    private final SurfaceControl.Transaction mTransaction = mock(SurfaceControl.Transaction.class);
+    private final SurfaceControl.Transaction mTransaction = spy(StubTransaction.class);
     private final Animation mAnimation = mock(Animation.class);
     private final Rect mStackBounds = new Rect(0, 0, 10, 10);
 
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContainerControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContainerControllerTests.java
deleted file mode 100644
index fc78635..0000000
--- a/services/tests/wmtests/src/com/android/server/wm/WindowContainerControllerTests.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2016 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 android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
-import static android.content.res.Configuration.EMPTY;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import android.content.res.Configuration;
-import android.platform.test.annotations.Presubmit;
-
-import androidx.test.filters.SmallTest;
-
-import org.junit.Test;
-
-/**
- * Test class for {@link WindowContainerController}.
- *
- * Build/Install/Run:
- *  atest WmTests:WindowContainerControllerTests
- */
-@SmallTest
-@Presubmit
-public class WindowContainerControllerTests extends WindowTestsBase {
-
-    @Test
-    public void testCreation() {
-        final WindowContainerController controller = new WindowContainerController<>(null, mWm);
-        final WindowContainer container = new WindowContainer(mWm);
-
-        container.setController(controller);
-        assertEquals(controller, container.getController());
-        assertEquals(controller.mContainer, container);
-    }
-
-    @Test
-    public void testSetContainer() {
-        final WindowContainerController controller = new WindowContainerController<>(null, mWm);
-        final WindowContainer container = new WindowContainer(mWm);
-
-        controller.setContainer(container);
-        assertEquals(controller.mContainer, container);
-
-        // Assert we can't change the container to another one once set
-        boolean gotException = false;
-        try {
-            controller.setContainer(new WindowContainer(mWm));
-        } catch (IllegalArgumentException e) {
-            gotException = true;
-        }
-        assertTrue(gotException);
-
-        // Assert that we can set the container to null.
-        controller.setContainer(null);
-        assertNull(controller.mContainer);
-    }
-
-    @Test
-    public void testRemoveContainer() {
-        final WindowContainerController controller = new WindowContainerController<>(null, mWm);
-        final WindowContainer container = new WindowContainer(mWm);
-
-        controller.setContainer(container);
-        assertEquals(controller.mContainer, container);
-
-        controller.removeContainer();
-        assertNull(controller.mContainer);
-    }
-
-    @Test
-    public void testOnOverrideConfigurationChanged() {
-        final WindowContainerController controller = new WindowContainerController<>(null, mWm);
-        final WindowContainer container = new WindowContainer(mWm);
-
-        controller.setContainer(container);
-        assertEquals(controller.mContainer, container);
-        assertEquals(EMPTY, container.getRequestedOverrideConfiguration());
-
-        final Configuration config = new Configuration();
-        config.windowConfiguration.setWindowingMode(WINDOWING_MODE_FREEFORM);
-        config.windowConfiguration.setAppBounds(10, 10, 10, 10);
-
-        // Assert that the config change through the controller is propagated to the container.
-        controller.onRequestedOverrideConfigurationChanged(config);
-        assertEquals(config, container.getRequestedOverrideConfiguration());
-
-        // Assert the container configuration isn't changed after removal from the controller.
-        controller.removeContainer();
-        controller.onRequestedOverrideConfigurationChanged(EMPTY);
-        assertEquals(config, container.getRequestedOverrideConfiguration());
-    }
-}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
index 921f105..8117ff6 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java
@@ -216,44 +216,6 @@
     }
 
     @Test
-    public void testRemoveImmediately_WithController() {
-        final WindowContainer container = new WindowContainer(mWm);
-        final WindowContainerController controller = new WindowContainerController<>(null, mWm);
-
-        container.setController(controller);
-        assertEquals(controller, container.getController());
-        assertEquals(container, controller.mContainer);
-
-        container.removeImmediately();
-        assertNull(container.getController());
-        assertNull(controller.mContainer);
-    }
-
-    @Test
-    public void testSetController() {
-        final WindowContainerController controller = new WindowContainerController<>(null, mWm);
-        final WindowContainer container = new WindowContainer(mWm);
-
-        container.setController(controller);
-        assertEquals(controller, container.getController());
-        assertEquals(container, controller.mContainer);
-
-        // Assert we can't change the controller to another one once set
-        boolean gotException = false;
-        try {
-            container.setController(new WindowContainerController<>(null, mWm));
-        } catch (IllegalArgumentException e) {
-            gotException = true;
-        }
-        assertTrue(gotException);
-
-        // Assert that we can set the controller to null.
-        container.setController(null);
-        assertNull(container.getController());
-        assertNull(controller.mContainer);
-    }
-
-    @Test
     public void testAddChildByIndex() {
         final TestWindowContainerBuilder builder = new TestWindowContainerBuilder(mWm);
         final TestWindowContainer root = builder.setLayer(0).build();
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java
index 60cefe8..3563feb 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java
@@ -43,16 +43,18 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.Mockito;
 
 /**
  * Tests for the {@link WindowState#computeFrameLw} method and other window frame machinery.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:WindowFrameTests
+ *  atest WmTests:WindowFrameTests
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class WindowFrameTests extends WindowTestsBase {
 
     private final IWindow mIWindow = new TestIWindow();
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowManagerGlobalLockRule.java b/services/tests/wmtests/src/com/android/server/wm/WindowManagerGlobalLockRule.java
index e0c314f..c5f13e0 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowManagerGlobalLockRule.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowManagerGlobalLockRule.java
@@ -27,6 +27,9 @@
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.Callable;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
@@ -59,34 +62,41 @@
         return base;
     }
 
-    void waitUntilHandlersIdle() {
-        if (!mIsLocked) {
-            mSystemServicesTestRule.waitUntilWindowManagerHandlersIdle();
-            return;
-        }
-
-        waitForLocked(mSystemServicesTestRule::waitUntilWindowManagerHandlersIdle);
+    boolean runWithScissors(Handler handler, Runnable r, long timeout) {
+        return waitForLocked(() -> handler.runWithScissors(r, timeout));
     }
 
-    void runWithScissors(Handler handler, Runnable r, long timeout) {
-        if (!mIsLocked) {
-            handler.runWithScissors(r, timeout);
-            return;
-        }
-
-        waitForLocked(() -> handler.runWithScissors(r, timeout));
+    void waitForLocked(Runnable r) {
+        waitForLocked(() -> {
+            r.run();
+            return null;
+        });
     }
 
     /**
      * If the test holds the lock, we need to invoke {@link Object#wait} to release it so other
      * threads won't be blocked when we are waiting.
      */
-    private void waitForLocked(Runnable r) {
+    <T> T waitForLocked(Callable<T> callable) {
+        if (!mIsLocked) {
+            try {
+                return callable.call();
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+
         final Object lock = mSystemServicesTestRule.getWindowManagerService().mGlobalLock;
         final AtomicBoolean done = new AtomicBoolean(false);
+        final List<T> result = Arrays.asList((T) null);
+        final Exception[] exception = { null };
 
         AsyncTask.SERIAL_EXECUTOR.execute(() -> {
-            r.run();
+            try {
+                result.set(0, callable.call());
+            } catch (Exception e) {
+                exception[0] = e;
+            }
             synchronized (lock) {
                 lock.notifyAll();
                 done.set(true);
@@ -101,6 +111,11 @@
                 }
             }
         }
+        if (exception[0] != null) {
+            throw new RuntimeException(exception[0]);
+        }
+
+        return result.get(0);
     }
 
     /** Wraps methods annotated with {@link org.junit.Test}. */
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
index 8c56ffa..cc90ca1 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
@@ -26,13 +26,13 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
 
 import android.content.pm.ApplicationInfo;
 import android.platform.test.annotations.Presubmit;
 
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 import org.mockito.InOrder;
 import org.mockito.Mockito;
 
@@ -43,6 +43,7 @@
  *  atest WmTests:WindowProcessControllerTests
  */
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class WindowProcessControllerTests extends ActivityTestsBase {
 
     WindowProcessController mWpc;
@@ -97,7 +98,7 @@
     public void testSetRunningRecentsAnimation() {
         mWpc.setRunningRecentsAnimation(true);
         mWpc.setRunningRecentsAnimation(false);
-        mService.mH.runWithScissors(() -> {}, 0);
+        waitHandlerIdle(mService.mH);
 
         InOrder orderVerifier = Mockito.inOrder(mMockListener);
         orderVerifier.verify(mMockListener).setRunningRemoteAnimation(eq(true));
@@ -108,7 +109,7 @@
     public void testSetRunningRemoteAnimation() {
         mWpc.setRunningRemoteAnimation(true);
         mWpc.setRunningRemoteAnimation(false);
-        mService.mH.runWithScissors(() -> {}, 0);
+        waitHandlerIdle(mService.mH);
 
         InOrder orderVerifier = Mockito.inOrder(mMockListener);
         orderVerifier.verify(mMockListener).setRunningRemoteAnimation(eq(true));
@@ -122,7 +123,7 @@
 
         mWpc.setRunningRecentsAnimation(false);
         mWpc.setRunningRemoteAnimation(false);
-        mService.mH.runWithScissors(() -> {}, 0);
+        waitHandlerIdle(mService.mH);
 
         InOrder orderVerifier = Mockito.inOrder(mMockListener);
         orderVerifier.verify(mMockListener, times(3)).setRunningRemoteAnimation(eq(true));
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
index f41f126..a09253a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java
@@ -57,6 +57,7 @@
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
 
 import android.graphics.Insets;
 import android.graphics.Matrix;
@@ -329,7 +330,7 @@
         // turn on the screen.
         appWindowToken.setCurrentLaunchCanTurnScreenOn(true);
         first.mAttrs.flags &= ~WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
-        doReturn(true).when(appWindowToken.mActivityRecord).canTurnScreenOn();
+        doReturn(true).when(appWindowToken).canTurnScreenOn();
 
         testPrepareWindowToDisplayDuringRelayout(first, true /* expectedWakeupCalled */,
                 false /* expectedCurrentLaunchCanTurnScreenOn */);
@@ -451,7 +452,7 @@
     @Test
     public void testSeamlesslyRotateWindow() {
         final WindowState app = createWindow(null, TYPE_APPLICATION, "app");
-        final SurfaceControl.Transaction t = mock(SurfaceControl.Transaction.class);
+        final SurfaceControl.Transaction t = spy(StubTransaction.class);
 
         app.mHasSurface = true;
         app.mSurfaceControl = mock(SurfaceControl.class);
@@ -535,7 +536,7 @@
 
         final float[] values = new float[9];
         final Matrix matrix = new Matrix();
-        final SurfaceControl.Transaction t = mock(SurfaceControl.Transaction.class);
+        final SurfaceControl.Transaction t = spy(StubTransaction.class);
         final WindowState win1 = createWindow(null, TYPE_APPLICATION, dc, "win1");
         win1.mHasSurface = true;
         win1.mSurfaceControl = mock(SurfaceControl.class);
@@ -547,4 +548,29 @@
         assertEquals(OFFSET_SUM, values[Matrix.MTRANS_X], 0f);
         assertEquals(0f, values[Matrix.MTRANS_Y], 0f);
     }
+
+    @Test
+    public void testCantReceiveTouchDuringRecentsAnimation() {
+        final WindowState win0 = createWindow(null, TYPE_APPLICATION, "win0");
+
+        // Mock active recents animation
+        RecentsAnimationController recentsController = mock(RecentsAnimationController.class);
+        when(recentsController.isAnimatingTask(win0.mAppToken.getTask())).thenReturn(true);
+        mWm.setRecentsAnimationController(recentsController);
+        assertTrue(win0.cantReceiveTouchInput());
+    }
+
+    @Test
+    public void testCantReceiveTouchWhenAppTokenHiddenRequested() {
+        final WindowState win0 = createWindow(null, TYPE_APPLICATION, "win0");
+        win0.mAppToken.hiddenRequested = true;
+        assertTrue(win0.cantReceiveTouchInput());
+    }
+
+    @Test
+    public void testCantReceiveTouchWhenShouldIgnoreInput() {
+        final WindowState win0 = createWindow(null, TYPE_APPLICATION, "win0");
+        win0.mAppToken.getStack().setAdjustedForMinimizedDock(1 /* Any non 0 value works */);
+        assertTrue(win0.cantReceiveTouchInput());
+    }
 }
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
index a7a785d..c627c19 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
@@ -19,14 +19,17 @@
 import static android.app.AppOpsManager.OP_NONE;
 import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
+import static com.android.server.wm.ActivityTestsBase.ActivityBuilder.createIntentAndActivityInfo;
 import static com.android.server.wm.WindowContainer.POSITION_TOP;
 
 import android.app.ActivityManager;
-import android.content.ComponentName;
-import android.os.Build;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.os.IBinder;
-import android.view.IApplicationToken;
+import android.util.Pair;
 import android.view.IWindow;
 import android.view.WindowManager;
 
@@ -48,57 +51,26 @@
     }
 
     /** Creates an {@link AppWindowToken} and adds it to the specified {@link Task}. */
-    static TestAppWindowToken createAppWindowTokenInTask(DisplayContent dc, Task task) {
-        final TestAppWindowToken newToken = createTestAppWindowToken(dc);
+    static AppWindowToken createAppWindowTokenInTask(DisplayContent dc, Task task) {
+        final AppWindowToken newToken = createTestAppWindowToken(dc);
         task.addChild(newToken, POSITION_TOP);
         return newToken;
     }
 
-    static TestAppWindowToken createTestAppWindowToken(DisplayContent dc) {
+    static AppWindowToken createTestAppWindowToken(DisplayContent dc) {
         synchronized (dc.mWmService.mGlobalLock) {
-            return new TestAppWindowToken(dc);
+            Pair<Intent, ActivityInfo> pair = createIntentAndActivityInfo();
+            final AppWindowToken token = new AppWindowToken(dc.mWmService,
+                    dc.mWmService.mAtmService, new ActivityRecord.Token(pair.first), pair.second,
+                    null, pair.first, dc);
+            token.setOccludesParent(true);
+            token.setHidden(false);
+            token.hiddenRequested = false;
+            spyOn(token);
+            return token;
         }
     }
 
-    /** Used so we can gain access to some protected members of the {@link AppWindowToken} class. */
-    static class TestAppWindowToken extends AppWindowToken {
-        boolean mOnTop = false;
-
-        private TestAppWindowToken(DisplayContent dc) {
-            super(dc.mWmService, new IApplicationToken.Stub() {
-                @Override
-                public String getName() {
-                    return null;
-                }
-            }, new ComponentName("", ""), false, dc, true /* fillsParent */);
-            mTargetSdk = Build.VERSION_CODES.CUR_DEVELOPMENT;
-            mActivityRecord = mock(ActivityRecord.class);
-            mActivityRecord.app = mock(WindowProcessController.class);
-        }
-
-        int getWindowsCount() {
-            return mChildren.size();
-        }
-
-        boolean hasWindow(WindowState w) {
-            return mChildren.contains(w);
-        }
-
-        WindowState getFirstChild() {
-            return mChildren.peekFirst();
-        }
-
-        WindowState getLastChild() {
-            return mChildren.peekLast();
-        }
-
-        @Override
-        boolean isOnTop() {
-            return mOnTop;
-        }
-
-    }
-
     static TestWindowToken createTestWindowToken(int type, DisplayContent dc) {
         return createTestWindowToken(type, dc, false /* persistOnEmpty */);
     }
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
index 8930e5a..4c4b21e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java
@@ -42,7 +42,6 @@
 
 import android.content.Context;
 import android.content.res.Configuration;
-import android.testing.DexmakerShareClassLoaderRule;
 import android.util.Log;
 import android.view.Display;
 import android.view.DisplayInfo;
@@ -55,7 +54,6 @@
 import org.junit.After;
 import org.junit.Before;
 import org.junit.BeforeClass;
-import org.junit.Rule;
 
 import java.util.HashSet;
 import java.util.LinkedList;
@@ -65,7 +63,7 @@
  *
  * Make sure any requests to WM hold the WM lock if needed b/73966377
  */
-class WindowTestsBase {
+class WindowTestsBase extends SystemServiceTestsBase {
     private static final String TAG = WindowTestsBase.class.getSimpleName();
 
     WindowManagerService mWm;
@@ -92,16 +90,6 @@
      */
     Transaction mTransaction;
 
-    @Rule
-    public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
-            new DexmakerShareClassLoaderRule();
-    @Rule
-    public final SystemServicesTestRule mSystemServicesTestRule = new SystemServicesTestRule();
-
-    @WindowTestRunner.MethodWrapperRule
-    public final WindowManagerGlobalLockRule mLockRule =
-            new WindowManagerGlobalLockRule(mSystemServicesTestRule);
-
     @BeforeClass
     public static void setUpOnceBase() {
         AttributeCache.init(getInstrumentation().getTargetContext());
@@ -205,13 +193,6 @@
         }
     }
 
-    /**
-     * Waits until the main handler for WM has processed all messages.
-     */
-    void waitUntilHandlersIdle() {
-        mLockRule.waitUntilHandlersIdle();
-    }
-
     private WindowToken createWindowToken(
             DisplayContent dc, int windowingMode, int activityType, int type) {
         synchronized (mWm.mGlobalLock) {
@@ -227,11 +208,11 @@
         return createTestAppWindowToken(dc, windowingMode, activityType);
     }
 
-    WindowTestUtils.TestAppWindowToken createTestAppWindowToken(DisplayContent dc, int
+    AppWindowToken createTestAppWindowToken(DisplayContent dc, int
             windowingMode, int activityType) {
         final TaskStack stack = createTaskStackOnDisplay(windowingMode, activityType, dc);
         final Task task = createTaskInStack(stack, 0 /* userId */);
-        final WindowTestUtils.TestAppWindowToken appWindowToken =
+        final AppWindowToken appWindowToken =
                 WindowTestUtils.createTestAppWindowToken(dc);
         task.addChild(appWindowToken, 0);
         return appWindowToken;
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTraceBufferTest.java b/services/tests/wmtests/src/com/android/server/wm/WindowTraceBufferTest.java
deleted file mode 100644
index b299f0d..0000000
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTraceBufferTest.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2019 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 androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
-
-import static com.android.server.wm.WindowManagerTraceFileProto.MAGIC_NUMBER;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import android.content.Context;
-import android.platform.test.annotations.Presubmit;
-import android.util.proto.ProtoOutputStream;
-
-import androidx.test.filters.SmallTest;
-
-import com.android.internal.util.Preconditions;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-
-
-/**
- * Test class for {@link WindowTraceBuffer}.
- *
- * Build/Install/Run:
- *  atest WmTests:WindowTraceBufferTest
- */
-@SmallTest
-@Presubmit
-public class WindowTraceBufferTest {
-    private File mFile;
-    private WindowTraceBuffer mBuffer;
-
-    @Before
-    public void setUp() throws Exception {
-        final Context testContext = getInstrumentation().getContext();
-        mFile = testContext.getFileStreamPath("tracing_test.dat");
-        mFile.delete();
-
-        mBuffer = new WindowTraceBuffer(10);
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        mFile.delete();
-    }
-
-    @Test
-    public void test_addItem() {
-        ProtoOutputStream toWrite = getDummy(1);
-        final int objectSize = toWrite.getRawSize();
-        mBuffer.setCapacity(objectSize);
-        mBuffer.resetBuffer();
-
-        Preconditions.checkArgument(mBuffer.size() == 0);
-
-        mBuffer.add(toWrite);
-
-        assertEquals("Item was not added to the buffer", 1, mBuffer.size());
-        assertEquals("Total buffer getSize differs from inserted object",
-                mBuffer.getBufferSize(), objectSize);
-        assertEquals("Available buffer space does not match used one", 0,
-                mBuffer.getAvailableSpace());
-    }
-
-    @Test
-    public void test_addItemMustOverwriteOne() {
-        ProtoOutputStream toWrite1 = getDummy(1);
-        ProtoOutputStream toWrite2 = getDummy(2);
-        ProtoOutputStream toWrite3 = getDummy(3);
-        final int objectSize = toWrite1.getRawSize();
-        final int bufferCapacity = objectSize * 2 + 1;
-        mBuffer.setCapacity(bufferCapacity);
-        mBuffer.resetBuffer();
-
-        mBuffer.add(toWrite1);
-        byte[] toWrite1Bytes = toWrite1.getBytes();
-        assertTrue("First element should be in the list",
-                mBuffer.contains(toWrite1Bytes));
-
-        mBuffer.add(toWrite2);
-        byte[] toWrite2Bytes = toWrite2.getBytes();
-        assertTrue("First element should be in the list",
-                mBuffer.contains(toWrite1Bytes));
-        assertTrue("Second element should be in the list",
-                mBuffer.contains(toWrite2Bytes));
-
-        mBuffer.add(toWrite3);
-        byte[] toWrite3Bytes = toWrite3.getBytes();
-        assertTrue("First element should not be in the list",
-                !mBuffer.contains(toWrite1Bytes));
-        assertTrue("Second element should be in the list",
-                mBuffer.contains(toWrite2Bytes));
-        assertTrue("Third element should be in the list",
-                mBuffer.contains(toWrite3Bytes));
-        assertEquals("Buffer should have 2 elements", 2, mBuffer.size());
-        assertEquals(String.format("Buffer is full, used space should be %d", bufferCapacity),
-                mBuffer.getBufferSize(), bufferCapacity - 1);
-        assertEquals(" Buffer is full, available space should be 0", 1,
-                mBuffer.getAvailableSpace());
-    }
-
-    @Test
-    public void test_addItemMustOverwriteMultiple() {
-        ProtoOutputStream toWriteSmall1 = getDummy(1);
-        ProtoOutputStream toWriteSmall2 = getDummy(2);
-        final int objectSize = toWriteSmall1.getRawSize();
-        final int bufferCapacity = objectSize * 2;
-        mBuffer.setCapacity(bufferCapacity);
-        mBuffer.resetBuffer();
-
-        ProtoOutputStream toWriteBig = new ProtoOutputStream();
-        toWriteBig.write(MAGIC_NUMBER, 1);
-        toWriteBig.write(MAGIC_NUMBER, 2);
-
-        mBuffer.add(toWriteSmall1);
-        byte[] toWriteSmall1Bytes = toWriteSmall1.getBytes();
-        assertTrue("First element should be in the list",
-                mBuffer.contains(toWriteSmall1Bytes));
-
-        mBuffer.add(toWriteSmall2);
-        byte[] toWriteSmall2Bytes = toWriteSmall2.getBytes();
-        assertTrue("First element should be in the list",
-                mBuffer.contains(toWriteSmall1Bytes));
-        assertTrue("Second element should be in the list",
-                mBuffer.contains(toWriteSmall2Bytes));
-
-        mBuffer.add(toWriteBig);
-        byte[] toWriteBigBytes = toWriteBig.getBytes();
-        assertTrue("Third element should overwrite all others",
-                !mBuffer.contains(toWriteSmall1Bytes));
-        assertTrue("Third element should overwrite all others",
-                !mBuffer.contains(toWriteSmall2Bytes));
-        assertTrue("Third element should overwrite all others",
-                mBuffer.contains(toWriteBigBytes));
-
-        assertEquals(" Buffer should have only 1 big element", 1, mBuffer.size());
-        assertEquals(String.format(" Buffer is full, used space should be %d", bufferCapacity),
-                mBuffer.getBufferSize(), bufferCapacity);
-        assertEquals(" Buffer is full, available space should be 0", 0,
-                mBuffer.getAvailableSpace());
-    }
-
-    @Test
-    public void test_startResetsBuffer() {
-        ProtoOutputStream toWrite = getDummy(1);
-        mBuffer.resetBuffer();
-        Preconditions.checkArgument(mBuffer.size() == 0);
-
-        mBuffer.add(toWrite);
-        assertEquals("Item was not added to the buffer", 1, mBuffer.size());
-        mBuffer.resetBuffer();
-        assertEquals("Buffer should be empty after reset", 0, mBuffer.size());
-        assertEquals("Buffer size should be 0 after reset", 0, mBuffer.getBufferSize());
-    }
-
-    private ProtoOutputStream getDummy(int value) {
-        ProtoOutputStream toWrite = new ProtoOutputStream();
-        toWrite.write(MAGIC_NUMBER, value);
-        toWrite.flush();
-
-        return toWrite;
-    }
-
-}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java b/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java
index 2105ab0..63b50b5 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ZOrderingTests.java
@@ -47,6 +47,7 @@
 
 import org.junit.After;
 import org.junit.Test;
+import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -61,6 +62,7 @@
  */
 @SmallTest
 @Presubmit
+@RunWith(WindowTestRunner.class)
 public class ZOrderingTests extends WindowTestsBase {
 
     private static class LayerRecordingTransaction extends SurfaceControl.Transaction {
diff --git a/services/usage/java/com/android/server/usage/AppStandbyController.java b/services/usage/java/com/android/server/usage/AppStandbyController.java
deleted file mode 100644
index 75e8fb5..0000000
--- a/services/usage/java/com/android/server/usage/AppStandbyController.java
+++ /dev/null
@@ -1,2032 +0,0 @@
-/**
- * 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.usage;
-
-import static android.app.usage.UsageStatsManager.REASON_MAIN_DEFAULT;
-import static android.app.usage.UsageStatsManager.REASON_MAIN_FORCED;
-import static android.app.usage.UsageStatsManager.REASON_MAIN_MASK;
-import static android.app.usage.UsageStatsManager.REASON_MAIN_PREDICTED;
-import static android.app.usage.UsageStatsManager.REASON_MAIN_TIMEOUT;
-import static android.app.usage.UsageStatsManager.REASON_MAIN_USAGE;
-import static android.app.usage.UsageStatsManager.REASON_SUB_PREDICTED_RESTORED;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_ACTIVE_TIMEOUT;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_START;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_FOREGROUND_SERVICE_START;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_BACKGROUND;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_NOTIFICATION_SEEN;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SLICE_PINNED;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SLICE_PINNED_PRIV;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYNC_ADAPTER;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_INTERACTION;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYSTEM_UPDATE;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED;
-import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_USER_INTERACTION;
-import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_ACTIVE;
-import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_EXEMPTED;
-import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_FREQUENT;
-import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_NEVER;
-import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_RARE;
-import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_WORKING_SET;
-
-import static com.android.server.SystemService.PHASE_BOOT_COMPLETED;
-import static com.android.server.SystemService.PHASE_SYSTEM_SERVICES_READY;
-
-import android.annotation.UserIdInt;
-import android.app.ActivityManager;
-import android.app.AppGlobals;
-import android.app.usage.AppStandbyInfo;
-import android.app.usage.UsageEvents;
-import android.app.usage.UsageStatsManager.StandbyBuckets;
-import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
-import android.appwidget.AppWidgetManager;
-import android.content.BroadcastReceiver;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManagerInternal;
-import android.content.pm.ParceledListSlice;
-import android.database.ContentObserver;
-import android.hardware.display.DisplayManager;
-import android.net.ConnectivityManager;
-import android.net.Network;
-import android.net.NetworkInfo;
-import android.net.NetworkRequest;
-import android.net.NetworkScoreManager;
-import android.os.BatteryManager;
-import android.os.BatteryStats;
-import android.os.Environment;
-import android.os.Handler;
-import android.os.IDeviceIdleController;
-import android.os.Looper;
-import android.os.Message;
-import android.os.PowerManager;
-import android.os.Process;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.SystemClock;
-import android.os.UserHandle;
-import android.provider.Settings.Global;
-import android.telephony.TelephonyManager;
-import android.util.ArraySet;
-import android.util.KeyValueListParser;
-import android.util.Slog;
-import android.util.SparseArray;
-import android.util.SparseIntArray;
-import android.util.TimeUtils;
-import android.view.Display;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.app.IBatteryStats;
-import com.android.internal.os.SomeArgs;
-import com.android.internal.util.ArrayUtils;
-import com.android.internal.util.ConcurrentUtils;
-import com.android.internal.util.IndentingPrintWriter;
-import com.android.server.LocalServices;
-import com.android.server.usage.AppIdleHistory.AppUsageHistory;
-
-import java.io.File;
-import java.io.PrintWriter;
-import java.time.Duration;
-import java.time.format.DateTimeParseException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-
-/**
- * Manages the standby state of an app, listening to various events.
- *
- * Unit test:
-   atest ${ANDROID_BUILD_TOP}/frameworks/base/services/tests/servicestests/src/com/android/server/usage/AppStandbyControllerTests.java
- */
-public class AppStandbyController {
-
-    private static final String TAG = "AppStandbyController";
-    static final boolean DEBUG = false;
-
-    static final boolean COMPRESS_TIME = false;
-    private static final long ONE_MINUTE = 60 * 1000;
-    private static final long ONE_HOUR = ONE_MINUTE * 60;
-    private static final long ONE_DAY = ONE_HOUR * 24;
-
-    static final long[] SCREEN_TIME_THRESHOLDS = {
-            0,
-            0,
-            COMPRESS_TIME ? 120 * 1000 : 1 * ONE_HOUR,
-            COMPRESS_TIME ? 240 * 1000 : 2 * ONE_HOUR
-    };
-
-    static final long[] ELAPSED_TIME_THRESHOLDS = {
-            0,
-            COMPRESS_TIME ?  1 * ONE_MINUTE : 12 * ONE_HOUR,
-            COMPRESS_TIME ?  4 * ONE_MINUTE : 24 * ONE_HOUR,
-            COMPRESS_TIME ? 16 * ONE_MINUTE : 48 * ONE_HOUR
-    };
-
-    static final int[] THRESHOLD_BUCKETS = {
-            STANDBY_BUCKET_ACTIVE,
-            STANDBY_BUCKET_WORKING_SET,
-            STANDBY_BUCKET_FREQUENT,
-            STANDBY_BUCKET_RARE
-    };
-
-    /** Default expiration time for bucket prediction. After this, use thresholds to downgrade. */
-    private static final long DEFAULT_PREDICTION_TIMEOUT = 12 * ONE_HOUR;
-
-    /**
-     * Indicates the maximum wait time for admin data to be available;
-     */
-    private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
-
-    // To name the lock for stack traces
-    static class Lock {}
-
-    /** Lock to protect the app's standby state. Required for calls into AppIdleHistory */
-    private final Object mAppIdleLock = new Lock();
-
-    /** Keeps the history and state for each app. */
-    @GuardedBy("mAppIdleLock")
-    private AppIdleHistory mAppIdleHistory;
-
-    @GuardedBy("mPackageAccessListeners")
-    private ArrayList<AppIdleStateChangeListener>
-            mPackageAccessListeners = new ArrayList<>();
-
-    /** Whether we've queried the list of carrier privileged apps. */
-    @GuardedBy("mAppIdleLock")
-    private boolean mHaveCarrierPrivilegedApps;
-
-    /** List of carrier-privileged apps that should be excluded from standby */
-    @GuardedBy("mAppIdleLock")
-    private List<String> mCarrierPrivilegedApps;
-
-    @GuardedBy("mActiveAdminApps")
-    private final SparseArray<Set<String>> mActiveAdminApps = new SparseArray<>();
-
-    private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
-
-    // Messages for the handler
-    static final int MSG_INFORM_LISTENERS = 3;
-    static final int MSG_FORCE_IDLE_STATE = 4;
-    static final int MSG_CHECK_IDLE_STATES = 5;
-    static final int MSG_CHECK_PAROLE_TIMEOUT = 6;
-    static final int MSG_PAROLE_END_TIMEOUT = 7;
-    static final int MSG_REPORT_CONTENT_PROVIDER_USAGE = 8;
-    static final int MSG_PAROLE_STATE_CHANGED = 9;
-    static final int MSG_ONE_TIME_CHECK_IDLE_STATES = 10;
-    /** Check the state of one app: arg1 = userId, arg2 = uid, obj = (String) packageName */
-    static final int MSG_CHECK_PACKAGE_IDLE_STATE = 11;
-    static final int MSG_REPORT_SYNC_SCHEDULED = 12;
-    static final int MSG_REPORT_EXEMPTED_SYNC_START = 13;
-    static final int MSG_UPDATE_STABLE_CHARGING= 14;
-
-    long mCheckIdleIntervalMillis;
-    long mAppIdleParoleIntervalMillis;
-    long mAppIdleParoleWindowMillis;
-    long mAppIdleParoleDurationMillis;
-    long[] mAppStandbyScreenThresholds = SCREEN_TIME_THRESHOLDS;
-    long[] mAppStandbyElapsedThresholds = ELAPSED_TIME_THRESHOLDS;
-    /** Minimum time a strong usage event should keep the bucket elevated. */
-    long mStrongUsageTimeoutMillis;
-    /** Minimum time a notification seen event should keep the bucket elevated. */
-    long mNotificationSeenTimeoutMillis;
-    /** Minimum time a system update event should keep the buckets elevated. */
-    long mSystemUpdateUsageTimeoutMillis;
-    /** Maximum time to wait for a prediction before using simple timeouts to downgrade buckets. */
-    long mPredictionTimeoutMillis;
-    /** Maximum time a sync adapter associated with a CP should keep the buckets elevated. */
-    long mSyncAdapterTimeoutMillis;
-    /**
-     * Maximum time an exempted sync should keep the buckets elevated, when sync is scheduled in
-     * non-doze
-     */
-    long mExemptedSyncScheduledNonDozeTimeoutMillis;
-    /**
-     * Maximum time an exempted sync should keep the buckets elevated, when sync is scheduled in
-     * doze
-     */
-    long mExemptedSyncScheduledDozeTimeoutMillis;
-    /**
-     * Maximum time an exempted sync should keep the buckets elevated, when sync is started.
-     */
-    long mExemptedSyncStartTimeoutMillis;
-    /**
-     * Maximum time an unexempted sync should keep the buckets elevated, when sync is scheduled
-     */
-    long mUnexemptedSyncScheduledTimeoutMillis;
-    /** Maximum time a system interaction should keep the buckets elevated. */
-    long mSystemInteractionTimeoutMillis;
-    /**
-     * Maximum time a foreground service start should keep the buckets elevated if the service
-     * start is the first usage of the app
-     */
-    long mInitialForegroundServiceStartTimeoutMillis;
-    /** The length of time phone must be charging before considered stable enough to run jobs  */
-    long mStableChargingThresholdMillis;
-
-    volatile boolean mAppIdleEnabled;
-    boolean mAppIdleTempParoled;
-    boolean mCharging;
-    boolean mChargingStable;
-    private long mLastAppIdleParoledTime;
-    private boolean mSystemServicesReady = false;
-    // There was a system update, defaults need to be initialized after services are ready
-    private boolean mPendingInitializeDefaults;
-
-    private final DeviceStateReceiver mDeviceStateReceiver;
-
-    private volatile boolean mPendingOneTimeCheckIdleStates;
-
-    private final AppStandbyHandler mHandler;
-    private final Context mContext;
-
-    // TODO: Provide a mechanism to set an external bucketing service
-
-    private AppWidgetManager mAppWidgetManager;
-    private ConnectivityManager mConnectivityManager;
-    private PowerManager mPowerManager;
-    private PackageManager mPackageManager;
-    Injector mInjector;
-
-    static final ArrayList<StandbyUpdateRecord> sStandbyUpdatePool = new ArrayList<>(4);
-
-    public static class StandbyUpdateRecord {
-        // Identity of the app whose standby state has changed
-        String packageName;
-        int userId;
-
-        // What the standby bucket the app is now in
-        int bucket;
-
-        // Whether the bucket change is because the user has started interacting with the app
-        boolean isUserInteraction;
-
-        // Reason for bucket change
-        int reason;
-
-        StandbyUpdateRecord(String pkgName, int userId, int bucket, int reason,
-                boolean isInteraction) {
-            this.packageName = pkgName;
-            this.userId = userId;
-            this.bucket = bucket;
-            this.reason = reason;
-            this.isUserInteraction = isInteraction;
-        }
-
-        public static StandbyUpdateRecord obtain(String pkgName, int userId,
-                int bucket, int reason, boolean isInteraction) {
-            synchronized (sStandbyUpdatePool) {
-                final int size = sStandbyUpdatePool.size();
-                if (size < 1) {
-                    return new StandbyUpdateRecord(pkgName, userId, bucket, reason, isInteraction);
-                }
-                StandbyUpdateRecord r = sStandbyUpdatePool.remove(size - 1);
-                r.packageName = pkgName;
-                r.userId = userId;
-                r.bucket = bucket;
-                r.reason = reason;
-                r.isUserInteraction = isInteraction;
-                return r;
-            }
-        }
-
-        public void recycle() {
-            synchronized (sStandbyUpdatePool) {
-                sStandbyUpdatePool.add(this);
-            }
-        }
-    }
-
-    AppStandbyController(Context context, Looper looper) {
-        this(new Injector(context, looper));
-    }
-
-    AppStandbyController(Injector injector) {
-        mInjector = injector;
-        mContext = mInjector.getContext();
-        mHandler = new AppStandbyHandler(mInjector.getLooper());
-        mPackageManager = mContext.getPackageManager();
-        mDeviceStateReceiver = new DeviceStateReceiver();
-
-        IntentFilter deviceStates = new IntentFilter(BatteryManager.ACTION_CHARGING);
-        deviceStates.addAction(BatteryManager.ACTION_DISCHARGING);
-        deviceStates.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
-        mContext.registerReceiver(mDeviceStateReceiver, deviceStates);
-
-        synchronized (mAppIdleLock) {
-            mAppIdleHistory = new AppIdleHistory(mInjector.getDataSystemDirectory(),
-                    mInjector.elapsedRealtime());
-        }
-
-        IntentFilter packageFilter = new IntentFilter();
-        packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
-        packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
-        packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
-        packageFilter.addDataScheme("package");
-
-        mContext.registerReceiverAsUser(new PackageReceiver(), UserHandle.ALL, packageFilter,
-                null, mHandler);
-    }
-
-    void setAppIdleEnabled(boolean enabled) {
-        synchronized (mAppIdleLock) {
-            if (mAppIdleEnabled != enabled) {
-                final boolean oldParoleState = isParoledOrCharging();
-                mAppIdleEnabled = enabled;
-                if (isParoledOrCharging() != oldParoleState) {
-                    postParoleStateChanged();
-                }
-            }
-        }
-    }
-
-    public void onBootPhase(int phase) {
-        mInjector.onBootPhase(phase);
-        if (phase == PHASE_SYSTEM_SERVICES_READY) {
-            Slog.d(TAG, "Setting app idle enabled state");
-            // Observe changes to the threshold
-            SettingsObserver settingsObserver = new SettingsObserver(mHandler);
-            settingsObserver.registerObserver();
-            settingsObserver.updateSettings();
-
-            mAppWidgetManager = mContext.getSystemService(AppWidgetManager.class);
-            mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
-            mPowerManager = mContext.getSystemService(PowerManager.class);
-
-            mInjector.registerDisplayListener(mDisplayListener, mHandler);
-            synchronized (mAppIdleLock) {
-                mAppIdleHistory.updateDisplay(isDisplayOn(), mInjector.elapsedRealtime());
-            }
-
-            mSystemServicesReady = true;
-
-            boolean userFileExists;
-            synchronized (mAppIdleLock) {
-                userFileExists = mAppIdleHistory.userFileExists(UserHandle.USER_SYSTEM);
-            }
-
-            if (mPendingInitializeDefaults || !userFileExists) {
-                initializeDefaultsForSystemApps(UserHandle.USER_SYSTEM);
-            }
-
-            if (mPendingOneTimeCheckIdleStates) {
-                postOneTimeCheckIdleStates();
-            }
-        } else if (phase == PHASE_BOOT_COMPLETED) {
-            setChargingState(mInjector.isCharging());
-        }
-    }
-
-    void reportContentProviderUsage(String authority, String providerPkgName, int userId) {
-        if (!mAppIdleEnabled) return;
-
-        // Get sync adapters for the authority
-        String[] packages = ContentResolver.getSyncAdapterPackagesForAuthorityAsUser(
-                authority, userId);
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-        for (String packageName: packages) {
-            // Only force the sync adapters to active if the provider is not in the same package and
-            // the sync adapter is a system package.
-            try {
-                PackageInfo pi = mPackageManager.getPackageInfoAsUser(
-                        packageName, PackageManager.MATCH_SYSTEM_ONLY, userId);
-                if (pi == null || pi.applicationInfo == null) {
-                    continue;
-                }
-                if (!packageName.equals(providerPkgName)) {
-                    synchronized (mAppIdleLock) {
-                        AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
-                                STANDBY_BUCKET_ACTIVE, REASON_SUB_USAGE_SYNC_ADAPTER,
-                                0,
-                                elapsedRealtime + mSyncAdapterTimeoutMillis);
-                        maybeInformListeners(packageName, userId, elapsedRealtime,
-                                appUsage.currentBucket, appUsage.bucketingReason, false);
-                    }
-                }
-            } catch (PackageManager.NameNotFoundException e) {
-                // Shouldn't happen
-            }
-        }
-    }
-
-    void reportExemptedSyncScheduled(String packageName, int userId) {
-        if (!mAppIdleEnabled) return;
-
-        final int bucketToPromote;
-        final int usageReason;
-        final long durationMillis;
-
-        if (!mInjector.isDeviceIdleMode()) {
-            // Not dozing.
-            bucketToPromote = STANDBY_BUCKET_ACTIVE;
-            usageReason = REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE;
-            durationMillis = mExemptedSyncScheduledNonDozeTimeoutMillis;
-        } else {
-            // Dozing.
-            bucketToPromote = STANDBY_BUCKET_WORKING_SET;
-            usageReason = REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE;
-            durationMillis = mExemptedSyncScheduledDozeTimeoutMillis;
-        }
-
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-
-        synchronized (mAppIdleLock) {
-            AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
-                    bucketToPromote, usageReason,
-                    0,
-                    elapsedRealtime + durationMillis);
-            maybeInformListeners(packageName, userId, elapsedRealtime,
-                    appUsage.currentBucket, appUsage.bucketingReason, false);
-        }
-    }
-
-    void reportUnexemptedSyncScheduled(String packageName, int userId) {
-        if (!mAppIdleEnabled) return;
-
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-        synchronized (mAppIdleLock) {
-            final int currentBucket =
-                    mAppIdleHistory.getAppStandbyBucket(packageName, userId, elapsedRealtime);
-            if (currentBucket == STANDBY_BUCKET_NEVER) {
-                // Bring the app out of the never bucket
-                AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
-                        STANDBY_BUCKET_WORKING_SET, REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED,
-                        0,
-                        elapsedRealtime + mUnexemptedSyncScheduledTimeoutMillis);
-                maybeInformListeners(packageName, userId, elapsedRealtime,
-                        appUsage.currentBucket, appUsage.bucketingReason, false);
-            }
-        }
-    }
-
-    void reportExemptedSyncStart(String packageName, int userId) {
-        if (!mAppIdleEnabled) return;
-
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-
-        synchronized (mAppIdleLock) {
-            AppUsageHistory appUsage = mAppIdleHistory.reportUsage(packageName, userId,
-                    STANDBY_BUCKET_ACTIVE, REASON_SUB_USAGE_EXEMPTED_SYNC_START,
-                    0,
-                    elapsedRealtime + mExemptedSyncStartTimeoutMillis);
-            maybeInformListeners(packageName, userId, elapsedRealtime,
-                    appUsage.currentBucket, appUsage.bucketingReason, false);
-        }
-    }
-
-    void setChargingState(boolean charging) {
-        synchronized (mAppIdleLock) {
-            if (mCharging != charging) {
-                mCharging = charging;
-                if (DEBUG) Slog.d(TAG, "Setting mCharging to " + charging);
-                if (charging) {
-                    if (DEBUG) {
-                        Slog.d(TAG, "Scheduling MSG_UPDATE_STABLE_CHARGING  delay = "
-                                + mStableChargingThresholdMillis);
-                    }
-                    mHandler.sendEmptyMessageDelayed(MSG_UPDATE_STABLE_CHARGING,
-                            mStableChargingThresholdMillis);
-                } else {
-                    mHandler.removeMessages(MSG_UPDATE_STABLE_CHARGING);
-                    updateChargingStableState();
-                }
-            }
-        }
-    }
-
-    void updateChargingStableState() {
-        synchronized (mAppIdleLock) {
-            if (mChargingStable != mCharging) {
-                if (DEBUG) Slog.d(TAG, "Setting mChargingStable to " + mCharging);
-                mChargingStable = mCharging;
-                postParoleStateChanged();
-            }
-        }
-    }
-
-    /** Paroled here means temporary pardon from being inactive */
-    void setAppIdleParoled(boolean paroled) {
-        synchronized (mAppIdleLock) {
-            final long now = mInjector.currentTimeMillis();
-            if (mAppIdleTempParoled != paroled) {
-                mAppIdleTempParoled = paroled;
-                if (DEBUG) Slog.d(TAG, "Changing paroled to " + mAppIdleTempParoled);
-                if (paroled) {
-                    postParoleEndTimeout();
-                } else {
-                    mLastAppIdleParoledTime = now;
-                    postNextParoleTimeout(now, false);
-                }
-                postParoleStateChanged();
-            }
-        }
-    }
-
-    boolean isParoledOrCharging() {
-        if (!mAppIdleEnabled) return true;
-        synchronized (mAppIdleLock) {
-            // Only consider stable charging when determining charge state.
-            return mAppIdleTempParoled || mChargingStable;
-        }
-    }
-
-    private void postNextParoleTimeout(long now, boolean forced) {
-        if (DEBUG) Slog.d(TAG, "Posting MSG_CHECK_PAROLE_TIMEOUT");
-        mHandler.removeMessages(MSG_CHECK_PAROLE_TIMEOUT);
-        // Compute when the next parole needs to happen. We check more frequently than necessary
-        // since the message handler delays are based on elapsedRealTime and not wallclock time.
-        // The comparison is done in wallclock time.
-        long timeLeft = (mLastAppIdleParoledTime + mAppIdleParoleIntervalMillis) - now;
-        if (forced) {
-            // Set next timeout for the end of the parole window
-            // If parole is not set by the end of the window it will be forced
-            timeLeft += mAppIdleParoleWindowMillis;
-        }
-        if (timeLeft < 0) {
-            timeLeft = 0;
-        }
-        mHandler.sendEmptyMessageDelayed(MSG_CHECK_PAROLE_TIMEOUT, timeLeft);
-    }
-
-    private void postParoleEndTimeout() {
-        if (DEBUG) Slog.d(TAG, "Posting MSG_PAROLE_END_TIMEOUT");
-        mHandler.removeMessages(MSG_PAROLE_END_TIMEOUT);
-        mHandler.sendEmptyMessageDelayed(MSG_PAROLE_END_TIMEOUT, mAppIdleParoleDurationMillis);
-    }
-
-    private void postParoleStateChanged() {
-        if (DEBUG) Slog.d(TAG, "Posting MSG_PAROLE_STATE_CHANGED");
-        mHandler.removeMessages(MSG_PAROLE_STATE_CHANGED);
-        mHandler.sendEmptyMessage(MSG_PAROLE_STATE_CHANGED);
-    }
-
-    void postCheckIdleStates(int userId) {
-        mHandler.sendMessage(mHandler.obtainMessage(MSG_CHECK_IDLE_STATES, userId, 0));
-    }
-
-    /**
-     * We send a different message to check idle states once, otherwise we would end up
-     * scheduling a series of repeating checkIdleStates each time we fired off one.
-     */
-    void postOneTimeCheckIdleStates() {
-        if (mInjector.getBootPhase() < PHASE_SYSTEM_SERVICES_READY) {
-            // Not booted yet; wait for it!
-            mPendingOneTimeCheckIdleStates = true;
-        } else {
-            mHandler.sendEmptyMessage(MSG_ONE_TIME_CHECK_IDLE_STATES);
-            mPendingOneTimeCheckIdleStates = false;
-        }
-    }
-
-    /**
-     * Check all running users' or specified user's apps to see if they enter an idle state.
-     * @return Returns whether checking should continue periodically.
-     */
-    boolean checkIdleStates(int checkUserId) {
-        if (!mAppIdleEnabled) {
-            return false;
-        }
-
-        final int[] runningUserIds;
-        try {
-            runningUserIds = mInjector.getRunningUserIds();
-            if (checkUserId != UserHandle.USER_ALL
-                    && !ArrayUtils.contains(runningUserIds, checkUserId)) {
-                return false;
-            }
-        } catch (RemoteException re) {
-            throw re.rethrowFromSystemServer();
-        }
-
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-        for (int i = 0; i < runningUserIds.length; i++) {
-            final int userId = runningUserIds[i];
-            if (checkUserId != UserHandle.USER_ALL && checkUserId != userId) {
-                continue;
-            }
-            if (DEBUG) {
-                Slog.d(TAG, "Checking idle state for user " + userId);
-            }
-            List<PackageInfo> packages = mPackageManager.getInstalledPackagesAsUser(
-                    PackageManager.MATCH_DISABLED_COMPONENTS,
-                    userId);
-            final int packageCount = packages.size();
-            for (int p = 0; p < packageCount; p++) {
-                final PackageInfo pi = packages.get(p);
-                final String packageName = pi.packageName;
-                checkAndUpdateStandbyState(packageName, userId, pi.applicationInfo.uid,
-                        elapsedRealtime);
-            }
-        }
-        if (DEBUG) {
-            Slog.d(TAG, "checkIdleStates took "
-                    + (mInjector.elapsedRealtime() - elapsedRealtime));
-        }
-        return true;
-    }
-
-    /** Check if we need to update the standby state of a specific app. */
-    private void checkAndUpdateStandbyState(String packageName, @UserIdInt int userId,
-            int uid, long elapsedRealtime) {
-        if (uid <= 0) {
-            try {
-                uid = mPackageManager.getPackageUidAsUser(packageName, userId);
-            } catch (PackageManager.NameNotFoundException e) {
-                // Not a valid package for this user, nothing to do
-                // TODO: Remove any history of removed packages
-                return;
-            }
-        }
-        final boolean isSpecial = isAppSpecial(packageName,
-                UserHandle.getAppId(uid),
-                userId);
-        if (DEBUG) {
-            Slog.d(TAG, "   Checking idle state for " + packageName + " special=" +
-                    isSpecial);
-        }
-        if (isSpecial) {
-            synchronized (mAppIdleLock) {
-                mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime,
-                        STANDBY_BUCKET_EXEMPTED, REASON_MAIN_DEFAULT);
-            }
-            maybeInformListeners(packageName, userId, elapsedRealtime,
-                    STANDBY_BUCKET_EXEMPTED, REASON_MAIN_DEFAULT, false);
-        } else {
-            synchronized (mAppIdleLock) {
-                final AppIdleHistory.AppUsageHistory app =
-                        mAppIdleHistory.getAppUsageHistory(packageName,
-                        userId, elapsedRealtime);
-                int reason = app.bucketingReason;
-                final int oldMainReason = reason & REASON_MAIN_MASK;
-
-                // If the bucket was forced by the user/developer, leave it alone.
-                // A usage event will be the only way to bring it out of this forced state
-                if (oldMainReason == REASON_MAIN_FORCED) {
-                    return;
-                }
-                final int oldBucket = app.currentBucket;
-                int newBucket = Math.max(oldBucket, STANDBY_BUCKET_ACTIVE); // Undo EXEMPTED
-                boolean predictionLate = predictionTimedOut(app, elapsedRealtime);
-                // Compute age-based bucket
-                if (oldMainReason == REASON_MAIN_DEFAULT
-                        || oldMainReason == REASON_MAIN_USAGE
-                        || oldMainReason == REASON_MAIN_TIMEOUT
-                        || predictionLate) {
-
-                    if (!predictionLate && app.lastPredictedBucket >= STANDBY_BUCKET_ACTIVE
-                            && app.lastPredictedBucket <= STANDBY_BUCKET_RARE) {
-                        newBucket = app.lastPredictedBucket;
-                        reason = REASON_MAIN_PREDICTED | REASON_SUB_PREDICTED_RESTORED;
-                        if (DEBUG) {
-                            Slog.d(TAG, "Restored predicted newBucket = " + newBucket);
-                        }
-                    } else {
-                        newBucket = getBucketForLocked(packageName, userId,
-                                elapsedRealtime);
-                        if (DEBUG) {
-                            Slog.d(TAG, "Evaluated AOSP newBucket = " + newBucket);
-                        }
-                        reason = REASON_MAIN_TIMEOUT;
-                    }
-                }
-
-                // Check if the app is within one of the timeouts for forced bucket elevation
-                final long elapsedTimeAdjusted = mAppIdleHistory.getElapsedTime(elapsedRealtime);
-                if (newBucket >= STANDBY_BUCKET_ACTIVE
-                        && app.bucketActiveTimeoutTime > elapsedTimeAdjusted) {
-                    newBucket = STANDBY_BUCKET_ACTIVE;
-                    reason = app.bucketingReason;
-                    if (DEBUG) {
-                        Slog.d(TAG, "    Keeping at ACTIVE due to min timeout");
-                    }
-                } else if (newBucket >= STANDBY_BUCKET_WORKING_SET
-                        && app.bucketWorkingSetTimeoutTime > elapsedTimeAdjusted) {
-                    newBucket = STANDBY_BUCKET_WORKING_SET;
-                    // If it was already there, keep the reason, else assume timeout to WS
-                    reason = (newBucket == oldBucket)
-                            ? app.bucketingReason
-                            : REASON_MAIN_USAGE | REASON_SUB_USAGE_ACTIVE_TIMEOUT;
-                    if (DEBUG) {
-                        Slog.d(TAG, "    Keeping at WORKING_SET due to min timeout");
-                    }
-                }
-                if (DEBUG) {
-                    Slog.d(TAG, "     Old bucket=" + oldBucket
-                            + ", newBucket=" + newBucket);
-                }
-                if (oldBucket < newBucket || predictionLate) {
-                    mAppIdleHistory.setAppStandbyBucket(packageName, userId,
-                            elapsedRealtime, newBucket, reason);
-                    maybeInformListeners(packageName, userId, elapsedRealtime,
-                            newBucket, reason, false);
-                }
-            }
-        }
-    }
-
-    /** Returns true if there hasn't been a prediction for the app in a while. */
-    private boolean predictionTimedOut(AppIdleHistory.AppUsageHistory app, long elapsedRealtime) {
-        return app.lastPredictedTime > 0
-                && mAppIdleHistory.getElapsedTime(elapsedRealtime)
-                    - app.lastPredictedTime > mPredictionTimeoutMillis;
-    }
-
-    /** Inform listeners if the bucket has changed since it was last reported to listeners */
-    private void maybeInformListeners(String packageName, int userId,
-            long elapsedRealtime, int bucket, int reason, boolean userStartedInteracting) {
-        synchronized (mAppIdleLock) {
-            if (mAppIdleHistory.shouldInformListeners(packageName, userId,
-                    elapsedRealtime, bucket)) {
-                final StandbyUpdateRecord r = StandbyUpdateRecord.obtain(packageName, userId,
-                        bucket, reason, userStartedInteracting);
-                if (DEBUG) Slog.d(TAG, "Standby bucket for " + packageName + "=" + bucket);
-                mHandler.sendMessage(mHandler.obtainMessage(MSG_INFORM_LISTENERS, r));
-            }
-        }
-    }
-
-    /**
-     * Evaluates next bucket based on time since last used and the bucketing thresholds.
-     * @param packageName the app
-     * @param userId the user
-     * @param elapsedRealtime as the name suggests, current elapsed time
-     * @return the bucket for the app, based on time since last used
-     */
-    @GuardedBy("mAppIdleLock")
-    @StandbyBuckets int getBucketForLocked(String packageName, int userId,
-            long elapsedRealtime) {
-        int bucketIndex = mAppIdleHistory.getThresholdIndex(packageName, userId,
-                elapsedRealtime, mAppStandbyScreenThresholds, mAppStandbyElapsedThresholds);
-        return THRESHOLD_BUCKETS[bucketIndex];
-    }
-
-    /**
-     * Check if it's been a while since last parole and let idle apps do some work.
-     * If network is not available, delay parole until it is available up until the end of the
-     * parole window. Force the parole to be set if end of the parole window is reached.
-     */
-    void checkParoleTimeout() {
-        boolean setParoled = false;
-        boolean waitForNetwork = false;
-        NetworkInfo activeNetwork = mConnectivityManager.getActiveNetworkInfo();
-        boolean networkActive = activeNetwork != null &&
-                activeNetwork.isConnected();
-
-        synchronized (mAppIdleLock) {
-            final long now = mInjector.currentTimeMillis();
-            if (!mAppIdleTempParoled) {
-                final long timeSinceLastParole = now - mLastAppIdleParoledTime;
-                if (timeSinceLastParole > mAppIdleParoleIntervalMillis) {
-                    if (DEBUG) Slog.d(TAG, "Crossed default parole interval");
-                    if (networkActive) {
-                        // If network is active set parole
-                        setParoled = true;
-                    } else {
-                        if (timeSinceLastParole
-                                > mAppIdleParoleIntervalMillis + mAppIdleParoleWindowMillis) {
-                            if (DEBUG) Slog.d(TAG, "Crossed end of parole window, force parole");
-                            setParoled = true;
-                        } else {
-                            if (DEBUG) Slog.d(TAG, "Network unavailable, delaying parole");
-                            waitForNetwork = true;
-                            postNextParoleTimeout(now, true);
-                        }
-                    }
-                } else {
-                    if (DEBUG) Slog.d(TAG, "Not long enough to go to parole");
-                    postNextParoleTimeout(now, false);
-                }
-            }
-        }
-        if (waitForNetwork) {
-            mConnectivityManager.registerNetworkCallback(mNetworkRequest, mNetworkCallback);
-        }
-        if (setParoled) {
-            // Set parole if network is available
-            setAppIdleParoled(true);
-        }
-    }
-
-    private void notifyBatteryStats(String packageName, int userId, boolean idle) {
-        try {
-            final int uid = mPackageManager.getPackageUidAsUser(packageName,
-                    PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
-            if (idle) {
-                mInjector.noteEvent(BatteryStats.HistoryItem.EVENT_PACKAGE_INACTIVE,
-                        packageName, uid);
-            } else {
-                mInjector.noteEvent(BatteryStats.HistoryItem.EVENT_PACKAGE_ACTIVE,
-                        packageName, uid);
-            }
-        } catch (PackageManager.NameNotFoundException | RemoteException e) {
-        }
-    }
-
-    void onDeviceIdleModeChanged() {
-        final boolean deviceIdle = mPowerManager.isDeviceIdleMode();
-        if (DEBUG) Slog.i(TAG, "DeviceIdleMode changed to " + deviceIdle);
-        boolean paroled = false;
-        synchronized (mAppIdleLock) {
-            final long timeSinceLastParole =
-                    mInjector.currentTimeMillis() - mLastAppIdleParoledTime;
-            if (!deviceIdle
-                    && timeSinceLastParole >= mAppIdleParoleIntervalMillis) {
-                if (DEBUG) {
-                    Slog.i(TAG,
-                            "Bringing idle apps out of inactive state due to deviceIdleMode=false");
-                }
-                paroled = true;
-            } else if (deviceIdle) {
-                if (DEBUG) Slog.i(TAG, "Device idle, back to prison");
-                paroled = false;
-            } else {
-                return;
-            }
-        }
-        setAppIdleParoled(paroled);
-    }
-
-    void reportEvent(UsageEvents.Event event, long elapsedRealtime, int userId) {
-        if (!mAppIdleEnabled) return;
-        synchronized (mAppIdleLock) {
-            // TODO: Ideally this should call isAppIdleFiltered() to avoid calling back
-            // about apps that are on some kind of whitelist anyway.
-            final boolean previouslyIdle = mAppIdleHistory.isIdle(
-                    event.mPackage, userId, elapsedRealtime);
-            // Inform listeners if necessary
-            if ((event.mEventType == UsageEvents.Event.ACTIVITY_RESUMED
-                    || event.mEventType == UsageEvents.Event.ACTIVITY_PAUSED
-                    || event.mEventType == UsageEvents.Event.SYSTEM_INTERACTION
-                    || event.mEventType == UsageEvents.Event.USER_INTERACTION
-                    || event.mEventType == UsageEvents.Event.NOTIFICATION_SEEN
-                    || event.mEventType == UsageEvents.Event.SLICE_PINNED
-                    || event.mEventType == UsageEvents.Event.SLICE_PINNED_PRIV
-                    || event.mEventType == UsageEvents.Event.FOREGROUND_SERVICE_START)) {
-
-                final AppUsageHistory appHistory = mAppIdleHistory.getAppUsageHistory(
-                        event.mPackage, userId, elapsedRealtime);
-                final int prevBucket = appHistory.currentBucket;
-                final int prevBucketReason = appHistory.bucketingReason;
-                final long nextCheckTime;
-                final int subReason = usageEventToSubReason(event.mEventType);
-                final int reason = REASON_MAIN_USAGE | subReason;
-                if (event.mEventType == UsageEvents.Event.NOTIFICATION_SEEN
-                        || event.mEventType == UsageEvents.Event.SLICE_PINNED) {
-                    // Mild usage elevates to WORKING_SET but doesn't change usage time.
-                    mAppIdleHistory.reportUsage(appHistory, event.mPackage,
-                            STANDBY_BUCKET_WORKING_SET, subReason,
-                            0, elapsedRealtime + mNotificationSeenTimeoutMillis);
-                    nextCheckTime = mNotificationSeenTimeoutMillis;
-                } else if (event.mEventType == UsageEvents.Event.SYSTEM_INTERACTION) {
-                    mAppIdleHistory.reportUsage(appHistory, event.mPackage,
-                            STANDBY_BUCKET_ACTIVE, subReason,
-                            0, elapsedRealtime + mSystemInteractionTimeoutMillis);
-                    nextCheckTime = mSystemInteractionTimeoutMillis;
-                } else if (event.mEventType == UsageEvents.Event.FOREGROUND_SERVICE_START) {
-                    // Only elevate bucket if this is the first usage of the app
-                    if (prevBucket != STANDBY_BUCKET_NEVER) return;
-                    mAppIdleHistory.reportUsage(appHistory, event.mPackage,
-                            STANDBY_BUCKET_ACTIVE, subReason,
-                            0, elapsedRealtime + mInitialForegroundServiceStartTimeoutMillis);
-                    nextCheckTime = mInitialForegroundServiceStartTimeoutMillis;
-                } else {
-                    mAppIdleHistory.reportUsage(appHistory, event.mPackage,
-                            STANDBY_BUCKET_ACTIVE, subReason,
-                            elapsedRealtime, elapsedRealtime + mStrongUsageTimeoutMillis);
-                    nextCheckTime = mStrongUsageTimeoutMillis;
-                }
-                mHandler.sendMessageDelayed(mHandler.obtainMessage
-                        (MSG_CHECK_PACKAGE_IDLE_STATE, userId, -1, event.mPackage),
-                        nextCheckTime);
-                final boolean userStartedInteracting =
-                        appHistory.currentBucket == STANDBY_BUCKET_ACTIVE &&
-                        prevBucket != appHistory.currentBucket &&
-                        (prevBucketReason & REASON_MAIN_MASK) != REASON_MAIN_USAGE;
-                maybeInformListeners(event.mPackage, userId, elapsedRealtime,
-                        appHistory.currentBucket, reason, userStartedInteracting);
-
-                if (previouslyIdle) {
-                    notifyBatteryStats(event.mPackage, userId, false);
-                }
-            }
-        }
-    }
-
-    private int usageEventToSubReason(int eventType) {
-        switch (eventType) {
-            case UsageEvents.Event.ACTIVITY_RESUMED: return REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
-            case UsageEvents.Event.ACTIVITY_PAUSED: return REASON_SUB_USAGE_MOVE_TO_BACKGROUND;
-            case UsageEvents.Event.SYSTEM_INTERACTION: return REASON_SUB_USAGE_SYSTEM_INTERACTION;
-            case UsageEvents.Event.USER_INTERACTION: return REASON_SUB_USAGE_USER_INTERACTION;
-            case UsageEvents.Event.NOTIFICATION_SEEN: return REASON_SUB_USAGE_NOTIFICATION_SEEN;
-            case UsageEvents.Event.SLICE_PINNED: return REASON_SUB_USAGE_SLICE_PINNED;
-            case UsageEvents.Event.SLICE_PINNED_PRIV: return REASON_SUB_USAGE_SLICE_PINNED_PRIV;
-            case UsageEvents.Event.FOREGROUND_SERVICE_START:
-                return REASON_SUB_USAGE_FOREGROUND_SERVICE_START;
-            default: return 0;
-        }
-    }
-
-    /**
-     * Forces the app's beginIdleTime and lastUsedTime to reflect idle or active. If idle,
-     * then it rolls back the beginIdleTime and lastUsedTime to a point in time that's behind
-     * the threshold for idle.
-     *
-     * This method is always called from the handler thread, so not much synchronization is
-     * required.
-     */
-    void forceIdleState(String packageName, int userId, boolean idle) {
-        if (!mAppIdleEnabled) return;
-
-        final int appId = getAppId(packageName);
-        if (appId < 0) return;
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-
-        final boolean previouslyIdle = isAppIdleFiltered(packageName, appId,
-                userId, elapsedRealtime);
-        final int standbyBucket;
-        synchronized (mAppIdleLock) {
-            standbyBucket = mAppIdleHistory.setIdle(packageName, userId, idle, elapsedRealtime);
-        }
-        final boolean stillIdle = isAppIdleFiltered(packageName, appId,
-                userId, elapsedRealtime);
-        // Inform listeners if necessary
-        if (previouslyIdle != stillIdle) {
-            maybeInformListeners(packageName, userId, elapsedRealtime, standbyBucket,
-                    REASON_MAIN_FORCED, false);
-            if (!stillIdle) {
-                notifyBatteryStats(packageName, userId, idle);
-            }
-        }
-    }
-
-    public void setLastJobRunTime(String packageName, int userId, long elapsedRealtime) {
-        synchronized (mAppIdleLock) {
-            mAppIdleHistory.setLastJobRunTime(packageName, userId, elapsedRealtime);
-        }
-    }
-
-    public long getTimeSinceLastJobRun(String packageName, int userId) {
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-        synchronized (mAppIdleLock) {
-            return mAppIdleHistory.getTimeSinceLastJobRun(packageName, userId, elapsedRealtime);
-        }
-    }
-
-    public void onUserRemoved(int userId) {
-        synchronized (mAppIdleLock) {
-            mAppIdleHistory.onUserRemoved(userId);
-            synchronized (mActiveAdminApps) {
-                mActiveAdminApps.remove(userId);
-            }
-        }
-    }
-
-    private boolean isAppIdleUnfiltered(String packageName, int userId, long elapsedRealtime) {
-        synchronized (mAppIdleLock) {
-            return mAppIdleHistory.isIdle(packageName, userId, elapsedRealtime);
-        }
-    }
-
-    void addListener(AppIdleStateChangeListener listener) {
-        synchronized (mPackageAccessListeners) {
-            if (!mPackageAccessListeners.contains(listener)) {
-                mPackageAccessListeners.add(listener);
-            }
-        }
-    }
-
-    void removeListener(AppIdleStateChangeListener listener) {
-        synchronized (mPackageAccessListeners) {
-            mPackageAccessListeners.remove(listener);
-        }
-    }
-
-    int getAppId(String packageName) {
-        try {
-            ApplicationInfo ai = mPackageManager.getApplicationInfo(packageName,
-                    PackageManager.MATCH_ANY_USER
-                            | PackageManager.MATCH_DISABLED_COMPONENTS);
-            return ai.uid;
-        } catch (PackageManager.NameNotFoundException re) {
-            return -1;
-        }
-    }
-
-    boolean isAppIdleFilteredOrParoled(String packageName, int userId, long elapsedRealtime,
-            boolean shouldObfuscateInstantApps) {
-        if (isParoledOrCharging()) {
-            return false;
-        }
-        if (shouldObfuscateInstantApps &&
-                mInjector.isPackageEphemeral(userId, packageName)) {
-            return false;
-        }
-        return isAppIdleFiltered(packageName, getAppId(packageName), userId, elapsedRealtime);
-    }
-
-    /** Returns true if this app should be whitelisted for some reason, to never go into standby */
-    boolean isAppSpecial(String packageName, int appId, int userId) {
-        if (packageName == null) return false;
-        // If not enabled at all, of course nobody is ever idle.
-        if (!mAppIdleEnabled) {
-            return true;
-        }
-        if (appId < Process.FIRST_APPLICATION_UID) {
-            // System uids never go idle.
-            return true;
-        }
-        if (packageName.equals("android")) {
-            // Nor does the framework (which should be redundant with the above, but for MR1 we will
-            // retain this for safety).
-            return true;
-        }
-        if (mSystemServicesReady) {
-            try {
-                // We allow all whitelisted apps, including those that don't want to be whitelisted
-                // for idle mode, because app idle (aka app standby) is really not as big an issue
-                // for controlling who participates vs. doze mode.
-                if (mInjector.isPowerSaveWhitelistExceptIdleApp(packageName)) {
-                    return true;
-                }
-            } catch (RemoteException re) {
-                throw re.rethrowFromSystemServer();
-            }
-
-            if (isActiveDeviceAdmin(packageName, userId)) {
-                return true;
-            }
-
-            if (isActiveNetworkScorer(packageName)) {
-                return true;
-            }
-
-            if (mAppWidgetManager != null
-                    && mInjector.isBoundWidgetPackage(mAppWidgetManager, packageName, userId)) {
-                return true;
-            }
-
-            if (isDeviceProvisioningPackage(packageName)) {
-                return true;
-            }
-        }
-
-        // Check this last, as it can be the most expensive check
-        if (isCarrierApp(packageName)) {
-            return true;
-        }
-
-        return false;
-    }
-
-    /**
-     * Checks if an app has been idle for a while and filters out apps that are excluded.
-     * It returns false if the current system state allows all apps to be considered active.
-     * This happens if the device is plugged in or temporarily allowed to make exceptions.
-     * Called by interface impls.
-     */
-    boolean isAppIdleFiltered(String packageName, int appId, int userId,
-            long elapsedRealtime) {
-        if (isAppSpecial(packageName, appId, userId)) {
-            return false;
-        } else {
-            return isAppIdleUnfiltered(packageName, userId, elapsedRealtime);
-        }
-    }
-
-    int[] getIdleUidsForUser(int userId) {
-        if (!mAppIdleEnabled) {
-            return new int[0];
-        }
-
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-
-        List<ApplicationInfo> apps;
-        try {
-            ParceledListSlice<ApplicationInfo> slice = AppGlobals.getPackageManager()
-                    .getInstalledApplications(/* flags= */ 0, userId);
-            if (slice == null) {
-                return new int[0];
-            }
-            apps = slice.getList();
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-
-        // State of each uid.  Key is the uid.  Value lower 16 bits is the number of apps
-        // associated with that uid, upper 16 bits is the number of those apps that is idle.
-        SparseIntArray uidStates = new SparseIntArray();
-
-        // Now resolve all app state.  Iterating over all apps, keeping track of how many
-        // we find for each uid and how many of those are idle.
-        for (int i = apps.size() - 1; i >= 0; i--) {
-            ApplicationInfo ai = apps.get(i);
-
-            // Check whether this app is idle.
-            boolean idle = isAppIdleFiltered(ai.packageName, UserHandle.getAppId(ai.uid),
-                    userId, elapsedRealtime);
-
-            int index = uidStates.indexOfKey(ai.uid);
-            if (index < 0) {
-                uidStates.put(ai.uid, 1 + (idle ? 1<<16 : 0));
-            } else {
-                int value = uidStates.valueAt(index);
-                uidStates.setValueAt(index, value + 1 + (idle ? 1<<16 : 0));
-            }
-        }
-        if (DEBUG) {
-            Slog.d(TAG, "getIdleUids took " + (mInjector.elapsedRealtime() - elapsedRealtime));
-        }
-        int numIdle = 0;
-        for (int i = uidStates.size() - 1; i >= 0; i--) {
-            int value = uidStates.valueAt(i);
-            if ((value&0x7fff) == (value>>16)) {
-                numIdle++;
-            }
-        }
-
-        int[] res = new int[numIdle];
-        numIdle = 0;
-        for (int i = uidStates.size() - 1; i >= 0; i--) {
-            int value = uidStates.valueAt(i);
-            if ((value&0x7fff) == (value>>16)) {
-                res[numIdle] = uidStates.keyAt(i);
-                numIdle++;
-            }
-        }
-
-        return res;
-    }
-
-    void setAppIdleAsync(String packageName, boolean idle, int userId) {
-        if (packageName == null || !mAppIdleEnabled) return;
-
-        mHandler.obtainMessage(MSG_FORCE_IDLE_STATE, userId, idle ? 1 : 0, packageName)
-                .sendToTarget();
-    }
-
-    @StandbyBuckets public int getAppStandbyBucket(String packageName, int userId,
-            long elapsedRealtime, boolean shouldObfuscateInstantApps) {
-        if (!mAppIdleEnabled || (shouldObfuscateInstantApps
-                && mInjector.isPackageEphemeral(userId, packageName))) {
-            return STANDBY_BUCKET_ACTIVE;
-        }
-
-        synchronized (mAppIdleLock) {
-            return mAppIdleHistory.getAppStandbyBucket(packageName, userId, elapsedRealtime);
-        }
-    }
-
-    public List<AppStandbyInfo> getAppStandbyBuckets(int userId) {
-        synchronized (mAppIdleLock) {
-            return mAppIdleHistory.getAppStandbyBuckets(userId, mAppIdleEnabled);
-        }
-    }
-
-    void setAppStandbyBucket(String packageName, int userId, @StandbyBuckets int newBucket,
-            int reason, long elapsedRealtime) {
-        setAppStandbyBucket(packageName, userId, newBucket, reason, elapsedRealtime, false);
-    }
-
-    void setAppStandbyBucket(String packageName, int userId, @StandbyBuckets int newBucket,
-            int reason, long elapsedRealtime, boolean resetTimeout) {
-        synchronized (mAppIdleLock) {
-            // If the package is not installed, don't allow the bucket to be set.
-            if (!mInjector.isPackageInstalled(packageName, 0, userId)) {
-                return;
-            }
-            AppIdleHistory.AppUsageHistory app = mAppIdleHistory.getAppUsageHistory(packageName,
-                    userId, elapsedRealtime);
-            boolean predicted = (reason & REASON_MAIN_MASK) == REASON_MAIN_PREDICTED;
-
-            // Don't allow changing bucket if higher than ACTIVE
-            if (app.currentBucket < STANDBY_BUCKET_ACTIVE) return;
-
-            // Don't allow prediction to change from/to NEVER
-            if ((app.currentBucket == STANDBY_BUCKET_NEVER
-                    || newBucket == STANDBY_BUCKET_NEVER)
-                    && predicted) {
-                return;
-            }
-
-            // If the bucket was forced, don't allow prediction to override
-            if ((app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_FORCED && predicted) return;
-
-            // If the bucket is required to stay in a higher state for a specified duration, don't
-            // override unless the duration has passed
-            if (predicted) {
-                // Check if the app is within one of the timeouts for forced bucket elevation
-                final long elapsedTimeAdjusted = mAppIdleHistory.getElapsedTime(elapsedRealtime);
-                // In case of not using the prediction, just keep track of it for applying after
-                // ACTIVE or WORKING_SET timeout.
-                mAppIdleHistory.updateLastPrediction(app, elapsedTimeAdjusted, newBucket);
-
-                if (newBucket > STANDBY_BUCKET_ACTIVE
-                        && app.bucketActiveTimeoutTime > elapsedTimeAdjusted) {
-                    newBucket = STANDBY_BUCKET_ACTIVE;
-                    reason = app.bucketingReason;
-                    if (DEBUG) {
-                        Slog.d(TAG, "    Keeping at ACTIVE due to min timeout");
-                    }
-                } else if (newBucket > STANDBY_BUCKET_WORKING_SET
-                        && app.bucketWorkingSetTimeoutTime > elapsedTimeAdjusted) {
-                    newBucket = STANDBY_BUCKET_WORKING_SET;
-                    if (app.currentBucket != newBucket) {
-                        reason = REASON_MAIN_USAGE | REASON_SUB_USAGE_ACTIVE_TIMEOUT;
-                    } else {
-                        reason = app.bucketingReason;
-                    }
-                    if (DEBUG) {
-                        Slog.d(TAG, "    Keeping at WORKING_SET due to min timeout");
-                    }
-                }
-            }
-
-            mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime, newBucket,
-                    reason, resetTimeout);
-        }
-        maybeInformListeners(packageName, userId, elapsedRealtime, newBucket, reason, false);
-    }
-
-    @VisibleForTesting
-    boolean isActiveDeviceAdmin(String packageName, int userId) {
-        synchronized (mActiveAdminApps) {
-            final Set<String> adminPkgs = mActiveAdminApps.get(userId);
-            return adminPkgs != null && adminPkgs.contains(packageName);
-        }
-    }
-
-    public void addActiveDeviceAdmin(String adminPkg, int userId) {
-        synchronized (mActiveAdminApps) {
-            Set<String> adminPkgs = mActiveAdminApps.get(userId);
-            if (adminPkgs == null) {
-                adminPkgs = new ArraySet<>();
-                mActiveAdminApps.put(userId, adminPkgs);
-            }
-            adminPkgs.add(adminPkg);
-        }
-    }
-
-    public void setActiveAdminApps(Set<String> adminPkgs, int userId) {
-        synchronized (mActiveAdminApps) {
-            if (adminPkgs == null) {
-                mActiveAdminApps.remove(userId);
-            } else {
-                mActiveAdminApps.put(userId, adminPkgs);
-            }
-        }
-    }
-
-    public void onAdminDataAvailable() {
-        mAdminDataAvailableLatch.countDown();
-    }
-
-    /**
-     * This will only ever be called once - during device boot.
-     */
-    private void waitForAdminData() {
-        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
-            ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
-                    WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
-        }
-    }
-
-    Set<String> getActiveAdminAppsForTest(int userId) {
-        synchronized (mActiveAdminApps) {
-            return mActiveAdminApps.get(userId);
-        }
-    }
-
-    /**
-     * Returns {@code true} if the supplied package is the device provisioning app. Otherwise,
-     * returns {@code false}.
-     */
-    private boolean isDeviceProvisioningPackage(String packageName) {
-        String deviceProvisioningPackage = mContext.getResources().getString(
-                com.android.internal.R.string.config_deviceProvisioningPackage);
-        return deviceProvisioningPackage != null && deviceProvisioningPackage.equals(packageName);
-    }
-
-    private boolean isCarrierApp(String packageName) {
-        synchronized (mAppIdleLock) {
-            if (!mHaveCarrierPrivilegedApps) {
-                fetchCarrierPrivilegedAppsLocked();
-            }
-            if (mCarrierPrivilegedApps != null) {
-                return mCarrierPrivilegedApps.contains(packageName);
-            }
-            return false;
-        }
-    }
-
-    void clearCarrierPrivilegedApps() {
-        if (DEBUG) {
-            Slog.i(TAG, "Clearing carrier privileged apps list");
-        }
-        synchronized (mAppIdleLock) {
-            mHaveCarrierPrivilegedApps = false;
-            mCarrierPrivilegedApps = null; // Need to be refetched.
-        }
-    }
-
-    @GuardedBy("mAppIdleLock")
-    private void fetchCarrierPrivilegedAppsLocked() {
-        TelephonyManager telephonyManager =
-                mContext.getSystemService(TelephonyManager.class);
-        mCarrierPrivilegedApps = telephonyManager.getPackagesWithCarrierPrivilegesForAllPhones();
-        mHaveCarrierPrivilegedApps = true;
-        if (DEBUG) {
-            Slog.d(TAG, "apps with carrier privilege " + mCarrierPrivilegedApps);
-        }
-    }
-
-    private boolean isActiveNetworkScorer(String packageName) {
-        String activeScorer = mInjector.getActiveNetworkScorer();
-        return packageName != null && packageName.equals(activeScorer);
-    }
-
-    void informListeners(String packageName, int userId, int bucket, int reason,
-            boolean userInteraction) {
-        final boolean idle = bucket >= STANDBY_BUCKET_RARE;
-        synchronized (mPackageAccessListeners) {
-            for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
-                listener.onAppIdleStateChanged(packageName, userId, idle, bucket, reason);
-                if (userInteraction) {
-                    listener.onUserInteractionStarted(packageName, userId);
-                }
-            }
-        }
-    }
-
-    void informParoleStateChanged() {
-        final boolean paroled = isParoledOrCharging();
-        synchronized (mPackageAccessListeners) {
-            for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
-                listener.onParoleStateChanged(paroled);
-            }
-        }
-    }
-
-    void flushToDisk(int userId) {
-        synchronized (mAppIdleLock) {
-            mAppIdleHistory.writeAppIdleTimes(userId);
-        }
-    }
-
-    void flushDurationsToDisk() {
-        // Persist elapsed and screen on time. If this fails for whatever reason, the apps will be
-        // considered not-idle, which is the safest outcome in such an event.
-        synchronized (mAppIdleLock) {
-            mAppIdleHistory.writeAppIdleDurations();
-        }
-    }
-
-    boolean isDisplayOn() {
-        return mInjector.isDefaultDisplayOn();
-    }
-
-    void clearAppIdleForPackage(String packageName, int userId) {
-        synchronized (mAppIdleLock) {
-            mAppIdleHistory.clearUsage(packageName, userId);
-        }
-    }
-
-    private class PackageReceiver extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            final String action = intent.getAction();
-            if (Intent.ACTION_PACKAGE_ADDED.equals(action)
-                    || Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
-                clearCarrierPrivilegedApps();
-            }
-            if ((Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
-                    Intent.ACTION_PACKAGE_ADDED.equals(action))
-                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
-                clearAppIdleForPackage(intent.getData().getSchemeSpecificPart(),
-                        getSendingUserId());
-            }
-        }
-    }
-
-    void initializeDefaultsForSystemApps(int userId) {
-        if (!mSystemServicesReady) {
-            // Do it later, since SettingsProvider wasn't queried yet for app_standby_enabled
-            mPendingInitializeDefaults = true;
-            return;
-        }
-        Slog.d(TAG, "Initializing defaults for system apps on user " + userId + ", "
-                + "appIdleEnabled=" + mAppIdleEnabled);
-        final long elapsedRealtime = mInjector.elapsedRealtime();
-        List<PackageInfo> packages = mPackageManager.getInstalledPackagesAsUser(
-                PackageManager.MATCH_DISABLED_COMPONENTS,
-                userId);
-        final int packageCount = packages.size();
-        synchronized (mAppIdleLock) {
-            for (int i = 0; i < packageCount; i++) {
-                final PackageInfo pi = packages.get(i);
-                String packageName = pi.packageName;
-                if (pi.applicationInfo != null && pi.applicationInfo.isSystemApp()) {
-                    // Mark app as used for 2 hours. After that it can timeout to whatever the
-                    // past usage pattern was.
-                    mAppIdleHistory.reportUsage(packageName, userId, STANDBY_BUCKET_ACTIVE,
-                            REASON_SUB_USAGE_SYSTEM_UPDATE, 0,
-                            elapsedRealtime + mSystemUpdateUsageTimeoutMillis);
-                }
-            }
-            // Immediately persist defaults to disk
-            mAppIdleHistory.writeAppIdleTimes(userId);
-        }
-    }
-
-    void postReportContentProviderUsage(String name, String packageName, int userId) {
-        SomeArgs args = SomeArgs.obtain();
-        args.arg1 = name;
-        args.arg2 = packageName;
-        args.arg3 = userId;
-        mHandler.obtainMessage(MSG_REPORT_CONTENT_PROVIDER_USAGE, args)
-                .sendToTarget();
-    }
-
-    void postReportSyncScheduled(String packageName, int userId, boolean exempted) {
-        mHandler.obtainMessage(MSG_REPORT_SYNC_SCHEDULED, userId, exempted ? 1 : 0, packageName)
-                .sendToTarget();
-    }
-
-    void postReportExemptedSyncStart(String packageName, int userId) {
-        mHandler.obtainMessage(MSG_REPORT_EXEMPTED_SYNC_START, userId, 0, packageName)
-                .sendToTarget();
-    }
-
-    void dumpUser(IndentingPrintWriter idpw, int userId, String pkg) {
-        synchronized (mAppIdleLock) {
-            mAppIdleHistory.dump(idpw, userId, pkg);
-        }
-    }
-
-    void dumpState(String[] args, PrintWriter pw) {
-        synchronized (mAppIdleLock) {
-            pw.println("Carrier privileged apps (have=" + mHaveCarrierPrivilegedApps
-                    + "): " + mCarrierPrivilegedApps);
-        }
-
-        final long now = System.currentTimeMillis();
-
-        pw.println();
-        pw.println("Settings:");
-
-        pw.print("  mCheckIdleIntervalMillis=");
-        TimeUtils.formatDuration(mCheckIdleIntervalMillis, pw);
-        pw.println();
-
-        pw.print("  mAppIdleParoleIntervalMillis=");
-        TimeUtils.formatDuration(mAppIdleParoleIntervalMillis, pw);
-        pw.println();
-
-        pw.print("  mAppIdleParoleWindowMillis=");
-        TimeUtils.formatDuration(mAppIdleParoleWindowMillis, pw);
-        pw.println();
-
-        pw.print("  mAppIdleParoleDurationMillis=");
-        TimeUtils.formatDuration(mAppIdleParoleDurationMillis, pw);
-        pw.println();
-
-        pw.print("  mStrongUsageTimeoutMillis=");
-        TimeUtils.formatDuration(mStrongUsageTimeoutMillis, pw);
-        pw.println();
-        pw.print("  mNotificationSeenTimeoutMillis=");
-        TimeUtils.formatDuration(mNotificationSeenTimeoutMillis, pw);
-        pw.println();
-        pw.print("  mSyncAdapterTimeoutMillis=");
-        TimeUtils.formatDuration(mSyncAdapterTimeoutMillis, pw);
-        pw.println();
-        pw.print("  mSystemInteractionTimeoutMillis=");
-        TimeUtils.formatDuration(mSystemInteractionTimeoutMillis, pw);
-        pw.println();
-        pw.print("  mInitialForegroundServiceStartTimeoutMillis=");
-        TimeUtils.formatDuration(mInitialForegroundServiceStartTimeoutMillis, pw);
-        pw.println();
-
-        pw.print("  mPredictionTimeoutMillis=");
-        TimeUtils.formatDuration(mPredictionTimeoutMillis, pw);
-        pw.println();
-
-        pw.print("  mExemptedSyncScheduledNonDozeTimeoutMillis=");
-        TimeUtils.formatDuration(mExemptedSyncScheduledNonDozeTimeoutMillis, pw);
-        pw.println();
-        pw.print("  mExemptedSyncScheduledDozeTimeoutMillis=");
-        TimeUtils.formatDuration(mExemptedSyncScheduledDozeTimeoutMillis, pw);
-        pw.println();
-        pw.print("  mExemptedSyncStartTimeoutMillis=");
-        TimeUtils.formatDuration(mExemptedSyncStartTimeoutMillis, pw);
-        pw.println();
-        pw.print("  mUnexemptedSyncScheduledTimeoutMillis=");
-        TimeUtils.formatDuration(mUnexemptedSyncScheduledTimeoutMillis, pw);
-        pw.println();
-
-        pw.print("  mSystemUpdateUsageTimeoutMillis=");
-        TimeUtils.formatDuration(mSystemUpdateUsageTimeoutMillis, pw);
-        pw.println();
-
-        pw.print("  mStableChargingThresholdMillis=");
-        TimeUtils.formatDuration(mStableChargingThresholdMillis, pw);
-        pw.println();
-
-        pw.println();
-        pw.print("mAppIdleEnabled="); pw.print(mAppIdleEnabled);
-        pw.print(" mAppIdleTempParoled="); pw.print(mAppIdleTempParoled);
-        pw.print(" mCharging="); pw.print(mCharging);
-        pw.print(" mChargingStable="); pw.print(mChargingStable);
-        pw.print(" mLastAppIdleParoledTime=");
-        TimeUtils.formatDuration(now - mLastAppIdleParoledTime, pw);
-        pw.println();
-        pw.print("mScreenThresholds="); pw.println(Arrays.toString(mAppStandbyScreenThresholds));
-        pw.print("mElapsedThresholds="); pw.println(Arrays.toString(mAppStandbyElapsedThresholds));
-        pw.print("mStableChargingThresholdMillis=");
-        TimeUtils.formatDuration(mStableChargingThresholdMillis, pw);
-        pw.println();
-    }
-
-    /**
-     * Injector for interaction with external code. Override methods to provide a mock
-     * implementation for tests.
-     * onBootPhase() must be called with at least the PHASE_SYSTEM_SERVICES_READY
-     */
-    static class Injector {
-
-        private final Context mContext;
-        private final Looper mLooper;
-        private IDeviceIdleController mDeviceIdleController;
-        private IBatteryStats mBatteryStats;
-        private PackageManagerInternal mPackageManagerInternal;
-        private DisplayManager mDisplayManager;
-        private PowerManager mPowerManager;
-        int mBootPhase;
-
-        Injector(Context context, Looper looper) {
-            mContext = context;
-            mLooper = looper;
-        }
-
-        Context getContext() {
-            return mContext;
-        }
-
-        Looper getLooper() {
-            return mLooper;
-        }
-
-        void onBootPhase(int phase) {
-            if (phase == PHASE_SYSTEM_SERVICES_READY) {
-                mDeviceIdleController = IDeviceIdleController.Stub.asInterface(
-                        ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
-                mBatteryStats = IBatteryStats.Stub.asInterface(
-                        ServiceManager.getService(BatteryStats.SERVICE_NAME));
-                mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
-                mDisplayManager = (DisplayManager) mContext.getSystemService(
-                        Context.DISPLAY_SERVICE);
-                mPowerManager = mContext.getSystemService(PowerManager.class);
-            }
-            mBootPhase = phase;
-        }
-
-        int getBootPhase() {
-            return mBootPhase;
-        }
-
-        /**
-         * Returns the elapsed realtime since the device started. Override this
-         * to control the clock.
-         * @return elapsed realtime
-         */
-        long elapsedRealtime() {
-            return SystemClock.elapsedRealtime();
-        }
-
-        long currentTimeMillis() {
-            return System.currentTimeMillis();
-        }
-
-        boolean isAppIdleEnabled() {
-            final boolean buildFlag = mContext.getResources().getBoolean(
-                    com.android.internal.R.bool.config_enableAutoPowerModes);
-            final boolean runtimeFlag = Global.getInt(mContext.getContentResolver(),
-                    Global.APP_STANDBY_ENABLED, 1) == 1
-                    && Global.getInt(mContext.getContentResolver(),
-                    Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED, 1) == 1;
-            return buildFlag && runtimeFlag;
-        }
-
-        boolean isCharging() {
-            return mContext.getSystemService(BatteryManager.class).isCharging();
-        }
-
-        boolean isPowerSaveWhitelistExceptIdleApp(String packageName) throws RemoteException {
-            return mDeviceIdleController.isPowerSaveWhitelistExceptIdleApp(packageName);
-        }
-
-        File getDataSystemDirectory() {
-            return Environment.getDataSystemDirectory();
-        }
-
-        void noteEvent(int event, String packageName, int uid) throws RemoteException {
-            mBatteryStats.noteEvent(event, packageName, uid);
-        }
-
-        boolean isPackageEphemeral(int userId, String packageName) {
-            return mPackageManagerInternal.isPackageEphemeral(userId, packageName);
-        }
-
-        boolean isPackageInstalled(String packageName, int flags, int userId) {
-            return mPackageManagerInternal.getPackageUid(packageName, flags, userId) >= 0;
-        }
-
-        int[] getRunningUserIds() throws RemoteException {
-            return ActivityManager.getService().getRunningUserIds();
-        }
-
-        boolean isDefaultDisplayOn() {
-            return mDisplayManager
-                    .getDisplay(Display.DEFAULT_DISPLAY).getState() == Display.STATE_ON;
-        }
-
-        void registerDisplayListener(DisplayManager.DisplayListener listener, Handler handler) {
-            mDisplayManager.registerDisplayListener(listener, handler);
-        }
-
-        String getActiveNetworkScorer() {
-            NetworkScoreManager nsm = (NetworkScoreManager) mContext.getSystemService(
-                    Context.NETWORK_SCORE_SERVICE);
-            return nsm.getActiveScorerPackage();
-        }
-
-        public boolean isBoundWidgetPackage(AppWidgetManager appWidgetManager, String packageName,
-                int userId) {
-            return appWidgetManager.isBoundWidgetPackage(packageName, userId);
-        }
-
-        String getAppIdleSettings() {
-            return Global.getString(mContext.getContentResolver(),
-                    Global.APP_IDLE_CONSTANTS);
-        }
-
-        /** Whether the device is in doze or not. */
-        public boolean isDeviceIdleMode() {
-            return mPowerManager.isDeviceIdleMode();
-        }
-    }
-
-    class AppStandbyHandler extends Handler {
-
-        AppStandbyHandler(Looper looper) {
-            super(looper);
-        }
-
-        @Override
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case MSG_INFORM_LISTENERS:
-                    StandbyUpdateRecord r = (StandbyUpdateRecord) msg.obj;
-                    informListeners(r.packageName, r.userId, r.bucket, r.reason,
-                            r.isUserInteraction);
-                    r.recycle();
-                    break;
-
-                case MSG_FORCE_IDLE_STATE:
-                    forceIdleState((String) msg.obj, msg.arg1, msg.arg2 == 1);
-                    break;
-
-                case MSG_CHECK_IDLE_STATES:
-                    if (checkIdleStates(msg.arg1) && mAppIdleEnabled) {
-                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
-                                MSG_CHECK_IDLE_STATES, msg.arg1, 0),
-                                mCheckIdleIntervalMillis);
-                    }
-                    break;
-
-                case MSG_ONE_TIME_CHECK_IDLE_STATES:
-                    mHandler.removeMessages(MSG_ONE_TIME_CHECK_IDLE_STATES);
-                    waitForAdminData();
-                    checkIdleStates(UserHandle.USER_ALL);
-                    break;
-
-                case MSG_CHECK_PAROLE_TIMEOUT:
-                    checkParoleTimeout();
-                    break;
-
-                case MSG_PAROLE_END_TIMEOUT:
-                    if (DEBUG) Slog.d(TAG, "Ending parole");
-                    setAppIdleParoled(false);
-                    break;
-
-                case MSG_REPORT_CONTENT_PROVIDER_USAGE:
-                    SomeArgs args = (SomeArgs) msg.obj;
-                    reportContentProviderUsage((String) args.arg1, // authority name
-                            (String) args.arg2, // package name
-                            (int) args.arg3); // userId
-                    args.recycle();
-                    break;
-
-                case MSG_PAROLE_STATE_CHANGED:
-                    if (DEBUG) Slog.d(TAG, "Parole state: " + mAppIdleTempParoled
-                            + ", Charging state:" + mChargingStable);
-                    informParoleStateChanged();
-                    break;
-                case MSG_CHECK_PACKAGE_IDLE_STATE:
-                    checkAndUpdateStandbyState((String) msg.obj, msg.arg1, msg.arg2,
-                            mInjector.elapsedRealtime());
-                    break;
-
-                case MSG_REPORT_SYNC_SCHEDULED:
-                    final boolean exempted = msg.arg1 > 0 ? true : false;
-                    if (exempted) {
-                        reportExemptedSyncScheduled((String) msg.obj, msg.arg1);
-                    } else {
-                        reportUnexemptedSyncScheduled((String) msg.obj, msg.arg1);
-                    }
-                    break;
-
-                case MSG_REPORT_EXEMPTED_SYNC_START:
-                    reportExemptedSyncStart((String) msg.obj, msg.arg1);
-                    break;
-
-                case MSG_UPDATE_STABLE_CHARGING:
-                    updateChargingStableState();
-                    break;
-
-                default:
-                    super.handleMessage(msg);
-                    break;
-
-            }
-        }
-    };
-
-    private class DeviceStateReceiver extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            switch (intent.getAction()) {
-                case BatteryManager.ACTION_CHARGING:
-                    setChargingState(true);
-                    break;
-                case BatteryManager.ACTION_DISCHARGING:
-                    setChargingState(false);
-                    break;
-                case PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED:
-                    onDeviceIdleModeChanged();
-                    break;
-            }
-        }
-    }
-
-    private final NetworkRequest mNetworkRequest = new NetworkRequest.Builder().build();
-
-    private final ConnectivityManager.NetworkCallback mNetworkCallback
-            = new ConnectivityManager.NetworkCallback() {
-        @Override
-        public void onAvailable(Network network) {
-            mConnectivityManager.unregisterNetworkCallback(this);
-            checkParoleTimeout();
-        }
-    };
-
-    private final DisplayManager.DisplayListener mDisplayListener
-            = new DisplayManager.DisplayListener() {
-
-        @Override public void onDisplayAdded(int displayId) {
-        }
-
-        @Override public void onDisplayRemoved(int displayId) {
-        }
-
-        @Override public void onDisplayChanged(int displayId) {
-            if (displayId == Display.DEFAULT_DISPLAY) {
-                final boolean displayOn = isDisplayOn();
-                synchronized (mAppIdleLock) {
-                    mAppIdleHistory.updateDisplay(displayOn, mInjector.elapsedRealtime());
-                }
-            }
-        }
-    };
-
-    /**
-     * Observe settings changes for {@link Global#APP_IDLE_CONSTANTS}.
-     */
-    private class SettingsObserver extends ContentObserver {
-        /**
-         * This flag has been used to disable app idle on older builds with bug b/26355386.
-         */
-        @Deprecated
-        private static final String KEY_IDLE_DURATION_OLD = "idle_duration";
-        @Deprecated
-        private static final String KEY_IDLE_DURATION = "idle_duration2";
-        @Deprecated
-        private static final String KEY_WALLCLOCK_THRESHOLD = "wallclock_threshold";
-
-        private static final String KEY_PAROLE_INTERVAL = "parole_interval";
-        private static final String KEY_PAROLE_WINDOW = "parole_window";
-        private static final String KEY_PAROLE_DURATION = "parole_duration";
-        private static final String KEY_SCREEN_TIME_THRESHOLDS = "screen_thresholds";
-        private static final String KEY_ELAPSED_TIME_THRESHOLDS = "elapsed_thresholds";
-        private static final String KEY_STRONG_USAGE_HOLD_DURATION = "strong_usage_duration";
-        private static final String KEY_NOTIFICATION_SEEN_HOLD_DURATION =
-                "notification_seen_duration";
-        private static final String KEY_SYSTEM_UPDATE_HOLD_DURATION =
-                "system_update_usage_duration";
-        private static final String KEY_PREDICTION_TIMEOUT = "prediction_timeout";
-        private static final String KEY_SYNC_ADAPTER_HOLD_DURATION = "sync_adapter_duration";
-        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION =
-                "exempted_sync_scheduled_nd_duration";
-        private static final String KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION =
-                "exempted_sync_scheduled_d_duration";
-        private static final String KEY_EXEMPTED_SYNC_START_HOLD_DURATION =
-                "exempted_sync_start_duration";
-        private static final String KEY_UNEXEMPTED_SYNC_SCHEDULED_HOLD_DURATION =
-                "unexempted_sync_scheduled_duration";
-        private static final String KEY_SYSTEM_INTERACTION_HOLD_DURATION =
-                "system_interaction_duration";
-        private static final String KEY_INITIAL_FOREGROUND_SERVICE_START_HOLD_DURATION =
-                "initial_foreground_service_start_duration";
-        private static final String KEY_STABLE_CHARGING_THRESHOLD = "stable_charging_threshold";
-        public static final long DEFAULT_STRONG_USAGE_TIMEOUT = 1 * ONE_HOUR;
-        public static final long DEFAULT_NOTIFICATION_TIMEOUT = 12 * ONE_HOUR;
-        public static final long DEFAULT_SYSTEM_UPDATE_TIMEOUT = 2 * ONE_HOUR;
-        public static final long DEFAULT_SYSTEM_INTERACTION_TIMEOUT = 10 * ONE_MINUTE;
-        public static final long DEFAULT_SYNC_ADAPTER_TIMEOUT = 10 * ONE_MINUTE;
-        public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT = 10 * ONE_MINUTE;
-        public static final long DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT = 4 * ONE_HOUR;
-        public static final long DEFAULT_EXEMPTED_SYNC_START_TIMEOUT = 10 * ONE_MINUTE;
-        public static final long DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT = 10 * ONE_MINUTE;
-        public static final long DEFAULT_STABLE_CHARGING_THRESHOLD = 10 * ONE_MINUTE;
-        public static final long DEFAULT_INITIAL_FOREGROUND_SERVICE_START_TIMEOUT = 30 * ONE_MINUTE;
-
-        private final KeyValueListParser mParser = new KeyValueListParser(',');
-
-        SettingsObserver(Handler handler) {
-            super(handler);
-        }
-
-        void registerObserver() {
-            final ContentResolver cr = mContext.getContentResolver();
-            cr.registerContentObserver(Global.getUriFor(Global.APP_IDLE_CONSTANTS), false, this);
-            cr.registerContentObserver(Global.getUriFor(Global.APP_STANDBY_ENABLED), false, this);
-            cr.registerContentObserver(Global.getUriFor(Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED),
-                    false, this);
-        }
-
-        @Override
-        public void onChange(boolean selfChange) {
-            updateSettings();
-            postOneTimeCheckIdleStates();
-        }
-
-        void updateSettings() {
-            if (DEBUG) {
-                Slog.d(TAG,
-                        "appidle=" + Global.getString(mContext.getContentResolver(),
-                                Global.APP_STANDBY_ENABLED));
-                Slog.d(TAG,
-                        "adaptivebat=" + Global.getString(mContext.getContentResolver(),
-                                Global.ADAPTIVE_BATTERY_MANAGEMENT_ENABLED));
-                Slog.d(TAG, "appidleconstants=" + Global.getString(
-                        mContext.getContentResolver(),
-                        Global.APP_IDLE_CONSTANTS));
-            }
-
-            // Look at global settings for this.
-            // TODO: Maybe apply different thresholds for different users.
-            try {
-                mParser.setString(mInjector.getAppIdleSettings());
-            } catch (IllegalArgumentException e) {
-                Slog.e(TAG, "Bad value for app idle settings: " + e.getMessage());
-                // fallthrough, mParser is empty and all defaults will be returned.
-            }
-
-            synchronized (mAppIdleLock) {
-
-                // Default: 24 hours between paroles
-                mAppIdleParoleIntervalMillis = mParser.getDurationMillis(KEY_PAROLE_INTERVAL,
-                        COMPRESS_TIME ? ONE_MINUTE * 10 : 24 * 60 * ONE_MINUTE);
-
-                // Default: 2 hours to wait on network
-                mAppIdleParoleWindowMillis = mParser.getDurationMillis(KEY_PAROLE_WINDOW,
-                        COMPRESS_TIME ? ONE_MINUTE * 2 : 2 * 60 * ONE_MINUTE);
-
-                mAppIdleParoleDurationMillis = mParser.getDurationMillis(KEY_PAROLE_DURATION,
-                        COMPRESS_TIME ? ONE_MINUTE : 10 * ONE_MINUTE); // 10 minutes
-
-                String screenThresholdsValue = mParser.getString(KEY_SCREEN_TIME_THRESHOLDS, null);
-                mAppStandbyScreenThresholds = parseLongArray(screenThresholdsValue,
-                        SCREEN_TIME_THRESHOLDS);
-
-                String elapsedThresholdsValue = mParser.getString(KEY_ELAPSED_TIME_THRESHOLDS,
-                        null);
-                mAppStandbyElapsedThresholds = parseLongArray(elapsedThresholdsValue,
-                        ELAPSED_TIME_THRESHOLDS);
-                mCheckIdleIntervalMillis = Math.min(mAppStandbyElapsedThresholds[1] / 4,
-                        COMPRESS_TIME ? ONE_MINUTE : 4 * 60 * ONE_MINUTE); // 4 hours
-                mStrongUsageTimeoutMillis = mParser.getDurationMillis(
-                        KEY_STRONG_USAGE_HOLD_DURATION,
-                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_STRONG_USAGE_TIMEOUT);
-                mNotificationSeenTimeoutMillis = mParser.getDurationMillis(
-                        KEY_NOTIFICATION_SEEN_HOLD_DURATION,
-                                COMPRESS_TIME ? 12 * ONE_MINUTE : DEFAULT_NOTIFICATION_TIMEOUT);
-                mSystemUpdateUsageTimeoutMillis = mParser.getDurationMillis(
-                        KEY_SYSTEM_UPDATE_HOLD_DURATION,
-                                COMPRESS_TIME ? 2 * ONE_MINUTE : DEFAULT_SYSTEM_UPDATE_TIMEOUT);
-                mPredictionTimeoutMillis = mParser.getDurationMillis(
-                        KEY_PREDICTION_TIMEOUT,
-                                COMPRESS_TIME ? 10 * ONE_MINUTE : DEFAULT_PREDICTION_TIMEOUT);
-                mSyncAdapterTimeoutMillis = mParser.getDurationMillis(
-                        KEY_SYNC_ADAPTER_HOLD_DURATION,
-                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_SYNC_ADAPTER_TIMEOUT);
-
-                mExemptedSyncScheduledNonDozeTimeoutMillis = mParser.getDurationMillis(
-                        KEY_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_HOLD_DURATION,
-                                COMPRESS_TIME ? (ONE_MINUTE / 2)
-                                        : DEFAULT_EXEMPTED_SYNC_SCHEDULED_NON_DOZE_TIMEOUT);
-
-                mExemptedSyncScheduledDozeTimeoutMillis = mParser.getDurationMillis(
-                        KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION,
-                                COMPRESS_TIME ? ONE_MINUTE
-                                        : DEFAULT_EXEMPTED_SYNC_SCHEDULED_DOZE_TIMEOUT);
-
-                mExemptedSyncStartTimeoutMillis = mParser.getDurationMillis(
-                        KEY_EXEMPTED_SYNC_START_HOLD_DURATION,
-                                COMPRESS_TIME ? ONE_MINUTE
-                                        : DEFAULT_EXEMPTED_SYNC_START_TIMEOUT);
-
-                mUnexemptedSyncScheduledTimeoutMillis = mParser.getDurationMillis(
-                        KEY_EXEMPTED_SYNC_SCHEDULED_DOZE_HOLD_DURATION,
-                                COMPRESS_TIME ? ONE_MINUTE
-                                        : DEFAULT_UNEXEMPTED_SYNC_SCHEDULED_TIMEOUT); // TODO
-
-                mSystemInteractionTimeoutMillis = mParser.getDurationMillis(
-                        KEY_SYSTEM_INTERACTION_HOLD_DURATION,
-                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_SYSTEM_INTERACTION_TIMEOUT);
-
-                mInitialForegroundServiceStartTimeoutMillis = mParser.getDurationMillis(
-                        KEY_INITIAL_FOREGROUND_SERVICE_START_HOLD_DURATION,
-                        COMPRESS_TIME ? ONE_MINUTE :
-                                DEFAULT_INITIAL_FOREGROUND_SERVICE_START_TIMEOUT);
-
-                mStableChargingThresholdMillis = mParser.getDurationMillis(
-                        KEY_STABLE_CHARGING_THRESHOLD,
-                                COMPRESS_TIME ? ONE_MINUTE : DEFAULT_STABLE_CHARGING_THRESHOLD);
-            }
-
-            // Check if app_idle_enabled has changed. Do this after getting the rest of the settings
-            // in case we need to change something based on the new values.
-            setAppIdleEnabled(mInjector.isAppIdleEnabled());
-        }
-
-        long[] parseLongArray(String values, long[] defaults) {
-            if (values == null) return defaults;
-            if (values.isEmpty()) {
-                // Reset to defaults
-                return defaults;
-            } else {
-                String[] thresholds = values.split("/");
-                if (thresholds.length == THRESHOLD_BUCKETS.length) {
-                    long[] array = new long[THRESHOLD_BUCKETS.length];
-                    for (int i = 0; i < THRESHOLD_BUCKETS.length; i++) {
-                        try {
-                            if (thresholds[i].startsWith("P") || thresholds[i].startsWith("p")) {
-                                array[i] = Duration.parse(thresholds[i]).toMillis();
-                            } else {
-                                array[i] = Long.parseLong(thresholds[i]);
-                            }
-                        } catch (NumberFormatException|DateTimeParseException e) {
-                            return defaults;
-                        }
-                    }
-                    return array;
-                } else {
-                    return defaults;
-                }
-            }
-        }
-    }
-}
diff --git a/services/usage/java/com/android/server/usage/UsageStatsService.java b/services/usage/java/com/android/server/usage/UsageStatsService.java
index 090623e..ecee709 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsService.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsService.java
@@ -97,6 +97,8 @@
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
 import java.nio.file.Files;
 import java.nio.file.StandardCopyOption;
 import java.util.Arrays;
@@ -159,7 +161,7 @@
     int mUsageSource;
 
     /** Manages the standby state of apps. */
-    AppStandbyController mAppStandby;
+    AppStandbyInternal mAppStandby;
 
     /** Manages app time limit observers */
     AppTimeLimitController mAppTimeLimit;
@@ -208,7 +210,9 @@
         mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
         mHandler = new H(BackgroundThread.get().getLooper());
 
-        mAppStandby = new AppStandbyController(getContext(), BackgroundThread.get().getLooper());
+        mAppStandby = AppStandbyInternal.newAppStandbyController(
+                UsageStatsService.class.getClassLoader(), getContext(),
+                BackgroundThread.get().getLooper());
 
         mAppTimeLimit = new AppTimeLimitController(
                 new AppTimeLimitController.TimeLimitCallbackListener() {
@@ -340,6 +344,10 @@
             mUserUnlockedStates.put(userId, true);
             final UserUsageStatsService userService = getUserDataAndInitializeIfNeededLocked(
                     userId, System.currentTimeMillis());
+            if (userService == null) {
+                Slog.i(TAG, "Attempted to unlock stopped or removed user " + userId);
+                return;
+            }
             userService.userUnlocked(System.currentTimeMillis());
             // Process all the pending reported events
             while (pendingEvents.peek() != null) {
@@ -456,7 +464,17 @@
                     "usagestats");
             service = new UserUsageStatsService(getContext(), userId, usageStatsDir, this);
             if (mUserUnlockedStates.get(userId)) {
-                service.init(currentTimeMillis);
+                try {
+                    service.init(currentTimeMillis);
+                } catch (Exception e) {
+                    if (mUserManager.isUserUnlocked(userId)) {
+                        throw e; // rethrow exception - user is unlocked
+                    } else {
+                        Slog.w(TAG, "Attempted to initialize service for "
+                                + "stopped or removed user " + userId);
+                        return null;
+                    }
+                }
             }
             mUserState.put(userId, service);
         }
@@ -779,6 +797,9 @@
 
             final UserUsageStatsService service =
                     getUserDataAndInitializeIfNeededLocked(userId, timeNow);
+            if (service == null) {
+                return; // user was stopped or removed
+            }
             service.reportEvent(event);
 
             mAppStandby.reportEvent(event, elapsedRealtime, userId);
@@ -841,6 +862,9 @@
 
             final UserUsageStatsService service =
                     getUserDataAndInitializeIfNeededLocked(userId, System.currentTimeMillis());
+            if (service == null) {
+                return null; // user was stopped or removed
+            }
             List<UsageStats> list = service.queryUsageStats(bucketType, beginTime, endTime);
             if (list == null) {
                 return null;
@@ -873,6 +897,9 @@
 
             final UserUsageStatsService service =
                     getUserDataAndInitializeIfNeededLocked(userId, System.currentTimeMillis());
+            if (service == null) {
+                return null; // user was stopped or removed
+            }
             return service.queryConfigurationStats(bucketType, beginTime, endTime);
         }
     }
@@ -890,6 +917,9 @@
 
             final UserUsageStatsService service =
                     getUserDataAndInitializeIfNeededLocked(userId, System.currentTimeMillis());
+            if (service == null) {
+                return null; // user was stopped or removed
+            }
             return service.queryEventStats(bucketType, beginTime, endTime);
         }
     }
@@ -907,6 +937,9 @@
 
             final UserUsageStatsService service =
                     getUserDataAndInitializeIfNeededLocked(userId, System.currentTimeMillis());
+            if (service == null) {
+                return null; // user was stopped or removed
+            }
             return service.queryEvents(beginTime, endTime, shouldObfuscateInstantApps);
         }
     }
@@ -924,6 +957,9 @@
 
             final UserUsageStatsService service =
                     getUserDataAndInitializeIfNeededLocked(userId, System.currentTimeMillis());
+            if (service == null) {
+                return null; // user was stopped or removed
+            }
             return service.queryEventsForPackage(beginTime, endTime, packageName, includeTaskRoot);
         }
     }
@@ -945,7 +981,9 @@
                 continue;
             }
             UserUsageStatsService service = mUserState.get(userId);
-            service.persistActiveStats();
+            if (service != null) {
+                service.persistActiveStats();
+            }
             mAppStandby.flushToDisk(userId);
         }
         mAppStandby.flushDurationsToDisk();
@@ -976,7 +1014,7 @@
                         pw.println("Flushed stats to disk");
                         return;
                     } else if ("is-app-standby-enabled".equals(arg)) {
-                        pw.println(mAppStandby.mAppIdleEnabled);
+                        pw.println(mAppStandby.isAppIdleEnabled());
                         return;
                     } else if ("apptimelimit".equals(arg)) {
                         if (i + 1 >= args.length) {
@@ -1113,7 +1151,15 @@
                     flushToDisk();
                     break;
                 case MSG_UNLOCKED_USER:
-                    onUserUnlocked(msg.arg1);
+                    try {
+                        onUserUnlocked(msg.arg1);
+                    } catch (Exception e) {
+                        if (mUserManager.isUserUnlocked(msg.arg1)) {
+                            throw e; // rethrow exception - user is unlocked
+                        } else {
+                            Slog.w(TAG, "Attempted to unlock stopped or removed user " + msg.arg1);
+                        }
+                    }
                     break;
                 case MSG_REMOVE_USER:
                     onUserRemoved(msg.arg1);
@@ -1687,10 +1733,13 @@
         public void registerAppUsageLimitObserver(int observerId, String[] packages,
                 long timeLimitMs, long timeUsedMs, PendingIntent callbackIntent,
                 String callingPackage) {
+            final int callingUid = Binder.getCallingUid();
+            final DevicePolicyManagerInternal dpmInternal = getDpmInternal();
             if (!hasPermissions(callingPackage,
-                    Manifest.permission.SUSPEND_APPS, Manifest.permission.OBSERVE_APP_USAGE)) {
-                throw new SecurityException("Caller doesn't have both SUSPEND_APPS and "
-                        + "OBSERVE_APP_USAGE permissions");
+                    Manifest.permission.SUSPEND_APPS, Manifest.permission.OBSERVE_APP_USAGE)
+                    && (dpmInternal != null && !dpmInternal.isActiveSupervisionApp(callingUid))) {
+                throw new SecurityException("Caller must be the active supervision app or "
+                        + "it must have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions");
             }
 
             if (packages == null || packages.length == 0) {
@@ -1699,7 +1748,6 @@
             if (callbackIntent == null && timeUsedMs < timeLimitMs) {
                 throw new NullPointerException("callbackIntent can't be null");
             }
-            final int callingUid = Binder.getCallingUid();
             final int userId = UserHandle.getUserId(callingUid);
             final long token = Binder.clearCallingIdentity();
             try {
@@ -1712,13 +1760,15 @@
 
         @Override
         public void unregisterAppUsageLimitObserver(int observerId, String callingPackage) {
+            final int callingUid = Binder.getCallingUid();
+            final DevicePolicyManagerInternal dpmInternal = getDpmInternal();
             if (!hasPermissions(callingPackage,
-                    Manifest.permission.SUSPEND_APPS, Manifest.permission.OBSERVE_APP_USAGE)) {
-                throw new SecurityException("Caller doesn't have both SUSPEND_APPS and "
-                        + "OBSERVE_APP_USAGE permissions");
+                    Manifest.permission.SUSPEND_APPS, Manifest.permission.OBSERVE_APP_USAGE)
+                    && (dpmInternal != null && !dpmInternal.isActiveSupervisionApp(callingUid))) {
+                throw new SecurityException("Caller must be the active supervision app or "
+                        + "it must have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions");
             }
 
-            final int callingUid = Binder.getCallingUid();
             final int userId = UserHandle.getUserId(callingUid);
             final long token = Binder.clearCallingIdentity();
             try {
@@ -1986,6 +2036,9 @@
                 if (user == UserHandle.USER_SYSTEM) {
                     final UserUsageStatsService userStats = getUserDataAndInitializeIfNeededLocked(
                             user, System.currentTimeMillis());
+                    if (userStats == null) {
+                        return null; // user was stopped or removed
+                    }
                     return userStats.getBackupPayload(key);
                 } else {
                     return null;
@@ -2004,6 +2057,9 @@
                 if (user == UserHandle.USER_SYSTEM) {
                     final UserUsageStatsService userStats = getUserDataAndInitializeIfNeededLocked(
                             user, System.currentTimeMillis());
+                    if (userStats == null) {
+                        return; // user was stopped or removed
+                    }
                     userStats.applyRestoredPayload(key, payload);
                 }
             }
diff --git a/services/usb/java/com/android/server/usb/UsbHostManager.java b/services/usb/java/com/android/server/usb/UsbHostManager.java
index e899dff..047fcec 100644
--- a/services/usb/java/com/android/server/usb/UsbHostManager.java
+++ b/services/usb/java/com/android/server/usb/UsbHostManager.java
@@ -386,7 +386,7 @@
                 return false;
             }
 
-            UsbDevice.Builder newDeviceBuilder = parser.toAndroidUsbDevice();
+            UsbDevice.Builder newDeviceBuilder = parser.toAndroidUsbDeviceBuilder();
             if (newDeviceBuilder == null) {
                 Slog.e(TAG, "Couldn't create UsbDevice object.");
                 // Tracking
diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbDescriptorParser.java b/services/usb/java/com/android/server/usb/descriptors/UsbDescriptorParser.java
index 6ffbd43..8e7babb 100644
--- a/services/usb/java/com/android/server/usb/descriptors/UsbDescriptorParser.java
+++ b/services/usb/java/com/android/server/usb/descriptors/UsbDescriptorParser.java
@@ -309,17 +309,17 @@
     /**
      * @hide
      */
-    public UsbDevice.Builder toAndroidUsbDevice() {
+    public UsbDevice.Builder toAndroidUsbDeviceBuilder() {
         if (mDeviceDescriptor == null) {
             Log.e(TAG, "toAndroidUsbDevice() ERROR - No Device Descriptor");
             return null;
         }
 
-        UsbDevice.Builder device = mDeviceDescriptor.toAndroid(this);
-        if (device == null) {
+        UsbDevice.Builder builder = mDeviceDescriptor.toAndroid(this);
+        if (builder == null) {
             Log.e(TAG, "toAndroidUsbDevice() ERROR Creating Device");
         }
-        return device;
+        return builder;
     }
 
     /**
@@ -524,6 +524,37 @@
     /**
      * @hide
      */
+    public boolean hasAudioTerminal(int subType) {
+        for (UsbDescriptor descriptor : mDescriptors) {
+            if (descriptor instanceof UsbACInterface) {
+                if (((UsbACInterface) descriptor).getSubclass()
+                        == UsbDescriptor.AUDIO_AUDIOCONTROL
+                        && ((UsbACInterface) descriptor).getSubtype()
+                        == subType) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * @hide
+     */
+    public boolean hasAudioPlayback() {
+        return hasAudioTerminal(UsbACInterface.ACI_OUTPUT_TERMINAL);
+    }
+
+    /**
+     * @hide
+     */
+    public boolean hasAudioCapture() {
+        return hasAudioTerminal(UsbACInterface.ACI_INPUT_TERMINAL);
+    }
+
+    /**
+     * @hide
+     */
     public boolean hasHIDInterface() {
         ArrayList<UsbDescriptor> descriptors =
                 getInterfaceDescriptorsForClass(UsbDescriptor.CLASSID_HID);
diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbDeviceDescriptor.java b/services/usb/java/com/android/server/usb/descriptors/UsbDeviceDescriptor.java
index e6e10fe..9739243 100644
--- a/services/usb/java/com/android/server/usb/descriptors/UsbDeviceDescriptor.java
+++ b/services/usb/java/com/android/server/usb/descriptors/UsbDeviceDescriptor.java
@@ -156,11 +156,11 @@
         for (int index = 0; index < mConfigDescriptors.size(); index++) {
             configs[index] = mConfigDescriptors.get(index).toAndroid(parser);
         }
-        UsbDevice.Builder device = new UsbDevice.Builder(parser.getDeviceAddr(), mVendorID,
-                mProductID, mDevClass, mDevSubClass, mProtocol, mfgName, prodName, versionString,
-                configs, serialStr);
 
-        return device;
+        return new UsbDevice.Builder(parser.getDeviceAddr(), mVendorID,
+                mProductID, mDevClass, mDevSubClass, mProtocol, mfgName, prodName, versionString,
+                configs, serialStr, parser.hasAudioPlayback(), parser.hasAudioCapture(),
+                parser.hasMIDIInterface());
     }
 
     @Override
diff --git a/services/wifi/Android.bp b/services/wifi/Android.bp
index 3c916a6..608fc2c 100644
--- a/services/wifi/Android.bp
+++ b/services/wifi/Android.bp
@@ -5,6 +5,9 @@
         "java/**/*.java",
         "java/**/*.aidl",
     ],
+    aidl: {
+        local_include_dirs: ["java"]
+    },
     libs: [
         "services.net",
     ],
diff --git a/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl b/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl
index eadc726..3af4666 100644
--- a/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl
+++ b/services/wifi/java/android/net/wifi/IWifiStackConnector.aidl
@@ -15,8 +15,9 @@
  */
 package android.net.wifi;
 
+import android.net.wifi.WifiApiServiceInfo;
+
 /** @hide */
 interface IWifiStackConnector {
-     IBinder retrieveApiServiceImpl(String serviceName);
-     boolean startApiService(String serviceName);
+     List<WifiApiServiceInfo> getWifiApiServiceInfos();
 }
diff --git a/services/wifi/java/android/net/wifi/WifiApiServiceInfo.aidl b/services/wifi/java/android/net/wifi/WifiApiServiceInfo.aidl
new file mode 100644
index 0000000..45e4c69
--- /dev/null
+++ b/services/wifi/java/android/net/wifi/WifiApiServiceInfo.aidl
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2019 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.net.wifi;
+
+/** @hide */
+parcelable WifiApiServiceInfo {
+    String name;
+    IBinder binder;
+}
diff --git a/services/wifi/java/android/net/wifi/WifiStackClient.java b/services/wifi/java/android/net/wifi/WifiStackClient.java
index 64af7a8..dcdfbc5 100644
--- a/services/wifi/java/android/net/wifi/WifiStackClient.java
+++ b/services/wifi/java/android/net/wifi/WifiStackClient.java
@@ -21,12 +21,13 @@
 import android.annotation.NonNull;
 import android.content.Context;
 import android.net.ConnectivityModuleConnector;
-import android.os.HandlerThread;
 import android.os.IBinder;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.util.Log;
 
+import java.util.List;
+
 /**
  * Service used to communicate with the wifi stack, which could be running in a separate
  * module.
@@ -56,21 +57,23 @@
         @Override
         public void onModuleServiceConnected(IBinder service) {
             Log.i(TAG, "Wifi stack connected");
+            registerWifiStackService(service);
 
-            // spin up a new thread to not block system_server main thread
-            HandlerThread thread = new HandlerThread("InitWifiServicesThread");
-            thread.start();
-            thread.getThreadHandler().post(() -> {
-                registerWifiStackService(service);
-                IWifiStackConnector connector = IWifiStackConnector.Stub.asInterface(service);
-                registerApiServiceAndStart(connector, Context.WIFI_SCANNING_SERVICE);
-                registerApiServiceAndStart(connector, Context.WIFI_SERVICE);
-                registerApiServiceAndStart(connector, Context.WIFI_P2P_SERVICE);
-                registerApiServiceAndStart(connector, Context.WIFI_AWARE_SERVICE);
-                registerApiServiceAndStart(connector, Context.WIFI_RTT_RANGING_SERVICE);
+            IWifiStackConnector connector = IWifiStackConnector.Stub.asInterface(service);
 
-                thread.quitSafely();
-            });
+            List<WifiApiServiceInfo> wifiApiServiceInfos;
+            try {
+                wifiApiServiceInfos = connector.getWifiApiServiceInfos();
+            } catch (RemoteException e) {
+                throw new RuntimeException("Failed to getWifiApiServiceInfos()", e);
+            }
+
+            for (WifiApiServiceInfo wifiApiServiceInfo : wifiApiServiceInfos) {
+                String serviceName = wifiApiServiceInfo.name;
+                IBinder binder = wifiApiServiceInfo.binder;
+                Log.i(TAG, "Registering " + serviceName);
+                ServiceManager.addService(serviceName, binder);
+            }
         }
     }
 
@@ -81,32 +84,6 @@
         Log.i(TAG, "Wifi stack service registered");
     }
 
-    private void registerApiServiceAndStart(
-            IWifiStackConnector stackConnector, String serviceName) {
-        IBinder service = null;
-        try {
-            service = stackConnector.retrieveApiServiceImpl(serviceName);
-        } catch (RemoteException e) {
-            throw new RuntimeException("Failed to retrieve service impl " + serviceName, e);
-        }
-        if (service == null) {
-            Log.i(TAG, "Service " + serviceName + " not available");
-            return;
-        }
-        Log.i(TAG, "Registering " + serviceName);
-        ServiceManager.addService(serviceName, service);
-
-        boolean success = false;
-        try {
-            success = stackConnector.startApiService(serviceName);
-        } catch (RemoteException e) {
-            throw new RuntimeException("Failed to start service " + serviceName, e);
-        }
-        if (!success) {
-            throw new RuntimeException("Service " + serviceName + " start failed");
-        }
-    }
-
     /**
      * Start the wifi stack. Should be called only once on device startup.
      *
diff --git a/startop/view_compiler/Android.bp b/startop/view_compiler/Android.bp
index 4f6524e..c380d29 100644
--- a/startop/view_compiler/Android.bp
+++ b/startop/view_compiler/Android.bp
@@ -25,6 +25,7 @@
         "slicer",
     ],
     static_libs: [
+        "libcutils",
         "libtinyxml2",
         "liblog",
         "libutils",
diff --git a/startop/view_compiler/dex_builder.cc b/startop/view_compiler/dex_builder.cc
index 499c42e..48b44d0 100644
--- a/startop/view_compiler/dex_builder.cc
+++ b/startop/view_compiler/dex_builder.cc
@@ -161,7 +161,7 @@
 
   MethodBuilder method{cbuilder.CreateMethod("foo", Prototype{TypeDescriptor::Int(), string_type})};
 
-  Value result = method.MakeRegister();
+  LiveRegister result = method.AllocRegister();
 
   MethodDeclData string_length =
       dex_file.GetOrDeclareMethod(string_type, "length", Prototype{TypeDescriptor::Int()});
@@ -314,7 +314,7 @@
   CHECK(decl_->prototype != nullptr);
   size_t const num_args =
       decl_->prototype->param_types != nullptr ? decl_->prototype->param_types->types.size() : 0;
-  code->registers = num_registers_ + num_args + kMaxScratchRegisters;
+  code->registers = NumRegisters() + num_args + kMaxScratchRegisters;
   code->ins_count = num_args;
   EncodeInstructions();
   code->instructions = slicer::ArrayView<const ::dex::u2>(buffer_.data(), buffer_.size());
@@ -327,7 +327,20 @@
   return method;
 }
 
-Value MethodBuilder::MakeRegister() { return Value::Local(num_registers_++); }
+LiveRegister MethodBuilder::AllocRegister() {
+  // Find a free register
+  for (size_t i = 0; i < register_liveness_.size(); ++i) {
+    if (!register_liveness_[i]) {
+      register_liveness_[i] = true;
+      return LiveRegister{&register_liveness_, i};
+    }
+  }
+
+  // If we get here, all the registers are in use, so we have to allocate a new
+  // one.
+  register_liveness_.push_back(true);
+  return LiveRegister{&register_liveness_, register_liveness_.size() - 1};
+}
 
 Value MethodBuilder::MakeLabel() {
   labels_.push_back({});
@@ -600,7 +613,7 @@
   if (value.is_register()) {
     return value.value();
   } else if (value.is_parameter()) {
-    return value.value() + num_registers_ + kMaxScratchRegisters;
+    return value.value() + NumRegisters() + kMaxScratchRegisters;
   }
   CHECK(false && "Must be either a parameter or a register");
   return 0;
diff --git a/startop/view_compiler/dex_builder.h b/startop/view_compiler/dex_builder.h
index 292d659..3924e77 100644
--- a/startop/view_compiler/dex_builder.h
+++ b/startop/view_compiler/dex_builder.h
@@ -140,6 +140,29 @@
   constexpr Value(size_t value, Kind kind) : value_{value}, kind_{kind} {}
 };
 
+// Represents an allocated register returned by MethodBuilder::AllocRegister
+class LiveRegister {
+  friend class MethodBuilder;
+
+ public:
+  LiveRegister(LiveRegister&& other) : liveness_{other.liveness_}, index_{other.index_} {
+    other.index_ = {};
+  };
+  ~LiveRegister() {
+    if (index_.has_value()) {
+      (*liveness_)[*index_] = false;
+    }
+  };
+
+  operator const Value() const { return Value::Local(*index_); }
+
+ private:
+  LiveRegister(std::vector<bool>* liveness, size_t index) : liveness_{liveness}, index_{index} {}
+
+  std::vector<bool>* const liveness_;
+  std::optional<size_t> index_;
+};
+
 // A virtual instruction. We convert these to real instructions in MethodBuilder::Encode.
 // Virtual instructions are needed to keep track of information that is not known until all of the
 // code is generated. This information includes things like how many local registers are created and
@@ -178,7 +201,8 @@
   }
   // For most instructions, which take some number of arguments and have an optional return value.
   template <typename... T>
-  static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest, T... args) {
+  static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest,
+                                       const T&... args) {
     return Instruction{opcode, /*index_argument=*/0, /*result_is_object=*/false, dest, args...};
   }
 
@@ -199,14 +223,14 @@
   template <typename... T>
   static inline Instruction InvokeVirtualObject(size_t index_argument,
                                                 std::optional<const Value> dest, Value this_arg,
-                                                T... args) {
+                                                const T&... args) {
     return Instruction{
         Op::kInvokeVirtual, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
   }
   // For direct calls (basically, constructors).
   template <typename... T>
   static inline Instruction InvokeDirect(size_t index_argument, std::optional<const Value> dest,
-                                         Value this_arg, T... args) {
+                                         Value this_arg, const T&... args) {
     return Instruction{
         Op::kInvokeDirect, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
   }
@@ -234,7 +258,7 @@
   // For static calls.
   template <typename... T>
   static inline Instruction InvokeInterface(size_t index_argument, std::optional<const Value> dest,
-                                            T... args) {
+                                            const T&... args) {
     return Instruction{
         Op::kInvokeInterface, index_argument, /*result_is_object=*/false, dest, args...};
   }
@@ -277,7 +301,7 @@
 
   template <typename... T>
   inline Instruction(Op opcode, size_t index_argument, bool result_is_object,
-                               std::optional<const Value> dest, T... args)
+                     std::optional<const Value> dest, const T&... args)
       : opcode_{opcode},
         index_argument_{index_argument},
         result_is_object_{result_is_object},
@@ -309,10 +333,8 @@
   // Encode the method into DEX format.
   ir::EncodedMethod* Encode();
 
-  // Create a new register to be used to storing values. Note that these are not SSA registers, like
-  // might be expected in similar code generators. This does no liveness tracking or anything, so
-  // it's up to the caller to reuse registers as appropriate.
-  Value MakeRegister();
+  // Create a new register to be used to storing values.
+  LiveRegister AllocRegister();
 
   Value MakeLabel();
 
@@ -329,7 +351,7 @@
   void BuildConst4(Value target, int value);
   void BuildConstString(Value target, const std::string& value);
   template <typename... T>
-  void BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args);
+  void BuildNew(Value target, TypeDescriptor type, Prototype constructor, const T&... args);
 
   // TODO: add builders for more instructions
 
@@ -427,7 +449,7 @@
     static_assert(num_regs <= kMaxScratchRegisters);
     std::array<Value, num_regs> regs;
     for (size_t i = 0; i < num_regs; ++i) {
-      regs[i] = std::move(Value::Local(num_registers_ + i));
+      regs[i] = std::move(Value::Local(NumRegisters() + i));
     }
     return regs;
   }
@@ -457,8 +479,9 @@
   // around to make legal DEX code.
   static constexpr size_t kMaxScratchRegisters = 5;
 
-  // How many registers we've allocated
-  size_t num_registers_{0};
+  size_t NumRegisters() const {
+    return register_liveness_.size();
+  }
 
   // Stores information needed to back-patch a label once it is bound. We need to know the start of
   // the instruction that refers to the label, and the offset to where the actual label value should
@@ -478,6 +501,8 @@
   // During encoding, keep track of the largest number of arguments needed, so we can use it for our
   // outs count
   size_t max_args_{0};
+
+  std::vector<bool> register_liveness_;
 };
 
 // A helper to build class definitions.
@@ -576,7 +601,8 @@
 };
 
 template <typename... T>
-void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args) {
+void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor,
+                             const T&... args) {
   MethodDeclData constructor_data{dex_->GetOrDeclareMethod(type, "<init>", constructor)};
   // allocate the object
   ir::Type* type_def = dex_->GetOrAddType(type.descriptor());
diff --git a/startop/view_compiler/dex_layout_compiler.cc b/startop/view_compiler/dex_layout_compiler.cc
index 8febfb7..cb820f8 100644
--- a/startop/view_compiler/dex_layout_compiler.cc
+++ b/startop/view_compiler/dex_layout_compiler.cc
@@ -22,76 +22,94 @@
 namespace startop {
 
 using android::base::StringPrintf;
+using dex::Instruction;
+using dex::LiveRegister;
+using dex::Prototype;
+using dex::TypeDescriptor;
+using dex::Value;
+
+namespace {
+// TODO: these are a bunch of static initializers, which we should avoid. See if
+// we can make them constexpr.
+const TypeDescriptor kAttributeSet = TypeDescriptor::FromClassname("android.util.AttributeSet");
+const TypeDescriptor kContext = TypeDescriptor::FromClassname("android.content.Context");
+const TypeDescriptor kLayoutInflater = TypeDescriptor::FromClassname("android.view.LayoutInflater");
+const TypeDescriptor kResources = TypeDescriptor::FromClassname("android.content.res.Resources");
+const TypeDescriptor kString = TypeDescriptor::FromClassname("java.lang.String");
+const TypeDescriptor kView = TypeDescriptor::FromClassname("android.view.View");
+const TypeDescriptor kViewGroup = TypeDescriptor::FromClassname("android.view.ViewGroup");
+const TypeDescriptor kXmlResourceParser =
+    TypeDescriptor::FromClassname("android.content.res.XmlResourceParser");
+}  // namespace
 
 DexViewBuilder::DexViewBuilder(dex::MethodBuilder* method)
     : method_{method},
-      context_{dex::Value::Parameter(0)},
-      resid_{dex::Value::Parameter(1)},
-      inflater_{method->MakeRegister()},
-      xml_{method->MakeRegister()},
-      attrs_{method->MakeRegister()},
-      classname_tmp_{method->MakeRegister()},
-      xml_next_{method->dex_file()->GetOrDeclareMethod(
-          dex::TypeDescriptor::FromClassname("android.content.res.XmlResourceParser"), "next",
-          dex::Prototype{dex::TypeDescriptor::Int()})},
+      context_{Value::Parameter(0)},
+      resid_{Value::Parameter(1)},
+      inflater_{method->AllocRegister()},
+      xml_{method->AllocRegister()},
+      attrs_{method->AllocRegister()},
+      classname_tmp_{method->AllocRegister()},
+      xml_next_{method->dex_file()->GetOrDeclareMethod(kXmlResourceParser, "next",
+                                                       Prototype{TypeDescriptor::Int()})},
       try_create_view_{method->dex_file()->GetOrDeclareMethod(
-          dex::TypeDescriptor::FromClassname("android.view.LayoutInflater"), "tryCreateView",
-          dex::Prototype{dex::TypeDescriptor::FromClassname("android.view.View"),
-                         dex::TypeDescriptor::FromClassname("android.view.View"),
-                         dex::TypeDescriptor::FromClassname("java.lang.String"),
-                         dex::TypeDescriptor::FromClassname("android.content.Context"),
-                         dex::TypeDescriptor::FromClassname("android.util.AttributeSet")})},
+          kLayoutInflater, "tryCreateView",
+          Prototype{kView, kView, kString, kContext, kAttributeSet})},
       generate_layout_params_{method->dex_file()->GetOrDeclareMethod(
-          dex::TypeDescriptor::FromClassname("android.view.ViewGroup"), "generateLayoutParams",
-          dex::Prototype{dex::TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams"),
-                         dex::TypeDescriptor::FromClassname("android.util.AttributeSet")})},
+          kViewGroup, "generateLayoutParams",
+          Prototype{TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams"),
+                    kAttributeSet})},
       add_view_{method->dex_file()->GetOrDeclareMethod(
-          dex::TypeDescriptor::FromClassname("android.view.ViewGroup"), "addView",
-          dex::Prototype{
-              dex::TypeDescriptor::Void(),
-              dex::TypeDescriptor::FromClassname("android.view.View"),
-              dex::TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams")})},
-      // The register stack starts with one register, which will be null for the root view.
-      register_stack_{{method->MakeRegister()}} {}
+          kViewGroup, "addView",
+          Prototype{TypeDescriptor::Void(),
+                    kView,
+                    TypeDescriptor::FromClassname("android.view.ViewGroup$LayoutParams")})} {}
+
+void DexViewBuilder::BuildGetLayoutInflater(Value dest) {
+  // dest = LayoutInflater.from(context);
+  auto layout_inflater_from = method_->dex_file()->GetOrDeclareMethod(
+      kLayoutInflater, "from", Prototype{kLayoutInflater, kContext});
+  method_->AddInstruction(Instruction::InvokeStaticObject(layout_inflater_from.id, dest, context_));
+}
+
+void DexViewBuilder::BuildGetResources(Value dest) {
+  // dest = context.getResources();
+  auto get_resources =
+      method_->dex_file()->GetOrDeclareMethod(kContext, "getResources", Prototype{kResources});
+  method_->AddInstruction(Instruction::InvokeVirtualObject(get_resources.id, dest, context_));
+}
+
+void DexViewBuilder::BuildGetLayoutResource(Value dest, Value resources, Value resid) {
+  // dest = resources.getLayout(resid);
+  auto get_layout = method_->dex_file()->GetOrDeclareMethod(
+      kResources, "getLayout", Prototype{kXmlResourceParser, TypeDescriptor::Int()});
+  method_->AddInstruction(Instruction::InvokeVirtualObject(get_layout.id, dest, resources, resid));
+}
+
+void DexViewBuilder::BuildLayoutResourceToAttributeSet(dex::Value dest,
+                                                       dex::Value layout_resource) {
+  // dest = Xml.asAttributeSet(layout_resource);
+  auto as_attribute_set = method_->dex_file()->GetOrDeclareMethod(
+      TypeDescriptor::FromClassname("android.util.Xml"),
+      "asAttributeSet",
+      Prototype{kAttributeSet, TypeDescriptor::FromClassname("org.xmlpull.v1.XmlPullParser")});
+  method_->AddInstruction(
+      Instruction::InvokeStaticObject(as_attribute_set.id, dest, layout_resource));
+}
+
+void DexViewBuilder::BuildXmlNext() {
+  // xml_.next();
+  method_->AddInstruction(Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+}
 
 void DexViewBuilder::Start() {
-  dex::DexBuilder* const dex = method_->dex_file();
+  BuildGetLayoutInflater(/*dest=*/inflater_);
+  BuildGetResources(/*dest=*/xml_);
+  BuildGetLayoutResource(/*dest=*/xml_, /*resources=*/xml_, resid_);
+  BuildLayoutResourceToAttributeSet(/*dest=*/attrs_, /*layout_resource=*/xml_);
 
-  // LayoutInflater inflater = LayoutInflater.from(context);
-  auto layout_inflater_from = dex->GetOrDeclareMethod(
-      dex::TypeDescriptor::FromClassname("android.view.LayoutInflater"),
-      "from",
-      dex::Prototype{dex::TypeDescriptor::FromClassname("android.view.LayoutInflater"),
-                     dex::TypeDescriptor::FromClassname("android.content.Context")});
-  method_->AddInstruction(
-      dex::Instruction::InvokeStaticObject(layout_inflater_from.id, /*dest=*/inflater_, context_));
-
-  // Resources res = context.getResources();
-  auto context_type = dex::TypeDescriptor::FromClassname("android.content.Context");
-  auto resources_type = dex::TypeDescriptor::FromClassname("android.content.res.Resources");
-  auto get_resources =
-      dex->GetOrDeclareMethod(context_type, "getResources", dex::Prototype{resources_type});
-  method_->AddInstruction(dex::Instruction::InvokeVirtualObject(get_resources.id, xml_, context_));
-
-  // XmlResourceParser xml = res.getLayout(resid);
-  auto xml_resource_parser_type =
-      dex::TypeDescriptor::FromClassname("android.content.res.XmlResourceParser");
-  auto get_layout =
-      dex->GetOrDeclareMethod(resources_type,
-                              "getLayout",
-                              dex::Prototype{xml_resource_parser_type, dex::TypeDescriptor::Int()});
-  method_->AddInstruction(dex::Instruction::InvokeVirtualObject(get_layout.id, xml_, xml_, resid_));
-
-  // AttributeSet attrs = Xml.asAttributeSet(xml);
-  auto as_attribute_set = dex->GetOrDeclareMethod(
-      dex::TypeDescriptor::FromClassname("android.util.Xml"),
-      "asAttributeSet",
-      dex::Prototype{dex::TypeDescriptor::FromClassname("android.util.AttributeSet"),
-                     dex::TypeDescriptor::FromClassname("org.xmlpull.v1.XmlPullParser")});
-  method_->AddInstruction(dex::Instruction::InvokeStaticObject(as_attribute_set.id, attrs_, xml_));
-
-  // xml.next(); // start document
-  method_->AddInstruction(dex::Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+  // Advance past start document tag
+  BuildXmlNext();
 }
 
 void DexViewBuilder::Finish() {}
@@ -107,58 +125,57 @@
 }
 }  // namespace
 
+void DexViewBuilder::BuildTryCreateView(Value dest, Value parent, Value classname) {
+  // dest = inflater_.tryCreateView(parent, classname, context_, attrs_);
+  method_->AddInstruction(Instruction::InvokeVirtualObject(
+      try_create_view_.id, dest, inflater_, parent, classname, context_, attrs_));
+}
+
 void DexViewBuilder::StartView(const std::string& name, bool is_viewgroup) {
   bool const is_root_view = view_stack_.empty();
 
-  // xml.next(); // start tag
-  method_->AddInstruction(dex::Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+  // Advance to start tag
+  BuildXmlNext();
 
-  dex::Value view = AcquireRegister();
+  LiveRegister view = AcquireRegister();
   // try to create the view using the factories
   method_->BuildConstString(classname_tmp_,
                             name);  // TODO: the need to fully qualify the classname
   if (is_root_view) {
-    dex::Value null = AcquireRegister();
+    LiveRegister null = AcquireRegister();
     method_->BuildConst4(null, 0);
-    method_->AddInstruction(dex::Instruction::InvokeVirtualObject(
-        try_create_view_.id, view, inflater_, null, classname_tmp_, context_, attrs_));
-    ReleaseRegister();
+    BuildTryCreateView(/*dest=*/view, /*parent=*/null, classname_tmp_);
   } else {
-    method_->AddInstruction(dex::Instruction::InvokeVirtualObject(
-        try_create_view_.id, view, inflater_, GetCurrentView(), classname_tmp_, context_, attrs_));
+    BuildTryCreateView(/*dest=*/view, /*parent=*/GetCurrentView(), classname_tmp_);
   }
   auto label = method_->MakeLabel();
   // branch if not null
   method_->AddInstruction(
-      dex::Instruction::OpWithArgs(dex::Instruction::Op::kBranchNEqz, /*dest=*/{}, view, label));
+      Instruction::OpWithArgs(Instruction::Op::kBranchNEqz, /*dest=*/{}, view, label));
 
   // If null, create the class directly.
   method_->BuildNew(view,
-                    dex::TypeDescriptor::FromClassname(ResolveName(name)),
-                    dex::Prototype{dex::TypeDescriptor::Void(),
-                                   dex::TypeDescriptor::FromClassname("android.content.Context"),
-                                   dex::TypeDescriptor::FromClassname("android.util.AttributeSet")},
+                    TypeDescriptor::FromClassname(ResolveName(name)),
+                    Prototype{TypeDescriptor::Void(), kContext, kAttributeSet},
                     context_,
                     attrs_);
 
-  method_->AddInstruction(
-      dex::Instruction::OpWithArgs(dex::Instruction::Op::kBindLabel, /*dest=*/{}, label));
+  method_->AddInstruction(Instruction::OpWithArgs(Instruction::Op::kBindLabel, /*dest=*/{}, label));
 
   if (is_viewgroup) {
     // Cast to a ViewGroup so we can add children later.
-    const ir::Type* view_group_def = method_->dex_file()->GetOrAddType(
-        dex::TypeDescriptor::FromClassname("android.view.ViewGroup").descriptor());
-    method_->AddInstruction(dex::Instruction::Cast(view, dex::Value::Type(view_group_def->orig_index)));
+    const ir::Type* view_group_def = method_->dex_file()->GetOrAddType(kViewGroup.descriptor());
+    method_->AddInstruction(Instruction::Cast(view, Value::Type(view_group_def->orig_index)));
   }
 
   if (!is_root_view) {
     // layout_params = parent.generateLayoutParams(attrs);
-    dex::Value layout_params{AcquireRegister()};
-    method_->AddInstruction(dex::Instruction::InvokeVirtualObject(
+    LiveRegister layout_params{AcquireRegister()};
+    method_->AddInstruction(Instruction::InvokeVirtualObject(
         generate_layout_params_.id, layout_params, GetCurrentView(), attrs_));
-    view_stack_.push_back({view, layout_params});
+    view_stack_.push_back({std::move(view), std::move(layout_params)});
   } else {
-    view_stack_.push_back({view, {}});
+    view_stack_.push_back({std::move(view), {}});
   }
 }
 
@@ -167,40 +184,24 @@
     method_->BuildReturn(GetCurrentView(), /*is_object=*/true);
   } else {
     // parent.add(view, layout_params)
-    method_->AddInstruction(dex::Instruction::InvokeVirtual(
+    method_->AddInstruction(Instruction::InvokeVirtual(
         add_view_.id, /*dest=*/{}, GetParentView(), GetCurrentView(), GetCurrentLayoutParams()));
     // xml.next(); // end tag
-    method_->AddInstruction(dex::Instruction::InvokeInterface(xml_next_.id, {}, xml_));
+    method_->AddInstruction(Instruction::InvokeInterface(xml_next_.id, {}, xml_));
   }
   PopViewStack();
 }
 
-dex::Value DexViewBuilder::AcquireRegister() {
-  top_register_++;
-  if (register_stack_.size() == top_register_) {
-    register_stack_.push_back(method_->MakeRegister());
-  }
-  return register_stack_[top_register_];
-}
+LiveRegister DexViewBuilder::AcquireRegister() { return method_->AllocRegister(); }
 
-void DexViewBuilder::ReleaseRegister() { top_register_--; }
-
-dex::Value DexViewBuilder::GetCurrentView() const { return view_stack_.back().view; }
-dex::Value DexViewBuilder::GetCurrentLayoutParams() const {
+Value DexViewBuilder::GetCurrentView() const { return view_stack_.back().view; }
+Value DexViewBuilder::GetCurrentLayoutParams() const {
   return view_stack_.back().layout_params.value();
 }
-dex::Value DexViewBuilder::GetParentView() const {
-  return view_stack_[view_stack_.size() - 2].view;
-}
+Value DexViewBuilder::GetParentView() const { return view_stack_[view_stack_.size() - 2].view; }
 
 void DexViewBuilder::PopViewStack() {
-  const auto& top = view_stack_.back();
-  // release the layout params if we have them
-  if (top.layout_params.has_value()) {
-    ReleaseRegister();
-  }
   // Unconditionally release the view register.
-  ReleaseRegister();
   view_stack_.pop_back();
 }
 
diff --git a/startop/view_compiler/dex_layout_compiler.h b/startop/view_compiler/dex_layout_compiler.h
index 170a1a6..a34ed1f 100644
--- a/startop/view_compiler/dex_layout_compiler.h
+++ b/startop/view_compiler/dex_layout_compiler.h
@@ -79,36 +79,41 @@
 
  private:
   // Accessors for the stack of views that are under construction.
-  dex::Value AcquireRegister();
-  void ReleaseRegister();
+  dex::LiveRegister AcquireRegister();
   dex::Value GetCurrentView() const;
   dex::Value GetCurrentLayoutParams() const;
   dex::Value GetParentView() const;
   void PopViewStack();
 
+  // Methods to simplify building different code fragments.
+  void BuildGetLayoutInflater(dex::Value dest);
+  void BuildGetResources(dex::Value dest);
+  void BuildGetLayoutResource(dex::Value dest, dex::Value resources, dex::Value resid);
+  void BuildLayoutResourceToAttributeSet(dex::Value dest, dex::Value layout_resource);
+  void BuildXmlNext();
+  void BuildTryCreateView(dex::Value dest, dex::Value parent, dex::Value classname);
+
   dex::MethodBuilder* method_;
 
-  // Registers used for code generation
+  // Parameters to the generated method
   dex::Value const context_;
   dex::Value const resid_;
-  const dex::Value inflater_;
-  const dex::Value xml_;
-  const dex::Value attrs_;
-  const dex::Value classname_tmp_;
+
+  // Registers used for code generation
+  const dex::LiveRegister inflater_;
+  const dex::LiveRegister xml_;
+  const dex::LiveRegister attrs_;
+  const dex::LiveRegister classname_tmp_;
 
   const dex::MethodDeclData xml_next_;
   const dex::MethodDeclData try_create_view_;
   const dex::MethodDeclData generate_layout_params_;
   const dex::MethodDeclData add_view_;
 
-  // used for keeping track of which registers are in use
-  size_t top_register_{0};
-  std::vector<dex::Value> register_stack_;
-
   // Keep track of the views currently in progress.
   struct ViewEntry {
-    dex::Value view;
-    std::optional<dex::Value> layout_params;
+    dex::LiveRegister view;
+    std::optional<dex::LiveRegister> layout_params;
   };
   std::vector<ViewEntry> view_stack_;
 };
diff --git a/startop/view_compiler/dex_testcase_generator.cc b/startop/view_compiler/dex_testcase_generator.cc
index 6dedf24..5dda59e 100644
--- a/startop/view_compiler/dex_testcase_generator.cc
+++ b/startop/view_compiler/dex_testcase_generator.cc
@@ -47,7 +47,7 @@
   // int return5() { return 5; }
   auto return5{cbuilder.CreateMethod("return5", Prototype{TypeDescriptor::Int()})};
   {
-    Value r{return5.MakeRegister()};
+    LiveRegister r{return5.AllocRegister()};
     return5.BuildConst4(r, 5);
     return5.BuildReturn(r);
   }
@@ -57,9 +57,9 @@
   auto integer_type{TypeDescriptor::FromClassname("java.lang.Integer")};
   auto returnInteger5{cbuilder.CreateMethod("returnInteger5", Prototype{integer_type})};
   [&](MethodBuilder& method) {
-    Value five{method.MakeRegister()};
+    LiveRegister five{method.AllocRegister()};
     method.BuildConst4(five, 5);
-    Value object{method.MakeRegister()};
+    LiveRegister object{method.AllocRegister()};
     method.BuildNew(
         object, integer_type, Prototype{TypeDescriptor::Void(), TypeDescriptor::Int()}, five);
     method.BuildReturn(object, /*is_object=*/true);
@@ -80,7 +80,7 @@
   auto returnStringLength{
       cbuilder.CreateMethod("returnStringLength", Prototype{TypeDescriptor::Int(), string_type})};
   {
-    Value result = returnStringLength.MakeRegister();
+    LiveRegister result = returnStringLength.AllocRegister();
     returnStringLength.AddInstruction(
         Instruction::InvokeVirtual(string_length.id, result, Value::Parameter(0)));
     returnStringLength.BuildReturn(result);
@@ -91,7 +91,7 @@
   MethodBuilder returnIfZero{cbuilder.CreateMethod(
       "returnIfZero", Prototype{TypeDescriptor::Int(), TypeDescriptor::Int()})};
   {
-    Value resultIfZero{returnIfZero.MakeRegister()};
+    LiveRegister resultIfZero{returnIfZero.AllocRegister()};
     Value else_target{returnIfZero.MakeLabel()};
     returnIfZero.AddInstruction(Instruction::OpWithArgs(
         Instruction::Op::kBranchEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -112,7 +112,7 @@
   MethodBuilder returnIfNotZero{cbuilder.CreateMethod(
       "returnIfNotZero", Prototype{TypeDescriptor::Int(), TypeDescriptor::Int()})};
   {
-    Value resultIfNotZero{returnIfNotZero.MakeRegister()};
+    LiveRegister resultIfNotZero{returnIfNotZero.AllocRegister()};
     Value else_target{returnIfNotZero.MakeLabel()};
     returnIfNotZero.AddInstruction(Instruction::OpWithArgs(
         Instruction::Op::kBranchNEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -148,8 +148,8 @@
   MethodBuilder backwardsBranch{
       cbuilder.CreateMethod("backwardsBranch", Prototype{TypeDescriptor::Int()})};
   [](MethodBuilder& method) {
-    Value zero = method.MakeRegister();
-    Value result = method.MakeRegister();
+    LiveRegister zero = method.AllocRegister();
+    LiveRegister result = method.AllocRegister();
     Value labelA = method.MakeLabel();
     Value labelB = method.MakeLabel();
     method.BuildConst4(zero, 0);
@@ -177,7 +177,7 @@
   // public static String returnNull() { return null; }
   MethodBuilder returnNull{cbuilder.CreateMethod("returnNull", Prototype{string_type})};
   [](MethodBuilder& method) {
-    Value zero = method.MakeRegister();
+    LiveRegister zero = method.AllocRegister();
     method.BuildConst4(zero, 0);
     method.BuildReturn(zero, /*is_object=*/true);
   }(returnNull);
@@ -188,7 +188,7 @@
   // public static String makeString() { return "Hello, World!"; }
   MethodBuilder makeString{cbuilder.CreateMethod("makeString", Prototype{string_type})};
   [](MethodBuilder& method) {
-    Value string = method.MakeRegister();
+    LiveRegister string = method.AllocRegister();
     method.BuildConstString(string, "Hello, World!");
     method.BuildReturn(string, /*is_object=*/true);
   }(makeString);
@@ -200,7 +200,7 @@
   MethodBuilder returnStringIfZeroAB{
       cbuilder.CreateMethod("returnStringIfZeroAB", Prototype{string_type, TypeDescriptor::Int()})};
   [&](MethodBuilder& method) {
-    Value resultIfZero{method.MakeRegister()};
+    LiveRegister resultIfZero{method.AllocRegister()};
     Value else_target{method.MakeLabel()};
     method.AddInstruction(Instruction::OpWithArgs(
         Instruction::Op::kBranchEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -220,7 +220,7 @@
   MethodBuilder returnStringIfZeroBA{
       cbuilder.CreateMethod("returnStringIfZeroBA", Prototype{string_type, TypeDescriptor::Int()})};
   [&](MethodBuilder& method) {
-    Value resultIfZero{method.MakeRegister()};
+    LiveRegister resultIfZero{method.AllocRegister()};
     Value else_target{method.MakeLabel()};
     method.AddInstruction(Instruction::OpWithArgs(
         Instruction::Op::kBranchEqz, /*dest=*/{}, Value::Parameter(0), else_target));
@@ -244,7 +244,7 @@
       cbuilder.CreateMethod("invokeStaticReturnObject",
                             Prototype{string_type, TypeDescriptor::Int(), TypeDescriptor::Int()})};
   [&](MethodBuilder& method) {
-    Value result{method.MakeRegister()};
+    LiveRegister result{method.AllocRegister()};
     MethodDeclData to_string{dex_file.GetOrDeclareMethod(
         TypeDescriptor::FromClassname("java.lang.Integer"),
         "toString",
@@ -260,7 +260,7 @@
   MethodBuilder invokeVirtualReturnObject{cbuilder.CreateMethod(
       "invokeVirtualReturnObject", Prototype{string_type, string_type, TypeDescriptor::Int()})};
   [&](MethodBuilder& method) {
-    Value result{method.MakeRegister()};
+    LiveRegister result{method.AllocRegister()};
     MethodDeclData substring{dex_file.GetOrDeclareMethod(
         string_type, "substring", Prototype{string_type, TypeDescriptor::Int()})};
     method.AddInstruction(Instruction::InvokeVirtualObject(
@@ -291,7 +291,7 @@
   [&](MethodBuilder& method) {
     const ir::FieldDecl* field =
         dex_file.GetOrAddField(test_class, "staticInteger", TypeDescriptor::Int());
-    Value result{method.MakeRegister()};
+    LiveRegister result{method.AllocRegister()};
     method.AddInstruction(Instruction::GetStaticField(field->orig_index, result));
     method.BuildReturn(result, /*is_object=*/false);
     method.Encode();
@@ -304,7 +304,7 @@
   [&](MethodBuilder& method) {
     const ir::FieldDecl* field =
         dex_file.GetOrAddField(test_class, "staticInteger", TypeDescriptor::Int());
-    Value number{method.MakeRegister()};
+    LiveRegister number{method.AllocRegister()};
     method.BuildConst4(number, 7);
     method.AddInstruction(Instruction::SetStaticField(field->orig_index, number));
     method.BuildReturn();
@@ -318,7 +318,7 @@
   [&](MethodBuilder& method) {
     const ir::FieldDecl* field =
         dex_file.GetOrAddField(test_class, "instanceField", TypeDescriptor::Int());
-    Value result{method.MakeRegister()};
+    LiveRegister result{method.AllocRegister()};
     method.AddInstruction(Instruction::GetField(field->orig_index, result, Value::Parameter(0)));
     method.BuildReturn(result, /*is_object=*/false);
     method.Encode();
@@ -331,7 +331,7 @@
   [&](MethodBuilder& method) {
     const ir::FieldDecl* field =
         dex_file.GetOrAddField(test_class, "instanceField", TypeDescriptor::Int());
-    Value number{method.MakeRegister()};
+    LiveRegister number{method.AllocRegister()};
     method.BuildConst4(number, 7);
     method.AddInstruction(Instruction::SetField(field->orig_index, Value::Parameter(0), number));
     method.BuildReturn();
diff --git a/telecomm/java/android/telecom/Call.java b/telecomm/java/android/telecom/Call.java
index 1822cee..5e71416 100644
--- a/telecomm/java/android/telecom/Call.java
+++ b/telecomm/java/android/telecom/Call.java
@@ -19,6 +19,7 @@
 import android.annotation.IntDef;
 import android.annotation.Nullable;
 import android.annotation.SystemApi;
+import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.net.Uri;
 import android.os.Build;
@@ -119,6 +120,20 @@
     public static final int STATE_PULLING_CALL = 11;
 
     /**
+     * The state of a call that is active with the network, but the audio from the call is
+     * being intercepted by an app on the local device. Telecom does not hold audio focus in this
+     * state, and the call will be invisible to the user except for a persistent notification.
+     */
+    public static final int STATE_AUDIO_PROCESSING = 12;
+
+    /**
+     * The state of a call that is being presented to the user after being in
+     * {@link #STATE_AUDIO_PROCESSING}. The call is still active with the network in this case, and
+     * Telecom will hold audio focus and play a ringtone if appropriate.
+     */
+    public static final int STATE_SIMULATED_RINGING = 13;
+
+    /**
      * The key to retrieve the optional {@code PhoneAccount}s Telecom can bundle with its Call
      * extras. Used to pass the phone accounts to display on the front end to the user in order to
      * select phone accounts to (for example) place a call.
@@ -1479,6 +1494,49 @@
     }
 
     /**
+     * Instructs Telecom to put the call into the background audio processing state.
+     *
+     * This method can be called either when the call is in {@link #STATE_RINGING} or
+     * {@link #STATE_ACTIVE}. After Telecom acknowledges the request by setting the call's state to
+     * {@link #STATE_AUDIO_PROCESSING}, your app may setup the audio paths with the audio stack in
+     * order to capture and play audio on the call stream.
+     *
+     * This method can only be called by the default dialer app.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    //@RequiresPermission(android.Manifest.permission.BACKGROUND_CALL_AUDIO)
+    public void enterBackgroundAudioProcessing() {
+        if (mState != STATE_ACTIVE && mState != STATE_RINGING) {
+            throw new IllegalStateException("Call must be active or ringing");
+        }
+        mInCallAdapter.enterBackgroundAudioProcessing(mTelecomCallId);
+    }
+
+    /**
+     * Instructs Telecom to come out of the background audio processing state requested by
+     * {@link #enterBackgroundAudioProcessing()} or from the call screening service.
+     *
+     * This method can only be called when the call is in {@link #STATE_AUDIO_PROCESSING}.
+     *
+     * @param shouldRing If true, Telecom will put the call into the
+     *                   {@link #STATE_SIMULATED_RINGING} state and notify other apps that there is
+     *                   a ringing call. Otherwise, the call will go into {@link #STATE_ACTIVE}
+     *                   immediately.
+     * @hide
+     */
+    @SystemApi
+    @TestApi
+    //@RequiresPermission(android.Manifest.permission.BACKGROUND_CALL_AUDIO)
+    public void exitBackgroundAudioProcessing(boolean shouldRing) {
+        if (mState != STATE_AUDIO_PROCESSING) {
+            throw new IllegalStateException("Call must in the audio processing state");
+        }
+        mInCallAdapter.exitBackgroundAudioProcessing(mTelecomCallId, shouldRing);
+    }
+
+    /**
      * Instructs this {@code Call} to play a dual-tone multi-frequency signaling (DTMF) tone.
      *
      * Any other currently playing DTMF tone in the specified call is immediately stopped.
diff --git a/telecomm/java/android/telecom/CallScreeningService.java b/telecomm/java/android/telecom/CallScreeningService.java
index 0e0406d..0d97567 100644
--- a/telecomm/java/android/telecom/CallScreeningService.java
+++ b/telecomm/java/android/telecom/CallScreeningService.java
@@ -16,9 +16,10 @@
 
 package android.telecom;
 
-import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.SdkConstant;
+import android.annotation.SystemApi;
+import android.annotation.TestApi;
 import android.app.Service;
 import android.content.ComponentName;
 import android.content.Intent;
@@ -33,9 +34,6 @@
 import com.android.internal.telecom.ICallScreeningAdapter;
 import com.android.internal.telecom.ICallScreeningService;
 
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
 /**
  * This service can be implemented by the default dialer (see
  * {@link TelecomManager#getDefaultDialerPackage()}) or a third party app to allow or disallow
@@ -75,7 +73,7 @@
  *
  * public void requestRole() {
  *     RoleManager roleManager = (RoleManager) getSystemService(ROLE_SERVICE);
- *     Intent intent = roleManager.createRequestRoleIntent("android.app.role.CALL_SCREENING");
+ *     Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING);
  *     startActivityForResult(intent, REQUEST_ID);
  * }
  *
@@ -140,23 +138,30 @@
         private final boolean mShouldSilenceCall;
         private final boolean mShouldSkipCallLog;
         private final boolean mShouldSkipNotification;
+        private final boolean mShouldScreenCallFurther;
 
         private CallResponse(
                 boolean shouldDisallowCall,
                 boolean shouldRejectCall,
                 boolean shouldSilenceCall,
                 boolean shouldSkipCallLog,
-                boolean shouldSkipNotification) {
+                boolean shouldSkipNotification,
+                boolean shouldScreenCallFurther) {
             if (!shouldDisallowCall
                     && (shouldRejectCall || shouldSkipCallLog || shouldSkipNotification)) {
                 throw new IllegalStateException("Invalid response state for allowed call.");
             }
 
+            if (shouldDisallowCall && shouldScreenCallFurther) {
+                throw new IllegalStateException("Invalid response state for allowed call.");
+            }
+
             mShouldDisallowCall = shouldDisallowCall;
             mShouldRejectCall = shouldRejectCall;
             mShouldSkipCallLog = shouldSkipCallLog;
             mShouldSkipNotification = shouldSkipNotification;
             mShouldSilenceCall = shouldSilenceCall;
+            mShouldScreenCallFurther = shouldScreenCallFurther;
         }
 
         /*
@@ -195,12 +200,22 @@
             return mShouldSkipNotification;
         }
 
+        /**
+         * @return Whether we should enter the {@link Call#STATE_AUDIO_PROCESSING} state to allow
+         * for further screening of the call.
+         * @hide
+         */
+        public boolean getShouldScreenCallFurther() {
+            return mShouldScreenCallFurther;
+        }
+
         public static class Builder {
             private boolean mShouldDisallowCall;
             private boolean mShouldRejectCall;
             private boolean mShouldSilenceCall;
             private boolean mShouldSkipCallLog;
             private boolean mShouldSkipNotification;
+            private boolean mShouldScreenCallFurther;
 
             /**
              * Sets whether the incoming call should be blocked.
@@ -256,13 +271,32 @@
                 return this;
             }
 
+            /**
+             * Sets whether to request background audio processing so that the in-call service can
+             * screen the call further. If set to {@code true}, {@link #setDisallowCall} should be
+             * called with {@code false}, and all other parameters in this builder will be ignored.
+             *
+             * This request will only be honored if the {@link CallScreeningService} shares the same
+             * uid as the default dialer app. Otherwise, the call will go through as usual.
+             *
+             * @param shouldScreenCallFurther Whether to request further call screening.
+             * @hide
+             */
+            @SystemApi
+            @TestApi
+            public Builder setShouldScreenCallFurther(boolean shouldScreenCallFurther) {
+                mShouldScreenCallFurther = shouldScreenCallFurther;
+                return this;
+            }
+
             public CallResponse build() {
                 return new CallResponse(
                         mShouldDisallowCall,
                         mShouldRejectCall,
                         mShouldSilenceCall,
                         mShouldSkipCallLog,
-                        mShouldSkipNotification);
+                        mShouldSkipNotification,
+                        mShouldScreenCallFurther);
             }
        }
     }
diff --git a/telecomm/java/android/telecom/Conference.java b/telecomm/java/android/telecom/Conference.java
index cd5fd97..d90f46d 100644
--- a/telecomm/java/android/telecom/Conference.java
+++ b/telecomm/java/android/telecom/Conference.java
@@ -24,6 +24,7 @@
 import android.os.Bundle;
 import android.os.SystemClock;
 import android.telecom.Connection.VideoProvider;
+import android.telephony.Annotation.RilRadioTechnology;
 import android.telephony.ServiceState;
 import android.telephony.TelephonyManager;
 import android.util.ArraySet;
@@ -687,7 +688,7 @@
      *
      * @hide
      */
-    public final void setCallRadioTech(@ServiceState.RilRadioTechnology int vrat) {
+    public final void setCallRadioTech(@RilRadioTechnology int vrat) {
         putExtra(TelecomManager.EXTRA_CALL_NETWORK_TYPE,
                 ServiceState.rilRadioTechnologyToNetworkType(vrat));
     }
@@ -700,7 +701,7 @@
      *
      * @hide
      */
-    public final @ServiceState.RilRadioTechnology int getCallRadioTech() {
+    public final @RilRadioTechnology int getCallRadioTech() {
         int voiceNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
         Bundle extras = getExtras();
         if (extras != null) {
diff --git a/telecomm/java/android/telecom/Connection.java b/telecomm/java/android/telecom/Connection.java
index 0983eea..525b938 100644
--- a/telecomm/java/android/telecom/Connection.java
+++ b/telecomm/java/android/telecom/Connection.java
@@ -34,6 +34,7 @@
 import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.os.SystemClock;
+import android.telephony.Annotation.RilRadioTechnology;
 import android.telephony.ServiceState;
 import android.telephony.TelephonyManager;
 import android.util.ArraySet;
@@ -1958,7 +1959,7 @@
      *
      * @hide
      */
-    public final @ServiceState.RilRadioTechnology int getCallRadioTech() {
+    public final @RilRadioTechnology int getCallRadioTech() {
         int voiceNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
         Bundle extras = getExtras();
         if (extras != null) {
@@ -2409,7 +2410,7 @@
      *
      * @hide
      */
-    public final void setCallRadioTech(@ServiceState.RilRadioTechnology int vrat) {
+    public final void setCallRadioTech(@RilRadioTechnology int vrat) {
         putExtra(TelecomManager.EXTRA_CALL_NETWORK_TYPE,
                 ServiceState.rilRadioTechnologyToNetworkType(vrat));
         // Propagates the call radio technology to its parent {@link android.telecom.Conference}
diff --git a/telecomm/java/android/telecom/InCallAdapter.java b/telecomm/java/android/telecom/InCallAdapter.java
index 8678e33..2612468 100644
--- a/telecomm/java/android/telecom/InCallAdapter.java
+++ b/telecomm/java/android/telecom/InCallAdapter.java
@@ -16,8 +16,8 @@
 
 package android.telecom;
 
-import android.net.Uri;
 import android.bluetooth.BluetoothDevice;
+import android.net.Uri;
 import android.os.Bundle;
 import android.os.RemoteException;
 
@@ -149,6 +149,26 @@
     }
 
     /**
+     * @see Call#enterBackgroundAudioProcessing()
+     */
+    public void enterBackgroundAudioProcessing(String callId) {
+        try {
+            mAdapter.enterBackgroundAudioProcessing(callId);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * @see Call#exitBackgroundAudioProcessing(boolean)
+     */
+    public void exitBackgroundAudioProcessing(String callId, boolean shouldRing) {
+        try {
+            mAdapter.exitBackgroundAudioProcessing(callId, shouldRing);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
      * Request audio routing to a specific bluetooth device. Calling this method may result in
      * the device routing audio to a different bluetooth device than the one specified. A list of
      * available devices can be obtained via {@link CallAudioState#getSupportedBluetoothDevices()}
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index 6409203..2bc20d5 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -33,6 +33,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.UserHandle;
+import android.telephony.Annotation.CallState;
 import android.telephony.SubscriptionManager;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
@@ -1412,7 +1413,7 @@
      * @hide
      */
     @SystemApi
-    public @TelephonyManager.CallState int getCallState() {
+    public @CallState int getCallState() {
         try {
             if (isServiceConnected()) {
                 return getTelecomService().getCallState();
@@ -2059,12 +2060,13 @@
     /**
      * Handles {@link Intent#ACTION_CALL} intents trampolined from UserCallActivity.
      * @param intent The {@link Intent#ACTION_CALL} intent to handle.
+     * @param callingPackageProxy The original package that called this before it was trampolined.
      * @hide
      */
-    public void handleCallIntent(Intent intent) {
+    public void handleCallIntent(Intent intent, String callingPackageProxy) {
         try {
             if (isServiceConnected()) {
-                getTelecomService().handleCallIntent(intent);
+                getTelecomService().handleCallIntent(intent, callingPackageProxy);
             }
         } catch (RemoteException e) {
             Log.e(TAG, "RemoteException handleCallIntent: " + e);
diff --git a/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl b/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl
index 3ee3285..83c8f62 100644
--- a/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl
+++ b/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl
@@ -30,6 +30,8 @@
 
     void silenceCall(String callId);
 
+    void screenCallFurther(String callId);
+
     void disallowCall(
             String callId,
             boolean shouldReject,
diff --git a/telecomm/java/com/android/internal/telecom/IInCallAdapter.aidl b/telecomm/java/com/android/internal/telecom/IInCallAdapter.aidl
index 57df5c1..60745e4 100644
--- a/telecomm/java/com/android/internal/telecom/IInCallAdapter.aidl
+++ b/telecomm/java/com/android/internal/telecom/IInCallAdapter.aidl
@@ -44,6 +44,10 @@
 
     void setAudioRoute(int route, String bluetoothAddress);
 
+    void enterBackgroundAudioProcessing(String callId);
+
+    void exitBackgroundAudioProcessing(String callId, boolean shouldRing);
+
     void playDtmfTone(String callId, char digit);
 
     void stopDtmfTone(String callId);
diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
index 4fcda4d..6a1b78f 100644
--- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
+++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
@@ -282,6 +282,11 @@
     void acceptHandover(in Uri srcAddr, int videoState, in PhoneAccountHandle destAcct);
 
     /**
+     * @see TelecomServiceImpl#setTestEmergencyPhoneAccountPackageNameFilter
+     */
+    void setTestEmergencyPhoneAccountPackageNameFilter(String packageName);
+
+    /**
      * @see TelecomServiceImpl#isInEmergencyCall
      */
     boolean isInEmergencyCall();
@@ -289,7 +294,7 @@
     /**
      * @see TelecomServiceImpl#handleCallIntent
      */
-    void handleCallIntent(in Intent intent);
+    void handleCallIntent(in Intent intent, in String callingPackageProxy);
 
     void setTestDefaultCallRedirectionApp(String packageName);
 
@@ -302,6 +307,11 @@
     void setTestAutoModeApp(String packageName);
 
     /**
+     * @see TelecomServiceImpl#setSystemDialer
+     */
+    void setSystemDialer(in ComponentName testComponentName);
+
+    /**
      * @see TelecomServiceImpl#setTestDefaultDialer
      */
     void setTestDefaultDialer(in String packageName);
diff --git a/telephony/common/com/android/internal/telephony/HbpcdLookup.java b/telephony/common/com/android/internal/telephony/HbpcdLookup.java
new file mode 100644
index 0000000..d9a3e72
--- /dev/null
+++ b/telephony/common/com/android/internal/telephony/HbpcdLookup.java
@@ -0,0 +1,124 @@
+/*
+**
+** Copyright 2014, 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.internal.telephony;
+
+import android.net.Uri;
+import android.provider.BaseColumns;
+
+/**
+ * @hide
+ */
+public class HbpcdLookup {
+    public static final String AUTHORITY = "hbpcd_lookup";
+
+    public static final Uri CONTENT_URI =
+        Uri.parse("content://" + AUTHORITY);
+
+    public static final String PATH_MCC_IDD = "idd";
+    public static final String PATH_MCC_LOOKUP_TABLE = "lookup";
+    public static final String PATH_MCC_SID_CONFLICT = "conflict";
+    public static final String PATH_MCC_SID_RANGE = "range";
+    public static final String PATH_NANP_AREA_CODE = "nanp";
+    public static final String PATH_ARBITRARY_MCC_SID_MATCH = "arbitrary";
+    public static final String PATH_USERADD_COUNTRY = "useradd";
+
+    public static final String ID = "_id";
+    public static final int IDINDEX = 0;
+
+    /**
+     * @hide
+     */
+    public static class MccIdd implements BaseColumns {
+        public static final Uri CONTENT_URI =
+            Uri.parse("content://" + AUTHORITY + "/" + PATH_MCC_IDD);
+        public static final String DEFAULT_SORT_ORDER = "MCC ASC";
+
+        public static final String MCC = "MCC";
+        public static final String IDD = "IDD";
+
+    }
+
+    /**
+     * @hide
+     */
+    public static class MccLookup implements BaseColumns {
+        public static final Uri CONTENT_URI =
+            Uri.parse("content://" + AUTHORITY + "/" + PATH_MCC_LOOKUP_TABLE);
+        public static final String DEFAULT_SORT_ORDER = "MCC ASC";
+
+        public static final String MCC = "MCC";
+        public static final String COUNTRY_CODE = "Country_Code";
+        public static final String COUNTRY_NAME = "Country_Name";
+        public static final String NDD = "NDD";
+        public static final String NANPS = "NANPS";
+        public static final String GMT_OFFSET_LOW = "GMT_Offset_Low";
+        public static final String GMT_OFFSET_HIGH = "GMT_Offset_High";
+        public static final String GMT_DST_LOW = "GMT_DST_Low";
+        public static final String GMT_DST_HIGH = "GMT_DST_High";
+
+    }
+
+    /**
+     * @hide
+     */
+    public static class MccSidConflicts implements BaseColumns {
+        public static final Uri CONTENT_URI =
+            Uri.parse("content://" + AUTHORITY + "/" + PATH_MCC_SID_CONFLICT);
+        public static final String DEFAULT_SORT_ORDER = "MCC ASC";
+
+        public static final String MCC = "MCC";
+        public static final String SID_CONFLICT = "SID_Conflict";
+
+    }
+
+    /**
+     * @hide
+     */
+    public static class MccSidRange implements BaseColumns {
+        public static final Uri CONTENT_URI =
+            Uri.parse("content://" + AUTHORITY + "/" + PATH_MCC_SID_RANGE);
+        public static final String DEFAULT_SORT_ORDER = "MCC ASC";
+
+        public static final String MCC = "MCC";
+        public static final String RANGE_LOW = "SID_Range_Low";
+        public static final String RANGE_HIGH = "SID_Range_High";
+    }
+
+    /**
+     * @hide
+     */
+    public static class ArbitraryMccSidMatch implements BaseColumns {
+        public static final Uri CONTENT_URI =
+            Uri.parse("content://" + AUTHORITY + "/" + PATH_ARBITRARY_MCC_SID_MATCH);
+        public static final String DEFAULT_SORT_ORDER = "MCC ASC";
+
+        public static final String MCC = "MCC";
+        public static final String SID = "SID";
+
+    }
+
+    /**
+     * @hide
+     */
+    public static class NanpAreaCode implements BaseColumns {
+        public static final Uri CONTENT_URI =
+            Uri.parse("content://" + AUTHORITY + "/" + PATH_NANP_AREA_CODE);
+        public static final String DEFAULT_SORT_ORDER = "Area_Code ASC";
+
+        public static final String AREA_CODE = "Area_Code";
+    }
+}
diff --git a/telephony/common/com/android/internal/telephony/HbpcdUtils.java b/telephony/common/com/android/internal/telephony/HbpcdUtils.java
new file mode 100644
index 0000000..2f31942
--- /dev/null
+++ b/telephony/common/com/android/internal/telephony/HbpcdUtils.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2014 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.internal.telephony;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.database.Cursor;
+import android.telephony.Rlog;
+
+import com.android.internal.telephony.HbpcdLookup.ArbitraryMccSidMatch;
+import com.android.internal.telephony.HbpcdLookup.MccIdd;
+import com.android.internal.telephony.HbpcdLookup.MccLookup;
+import com.android.internal.telephony.HbpcdLookup.MccSidConflicts;
+import com.android.internal.telephony.HbpcdLookup.MccSidRange;
+
+public final class HbpcdUtils {
+    private static final String LOG_TAG = "HbpcdUtils";
+    private static final boolean DBG = false;
+    private ContentResolver resolver = null;
+
+    public HbpcdUtils(Context context) {
+        resolver = context.getContentResolver();
+    }
+
+    /**
+     *  Resolves the unknown MCC with SID and Timezone information.
+    */
+    public int getMcc(int sid, int tz, int DSTflag, boolean isNitzTimeZone) {
+        int tmpMcc = 0;
+
+        // check if SID exists in arbitrary_mcc_sid_match table.
+        // these SIDs are assigned to more than 1 operators, but they are known to
+        // be used by a specific operator, other operators having the same SID are
+        // not using it currently, if that SID is in this table, we don't need to
+        // check other tables.
+        String projection2[] = {ArbitraryMccSidMatch.MCC};
+        Cursor c2 = resolver.query(ArbitraryMccSidMatch.CONTENT_URI, projection2,
+                            ArbitraryMccSidMatch.SID + "=" + sid, null, null);
+
+        if (c2 != null) {
+            int c2Counter = c2.getCount();
+            if (DBG) {
+                Rlog.d(LOG_TAG, "Query unresolved arbitrary table, entries are " + c2Counter);
+            }
+            if (c2Counter == 1) {
+                if (DBG) {
+                    Rlog.d(LOG_TAG, "Query Unresolved arbitrary returned the cursor " + c2);
+                }
+                c2.moveToFirst();
+                tmpMcc = c2.getInt(0);
+                if (DBG) {
+                    Rlog.d(LOG_TAG, "MCC found in arbitrary_mcc_sid_match: " + tmpMcc);
+                }
+                c2.close();
+                return tmpMcc;
+            }
+            c2.close();
+        }
+
+        // Then check if SID exists in mcc_sid_conflict table.
+        // and use the timezone in mcc_lookup table to check which MCC matches.
+        String projection3[] = {MccSidConflicts.MCC};
+        Cursor c3 = resolver.query(MccSidConflicts.CONTENT_URI, projection3,
+                MccSidConflicts.SID_CONFLICT + "=" + sid + " and (((" +
+                MccLookup.GMT_OFFSET_LOW + "<=" + tz + ") and (" + tz + "<=" +
+                MccLookup.GMT_OFFSET_HIGH + ") and (" + "0=" + DSTflag + ")) or ((" +
+                MccLookup.GMT_DST_LOW + "<=" + tz + ") and (" + tz + "<=" +
+                MccLookup.GMT_DST_HIGH + ") and (" + "1=" + DSTflag + ")))",
+                        null, null);
+        if (c3 != null) {
+            int c3Counter = c3.getCount();
+            if (c3Counter > 0) {
+                if (c3Counter > 1) {
+                    Rlog.w(LOG_TAG, "something wrong, get more results for 1 conflict SID: " + c3);
+                }
+                if (DBG) Rlog.d(LOG_TAG, "Query conflict sid returned the cursor " + c3);
+                c3.moveToFirst();
+                tmpMcc = c3.getInt(0);
+                if (DBG) {
+                    Rlog.d(LOG_TAG, "MCC found in mcc_lookup_table. Return tmpMcc = " + tmpMcc);
+                }
+                if (!isNitzTimeZone) {
+                    // time zone is not accurate, it may get wrong mcc, ignore it.
+                    if (DBG) {
+                        Rlog.d(LOG_TAG, "time zone is not accurate, mcc may be " + tmpMcc);
+                    }
+                    tmpMcc = 0;
+                }
+                c3.close();
+                return tmpMcc;
+            } else {
+                c3.close();
+            }
+        }
+
+        // if there is no conflict, then check if SID is in mcc_sid_range.
+        String projection5[] = {MccSidRange.MCC};
+        Cursor c5 = resolver.query(MccSidRange.CONTENT_URI, projection5,
+                MccSidRange.RANGE_LOW + "<=" + sid + " and " +
+                MccSidRange.RANGE_HIGH + ">=" + sid,
+                null, null);
+        if (c5 != null) {
+            if (c5.getCount() > 0) {
+                if (DBG) Rlog.d(LOG_TAG, "Query Range returned the cursor " + c5);
+                c5.moveToFirst();
+                tmpMcc = c5.getInt(0);
+                if (DBG) Rlog.d(LOG_TAG, "SID found in mcc_sid_range. Return tmpMcc = " + tmpMcc);
+                c5.close();
+                return tmpMcc;
+            }
+            c5.close();
+        }
+        if (DBG) Rlog.d(LOG_TAG, "SID NOT found in mcc_sid_range.");
+
+        if (DBG) Rlog.d(LOG_TAG, "Exit getMccByOtherFactors. Return tmpMcc =  " + tmpMcc);
+        // If unknown MCC still could not be resolved,
+        return tmpMcc;
+    }
+
+    /**
+     *  Gets country information with given MCC.
+    */
+    public String getIddByMcc(int mcc) {
+        if (DBG) Rlog.d(LOG_TAG, "Enter getHbpcdInfoByMCC.");
+        String idd = "";
+
+        Cursor c = null;
+
+        String projection[] = {MccIdd.IDD};
+        Cursor cur = resolver.query(MccIdd.CONTENT_URI, projection,
+                MccIdd.MCC + "=" + mcc, null, null);
+        if (cur != null) {
+            if (cur.getCount() > 0) {
+                if (DBG) Rlog.d(LOG_TAG, "Query Idd returned the cursor " + cur);
+                // TODO: for those country having more than 1 IDDs, need more information
+                // to decide which IDD would be used. currently just use the first 1.
+                cur.moveToFirst();
+                idd = cur.getString(0);
+                if (DBG) Rlog.d(LOG_TAG, "IDD = " + idd);
+
+            }
+            cur.close();
+        }
+        if (c != null) c.close();
+
+        if (DBG) Rlog.d(LOG_TAG, "Exit getHbpcdInfoByMCC.");
+        return idd;
+    }
+}
diff --git a/telephony/common/com/android/internal/telephony/SmsApplication.java b/telephony/common/com/android/internal/telephony/SmsApplication.java
new file mode 100644
index 0000000..f4eae8e
--- /dev/null
+++ b/telephony/common/com/android/internal/telephony/SmsApplication.java
@@ -0,0 +1,1077 @@
+/*
+ * Copyright (C) 2013 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.internal.telephony;
+
+import android.Manifest.permission;
+import android.annotation.Nullable;
+import android.app.AppOpsManager;
+import android.app.role.RoleManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ResolveInfo;
+import android.content.pm.ServiceInfo;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.Binder;
+import android.os.Debug;
+import android.os.Process;
+import android.os.UserHandle;
+import android.provider.Telephony;
+import android.provider.Telephony.Sms.Intents;
+import android.telephony.Rlog;
+import android.telephony.TelephonyManager;
+import android.util.Log;
+
+import com.android.internal.content.PackageMonitor;
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+
+import dalvik.annotation.compat.UnsupportedAppUsage;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
+
+/**
+ * Class for managing the primary application that we will deliver SMS/MMS messages to
+ *
+ * {@hide}
+ */
+public final class SmsApplication {
+    static final String LOG_TAG = "SmsApplication";
+    private static final String PHONE_PACKAGE_NAME = "com.android.phone";
+    private static final String BLUETOOTH_PACKAGE_NAME = "com.android.bluetooth";
+    private static final String MMS_SERVICE_PACKAGE_NAME = "com.android.mms.service";
+    private static final String TELEPHONY_PROVIDER_PACKAGE_NAME = "com.android.providers.telephony";
+
+    private static final String SCHEME_SMS = "sms";
+    private static final String SCHEME_SMSTO = "smsto";
+    private static final String SCHEME_MMS = "mms";
+    private static final String SCHEME_MMSTO = "mmsto";
+    private static final boolean DEBUG = false;
+    private static final boolean DEBUG_MULTIUSER = false;
+
+    private static final int[] DEFAULT_APP_EXCLUSIVE_APPOPS = {
+            AppOpsManager.OP_READ_SMS,
+            AppOpsManager.OP_WRITE_SMS,
+            AppOpsManager.OP_RECEIVE_SMS,
+            AppOpsManager.OP_RECEIVE_WAP_PUSH,
+            AppOpsManager.OP_SEND_SMS,
+            AppOpsManager.OP_READ_CELL_BROADCASTS
+    };
+
+    private static SmsPackageMonitor sSmsPackageMonitor = null;
+
+    public static class SmsApplicationData {
+        /**
+         * Name of this SMS app for display.
+         */
+        @UnsupportedAppUsage
+        private String mApplicationName;
+
+        /**
+         * Package name for this SMS app.
+         */
+        public String mPackageName;
+
+        /**
+         * The class name of the SMS_DELIVER_ACTION receiver in this app.
+         */
+        private String mSmsReceiverClass;
+
+        /**
+         * The class name of the WAP_PUSH_DELIVER_ACTION receiver in this app.
+         */
+        private String mMmsReceiverClass;
+
+        /**
+         * The class name of the ACTION_RESPOND_VIA_MESSAGE intent in this app.
+         */
+        private String mRespondViaMessageClass;
+
+        /**
+         * The class name of the ACTION_SENDTO intent in this app.
+         */
+        private String mSendToClass;
+
+        /**
+         * The class name of the ACTION_DEFAULT_SMS_PACKAGE_CHANGED receiver in this app.
+         */
+        private String mSmsAppChangedReceiverClass;
+
+        /**
+         * The class name of the ACTION_EXTERNAL_PROVIDER_CHANGE receiver in this app.
+         */
+        private String mProviderChangedReceiverClass;
+
+        /**
+         * The class name of the SIM_FULL_ACTION receiver in this app.
+         */
+        private String mSimFullReceiverClass;
+
+        /**
+         * The user-id for this application
+         */
+        private int mUid;
+
+        /**
+         * Returns true if this SmsApplicationData is complete (all intents handled).
+         * @return
+         */
+        public boolean isComplete() {
+            return (mSmsReceiverClass != null && mMmsReceiverClass != null
+                    && mRespondViaMessageClass != null && mSendToClass != null);
+        }
+
+        public SmsApplicationData(String packageName, int uid) {
+            mPackageName = packageName;
+            mUid = uid;
+        }
+
+        public String getApplicationName(Context context) {
+            if (mApplicationName == null) {
+                PackageManager pm = context.getPackageManager();
+                ApplicationInfo appInfo;
+                try {
+                    appInfo = pm.getApplicationInfoAsUser(mPackageName, 0,
+                            UserHandle.getUserHandleForUid(mUid));
+                } catch (NameNotFoundException e) {
+                    return null;
+                }
+                if (appInfo != null) {
+                    CharSequence label  = pm.getApplicationLabel(appInfo);
+                    mApplicationName = (label == null) ? null : label.toString();
+                }
+            }
+            return mApplicationName;
+        }
+
+        @Override
+        public String toString() {
+            return " mPackageName: " + mPackageName
+                    + " mSmsReceiverClass: " + mSmsReceiverClass
+                    + " mMmsReceiverClass: " + mMmsReceiverClass
+                    + " mRespondViaMessageClass: " + mRespondViaMessageClass
+                    + " mSendToClass: " + mSendToClass
+                    + " mSmsAppChangedClass: " + mSmsAppChangedReceiverClass
+                    + " mProviderChangedReceiverClass: " + mProviderChangedReceiverClass
+                    + " mSimFullReceiverClass: " + mSimFullReceiverClass
+                    + " mUid: " + mUid;
+        }
+    }
+
+    /**
+     * Returns the userId of the Context object, if called from a system app,
+     * otherwise it returns the caller's userId
+     * @param context The context object passed in by the caller.
+     * @return
+     */
+    private static int getIncomingUserId(Context context) {
+        int contextUserId = UserHandle.myUserId();
+        final int callingUid = Binder.getCallingUid();
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getIncomingUserHandle caller=" + callingUid + ", myuid="
+                    + android.os.Process.myUid() + "\n\t" + Debug.getCallers(4));
+        }
+        if (UserHandle.getAppId(callingUid)
+                < android.os.Process.FIRST_APPLICATION_UID) {
+            return contextUserId;
+        } else {
+            return UserHandle.getUserId(callingUid);
+        }
+    }
+
+    /**
+     * Returns the list of available SMS apps defined as apps that are registered for both the
+     * SMS_RECEIVED_ACTION (SMS) and WAP_PUSH_RECEIVED_ACTION (MMS) broadcasts (and their broadcast
+     * receivers are enabled)
+     *
+     * Requirements to be an SMS application:
+     * Implement SMS_DELIVER_ACTION broadcast receiver.
+     * Require BROADCAST_SMS permission.
+     *
+     * Implement WAP_PUSH_DELIVER_ACTION broadcast receiver.
+     * Require BROADCAST_WAP_PUSH permission.
+     *
+     * Implement RESPOND_VIA_MESSAGE intent.
+     * Support smsto Uri scheme.
+     * Require SEND_RESPOND_VIA_MESSAGE permission.
+     *
+     * Implement ACTION_SENDTO intent.
+     * Support smsto Uri scheme.
+     */
+    @UnsupportedAppUsage
+    public static Collection<SmsApplicationData> getApplicationCollection(Context context) {
+        return getApplicationCollectionAsUser(context, getIncomingUserId(context));
+    }
+
+    /**
+     * Same as {@link #getApplicationCollection} but it takes a target user ID.
+     */
+    public static Collection<SmsApplicationData> getApplicationCollectionAsUser(Context context,
+            int userId) {
+        final long token = Binder.clearCallingIdentity();
+        try {
+            return getApplicationCollectionInternal(context, userId);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    private static Collection<SmsApplicationData> getApplicationCollectionInternal(
+            Context context, int userId) {
+        PackageManager packageManager = context.getPackageManager();
+
+        // Get the list of apps registered for SMS
+        Intent intent = new Intent(Intents.SMS_DELIVER_ACTION);
+        if (DEBUG) {
+            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
+        }
+        List<ResolveInfo> smsReceivers = packageManager.queryBroadcastReceiversAsUser(intent,
+                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+                userId);
+
+        HashMap<String, SmsApplicationData> receivers = new HashMap<String, SmsApplicationData>();
+
+        // Add one entry to the map for every sms receiver (ignoring duplicate sms receivers)
+        for (ResolveInfo resolveInfo : smsReceivers) {
+            final ActivityInfo activityInfo = resolveInfo.activityInfo;
+            if (activityInfo == null) {
+                continue;
+            }
+            if (!permission.BROADCAST_SMS.equals(activityInfo.permission)) {
+                continue;
+            }
+            final String packageName = activityInfo.packageName;
+            if (!receivers.containsKey(packageName)) {
+                final SmsApplicationData smsApplicationData = new SmsApplicationData(packageName,
+                        activityInfo.applicationInfo.uid);
+                smsApplicationData.mSmsReceiverClass = activityInfo.name;
+                receivers.put(packageName, smsApplicationData);
+            }
+        }
+
+        // Update any existing entries with mms receiver class
+        intent = new Intent(Intents.WAP_PUSH_DELIVER_ACTION);
+        intent.setDataAndType(null, "application/vnd.wap.mms-message");
+        List<ResolveInfo> mmsReceivers = packageManager.queryBroadcastReceiversAsUser(intent,
+                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+                userId);
+        for (ResolveInfo resolveInfo : mmsReceivers) {
+            final ActivityInfo activityInfo = resolveInfo.activityInfo;
+            if (activityInfo == null) {
+                continue;
+            }
+            if (!permission.BROADCAST_WAP_PUSH.equals(activityInfo.permission)) {
+                continue;
+            }
+            final String packageName = activityInfo.packageName;
+            final SmsApplicationData smsApplicationData = receivers.get(packageName);
+            if (smsApplicationData != null) {
+                smsApplicationData.mMmsReceiverClass = activityInfo.name;
+            }
+        }
+
+        // Update any existing entries with respond via message intent class.
+        intent = new Intent(TelephonyManager.ACTION_RESPOND_VIA_MESSAGE,
+                Uri.fromParts(SCHEME_SMSTO, "", null));
+        List<ResolveInfo> respondServices = packageManager.queryIntentServicesAsUser(intent,
+                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+                UserHandle.of(userId));
+        for (ResolveInfo resolveInfo : respondServices) {
+            final ServiceInfo serviceInfo = resolveInfo.serviceInfo;
+            if (serviceInfo == null) {
+                continue;
+            }
+            if (!permission.SEND_RESPOND_VIA_MESSAGE.equals(serviceInfo.permission)) {
+                continue;
+            }
+            final String packageName = serviceInfo.packageName;
+            final SmsApplicationData smsApplicationData = receivers.get(packageName);
+            if (smsApplicationData != null) {
+                smsApplicationData.mRespondViaMessageClass = serviceInfo.name;
+            }
+        }
+
+        // Update any existing entries with supports send to.
+        intent = new Intent(Intent.ACTION_SENDTO,
+                Uri.fromParts(SCHEME_SMSTO, "", null));
+        List<ResolveInfo> sendToActivities = packageManager.queryIntentActivitiesAsUser(intent,
+                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
+                userId);
+        for (ResolveInfo resolveInfo : sendToActivities) {
+            final ActivityInfo activityInfo = resolveInfo.activityInfo;
+            if (activityInfo == null) {
+                continue;
+            }
+            final String packageName = activityInfo.packageName;
+            final SmsApplicationData smsApplicationData = receivers.get(packageName);
+            if (smsApplicationData != null) {
+                smsApplicationData.mSendToClass = activityInfo.name;
+            }
+        }
+
+        // Update any existing entries with the default sms changed handler.
+        intent = new Intent(Telephony.Sms.Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED);
+        List<ResolveInfo> smsAppChangedReceivers =
+                packageManager.queryBroadcastReceiversAsUser(intent,
+                        PackageManager.MATCH_DIRECT_BOOT_AWARE
+                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getApplicationCollectionInternal smsAppChangedActivities=" +
+                    smsAppChangedReceivers);
+        }
+        for (ResolveInfo resolveInfo : smsAppChangedReceivers) {
+            final ActivityInfo activityInfo = resolveInfo.activityInfo;
+            if (activityInfo == null) {
+                continue;
+            }
+            final String packageName = activityInfo.packageName;
+            final SmsApplicationData smsApplicationData = receivers.get(packageName);
+            if (DEBUG_MULTIUSER) {
+                Log.i(LOG_TAG, "getApplicationCollectionInternal packageName=" +
+                        packageName + " smsApplicationData: " + smsApplicationData +
+                        " activityInfo.name: " + activityInfo.name);
+            }
+            if (smsApplicationData != null) {
+                smsApplicationData.mSmsAppChangedReceiverClass = activityInfo.name;
+            }
+        }
+
+        // Update any existing entries with the external provider changed handler.
+        intent = new Intent(Telephony.Sms.Intents.ACTION_EXTERNAL_PROVIDER_CHANGE);
+        List<ResolveInfo> providerChangedReceivers =
+                packageManager.queryBroadcastReceiversAsUser(intent,
+                        PackageManager.MATCH_DIRECT_BOOT_AWARE
+                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getApplicationCollectionInternal providerChangedActivities=" +
+                    providerChangedReceivers);
+        }
+        for (ResolveInfo resolveInfo : providerChangedReceivers) {
+            final ActivityInfo activityInfo = resolveInfo.activityInfo;
+            if (activityInfo == null) {
+                continue;
+            }
+            final String packageName = activityInfo.packageName;
+            final SmsApplicationData smsApplicationData = receivers.get(packageName);
+            if (DEBUG_MULTIUSER) {
+                Log.i(LOG_TAG, "getApplicationCollectionInternal packageName=" +
+                        packageName + " smsApplicationData: " + smsApplicationData +
+                        " activityInfo.name: " + activityInfo.name);
+            }
+            if (smsApplicationData != null) {
+                smsApplicationData.mProviderChangedReceiverClass = activityInfo.name;
+            }
+        }
+
+        // Update any existing entries with the sim full handler.
+        intent = new Intent(Intents.SIM_FULL_ACTION);
+        List<ResolveInfo> simFullReceivers =
+                packageManager.queryBroadcastReceiversAsUser(intent,
+                        PackageManager.MATCH_DIRECT_BOOT_AWARE
+                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getApplicationCollectionInternal simFullReceivers="
+                    + simFullReceivers);
+        }
+        for (ResolveInfo resolveInfo : simFullReceivers) {
+            final ActivityInfo activityInfo = resolveInfo.activityInfo;
+            if (activityInfo == null) {
+                continue;
+            }
+            final String packageName = activityInfo.packageName;
+            final SmsApplicationData smsApplicationData = receivers.get(packageName);
+            if (DEBUG_MULTIUSER) {
+                Log.i(LOG_TAG, "getApplicationCollectionInternal packageName="
+                        + packageName + " smsApplicationData: " + smsApplicationData
+                        + " activityInfo.name: " + activityInfo.name);
+            }
+            if (smsApplicationData != null) {
+                smsApplicationData.mSimFullReceiverClass = activityInfo.name;
+            }
+        }
+
+        // Remove any entries for which we did not find all required intents.
+        for (ResolveInfo resolveInfo : smsReceivers) {
+            final ActivityInfo activityInfo = resolveInfo.activityInfo;
+            if (activityInfo == null) {
+                continue;
+            }
+            final String packageName = activityInfo.packageName;
+            final SmsApplicationData smsApplicationData = receivers.get(packageName);
+            if (smsApplicationData != null) {
+                if (!smsApplicationData.isComplete()) {
+                    receivers.remove(packageName);
+                }
+            }
+        }
+        return receivers.values();
+    }
+
+    /**
+     * Checks to see if we have a valid installed SMS application for the specified package name
+     * @return Data for the specified package name or null if there isn't one
+     */
+    public static SmsApplicationData getApplicationForPackage(
+            Collection<SmsApplicationData> applications, String packageName) {
+        if (packageName == null) {
+            return null;
+        }
+        // Is there an entry in the application list for the specified package?
+        for (SmsApplicationData application : applications) {
+            if (application.mPackageName.contentEquals(packageName)) {
+                return application;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Get the application we will use for delivering SMS/MMS messages.
+     *
+     * We return the preferred sms application with the following order of preference:
+     * (1) User selected SMS app (if selected, and if still valid)
+     * (2) Android Messaging (if installed)
+     * (3) The currently configured highest priority broadcast receiver
+     * (4) Null
+     */
+    private static SmsApplicationData getApplication(Context context, boolean updateIfNeeded,
+            int userId) {
+        TelephonyManager tm = (TelephonyManager)
+                context.getSystemService(Context.TELEPHONY_SERVICE);
+        RoleManager roleManager = (RoleManager) context.getSystemService(Context.ROLE_SERVICE);
+        // (b/134400042) RoleManager might be null in unit tests running older mockito versions
+        // that do not support mocking final classes.
+        if (!tm.isSmsCapable() && (roleManager == null || !roleManager.isRoleAvailable(
+                RoleManager.ROLE_SMS))) {
+            // No phone, no SMS
+            return null;
+        }
+
+        Collection<SmsApplicationData> applications = getApplicationCollectionInternal(context,
+                userId);
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getApplication userId=" + userId);
+        }
+        // Determine which application receives the broadcast
+        String defaultApplication = getDefaultSmsPackage(context, userId);
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getApplication defaultApp=" + defaultApplication);
+        }
+
+        SmsApplicationData applicationData = null;
+        if (defaultApplication != null) {
+            applicationData = getApplicationForPackage(applications, defaultApplication);
+        }
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getApplication appData=" + applicationData);
+        }
+
+        // If we found a package, make sure AppOps permissions are set up correctly
+        if (applicationData != null) {
+            // We can only call checkOp if we are privileged (updateIfNeeded) or if the app we
+            // are checking is for our current uid. Doing this check from the unprivileged current
+            // SMS app allows us to tell the current SMS app that it is not in a good state and
+            // needs to ask to be the current SMS app again to work properly.
+            if (updateIfNeeded || applicationData.mUid == android.os.Process.myUid()) {
+                // Verify that the SMS app has permissions
+                boolean appOpsFixed =
+                        tryFixExclusiveSmsAppops(context, applicationData, updateIfNeeded);
+                if (!appOpsFixed) {
+                    // We can not return a package if permissions are not set up correctly
+                    applicationData = null;
+                }
+            }
+
+            // We can only verify the phone and BT app's permissions from a privileged caller
+            if (applicationData != null && updateIfNeeded) {
+                // Ensure this component is still configured as the preferred activity. Usually the
+                // current SMS app will already be the preferred activity - but checking whether or
+                // not this is true is just as expensive as reconfiguring the preferred activity so
+                // we just reconfigure every time.
+                defaultSmsAppChanged(context);
+            }
+        }
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "getApplication returning appData=" + applicationData);
+        }
+        return applicationData;
+    }
+
+    private static String getDefaultSmsPackage(Context context, int userId) {
+        return context.getSystemService(RoleManager.class).getDefaultSmsPackage(userId);
+    }
+
+    /**
+     * Grants various permissions and appops on sms app change
+     */
+    private static void defaultSmsAppChanged(Context context) {
+        PackageManager packageManager = context.getPackageManager();
+        AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
+
+        // Assign permission to special system apps
+        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
+                PHONE_PACKAGE_NAME);
+        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
+                BLUETOOTH_PACKAGE_NAME);
+        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
+                MMS_SERVICE_PACKAGE_NAME);
+        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
+                TELEPHONY_PROVIDER_PACKAGE_NAME);
+
+        // Give AppOps permission to UID 1001 which contains multiple
+        // apps, all of them should be able to write to telephony provider.
+        // This is to allow the proxy package permission check in telephony provider
+        // to pass.
+        for (int appop : DEFAULT_APP_EXCLUSIVE_APPOPS) {
+            appOps.setUidMode(appop, Process.PHONE_UID, AppOpsManager.MODE_ALLOWED);
+        }
+    }
+
+    private static boolean tryFixExclusiveSmsAppops(Context context,
+            SmsApplicationData applicationData, boolean updateIfNeeded) {
+        AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
+        for (int appOp : DEFAULT_APP_EXCLUSIVE_APPOPS) {
+            int mode = appOps.checkOp(appOp, applicationData.mUid,
+                    applicationData.mPackageName);
+            if (mode != AppOpsManager.MODE_ALLOWED) {
+                Rlog.e(LOG_TAG, applicationData.mPackageName + " lost "
+                        + AppOpsManager.modeToName(appOp) + ": "
+                        + (updateIfNeeded ? " (fixing)" : " (no permission to fix)"));
+                if (updateIfNeeded) {
+                    appOps.setUidMode(appOp, applicationData.mUid, AppOpsManager.MODE_ALLOWED);
+                } else {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Sets the specified package as the default SMS/MMS application. The caller of this method
+     * needs to have permission to set AppOps and write to secure settings.
+     */
+    @UnsupportedAppUsage
+    public static void setDefaultApplication(String packageName, Context context) {
+        setDefaultApplicationAsUser(packageName, context, getIncomingUserId(context));
+    }
+
+    /**
+     * Same as {@link #setDefaultApplication} but takes a target user id.
+     */
+    public static void setDefaultApplicationAsUser(String packageName, Context context,
+            int userId) {
+        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
+        RoleManager roleManager = (RoleManager) context.getSystemService(Context.ROLE_SERVICE);
+        // (b/134400042) RoleManager might be null in unit tests running older mockito versions
+        // that do not support mocking final classes.
+        if (!tm.isSmsCapable() && (roleManager == null || !roleManager.isRoleAvailable(
+                RoleManager.ROLE_SMS))) {
+            // No phone, no SMS
+            return;
+        }
+
+        final long token = Binder.clearCallingIdentity();
+        try {
+            setDefaultApplicationInternal(packageName, context, userId);
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    private static void setDefaultApplicationInternal(String packageName, Context context,
+            int userId) {
+        final UserHandle userHandle = UserHandle.of(userId);
+
+        // Get old package name
+        String oldPackageName = getDefaultSmsPackage(context, userId);
+
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "setDefaultApplicationInternal old=" + oldPackageName +
+                    " new=" + packageName);
+        }
+
+        if (packageName != null && oldPackageName != null && packageName.equals(oldPackageName)) {
+            // No change
+            return;
+        }
+
+        // We only make the change if the new package is valid
+        PackageManager packageManager = context.getPackageManager();
+        Collection<SmsApplicationData> applications = getApplicationCollectionInternal(
+                context, userId);
+        SmsApplicationData oldAppData = oldPackageName != null ?
+                getApplicationForPackage(applications, oldPackageName) : null;
+        SmsApplicationData applicationData = getApplicationForPackage(applications, packageName);
+        if (applicationData != null) {
+            // Ignore relevant appops for the previously configured default SMS app.
+            AppOpsManager appOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
+            if (oldPackageName != null) {
+                try {
+                    int uid = packageManager.getPackageInfoAsUser(
+                            oldPackageName, 0, userId).applicationInfo.uid;
+                    setExclusiveAppops(oldPackageName, appOps, uid, AppOpsManager.MODE_DEFAULT);
+                } catch (NameNotFoundException e) {
+                    Rlog.w(LOG_TAG, "Old SMS package not found: " + oldPackageName);
+                }
+            }
+
+            // Update the setting.
+            CompletableFuture<Void> future = new CompletableFuture<>();
+            Consumer<Boolean> callback = successful -> {
+                if (successful) {
+                    future.complete(null);
+                } else {
+                    future.completeExceptionally(new RuntimeException());
+                }
+            };
+            context.getSystemService(RoleManager.class).addRoleHolderAsUser(
+                    RoleManager.ROLE_SMS, applicationData.mPackageName, 0, UserHandle.of(userId),
+                    AsyncTask.THREAD_POOL_EXECUTOR, callback);
+            try {
+                future.get(5, TimeUnit.SECONDS);
+            } catch (InterruptedException | ExecutionException | TimeoutException e) {
+                Log.e(LOG_TAG, "Exception while adding sms role holder " + applicationData, e);
+                return;
+            }
+
+            defaultSmsAppChanged(context);
+        }
+    }
+
+    /**
+     * Sends broadcasts on sms app change:
+     * {@link Intent#ACTION_DEFAULT_SMS_PACKAGE_CHANGED}
+     * {@link Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED_INTERNAL}
+     */
+    public static void broadcastSmsAppChange(Context context,
+            UserHandle userHandle, @Nullable String oldPackage, @Nullable String newPackage) {
+        Collection<SmsApplicationData> apps = getApplicationCollection(context);
+
+        broadcastSmsAppChange(context, userHandle,
+                getApplicationForPackage(apps, oldPackage),
+                getApplicationForPackage(apps, newPackage));
+    }
+
+    private static void broadcastSmsAppChange(Context context, UserHandle userHandle,
+            @Nullable SmsApplicationData oldAppData,
+            @Nullable SmsApplicationData applicationData) {
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "setDefaultApplicationInternal oldAppData=" + oldAppData);
+        }
+        if (oldAppData != null && oldAppData.mSmsAppChangedReceiverClass != null) {
+            // Notify the old sms app that it's no longer the default
+            final Intent oldAppIntent =
+                    new Intent(Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED);
+            final ComponentName component = new ComponentName(oldAppData.mPackageName,
+                    oldAppData.mSmsAppChangedReceiverClass);
+            oldAppIntent.setComponent(component);
+            oldAppIntent.putExtra(Intents.EXTRA_IS_DEFAULT_SMS_APP, false);
+            if (DEBUG_MULTIUSER) {
+                Log.i(LOG_TAG, "setDefaultApplicationInternal old=" + oldAppData.mPackageName);
+            }
+            context.sendBroadcastAsUser(oldAppIntent, userHandle);
+        }
+        // Notify the new sms app that it's now the default (if the new sms app has a receiver
+        // to handle the changed default sms intent).
+        if (DEBUG_MULTIUSER) {
+            Log.i(LOG_TAG, "setDefaultApplicationInternal new applicationData=" +
+                    applicationData);
+        }
+        if (applicationData != null && applicationData.mSmsAppChangedReceiverClass != null) {
+            final Intent intent =
+                    new Intent(Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED);
+            final ComponentName component = new ComponentName(applicationData.mPackageName,
+                    applicationData.mSmsAppChangedReceiverClass);
+            intent.setComponent(component);
+            intent.putExtra(Intents.EXTRA_IS_DEFAULT_SMS_APP, true);
+            if (DEBUG_MULTIUSER) {
+                Log.i(LOG_TAG, "setDefaultApplicationInternal new=" + applicationData.mPackageName);
+            }
+            context.sendBroadcastAsUser(intent, userHandle);
+        }
+
+        // Send an implicit broadcast for the system server.
+        // (or anyone with MONITOR_DEFAULT_SMS_PACKAGE, really.)
+        final Intent intent =
+                new Intent(Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED_INTERNAL);
+        context.sendBroadcastAsUser(intent, userHandle,
+                permission.MONITOR_DEFAULT_SMS_PACKAGE);
+
+        if (applicationData != null) {
+            MetricsLogger.action(context, MetricsEvent.ACTION_DEFAULT_SMS_APP_CHANGED,
+                    applicationData.mPackageName);
+        }
+    }
+
+    /**
+     * Assign WRITE_SMS AppOps permission to some special system apps.
+     *
+     * @param context The context
+     * @param packageManager The package manager instance
+     * @param appOps The AppOps manager instance
+     * @param packageName The package name of the system app
+     */
+    private static void assignExclusiveSmsPermissionsToSystemApp(Context context,
+            PackageManager packageManager, AppOpsManager appOps, String packageName) {
+        // First check package signature matches the caller's package signature.
+        // Since this class is only used internally by the system, this check makes sure
+        // the package signature matches system signature.
+        final int result = packageManager.checkSignatures(context.getPackageName(), packageName);
+        if (result != PackageManager.SIGNATURE_MATCH) {
+            Rlog.e(LOG_TAG, packageName + " does not have system signature");
+            return;
+        }
+        try {
+            PackageInfo info = packageManager.getPackageInfo(packageName, 0);
+            int mode = appOps.checkOp(AppOpsManager.OP_WRITE_SMS, info.applicationInfo.uid,
+                    packageName);
+            if (mode != AppOpsManager.MODE_ALLOWED) {
+                Rlog.w(LOG_TAG, packageName + " does not have OP_WRITE_SMS:  (fixing)");
+                setExclusiveAppops(packageName, appOps, info.applicationInfo.uid,
+                        AppOpsManager.MODE_ALLOWED);
+            }
+        } catch (NameNotFoundException e) {
+            // No whitelisted system app on this device
+            Rlog.e(LOG_TAG, "Package not found: " + packageName);
+        }
+
+    }
+
+    private static void setExclusiveAppops(String pkg, AppOpsManager appOpsManager, int uid,
+            int mode) {
+        for (int appop : DEFAULT_APP_EXCLUSIVE_APPOPS) {
+            appOpsManager.setUidMode(appop, uid, mode);
+        }
+    }
+
+    /**
+     * Tracks package changes and ensures that the default SMS app is always configured to be the
+     * preferred activity for SENDTO sms/mms intents.
+     */
+    private static final class SmsPackageMonitor extends PackageMonitor {
+        final Context mContext;
+
+        public SmsPackageMonitor(Context context) {
+            super();
+            mContext = context;
+        }
+
+        @Override
+        public void onPackageDisappeared(String packageName, int reason) {
+            onPackageChanged();
+        }
+
+        @Override
+        public void onPackageAppeared(String packageName, int reason) {
+            onPackageChanged();
+        }
+
+        @Override
+        public void onPackageModified(String packageName) {
+            onPackageChanged();
+        }
+
+        private void onPackageChanged() {
+            PackageManager packageManager = mContext.getPackageManager();
+            Context userContext = mContext;
+            final int userId = getSendingUserId();
+            if (userId != UserHandle.USER_SYSTEM) {
+                try {
+                    userContext = mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
+                        UserHandle.of(userId));
+                } catch (NameNotFoundException nnfe) {
+                    if (DEBUG_MULTIUSER) {
+                        Log.w(LOG_TAG, "Unable to create package context for user " + userId);
+                    }
+                }
+            }
+            // Ensure this component is still configured as the preferred activity
+            ComponentName componentName = getDefaultSendToApplication(userContext, true);
+            if (componentName != null) {
+                configurePreferredActivity(packageManager, componentName, userId);
+            }
+        }
+    }
+
+    public static void initSmsPackageMonitor(Context context) {
+        sSmsPackageMonitor = new SmsPackageMonitor(context);
+        sSmsPackageMonitor.register(context, context.getMainLooper(), UserHandle.ALL, false);
+    }
+
+    @UnsupportedAppUsage
+    private static void configurePreferredActivity(PackageManager packageManager,
+            ComponentName componentName, int userId) {
+        // Add the four activity preferences we want to direct to this app.
+        replacePreferredActivity(packageManager, componentName, userId, SCHEME_SMS);
+        replacePreferredActivity(packageManager, componentName, userId, SCHEME_SMSTO);
+        replacePreferredActivity(packageManager, componentName, userId, SCHEME_MMS);
+        replacePreferredActivity(packageManager, componentName, userId, SCHEME_MMSTO);
+    }
+
+    /**
+     * Updates the ACTION_SENDTO activity to the specified component for the specified scheme.
+     */
+    private static void replacePreferredActivity(PackageManager packageManager,
+            ComponentName componentName, int userId, String scheme) {
+        // Build the set of existing activities that handle this scheme
+        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(scheme, "", null));
+        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivitiesAsUser(
+                intent, PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER,
+                userId);
+
+        // Build the set of ComponentNames for these activities
+        final int n = resolveInfoList.size();
+        ComponentName[] set = new ComponentName[n];
+        for (int i = 0; i < n; i++) {
+            ResolveInfo info = resolveInfoList.get(i);
+            set[i] = new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
+        }
+
+        // Update the preferred SENDTO activity for the specified scheme
+        IntentFilter intentFilter = new IntentFilter();
+        intentFilter.addAction(Intent.ACTION_SENDTO);
+        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
+        intentFilter.addDataScheme(scheme);
+        packageManager.replacePreferredActivityAsUser(intentFilter,
+                IntentFilter.MATCH_CATEGORY_SCHEME + IntentFilter.MATCH_ADJUSTMENT_NORMAL,
+                set, componentName, userId);
+    }
+
+    /**
+     * Returns SmsApplicationData for this package if this package is capable of being set as the
+     * default SMS application.
+     */
+    @UnsupportedAppUsage
+    public static SmsApplicationData getSmsApplicationData(String packageName, Context context) {
+        Collection<SmsApplicationData> applications = getApplicationCollection(context);
+        return getApplicationForPackage(applications, packageName);
+    }
+
+    /**
+     * Gets the default SMS application
+     * @param context context from the calling app
+     * @param updateIfNeeded update the default app if there is no valid default app configured.
+     * @return component name of the app and class to deliver SMS messages to
+     */
+    @UnsupportedAppUsage
+    public static ComponentName getDefaultSmsApplication(Context context, boolean updateIfNeeded) {
+        return getDefaultSmsApplicationAsUser(context, updateIfNeeded, getIncomingUserId(context));
+    }
+
+    /**
+     * Gets the default SMS application on a given user
+     * @param context context from the calling app
+     * @param updateIfNeeded update the default app if there is no valid default app configured.
+     * @param userId target user ID.
+     * @return component name of the app and class to deliver SMS messages to
+     */
+    public static ComponentName getDefaultSmsApplicationAsUser(Context context,
+            boolean updateIfNeeded, int userId) {
+        final long token = Binder.clearCallingIdentity();
+        try {
+            ComponentName component = null;
+            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
+                    userId);
+            if (smsApplicationData != null) {
+                component = new ComponentName(smsApplicationData.mPackageName,
+                        smsApplicationData.mSmsReceiverClass);
+            }
+            return component;
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    /**
+     * Gets the default MMS application
+     * @param context context from the calling app
+     * @param updateIfNeeded update the default app if there is no valid default app configured.
+     * @return component name of the app and class to deliver MMS messages to
+     */
+    @UnsupportedAppUsage
+    public static ComponentName getDefaultMmsApplication(Context context, boolean updateIfNeeded) {
+        int userId = getIncomingUserId(context);
+        final long token = Binder.clearCallingIdentity();
+        try {
+            ComponentName component = null;
+            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
+                    userId);
+            if (smsApplicationData != null) {
+                component = new ComponentName(smsApplicationData.mPackageName,
+                        smsApplicationData.mMmsReceiverClass);
+            }
+            return component;
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    /**
+     * Gets the default Respond Via Message application
+     * @param context context from the calling app
+     * @param updateIfNeeded update the default app if there is no valid default app configured.
+     * @return component name of the app and class to direct Respond Via Message intent to
+     */
+    @UnsupportedAppUsage
+    public static ComponentName getDefaultRespondViaMessageApplication(Context context,
+            boolean updateIfNeeded) {
+        int userId = getIncomingUserId(context);
+        final long token = Binder.clearCallingIdentity();
+        try {
+            ComponentName component = null;
+            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
+                    userId);
+            if (smsApplicationData != null) {
+                component = new ComponentName(smsApplicationData.mPackageName,
+                        smsApplicationData.mRespondViaMessageClass);
+            }
+            return component;
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    /**
+     * Gets the default Send To (smsto) application.
+     * <p>
+     * Caller must pass in the correct user context if calling from a singleton service.
+     * @param context context from the calling app
+     * @param updateIfNeeded update the default app if there is no valid default app configured.
+     * @return component name of the app and class to direct SEND_TO (smsto) intent to
+     */
+    public static ComponentName getDefaultSendToApplication(Context context,
+            boolean updateIfNeeded) {
+        int userId = getIncomingUserId(context);
+        final long token = Binder.clearCallingIdentity();
+        try {
+            ComponentName component = null;
+            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
+                    userId);
+            if (smsApplicationData != null) {
+                component = new ComponentName(smsApplicationData.mPackageName,
+                        smsApplicationData.mSendToClass);
+            }
+            return component;
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    /**
+     * Gets the default application that handles external changes to the SmsProvider and
+     * MmsProvider.
+     * @param context context from the calling app
+     * @param updateIfNeeded update the default app if there is no valid default app configured.
+     * @return component name of the app and class to deliver change intents to
+     */
+    public static ComponentName getDefaultExternalTelephonyProviderChangedApplication(
+            Context context, boolean updateIfNeeded) {
+        int userId = getIncomingUserId(context);
+        final long token = Binder.clearCallingIdentity();
+        try {
+            ComponentName component = null;
+            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
+                    userId);
+            if (smsApplicationData != null
+                    && smsApplicationData.mProviderChangedReceiverClass != null) {
+                component = new ComponentName(smsApplicationData.mPackageName,
+                        smsApplicationData.mProviderChangedReceiverClass);
+            }
+            return component;
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    /**
+     * Gets the default application that handles sim full event.
+     * @param context context from the calling app
+     * @param updateIfNeeded update the default app if there is no valid default app configured.
+     * @return component name of the app and class to deliver change intents to
+     */
+    public static ComponentName getDefaultSimFullApplication(
+            Context context, boolean updateIfNeeded) {
+        int userId = getIncomingUserId(context);
+        final long token = Binder.clearCallingIdentity();
+        try {
+            ComponentName component = null;
+            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
+                    userId);
+            if (smsApplicationData != null
+                    && smsApplicationData.mSimFullReceiverClass != null) {
+                component = new ComponentName(smsApplicationData.mPackageName,
+                        smsApplicationData.mSimFullReceiverClass);
+            }
+            return component;
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
+    }
+
+    /**
+     * Returns whether need to write the SMS message to SMS database for this package.
+     * <p>
+     * Caller must pass in the correct user context if calling from a singleton service.
+     */
+    @UnsupportedAppUsage
+    public static boolean shouldWriteMessageForPackage(String packageName, Context context) {
+        return !isDefaultSmsApplication(context, packageName);
+    }
+
+    /**
+     * Check if a package is default sms app (or equivalent, like bluetooth)
+     *
+     * @param context context from the calling app
+     * @param packageName the name of the package to be checked
+     * @return true if the package is default sms app or bluetooth
+     */
+    @UnsupportedAppUsage
+    public static boolean isDefaultSmsApplication(Context context, String packageName) {
+        if (packageName == null) {
+            return false;
+        }
+        final String defaultSmsPackage = getDefaultSmsApplicationPackageName(context);
+        if ((defaultSmsPackage != null && defaultSmsPackage.equals(packageName))
+                || BLUETOOTH_PACKAGE_NAME.equals(packageName)) {
+            return true;
+        }
+        return false;
+    }
+
+    private static String getDefaultSmsApplicationPackageName(Context context) {
+        final ComponentName component = getDefaultSmsApplication(context, false);
+        if (component != null) {
+            return component.getPackageName();
+        }
+        return null;
+    }
+}
diff --git a/telephony/common/com/android/internal/telephony/SmsNumberUtils.java b/telephony/common/com/android/internal/telephony/SmsNumberUtils.java
new file mode 100644
index 0000000..0d33af6
--- /dev/null
+++ b/telephony/common/com/android/internal/telephony/SmsNumberUtils.java
@@ -0,0 +1,627 @@
+/*
+ * Copyright (C) 2014 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.internal.telephony;
+
+import android.content.Context;
+import android.database.Cursor;
+import android.database.SQLException;
+import android.os.Binder;
+import android.os.Build;
+import android.os.PersistableBundle;
+import android.telephony.CarrierConfigManager;
+import android.telephony.PhoneNumberUtils;
+import android.telephony.Rlog;
+import android.telephony.TelephonyManager;
+import android.text.TextUtils;
+
+import com.android.internal.telephony.HbpcdLookup.MccIdd;
+import com.android.internal.telephony.HbpcdLookup.MccLookup;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+
+/**
+ * This class implements handle the MO SMS target address before sending.
+ * This is special for VZW requirement. Follow the specifications of assisted dialing
+ * of MO SMS while traveling on VZW CDMA, international CDMA or GSM markets.
+ * {@hide}
+ */
+public class SmsNumberUtils {
+    private static final String TAG = "SmsNumberUtils";
+    private static final boolean DBG = Build.IS_DEBUGGABLE;
+
+    private static final String PLUS_SIGN = "+";
+
+    private static final int NANP_SHORT_LENGTH = 7;
+    private static final int NANP_MEDIUM_LENGTH = 10;
+    private static final int NANP_LONG_LENGTH = 11;
+
+    private static final int NANP_CC = 1;
+    private static final String NANP_NDD = "1";
+    private static final String NANP_IDD = "011";
+
+    private static final int MIN_COUNTRY_AREA_LOCAL_LENGTH = 10;
+
+    private static final int GSM_UMTS_NETWORK = 0;
+    private static final int CDMA_HOME_NETWORK = 1;
+    private static final int CDMA_ROAMING_NETWORK = 2;
+
+    private static final int NP_NONE = 0;
+    private static final int NP_NANP_BEGIN = 1;
+
+    /* <Phone Number>, <NXX>-<XXXX> N[2-9] */
+    private static final int NP_NANP_LOCAL = NP_NANP_BEGIN;
+
+    /* <Area_code>-<Phone Number>, <NXX>-<NXX>-<XXXX> N[2-9] */
+    private static final int NP_NANP_AREA_LOCAL = NP_NANP_BEGIN + 1;
+
+    /* <1>-<Area_code>-<Phone Number>, 1-<NXX>-<NXX>-<XXXX> N[2-9] */
+    private static final int NP_NANP_NDD_AREA_LOCAL = NP_NANP_BEGIN + 2;
+
+    /* <+><U.S.Country_code><Area_code><Phone Number>, +1-<NXX>-<NXX>-<XXXX> N[2-9] */
+    private static final int NP_NANP_NBPCD_CC_AREA_LOCAL = NP_NANP_BEGIN + 3;
+
+    /* <Local_IDD><Country_code><Area_code><Phone Number>, 001-1-<NXX>-<NXX>-<XXXX> N[2-9] */
+    private static final int NP_NANP_LOCALIDD_CC_AREA_LOCAL = NP_NANP_BEGIN + 4;
+
+    /* <+><Home_IDD><Country_code><Area_code><Phone Number>, +011-1-<NXX>-<NXX>-<XXXX> N[2-9] */
+    private static final int NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL = NP_NANP_BEGIN + 5;
+
+    private static final int NP_INTERNATIONAL_BEGIN = 100;
+    /* <+>-<Home_IDD>-<Country_code>-<Area_code>-<Phone Number>, +011-86-25-86281234 */
+    private static final int NP_NBPCD_HOMEIDD_CC_AREA_LOCAL = NP_INTERNATIONAL_BEGIN;
+
+    /* <Home_IDD>-<Country_code>-<Area_code>-<Phone Number>, 011-86-25-86281234 */
+    private static final int NP_HOMEIDD_CC_AREA_LOCAL = NP_INTERNATIONAL_BEGIN + 1;
+
+    /* <NBPCD>-<Country_code>-<Area_code>-<Phone Number>, +1-86-25-86281234 */
+    private static final int NP_NBPCD_CC_AREA_LOCAL = NP_INTERNATIONAL_BEGIN + 2;
+
+    /* <Local_IDD>-<Country_code>-<Area_code>-<Phone Number>, 00-86-25-86281234 */
+    private static final int NP_LOCALIDD_CC_AREA_LOCAL = NP_INTERNATIONAL_BEGIN + 3;
+
+    /* <Country_code>-<Area_code>-<Phone Number>, 86-25-86281234*/
+    private static final int NP_CC_AREA_LOCAL = NP_INTERNATIONAL_BEGIN + 4;
+
+    private static int[] ALL_COUNTRY_CODES = null;
+    private static int MAX_COUNTRY_CODES_LENGTH;
+    private static HashMap<String, ArrayList<String>> IDDS_MAPS =
+            new HashMap<String, ArrayList<String>>();
+
+    private static class NumberEntry {
+        public String number;
+        public String IDD;
+        public int countryCode;
+        public NumberEntry(String number) {
+            this.number = number;
+        }
+    }
+
+    /**
+     * Breaks the given number down and formats it according to the rules
+     * for different number plans and different network.
+     *
+     * @param number destination number which need to be format
+     * @param activeMcc current network's mcc
+     * @param networkType current network type
+     *
+     * @return the number after formatting.
+     */
+    private static String formatNumber(Context context, String number,
+                               String activeMcc,
+                               int networkType) {
+        if (number == null ) {
+            throw new IllegalArgumentException("number is null");
+        }
+
+        if (activeMcc == null || activeMcc.trim().length() == 0) {
+            throw new IllegalArgumentException("activeMcc is null or empty!");
+        }
+
+        String networkPortionNumber = PhoneNumberUtils.extractNetworkPortion(number);
+        if (networkPortionNumber == null || networkPortionNumber.length() == 0) {
+            throw new IllegalArgumentException("Number is invalid!");
+        }
+
+        NumberEntry numberEntry = new NumberEntry(networkPortionNumber);
+        ArrayList<String> allIDDs = getAllIDDs(context, activeMcc);
+
+        // First check whether the number is a NANP number.
+        int nanpState = checkNANP(numberEntry, allIDDs);
+        if (DBG) Rlog.d(TAG, "NANP type: " + getNumberPlanType(nanpState));
+
+        if ((nanpState == NP_NANP_LOCAL)
+            || (nanpState == NP_NANP_AREA_LOCAL)
+            || (nanpState == NP_NANP_NDD_AREA_LOCAL)) {
+            return networkPortionNumber;
+        } else if (nanpState == NP_NANP_NBPCD_CC_AREA_LOCAL) {
+            if (networkType == CDMA_HOME_NETWORK
+                    || networkType == CDMA_ROAMING_NETWORK) {
+                // Remove "+"
+                return networkPortionNumber.substring(1);
+            } else {
+                return networkPortionNumber;
+            }
+        } else if (nanpState == NP_NANP_LOCALIDD_CC_AREA_LOCAL) {
+            if (networkType == CDMA_HOME_NETWORK) {
+                return networkPortionNumber;
+            } else if (networkType == GSM_UMTS_NETWORK) {
+                // Remove the local IDD and replace with "+"
+                int iddLength  =  numberEntry.IDD != null ? numberEntry.IDD.length() : 0;
+                return PLUS_SIGN + networkPortionNumber.substring(iddLength);
+            } else if (networkType == CDMA_ROAMING_NETWORK) {
+                // Remove the local IDD
+                int iddLength  =  numberEntry.IDD != null ? numberEntry.IDD.length() : 0;
+                return  networkPortionNumber.substring(iddLength);
+            }
+        }
+
+        int internationalState = checkInternationalNumberPlan(context, numberEntry, allIDDs,
+                NANP_IDD);
+        if (DBG) Rlog.d(TAG, "International type: " + getNumberPlanType(internationalState));
+        String returnNumber = null;
+
+        switch (internationalState) {
+            case NP_NBPCD_HOMEIDD_CC_AREA_LOCAL:
+                if (networkType == GSM_UMTS_NETWORK) {
+                    // Remove "+"
+                    returnNumber = networkPortionNumber.substring(1);
+                }
+                break;
+
+            case NP_NBPCD_CC_AREA_LOCAL:
+                // Replace "+" with "011"
+                returnNumber = NANP_IDD + networkPortionNumber.substring(1);
+                break;
+
+            case NP_LOCALIDD_CC_AREA_LOCAL:
+                if (networkType == GSM_UMTS_NETWORK || networkType == CDMA_ROAMING_NETWORK) {
+                    int iddLength  =  numberEntry.IDD != null ? numberEntry.IDD.length() : 0;
+                    // Replace <Local IDD> to <Home IDD>("011")
+                    returnNumber = NANP_IDD + networkPortionNumber.substring(iddLength);
+                }
+                break;
+
+            case NP_CC_AREA_LOCAL:
+                int countryCode = numberEntry.countryCode;
+
+                if (!inExceptionListForNpCcAreaLocal(numberEntry)
+                    && networkPortionNumber.length() >= 11 && countryCode != NANP_CC) {
+                    // Add "011"
+                    returnNumber = NANP_IDD + networkPortionNumber;
+                }
+                break;
+
+            case NP_HOMEIDD_CC_AREA_LOCAL:
+                returnNumber = networkPortionNumber;
+                break;
+
+            default:
+                // Replace "+" with 011 in CDMA network if the number's country
+                // code is not in the HbpcdLookup database.
+                if (networkPortionNumber.startsWith(PLUS_SIGN)
+                    && (networkType == CDMA_HOME_NETWORK || networkType == CDMA_ROAMING_NETWORK)) {
+                    if (networkPortionNumber.startsWith(PLUS_SIGN + NANP_IDD)) {
+                        // Only remove "+"
+                        returnNumber = networkPortionNumber.substring(1);
+                    } else {
+                        // Replace "+" with "011"
+                        returnNumber = NANP_IDD + networkPortionNumber.substring(1);
+                    }
+                }
+        }
+
+        if (returnNumber == null) {
+            returnNumber = networkPortionNumber;
+        }
+        return returnNumber;
+    }
+
+    /**
+     * Query International direct dialing from HbpcdLookup.db
+     * for specified country code
+     *
+     * @param mcc current network's country code
+     *
+     * @return the IDD array list.
+     */
+    private static ArrayList<String> getAllIDDs(Context context, String mcc) {
+        ArrayList<String> allIDDs = IDDS_MAPS.get(mcc);
+        if (allIDDs != null) {
+            return allIDDs;
+        } else {
+            allIDDs = new ArrayList<String>();
+        }
+
+        String projection[] = {MccIdd.IDD, MccIdd.MCC};
+        String where = null;
+
+        // if mcc is null         : return all rows
+        // if mcc is empty-string : return those rows whose mcc is emptry-string
+        String[] selectionArgs = null;
+        if (mcc != null) {
+            where = MccIdd.MCC + "=?";
+            selectionArgs = new String[] {mcc};
+        }
+
+        Cursor cursor = null;
+        try {
+            cursor = context.getContentResolver().query(MccIdd.CONTENT_URI, projection,
+                    where, selectionArgs, null);
+            if (cursor.getCount() > 0) {
+                while (cursor.moveToNext()) {
+                    String idd = cursor.getString(0);
+                    if (!allIDDs.contains(idd)) {
+                        allIDDs.add(idd);
+                    }
+                }
+            }
+        } catch (SQLException e) {
+            Rlog.e(TAG, "Can't access HbpcdLookup database", e);
+        } finally {
+            if (cursor != null) {
+                cursor.close();
+            }
+        }
+
+        IDDS_MAPS.put(mcc, allIDDs);
+
+        if (DBG) Rlog.d(TAG, "MCC = " + mcc + ", all IDDs = " + allIDDs);
+        return allIDDs;
+    }
+
+
+    /**
+     * Verify if the the destination number is a NANP number
+     *
+     * @param numberEntry including number and IDD array
+     * @param allIDDs the IDD array list of the current network's country code
+     *
+     * @return the number plan type related NANP
+     */
+    private static int checkNANP(NumberEntry numberEntry, ArrayList<String> allIDDs) {
+        boolean isNANP = false;
+        String number = numberEntry.number;
+
+        if (number.length() == NANP_SHORT_LENGTH) {
+            // 7 digits - Seven digit phone numbers
+            char firstChar = number.charAt(0);
+            if (firstChar >= '2' && firstChar <= '9') {
+                isNANP = true;
+                for (int i=1; i< NANP_SHORT_LENGTH; i++ ) {
+                    char c= number.charAt(i);
+                    if (!PhoneNumberUtils.isISODigit(c)) {
+                        isNANP = false;
+                        break;
+                    }
+                }
+            }
+            if (isNANP) {
+                return NP_NANP_LOCAL;
+            }
+        } else if (number.length() == NANP_MEDIUM_LENGTH) {
+            // 10 digits - Three digit area code followed by seven digit phone numbers/
+            if (isNANP(number)) {
+                return NP_NANP_AREA_LOCAL;
+            }
+        } else if (number.length() == NANP_LONG_LENGTH) {
+            // 11 digits - One digit U.S. NDD(National Direct Dial) prefix '1',
+            // followed by three digit area code and seven digit phone numbers
+            if (isNANP(number)) {
+                return NP_NANP_NDD_AREA_LOCAL;
+            }
+        } else if (number.startsWith(PLUS_SIGN)) {
+            number = number.substring(1);
+            if (number.length() == NANP_LONG_LENGTH) {
+                // '+' and 11 digits -'+', followed by NANP CC prefix '1' followed by
+                // three digit area code and seven digit phone numbers
+                if (isNANP(number)) {
+                    return NP_NANP_NBPCD_CC_AREA_LOCAL;
+                }
+            } else if (number.startsWith(NANP_IDD) && number.length() == NANP_LONG_LENGTH + 3) {
+                // '+' and 14 digits -'+', followed by NANP IDD "011" followed by NANP CC
+                // prefix '1' followed by three digit area code and seven digit phone numbers
+                number = number.substring(3);
+                if (isNANP(number)) {
+                    return NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL;
+                }
+            }
+        } else {
+            // Check whether it's NP_NANP_LOCALIDD_CC_AREA_LOCAL
+            for (String idd : allIDDs) {
+                if (number.startsWith(idd)) {
+                    String number2 = number.substring(idd.length());
+                    if(number2 !=null && number2.startsWith(String.valueOf(NANP_CC))){
+                        if (isNANP(number2)) {
+                            numberEntry.IDD = idd;
+                            return NP_NANP_LOCALIDD_CC_AREA_LOCAL;
+                        }
+                    }
+                }
+            }
+        }
+
+        return NP_NONE;
+    }
+
+    private static boolean isNANP(String number) {
+        if (number.length() == NANP_MEDIUM_LENGTH
+            || (number.length() == NANP_LONG_LENGTH  && number.startsWith(NANP_NDD))) {
+            if (number.length() == NANP_LONG_LENGTH) {
+                number = number.substring(1);
+            }
+            return (PhoneNumberUtils.isNanp(number));
+        }
+        return false;
+    }
+
+    /**
+     * Verify if the the destination number is an internal number
+     *
+     * @param numberEntry including number and IDD array
+     * @param allIDDs the IDD array list of the current network's country code
+     *
+     * @return the number plan type related international number
+     */
+    private static int checkInternationalNumberPlan(Context context, NumberEntry numberEntry,
+            ArrayList<String> allIDDs,String homeIDD) {
+        String number = numberEntry.number;
+        int countryCode = -1;
+
+        if (number.startsWith(PLUS_SIGN)) {
+            // +xxxxxxxxxx
+            String numberNoNBPCD = number.substring(1);
+            if (numberNoNBPCD.startsWith(homeIDD)) {
+                // +011xxxxxxxx
+                String numberCountryAreaLocal = numberNoNBPCD.substring(homeIDD.length());
+                if ((countryCode = getCountryCode(context, numberCountryAreaLocal)) > 0) {
+                    numberEntry.countryCode = countryCode;
+                    return NP_NBPCD_HOMEIDD_CC_AREA_LOCAL;
+                }
+            } else if ((countryCode = getCountryCode(context, numberNoNBPCD)) > 0) {
+                numberEntry.countryCode = countryCode;
+                return NP_NBPCD_CC_AREA_LOCAL;
+            }
+
+        } else if (number.startsWith(homeIDD)) {
+            // 011xxxxxxxxx
+            String numberCountryAreaLocal = number.substring(homeIDD.length());
+            if ((countryCode = getCountryCode(context, numberCountryAreaLocal)) > 0) {
+                numberEntry.countryCode = countryCode;
+                return NP_HOMEIDD_CC_AREA_LOCAL;
+            }
+        } else {
+            for (String exitCode : allIDDs) {
+                if (number.startsWith(exitCode)) {
+                    String numberNoIDD = number.substring(exitCode.length());
+                    if ((countryCode = getCountryCode(context, numberNoIDD)) > 0) {
+                        numberEntry.countryCode = countryCode;
+                        numberEntry.IDD = exitCode;
+                        return NP_LOCALIDD_CC_AREA_LOCAL;
+                    }
+                }
+            }
+
+            if (!number.startsWith("0") && (countryCode = getCountryCode(context, number)) > 0) {
+                numberEntry.countryCode = countryCode;
+                return NP_CC_AREA_LOCAL;
+            }
+        }
+        return NP_NONE;
+    }
+
+    /**
+     *  Returns the country code from the given number.
+     */
+    private static int getCountryCode(Context context, String number) {
+        int countryCode = -1;
+        if (number.length() >= MIN_COUNTRY_AREA_LOCAL_LENGTH) {
+            // Check Country code
+            int[] allCCs = getAllCountryCodes(context);
+            if (allCCs == null) {
+                return countryCode;
+            }
+
+            int[] ccArray = new int[MAX_COUNTRY_CODES_LENGTH];
+            for (int i = 0; i < MAX_COUNTRY_CODES_LENGTH; i ++) {
+                ccArray[i] = Integer.parseInt(number.substring(0, i+1));
+            }
+
+            for (int i = 0; i < allCCs.length; i ++) {
+                int tempCC = allCCs[i];
+                for (int j = 0; j < MAX_COUNTRY_CODES_LENGTH; j ++) {
+                    if (tempCC == ccArray[j]) {
+                        if (DBG) Rlog.d(TAG, "Country code = " + tempCC);
+                        return tempCC;
+                    }
+                }
+            }
+        }
+
+        return countryCode;
+    }
+
+    /**
+     *  Gets all country Codes information with given MCC.
+     */
+    private static int[] getAllCountryCodes(Context context) {
+        if (ALL_COUNTRY_CODES != null) {
+            return ALL_COUNTRY_CODES;
+        }
+
+        Cursor cursor = null;
+        try {
+            String projection[] = {MccLookup.COUNTRY_CODE};
+            cursor = context.getContentResolver().query(MccLookup.CONTENT_URI,
+                    projection, null, null, null);
+
+            if (cursor.getCount() > 0) {
+                ALL_COUNTRY_CODES = new int[cursor.getCount()];
+                int i = 0;
+                while (cursor.moveToNext()) {
+                    int countryCode = cursor.getInt(0);
+                    ALL_COUNTRY_CODES[i++] = countryCode;
+                    int length = String.valueOf(countryCode).trim().length();
+                    if (length > MAX_COUNTRY_CODES_LENGTH) {
+                        MAX_COUNTRY_CODES_LENGTH = length;
+                    }
+                }
+            }
+        } catch (SQLException e) {
+            Rlog.e(TAG, "Can't access HbpcdLookup database", e);
+        } finally {
+            if (cursor != null) {
+                cursor.close();
+            }
+        }
+        return ALL_COUNTRY_CODES;
+    }
+
+    private static boolean inExceptionListForNpCcAreaLocal(NumberEntry numberEntry) {
+        int countryCode = numberEntry.countryCode;
+        boolean result = (numberEntry.number.length() == 12
+                          && (countryCode == 7 || countryCode == 20
+                              || countryCode == 65 || countryCode == 90));
+        return result;
+    }
+
+    private static String getNumberPlanType(int state) {
+        String numberPlanType = "Number Plan type (" + state + "): ";
+
+        if (state == NP_NANP_LOCAL) {
+            numberPlanType = "NP_NANP_LOCAL";
+        } else if (state == NP_NANP_AREA_LOCAL) {
+            numberPlanType = "NP_NANP_AREA_LOCAL";
+        } else if (state  == NP_NANP_NDD_AREA_LOCAL) {
+            numberPlanType = "NP_NANP_NDD_AREA_LOCAL";
+        } else if (state == NP_NANP_NBPCD_CC_AREA_LOCAL) {
+            numberPlanType = "NP_NANP_NBPCD_CC_AREA_LOCAL";
+        } else if (state == NP_NANP_LOCALIDD_CC_AREA_LOCAL) {
+            numberPlanType = "NP_NANP_LOCALIDD_CC_AREA_LOCAL";
+        } else if (state == NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL) {
+            numberPlanType = "NP_NANP_NBPCD_HOMEIDD_CC_AREA_LOCAL";
+        } else if (state == NP_NBPCD_HOMEIDD_CC_AREA_LOCAL) {
+            numberPlanType = "NP_NBPCD_HOMEIDD_CC_AREA_LOCAL";
+        } else if (state == NP_HOMEIDD_CC_AREA_LOCAL) {
+            numberPlanType = "NP_HOMEIDD_CC_AREA_LOCAL";
+        } else if (state == NP_NBPCD_CC_AREA_LOCAL) {
+            numberPlanType = "NP_NBPCD_CC_AREA_LOCAL";
+        } else if (state == NP_LOCALIDD_CC_AREA_LOCAL) {
+            numberPlanType = "NP_LOCALIDD_CC_AREA_LOCAL";
+        } else if (state == NP_CC_AREA_LOCAL) {
+            numberPlanType = "NP_CC_AREA_LOCAL";
+        } else {
+            numberPlanType = "Unknown type";
+        }
+        return numberPlanType;
+    }
+
+    /**
+     * Filter the destination number if using VZW sim card.
+     */
+    public static String filterDestAddr(Context context, int subId, String destAddr) {
+        if (DBG) Rlog.d(TAG, "enter filterDestAddr. destAddr=\"" + Rlog.pii(TAG, destAddr) + "\"" );
+
+        if (destAddr == null || !PhoneNumberUtils.isGlobalPhoneNumber(destAddr)) {
+            Rlog.w(TAG, "destAddr" + Rlog.pii(TAG, destAddr) +
+                    " is not a global phone number! Nothing changed.");
+            return destAddr;
+        }
+
+        final TelephonyManager telephonyManager = ((TelephonyManager) context
+                .getSystemService(Context.TELEPHONY_SERVICE)).createForSubscriptionId(subId);
+        final String networkOperator = telephonyManager.getNetworkOperator();
+        String result = null;
+
+        if (needToConvert(context, subId)) {
+            final int networkType = getNetworkType(telephonyManager);
+            if (networkType != -1 && !TextUtils.isEmpty(networkOperator)) {
+                String networkMcc = networkOperator.substring(0, 3);
+                if (networkMcc != null && networkMcc.trim().length() > 0) {
+                    result = formatNumber(context, destAddr, networkMcc, networkType);
+                }
+            }
+        }
+
+        if (DBG) {
+            Rlog.d(TAG, "destAddr is " + ((result != null)?"formatted.":"not formatted."));
+            Rlog.d(TAG, "leave filterDestAddr, new destAddr=\"" + (result != null ? Rlog.pii(TAG,
+                    result) : Rlog.pii(TAG, destAddr)) + "\"");
+        }
+        return result != null ? result : destAddr;
+    }
+
+    /**
+     * Returns the current network type
+     */
+    private static int getNetworkType(TelephonyManager telephonyManager) {
+        int networkType = -1;
+        int phoneType = telephonyManager.getPhoneType();
+
+        if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
+            networkType = GSM_UMTS_NETWORK;
+        } else if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
+            if (isInternationalRoaming(telephonyManager)) {
+                networkType = CDMA_ROAMING_NETWORK;
+            } else {
+                networkType = CDMA_HOME_NETWORK;
+            }
+        } else {
+            if (DBG) Rlog.w(TAG, "warning! unknown mPhoneType value=" + phoneType);
+        }
+
+        return networkType;
+    }
+
+    private static boolean isInternationalRoaming(TelephonyManager telephonyManager) {
+        String operatorIsoCountry = telephonyManager.getNetworkCountryIso();
+        String simIsoCountry = telephonyManager.getSimCountryIso();
+        boolean internationalRoaming = !TextUtils.isEmpty(operatorIsoCountry)
+                && !TextUtils.isEmpty(simIsoCountry)
+                && !simIsoCountry.equals(operatorIsoCountry);
+        if (internationalRoaming) {
+            if ("us".equals(simIsoCountry)) {
+                internationalRoaming = !"vi".equals(operatorIsoCountry);
+            } else if ("vi".equals(simIsoCountry)) {
+                internationalRoaming = !"us".equals(operatorIsoCountry);
+            }
+        }
+        return internationalRoaming;
+    }
+
+    private static boolean needToConvert(Context context, int subId) {
+        // Calling package may not have READ_PHONE_STATE which is required for getConfig().
+        // Clear the calling identity so that it is called as self.
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            CarrierConfigManager configManager = (CarrierConfigManager)
+                    context.getSystemService(Context.CARRIER_CONFIG_SERVICE);
+            if (configManager != null) {
+                PersistableBundle bundle = configManager.getConfigForSubId(subId);
+                if (bundle != null) {
+                    return bundle.getBoolean(CarrierConfigManager
+                            .KEY_SMS_REQUIRES_DESTINATION_NUMBER_CONVERSION_BOOL);
+                }
+            }
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+        // by default this value is false
+        return false;
+    }
+}
diff --git a/telephony/java/com/google/android/mms/ContentType.java b/telephony/common/com/google/android/mms/ContentType.java
similarity index 100%
rename from telephony/java/com/google/android/mms/ContentType.java
rename to telephony/common/com/google/android/mms/ContentType.java
diff --git a/telephony/java/com/google/android/mms/InvalidHeaderValueException.java b/telephony/common/com/google/android/mms/InvalidHeaderValueException.java
similarity index 100%
rename from telephony/java/com/google/android/mms/InvalidHeaderValueException.java
rename to telephony/common/com/google/android/mms/InvalidHeaderValueException.java
diff --git a/telephony/java/com/google/android/mms/MmsException.java b/telephony/common/com/google/android/mms/MmsException.java
similarity index 100%
rename from telephony/java/com/google/android/mms/MmsException.java
rename to telephony/common/com/google/android/mms/MmsException.java
diff --git a/telephony/java/com/google/android/mms/package.html b/telephony/common/com/google/android/mms/package.html
similarity index 100%
rename from telephony/java/com/google/android/mms/package.html
rename to telephony/common/com/google/android/mms/package.html
diff --git a/telephony/java/com/google/android/mms/pdu/AcknowledgeInd.java b/telephony/common/com/google/android/mms/pdu/AcknowledgeInd.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/AcknowledgeInd.java
rename to telephony/common/com/google/android/mms/pdu/AcknowledgeInd.java
diff --git a/telephony/java/com/google/android/mms/pdu/Base64.java b/telephony/common/com/google/android/mms/pdu/Base64.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/Base64.java
rename to telephony/common/com/google/android/mms/pdu/Base64.java
diff --git a/telephony/java/com/google/android/mms/pdu/CharacterSets.java b/telephony/common/com/google/android/mms/pdu/CharacterSets.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/CharacterSets.java
rename to telephony/common/com/google/android/mms/pdu/CharacterSets.java
diff --git a/telephony/java/com/google/android/mms/pdu/DeliveryInd.java b/telephony/common/com/google/android/mms/pdu/DeliveryInd.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/DeliveryInd.java
rename to telephony/common/com/google/android/mms/pdu/DeliveryInd.java
diff --git a/telephony/java/com/google/android/mms/pdu/EncodedStringValue.java b/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/EncodedStringValue.java
rename to telephony/common/com/google/android/mms/pdu/EncodedStringValue.java
diff --git a/telephony/java/com/google/android/mms/pdu/GenericPdu.java b/telephony/common/com/google/android/mms/pdu/GenericPdu.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/GenericPdu.java
rename to telephony/common/com/google/android/mms/pdu/GenericPdu.java
diff --git a/telephony/java/com/google/android/mms/pdu/MultimediaMessagePdu.java b/telephony/common/com/google/android/mms/pdu/MultimediaMessagePdu.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/MultimediaMessagePdu.java
rename to telephony/common/com/google/android/mms/pdu/MultimediaMessagePdu.java
diff --git a/telephony/java/com/google/android/mms/pdu/NotificationInd.java b/telephony/common/com/google/android/mms/pdu/NotificationInd.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/NotificationInd.java
rename to telephony/common/com/google/android/mms/pdu/NotificationInd.java
diff --git a/telephony/java/com/google/android/mms/pdu/NotifyRespInd.java b/telephony/common/com/google/android/mms/pdu/NotifyRespInd.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/NotifyRespInd.java
rename to telephony/common/com/google/android/mms/pdu/NotifyRespInd.java
diff --git a/telephony/java/com/google/android/mms/pdu/PduBody.java b/telephony/common/com/google/android/mms/pdu/PduBody.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/PduBody.java
rename to telephony/common/com/google/android/mms/pdu/PduBody.java
diff --git a/telephony/java/com/google/android/mms/pdu/PduComposer.java b/telephony/common/com/google/android/mms/pdu/PduComposer.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/PduComposer.java
rename to telephony/common/com/google/android/mms/pdu/PduComposer.java
diff --git a/telephony/java/com/google/android/mms/pdu/PduContentTypes.java b/telephony/common/com/google/android/mms/pdu/PduContentTypes.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/PduContentTypes.java
rename to telephony/common/com/google/android/mms/pdu/PduContentTypes.java
diff --git a/telephony/java/com/google/android/mms/pdu/PduHeaders.java b/telephony/common/com/google/android/mms/pdu/PduHeaders.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/PduHeaders.java
rename to telephony/common/com/google/android/mms/pdu/PduHeaders.java
diff --git a/telephony/java/com/google/android/mms/pdu/PduParser.java b/telephony/common/com/google/android/mms/pdu/PduParser.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/PduParser.java
rename to telephony/common/com/google/android/mms/pdu/PduParser.java
diff --git a/telephony/java/com/google/android/mms/pdu/PduPart.java b/telephony/common/com/google/android/mms/pdu/PduPart.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/PduPart.java
rename to telephony/common/com/google/android/mms/pdu/PduPart.java
diff --git a/telephony/java/com/google/android/mms/pdu/PduPersister.java b/telephony/common/com/google/android/mms/pdu/PduPersister.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/PduPersister.java
rename to telephony/common/com/google/android/mms/pdu/PduPersister.java
diff --git a/telephony/java/com/google/android/mms/pdu/QuotedPrintable.java b/telephony/common/com/google/android/mms/pdu/QuotedPrintable.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/QuotedPrintable.java
rename to telephony/common/com/google/android/mms/pdu/QuotedPrintable.java
diff --git a/telephony/java/com/google/android/mms/pdu/ReadOrigInd.java b/telephony/common/com/google/android/mms/pdu/ReadOrigInd.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/ReadOrigInd.java
rename to telephony/common/com/google/android/mms/pdu/ReadOrigInd.java
diff --git a/telephony/java/com/google/android/mms/pdu/ReadRecInd.java b/telephony/common/com/google/android/mms/pdu/ReadRecInd.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/ReadRecInd.java
rename to telephony/common/com/google/android/mms/pdu/ReadRecInd.java
diff --git a/telephony/java/com/google/android/mms/pdu/RetrieveConf.java b/telephony/common/com/google/android/mms/pdu/RetrieveConf.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/RetrieveConf.java
rename to telephony/common/com/google/android/mms/pdu/RetrieveConf.java
diff --git a/telephony/java/com/google/android/mms/pdu/SendConf.java b/telephony/common/com/google/android/mms/pdu/SendConf.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/SendConf.java
rename to telephony/common/com/google/android/mms/pdu/SendConf.java
diff --git a/telephony/java/com/google/android/mms/pdu/SendReq.java b/telephony/common/com/google/android/mms/pdu/SendReq.java
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/SendReq.java
rename to telephony/common/com/google/android/mms/pdu/SendReq.java
diff --git a/telephony/java/com/google/android/mms/pdu/package.html b/telephony/common/com/google/android/mms/pdu/package.html
similarity index 100%
rename from telephony/java/com/google/android/mms/pdu/package.html
rename to telephony/common/com/google/android/mms/pdu/package.html
diff --git a/telephony/java/com/google/android/mms/util/AbstractCache.java b/telephony/common/com/google/android/mms/util/AbstractCache.java
similarity index 100%
rename from telephony/java/com/google/android/mms/util/AbstractCache.java
rename to telephony/common/com/google/android/mms/util/AbstractCache.java
diff --git a/telephony/java/com/google/android/mms/util/DownloadDrmHelper.java b/telephony/common/com/google/android/mms/util/DownloadDrmHelper.java
similarity index 100%
rename from telephony/java/com/google/android/mms/util/DownloadDrmHelper.java
rename to telephony/common/com/google/android/mms/util/DownloadDrmHelper.java
diff --git a/telephony/java/com/google/android/mms/util/DrmConvertSession.java b/telephony/common/com/google/android/mms/util/DrmConvertSession.java
similarity index 100%
rename from telephony/java/com/google/android/mms/util/DrmConvertSession.java
rename to telephony/common/com/google/android/mms/util/DrmConvertSession.java
diff --git a/telephony/java/com/google/android/mms/util/PduCache.java b/telephony/common/com/google/android/mms/util/PduCache.java
similarity index 100%
rename from telephony/java/com/google/android/mms/util/PduCache.java
rename to telephony/common/com/google/android/mms/util/PduCache.java
diff --git a/telephony/java/com/google/android/mms/util/PduCacheEntry.java b/telephony/common/com/google/android/mms/util/PduCacheEntry.java
similarity index 100%
rename from telephony/java/com/google/android/mms/util/PduCacheEntry.java
rename to telephony/common/com/google/android/mms/util/PduCacheEntry.java
diff --git a/telephony/java/com/google/android/mms/util/SqliteWrapper.java b/telephony/common/com/google/android/mms/util/SqliteWrapper.java
similarity index 100%
rename from telephony/java/com/google/android/mms/util/SqliteWrapper.java
rename to telephony/common/com/google/android/mms/util/SqliteWrapper.java
diff --git a/telephony/java/com/google/android/mms/util/package.html b/telephony/common/com/google/android/mms/util/package.html
similarity index 100%
rename from telephony/java/com/google/android/mms/util/package.html
rename to telephony/common/com/google/android/mms/util/package.html
diff --git a/telephony/java/android/provider/Telephony.java b/telephony/java/android/provider/Telephony.java
index 67b252e..bc29b59 100644
--- a/telephony/java/android/provider/Telephony.java
+++ b/telephony/java/android/provider/Telephony.java
@@ -3962,13 +3962,21 @@
         public static final Uri CONTENT_URI = Uri.parse("content://cellbroadcasts");
 
         /**
-         * The id of the subscription which received this cell broadcast message.
+         * The subscription which received this cell broadcast message.
+         * @deprecated use {@link #SLOT_INDEX} instead.
          * <P>Type: INTEGER</P>
          * @hide
          */
         public static final String SUB_ID = "sub_id";
 
         /**
+         * The slot which received this cell broadcast message.
+         * <P>Type: INTEGER</P>
+         * @hide
+         */
+        public static final String SLOT_INDEX = "slot_index";
+
+        /**
          * Message geographical scope. Valid values are:
          * <ul>
          * <li>{@link android.telephony.SmsCbMessage#GEOGRAPHICAL_SCOPE_CELL_WIDE}. meaning the
@@ -4202,7 +4210,7 @@
         public static final String MAXIMUM_WAIT_TIME = "maximum_wait_time";
 
         /**
-         * Query columns for instantiating {@link android.telephony.CellBroadcastMessage} objects.
+         * Query columns for instantiating com.android.cellbroadcastreceiver.CellBroadcastMessage.
          * @hide
          */
         @NonNull
@@ -4235,6 +4243,7 @@
          */
         public static final String[] QUERY_COLUMNS_FWK = {
                 _ID,
+                SLOT_INDEX,
                 GEOGRAPHICAL_SCOPE,
                 PLMN,
                 LAC,
diff --git a/telephony/java/android/telephony/Annotation.java b/telephony/java/android/telephony/Annotation.java
new file mode 100644
index 0000000..72f758e
--- /dev/null
+++ b/telephony/java/android/telephony/Annotation.java
@@ -0,0 +1,512 @@
+package android.telephony;
+
+import android.annotation.IntDef;
+import android.telephony.data.ApnSetting;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Telephony Annotations.
+ * Telephony sdk is a mainline module and others cannot reference hidden @IntDef. Moving some
+ * telephony annotations to a separate class to allow others statically link to it.
+ *
+ * @hide
+ */
+public class Annotation {
+    @IntDef(prefix = {"DATA_"}, value = {
+            TelephonyManager.DATA_ACTIVITY_NONE,
+            TelephonyManager.DATA_ACTIVITY_IN,
+            TelephonyManager.DATA_ACTIVITY_OUT,
+            TelephonyManager.DATA_ACTIVITY_INOUT,
+            TelephonyManager.DATA_ACTIVITY_DORMANT,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface DataActivityType {
+    }
+
+    @IntDef(prefix = {"DATA_"}, value = {
+            TelephonyManager.DATA_UNKNOWN,
+            TelephonyManager.DATA_DISCONNECTED,
+            TelephonyManager.DATA_CONNECTING,
+            TelephonyManager.DATA_CONNECTED,
+            TelephonyManager.DATA_SUSPENDED,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface DataState {
+    }
+
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(prefix = {"RADIO_POWER_"},
+            value = {
+                    TelephonyManager.RADIO_POWER_OFF,
+                    TelephonyManager.RADIO_POWER_ON,
+                    TelephonyManager.RADIO_POWER_UNAVAILABLE,
+            })
+    public @interface RadioPowerState {
+    }
+
+    @IntDef({
+            TelephonyManager.SIM_ACTIVATION_STATE_UNKNOWN,
+            TelephonyManager.SIM_ACTIVATION_STATE_ACTIVATING,
+            TelephonyManager.SIM_ACTIVATION_STATE_ACTIVATED,
+            TelephonyManager.SIM_ACTIVATION_STATE_DEACTIVATED,
+            TelephonyManager.SIM_ACTIVATION_STATE_RESTRICTED
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface SimActivationState {
+    }
+
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(prefix = {"SRVCC_STATE_"},
+            value = {
+                    TelephonyManager.SRVCC_STATE_HANDOVER_NONE,
+                    TelephonyManager.SRVCC_STATE_HANDOVER_STARTED,
+                    TelephonyManager.SRVCC_STATE_HANDOVER_COMPLETED,
+                    TelephonyManager.SRVCC_STATE_HANDOVER_FAILED,
+                    TelephonyManager.SRVCC_STATE_HANDOVER_CANCELED})
+    public @interface SrvccState {
+    }
+
+    @IntDef(prefix = {"CALL_STATE_"}, value = {
+            TelephonyManager.CALL_STATE_IDLE,
+            TelephonyManager.CALL_STATE_RINGING,
+            TelephonyManager.CALL_STATE_OFFHOOK
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface CallState {
+    }
+
+    @IntDef({
+            TelephonyManager.NETWORK_TYPE_UNKNOWN,
+            TelephonyManager.NETWORK_TYPE_GPRS,
+            TelephonyManager.NETWORK_TYPE_EDGE,
+            TelephonyManager.NETWORK_TYPE_UMTS,
+            TelephonyManager.NETWORK_TYPE_CDMA,
+            TelephonyManager.NETWORK_TYPE_EVDO_0,
+            TelephonyManager.NETWORK_TYPE_EVDO_A,
+            TelephonyManager.NETWORK_TYPE_1xRTT,
+            TelephonyManager.NETWORK_TYPE_HSDPA,
+            TelephonyManager.NETWORK_TYPE_HSUPA,
+            TelephonyManager.NETWORK_TYPE_HSPA,
+            TelephonyManager.NETWORK_TYPE_IDEN,
+            TelephonyManager.NETWORK_TYPE_EVDO_B,
+            TelephonyManager.NETWORK_TYPE_LTE,
+            TelephonyManager.NETWORK_TYPE_EHRPD,
+            TelephonyManager.NETWORK_TYPE_HSPAP,
+            TelephonyManager.NETWORK_TYPE_GSM,
+            TelephonyManager.NETWORK_TYPE_TD_SCDMA,
+            TelephonyManager.NETWORK_TYPE_IWLAN,
+            TelephonyManager.NETWORK_TYPE_LTE_CA,
+            TelephonyManager.NETWORK_TYPE_NR,
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface NetworkType {
+    }
+
+    @IntDef(flag = true, prefix = {"TYPE_"}, value = {
+            ApnSetting.TYPE_DEFAULT,
+            ApnSetting.TYPE_MMS,
+            ApnSetting.TYPE_SUPL,
+            ApnSetting.TYPE_DUN,
+            ApnSetting.TYPE_HIPRI,
+            ApnSetting.TYPE_FOTA,
+            ApnSetting.TYPE_IMS,
+            ApnSetting.TYPE_CBS,
+            ApnSetting.TYPE_IA,
+            ApnSetting.TYPE_EMERGENCY,
+            ApnSetting.TYPE_MCX
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface ApnType {
+    }
+
+    @IntDef(value = {
+            DataFailCause.NONE,
+            DataFailCause.OPERATOR_BARRED,
+            DataFailCause.NAS_SIGNALLING,
+            DataFailCause.LLC_SNDCP,
+            DataFailCause.INSUFFICIENT_RESOURCES,
+            DataFailCause.MISSING_UNKNOWN_APN,
+            DataFailCause.UNKNOWN_PDP_ADDRESS_TYPE,
+            DataFailCause.USER_AUTHENTICATION,
+            DataFailCause.ACTIVATION_REJECT_GGSN,
+            DataFailCause.ACTIVATION_REJECT_UNSPECIFIED,
+            DataFailCause.SERVICE_OPTION_NOT_SUPPORTED,
+            DataFailCause.SERVICE_OPTION_NOT_SUBSCRIBED,
+            DataFailCause.SERVICE_OPTION_OUT_OF_ORDER,
+            DataFailCause.NSAPI_IN_USE,
+            DataFailCause.REGULAR_DEACTIVATION,
+            DataFailCause.QOS_NOT_ACCEPTED,
+            DataFailCause.NETWORK_FAILURE,
+            DataFailCause.UMTS_REACTIVATION_REQ,
+            DataFailCause.FEATURE_NOT_SUPP,
+            DataFailCause.TFT_SEMANTIC_ERROR,
+            DataFailCause.TFT_SYTAX_ERROR,
+            DataFailCause.UNKNOWN_PDP_CONTEXT,
+            DataFailCause.FILTER_SEMANTIC_ERROR,
+            DataFailCause.FILTER_SYTAX_ERROR,
+            DataFailCause.PDP_WITHOUT_ACTIVE_TFT,
+            DataFailCause.ACTIVATION_REJECTED_BCM_VIOLATION,
+            DataFailCause.ONLY_IPV4_ALLOWED,
+            DataFailCause.ONLY_IPV6_ALLOWED,
+            DataFailCause.ONLY_SINGLE_BEARER_ALLOWED,
+            DataFailCause.ESM_INFO_NOT_RECEIVED,
+            DataFailCause.PDN_CONN_DOES_NOT_EXIST,
+            DataFailCause.MULTI_CONN_TO_SAME_PDN_NOT_ALLOWED,
+            DataFailCause.COLLISION_WITH_NETWORK_INITIATED_REQUEST,
+            DataFailCause.ONLY_IPV4V6_ALLOWED,
+            DataFailCause.ONLY_NON_IP_ALLOWED,
+            DataFailCause.UNSUPPORTED_QCI_VALUE,
+            DataFailCause.BEARER_HANDLING_NOT_SUPPORTED,
+            DataFailCause.ACTIVE_PDP_CONTEXT_MAX_NUMBER_REACHED,
+            DataFailCause.UNSUPPORTED_APN_IN_CURRENT_PLMN,
+            DataFailCause.INVALID_TRANSACTION_ID,
+            DataFailCause.MESSAGE_INCORRECT_SEMANTIC,
+            DataFailCause.INVALID_MANDATORY_INFO,
+            DataFailCause.MESSAGE_TYPE_UNSUPPORTED,
+            DataFailCause.MSG_TYPE_NONCOMPATIBLE_STATE,
+            DataFailCause.UNKNOWN_INFO_ELEMENT,
+            DataFailCause.CONDITIONAL_IE_ERROR,
+            DataFailCause.MSG_AND_PROTOCOL_STATE_UNCOMPATIBLE,
+            DataFailCause.PROTOCOL_ERRORS,
+            DataFailCause.APN_TYPE_CONFLICT,
+            DataFailCause.INVALID_PCSCF_ADDR,
+            DataFailCause.INTERNAL_CALL_PREEMPT_BY_HIGH_PRIO_APN,
+            DataFailCause.EMM_ACCESS_BARRED,
+            DataFailCause.EMERGENCY_IFACE_ONLY,
+            DataFailCause.IFACE_MISMATCH,
+            DataFailCause.COMPANION_IFACE_IN_USE,
+            DataFailCause.IP_ADDRESS_MISMATCH,
+            DataFailCause.IFACE_AND_POL_FAMILY_MISMATCH,
+            DataFailCause.EMM_ACCESS_BARRED_INFINITE_RETRY,
+            DataFailCause.AUTH_FAILURE_ON_EMERGENCY_CALL,
+            DataFailCause.INVALID_DNS_ADDR,
+            DataFailCause.INVALID_PCSCF_OR_DNS_ADDRESS,
+            DataFailCause.CALL_PREEMPT_BY_EMERGENCY_APN,
+            DataFailCause.UE_INITIATED_DETACH_OR_DISCONNECT,
+            DataFailCause.MIP_FA_REASON_UNSPECIFIED,
+            DataFailCause.MIP_FA_ADMIN_PROHIBITED,
+            DataFailCause.MIP_FA_INSUFFICIENT_RESOURCES,
+            DataFailCause.MIP_FA_MOBILE_NODE_AUTHENTICATION_FAILURE,
+            DataFailCause.MIP_FA_HOME_AGENT_AUTHENTICATION_FAILURE,
+            DataFailCause.MIP_FA_REQUESTED_LIFETIME_TOO_LONG,
+            DataFailCause.MIP_FA_MALFORMED_REQUEST,
+            DataFailCause.MIP_FA_MALFORMED_REPLY,
+            DataFailCause.MIP_FA_ENCAPSULATION_UNAVAILABLE,
+            DataFailCause.MIP_FA_VJ_HEADER_COMPRESSION_UNAVAILABLE,
+            DataFailCause.MIP_FA_REVERSE_TUNNEL_UNAVAILABLE,
+            DataFailCause.MIP_FA_REVERSE_TUNNEL_IS_MANDATORY,
+            DataFailCause.MIP_FA_DELIVERY_STYLE_NOT_SUPPORTED,
+            DataFailCause.MIP_FA_MISSING_NAI,
+            DataFailCause.MIP_FA_MISSING_HOME_AGENT,
+            DataFailCause.MIP_FA_MISSING_HOME_ADDRESS,
+            DataFailCause.MIP_FA_UNKNOWN_CHALLENGE,
+            DataFailCause.MIP_FA_MISSING_CHALLENGE,
+            DataFailCause.MIP_FA_STALE_CHALLENGE,
+            DataFailCause.MIP_HA_REASON_UNSPECIFIED,
+            DataFailCause.MIP_HA_ADMIN_PROHIBITED,
+            DataFailCause.MIP_HA_INSUFFICIENT_RESOURCES,
+            DataFailCause.MIP_HA_MOBILE_NODE_AUTHENTICATION_FAILURE,
+            DataFailCause.MIP_HA_FOREIGN_AGENT_AUTHENTICATION_FAILURE,
+            DataFailCause.MIP_HA_REGISTRATION_ID_MISMATCH,
+            DataFailCause.MIP_HA_MALFORMED_REQUEST,
+            DataFailCause.MIP_HA_UNKNOWN_HOME_AGENT_ADDRESS,
+            DataFailCause.MIP_HA_REVERSE_TUNNEL_UNAVAILABLE,
+            DataFailCause.MIP_HA_REVERSE_TUNNEL_IS_MANDATORY,
+            DataFailCause.MIP_HA_ENCAPSULATION_UNAVAILABLE,
+            DataFailCause.CLOSE_IN_PROGRESS,
+            DataFailCause.NETWORK_INITIATED_TERMINATION,
+            DataFailCause.MODEM_APP_PREEMPTED,
+            DataFailCause.PDN_IPV4_CALL_DISALLOWED,
+            DataFailCause.PDN_IPV4_CALL_THROTTLED,
+            DataFailCause.PDN_IPV6_CALL_DISALLOWED,
+            DataFailCause.PDN_IPV6_CALL_THROTTLED,
+            DataFailCause.MODEM_RESTART,
+            DataFailCause.PDP_PPP_NOT_SUPPORTED,
+            DataFailCause.UNPREFERRED_RAT,
+            DataFailCause.PHYSICAL_LINK_CLOSE_IN_PROGRESS,
+            DataFailCause.APN_PENDING_HANDOVER,
+            DataFailCause.PROFILE_BEARER_INCOMPATIBLE,
+            DataFailCause.SIM_CARD_CHANGED,
+            DataFailCause.LOW_POWER_MODE_OR_POWERING_DOWN,
+            DataFailCause.APN_DISABLED,
+            DataFailCause.MAX_PPP_INACTIVITY_TIMER_EXPIRED,
+            DataFailCause.IPV6_ADDRESS_TRANSFER_FAILED,
+            DataFailCause.TRAT_SWAP_FAILED,
+            DataFailCause.EHRPD_TO_HRPD_FALLBACK,
+            DataFailCause.MIP_CONFIG_FAILURE,
+            DataFailCause.PDN_INACTIVITY_TIMER_EXPIRED,
+            DataFailCause.MAX_IPV4_CONNECTIONS,
+            DataFailCause.MAX_IPV6_CONNECTIONS,
+            DataFailCause.APN_MISMATCH,
+            DataFailCause.IP_VERSION_MISMATCH,
+            DataFailCause.DUN_CALL_DISALLOWED,
+            DataFailCause.INTERNAL_EPC_NONEPC_TRANSITION,
+            DataFailCause.INTERFACE_IN_USE,
+            DataFailCause.APN_DISALLOWED_ON_ROAMING,
+            DataFailCause.APN_PARAMETERS_CHANGED,
+            DataFailCause.NULL_APN_DISALLOWED,
+            DataFailCause.THERMAL_MITIGATION,
+            DataFailCause.DATA_SETTINGS_DISABLED,
+            DataFailCause.DATA_ROAMING_SETTINGS_DISABLED,
+            DataFailCause.DDS_SWITCHED,
+            DataFailCause.FORBIDDEN_APN_NAME,
+            DataFailCause.DDS_SWITCH_IN_PROGRESS,
+            DataFailCause.CALL_DISALLOWED_IN_ROAMING,
+            DataFailCause.NON_IP_NOT_SUPPORTED,
+            DataFailCause.PDN_NON_IP_CALL_THROTTLED,
+            DataFailCause.PDN_NON_IP_CALL_DISALLOWED,
+            DataFailCause.CDMA_LOCK,
+            DataFailCause.CDMA_INTERCEPT,
+            DataFailCause.CDMA_REORDER,
+            DataFailCause.CDMA_RELEASE_DUE_TO_SO_REJECTION,
+            DataFailCause.CDMA_INCOMING_CALL,
+            DataFailCause.CDMA_ALERT_STOP,
+            DataFailCause.CHANNEL_ACQUISITION_FAILURE,
+            DataFailCause.MAX_ACCESS_PROBE,
+            DataFailCause.CONCURRENT_SERVICE_NOT_SUPPORTED_BY_BASE_STATION,
+            DataFailCause.NO_RESPONSE_FROM_BASE_STATION,
+            DataFailCause.REJECTED_BY_BASE_STATION,
+            DataFailCause.CONCURRENT_SERVICES_INCOMPATIBLE,
+            DataFailCause.NO_CDMA_SERVICE,
+            DataFailCause.RUIM_NOT_PRESENT,
+            DataFailCause.CDMA_RETRY_ORDER,
+            DataFailCause.ACCESS_BLOCK,
+            DataFailCause.ACCESS_BLOCK_ALL,
+            DataFailCause.IS707B_MAX_ACCESS_PROBES,
+            DataFailCause.THERMAL_EMERGENCY,
+            DataFailCause.CONCURRENT_SERVICES_NOT_ALLOWED,
+            DataFailCause.INCOMING_CALL_REJECTED,
+            DataFailCause.NO_SERVICE_ON_GATEWAY,
+            DataFailCause.NO_GPRS_CONTEXT,
+            DataFailCause.ILLEGAL_MS,
+            DataFailCause.ILLEGAL_ME,
+            DataFailCause.GPRS_SERVICES_AND_NON_GPRS_SERVICES_NOT_ALLOWED,
+            DataFailCause.GPRS_SERVICES_NOT_ALLOWED,
+            DataFailCause.MS_IDENTITY_CANNOT_BE_DERIVED_BY_THE_NETWORK,
+            DataFailCause.IMPLICITLY_DETACHED,
+            DataFailCause.PLMN_NOT_ALLOWED,
+            DataFailCause.LOCATION_AREA_NOT_ALLOWED,
+            DataFailCause.GPRS_SERVICES_NOT_ALLOWED_IN_THIS_PLMN,
+            DataFailCause.PDP_DUPLICATE,
+            DataFailCause.UE_RAT_CHANGE,
+            DataFailCause.CONGESTION,
+            DataFailCause.NO_PDP_CONTEXT_ACTIVATED,
+            DataFailCause.ACCESS_CLASS_DSAC_REJECTION,
+            DataFailCause.PDP_ACTIVATE_MAX_RETRY_FAILED,
+            DataFailCause.RADIO_ACCESS_BEARER_FAILURE,
+            DataFailCause.ESM_UNKNOWN_EPS_BEARER_CONTEXT,
+            DataFailCause.DRB_RELEASED_BY_RRC,
+            DataFailCause.CONNECTION_RELEASED,
+            DataFailCause.EMM_DETACHED,
+            DataFailCause.EMM_ATTACH_FAILED,
+            DataFailCause.EMM_ATTACH_STARTED,
+            DataFailCause.LTE_NAS_SERVICE_REQUEST_FAILED,
+            DataFailCause.DUPLICATE_BEARER_ID,
+            DataFailCause.ESM_COLLISION_SCENARIOS,
+            DataFailCause.ESM_BEARER_DEACTIVATED_TO_SYNC_WITH_NETWORK,
+            DataFailCause.ESM_NW_ACTIVATED_DED_BEARER_WITH_ID_OF_DEF_BEARER,
+            DataFailCause.ESM_BAD_OTA_MESSAGE,
+            DataFailCause.ESM_DOWNLOAD_SERVER_REJECTED_THE_CALL,
+            DataFailCause.ESM_CONTEXT_TRANSFERRED_DUE_TO_IRAT,
+            DataFailCause.DS_EXPLICIT_DEACTIVATION,
+            DataFailCause.ESM_LOCAL_CAUSE_NONE,
+            DataFailCause.LTE_THROTTLING_NOT_REQUIRED,
+            DataFailCause.ACCESS_CONTROL_LIST_CHECK_FAILURE,
+            DataFailCause.SERVICE_NOT_ALLOWED_ON_PLMN,
+            DataFailCause.EMM_T3417_EXPIRED,
+            DataFailCause.EMM_T3417_EXT_EXPIRED,
+            DataFailCause.RRC_UPLINK_DATA_TRANSMISSION_FAILURE,
+            DataFailCause.RRC_UPLINK_DELIVERY_FAILED_DUE_TO_HANDOVER,
+            DataFailCause.RRC_UPLINK_CONNECTION_RELEASE,
+            DataFailCause.RRC_UPLINK_RADIO_LINK_FAILURE,
+            DataFailCause.RRC_UPLINK_ERROR_REQUEST_FROM_NAS,
+            DataFailCause.RRC_CONNECTION_ACCESS_STRATUM_FAILURE,
+            DataFailCause.RRC_CONNECTION_ANOTHER_PROCEDURE_IN_PROGRESS,
+            DataFailCause.RRC_CONNECTION_ACCESS_BARRED,
+            DataFailCause.RRC_CONNECTION_CELL_RESELECTION,
+            DataFailCause.RRC_CONNECTION_CONFIG_FAILURE,
+            DataFailCause.RRC_CONNECTION_TIMER_EXPIRED,
+            DataFailCause.RRC_CONNECTION_LINK_FAILURE,
+            DataFailCause.RRC_CONNECTION_CELL_NOT_CAMPED,
+            DataFailCause.RRC_CONNECTION_SYSTEM_INTERVAL_FAILURE,
+            DataFailCause.RRC_CONNECTION_REJECT_BY_NETWORK,
+            DataFailCause.RRC_CONNECTION_NORMAL_RELEASE,
+            DataFailCause.RRC_CONNECTION_RADIO_LINK_FAILURE,
+            DataFailCause.RRC_CONNECTION_REESTABLISHMENT_FAILURE,
+            DataFailCause.RRC_CONNECTION_OUT_OF_SERVICE_DURING_CELL_REGISTER,
+            DataFailCause.RRC_CONNECTION_ABORT_REQUEST,
+            DataFailCause.RRC_CONNECTION_SYSTEM_INFORMATION_BLOCK_READ_ERROR,
+            DataFailCause.NETWORK_INITIATED_DETACH_WITH_AUTO_REATTACH,
+            DataFailCause.NETWORK_INITIATED_DETACH_NO_AUTO_REATTACH,
+            DataFailCause.ESM_PROCEDURE_TIME_OUT,
+            DataFailCause.INVALID_CONNECTION_ID,
+            DataFailCause.MAXIMIUM_NSAPIS_EXCEEDED,
+            DataFailCause.INVALID_PRIMARY_NSAPI,
+            DataFailCause.CANNOT_ENCODE_OTA_MESSAGE,
+            DataFailCause.RADIO_ACCESS_BEARER_SETUP_FAILURE,
+            DataFailCause.PDP_ESTABLISH_TIMEOUT_EXPIRED,
+            DataFailCause.PDP_MODIFY_TIMEOUT_EXPIRED,
+            DataFailCause.PDP_INACTIVE_TIMEOUT_EXPIRED,
+            DataFailCause.PDP_LOWERLAYER_ERROR,
+            DataFailCause.PDP_MODIFY_COLLISION,
+            DataFailCause.MAXINUM_SIZE_OF_L2_MESSAGE_EXCEEDED,
+            DataFailCause.NAS_REQUEST_REJECTED_BY_NETWORK,
+            DataFailCause.RRC_CONNECTION_INVALID_REQUEST,
+            DataFailCause.RRC_CONNECTION_TRACKING_AREA_ID_CHANGED,
+            DataFailCause.RRC_CONNECTION_RF_UNAVAILABLE,
+            DataFailCause.RRC_CONNECTION_ABORTED_DUE_TO_IRAT_CHANGE,
+            DataFailCause.RRC_CONNECTION_RELEASED_SECURITY_NOT_ACTIVE,
+            DataFailCause.RRC_CONNECTION_ABORTED_AFTER_HANDOVER,
+            DataFailCause.RRC_CONNECTION_ABORTED_AFTER_IRAT_CELL_CHANGE,
+            DataFailCause.RRC_CONNECTION_ABORTED_DURING_IRAT_CELL_CHANGE,
+            DataFailCause.IMSI_UNKNOWN_IN_HOME_SUBSCRIBER_SERVER,
+            DataFailCause.IMEI_NOT_ACCEPTED,
+            DataFailCause.EPS_SERVICES_AND_NON_EPS_SERVICES_NOT_ALLOWED,
+            DataFailCause.EPS_SERVICES_NOT_ALLOWED_IN_PLMN,
+            DataFailCause.MSC_TEMPORARILY_NOT_REACHABLE,
+            DataFailCause.CS_DOMAIN_NOT_AVAILABLE,
+            DataFailCause.ESM_FAILURE,
+            DataFailCause.MAC_FAILURE,
+            DataFailCause.SYNCHRONIZATION_FAILURE,
+            DataFailCause.UE_SECURITY_CAPABILITIES_MISMATCH,
+            DataFailCause.SECURITY_MODE_REJECTED,
+            DataFailCause.UNACCEPTABLE_NON_EPS_AUTHENTICATION,
+            DataFailCause.CS_FALLBACK_CALL_ESTABLISHMENT_NOT_ALLOWED,
+            DataFailCause.NO_EPS_BEARER_CONTEXT_ACTIVATED,
+            DataFailCause.INVALID_EMM_STATE,
+            DataFailCause.NAS_LAYER_FAILURE,
+            DataFailCause.MULTIPLE_PDP_CALL_NOT_ALLOWED,
+            DataFailCause.EMBMS_NOT_ENABLED,
+            DataFailCause.IRAT_HANDOVER_FAILED,
+            DataFailCause.EMBMS_REGULAR_DEACTIVATION,
+            DataFailCause.TEST_LOOPBACK_REGULAR_DEACTIVATION,
+            DataFailCause.LOWER_LAYER_REGISTRATION_FAILURE,
+            DataFailCause.DATA_PLAN_EXPIRED,
+            DataFailCause.UMTS_HANDOVER_TO_IWLAN,
+            DataFailCause.EVDO_CONNECTION_DENY_BY_GENERAL_OR_NETWORK_BUSY,
+            DataFailCause.EVDO_CONNECTION_DENY_BY_BILLING_OR_AUTHENTICATION_FAILURE,
+            DataFailCause.EVDO_HDR_CHANGED,
+            DataFailCause.EVDO_HDR_EXITED,
+            DataFailCause.EVDO_HDR_NO_SESSION,
+            DataFailCause.EVDO_USING_GPS_FIX_INSTEAD_OF_HDR_CALL,
+            DataFailCause.EVDO_HDR_CONNECTION_SETUP_TIMEOUT,
+            DataFailCause.FAILED_TO_ACQUIRE_COLOCATED_HDR,
+            DataFailCause.OTASP_COMMIT_IN_PROGRESS,
+            DataFailCause.NO_HYBRID_HDR_SERVICE,
+            DataFailCause.HDR_NO_LOCK_GRANTED,
+            DataFailCause.DBM_OR_SMS_IN_PROGRESS,
+            DataFailCause.HDR_FADE,
+            DataFailCause.HDR_ACCESS_FAILURE,
+            DataFailCause.UNSUPPORTED_1X_PREV,
+            DataFailCause.LOCAL_END,
+            DataFailCause.NO_SERVICE,
+            DataFailCause.FADE,
+            DataFailCause.NORMAL_RELEASE,
+            DataFailCause.ACCESS_ATTEMPT_ALREADY_IN_PROGRESS,
+            DataFailCause.REDIRECTION_OR_HANDOFF_IN_PROGRESS,
+            DataFailCause.EMERGENCY_MODE,
+            DataFailCause.PHONE_IN_USE,
+            DataFailCause.INVALID_MODE,
+            DataFailCause.INVALID_SIM_STATE,
+            DataFailCause.NO_COLLOCATED_HDR,
+            DataFailCause.UE_IS_ENTERING_POWERSAVE_MODE,
+            DataFailCause.DUAL_SWITCH,
+            DataFailCause.PPP_TIMEOUT,
+            DataFailCause.PPP_AUTH_FAILURE,
+            DataFailCause.PPP_OPTION_MISMATCH,
+            DataFailCause.PPP_PAP_FAILURE,
+            DataFailCause.PPP_CHAP_FAILURE,
+            DataFailCause.PPP_CLOSE_IN_PROGRESS,
+            DataFailCause.LIMITED_TO_IPV4,
+            DataFailCause.LIMITED_TO_IPV6,
+            DataFailCause.VSNCP_TIMEOUT,
+            DataFailCause.VSNCP_GEN_ERROR,
+            DataFailCause.VSNCP_APN_UNATHORIZED,
+            DataFailCause.VSNCP_PDN_LIMIT_EXCEEDED,
+            DataFailCause.VSNCP_NO_PDN_GATEWAY_ADDRESS,
+            DataFailCause.VSNCP_PDN_GATEWAY_UNREACHABLE,
+            DataFailCause.VSNCP_PDN_GATEWAY_REJECT,
+            DataFailCause.VSNCP_INSUFFICIENT_PARAMETERS,
+            DataFailCause.VSNCP_RESOURCE_UNAVAILABLE,
+            DataFailCause.VSNCP_ADMINISTRATIVELY_PROHIBITED,
+            DataFailCause.VSNCP_PDN_ID_IN_USE,
+            DataFailCause.VSNCP_SUBSCRIBER_LIMITATION,
+            DataFailCause.VSNCP_PDN_EXISTS_FOR_THIS_APN,
+            DataFailCause.VSNCP_RECONNECT_NOT_ALLOWED,
+            DataFailCause.IPV6_PREFIX_UNAVAILABLE,
+            DataFailCause.HANDOFF_PREFERENCE_CHANGED,
+            DataFailCause.OEM_DCFAILCAUSE_1,
+            DataFailCause.OEM_DCFAILCAUSE_2,
+            DataFailCause.OEM_DCFAILCAUSE_3,
+            DataFailCause.OEM_DCFAILCAUSE_4,
+            DataFailCause.OEM_DCFAILCAUSE_5,
+            DataFailCause.OEM_DCFAILCAUSE_6,
+            DataFailCause.OEM_DCFAILCAUSE_7,
+            DataFailCause.OEM_DCFAILCAUSE_8,
+            DataFailCause.OEM_DCFAILCAUSE_9,
+            DataFailCause.OEM_DCFAILCAUSE_10,
+            DataFailCause.OEM_DCFAILCAUSE_11,
+            DataFailCause.OEM_DCFAILCAUSE_12,
+            DataFailCause.OEM_DCFAILCAUSE_13,
+            DataFailCause.OEM_DCFAILCAUSE_14,
+            DataFailCause.OEM_DCFAILCAUSE_15,
+            DataFailCause.REGISTRATION_FAIL,
+            DataFailCause.GPRS_REGISTRATION_FAIL,
+            DataFailCause.SIGNAL_LOST,
+            DataFailCause.PREF_RADIO_TECH_CHANGED,
+            DataFailCause.RADIO_POWER_OFF,
+            DataFailCause.TETHERED_CALL_ACTIVE,
+            DataFailCause.ERROR_UNSPECIFIED,
+            DataFailCause.UNKNOWN,
+            DataFailCause.RADIO_NOT_AVAILABLE,
+            DataFailCause.UNACCEPTABLE_NETWORK_PARAMETER,
+            DataFailCause.CONNECTION_TO_DATACONNECTIONAC_BROKEN,
+            DataFailCause.LOST_CONNECTION,
+            DataFailCause.RESET_BY_FRAMEWORK
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    public @interface DataFailureCause {
+    }
+
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(prefix = {"PRECISE_CALL_STATE_"},
+            value = {
+            PreciseCallState.PRECISE_CALL_STATE_NOT_VALID,
+            PreciseCallState.PRECISE_CALL_STATE_IDLE,
+            PreciseCallState.PRECISE_CALL_STATE_ACTIVE,
+            PreciseCallState.PRECISE_CALL_STATE_HOLDING,
+            PreciseCallState.PRECISE_CALL_STATE_DIALING,
+            PreciseCallState.PRECISE_CALL_STATE_ALERTING,
+            PreciseCallState. PRECISE_CALL_STATE_INCOMING,
+            PreciseCallState.PRECISE_CALL_STATE_WAITING,
+            PreciseCallState.PRECISE_CALL_STATE_DISCONNECTED,
+            PreciseCallState.PRECISE_CALL_STATE_DISCONNECTING})
+    public @interface PreciseCallStates {}
+
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(prefix = {"RIL_RADIO_TECHNOLOGY_" }, value = {
+            ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN,
+            ServiceState.RIL_RADIO_TECHNOLOGY_GPRS,
+            ServiceState.RIL_RADIO_TECHNOLOGY_EDGE,
+            ServiceState.RIL_RADIO_TECHNOLOGY_UMTS,
+            ServiceState.RIL_RADIO_TECHNOLOGY_IS95A,
+            ServiceState.RIL_RADIO_TECHNOLOGY_IS95B,
+            ServiceState.RIL_RADIO_TECHNOLOGY_1xRTT,
+            ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_0,
+            ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A,
+            ServiceState.RIL_RADIO_TECHNOLOGY_HSDPA,
+            ServiceState.RIL_RADIO_TECHNOLOGY_HSUPA,
+            ServiceState.RIL_RADIO_TECHNOLOGY_HSPA,
+            ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_B,
+            ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD,
+            ServiceState.RIL_RADIO_TECHNOLOGY_LTE,
+            ServiceState.RIL_RADIO_TECHNOLOGY_HSPAP,
+            ServiceState.RIL_RADIO_TECHNOLOGY_GSM,
+            ServiceState.RIL_RADIO_TECHNOLOGY_TD_SCDMA,
+            ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN,
+            ServiceState.RIL_RADIO_TECHNOLOGY_LTE_CA,
+            ServiceState.RIL_RADIO_TECHNOLOGY_NR})
+    public @interface RilRadioTechnology {}
+}
diff --git a/telephony/java/android/telephony/CallAttributes.java b/telephony/java/android/telephony/CallAttributes.java
index 1c03d80..cd830ad 100644
--- a/telephony/java/android/telephony/CallAttributes.java
+++ b/telephony/java/android/telephony/CallAttributes.java
@@ -21,8 +21,8 @@
 import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.telephony.TelephonyManager.NetworkType;
 
+import android.telephony.Annotation.NetworkType;
 import java.util.Objects;
 
 /**
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index b449578..1d5c18d 100755
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -1739,9 +1739,8 @@
             "allow_emergency_video_calls_bool";
 
     /**
-     * Flag indicating whether the carrier supports RCS presence indication for video calls.  When
-     * {@code true}, the carrier supports RCS presence indication for video calls.  When presence
-     * is supported, the device should use the
+     * Flag indicating whether the carrier supports RCS presence indication for
+     * User Capability Exchange (UCE).  When presence is supported, the device should use the
      * {@link android.provider.ContactsContract.Data#CARRIER_PRESENCE} bit mask and set the
      * {@link android.provider.ContactsContract.Data#CARRIER_PRESENCE_VT_CAPABLE} bit to indicate
      * whether each contact supports video calling.  The UI is made aware that presence is enabled
@@ -1752,6 +1751,12 @@
     public static final String KEY_USE_RCS_PRESENCE_BOOL = "use_rcs_presence_bool";
 
     /**
+     * Flag indicating whether the carrier supports RCS SIP OPTIONS indication for
+     * User Capability Exchange (UCE).
+     */
+    public static final String KEY_USE_RCS_SIP_OPTIONS_BOOL = "use_rcs_sip_options_bool";
+
+    /**
      * The duration in seconds that platform call and message blocking is disabled after the user
      * contacts emergency services. Platform considers values for below cases:
      *  1) 0 <= VALUE <= 604800(one week): the value will be used as the duration directly.
@@ -3435,6 +3440,7 @@
         sDefaults.putBoolean(KEY_ALLOW_NON_EMERGENCY_CALLS_IN_ECM_BOOL, true);
         sDefaults.putInt(KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT, 0);
         sDefaults.putBoolean(KEY_USE_RCS_PRESENCE_BOOL, false);
+        sDefaults.putBoolean(KEY_USE_RCS_SIP_OPTIONS_BOOL, false);
         sDefaults.putBoolean(KEY_FORCE_IMEI_BOOL, false);
         sDefaults.putInt(
                 KEY_CDMA_ROAMING_MODE_INT, TelephonyManager.CDMA_ROAMING_MODE_RADIO_DEFAULT);
diff --git a/telephony/java/android/telephony/CellBroadcastService.java b/telephony/java/android/telephony/CellBroadcastService.java
new file mode 100644
index 0000000..d5e447e
--- /dev/null
+++ b/telephony/java/android/telephony/CellBroadcastService.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2019 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.telephony;
+
+import android.annotation.CallSuper;
+import android.annotation.SystemApi;
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+
+/**
+ * A service which exposes the cell broadcast handling module to the system.
+ * <p>
+ * To extend this class, you must declare the service in your manifest file to require the
+ * {@link android.Manifest.permission#BIND_CELL_BROADCAST_SERVICE} permission and include an intent
+ * filter with the {@link #CELL_BROADCAST_SERVICE_INTERFACE}.
+ * Implementations of this service should run in the phone process and with its UID.
+ * <p>
+ * For example:
+ * <pre>{@code
+ * <manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ *       android:sharedUserId="android.uid.phone">
+ *   <service android:name=".MyCellBroadcastService"
+ *         android:label="@string/service_name"
+ *         android:process="com.android.phone"
+ *         android:exported="true"
+ *         android:permission="android.permission.BIND_CELL_BROADCAST_SERVICE">
+ *     <intent-filter>
+ *           <action android:name="android.telephony.CellBroadcastService" />
+ *     </intent-filter>
+ *   </service>
+ * </manifest>
+ * }</pre>
+ * @hide
+ */
+@SystemApi
+public abstract class CellBroadcastService extends Service {
+
+    public static final String CELL_BROADCAST_SERVICE_INTERFACE =
+            "android.telephony.CellBroadcastService";
+
+    private final ICellBroadcastService.Stub mStubWrapper;
+
+    public CellBroadcastService() {
+        mStubWrapper = new ICellBroadcastServiceWrapper();
+    }
+
+    /**
+     * Handle a GSM cell broadcast SMS message forwarded from the system.
+     * @param slotIndex the index of the slot which received the message
+     * @param message the SMS PDU
+     */
+    public abstract void onGsmCellBroadcastSms(int slotIndex, byte[] message);
+
+    /**
+     * Handle a CDMA cell broadcast SMS message forwarded from the system.
+     * @param slotIndex the index of the slot which received the message
+     * @param message the SMS PDU
+     */
+    public abstract void onCdmaCellBroadcastSms(int slotIndex, byte[] message);
+
+    /**
+     * If overriding this method, call through to the super method for any unknown actions.
+     * {@inheritDoc}
+     */
+    @Override
+    @CallSuper
+    public IBinder onBind(Intent intent) {
+        return mStubWrapper;
+    }
+
+    /**
+     * A wrapper around ICellBroadcastService that forwards calls to implementations of
+     * {@link CellBroadcastService}.
+     * @hide
+     */
+    public class ICellBroadcastServiceWrapper extends ICellBroadcastService.Stub {
+        /**
+         * Handle a GSM cell broadcast SMS.
+         * @param slotIndex the index of the slot which received the broadcast
+         * @param message the SMS message PDU
+         */
+        @Override
+        public void handleGsmCellBroadcastSms(int slotIndex, byte[] message) {
+            CellBroadcastService.this.onGsmCellBroadcastSms(slotIndex, message);
+        }
+
+        /**
+         * Handle a CDMA cell broadcast SMS.
+         * @param slotIndex the index of the slot which received the broadcast
+         * @param message the SMS message PDU
+         */
+        @Override
+        public void handleCdmaCellBroadcastSms(int slotIndex, byte[] message) {
+            CellBroadcastService.this.onCdmaCellBroadcastSms(slotIndex, message);
+        }
+    }
+}
diff --git a/telephony/java/android/telephony/CellIdentity.java b/telephony/java/android/telephony/CellIdentity.java
index 432978d..b7dab16 100644
--- a/telephony/java/android/telephony/CellIdentity.java
+++ b/telephony/java/android/telephony/CellIdentity.java
@@ -35,6 +35,15 @@
     /** @hide */
     public static final int INVALID_CHANNEL_NUMBER = -1;
 
+    /**
+     * parameters for validation
+     * @hide
+     */
+    public static final int MCC_LENGTH = 3;
+
+    private static final int MNC_MIN_LENGTH = 2;
+    private static final int MNC_MAX_LENGTH = 3;
+
     // Log tag
     /** @hide */
     protected final String mTag;
@@ -207,6 +216,17 @@
         dest.writeString(mAlphaShort);
     }
 
+    /** Used by phone interface manager to verify if a given string is valid MccMnc
+     * @hide
+     */
+    public static boolean isValidPlmn(@NonNull String plmn) {
+        if (plmn.length() < MCC_LENGTH + MNC_MIN_LENGTH
+                || plmn.length() > MCC_LENGTH + MNC_MAX_LENGTH) {
+            return false;
+        }
+        return (isMcc(plmn.substring(0, MCC_LENGTH)) && isMnc(plmn.substring(MCC_LENGTH)));
+    }
+
     /**
      * Construct from Parcel
      * @hide
@@ -267,10 +287,10 @@
     /** @hide */
     private static boolean isMcc(@NonNull String mcc) {
         // ensure no out of bounds indexing
-        if (mcc.length() != 3) return false;
+        if (mcc.length() != MCC_LENGTH) return false;
 
         // Character.isDigit allows all unicode digits, not just [0-9]
-        for (int i = 0; i < 3; i++) {
+        for (int i = 0; i < MCC_LENGTH; i++) {
             if (mcc.charAt(i) < '0' || mcc.charAt(i) > '9') return false;
         }
 
@@ -280,7 +300,7 @@
     /** @hide */
     private static boolean isMnc(@NonNull String mnc) {
         // ensure no out of bounds indexing
-        if (mnc.length() < 2 || mnc.length() > 3) return false;
+        if (mnc.length() < MNC_MIN_LENGTH || mnc.length() > MNC_MAX_LENGTH) return false;
 
         // Character.isDigit allows all unicode digits, not just [0-9]
         for (int i = 0; i < mnc.length(); i++) {
@@ -289,4 +309,5 @@
 
         return true;
     }
+
 }
diff --git a/telephony/java/android/telephony/DataFailCause.java b/telephony/java/android/telephony/DataFailCause.java
index ca264f7..246bec7 100644
--- a/telephony/java/android/telephony/DataFailCause.java
+++ b/telephony/java/android/telephony/DataFailCause.java
@@ -21,6 +21,7 @@
 import android.content.Context;
 import android.os.PersistableBundle;
 
+import android.telephony.Annotation.DataFailureCause;
 import com.android.internal.util.ArrayUtils;
 
 import java.lang.annotation.Retention;
@@ -968,355 +969,6 @@
      */
     public static final int HANDOVER_FAILED = 0x10006;
 
-    /** @hide */
-    @IntDef(value = {
-            NONE,
-            OPERATOR_BARRED,
-            NAS_SIGNALLING,
-            LLC_SNDCP,
-            INSUFFICIENT_RESOURCES,
-            MISSING_UNKNOWN_APN,
-            UNKNOWN_PDP_ADDRESS_TYPE,
-            USER_AUTHENTICATION,
-            ACTIVATION_REJECT_GGSN,
-            ACTIVATION_REJECT_UNSPECIFIED,
-            SERVICE_OPTION_NOT_SUPPORTED,
-            SERVICE_OPTION_NOT_SUBSCRIBED,
-            SERVICE_OPTION_OUT_OF_ORDER,
-            NSAPI_IN_USE,
-            REGULAR_DEACTIVATION,
-            QOS_NOT_ACCEPTED,
-            NETWORK_FAILURE,
-            UMTS_REACTIVATION_REQ,
-            FEATURE_NOT_SUPP,
-            TFT_SEMANTIC_ERROR,
-            TFT_SYTAX_ERROR,
-            UNKNOWN_PDP_CONTEXT,
-            FILTER_SEMANTIC_ERROR,
-            FILTER_SYTAX_ERROR,
-            PDP_WITHOUT_ACTIVE_TFT,
-            ACTIVATION_REJECTED_BCM_VIOLATION,
-            ONLY_IPV4_ALLOWED,
-            ONLY_IPV6_ALLOWED,
-            ONLY_SINGLE_BEARER_ALLOWED,
-            ESM_INFO_NOT_RECEIVED,
-            PDN_CONN_DOES_NOT_EXIST,
-            MULTI_CONN_TO_SAME_PDN_NOT_ALLOWED,
-            COLLISION_WITH_NETWORK_INITIATED_REQUEST,
-            ONLY_IPV4V6_ALLOWED,
-            ONLY_NON_IP_ALLOWED,
-            UNSUPPORTED_QCI_VALUE,
-            BEARER_HANDLING_NOT_SUPPORTED,
-            ACTIVE_PDP_CONTEXT_MAX_NUMBER_REACHED,
-            UNSUPPORTED_APN_IN_CURRENT_PLMN,
-            INVALID_TRANSACTION_ID,
-            MESSAGE_INCORRECT_SEMANTIC,
-            INVALID_MANDATORY_INFO,
-            MESSAGE_TYPE_UNSUPPORTED,
-            MSG_TYPE_NONCOMPATIBLE_STATE,
-            UNKNOWN_INFO_ELEMENT,
-            CONDITIONAL_IE_ERROR,
-            MSG_AND_PROTOCOL_STATE_UNCOMPATIBLE,
-            PROTOCOL_ERRORS,
-            APN_TYPE_CONFLICT,
-            INVALID_PCSCF_ADDR,
-            INTERNAL_CALL_PREEMPT_BY_HIGH_PRIO_APN,
-            EMM_ACCESS_BARRED,
-            EMERGENCY_IFACE_ONLY,
-            IFACE_MISMATCH,
-            COMPANION_IFACE_IN_USE,
-            IP_ADDRESS_MISMATCH,
-            IFACE_AND_POL_FAMILY_MISMATCH,
-            EMM_ACCESS_BARRED_INFINITE_RETRY,
-            AUTH_FAILURE_ON_EMERGENCY_CALL,
-            INVALID_DNS_ADDR,
-            INVALID_PCSCF_OR_DNS_ADDRESS,
-            CALL_PREEMPT_BY_EMERGENCY_APN,
-            UE_INITIATED_DETACH_OR_DISCONNECT,
-            MIP_FA_REASON_UNSPECIFIED,
-            MIP_FA_ADMIN_PROHIBITED,
-            MIP_FA_INSUFFICIENT_RESOURCES,
-            MIP_FA_MOBILE_NODE_AUTHENTICATION_FAILURE,
-            MIP_FA_HOME_AGENT_AUTHENTICATION_FAILURE,
-            MIP_FA_REQUESTED_LIFETIME_TOO_LONG,
-            MIP_FA_MALFORMED_REQUEST,
-            MIP_FA_MALFORMED_REPLY,
-            MIP_FA_ENCAPSULATION_UNAVAILABLE,
-            MIP_FA_VJ_HEADER_COMPRESSION_UNAVAILABLE,
-            MIP_FA_REVERSE_TUNNEL_UNAVAILABLE,
-            MIP_FA_REVERSE_TUNNEL_IS_MANDATORY,
-            MIP_FA_DELIVERY_STYLE_NOT_SUPPORTED,
-            MIP_FA_MISSING_NAI,
-            MIP_FA_MISSING_HOME_AGENT,
-            MIP_FA_MISSING_HOME_ADDRESS,
-            MIP_FA_UNKNOWN_CHALLENGE,
-            MIP_FA_MISSING_CHALLENGE,
-            MIP_FA_STALE_CHALLENGE,
-            MIP_HA_REASON_UNSPECIFIED,
-            MIP_HA_ADMIN_PROHIBITED,
-            MIP_HA_INSUFFICIENT_RESOURCES,
-            MIP_HA_MOBILE_NODE_AUTHENTICATION_FAILURE,
-            MIP_HA_FOREIGN_AGENT_AUTHENTICATION_FAILURE,
-            MIP_HA_REGISTRATION_ID_MISMATCH,
-            MIP_HA_MALFORMED_REQUEST,
-            MIP_HA_UNKNOWN_HOME_AGENT_ADDRESS,
-            MIP_HA_REVERSE_TUNNEL_UNAVAILABLE,
-            MIP_HA_REVERSE_TUNNEL_IS_MANDATORY,
-            MIP_HA_ENCAPSULATION_UNAVAILABLE,
-            CLOSE_IN_PROGRESS,
-            NETWORK_INITIATED_TERMINATION,
-            MODEM_APP_PREEMPTED,
-            PDN_IPV4_CALL_DISALLOWED,
-            PDN_IPV4_CALL_THROTTLED,
-            PDN_IPV6_CALL_DISALLOWED,
-            PDN_IPV6_CALL_THROTTLED,
-            MODEM_RESTART,
-            PDP_PPP_NOT_SUPPORTED,
-            UNPREFERRED_RAT,
-            PHYSICAL_LINK_CLOSE_IN_PROGRESS,
-            APN_PENDING_HANDOVER,
-            PROFILE_BEARER_INCOMPATIBLE,
-            SIM_CARD_CHANGED,
-            LOW_POWER_MODE_OR_POWERING_DOWN,
-            APN_DISABLED,
-            MAX_PPP_INACTIVITY_TIMER_EXPIRED,
-            IPV6_ADDRESS_TRANSFER_FAILED,
-            TRAT_SWAP_FAILED,
-            EHRPD_TO_HRPD_FALLBACK,
-            MIP_CONFIG_FAILURE,
-            PDN_INACTIVITY_TIMER_EXPIRED,
-            MAX_IPV4_CONNECTIONS,
-            MAX_IPV6_CONNECTIONS,
-            APN_MISMATCH,
-            IP_VERSION_MISMATCH,
-            DUN_CALL_DISALLOWED,
-            INTERNAL_EPC_NONEPC_TRANSITION,
-            INTERFACE_IN_USE,
-            APN_DISALLOWED_ON_ROAMING,
-            APN_PARAMETERS_CHANGED,
-            NULL_APN_DISALLOWED,
-            THERMAL_MITIGATION,
-            DATA_SETTINGS_DISABLED,
-            DATA_ROAMING_SETTINGS_DISABLED,
-            DDS_SWITCHED,
-            FORBIDDEN_APN_NAME,
-            DDS_SWITCH_IN_PROGRESS,
-            CALL_DISALLOWED_IN_ROAMING,
-            NON_IP_NOT_SUPPORTED,
-            PDN_NON_IP_CALL_THROTTLED,
-            PDN_NON_IP_CALL_DISALLOWED,
-            CDMA_LOCK,
-            CDMA_INTERCEPT,
-            CDMA_REORDER,
-            CDMA_RELEASE_DUE_TO_SO_REJECTION,
-            CDMA_INCOMING_CALL,
-            CDMA_ALERT_STOP,
-            CHANNEL_ACQUISITION_FAILURE,
-            MAX_ACCESS_PROBE,
-            CONCURRENT_SERVICE_NOT_SUPPORTED_BY_BASE_STATION,
-            NO_RESPONSE_FROM_BASE_STATION,
-            REJECTED_BY_BASE_STATION,
-            CONCURRENT_SERVICES_INCOMPATIBLE,
-            NO_CDMA_SERVICE,
-            RUIM_NOT_PRESENT,
-            CDMA_RETRY_ORDER,
-            ACCESS_BLOCK,
-            ACCESS_BLOCK_ALL,
-            IS707B_MAX_ACCESS_PROBES,
-            THERMAL_EMERGENCY,
-            CONCURRENT_SERVICES_NOT_ALLOWED,
-            INCOMING_CALL_REJECTED,
-            NO_SERVICE_ON_GATEWAY,
-            NO_GPRS_CONTEXT,
-            ILLEGAL_MS,
-            ILLEGAL_ME,
-            GPRS_SERVICES_AND_NON_GPRS_SERVICES_NOT_ALLOWED,
-            GPRS_SERVICES_NOT_ALLOWED,
-            MS_IDENTITY_CANNOT_BE_DERIVED_BY_THE_NETWORK,
-            IMPLICITLY_DETACHED,
-            PLMN_NOT_ALLOWED,
-            LOCATION_AREA_NOT_ALLOWED,
-            GPRS_SERVICES_NOT_ALLOWED_IN_THIS_PLMN,
-            PDP_DUPLICATE,
-            UE_RAT_CHANGE,
-            CONGESTION,
-            NO_PDP_CONTEXT_ACTIVATED,
-            ACCESS_CLASS_DSAC_REJECTION,
-            PDP_ACTIVATE_MAX_RETRY_FAILED,
-            RADIO_ACCESS_BEARER_FAILURE,
-            ESM_UNKNOWN_EPS_BEARER_CONTEXT,
-            DRB_RELEASED_BY_RRC,
-            CONNECTION_RELEASED,
-            EMM_DETACHED,
-            EMM_ATTACH_FAILED,
-            EMM_ATTACH_STARTED,
-            LTE_NAS_SERVICE_REQUEST_FAILED,
-            DUPLICATE_BEARER_ID,
-            ESM_COLLISION_SCENARIOS,
-            ESM_BEARER_DEACTIVATED_TO_SYNC_WITH_NETWORK,
-            ESM_NW_ACTIVATED_DED_BEARER_WITH_ID_OF_DEF_BEARER,
-            ESM_BAD_OTA_MESSAGE,
-            ESM_DOWNLOAD_SERVER_REJECTED_THE_CALL,
-            ESM_CONTEXT_TRANSFERRED_DUE_TO_IRAT,
-            DS_EXPLICIT_DEACTIVATION,
-            ESM_LOCAL_CAUSE_NONE,
-            LTE_THROTTLING_NOT_REQUIRED,
-            ACCESS_CONTROL_LIST_CHECK_FAILURE,
-            SERVICE_NOT_ALLOWED_ON_PLMN,
-            EMM_T3417_EXPIRED,
-            EMM_T3417_EXT_EXPIRED,
-            RRC_UPLINK_DATA_TRANSMISSION_FAILURE,
-            RRC_UPLINK_DELIVERY_FAILED_DUE_TO_HANDOVER,
-            RRC_UPLINK_CONNECTION_RELEASE,
-            RRC_UPLINK_RADIO_LINK_FAILURE,
-            RRC_UPLINK_ERROR_REQUEST_FROM_NAS,
-            RRC_CONNECTION_ACCESS_STRATUM_FAILURE,
-            RRC_CONNECTION_ANOTHER_PROCEDURE_IN_PROGRESS,
-            RRC_CONNECTION_ACCESS_BARRED,
-            RRC_CONNECTION_CELL_RESELECTION,
-            RRC_CONNECTION_CONFIG_FAILURE,
-            RRC_CONNECTION_TIMER_EXPIRED,
-            RRC_CONNECTION_LINK_FAILURE,
-            RRC_CONNECTION_CELL_NOT_CAMPED,
-            RRC_CONNECTION_SYSTEM_INTERVAL_FAILURE,
-            RRC_CONNECTION_REJECT_BY_NETWORK,
-            RRC_CONNECTION_NORMAL_RELEASE,
-            RRC_CONNECTION_RADIO_LINK_FAILURE,
-            RRC_CONNECTION_REESTABLISHMENT_FAILURE,
-            RRC_CONNECTION_OUT_OF_SERVICE_DURING_CELL_REGISTER,
-            RRC_CONNECTION_ABORT_REQUEST,
-            RRC_CONNECTION_SYSTEM_INFORMATION_BLOCK_READ_ERROR,
-            NETWORK_INITIATED_DETACH_WITH_AUTO_REATTACH,
-            NETWORK_INITIATED_DETACH_NO_AUTO_REATTACH,
-            ESM_PROCEDURE_TIME_OUT,
-            INVALID_CONNECTION_ID,
-            MAXIMIUM_NSAPIS_EXCEEDED,
-            INVALID_PRIMARY_NSAPI,
-            CANNOT_ENCODE_OTA_MESSAGE,
-            RADIO_ACCESS_BEARER_SETUP_FAILURE,
-            PDP_ESTABLISH_TIMEOUT_EXPIRED,
-            PDP_MODIFY_TIMEOUT_EXPIRED,
-            PDP_INACTIVE_TIMEOUT_EXPIRED,
-            PDP_LOWERLAYER_ERROR,
-            PDP_MODIFY_COLLISION,
-            MAXINUM_SIZE_OF_L2_MESSAGE_EXCEEDED,
-            NAS_REQUEST_REJECTED_BY_NETWORK,
-            RRC_CONNECTION_INVALID_REQUEST,
-            RRC_CONNECTION_TRACKING_AREA_ID_CHANGED,
-            RRC_CONNECTION_RF_UNAVAILABLE,
-            RRC_CONNECTION_ABORTED_DUE_TO_IRAT_CHANGE,
-            RRC_CONNECTION_RELEASED_SECURITY_NOT_ACTIVE,
-            RRC_CONNECTION_ABORTED_AFTER_HANDOVER,
-            RRC_CONNECTION_ABORTED_AFTER_IRAT_CELL_CHANGE,
-            RRC_CONNECTION_ABORTED_DURING_IRAT_CELL_CHANGE,
-            IMSI_UNKNOWN_IN_HOME_SUBSCRIBER_SERVER,
-            IMEI_NOT_ACCEPTED,
-            EPS_SERVICES_AND_NON_EPS_SERVICES_NOT_ALLOWED,
-            EPS_SERVICES_NOT_ALLOWED_IN_PLMN,
-            MSC_TEMPORARILY_NOT_REACHABLE,
-            CS_DOMAIN_NOT_AVAILABLE,
-            ESM_FAILURE,
-            MAC_FAILURE,
-            SYNCHRONIZATION_FAILURE,
-            UE_SECURITY_CAPABILITIES_MISMATCH,
-            SECURITY_MODE_REJECTED,
-            UNACCEPTABLE_NON_EPS_AUTHENTICATION,
-            CS_FALLBACK_CALL_ESTABLISHMENT_NOT_ALLOWED,
-            NO_EPS_BEARER_CONTEXT_ACTIVATED,
-            INVALID_EMM_STATE,
-            NAS_LAYER_FAILURE,
-            MULTIPLE_PDP_CALL_NOT_ALLOWED,
-            EMBMS_NOT_ENABLED,
-            IRAT_HANDOVER_FAILED,
-            EMBMS_REGULAR_DEACTIVATION,
-            TEST_LOOPBACK_REGULAR_DEACTIVATION,
-            LOWER_LAYER_REGISTRATION_FAILURE,
-            DATA_PLAN_EXPIRED,
-            UMTS_HANDOVER_TO_IWLAN,
-            EVDO_CONNECTION_DENY_BY_GENERAL_OR_NETWORK_BUSY,
-            EVDO_CONNECTION_DENY_BY_BILLING_OR_AUTHENTICATION_FAILURE,
-            EVDO_HDR_CHANGED,
-            EVDO_HDR_EXITED,
-            EVDO_HDR_NO_SESSION,
-            EVDO_USING_GPS_FIX_INSTEAD_OF_HDR_CALL,
-            EVDO_HDR_CONNECTION_SETUP_TIMEOUT,
-            FAILED_TO_ACQUIRE_COLOCATED_HDR,
-            OTASP_COMMIT_IN_PROGRESS,
-            NO_HYBRID_HDR_SERVICE,
-            HDR_NO_LOCK_GRANTED,
-            DBM_OR_SMS_IN_PROGRESS,
-            HDR_FADE,
-            HDR_ACCESS_FAILURE,
-            UNSUPPORTED_1X_PREV,
-            LOCAL_END,
-            NO_SERVICE,
-            FADE,
-            NORMAL_RELEASE,
-            ACCESS_ATTEMPT_ALREADY_IN_PROGRESS,
-            REDIRECTION_OR_HANDOFF_IN_PROGRESS,
-            EMERGENCY_MODE,
-            PHONE_IN_USE,
-            INVALID_MODE,
-            INVALID_SIM_STATE,
-            NO_COLLOCATED_HDR,
-            UE_IS_ENTERING_POWERSAVE_MODE,
-            DUAL_SWITCH,
-            PPP_TIMEOUT,
-            PPP_AUTH_FAILURE,
-            PPP_OPTION_MISMATCH,
-            PPP_PAP_FAILURE,
-            PPP_CHAP_FAILURE,
-            PPP_CLOSE_IN_PROGRESS,
-            LIMITED_TO_IPV4,
-            LIMITED_TO_IPV6,
-            VSNCP_TIMEOUT,
-            VSNCP_GEN_ERROR,
-            VSNCP_APN_UNATHORIZED,
-            VSNCP_PDN_LIMIT_EXCEEDED,
-            VSNCP_NO_PDN_GATEWAY_ADDRESS,
-            VSNCP_PDN_GATEWAY_UNREACHABLE,
-            VSNCP_PDN_GATEWAY_REJECT,
-            VSNCP_INSUFFICIENT_PARAMETERS,
-            VSNCP_RESOURCE_UNAVAILABLE,
-            VSNCP_ADMINISTRATIVELY_PROHIBITED,
-            VSNCP_PDN_ID_IN_USE,
-            VSNCP_SUBSCRIBER_LIMITATION,
-            VSNCP_PDN_EXISTS_FOR_THIS_APN,
-            VSNCP_RECONNECT_NOT_ALLOWED,
-            IPV6_PREFIX_UNAVAILABLE,
-            HANDOFF_PREFERENCE_CHANGED,
-            OEM_DCFAILCAUSE_1,
-            OEM_DCFAILCAUSE_2,
-            OEM_DCFAILCAUSE_3,
-            OEM_DCFAILCAUSE_4,
-            OEM_DCFAILCAUSE_5,
-            OEM_DCFAILCAUSE_6,
-            OEM_DCFAILCAUSE_7,
-            OEM_DCFAILCAUSE_8,
-            OEM_DCFAILCAUSE_9,
-            OEM_DCFAILCAUSE_10,
-            OEM_DCFAILCAUSE_11,
-            OEM_DCFAILCAUSE_12,
-            OEM_DCFAILCAUSE_13,
-            OEM_DCFAILCAUSE_14,
-            OEM_DCFAILCAUSE_15,
-            REGISTRATION_FAIL,
-            GPRS_REGISTRATION_FAIL,
-            SIGNAL_LOST,
-            PREF_RADIO_TECH_CHANGED,
-            RADIO_POWER_OFF,
-            TETHERED_CALL_ACTIVE,
-            ERROR_UNSPECIFIED,
-            UNKNOWN,
-            RADIO_NOT_AVAILABLE,
-            UNACCEPTABLE_NETWORK_PARAMETER,
-            CONNECTION_TO_DATACONNECTIONAC_BROKEN,
-            LOST_CONNECTION,
-            RESET_BY_FRAMEWORK
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface FailCause{}
-
     private static final Map<Integer, String> sFailCauseMap;
     static {
         sFailCauseMap = new HashMap<>();
@@ -1737,7 +1389,8 @@
      *
      * @hide
      */
-    public static boolean isRadioRestartFailure(@NonNull Context context, @FailCause int cause,
+    public static boolean isRadioRestartFailure(@NonNull Context context,
+                                                @DataFailureCause int cause,
                                                 int subId) {
         CarrierConfigManager configManager = (CarrierConfigManager)
                 context.getSystemService(Context.CARRIER_CONFIG_SERVICE);
@@ -1765,7 +1418,8 @@
     }
 
     /** @hide */
-    public static boolean isPermanentFailure(@NonNull Context context, @FailCause int failCause,
+    public static boolean isPermanentFailure(@NonNull Context context,
+                                             @DataFailureCause int failCause,
                                              int subId) {
         synchronized (sPermanentFailureCache) {
 
@@ -1825,7 +1479,7 @@
     }
 
     /** @hide */
-    public static boolean isEventLoggable(@FailCause int dataFailCause) {
+    public static boolean isEventLoggable(@DataFailureCause int dataFailCause) {
         return (dataFailCause == OPERATOR_BARRED) || (dataFailCause == INSUFFICIENT_RESOURCES)
                 || (dataFailCause == UNKNOWN_PDP_ADDRESS_TYPE)
                 || (dataFailCause == USER_AUTHENTICATION)
@@ -1845,13 +1499,13 @@
     }
 
     /** @hide */
-    public static String toString(@FailCause int dataFailCause) {
+    public static String toString(@DataFailureCause int dataFailCause) {
         int cause = getFailCause(dataFailCause);
         return (cause == UNKNOWN) ? "UNKNOWN(" + dataFailCause + ")" : sFailCauseMap.get(cause);
     }
 
     /** @hide */
-    public static int getFailCause(@FailCause int failCause) {
+    public static int getFailCause(@DataFailureCause int failCause) {
         if (sFailCauseMap.containsKey(failCause)) {
             return failCause;
         } else {
diff --git a/telephony/java/android/telephony/ICellBroadcastService.aidl b/telephony/java/android/telephony/ICellBroadcastService.aidl
new file mode 100644
index 0000000..eff64a2
--- /dev/null
+++ b/telephony/java/android/telephony/ICellBroadcastService.aidl
@@ -0,0 +1,32 @@
+/**
+ * Copyright (c) 2019, 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.telephony;
+
+/**
+ * Service bound to by the system to allow custom handling of cell broadcast messages.
+ * <p>
+ * @see android.telephony.CellBroadcastService
+ * @hide
+ */
+interface ICellBroadcastService {
+
+    /** @see android.telephony.CellBroadcastService#onGsmCellBroadcastSms */
+    oneway void handleGsmCellBroadcastSms(int slotId, in byte[] message);
+
+    /** @see android.telephony.CellBroadcastService#onCdmaCellBroadcastSms */
+    oneway void handleCdmaCellBroadcastSms(int slotId, in byte[] message);
+}
diff --git a/telephony/java/android/telephony/IFinancialSmsCallback.aidl b/telephony/java/android/telephony/IFinancialSmsCallback.aidl
deleted file mode 100644
index aa88615..0000000
--- a/telephony/java/android/telephony/IFinancialSmsCallback.aidl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-** Copyright 2019, 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.telephony;
-
-import android.app.PendingIntent;
-import android.database.CursorWindow;
-import android.net.Uri;
-import android.os.Bundle;
-import com.android.internal.telephony.SmsRawData;
-
-/** Interface for returning back the financial sms messages asynchrously.
- *  @hide
- */
-interface IFinancialSmsCallback {
-    /**
-     * Return sms messages back to calling financial app.
-     *
-     * @param messages the sms messages returned for cinancial app.
-     */
-    oneway void onGetSmsMessagesForFinancialApp(in CursorWindow messages);
-}
diff --git a/telephony/java/android/telephony/MbmsDownloadSession.java b/telephony/java/android/telephony/MbmsDownloadSession.java
index da4da79..45deea2 100644
--- a/telephony/java/android/telephony/MbmsDownloadSession.java
+++ b/telephony/java/android/telephony/MbmsDownloadSession.java
@@ -243,6 +243,7 @@
     };
 
     private AtomicReference<IMbmsDownloadService> mService = new AtomicReference<>(null);
+    private ServiceConnection mServiceConnection;
     private final InternalDownloadSessionCallback mInternalCallback;
     private final Map<DownloadStatusListener, InternalDownloadStatusListener>
             mInternalDownloadStatusListeners = new HashMap<>();
@@ -318,56 +319,66 @@
     }
 
     private int bindAndInitialize() {
-        return MbmsUtils.startBinding(mContext, MBMS_DOWNLOAD_SERVICE_ACTION,
-                new ServiceConnection() {
-                    @Override
-                    public void onServiceConnected(ComponentName name, IBinder service) {
-                        IMbmsDownloadService downloadService =
-                                IMbmsDownloadService.Stub.asInterface(service);
-                        int result;
-                        try {
-                            result = downloadService.initialize(mSubscriptionId, mInternalCallback);
-                        } catch (RemoteException e) {
-                            Log.e(LOG_TAG, "Service died before initialization");
-                            sIsInitialized.set(false);
-                            return;
-                        } catch (RuntimeException e) {
-                            Log.e(LOG_TAG, "Runtime exception during initialization");
-                            sendErrorToApp(
-                                    MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
-                                    e.toString());
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        if (result == MbmsErrors.UNKNOWN) {
-                            // Unbind and throw an obvious error
-                            close();
-                            throw new IllegalStateException("Middleware must not return an"
-                                    + " unknown error code");
-                        }
-                        if (result != MbmsErrors.SUCCESS) {
-                            sendErrorToApp(result, "Error returned during initialization");
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        try {
-                            downloadService.asBinder().linkToDeath(mDeathRecipient, 0);
-                        } catch (RemoteException e) {
-                            sendErrorToApp(MbmsErrors.ERROR_MIDDLEWARE_LOST,
-                                    "Middleware lost during initialization");
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        mService.set(downloadService);
-                    }
+        mServiceConnection = new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                IMbmsDownloadService downloadService =
+                        IMbmsDownloadService.Stub.asInterface(service);
+                int result;
+                try {
+                    result = downloadService.initialize(mSubscriptionId, mInternalCallback);
+                } catch (RemoteException e) {
+                    Log.e(LOG_TAG, "Service died before initialization");
+                    sIsInitialized.set(false);
+                    return;
+                } catch (RuntimeException e) {
+                    Log.e(LOG_TAG, "Runtime exception during initialization");
+                    sendErrorToApp(
+                            MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
+                            e.toString());
+                    sIsInitialized.set(false);
+                    return;
+                }
+                if (result == MbmsErrors.UNKNOWN) {
+                    // Unbind and throw an obvious error
+                    close();
+                    throw new IllegalStateException("Middleware must not return an"
+                            + " unknown error code");
+                }
+                if (result != MbmsErrors.SUCCESS) {
+                    sendErrorToApp(result, "Error returned during initialization");
+                    sIsInitialized.set(false);
+                    return;
+                }
+                try {
+                    downloadService.asBinder().linkToDeath(mDeathRecipient, 0);
+                } catch (RemoteException e) {
+                    sendErrorToApp(MbmsErrors.ERROR_MIDDLEWARE_LOST,
+                            "Middleware lost during initialization");
+                    sIsInitialized.set(false);
+                    return;
+                }
+                mService.set(downloadService);
+            }
 
-                    @Override
-                    public void onServiceDisconnected(ComponentName name) {
-                        Log.w(LOG_TAG, "bindAndInitialize: Remote service disconnected");
-                        sIsInitialized.set(false);
-                        mService.set(null);
-                    }
-                });
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                Log.w(LOG_TAG, "bindAndInitialize: Remote service disconnected");
+                sIsInitialized.set(false);
+                mService.set(null);
+            }
+
+            @Override
+            public void onNullBinding(ComponentName name) {
+                Log.w(LOG_TAG, "bindAndInitialize: Remote service returned null");
+                sendErrorToApp(MbmsErrors.ERROR_MIDDLEWARE_LOST,
+                        "Middleware service binding returned null");
+                sIsInitialized.set(false);
+                mService.set(null);
+                mContext.unbindService(this);
+            }
+        };
+        return MbmsUtils.startBinding(mContext, MBMS_DOWNLOAD_SERVICE_ACTION, mServiceConnection);
     }
 
     /**
@@ -965,17 +976,19 @@
     public void close() {
         try {
             IMbmsDownloadService downloadService = mService.get();
-            if (downloadService == null) {
+            if (downloadService == null || mServiceConnection == null) {
                 Log.i(LOG_TAG, "Service already dead");
                 return;
             }
             downloadService.dispose(mSubscriptionId);
+            mContext.unbindService(mServiceConnection);
         } catch (RemoteException e) {
             // Ignore
             Log.i(LOG_TAG, "Remote exception while disposing of service");
         } finally {
             mService.set(null);
             sIsInitialized.set(false);
+            mServiceConnection = null;
             mInternalCallback.stop();
         }
     }
diff --git a/telephony/java/android/telephony/MbmsGroupCallSession.java b/telephony/java/android/telephony/MbmsGroupCallSession.java
index f1be31f..d54071f 100644
--- a/telephony/java/android/telephony/MbmsGroupCallSession.java
+++ b/telephony/java/android/telephony/MbmsGroupCallSession.java
@@ -80,6 +80,7 @@
     };
 
     private InternalGroupCallSessionCallback mInternalCallback;
+    private ServiceConnection mServiceConnection;
     private Set<GroupCall> mKnownActiveGroupCalls = new ArraySet<>();
 
     private final Context mContext;
@@ -163,7 +164,7 @@
     public void close() {
         try {
             IMbmsGroupCallService groupCallService = mService.get();
-            if (groupCallService == null) {
+            if (groupCallService == null || mServiceConnection == null) {
                 // Ignore and return, assume already disposed.
                 return;
             }
@@ -172,11 +173,13 @@
                 s.getCallback().stop();
             }
             mKnownActiveGroupCalls.clear();
+            mContext.unbindService(mServiceConnection);
         } catch (RemoteException e) {
             // Ignore for now
         } finally {
             mService.set(null);
             sIsInitialized.set(false);
+            mServiceConnection = null;
             mInternalCallback.stop();
         }
     }
@@ -244,59 +247,69 @@
     }
 
     private int bindAndInitialize() {
-        return MbmsUtils.startBinding(mContext, MBMS_GROUP_CALL_SERVICE_ACTION,
-                new ServiceConnection() {
-                    @Override
-                    public void onServiceConnected(ComponentName name, IBinder service) {
-                        IMbmsGroupCallService groupCallService =
-                                IMbmsGroupCallService.Stub.asInterface(service);
-                        int result;
-                        try {
-                            result = groupCallService.initialize(mInternalCallback,
-                                    mSubscriptionId);
-                        } catch (RemoteException e) {
-                            Log.e(LOG_TAG, "Service died before initialization");
-                            mInternalCallback.onError(
-                                    MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
-                                    e.toString());
-                            sIsInitialized.set(false);
-                            return;
-                        } catch (RuntimeException e) {
-                            Log.e(LOG_TAG, "Runtime exception during initialization");
-                            mInternalCallback.onError(
-                                    MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
-                                    e.toString());
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        if (result == MbmsErrors.UNKNOWN) {
-                            // Unbind and throw an obvious error
-                            close();
-                            throw new IllegalStateException("Middleware must not return"
-                                    + " an unknown error code");
-                        }
-                        if (result != MbmsErrors.SUCCESS) {
-                            mInternalCallback.onError(result,
-                                    "Error returned during initialization");
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        try {
-                            groupCallService.asBinder().linkToDeath(mDeathRecipient, 0);
-                        } catch (RemoteException e) {
-                            mInternalCallback.onError(MbmsErrors.ERROR_MIDDLEWARE_LOST,
-                                    "Middleware lost during initialization");
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        mService.set(groupCallService);
-                    }
+        mServiceConnection = new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                IMbmsGroupCallService groupCallService =
+                        IMbmsGroupCallService.Stub.asInterface(service);
+                int result;
+                try {
+                    result = groupCallService.initialize(mInternalCallback,
+                            mSubscriptionId);
+                } catch (RemoteException e) {
+                    Log.e(LOG_TAG, "Service died before initialization");
+                    mInternalCallback.onError(
+                            MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
+                            e.toString());
+                    sIsInitialized.set(false);
+                    return;
+                } catch (RuntimeException e) {
+                    Log.e(LOG_TAG, "Runtime exception during initialization");
+                    mInternalCallback.onError(
+                            MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
+                            e.toString());
+                    sIsInitialized.set(false);
+                    return;
+                }
+                if (result == MbmsErrors.UNKNOWN) {
+                    // Unbind and throw an obvious error
+                    close();
+                    throw new IllegalStateException("Middleware must not return"
+                            + " an unknown error code");
+                }
+                if (result != MbmsErrors.SUCCESS) {
+                    mInternalCallback.onError(result,
+                            "Error returned during initialization");
+                    sIsInitialized.set(false);
+                    return;
+                }
+                try {
+                    groupCallService.asBinder().linkToDeath(mDeathRecipient, 0);
+                } catch (RemoteException e) {
+                    mInternalCallback.onError(MbmsErrors.ERROR_MIDDLEWARE_LOST,
+                            "Middleware lost during initialization");
+                    sIsInitialized.set(false);
+                    return;
+                }
+                mService.set(groupCallService);
+            }
 
-                    @Override
-                    public void onServiceDisconnected(ComponentName name) {
-                        sIsInitialized.set(false);
-                        mService.set(null);
-                    }
-                });
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                sIsInitialized.set(false);
+                mService.set(null);
+            }
+
+            @Override
+            public void onNullBinding(ComponentName name) {
+                Log.w(LOG_TAG, "bindAndInitialize: Remote service returned null");
+                mInternalCallback.onError(MbmsErrors.ERROR_MIDDLEWARE_LOST,
+                        "Middleware service binding returned null");
+                sIsInitialized.set(false);
+                mService.set(null);
+                mContext.unbindService(this);
+            }
+        };
+        return MbmsUtils.startBinding(mContext, MBMS_GROUP_CALL_SERVICE_ACTION, mServiceConnection);
     }
 }
diff --git a/telephony/java/android/telephony/MbmsStreamingSession.java b/telephony/java/android/telephony/MbmsStreamingSession.java
index cd465d2..3fbbc03 100644
--- a/telephony/java/android/telephony/MbmsStreamingSession.java
+++ b/telephony/java/android/telephony/MbmsStreamingSession.java
@@ -82,6 +82,7 @@
     };
 
     private InternalStreamingSessionCallback mInternalCallback;
+    private ServiceConnection mServiceConnection;
     private Set<StreamingService> mKnownActiveStreamingServices = new ArraySet<>();
 
     private final Context mContext;
@@ -168,7 +169,7 @@
     public void close() {
         try {
             IMbmsStreamingService streamingService = mService.get();
-            if (streamingService == null) {
+            if (streamingService == null || mServiceConnection == null) {
                 // Ignore and return, assume already disposed.
                 return;
             }
@@ -177,11 +178,13 @@
                 s.getCallback().stop();
             }
             mKnownActiveStreamingServices.clear();
+            mContext.unbindService(mServiceConnection);
         } catch (RemoteException e) {
             // Ignore for now
         } finally {
             mService.set(null);
             sIsInitialized.set(false);
+            mServiceConnection = null;
             mInternalCallback.stop();
         }
     }
@@ -286,59 +289,69 @@
     }
 
     private int bindAndInitialize() {
-        return MbmsUtils.startBinding(mContext, MBMS_STREAMING_SERVICE_ACTION,
-                new ServiceConnection() {
-                    @Override
-                    public void onServiceConnected(ComponentName name, IBinder service) {
-                        IMbmsStreamingService streamingService =
-                                IMbmsStreamingService.Stub.asInterface(service);
-                        int result;
-                        try {
-                            result = streamingService.initialize(mInternalCallback,
-                                    mSubscriptionId);
-                        } catch (RemoteException e) {
-                            Log.e(LOG_TAG, "Service died before initialization");
-                            sendErrorToApp(
-                                    MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
-                                    e.toString());
-                            sIsInitialized.set(false);
-                            return;
-                        } catch (RuntimeException e) {
-                            Log.e(LOG_TAG, "Runtime exception during initialization");
-                            sendErrorToApp(
-                                    MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
-                                    e.toString());
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        if (result == MbmsErrors.UNKNOWN) {
-                            // Unbind and throw an obvious error
-                            close();
-                            throw new IllegalStateException("Middleware must not return"
-                                    + " an unknown error code");
-                        }
-                        if (result != MbmsErrors.SUCCESS) {
-                            sendErrorToApp(result, "Error returned during initialization");
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        try {
-                            streamingService.asBinder().linkToDeath(mDeathRecipient, 0);
-                        } catch (RemoteException e) {
-                            sendErrorToApp(MbmsErrors.ERROR_MIDDLEWARE_LOST,
-                                    "Middleware lost during initialization");
-                            sIsInitialized.set(false);
-                            return;
-                        }
-                        mService.set(streamingService);
-                    }
+        mServiceConnection = new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                IMbmsStreamingService streamingService =
+                        IMbmsStreamingService.Stub.asInterface(service);
+                int result;
+                try {
+                    result = streamingService.initialize(mInternalCallback,
+                            mSubscriptionId);
+                } catch (RemoteException e) {
+                    Log.e(LOG_TAG, "Service died before initialization");
+                    sendErrorToApp(
+                            MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
+                            e.toString());
+                    sIsInitialized.set(false);
+                    return;
+                } catch (RuntimeException e) {
+                    Log.e(LOG_TAG, "Runtime exception during initialization");
+                    sendErrorToApp(
+                            MbmsErrors.InitializationErrors.ERROR_UNABLE_TO_INITIALIZE,
+                            e.toString());
+                    sIsInitialized.set(false);
+                    return;
+                }
+                if (result == MbmsErrors.UNKNOWN) {
+                    // Unbind and throw an obvious error
+                    close();
+                    throw new IllegalStateException("Middleware must not return"
+                            + " an unknown error code");
+                }
+                if (result != MbmsErrors.SUCCESS) {
+                    sendErrorToApp(result, "Error returned during initialization");
+                    sIsInitialized.set(false);
+                    return;
+                }
+                try {
+                    streamingService.asBinder().linkToDeath(mDeathRecipient, 0);
+                } catch (RemoteException e) {
+                    sendErrorToApp(MbmsErrors.ERROR_MIDDLEWARE_LOST,
+                            "Middleware lost during initialization");
+                    sIsInitialized.set(false);
+                    return;
+                }
+                mService.set(streamingService);
+            }
 
-                    @Override
-                    public void onServiceDisconnected(ComponentName name) {
-                        sIsInitialized.set(false);
-                        mService.set(null);
-                    }
-                });
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                sIsInitialized.set(false);
+                mService.set(null);
+            }
+
+            @Override
+            public void onNullBinding(ComponentName name) {
+                Log.w(LOG_TAG, "bindAndInitialize: Remote service returned null");
+                sendErrorToApp(MbmsErrors.ERROR_MIDDLEWARE_LOST,
+                        "Middleware service binding returned null");
+                sIsInitialized.set(false);
+                mService.set(null);
+                mContext.unbindService(this);
+            }
+        };
+        return MbmsUtils.startBinding(mContext, MBMS_STREAMING_SERVICE_ACTION, mServiceConnection);
     }
 
     private void sendErrorToApp(int errorCode, String message) {
diff --git a/telephony/java/android/telephony/NetworkRegistrationInfo.java b/telephony/java/android/telephony/NetworkRegistrationInfo.java
index a76b8da..3e02871 100644
--- a/telephony/java/android/telephony/NetworkRegistrationInfo.java
+++ b/telephony/java/android/telephony/NetworkRegistrationInfo.java
@@ -24,8 +24,8 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.telephony.AccessNetworkConstants.TransportType;
-import android.telephony.TelephonyManager.NetworkType;
 
+import android.telephony.Annotation.NetworkType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
diff --git a/telephony/java/android/telephony/PhoneStateListener.java b/telephony/java/android/telephony/PhoneStateListener.java
index 1ffed25..1ba0a41 100644
--- a/telephony/java/android/telephony/PhoneStateListener.java
+++ b/telephony/java/android/telephony/PhoneStateListener.java
@@ -20,6 +20,7 @@
 import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
 import android.annotation.SystemApi;
+import android.annotation.TestApi;
 import android.annotation.UnsupportedAppUsage;
 import android.os.Binder;
 import android.os.Build;
@@ -27,6 +28,10 @@
 import android.os.Handler;
 import android.os.HandlerExecutor;
 import android.os.Looper;
+import android.telephony.Annotation.CallState;
+import android.telephony.Annotation.RadioPowerState;
+import android.telephony.Annotation.SimActivationState;
+import android.telephony.Annotation.SrvccState;
 import android.telephony.emergency.EmergencyNumber;
 import android.telephony.ims.ImsReasonInfo;
 
@@ -179,7 +184,8 @@
     public static final int LISTEN_CELL_INFO = 0x00000400;
 
     /**
-     * Listen for {@link PreciseCallState.State} of ringing, background and foreground calls.
+     * Listen for {@link android.telephony.Annotation.PreciseCallStates} of ringing,
+     * background and foreground calls.
      *
      * @hide
      */
@@ -366,8 +372,9 @@
      * @hide
      */
     @SystemApi
+    @TestApi
     @RequiresPermission(Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
-    public static final int LISTEN_OUTGOING_CALL_EMERGENCY_NUMBER           = 0x10000000;
+    public static final int LISTEN_OUTGOING_EMERGENCY_CALL                  = 0x10000000;
 
     /**
      * Listen for the emergency number placed from an outgoing SMS.
@@ -378,8 +385,9 @@
      * @hide
      */
     @SystemApi
+    @TestApi
     @RequiresPermission(Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
-    public static final int LISTEN_OUTGOING_SMS_EMERGENCY_NUMBER            = 0x20000000;
+    public static final int LISTEN_OUTGOING_EMERGENCY_SMS                   = 0x20000000;
 
     /*
      * Subscription used to listen to the phone state changes
@@ -564,7 +572,7 @@
      * privileges (see {@link TelephonyManager#hasCarrierPrivileges}), an empty string will be
      * passed as an argument.
      */
-    public void onCallStateChanged(@TelephonyManager.CallState int state, String phoneNumber) {
+    public void onCallStateChanged(@CallState int state, String phoneNumber) {
         // default implementation empty
     }
 
@@ -770,7 +778,7 @@
      * @hide
      */
     @SystemApi
-    public void onSrvccStateChanged(@TelephonyManager.SrvccState int srvccState) {
+    public void onSrvccStateChanged(@SrvccState int srvccState) {
 
     }
 
@@ -788,7 +796,7 @@
      * @hide
      */
     @SystemApi
-    public void onVoiceActivationStateChanged(@TelephonyManager.SimActivationState int state) {
+    public void onVoiceActivationStateChanged(@SimActivationState int state) {
     }
 
     /**
@@ -804,7 +812,7 @@
      * @param state is the current SIM data activation state
      * @hide
      */
-    public void onDataActivationStateChanged(@TelephonyManager.SimActivationState int state) {
+    public void onDataActivationStateChanged(@SimActivationState int state) {
     }
 
     /**
@@ -869,6 +877,8 @@
      *                              to.
      * @hide
      */
+    @SystemApi
+    @TestApi
     public void onOutgoingEmergencyCall(@NonNull EmergencyNumber placedEmergencyNumber) {
         // default implementation empty
     }
@@ -879,6 +889,8 @@
      * @param sentEmergencyNumber the emergency number {@link EmergencyNumber} the SMS is sent to.
      * @hide
      */
+    @SystemApi
+    @TestApi
     public void onOutgoingEmergencySms(@NonNull EmergencyNumber sentEmergencyNumber) {
         // default implementation empty
     }
@@ -959,7 +971,7 @@
      * @hide
      */
     @SystemApi
-    public void onRadioPowerStateChanged(@TelephonyManager.RadioPowerState int state) {
+    public void onRadioPowerStateChanged(@RadioPowerState int state) {
         // default implementation empty
     }
 
@@ -1226,7 +1238,7 @@
                     () -> mExecutor.execute(() -> psl.onPhoneCapabilityChanged(capability)));
         }
 
-        public void onRadioPowerStateChanged(@TelephonyManager.RadioPowerState int state) {
+        public void onRadioPowerStateChanged(@RadioPowerState int state) {
             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
             if (psl == null) return;
 
diff --git a/telephony/java/android/telephony/PhysicalChannelConfig.java b/telephony/java/android/telephony/PhysicalChannelConfig.java
index e1763ab..4273f5a 100644
--- a/telephony/java/android/telephony/PhysicalChannelConfig.java
+++ b/telephony/java/android/telephony/PhysicalChannelConfig.java
@@ -19,8 +19,8 @@
 import android.annotation.IntDef;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.telephony.TelephonyManager.NetworkType;
 
+import android.telephony.Annotation.NetworkType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.Arrays;
diff --git a/telephony/java/android/telephony/PreciseCallState.java b/telephony/java/android/telephony/PreciseCallState.java
index 701a375..9f75332 100644
--- a/telephony/java/android/telephony/PreciseCallState.java
+++ b/telephony/java/android/telephony/PreciseCallState.java
@@ -23,6 +23,7 @@
 import android.annotation.UnsupportedAppUsage;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.telephony.Annotation.PreciseCallStates;
 import android.telephony.DisconnectCause;
 import android.telephony.PreciseDisconnectCause;
 
@@ -41,29 +42,13 @@
  *   <li>Precise background call state.
  * </ul>
  *
- * @see android.telephony.TelephonyManager.CallState which contains generic call states.
+ * @see android.telephony.Annotation.CallState which contains generic call states.
  *
  * @hide
  */
 @SystemApi
 public final class PreciseCallState implements Parcelable {
 
-    /** @hide */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(prefix = {"PRECISE_CALL_STATE_"},
-            value = {
-                    PRECISE_CALL_STATE_NOT_VALID,
-                    PRECISE_CALL_STATE_IDLE,
-                    PRECISE_CALL_STATE_ACTIVE,
-                    PRECISE_CALL_STATE_HOLDING,
-                    PRECISE_CALL_STATE_DIALING,
-                    PRECISE_CALL_STATE_ALERTING,
-                    PRECISE_CALL_STATE_INCOMING,
-                    PRECISE_CALL_STATE_WAITING,
-                    PRECISE_CALL_STATE_DISCONNECTED,
-                    PRECISE_CALL_STATE_DISCONNECTING})
-    public @interface State {}
-
     /** Call state is not valid (Not received a call state). */
     public static final int PRECISE_CALL_STATE_NOT_VALID =      -1;
     /** Call state: No activity. */
@@ -85,9 +70,9 @@
     /** Call state: Disconnecting. */
     public static final int PRECISE_CALL_STATE_DISCONNECTING =  8;
 
-    private @State int mRingingCallState = PRECISE_CALL_STATE_NOT_VALID;
-    private @State int mForegroundCallState = PRECISE_CALL_STATE_NOT_VALID;
-    private @State int mBackgroundCallState = PRECISE_CALL_STATE_NOT_VALID;
+    private @PreciseCallStates int mRingingCallState = PRECISE_CALL_STATE_NOT_VALID;
+    private @PreciseCallStates int mForegroundCallState = PRECISE_CALL_STATE_NOT_VALID;
+    private @PreciseCallStates int mBackgroundCallState = PRECISE_CALL_STATE_NOT_VALID;
     private int mDisconnectCause = DisconnectCause.NOT_VALID;
     private int mPreciseDisconnectCause = PreciseDisconnectCause.NOT_VALID;
 
@@ -97,8 +82,9 @@
      * @hide
      */
     @UnsupportedAppUsage
-    public PreciseCallState(@State int ringingCall, @State int foregroundCall,
-                            @State int backgroundCall, int disconnectCause,
+    public PreciseCallState(@PreciseCallStates int ringingCall,
+                            @PreciseCallStates int foregroundCall,
+                            @PreciseCallStates int backgroundCall, int disconnectCause,
                             int preciseDisconnectCause) {
         mRingingCallState = ringingCall;
         mForegroundCallState = foregroundCall;
@@ -131,21 +117,21 @@
     /**
      * Returns the precise ringing call state.
      */
-    public @State int getRingingCallState() {
+    public @PreciseCallStates int getRingingCallState() {
         return mRingingCallState;
     }
 
     /**
      * Returns the precise foreground call state.
      */
-    public @State int getForegroundCallState() {
+    public @PreciseCallStates int getForegroundCallState() {
         return mForegroundCallState;
     }
 
     /**
      * Returns the precise background call state.
      */
-    public @State int getBackgroundCallState() {
+    public @PreciseCallStates int getBackgroundCallState() {
         return mBackgroundCallState;
     }
 
diff --git a/telephony/java/android/telephony/PreciseDataConnectionState.java b/telephony/java/android/telephony/PreciseDataConnectionState.java
index 90d443a..257d634 100644
--- a/telephony/java/android/telephony/PreciseDataConnectionState.java
+++ b/telephony/java/android/telephony/PreciseDataConnectionState.java
@@ -23,6 +23,10 @@
 import android.net.LinkProperties;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.telephony.Annotation.ApnType;
+import android.telephony.Annotation.DataFailureCause;
+import android.telephony.Annotation.DataState;
+import android.telephony.Annotation.NetworkType;
 import android.telephony.data.ApnSetting;
 
 import java.util.Objects;
@@ -47,10 +51,10 @@
 @SystemApi
 public final class PreciseDataConnectionState implements Parcelable {
 
-    private @TelephonyManager.DataState int mState = TelephonyManager.DATA_UNKNOWN;
-    private @TelephonyManager.NetworkType int mNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
-    private @DataFailCause.FailCause int mFailCause = DataFailCause.NONE;
-    private @ApnSetting.ApnType int mAPNTypes = ApnSetting.TYPE_NONE;
+    private @DataState int mState = TelephonyManager.DATA_UNKNOWN;
+    private @NetworkType int mNetworkType = TelephonyManager.NETWORK_TYPE_UNKNOWN;
+    private @DataFailureCause int mFailCause = DataFailCause.NONE;
+    private @ApnType int mAPNTypes = ApnSetting.TYPE_NONE;
     private String mAPN = "";
     private LinkProperties mLinkProperties = null;
 
@@ -60,11 +64,11 @@
      * @hide
      */
     @UnsupportedAppUsage
-    public PreciseDataConnectionState(@TelephonyManager.DataState int state,
-                                      @TelephonyManager.NetworkType int networkType,
-                                      @ApnSetting.ApnType int apnTypes, String apn,
+    public PreciseDataConnectionState(@DataState int state,
+                                      @NetworkType int networkType,
+                                      @ApnType int apnTypes, String apn,
                                       LinkProperties linkProperties,
-                                      @DataFailCause.FailCause int failCause) {
+                                      @DataFailureCause int failCause) {
         mState = state;
         mNetworkType = networkType;
         mAPNTypes = apnTypes;
@@ -99,7 +103,7 @@
      * Returns the state of data connection that supported the apn types returned by
      * {@link #getDataConnectionApnTypeBitMask()}
      */
-    public @TelephonyManager.DataState int getDataConnectionState() {
+    public @DataState int getDataConnectionState() {
         return mState;
     }
 
@@ -107,7 +111,7 @@
      * Returns the network type associated with this data connection.
      * @hide
      */
-    public @TelephonyManager.NetworkType int getDataConnectionNetworkType() {
+    public @NetworkType int getDataConnectionNetworkType() {
         return mNetworkType;
     }
 
@@ -115,7 +119,7 @@
      * Returns the data connection APN types supported by this connection and triggers
      * {@link PreciseDataConnectionState} change.
      */
-    public @ApnSetting.ApnType int getDataConnectionApnTypeBitMask() {
+    public @ApnType int getDataConnectionApnTypeBitMask() {
         return mAPNTypes;
     }
 
@@ -139,7 +143,7 @@
     /**
      * Returns data connection fail cause, in case there was a failure.
      */
-    public @DataFailCause.FailCause int getDataConnectionFailCause() {
+    public @Annotation.DataFailureCause int getDataConnectionFailCause() {
         return mFailCause;
     }
 
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index a985a6b..1d00b4f 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -29,6 +29,8 @@
 import android.os.Parcelable;
 import android.telephony.AccessNetworkConstants.AccessNetworkType;
 import android.telephony.AccessNetworkConstants.TransportType;
+import android.telephony.Annotation.NetworkType;
+import android.telephony.Annotation.RilRadioTechnology;
 import android.telephony.NetworkRegistrationInfo.Domain;
 import android.telephony.NetworkRegistrationInfo.NRState;
 import android.text.TextUtils;
@@ -154,32 +156,6 @@
      */
     public static final int DUPLEX_MODE_TDD = 2;
 
-    /** @hide */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(prefix = { "RIL_RADIO_TECHNOLOGY_" },
-            value = {
-                    RIL_RADIO_TECHNOLOGY_UNKNOWN,
-                    RIL_RADIO_TECHNOLOGY_GPRS,
-                    RIL_RADIO_TECHNOLOGY_EDGE,
-                    RIL_RADIO_TECHNOLOGY_UMTS,
-                    RIL_RADIO_TECHNOLOGY_IS95A,
-                    RIL_RADIO_TECHNOLOGY_IS95B,
-                    RIL_RADIO_TECHNOLOGY_1xRTT,
-                    RIL_RADIO_TECHNOLOGY_EVDO_0,
-                    RIL_RADIO_TECHNOLOGY_EVDO_A,
-                    RIL_RADIO_TECHNOLOGY_HSDPA,
-                    RIL_RADIO_TECHNOLOGY_HSUPA,
-                    RIL_RADIO_TECHNOLOGY_HSPA,
-                    RIL_RADIO_TECHNOLOGY_EVDO_B,
-                    RIL_RADIO_TECHNOLOGY_EHRPD,
-                    RIL_RADIO_TECHNOLOGY_LTE,
-                    RIL_RADIO_TECHNOLOGY_HSPAP,
-                    RIL_RADIO_TECHNOLOGY_GSM,
-                    RIL_RADIO_TECHNOLOGY_TD_SCDMA,
-                    RIL_RADIO_TECHNOLOGY_IWLAN,
-                    RIL_RADIO_TECHNOLOGY_LTE_CA,
-                    RIL_RADIO_TECHNOLOGY_NR})
-    public @interface RilRadioTechnology {}
     /**
      * Available radio technologies for GSM, UMTS and CDMA.
      * Duplicates the constants from hardware/radio/include/ril.h
@@ -987,6 +963,9 @@
             case RIL_RADIO_TECHNOLOGY_LTE_CA:
                 rtString = "LTE_CA";
                 break;
+            case RIL_RADIO_TECHNOLOGY_NR:
+                rtString = "LTE_NR";
+                break;
             default:
                 rtString = "Unexpected";
                 Rlog.w(LOG_TAG, "Unexpected radioTechnology=" + rt);
@@ -1553,6 +1532,7 @@
                 return AccessNetworkType.CDMA2000;
             case RIL_RADIO_TECHNOLOGY_LTE:
             case RIL_RADIO_TECHNOLOGY_LTE_CA:
+            case RIL_RADIO_TECHNOLOGY_NR:
                 return AccessNetworkType.EUTRAN;
             case RIL_RADIO_TECHNOLOGY_IWLAN:
                 return AccessNetworkType.IWLAN;
@@ -1601,6 +1581,8 @@
                 return ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN;
             case TelephonyManager.NETWORK_TYPE_LTE_CA:
                 return ServiceState.RIL_RADIO_TECHNOLOGY_LTE_CA;
+            case TelephonyManager.NETWORK_TYPE_NR:
+                return ServiceState.RIL_RADIO_TECHNOLOGY_NR;
             default:
                 return ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN;
         }
@@ -1617,7 +1599,7 @@
      * @hide
      */
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
-    public @TelephonyManager.NetworkType int getDataNetworkType() {
+    public @NetworkType int getDataNetworkType() {
         final NetworkRegistrationInfo iwlanRegInfo = getNetworkRegistrationInfo(
                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
         final NetworkRegistrationInfo wwanRegInfo = getNetworkRegistrationInfo(
@@ -1644,7 +1626,7 @@
 
     /** @hide */
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
-    public @TelephonyManager.NetworkType int getVoiceNetworkType() {
+    public @NetworkType int getVoiceNetworkType() {
         final NetworkRegistrationInfo regState = getNetworkRegistrationInfo(
                 NetworkRegistrationInfo.DOMAIN_CS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
         if (regState != null) {
@@ -1691,7 +1673,8 @@
                 || radioTechnology == RIL_RADIO_TECHNOLOGY_GSM
                 || radioTechnology == RIL_RADIO_TECHNOLOGY_TD_SCDMA
                 || radioTechnology == RIL_RADIO_TECHNOLOGY_IWLAN
-                || radioTechnology == RIL_RADIO_TECHNOLOGY_LTE_CA;
+                || radioTechnology == RIL_RADIO_TECHNOLOGY_LTE_CA
+                || radioTechnology == RIL_RADIO_TECHNOLOGY_NR;
 
     }
 
diff --git a/telephony/java/android/telephony/SmsCbMessage.java b/telephony/java/android/telephony/SmsCbMessage.java
index c078764..dc991b9 100644
--- a/telephony/java/android/telephony/SmsCbMessage.java
+++ b/telephony/java/android/telephony/SmsCbMessage.java
@@ -207,17 +207,19 @@
     /** CMAS warning area coordinates. */
     private final List<Geometry> mGeometries;
 
+    private int mSlotIndex = 0;
+
     /**
      * Create a new SmsCbMessage with the specified data.
      */
     public SmsCbMessage(int messageFormat, int geographicalScope, int serialNumber,
             @NonNull SmsCbLocation location, int serviceCategory, @Nullable String language,
             @Nullable String body, int priority, @Nullable SmsCbEtwsInfo etwsWarningInfo,
-            @Nullable SmsCbCmasInfo cmasWarningInfo) {
+            @Nullable SmsCbCmasInfo cmasWarningInfo, int slotIndex) {
 
         this(messageFormat, geographicalScope, serialNumber, location, serviceCategory, language,
                 body, priority, etwsWarningInfo, cmasWarningInfo, 0 /* maximumWaitingTime */,
-                null /* geometries */, System.currentTimeMillis());
+                null /* geometries */, System.currentTimeMillis(), slotIndex);
     }
 
     /**
@@ -227,7 +229,8 @@
     public SmsCbMessage(int messageFormat, int geographicalScope, int serialNumber,
             SmsCbLocation location, int serviceCategory, String language, String body,
             int priority, SmsCbEtwsInfo etwsWarningInfo, SmsCbCmasInfo cmasWarningInfo,
-            int maximumWaitTimeSec, List<Geometry> geometries, long receivedTimeMillis) {
+            int maximumWaitTimeSec, List<Geometry> geometries, long receivedTimeMillis,
+            int slotIndex) {
         mMessageFormat = messageFormat;
         mGeographicalScope = geographicalScope;
         mSerialNumber = serialNumber;
@@ -241,6 +244,7 @@
         mReceivedTimeMillis = receivedTimeMillis;
         mGeometries = geometries;
         mMaximumWaitTimeSec = maximumWaitTimeSec;
+        mSlotIndex = slotIndex;
     }
 
     /**
@@ -278,6 +282,7 @@
         String geoStr = in.readString();
         mGeometries = geoStr != null ? CbGeoUtils.parseGeometriesFromString(geoStr) : null;
         mMaximumWaitTimeSec = in.readInt();
+        mSlotIndex = in.readInt();
     }
 
     /**
@@ -312,6 +317,7 @@
         dest.writeString(
                 mGeometries != null ? CbGeoUtils.encodeGeometriesToString(mGeometries) : null);
         dest.writeInt(mMaximumWaitTimeSec);
+        dest.writeInt(mSlotIndex);
     }
 
     @NonNull
@@ -423,6 +429,14 @@
     }
 
     /**
+     * Get the slotIndex associated with this message.
+     * @return the slotIndex associated with this message
+     */
+    public int getSlotIndex() {
+        return mSlotIndex;
+    }
+
+    /**
      * Get the message format ({@link #MESSAGE_FORMAT_3GPP} or {@link #MESSAGE_FORMAT_3GPP2}).
      * @return an integer representing 3GPP or 3GPP2 message format
      */
@@ -502,6 +516,7 @@
                 + (mEtwsWarningInfo != null ? (", " + mEtwsWarningInfo.toString()) : "")
                 + (mCmasWarningInfo != null ? (", " + mCmasWarningInfo.toString()) : "")
                 + ", maximumWaitingTime = " + mMaximumWaitTimeSec
+                + ", slotIndex = " + mSlotIndex
                 + ", geo=" + (mGeometries != null
                 ? CbGeoUtils.encodeGeometriesToString(mGeometries) : "null")
                 + '}';
@@ -522,6 +537,7 @@
     @NonNull
     public ContentValues getContentValues() {
         ContentValues cv = new ContentValues(16);
+        cv.put(CellBroadcasts.SLOT_INDEX, mSlotIndex);
         cv.put(CellBroadcasts.GEOGRAPHICAL_SCOPE, mGeographicalScope);
         if (mLocation.getPlmn() != null) {
             cv.put(CellBroadcasts.PLMN, mLocation.getPlmn());
@@ -563,6 +579,7 @@
         }
 
         cv.put(CellBroadcasts.MAXIMUM_WAIT_TIME, mMaximumWaitTimeSec);
+        cv.put(CellBroadcasts.SLOT_INDEX, mSlotIndex);
 
         return cv;
     }
@@ -584,6 +601,7 @@
         String body = cursor.getString(cursor.getColumnIndexOrThrow(CellBroadcasts.MESSAGE_BODY));
         int format = cursor.getInt(cursor.getColumnIndexOrThrow(CellBroadcasts.MESSAGE_FORMAT));
         int priority = cursor.getInt(cursor.getColumnIndexOrThrow(CellBroadcasts.MESSAGE_PRIORITY));
+        int slotIndex = cursor.getInt(cursor.getColumnIndexOrThrow(CellBroadcasts.SLOT_INDEX));
 
         String plmn;
         int plmnColumn = cursor.getColumnIndex(CellBroadcasts.PLMN);
@@ -681,7 +699,7 @@
 
         return new SmsCbMessage(format, geoScope, serialNum, location, category,
                 language, body, priority, etwsInfo, cmasInfo, maximumWaitTimeSec, geometries,
-                receivedTimeMillis);
+                receivedTimeMillis, slotIndex);
     }
 
     /**
diff --git a/telephony/java/android/telephony/SmsManager.java b/telephony/java/android/telephony/SmsManager.java
index 8c14cb4..f4330fa 100644
--- a/telephony/java/android/telephony/SmsManager.java
+++ b/telephony/java/android/telephony/SmsManager.java
@@ -27,14 +27,13 @@
 import android.annotation.UnsupportedAppUsage;
 import android.app.ActivityThread;
 import android.app.PendingIntent;
-import android.content.ContentValues;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.database.CursorWindow;
 import android.net.Uri;
-import android.os.BaseBundle;
 import android.os.Binder;
+import android.os.BaseBundle;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.RemoteException;
@@ -45,7 +44,6 @@
 import android.util.Log;
 
 import com.android.internal.telephony.IIntegerConsumer;
-import com.android.internal.telephony.IMms;
 import com.android.internal.telephony.ISms;
 import com.android.internal.telephony.ITelephony;
 import com.android.internal.telephony.SmsRawData;
@@ -357,6 +355,68 @@
                 true /* persistMessage*/, ActivityThread.currentPackageName());
     }
 
+    /**
+     * Send a text based SMS with messaging options.
+     *
+     * <p class="note"><strong>Note:</strong> If {@link #getDefault()} is used to instantiate this
+     * manager on a multi-SIM device, this operation may fail sending the SMS message because no
+     * suitable default subscription could be found. In this case, if {@code sentIntent} is
+     * non-null, then the {@link PendingIntent} will be sent with an error code
+     * {@code RESULT_ERROR_GENERIC_FAILURE} and an extra string {@code "noDefault"} containing the
+     * boolean value {@code true}. See {@link #getDefault()} for more information on the conditions
+     * where this operation may fail.
+     * </p>
+     *
+     * @param destinationAddress the address to send the message to
+     * @param scAddress is the service center address or null to use
+     *  the current default SMSC
+     * @param text the body of the message to send
+     * @param sentIntent if not NULL this <code>PendingIntent</code> is
+     *  broadcast when the message is successfully sent, or failed.
+     *  The result code will be <code>Activity.RESULT_OK</code> for success,
+     *  or one of these errors:<br>
+     *  <code>RESULT_ERROR_GENERIC_FAILURE</code><br>
+     *  <code>RESULT_ERROR_RADIO_OFF</code><br>
+     *  <code>RESULT_ERROR_NULL_PDU</code><br>
+     *  For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include
+     *  the extra "errorCode" containing a radio technology specific value,
+     *  generally only useful for troubleshooting.<br>
+     *  The per-application based SMS control checks sentIntent. If sentIntent
+     *  is NULL the caller will be checked against all unknown applications,
+     *  which cause smaller number of SMS to be sent in checking period.
+     * @param deliveryIntent if not NULL this <code>PendingIntent</code> is
+     *  broadcast when the message is delivered to the recipient.  The
+     *  raw pdu of the status report is in the extended data ("pdu").
+     * @param priority Priority level of the message
+     *  Refer specification See 3GPP2 C.S0015-B, v2.0, table 4.5.9-1
+     *  ---------------------------------
+     *  PRIORITY      | Level of Priority
+     *  ---------------------------------
+     *      '00'      |     Normal
+     *      '01'      |     Interactive
+     *      '10'      |     Urgent
+     *      '11'      |     Emergency
+     *  ----------------------------------
+     *  Any Other values included Negative considered as Invalid Priority Indicator of the message.
+     * @param expectMore is a boolean to indicate the sending messages through same link or not.
+     * @param validityPeriod Validity Period of the message in mins.
+     *  Refer specification 3GPP TS 23.040 V6.8.1 section 9.2.3.12.1.
+     *  Validity Period(Minimum) -> 5 mins
+     *  Validity Period(Maximum) -> 635040 mins(i.e.63 weeks).
+     *  Any Other values included Negative considered as Invalid Validity Period of the message.
+     *
+     * @throws IllegalArgumentException if destinationAddress or text are empty
+     * {@hide}
+     */
+    @UnsupportedAppUsage
+    public void sendTextMessage(
+            String destinationAddress, String scAddress, String text,
+            PendingIntent sentIntent, PendingIntent deliveryIntent,
+            int priority, boolean expectMore, int validityPeriod) {
+        sendTextMessageInternal(destinationAddress, scAddress, text, sentIntent, deliveryIntent,
+                true /* persistMessage*/, priority, expectMore, validityPeriod);
+    }
+
     private void sendTextMessageInternal(String destinationAddress, String scAddress,
             String text, PendingIntent sentIntent, PendingIntent deliveryIntent,
             boolean persistMessage, String packageName) {
@@ -455,109 +515,6 @@
                 false /* persistMessage */, ActivityThread.currentPackageName());
     }
 
-    /**
-     * A variant of {@link SmsManager#sendTextMessage} that allows self to be the caller. This is
-     * for internal use only.
-     *
-     * <p class="note"><strong>Note:</strong> This method is intended for internal use by carrier
-     * applications or the Telephony framework and will never trigger an SMS disambiguation
-     * dialog. If this method is called on a device that has multiple active subscriptions, this
-     * {@link SmsManager} instance has been created with {@link #getDefault()}, and no user-defined
-     * default subscription is defined, the subscription ID associated with this message will be
-     * INVALID, which will result in the SMS being sent on the subscription associated with logical
-     * slot 0. Use {@link #getSmsManagerForSubscriptionId(int)} to ensure the SMS is sent on the
-     * correct subscription.
-     * </p>
-     *
-     * @param persistMessage whether to persist the sent message in the SMS app. the caller must be
-     * the Phone process if set to false.
-     *
-     * @hide
-     */
-    public void sendTextMessageWithSelfPermissions(
-            String destinationAddress, String scAddress, String text,
-            PendingIntent sentIntent, PendingIntent deliveryIntent, boolean persistMessage) {
-        if (TextUtils.isEmpty(destinationAddress)) {
-            throw new IllegalArgumentException("Invalid destinationAddress");
-        }
-
-        if (TextUtils.isEmpty(text)) {
-            throw new IllegalArgumentException("Invalid message body");
-        }
-
-        try {
-            ISms iSms = getISmsServiceOrThrow();
-            iSms.sendTextForSubscriberWithSelfPermissions(getSubscriptionId(),
-                    ActivityThread.currentPackageName(),
-                    destinationAddress,
-                    scAddress, text, sentIntent, deliveryIntent, persistMessage);
-        } catch (RemoteException ex) {
-            notifySmsGenericError(sentIntent);
-        }
-    }
-
-    /**
-     * Send a text based SMS with messaging options.
-     *
-     * <p class="note"><strong>Note:</strong> If {@link #getDefault()} is used to instantiate this
-     * manager on a multi-SIM device, this operation may fail sending the SMS message because no
-     * suitable default subscription could be found. In this case, if {@code sentIntent} is
-     * non-null, then the {@link PendingIntent} will be sent with an error code
-     * {@code RESULT_ERROR_GENERIC_FAILURE} and an extra string {@code "noDefault"} containing the
-     * boolean value {@code true}. See {@link #getDefault()} for more information on the conditions
-     * where this operation may fail.
-     * </p>
-     *
-     * @param destinationAddress the address to send the message to
-     * @param scAddress is the service center address or null to use
-     *  the current default SMSC
-     * @param text the body of the message to send
-     * @param sentIntent if not NULL this <code>PendingIntent</code> is
-     *  broadcast when the message is successfully sent, or failed.
-     *  The result code will be <code>Activity.RESULT_OK</code> for success,
-     *  or one of these errors:<br>
-     *  <code>RESULT_ERROR_GENERIC_FAILURE</code><br>
-     *  <code>RESULT_ERROR_RADIO_OFF</code><br>
-     *  <code>RESULT_ERROR_NULL_PDU</code><br>
-     *  For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include
-     *  the extra "errorCode" containing a radio technology specific value,
-     *  generally only useful for troubleshooting.<br>
-     *  The per-application based SMS control checks sentIntent. If sentIntent
-     *  is NULL the caller will be checked against all unknown applications,
-     *  which cause smaller number of SMS to be sent in checking period.
-     * @param deliveryIntent if not NULL this <code>PendingIntent</code> is
-     *  broadcast when the message is delivered to the recipient.  The
-     *  raw pdu of the status report is in the extended data ("pdu").
-     * @param priority Priority level of the message
-     *  Refer specification See 3GPP2 C.S0015-B, v2.0, table 4.5.9-1
-     *  ---------------------------------
-     *  PRIORITY      | Level of Priority
-     *  ---------------------------------
-     *      '00'      |     Normal
-     *      '01'      |     Interactive
-     *      '10'      |     Urgent
-     *      '11'      |     Emergency
-     *  ----------------------------------
-     *  Any Other values included Negative considered as Invalid Priority Indicator of the message.
-     * @param expectMore is a boolean to indicate the sending messages through same link or not.
-     * @param validityPeriod Validity Period of the message in mins.
-     *  Refer specification 3GPP TS 23.040 V6.8.1 section 9.2.3.12.1.
-     *  Validity Period(Minimum) -> 5 mins
-     *  Validity Period(Maximum) -> 635040 mins(i.e.63 weeks).
-     *  Any Other values included Negative considered as Invalid Validity Period of the message.
-     *
-     * @throws IllegalArgumentException if destinationAddress or text are empty
-     * {@hide}
-     */
-    @UnsupportedAppUsage
-    public void sendTextMessage(
-            String destinationAddress, String scAddress, String text,
-            PendingIntent sentIntent, PendingIntent deliveryIntent,
-            int priority, boolean expectMore, int validityPeriod) {
-        sendTextMessageInternal(destinationAddress, scAddress, text, sentIntent, deliveryIntent,
-                true /* persistMessage*/, priority, expectMore, validityPeriod);
-    }
-
     private void sendTextMessageInternal(
             String destinationAddress, String scAddress, String text,
             PendingIntent sentIntent, PendingIntent deliveryIntent, boolean persistMessage,
@@ -1078,37 +1035,6 @@
     }
 
     /**
-     * Send a multi-part text based SMS without writing it into the SMS Provider.
-     *
-     * <p>Requires Permission:
-     * {@link android.Manifest.permission#MODIFY_PHONE_STATE} or the calling app has carrier
-     * privileges.
-     * </p>
-     *
-     * <p class="note"><strong>Note:</strong> This method is intended for internal use the Telephony
-     * framework and will never trigger an SMS disambiguation dialog. If this method is called on a
-     * device that has multiple active subscriptions, this {@link SmsManager} instance has been
-     * created with {@link #getDefault()}, and no user-defined default subscription is defined, the
-     * subscription ID associated with this message will be INVALID, which will result in the SMS
-     * being sent on the subscription associated with logical slot 0. Use
-     * {@link #getSmsManagerForSubscriptionId(int)} to ensure the SMS is sent on the correct
-     * subscription.
-     * </p>
-     *
-     * @see #sendMultipartTextMessage(String, String, ArrayList, ArrayList,
-     * ArrayList, int, boolean, int)
-     * @hide
-     **/
-    public void sendMultipartTextMessageWithoutPersisting(
-            String destinationAddress, String scAddress, List<String> parts,
-            List<PendingIntent> sentIntents, List<PendingIntent> deliveryIntents,
-            int priority, boolean expectMore, int validityPeriod) {
-        sendMultipartTextMessageInternal(destinationAddress, scAddress, parts, sentIntents,
-                deliveryIntents, false /* persistMessage*/, priority, expectMore,
-                validityPeriod);
-    }
-
-    /**
      * Send a data based SMS to a specific application port.
      *
      * <p class="note"><strong>Note:</strong> Using this method requires that your app has the
@@ -1180,45 +1106,6 @@
     }
 
     /**
-     * A variant of {@link SmsManager#sendDataMessage} that allows self to be the caller. This is
-     * for internal use only.
-     *
-     * <p class="note"><strong>Note:</strong> This method is intended for internal use by carrier
-     * applications or the Telephony framework and will never trigger an SMS disambiguation
-     * dialog. If this method is called on a device that has multiple active subscriptions, this
-     * {@link SmsManager} instance has been created with {@link #getDefault()}, and no user-defined
-     * default subscription is defined, the subscription ID associated with this message will be
-     * INVALID, which will result in the SMS being sent on the subscription associated with logical
-     * slot 0. Use {@link #getSmsManagerForSubscriptionId(int)} to ensure the SMS is sent on the
-     * correct subscription.
-     * </p>
-     *
-     * @hide
-     */
-    public void sendDataMessageWithSelfPermissions(
-            String destinationAddress, String scAddress, short destinationPort,
-            byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent) {
-        if (TextUtils.isEmpty(destinationAddress)) {
-            throw new IllegalArgumentException("Invalid destinationAddress");
-        }
-
-        if (data == null || data.length == 0) {
-            throw new IllegalArgumentException("Invalid message data");
-        }
-
-        try {
-            ISms iSms = getISmsServiceOrThrow();
-            iSms.sendDataForSubscriberWithSelfPermissions(getSubscriptionId(),
-                    ActivityThread.currentPackageName(), destinationAddress, scAddress,
-                    destinationPort & 0xFFFF, data, sentIntent, deliveryIntent);
-        } catch (RemoteException e) {
-            Log.e(TAG, "sendDataMessageWithSelfPermissions: Couldn't send SMS - Exception: "
-                    + e.getMessage());
-            notifySmsGenericError(sentIntent);
-        }
-    }
-
-    /**
      * Get the SmsManager associated with the default subscription id. The instance will always be
      * associated with the default subscription id, even if the default subscription id changes.
      *
@@ -1650,100 +1537,6 @@
 
     /**
      * Enable reception of cell broadcast (SMS-CB) messages with the given
-     * message identifier and RAN type. The RAN type specify this message ID
-     * belong to 3GPP (GSM) or 3GPP2(CDMA).Note that if two different clients
-     * enable the same message identifier, they must both disable it for the device to stop
-     * receiving those messages. All received messages will be broadcast in an
-     * intent with the action "android.provider.Telephony.SMS_CB_RECEIVED".
-     * Note: This call is blocking, callers may want to avoid calling it from
-     * the main thread of an application.
-     *
-     * <p class="note"><strong>Note:</strong> This method is intended for internal use by carrier
-     * applications or the Telephony framework and will never trigger an SMS disambiguation
-     * dialog. If this method is called on a device that has multiple active subscriptions, this
-     * {@link SmsManager} instance has been created with {@link #getDefault()}, and no user-defined
-     * default subscription is defined, the subscription ID associated with this message will be
-     * INVALID, which will result in the operation being completed on the subscription associated
-     * with logical slot 0. Use {@link #getSmsManagerForSubscriptionId(int)} to ensure the
-     * operation is performed on the correct subscription.
-     * </p>
-     *
-     * @param messageIdentifier Message identifier as specified in TS 23.041 (3GPP)
-     * or C.R1001-G (3GPP2)
-     * @param ranType the message format as defined in {@link SmsCbMessage]
-     * @return true if successful, false otherwise
-     * @see #disableCellBroadcast(int, int)
-     *
-     * {@hide}
-     */
-    public boolean enableCellBroadcast(int messageIdentifier,
-            @android.telephony.SmsCbMessage.MessageFormat int ranType) {
-        boolean success = false;
-
-        try {
-            ISms iSms = getISmsService();
-            if (iSms != null) {
-                // If getSubscriptionId() returns INVALID or an inactive subscription, we will use
-                // the default phone internally.
-                success = iSms.enableCellBroadcastForSubscriber(getSubscriptionId(),
-                        messageIdentifier, ranType);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-
-        return success;
-    }
-
-    /**
-     * Disable reception of cell broadcast (SMS-CB) messages with the given
-     * message identifier and RAN type. The RAN type specify this message ID
-     * belong to 3GPP (GSM) or 3GPP2(CDMA). Note that if two different clients
-     * enable the same message identifier, they must both disable it for the
-     * device to stop receiving those messages.
-     * Note: This call is blocking, callers may want to avoid calling it from
-     * the main thread of an application.
-     *
-     * <p class="note"><strong>Note:</strong> This method is intended for internal use by carrier
-     * applications or the Telephony framework and will never trigger an SMS disambiguation
-     * dialog. If this method is called on a device that has multiple active subscriptions, this
-     * {@link SmsManager} instance has been created with {@link #getDefault()}, and no user-defined
-     * default subscription is defined, the subscription ID associated with this message will be
-     * INVALID, which will result in the operation being completed on the subscription associated
-     * with logical slot 0. Use {@link #getSmsManagerForSubscriptionId(int)} to ensure the
-     * operation is performed on the correct subscription.
-     * </p>
-     *
-     * @param messageIdentifier Message identifier as specified in TS 23.041 (3GPP)
-     * or C.R1001-G (3GPP2)
-     * @param ranType the message format as defined in {@link SmsCbMessage}
-     * @return true if successful, false otherwise
-     *
-     * @see #enableCellBroadcast(int, int)
-     *
-     * {@hide}
-     */
-    public boolean disableCellBroadcast(int messageIdentifier,
-            @android.telephony.SmsCbMessage.MessageFormat int ranType) {
-        boolean success = false;
-
-        try {
-            ISms iSms = getISmsService();
-            if (iSms != null) {
-                // If getSubscriptionId() returns INVALID or an inactive subscription, we will use
-                // the default phone internally.
-                success = iSms.disableCellBroadcastForSubscriber(getSubscriptionId(),
-                        messageIdentifier, ranType);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-
-        return success;
-    }
-
-    /**
-     * Enable reception of cell broadcast (SMS-CB) messages with the given
      * message identifier range and RAN type. The RAN type specifies if this message ID
      * belongs to 3GPP (GSM) or 3GPP2(CDMA). Note that if two different clients enable
      * the same message identifier, they must both disable it for the device to stop
@@ -2144,9 +1937,6 @@
     @SystemApi
     static public final int RESULT_REQUEST_NOT_SUPPORTED = 24;
 
-
-    static private final String PHONE_PACKAGE_NAME = "com.android.phone";
-
     /**
      * Send an MMS message
      *
@@ -2173,17 +1963,8 @@
         if (contentUri == null) {
             throw new IllegalArgumentException("Uri contentUri null");
         }
-        try {
-            final IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms == null) {
-                return;
-            }
-
-            iMms.sendMessage(getSubscriptionId(), ActivityThread.currentPackageName(), contentUri,
+        MmsManager.getInstance().sendMultimediaMessage(getSubscriptionId(), contentUri,
                     locationUrl, configOverrides, sentIntent);
-        } catch (RemoteException e) {
-            // Ignore it
-        }
     }
 
     /**
@@ -2216,16 +1997,8 @@
         if (contentUri == null) {
             throw new IllegalArgumentException("Uri contentUri null");
         }
-        try {
-            final IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms == null) {
-                return;
-            }
-            iMms.downloadMessage(getSubscriptionId(), ActivityThread.currentPackageName(),
-                    locationUrl, contentUri, configOverrides, downloadedIntent);
-        } catch (RemoteException e) {
-            // Ignore it
-        }
+        MmsManager.getInstance().downloadMultimediaMessage(getSubscriptionId(), locationUrl,
+                contentUri, configOverrides, downloadedIntent);
     }
 
     // MMS send/download failure result codes
@@ -2243,434 +2016,17 @@
     /** Intent extra name for HTTP status code for MMS HTTP failure in integer type */
     public static final String EXTRA_MMS_HTTP_STATUS = "android.telephony.extra.MMS_HTTP_STATUS";
 
-    /**
-     * Import a text message into system's SMS store
-     *
-     * Only default SMS apps can import SMS
-     *
-     * @param address the destination(source) address of the sent(received) message
-     * @param type the type of the message
-     * @param text the message text
-     * @param timestampMillis the message timestamp in milliseconds
-     * @param seen if the message is seen
-     * @param read if the message is read
-     * @return the message URI, null if failed
-     * @hide
-     */
-    public Uri importTextMessage(String address, int type, String text, long timestampMillis,
-            boolean seen, boolean read) {
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.importTextMessage(ActivityThread.currentPackageName(),
-                        address, type, text, timestampMillis, seen, read);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return null;
-    }
-
     /** Represents the received SMS message for importing {@hide} */
     public static final int SMS_TYPE_INCOMING = 0;
     /** Represents the sent SMS message for importing {@hide} */
     public static final int SMS_TYPE_OUTGOING = 1;
 
-    /**
-     * Import a multimedia message into system's MMS store. Only the following PDU type is
-     * supported: Retrieve.conf, Send.req, Notification.ind, Delivery.ind, Read-Orig.ind
-     *
-     * Only default SMS apps can import MMS
-     *
-     * @param contentUri the content uri from which to read the PDU of the message to import
-     * @param messageId the optional message id. Use null if not specifying
-     * @param timestampSecs the optional message timestamp. Use -1 if not specifying
-     * @param seen if the message is seen
-     * @param read if the message is read
-     * @return the message URI, null if failed
-     * @throws IllegalArgumentException if pdu is empty
-     * {@hide}
-     */
-    public Uri importMultimediaMessage(Uri contentUri, String messageId, long timestampSecs,
-            boolean seen, boolean read) {
-        if (contentUri == null) {
-            throw new IllegalArgumentException("Uri contentUri null");
-        }
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.importMultimediaMessage(ActivityThread.currentPackageName(),
-                        contentUri, messageId, timestampSecs, seen, read);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return null;
-    }
-
-    /**
-     * Delete a system stored SMS or MMS message
-     *
-     * Only default SMS apps can delete system stored SMS and MMS messages
-     *
-     * @param messageUri the URI of the stored message
-     * @return true if deletion is successful, false otherwise
-     * @throws IllegalArgumentException if messageUri is empty
-     * {@hide}
-     */
-    public boolean deleteStoredMessage(Uri messageUri) {
-        if (messageUri == null) {
-            throw new IllegalArgumentException("Empty message URI");
-        }
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.deleteStoredMessage(ActivityThread.currentPackageName(), messageUri);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return false;
-    }
-
-    /**
-     * Delete a system stored SMS or MMS thread
-     *
-     * Only default SMS apps can delete system stored SMS and MMS conversations
-     *
-     * @param conversationId the ID of the message conversation
-     * @return true if deletion is successful, false otherwise
-     * {@hide}
-     */
-    public boolean deleteStoredConversation(long conversationId) {
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.deleteStoredConversation(
-                        ActivityThread.currentPackageName(), conversationId);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return false;
-    }
-
-    /**
-     * Update the status properties of a system stored SMS or MMS message, e.g.
-     * the read status of a message, etc.
-     *
-     * @param messageUri the URI of the stored message
-     * @param statusValues a list of status properties in key-value pairs to update
-     * @return true if update is successful, false otherwise
-     * @throws IllegalArgumentException if messageUri is empty
-     * {@hide}
-     */
-    public boolean updateStoredMessageStatus(Uri messageUri, ContentValues statusValues) {
-        if (messageUri == null) {
-            throw new IllegalArgumentException("Empty message URI");
-        }
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.updateStoredMessageStatus(ActivityThread.currentPackageName(),
-                        messageUri, statusValues);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return false;
-    }
-
     /** Message status property: whether the message has been seen. 1 means seen, 0 not {@hide} */
     public static final String MESSAGE_STATUS_SEEN = "seen";
     /** Message status property: whether the message has been read. 1 means read, 0 not {@hide} */
     public static final String MESSAGE_STATUS_READ = "read";
 
     /**
-     * Archive or unarchive a stored conversation
-     *
-     * @param conversationId the ID of the message conversation
-     * @param archived true to archive the conversation, false to unarchive
-     * @return true if update is successful, false otherwise
-     * {@hide}
-     */
-    public boolean archiveStoredConversation(long conversationId, boolean archived) {
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.archiveStoredConversation(ActivityThread.currentPackageName(),
-                        conversationId, archived);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return false;
-    }
-
-    /**
-     * Add a text message draft to system SMS store
-     *
-     * Only default SMS apps can add SMS draft
-     *
-     * @param address the destination address of message
-     * @param text the body of the message to send
-     * @return the URI of the stored draft message
-     * {@hide}
-     */
-    public Uri addTextMessageDraft(String address, String text) {
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.addTextMessageDraft(ActivityThread.currentPackageName(), address, text);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return null;
-    }
-
-    /**
-     * Add a multimedia message draft to system MMS store
-     *
-     * Only default SMS apps can add MMS draft
-     *
-     * @param contentUri the content uri from which to read the PDU data of the draft MMS
-     * @return the URI of the stored draft message
-     * @throws IllegalArgumentException if pdu is empty
-     * {@hide}
-     */
-    public Uri addMultimediaMessageDraft(Uri contentUri) {
-        if (contentUri == null) {
-            throw new IllegalArgumentException("Uri contentUri null");
-        }
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.addMultimediaMessageDraft(ActivityThread.currentPackageName(),
-                        contentUri);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return null;
-    }
-
-    /**
-     * Send a system stored text message.
-     *
-     * You can only send a failed text message or a draft text message.
-     *
-     * <p class="note"><strong>Note:</strong> If {@link #getDefault()} is used to instantiate this
-     * manager on a multi-SIM device, this operation may fail sending the SMS message because no
-     * suitable default subscription could be found. In this case, if {@code sentIntent} is
-     * non-null, then the {@link PendingIntent} will be sent with an error code
-     * {@code RESULT_ERROR_GENERIC_FAILURE} and an extra string {@code "noDefault"} containing the
-     * boolean value {@code true}. See {@link #getDefault()} for more information on the conditions
-     * where this operation may fail.
-     * </p>
-     *
-     * @param messageUri the URI of the stored message
-     * @param scAddress is the service center address or null to use the current default SMSC
-     * @param sentIntent if not NULL this <code>PendingIntent</code> is
-     *  broadcast when the message is successfully sent, or failed.
-     *  The result code will be <code>Activity.RESULT_OK</code> for success,
-     *  or one of these errors:<br>
-     *  <code>RESULT_ERROR_GENERIC_FAILURE</code><br>
-     *  <code>RESULT_ERROR_RADIO_OFF</code><br>
-     *  <code>RESULT_ERROR_NULL_PDU</code><br>
-     *  For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include
-     *  the extra "errorCode" containing a radio technology specific value,
-     *  generally only useful for troubleshooting.<br>
-     *  The per-application based SMS control checks sentIntent. If sentIntent
-     *  is NULL the caller will be checked against all unknown applications,
-     *  which cause smaller number of SMS to be sent in checking period.
-     * @param deliveryIntent if not NULL this <code>PendingIntent</code> is
-     *  broadcast when the message is delivered to the recipient.  The
-     *  raw pdu of the status report is in the extended data ("pdu").
-     *
-     * @throws IllegalArgumentException if messageUri is empty
-     * {@hide}
-     */
-    public void sendStoredTextMessage(Uri messageUri, String scAddress, PendingIntent sentIntent,
-            PendingIntent deliveryIntent) {
-        if (messageUri == null) {
-            throw new IllegalArgumentException("Empty message URI");
-        }
-        final Context context = ActivityThread.currentApplication().getApplicationContext();
-        resolveSubscriptionForOperation(new SubscriptionResolverResult() {
-            @Override
-            public void onSuccess(int subId) {
-                try {
-                    ISms iSms = getISmsServiceOrThrow();
-                    iSms.sendStoredText(subId, ActivityThread.currentPackageName(), messageUri,
-                            scAddress, sentIntent, deliveryIntent);
-                } catch (RemoteException e) {
-                    Log.e(TAG, "sendStoredTextMessage: Couldn't send SMS - Exception: "
-                            + e.getMessage());
-                    notifySmsGenericError(sentIntent);
-                }
-            }
-            @Override
-            public void onFailure() {
-                notifySmsErrorNoDefaultSet(context, sentIntent);
-            }
-        });
-    }
-
-    /**
-     * Send a system stored multi-part text message.
-     *
-     * You can only send a failed text message or a draft text message.
-     * The provided <code>PendingIntent</code> lists should match the part number of the
-     * divided text of the stored message by using <code>divideMessage</code>
-     *
-     * <p class="note"><strong>Note:</strong> If {@link #getDefault()} is used to instantiate this
-     * manager on a multi-SIM device, this operation may fail sending the SMS message because no
-     * suitable default subscription could be found. In this case, if {@code sentIntent} is
-     * non-null, then the {@link PendingIntent} will be sent with an error code
-     * {@code RESULT_ERROR_GENERIC_FAILURE} and an extra string {@code "noDefault"} containing the
-     * boolean value {@code true}. See {@link #getDefault()} for more information on the conditions
-     * where this operation may fail.
-     * </p>
-     *
-     * @param messageUri the URI of the stored message
-     * @param scAddress is the service center address or null to use
-     *   the current default SMSC
-     * @param sentIntents if not null, an <code>ArrayList</code> of
-     *   <code>PendingIntent</code>s (one for each message part) that is
-     *   broadcast when the corresponding message part has been sent.
-     *   The result code will be <code>Activity.RESULT_OK</code> for success,
-     *   or one of these errors:<br>
-     *   <code>RESULT_ERROR_GENERIC_FAILURE</code><br>
-     *   <code>RESULT_ERROR_RADIO_OFF</code><br>
-     *   <code>RESULT_ERROR_NULL_PDU</code><br>
-     *   For <code>RESULT_ERROR_GENERIC_FAILURE</code> each sentIntent may include
-     *   the extra "errorCode" containing a radio technology specific value,
-     *   generally only useful for troubleshooting.<br>
-     *   The per-application based SMS control checks sentIntent. If sentIntent
-     *   is NULL the caller will be checked against all unknown applications,
-     *   which cause smaller number of SMS to be sent in checking period.
-     * @param deliveryIntents if not null, an <code>ArrayList</code> of
-     *   <code>PendingIntent</code>s (one for each message part) that is
-     *   broadcast when the corresponding message part has been delivered
-     *   to the recipient.  The raw pdu of the status report is in the
-     *   extended data ("pdu").
-     *
-     * @throws IllegalArgumentException if messageUri is empty
-     * {@hide}
-     */
-    public void sendStoredMultipartTextMessage(Uri messageUri, String scAddress,
-            ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) {
-        if (messageUri == null) {
-            throw new IllegalArgumentException("Empty message URI");
-        }
-        final Context context = ActivityThread.currentApplication().getApplicationContext();
-        resolveSubscriptionForOperation(new SubscriptionResolverResult() {
-            @Override
-            public void onSuccess(int subId) {
-                try {
-                    ISms iSms = getISmsServiceOrThrow();
-                    iSms.sendStoredMultipartText(subId, ActivityThread.currentPackageName(),
-                            messageUri, scAddress, sentIntents, deliveryIntents);
-                } catch (RemoteException e) {
-                    Log.e(TAG, "sendStoredTextMessage: Couldn't send SMS - Exception: "
-                            + e.getMessage());
-                    notifySmsGenericError(sentIntents);
-                }
-            }
-            @Override
-            public void onFailure() {
-                notifySmsErrorNoDefaultSet(context, sentIntents);
-            }
-        });
-    }
-
-    /**
-     * Send a system stored MMS message
-     *
-     * This is used for sending a previously sent, but failed-to-send, message or
-     * for sending a text message that has been stored as a draft.
-     *
-     * <p class="note"><strong>Note:</strong> This method will never trigger an SMS disambiguation
-     * dialog. If this method is called on a device that has multiple active subscriptions, this
-     * {@link SmsManager} instance has been created with {@link #getDefault()}, and no user-defined
-     * default subscription is defined, the subscription ID associated with this message will be
-     * INVALID, which will result in the operation being completed on the subscription associated
-     * with logical slot 0. Use {@link #getSmsManagerForSubscriptionId(int)} to ensure the
-     * operation is performed on the correct subscription.
-     * </p>
-     *
-     * @param messageUri the URI of the stored message
-     * @param configOverrides the carrier-specific messaging configuration values to override for
-     *  sending the message.
-     * @param sentIntent if not NULL this <code>PendingIntent</code> is
-     *  broadcast when the message is successfully sent, or failed
-     * @throws IllegalArgumentException if messageUri is empty
-     * {@hide}
-     */
-    public void sendStoredMultimediaMessage(Uri messageUri, Bundle configOverrides,
-            PendingIntent sentIntent) {
-        if (messageUri == null) {
-            throw new IllegalArgumentException("Empty message URI");
-        }
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                iMms.sendStoredMessage(
-                        getSubscriptionId(), ActivityThread.currentPackageName(), messageUri,
-                        configOverrides, sentIntent);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-    }
-
-    /**
-     * Turns on/off the flag to automatically write sent/received SMS/MMS messages into system
-     *
-     * When this flag is on, all SMS/MMS sent/received are stored by system automatically
-     * When this flag is off, only SMS/MMS sent by non-default SMS apps are stored by system
-     * automatically
-     *
-     * This flag can only be changed by default SMS apps
-     *
-     * @param enabled Whether to enable message auto persisting
-     * {@hide}
-     */
-    public void setAutoPersisting(boolean enabled) {
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                iMms.setAutoPersisting(ActivityThread.currentPackageName(), enabled);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-    }
-
-    /**
-     * Get the value of the flag to automatically write sent/received SMS/MMS messages into system
-     *
-     * When this flag is on, all SMS/MMS sent/received are stored by system automatically
-     * When this flag is off, only SMS/MMS sent by non-default SMS apps are stored by system
-     * automatically
-     *
-     * @return the current value of the auto persist flag
-     * {@hide}
-     */
-    public boolean getAutoPersisting() {
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.getAutoPersisting();
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return false;
-    }
-
-    /**
      * Get carrier-dependent configuration values.
      *
      * <p class="note"><strong>Note:</strong> This method is intended for internal use by carrier
@@ -2686,15 +2042,7 @@
      * @return bundle key/values pairs of configuration values
      */
     public Bundle getCarrierConfigValues() {
-        try {
-            IMms iMms = IMms.Stub.asInterface(ServiceManager.getService("imms"));
-            if (iMms != null) {
-                return iMms.getCarrierConfigValues(getSubscriptionId());
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-        return null;
+        return MmsManager.getInstance().getCarrierConfigValues(getSubscriptionId());
     }
 
     /**
@@ -2733,7 +2081,9 @@
         }
     }
 
-    /** callback for providing asynchronous sms messages for financial app. */
+    /**
+     * callback for providing asynchronous sms messages for financial app.
+     */
     public abstract static class FinancialSmsCallback {
         /**
          * Callback to send sms messages back to financial app asynchronously.
@@ -2759,59 +2109,49 @@
      * @param params the parameters to filter SMS messages returned.
      * @param executor the executor on which callback will be invoked.
      * @param callback a callback to receive CursorWindow with SMS messages.
+     *
      */
     @RequiresPermission(android.Manifest.permission.SMS_FINANCIAL_TRANSACTIONS)
     public void getSmsMessagesForFinancialApp(
             Bundle params,
             @NonNull @CallbackExecutor Executor executor,
             @NonNull FinancialSmsCallback callback) {
-        try {
-            ISms iccSms = getISmsServiceOrThrow();
-            iccSms.getSmsMessagesForFinancialApp(
-                    getSubscriptionId(), ActivityThread.currentPackageName(), params,
-                    new IFinancialSmsCallback.Stub() {
-                        public void onGetSmsMessagesForFinancialApp(CursorWindow msgs) {
-                            Binder.withCleanCallingIdentity(() -> executor.execute(
-                                    () -> callback.onFinancialSmsMessages(msgs)));
-                        }});
-        } catch (RemoteException ex) {
-            ex.rethrowFromSystemServer();
-        }
+        // This API is not functional and thus removed to avoid future confusion.
     }
 
     /**
-     * @see #createAppSpecificSmsTokenWithPackageInfo().
+     * @see #createAppSpecificSmsTokenWithPackageInfo(String, PendingIntent).
      * The prefixes is a list of prefix {@code String} separated by this delimiter.
      * @hide
      */
     public static final String REGEX_PREFIX_DELIMITER = ",";
     /**
-     * @see #createAppSpecificSmsTokenWithPackageInfo().
+     * @see #createAppSpecificSmsTokenWithPackageInfo(String, PendingIntent).
      * The success status to be added into the intent to be sent to the calling package.
      * @hide
      */
     public static final int RESULT_STATUS_SUCCESS = 0;
     /**
-     * @see #createAppSpecificSmsTokenWithPackageInfo().
+     * @see #createAppSpecificSmsTokenWithPackageInfo(String, PendingIntent).
      * The timeout status to be added into the intent to be sent to the calling package.
      * @hide
      */
     public static final int RESULT_STATUS_TIMEOUT = 1;
     /**
-     * @see #createAppSpecificSmsTokenWithPackageInfo().
+     * @see #createAppSpecificSmsTokenWithPackageInfo(String, PendingIntent).
      * Intent extra key of the retrieved SMS message as a {@code String}.
      * @hide
      */
     public static final String EXTRA_SMS_MESSAGE = "android.telephony.extra.SMS_MESSAGE";
     /**
-     * @see #createAppSpecificSmsTokenWithPackageInfo().
+     * @see #createAppSpecificSmsTokenWithPackageInfo(String, PendingIntent).
      * Intent extra key of SMS retriever status, which indicates whether the request for the
      * coming SMS message is SUCCESS or TIMEOUT
      * @hide
      */
     public static final String EXTRA_STATUS = "android.telephony.extra.STATUS";
     /**
-     * @see #createAppSpecificSmsTokenWithPackageInfo().
+     * @see #createAppSpecificSmsTokenWithPackageInfo(String, PendingIntent).
      * [Optional] Intent extra key of the retrieved Sim card subscription Id if any. {@code int}
      * @hide
      */
@@ -2861,74 +2201,6 @@
         }
     }
 
-    /**
-     * Filters a bundle to only contain MMS config variables.
-     *
-     * This is for use with bundles returned by {@link CarrierConfigManager} which contain MMS
-     * config and unrelated config. It is assumed that all MMS_CONFIG_* keys are present in the
-     * supplied bundle.
-     *
-     * @param config a Bundle that contains MMS config variables and possibly more.
-     * @return a new Bundle that only contains the MMS_CONFIG_* keys defined above.
-     * @hide
-     */
-    public static Bundle getMmsConfig(BaseBundle config) {
-        Bundle filtered = new Bundle();
-        filtered.putBoolean(MMS_CONFIG_APPEND_TRANSACTION_ID,
-                config.getBoolean(MMS_CONFIG_APPEND_TRANSACTION_ID));
-        filtered.putBoolean(MMS_CONFIG_MMS_ENABLED, config.getBoolean(MMS_CONFIG_MMS_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_GROUP_MMS_ENABLED,
-                config.getBoolean(MMS_CONFIG_GROUP_MMS_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_NOTIFY_WAP_MMSC_ENABLED,
-                config.getBoolean(MMS_CONFIG_NOTIFY_WAP_MMSC_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_ALIAS_ENABLED, config.getBoolean(MMS_CONFIG_ALIAS_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_ALLOW_ATTACH_AUDIO,
-                config.getBoolean(MMS_CONFIG_ALLOW_ATTACH_AUDIO));
-        filtered.putBoolean(MMS_CONFIG_MULTIPART_SMS_ENABLED,
-                config.getBoolean(MMS_CONFIG_MULTIPART_SMS_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_SMS_DELIVERY_REPORT_ENABLED,
-                config.getBoolean(MMS_CONFIG_SMS_DELIVERY_REPORT_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_SUPPORT_MMS_CONTENT_DISPOSITION,
-                config.getBoolean(MMS_CONFIG_SUPPORT_MMS_CONTENT_DISPOSITION));
-        filtered.putBoolean(MMS_CONFIG_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES,
-                config.getBoolean(MMS_CONFIG_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES));
-        filtered.putBoolean(MMS_CONFIG_MMS_READ_REPORT_ENABLED,
-                config.getBoolean(MMS_CONFIG_MMS_READ_REPORT_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_MMS_DELIVERY_REPORT_ENABLED,
-                config.getBoolean(MMS_CONFIG_MMS_DELIVERY_REPORT_ENABLED));
-        filtered.putBoolean(MMS_CONFIG_CLOSE_CONNECTION,
-                config.getBoolean(MMS_CONFIG_CLOSE_CONNECTION));
-        filtered.putInt(MMS_CONFIG_MAX_MESSAGE_SIZE, config.getInt(MMS_CONFIG_MAX_MESSAGE_SIZE));
-        filtered.putInt(MMS_CONFIG_MAX_IMAGE_WIDTH, config.getInt(MMS_CONFIG_MAX_IMAGE_WIDTH));
-        filtered.putInt(MMS_CONFIG_MAX_IMAGE_HEIGHT, config.getInt(MMS_CONFIG_MAX_IMAGE_HEIGHT));
-        filtered.putInt(MMS_CONFIG_RECIPIENT_LIMIT, config.getInt(MMS_CONFIG_RECIPIENT_LIMIT));
-        filtered.putInt(MMS_CONFIG_ALIAS_MIN_CHARS, config.getInt(MMS_CONFIG_ALIAS_MIN_CHARS));
-        filtered.putInt(MMS_CONFIG_ALIAS_MAX_CHARS, config.getInt(MMS_CONFIG_ALIAS_MAX_CHARS));
-        filtered.putInt(MMS_CONFIG_SMS_TO_MMS_TEXT_THRESHOLD,
-                config.getInt(MMS_CONFIG_SMS_TO_MMS_TEXT_THRESHOLD));
-        filtered.putInt(MMS_CONFIG_SMS_TO_MMS_TEXT_LENGTH_THRESHOLD,
-                config.getInt(MMS_CONFIG_SMS_TO_MMS_TEXT_LENGTH_THRESHOLD));
-        filtered.putInt(MMS_CONFIG_MESSAGE_TEXT_MAX_SIZE,
-                config.getInt(MMS_CONFIG_MESSAGE_TEXT_MAX_SIZE));
-        filtered.putInt(MMS_CONFIG_SUBJECT_MAX_LENGTH,
-                config.getInt(MMS_CONFIG_SUBJECT_MAX_LENGTH));
-        filtered.putInt(MMS_CONFIG_HTTP_SOCKET_TIMEOUT,
-                config.getInt(MMS_CONFIG_HTTP_SOCKET_TIMEOUT));
-        filtered.putString(MMS_CONFIG_UA_PROF_TAG_NAME,
-                config.getString(MMS_CONFIG_UA_PROF_TAG_NAME));
-        filtered.putString(MMS_CONFIG_USER_AGENT, config.getString(MMS_CONFIG_USER_AGENT));
-        filtered.putString(MMS_CONFIG_UA_PROF_URL, config.getString(MMS_CONFIG_UA_PROF_URL));
-        filtered.putString(MMS_CONFIG_HTTP_PARAMS, config.getString(MMS_CONFIG_HTTP_PARAMS));
-        filtered.putString(MMS_CONFIG_EMAIL_GATEWAY_NUMBER,
-                config.getString(MMS_CONFIG_EMAIL_GATEWAY_NUMBER));
-        filtered.putString(MMS_CONFIG_NAI_SUFFIX, config.getString(MMS_CONFIG_NAI_SUFFIX));
-        filtered.putBoolean(MMS_CONFIG_SHOW_CELL_BROADCAST_APP_LINKS,
-                config.getBoolean(MMS_CONFIG_SHOW_CELL_BROADCAST_APP_LINKS));
-        filtered.putBoolean(MMS_CONFIG_SUPPORT_HTTP_CHARSET_HEADER,
-                config.getBoolean(MMS_CONFIG_SUPPORT_HTTP_CHARSET_HEADER));
-        return filtered;
-    }
-
     /** @hide */
     @Retention(RetentionPolicy.SOURCE)
     @IntDef(prefix = {"SMS_CATEGORY_"},
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 51de903..1b87657 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -53,7 +53,7 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.ServiceManager;
-import android.telephony.TelephonyManager.NetworkType;
+import android.telephony.Annotation.NetworkType;
 import android.telephony.euicc.EuiccManager;
 import android.telephony.ims.ImsMmTelManager;
 import android.util.DisplayMetrics;
@@ -896,6 +896,11 @@
      */
     public static final String EXTRA_SUBSCRIPTION_INDEX = "android.telephony.extra.SUBSCRIPTION_INDEX";
 
+    /**
+     * Integer extra to specify SIM slot index.
+     */
+    public static final String EXTRA_SLOT_INDEX = "android.telephony.extra.SLOT_INDEX";
+
     private final Context mContext;
     private volatile INetworkPolicyManager mNetworkPolicy;
 
@@ -2096,13 +2101,13 @@
     /** @hide */
     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
     public static boolean isValidSlotIndex(int slotIndex) {
-        return slotIndex >= 0 && slotIndex < TelephonyManager.getDefault().getSimCount();
+        return slotIndex >= 0 && slotIndex < TelephonyManager.getDefault().getMaxPhoneCount();
     }
 
     /** @hide */
     @UnsupportedAppUsage
     public static boolean isValidPhoneId(int phoneId) {
-        return phoneId >= 0 && phoneId < TelephonyManager.getDefault().getPhoneCount();
+        return phoneId >= 0 && phoneId < TelephonyManager.getDefault().getMaxPhoneCount();
     }
 
     /** @hide */
@@ -2123,6 +2128,7 @@
         if (VDBG) logd("putPhoneIdAndSubIdExtra: phoneId=" + phoneId + " subId=" + subId);
         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
         intent.putExtra(EXTRA_SUBSCRIPTION_INDEX, subId);
+        intent.putExtra(EXTRA_SLOT_INDEX, phoneId);
         intent.putExtra(PhoneConstants.PHONE_KEY, phoneId);
     }
 
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index ea55a82..2442023 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -63,10 +63,16 @@
 import android.telecom.PhoneAccount;
 import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
+import android.telephony.Annotation.ApnType;
+import android.telephony.Annotation.CallState;
+import android.telephony.Annotation.DataState;
+import android.telephony.Annotation.NetworkType;
+import android.telephony.Annotation.RadioPowerState;
+import android.telephony.Annotation.SimActivationState;
 import android.telephony.VisualVoicemailService.VisualVoicemailTask;
-import android.telephony.data.ApnSetting;
 import android.telephony.emergency.EmergencyNumber;
 import android.telephony.emergency.EmergencyNumber.EmergencyServiceCategories;
+import android.telephony.ims.ImsMmTelManager;
 import android.telephony.ims.aidl.IImsConfig;
 import android.telephony.ims.aidl.IImsMmTelFeature;
 import android.telephony.ims.aidl.IImsRcsFeature;
@@ -253,17 +259,6 @@
      */
     public static final int UNINITIALIZED_CARD_ID = -2;
 
-    /** @hide */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(prefix = {"SRVCC_STATE_"},
-            value = {
-                    SRVCC_STATE_HANDOVER_NONE,
-                    SRVCC_STATE_HANDOVER_STARTED,
-                    SRVCC_STATE_HANDOVER_COMPLETED,
-                    SRVCC_STATE_HANDOVER_FAILED,
-                    SRVCC_STATE_HANDOVER_CANCELED})
-    public @interface SrvccState {}
-
     private final Context mContext;
     private final int mSubId;
     @UnsupportedAppUsage
@@ -403,7 +398,7 @@
      * TODO: b/139642279 publicize and rename.
      * @hide
      */
-    public static int getMaxPhoneCount() {
+    public int getMaxPhoneCount() {
         // TODO: b/139642279 when turning on this feature, remove dependency of
         // PROPERTY_REBOOT_REQUIRED_ON_MODEM_CHANGE and always return result based on
         // PROPERTY_MAX_ACTIVE_MODEMS.
@@ -412,9 +407,9 @@
         if (rebootRequired.equals("false")) {
             // If no reboot is required, return max possible active modems.
             return SystemProperties.getInt(
-                    TelephonyProperties.PROPERTY_MAX_ACTIVE_MODEMS, getDefault().getPhoneCount());
+                    TelephonyProperties.PROPERTY_MAX_ACTIVE_MODEMS, getPhoneCount());
         } else {
-            return getDefault().getPhoneCount();
+            return getPhoneCount();
         }
     }
 
@@ -1176,6 +1171,35 @@
             "android.telephony.extra.VOICEMAIL_SCRAMBLED_PIN_STRING";
 
     /**
+     * Broadcast intent that indicates multi-SIM configuration is changed. For example, it changed
+     * from single SIM capable to dual-SIM capable (DSDS or DSDA) or triple-SIM mode.
+     *
+     * It doesn't indicate how many subscriptions are actually active, or which states SIMs are,
+     * or that all steps during multi-SIM change are done. To know those information you still need
+     * to listen to SIM_STATE changes or active subscription changes.
+     *
+     * See extra of {@link #EXTRA_NUM_OF_ACTIVE_SIM_SUPPORTED} for updated value.
+     */
+    public static final String ACTION_MULTI_SIM_CONFIG_CHANGED =
+            "android.telephony.action.MULTI_SIM_CONFIG_CHANGED";
+
+
+    /**
+     * The number of active SIM supported by current multi-SIM config. It's not related to how many
+     * SIM/subscriptions are currently active.
+     *
+     * For single SIM mode, it's 1.
+     * For DSDS or DSDA mode, it's 2.
+     * For triple-SIM mode, it's 3.
+     *
+     * Extra of {@link #ACTION_MULTI_SIM_CONFIG_CHANGED}.
+     *
+     * type: integer
+     */
+    public static final String EXTRA_NUM_OF_ACTIVE_SIM_SUPPORTED =
+            "android.telephony.extra.NUM_OF_ACTIVE_SIM_SUPPORTED";
+
+    /**
      * @hide
      */
     public static final String USSD_RESPONSE = "USSD_RESPONSE";
@@ -1871,11 +1895,23 @@
     /**
      * Returns the Network Access Identifier (NAI). Return null if NAI is not available.
      *
-     * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
-     * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
+     * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
+     * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
+     * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
+     * managed profile on the device; for more details see <a
+     * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
+     * access is deprecated and will be removed in a future release.
+     *
+     * <ul>
+     *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
+     *     READ_PHONE_STATE permission then null is returned.</li>
+     *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
+     *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
+     *     higher, then a SecurityException is thrown.</li>
+     * </ul>
      */
-    @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
-    @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
+    @SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
+    @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
     public String getNai() {
         return getNaiBySubscriberId(getSubId());
     }
@@ -1883,6 +1919,21 @@
     /**
      * Returns the NAI. Return null if NAI is not available.
      *
+     * <p>Requires Permission: READ_PRIVILEGED_PHONE_STATE, for the calling app to be the device or
+     * profile owner and have the READ_PHONE_STATE permission, or that the calling app has carrier
+     * privileges (see {@link #hasCarrierPrivileges}). The profile owner is an app that owns a
+     * managed profile on the device; for more details see <a
+     * href="https://developer.android.com/work/managed-profiles">Work profiles</a>. Profile owner
+     * access is deprecated and will be removed in a future release.
+     *
+     * <ul>
+     *     <li>If the calling app's target SDK is API level 28 or lower and the app has the
+     *     READ_PHONE_STATE permission then null is returned.</li>
+     *     <li>If the calling app's target SDK is API level 28 or lower and the app does not have
+     *     the READ_PHONE_STATE permission, or if the calling app is targeting API level 29 or
+     *     higher, then a SecurityException is thrown.</li>
+     * </ul>
+     *
      *  @param slotIndex of which Nai is returned
      */
     /** {@hide}*/
@@ -2448,41 +2499,45 @@
      * @return the lowercase 2 character ISO-3166 country code, or empty string if not available.
      */
     public String getNetworkCountryIso() {
-        return getNetworkCountryIsoForPhone(getPhoneId());
-    }
-
-    /**
-     * Returns the ISO country code equivalent of the MCC (Mobile Country Code) of the current
-     * registered operator or the cell nearby, if available.
-     * <p>
-     * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
-     * if on a CDMA network).
-     *
-     * @param subId for which Network CountryIso is returned
-     * @hide
-     */
-    @UnsupportedAppUsage
-    public String getNetworkCountryIso(int subId) {
-        return getNetworkCountryIsoForPhone(getPhoneId(subId));
-    }
-
-    /**
-     * Returns the ISO country code equivalent of the current registered
-     * operator's MCC (Mobile Country Code) of a subscription.
-     * <p>
-     * Availability: Only when user is registered to a network. Result may be
-     * unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
-     * on a CDMA network).
-     *
-     * @param phoneId for which Network CountryIso is returned
-     */
-    /** {@hide} */
-    @UnsupportedAppUsage
-    public String getNetworkCountryIsoForPhone(int phoneId) {
         try {
             ITelephony telephony = getITelephony();
             if (telephony == null) return "";
-            return telephony.getNetworkCountryIsoForPhone(phoneId);
+            return telephony.getNetworkCountryIsoForPhone(getPhoneId(),
+                    null /* no permission check */);
+        } catch (RemoteException ex) {
+            return "";
+        }
+    }
+
+    /**
+     * Returns the ISO-3166 country code equivalent of the MCC (Mobile Country Code) of the current
+     * registered operator or the cell nearby, if available.
+     * <p>
+     * The ISO-3166 country code is provided in lowercase 2 character format.
+     * <p>
+     * Note: In multi-sim, this returns a shared emergency network country iso from other
+     * subscription if the subscription used to create the TelephonyManager doesn't camp on
+     * a network due to some reason (e.g. pin/puk locked), or sim is absent in the corresponding
+     * slot.
+     * Note: Result may be unreliable on CDMA networks (use {@link #getPhoneType()} to determine
+     * if on a CDMA network).
+     * <p>
+     *
+     * @param slotIndex the SIM slot index to get network country ISO.
+     *
+     * @return the lowercase 2 character ISO-3166 country code, or empty string if not available.
+     *
+     * {@hide}
+     */
+    @SystemApi
+    @TestApi
+    @NonNull
+    @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+    public String getNetworkCountryIso(int slotIndex) {
+        try {
+            ITelephony telephony = getITelephony();
+            if (telephony == null) return "";
+            return telephony.getNetworkCountryIsoForPhone(slotIndex, getOpPackageName());
         } catch (RemoteException ex) {
             return "";
         }
@@ -2541,33 +2596,6 @@
     /** Max network type number. Update as new types are added. Don't add negative types. {@hide} */
     public static final int MAX_NETWORK_TYPE = NETWORK_TYPE_NR;
 
-    /** @hide */
-    @IntDef({
-            NETWORK_TYPE_UNKNOWN,
-            NETWORK_TYPE_GPRS,
-            NETWORK_TYPE_EDGE,
-            NETWORK_TYPE_UMTS,
-            NETWORK_TYPE_CDMA,
-            NETWORK_TYPE_EVDO_0,
-            NETWORK_TYPE_EVDO_A,
-            NETWORK_TYPE_1xRTT,
-            NETWORK_TYPE_HSDPA,
-            NETWORK_TYPE_HSUPA,
-            NETWORK_TYPE_HSPA,
-            NETWORK_TYPE_IDEN,
-            NETWORK_TYPE_EVDO_B,
-            NETWORK_TYPE_LTE,
-            NETWORK_TYPE_EHRPD,
-            NETWORK_TYPE_HSPAP,
-            NETWORK_TYPE_GSM,
-            NETWORK_TYPE_TD_SCDMA,
-            NETWORK_TYPE_IWLAN,
-            NETWORK_TYPE_LTE_CA,
-            NETWORK_TYPE_NR,
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface NetworkType{}
-
     /**
      * Return the current data network type.
      *
@@ -2744,6 +2772,8 @@
     /** Class of broadly defined "4G" networks. {@hide} */
     @UnsupportedAppUsage
     public static final int NETWORK_CLASS_4_G = 3;
+    /** Class of broadly defined "5G" networks. {@hide} */
+    public static final int NETWORK_CLASS_5_G = 4;
 
     /**
      * Return general class of network type, such as "3G" or "4G". In cases
@@ -2776,6 +2806,8 @@
             case NETWORK_TYPE_IWLAN:
             case NETWORK_TYPE_LTE_CA:
                 return NETWORK_CLASS_4_G;
+            case NETWORK_TYPE_NR:
+                return NETWORK_CLASS_5_G;
             default:
                 return NETWORK_CLASS_UNKNOWN;
         }
@@ -4561,6 +4593,17 @@
     }
 
     /**
+     * Sim activation type: voice
+     * @hide
+     */
+    public static final int SIM_ACTIVATION_TYPE_VOICE = 0;
+    /**
+     * Sim activation type: data
+     * @hide
+     */
+    public static final int SIM_ACTIVATION_TYPE_DATA = 1;
+
+    /**
      * Initial SIM activation state, unknown. Not set by any carrier apps.
      * @hide
      */
@@ -4603,17 +4646,6 @@
     @SystemApi
     public static final int SIM_ACTIVATION_STATE_RESTRICTED = 4;
 
-    /** @hide */
-    @IntDef({
-            SIM_ACTIVATION_STATE_UNKNOWN,
-            SIM_ACTIVATION_STATE_ACTIVATING,
-            SIM_ACTIVATION_STATE_ACTIVATED,
-            SIM_ACTIVATION_STATE_DEACTIVATED,
-            SIM_ACTIVATION_STATE_RESTRICTED
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface SimActivationState{}
-
      /**
       * Sets the voice activation state
       *
@@ -4998,15 +5030,6 @@
      */
     public static final int CALL_STATE_OFFHOOK = 2;
 
-    /** @hide */
-    @IntDef(prefix = { "CALL_STATE_" }, value = {
-            CALL_STATE_IDLE,
-            CALL_STATE_RINGING,
-            CALL_STATE_OFFHOOK
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface CallState{}
-
     /**
      * Returns the state of all calls on the device.
      * <p>
@@ -6829,6 +6852,40 @@
     }
 
     /**
+     * Replace the contents of the forbidden PLMN SIM file with the provided values.
+     * Passing an empty list will clear the contents of the EFfplmn file.
+     * If the provided list is shorter than the size of EFfplmn, then the list will be padded
+     * up to the file size with 'FFFFFF'. (required by 3GPP TS 31.102 spec 4.2.16)
+     * If the list is longer than the size of EFfplmn, then the file will be written from the
+     * beginning of the list up to the file size.
+     *
+     * <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
+     * or that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
+     *
+     * @param fplmns a list of PLMNs to be forbidden.
+     *
+     * @return number of PLMNs that were successfully written to the SIM FPLMN list.
+     * This may be less than the number of PLMNs passed in where the SIM file does not have enough
+     * room for all of the values passed in. Return -1 in the event of an unexpected failure
+     */
+    @SuppressAutoDoc // Blocked by b/72967236 - no support for carrier privileges
+    @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
+    public int setForbiddenPlmns(@NonNull List<String> fplmns) {
+        try {
+            ITelephony telephony = getITelephony();
+            if (telephony == null) return 0;
+            return telephony.setForbiddenPlmns(
+                    getSubId(), APPTYPE_USIM, fplmns, getOpPackageName());
+        } catch (RemoteException ex) {
+            Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
+        } catch (NullPointerException ex) {
+            // This could happen before phone starts
+            Rlog.e(TAG, "setForbiddenPlmns NullPointerException: " + ex.getMessage());
+        }
+        return 0;
+    }
+
+    /**
      * Get P-CSCF address from PCO after data connection is established or modified.
      * @param apnType the apnType, "ims" for IMS APN, "emergency" for EMERGENCY APN
      * @return array of P-CSCF address
@@ -8302,15 +8359,6 @@
         return false;
     }
 
-    /** @hide */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(prefix = {"RADIO_POWER_"},
-            value = {RADIO_POWER_OFF,
-                    RADIO_POWER_ON,
-                    RADIO_POWER_UNAVAILABLE,
-            })
-    public @interface RadioPowerState {}
-
     /**
      * Radio explicitly powered off (e.g, airplane mode).
      * @hide
@@ -8671,7 +8719,12 @@
         return -1;
     }
 
-    /** @hide */
+    /**
+     * @deprecated Use {@link android.telephony.ims.ImsMmTelManager#setVtSettingEnabled(boolean)}
+     * instead.
+     * @hide
+     */
+    @Deprecated
     @SystemApi
     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
     public void enableVideoCalling(boolean enable) {
@@ -8684,7 +8737,14 @@
         }
     }
 
-    /** @hide */
+    /**
+     * @deprecated Use {@link ImsMmTelManager#isVtSettingEnabled()} instead to check if the user
+     * has enabled the Video Calling setting, {@link ImsMmTelManager#isAvailable(int, int)} to
+     * determine if video calling is available, or {@link ImsMmTelManager#isCapable(int, int)} to
+     * determine if video calling is capable.
+     * @hide
+     */
+    @Deprecated
     @SystemApi
     @RequiresPermission(anyOf = {
             android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
@@ -8804,6 +8864,7 @@
      * @param subId Subscription ID
      * @return true if IMS status is registered, false if the IMS status is not registered or a
      * RemoteException occurred.
+     * Use {@link ImsMmTelManager.RegistrationCallback} instead.
      * @hide
      */
     public boolean isImsRegistered(int subId) {
@@ -8840,6 +8901,8 @@
      * used during creation, the default subscription ID will be used.
      * @return true if Voice over LTE is available or false if it is unavailable or unknown.
      * @see SubscriptionManager#getDefaultSubscriptionId()
+     * <p>
+     * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
      * @hide
      */
     @UnsupportedAppUsage
@@ -8859,6 +8922,7 @@
      * used during creation, the default subscription ID will be used. To query the
      * underlying technology that VT is available on, use {@link #getImsRegTechnologyForMmTel}.
      * @return true if VT is available, or false if it is unavailable or unknown.
+     * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
      * @hide
      */
     @UnsupportedAppUsage
@@ -8874,6 +8938,7 @@
      * Returns the Status of Wi-Fi calling (Voice over WiFi) for the subscription ID specified.
      * @param subId the subscription ID.
      * @return true if VoWiFi is available, or false if it is unavailable or unknown.
+     * Use {@link ImsMmTelManager#isAvailable(int, int)} instead.
      * @hide
      */
     @UnsupportedAppUsage
@@ -8894,6 +8959,7 @@
      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_IWLAN} for IWLAN registration, or
      *  - {@link ImsRegistrationImplBase#REGISTRATION_TECH_NONE} if we are not registered or the
      *  result is unavailable.
+     *  Use {@link ImsMmTelManager.RegistrationCallback} instead.
      *  @hide
      */
     public @ImsRegistrationImplBase.ImsRegistrationTech int getImsRegTechnologyForMmTel() {
@@ -11402,11 +11468,14 @@
      *  3) APN type is whitelisted. E.g. MMS is whitelisted if
      *  {@link SubscriptionManager#setAlwaysAllowMmsData} is turned on.
      *
+     * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
      * @return whether data is enabled for a apn type.
      *
      * @hide
      */
-    public boolean isDataEnabledForApn(@ApnSetting.ApnType int apnType) {
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+    public boolean isDataEnabledForApn(@ApnType int apnType) {
         String pkgForDebug = mContext != null ? mContext.getOpPackageName() : "<unknown>";
         try {
             ITelephony service = getITelephony();
@@ -11427,7 +11496,7 @@
      *
      * @hide
      */
-    public boolean isApnMetered(@ApnSetting.ApnType int apnType) {
+    public boolean isApnMetered(@ApnType int apnType) {
         try {
             ITelephony service = getITelephony();
             if (service != null) {
diff --git a/telephony/java/android/telephony/TelephonyScanManager.java b/telephony/java/android/telephony/TelephonyScanManager.java
index 28747da..9ff8515 100644
--- a/telephony/java/android/telephony/TelephonyScanManager.java
+++ b/telephony/java/android/telephony/TelephonyScanManager.java
@@ -104,7 +104,7 @@
 
     private final Looper mLooper;
     private final Messenger mMessenger;
-    private SparseArray<NetworkScanInfo> mScanInfo = new SparseArray<NetworkScanInfo>();
+    private final SparseArray<NetworkScanInfo> mScanInfo = new SparseArray<NetworkScanInfo>();
 
     public TelephonyScanManager() {
         HandlerThread thread = new HandlerThread(TAG);
@@ -204,14 +204,16 @@
         try {
             ITelephony telephony = getITelephony();
             if (telephony != null) {
-                int scanId = telephony.requestNetworkScan(
-                        subId, request, mMessenger, new Binder(), callingPackage);
-                if (scanId == INVALID_SCAN_ID) {
-                    Rlog.e(TAG, "Failed to initiate network scan");
-                    return null;
+                synchronized (mScanInfo) {
+                    int scanId = telephony.requestNetworkScan(
+                            subId, request, mMessenger, new Binder(), callingPackage);
+                    if (scanId == INVALID_SCAN_ID) {
+                        Rlog.e(TAG, "Failed to initiate network scan");
+                        return null;
+                    }
+                    saveScanInfo(scanId, request, executor, callback);
+                    return new NetworkScan(scanId, subId);
                 }
-                saveScanInfo(scanId, request, executor, callback);
-                return new NetworkScan(scanId, subId);
             }
         } catch (RemoteException ex) {
             Rlog.e(TAG, "requestNetworkScan RemoteException", ex);
@@ -223,9 +225,7 @@
 
     private void saveScanInfo(
             int id, NetworkScanRequest request, Executor executor, NetworkScanCallback callback) {
-        synchronized (mScanInfo) {
-            mScanInfo.put(id, new NetworkScanInfo(request, executor, callback));
-        }
+        mScanInfo.put(id, new NetworkScanInfo(request, executor, callback));
     }
 
     private ITelephony getITelephony() {
diff --git a/telephony/java/android/telephony/cdma/CdmaSmsCbProgramData.java b/telephony/java/android/telephony/cdma/CdmaSmsCbProgramData.java
index 5f2f75d..02429b5 100644
--- a/telephony/java/android/telephony/cdma/CdmaSmsCbProgramData.java
+++ b/telephony/java/android/telephony/cdma/CdmaSmsCbProgramData.java
@@ -16,12 +16,19 @@
 
 package android.telephony.cdma;
 
+import android.annotation.IntDef;
 import android.annotation.NonNull;
+import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
 
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
 /**
- * CDMA Service Category Program Data from SCPT teleservice SMS.
+ * CDMA Service Category Program Data from SCPT (Service Category Programming Teleservice) SMS,
+ * as defined in 3GPP2 C.S0015-B section 4.5.19.
+ * <p>
  * The CellBroadcastReceiver app receives an Intent with action
  * {@link android.provider.Telephony.Sms.Intents#SMS_SERVICE_CATEGORY_PROGRAM_DATA_RECEIVED_ACTION}
  * containing an array of these objects to update its list of cell broadcast service categories
@@ -29,6 +36,7 @@
  *
  * {@hide}
  */
+@SystemApi
 public final class CdmaSmsCbProgramData implements Parcelable {
 
     /** Delete the specified service category from the list of enabled categories. */
@@ -40,40 +48,83 @@
     /** Clear all service categories from the list of enabled categories. */
     public static final int OPERATION_CLEAR_CATEGORIES  = 2;
 
-    /** Alert option: no alert. */
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(prefix = {"OPERATION_"},
+            value = {
+                    OPERATION_DELETE_CATEGORY,
+                    OPERATION_ADD_CATEGORY,
+                    OPERATION_CLEAR_CATEGORIES,
+            })
+    public @interface Operation {}
+
+    // CMAS alert service category assignments, see 3GPP2 C.R1001 table 9.3.3-1
+    /** Indicates a presidential-level alert */
+    public static final int CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT  = 0x1000;
+
+    /** Indicates an extreme threat to life and property */
+    public static final int CATEGORY_CMAS_EXTREME_THREAT            = 0x1001;
+
+    /** Indicates an severe threat to life and property */
+    public static final int CATEGORY_CMAS_SEVERE_THREAT             = 0x1002;
+
+    /** Indicates an AMBER child abduction emergency */
+    public static final int CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY = 0x1003;
+
+    /** Indicates a CMAS test message */
+    public static final int CATEGORY_CMAS_TEST_MESSAGE              = 0x1004;
+
+    /** The last reserved value of a CMAS service category according to 3GPP C.R1001 table
+     * 9.3.3-1. */
+    public static final int CATEGORY_CMAS_LAST_RESERVED_VALUE       = 0x10ff;
+
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(prefix = {"CATEGORY_"},
+            value = {
+                    CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT,
+                    CATEGORY_CMAS_EXTREME_THREAT,
+                    CATEGORY_CMAS_SEVERE_THREAT,
+                    CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY,
+                    CATEGORY_CMAS_TEST_MESSAGE,
+                    CATEGORY_CMAS_LAST_RESERVED_VALUE,
+            })
+    public @interface Category {}
+
+    /** Alert option: no alert. @hide */
     public static final int ALERT_OPTION_NO_ALERT               = 0;
 
-    /** Alert option: default alert. */
+    /** Alert option: default alert. @hide */
     public static final int ALERT_OPTION_DEFAULT_ALERT          = 1;
 
-    /** Alert option: vibrate alert once. */
+    /** Alert option: vibrate alert once. @hide */
     public static final int ALERT_OPTION_VIBRATE_ONCE           = 2;
 
-    /** Alert option: vibrate alert - repeat. */
+    /** Alert option: vibrate alert - repeat. @hide */
     public static final int ALERT_OPTION_VIBRATE_REPEAT         = 3;
 
-    /** Alert option: visual alert once. */
+    /** Alert option: visual alert once. @hide */
     public static final int ALERT_OPTION_VISUAL_ONCE            = 4;
 
-    /** Alert option: visual alert - repeat. */
+    /** Alert option: visual alert - repeat. @hide */
     public static final int ALERT_OPTION_VISUAL_REPEAT          = 5;
 
-    /** Alert option: low-priority alert once. */
+    /** Alert option: low-priority alert once. @hide */
     public static final int ALERT_OPTION_LOW_PRIORITY_ONCE      = 6;
 
-    /** Alert option: low-priority alert - repeat. */
+    /** Alert option: low-priority alert - repeat. @hide */
     public static final int ALERT_OPTION_LOW_PRIORITY_REPEAT    = 7;
 
-    /** Alert option: medium-priority alert once. */
+    /** Alert option: medium-priority alert once. @hide */
     public static final int ALERT_OPTION_MED_PRIORITY_ONCE      = 8;
 
-    /** Alert option: medium-priority alert - repeat. */
+    /** Alert option: medium-priority alert - repeat. @hide */
     public static final int ALERT_OPTION_MED_PRIORITY_REPEAT    = 9;
 
-    /** Alert option: high-priority alert once. */
+    /** Alert option: high-priority alert once. @hide */
     public static final int ALERT_OPTION_HIGH_PRIORITY_ONCE     = 10;
 
-    /** Alert option: high-priority alert - repeat. */
+    /** Alert option: high-priority alert - repeat. @hide */
     public static final int ALERT_OPTION_HIGH_PRIORITY_REPEAT   = 11;
 
     /** Service category operation (add/delete/clear). */
@@ -94,9 +145,12 @@
     /** Name of service category. */
     private final String mCategoryName;
 
-    /** Create a new CdmaSmsCbProgramData object with the specified values. */
-    public CdmaSmsCbProgramData(int operation, int category, int language, int maxMessages,
-            int alertOption, @NonNull String categoryName) {
+    /**
+     * Create a new CdmaSmsCbProgramData object with the specified values.
+     * @hide
+     */
+    public CdmaSmsCbProgramData(@Operation int operation, @Category int category, int language,
+            int maxMessages, int alertOption, @NonNull String categoryName) {
         mOperation = operation;
         mCategory = category;
         mLanguage = language;
@@ -105,7 +159,10 @@
         mCategoryName = categoryName;
     }
 
-    /** Create a new CdmaSmsCbProgramData object from a Parcel. */
+    /**
+     * Create a new CdmaSmsCbProgramData object from a Parcel.
+     * @hide
+     */
     CdmaSmsCbProgramData(Parcel in) {
         mOperation = in.readInt();
         mCategory = in.readInt();
@@ -133,23 +190,28 @@
 
     /**
      * Returns the service category operation, e.g. {@link #OPERATION_ADD_CATEGORY}.
-     * @return one of the {@code OPERATION_*} values
+     *
+     * @return the service category operation
      */
-    public int getOperation() {
+    public @Operation int getOperation() {
         return mOperation;
     }
 
     /**
-     * Returns the CDMA service category to modify.
+     * Returns the CDMA service category to modify. See 3GPP2 C.S0015-B section 3.4.3.2 for more
+     * information on the service category. Currently only CMAS service categories 0x1000 through
+     * 0x10FF are supported.
+     *
      * @return a 16-bit CDMA service category value
      */
-    public int getCategory() {
+    public @Category int getCategory() {
         return mCategory;
     }
 
     /**
      * Returns the CDMA language code for this service category.
      * @return one of the language values defined in BearerData.LANGUAGE_*
+     * @hide
      */
     public int getLanguage() {
         return mLanguage;
@@ -158,6 +220,7 @@
     /**
      * Returns the maximum number of messages to store for this service category.
      * @return the maximum number of messages to store for this service category
+     * @hide
      */
     public int getMaxMessages() {
         return mMaxMessages;
@@ -166,6 +229,7 @@
     /**
      * Returns the service category alert option, e.g. {@link #ALERT_OPTION_DEFAULT_ALERT}.
      * @return one of the {@code ALERT_OPTION_*} values
+     * @hide
      */
     public int getAlertOption() {
         return mAlertOption;
@@ -174,6 +238,7 @@
     /**
      * Returns the service category name, in the language specified by {@link #getLanguage()}.
      * @return an optional service category name
+     * @hide
      */
     @NonNull
     public String getCategoryName() {
@@ -196,7 +261,10 @@
         return 0;
     }
 
-    /** Creator for unparcelling objects. */
+    /**
+     * Creator for unparcelling objects.
+     */
+    @NonNull
     public static final Parcelable.Creator<CdmaSmsCbProgramData>
             CREATOR = new Parcelable.Creator<CdmaSmsCbProgramData>() {
         @Override
diff --git a/telephony/java/android/telephony/data/ApnSetting.java b/telephony/java/android/telephony/data/ApnSetting.java
index 116c051..2161dcb 100644
--- a/telephony/java/android/telephony/data/ApnSetting.java
+++ b/telephony/java/android/telephony/data/ApnSetting.java
@@ -26,6 +26,8 @@
 import android.os.Parcelable;
 import android.provider.Telephony;
 import android.provider.Telephony.Carriers;
+import android.telephony.Annotation.ApnType;
+import android.telephony.Annotation.NetworkType;
 import android.telephony.Rlog;
 import android.telephony.ServiceState;
 import android.telephony.TelephonyManager;
@@ -109,23 +111,6 @@
     /** APN type for MCX (Mission Critical Service) where X can be PTT/Video/Data */
     public static final int TYPE_MCX = ApnTypes.MCX;
 
-    /** @hide */
-    @IntDef(flag = true, prefix = { "TYPE_" }, value = {
-        TYPE_DEFAULT,
-        TYPE_MMS,
-        TYPE_SUPL,
-        TYPE_DUN,
-        TYPE_HIPRI,
-        TYPE_FOTA,
-        TYPE_IMS,
-        TYPE_CBS,
-        TYPE_IA,
-        TYPE_EMERGENCY,
-        TYPE_MCX
-    })
-    @Retention(RetentionPolicy.SOURCE)
-    public @interface ApnType {}
-
     // Possible values for authentication types.
     /** No authentication type. */
     public static final int AUTH_TYPE_NONE = 0;
@@ -1425,7 +1410,7 @@
      *
      * @hide
      */
-    public boolean canSupportNetworkType(@TelephonyManager.NetworkType int networkType) {
+    public boolean canSupportNetworkType(@NetworkType int networkType) {
         // Do a special checking for GSM. In reality, GSM is a voice only network type and can never
         // be used for data. We allow it here because in some DSDS corner cases, on the non-DDS
         // sub, modem reports data rat unknown. In that case if voice is GSM and this APN supports
diff --git a/telephony/java/android/telephony/data/DataCallResponse.java b/telephony/java/android/telephony/data/DataCallResponse.java
index 9170e88..49625bb 100644
--- a/telephony/java/android/telephony/data/DataCallResponse.java
+++ b/telephony/java/android/telephony/data/DataCallResponse.java
@@ -24,8 +24,8 @@
 import android.net.LinkAddress;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.telephony.Annotation.DataFailureCause;
 import android.telephony.DataFailCause;
-import android.telephony.DataFailCause.FailCause;
 import android.telephony.data.ApnSetting.ProtocolType;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -67,7 +67,7 @@
     /** Indicates the data connection is active with physical link up. */
     public static final int LINK_STATUS_ACTIVE = 2;
 
-    private final @FailCause int mCause;
+    private final @DataFailureCause int mCause;
     private final int mSuggestedRetryTime;
     private final int mId;
     private final @LinkStatus int mLinkStatus;
@@ -103,7 +103,7 @@
      *
      * @removed Use the {@link Builder()} instead.
      */
-    public DataCallResponse(@FailCause int cause, int suggestedRetryTime, int id,
+    public DataCallResponse(@DataFailureCause int cause, int suggestedRetryTime, int id,
                             @LinkStatus int linkStatus,
                             @ProtocolType int protocolType, @Nullable String interfaceName,
                             @Nullable List<LinkAddress> addresses,
@@ -150,7 +150,7 @@
     /**
      * @return Data call fail cause. {@link DataFailCause#NONE} indicates no error.
      */
-    @FailCause
+    @DataFailureCause
     public int getCause() { return mCause; }
 
     /**
@@ -314,7 +314,7 @@
      * </code></pre>
      */
     public static final class Builder {
-        private @FailCause int mCause;
+        private @DataFailureCause int mCause;
 
         private int mSuggestedRetryTime;
 
@@ -348,7 +348,7 @@
          * @param cause Data call fail cause. {@link DataFailCause#NONE} indicates no error.
          * @return The same instance of the builder.
          */
-        public @NonNull Builder setCause(@FailCause int cause) {
+        public @NonNull Builder setCause(@DataFailureCause int cause) {
             mCause = cause;
             return this;
         }
diff --git a/telephony/java/android/telephony/data/DataProfile.java b/telephony/java/android/telephony/data/DataProfile.java
index 0d79ec9..30c209b 100644
--- a/telephony/java/android/telephony/data/DataProfile.java
+++ b/telephony/java/android/telephony/data/DataProfile.java
@@ -25,8 +25,8 @@
 import android.os.Build;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.telephony.Annotation.ApnType;
 import android.telephony.TelephonyManager.NetworkTypeBitMask;
-import android.telephony.data.ApnSetting.ApnType;
 import android.telephony.data.ApnSetting.AuthType;
 import android.text.TextUtils;
 
diff --git a/telephony/java/android/telephony/data/QualifiedNetworksService.java b/telephony/java/android/telephony/data/QualifiedNetworksService.java
index 0e1751d..e793979 100644
--- a/telephony/java/android/telephony/data/QualifiedNetworksService.java
+++ b/telephony/java/android/telephony/data/QualifiedNetworksService.java
@@ -27,8 +27,8 @@
 import android.os.Message;
 import android.os.RemoteException;
 import android.telephony.AccessNetworkConstants.AccessNetworkType;
+import android.telephony.Annotation.ApnType;
 import android.telephony.Rlog;
-import android.telephony.data.ApnSetting.ApnType;
 import android.util.SparseArray;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -133,7 +133,7 @@
          * service.
          *
          * @param apnTypes APN types of the qualified networks. This must be a bitmask combination
-         * of {@link ApnSetting.ApnType}.
+         * of {@link 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 list
          * is a {@link AccessNetworkType}. An empty list indicates no networks are qualified
diff --git a/telephony/java/android/telephony/emergency/EmergencyNumber.java b/telephony/java/android/telephony/emergency/EmergencyNumber.java
index 19d0724..1666265 100644
--- a/telephony/java/android/telephony/emergency/EmergencyNumber.java
+++ b/telephony/java/android/telephony/emergency/EmergencyNumber.java
@@ -18,6 +18,7 @@
 
 import android.annotation.IntDef;
 import android.annotation.NonNull;
+import android.annotation.TestApi;
 import android.hardware.radio.V1_4.EmergencyNumberSource;
 import android.hardware.radio.V1_4.EmergencyServiceCategory;
 import android.os.Parcel;
@@ -184,6 +185,7 @@
      *
      * @hide
      */
+    @TestApi
     public static final int EMERGENCY_NUMBER_SOURCE_TEST =  1 << 5;
     /** Bit-field which indicates the number is from the modem config. */
     public static final int EMERGENCY_NUMBER_SOURCE_MODEM_CONFIG =
diff --git a/telephony/java/android/telephony/euicc/EuiccManager.java b/telephony/java/android/telephony/euicc/EuiccManager.java
index cabd4df..5a90cb1 100644
--- a/telephony/java/android/telephony/euicc/EuiccManager.java
+++ b/telephony/java/android/telephony/euicc/EuiccManager.java
@@ -32,6 +32,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.telephony.TelephonyManager;
+import android.telephony.euicc.EuiccCardManager.ResetOption;
 
 import com.android.internal.telephony.euicc.IEuiccController;
 
@@ -821,17 +822,22 @@
     }
 
     /**
-     * Erase all subscriptions and reset the eUICC.
+     * Erase all operational subscriptions and reset the eUICC.
      *
      * <p>Requires that the calling app has the
      * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
      *
      * @param callbackIntent a PendingIntent to launch when the operation completes.
+     *
+     * @deprecated From R, callers should specify a flag for specific set of subscriptions to erase
+     * and use @link{eraseSubscriptionsWithOptions} instead
+     *
      * @hide
      */
     @SystemApi
     @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
-    public void eraseSubscriptions(PendingIntent callbackIntent) {
+    @Deprecated
+    public void eraseSubscriptions(@NonNull PendingIntent callbackIntent) {
         if (!isEnabled()) {
             sendUnavailableError(callbackIntent);
             return;
@@ -844,6 +850,32 @@
     }
 
     /**
+     * Erase all specific subscriptions and reset the eUICC.
+     *
+     * <p>Requires that the calling app has the
+     * {@code android.Manifest.permission#WRITE_EMBEDDED_SUBSCRIPTIONS} permission.
+     *
+     * @param options flag indicating specific set of subscriptions to erase
+     * @param callbackIntent a PendingIntent to launch when the operation completes.
+     *
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(Manifest.permission.WRITE_EMBEDDED_SUBSCRIPTIONS)
+    public void eraseSubscriptionsWithOptions(
+            @ResetOption int options, @NonNull PendingIntent callbackIntent) {
+        if (!isEnabled()) {
+            sendUnavailableError(callbackIntent);
+            return;
+        }
+        try {
+            getIEuiccController().eraseSubscriptionsWithOptions(mCardId, options, callbackIntent);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Ensure that subscriptions will be retained on the next factory reset.
      *
      * <p>By default, all subscriptions on the eUICC are erased the first time a device boots (ever
diff --git a/telephony/java/com/android/internal/telephony/ISms.aidl b/telephony/java/com/android/internal/telephony/ISms.aidl
index 7441c26..f3a335d 100644
--- a/telephony/java/com/android/internal/telephony/ISms.aidl
+++ b/telephony/java/com/android/internal/telephony/ISms.aidl
@@ -19,7 +19,6 @@
 import android.app.PendingIntent;
 import android.net.Uri;
 import android.os.Bundle;
-import android.telephony.IFinancialSmsCallback;
 import com.android.internal.telephony.SmsRawData;
 
 /**
@@ -570,17 +569,6 @@
             int subId, String callingPkg, String prefixes, in PendingIntent intent);
 
     /**
-     * Get sms inbox messages for the calling financial app.
-     *
-     * @param subId the SIM id.
-     * @param callingPkg the package name of the calling app.
-     * @param params parameters to filter the sms messages.
-     * @param callback the callback interface to deliver the result.
-     */
-    void getSmsMessagesForFinancialApp(
-        int subId, String callingPkg, in Bundle params, in IFinancialSmsCallback callback);
-
-    /**
      * Check if the destination is a possible premium short code.
      *
      * @param destAddress the destination address to test for possible short code
diff --git a/telephony/java/com/android/internal/telephony/ISmsImplBase.java b/telephony/java/com/android/internal/telephony/ISmsImplBase.java
index aa1f94f..2096325 100644
--- a/telephony/java/com/android/internal/telephony/ISmsImplBase.java
+++ b/telephony/java/com/android/internal/telephony/ISmsImplBase.java
@@ -19,7 +19,6 @@
 import android.app.PendingIntent;
 import android.net.Uri;
 import android.os.Bundle;
-import android.telephony.IFinancialSmsCallback;
 
 import java.util.List;
 
@@ -198,12 +197,6 @@
     }
 
     @Override
-    public void getSmsMessagesForFinancialApp(
-            int subId, String callingPkg, Bundle params, IFinancialSmsCallback callback) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
     public int checkSmsShortCodeDestination(
             int subid, String callingApk, String destAddress, String countryIso) {
         throw new UnsupportedOperationException();
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index 866e936..fd7ec56 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -302,7 +302,7 @@
      * operator's MCC (Mobile Country Code).
      * @see android.telephony.TelephonyManager#getNetworkCountryIso
      */
-    String getNetworkCountryIsoForPhone(int phoneId);
+    String getNetworkCountryIsoForPhone(int phoneId, String callingPkg);
 
     /**
      * Returns the neighboring cell information of the device.
@@ -1612,6 +1612,18 @@
     String[] getForbiddenPlmns(int subId, int appType, String callingPackage);
 
     /**
+     * Set the forbidden PLMN list from the givven app type (ex APPTYPE_USIM) on a particular
+     * subscription.
+     *
+     * @param subId subId the id of the subscription
+     * @param appType appType the uicc app type, must be USIM or SIM.
+     * @param fplmns plmns the Forbiden plmns list that needed to be written to the SIM.
+     * @param content callingPackage the op Package name.
+     * @return number of fplmns that is successfully written to the SIM
+     */
+    int setForbiddenPlmns(int subId, int appType, in List<String> fplmns, String callingPackage);
+
+    /**
      * Check if phone is in emergency callback mode
      * @return true if phone is in emergency callback mode
      * @param subId the subscription ID that this action applies to.
diff --git a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
index 98fee83..d7a7af1 100644
--- a/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephonyRegistry.aidl
@@ -43,8 +43,8 @@
     void listenForSubscriber(in int subId, String pkg, IPhoneStateListener callback, int events,
             boolean notifyNow);
     @UnsupportedAppUsage
-    void notifyCallState(int state, String incomingNumber);
-    void notifyCallStateForPhoneId(in int phoneId, in int subId, int state, String incomingNumber);
+    void notifyCallStateForAllSubs(int state, String incomingNumber);
+    void notifyCallState(in int phoneId, in int subId, int state, String incomingNumber);
     void notifyServiceStateForPhoneId(in int phoneId, in int subId, in ServiceState state);
     void notifySignalStrengthForPhoneId(in int phoneId, in int subId,
             in SignalStrength signalStrength);
@@ -93,6 +93,10 @@
     void notifyActiveDataSubIdChanged(int activeDataSubId);
     void notifyRadioPowerStateChanged(in int phoneId, in int subId, in int state);
     void notifyEmergencyNumberList(in int phoneId, in int subId);
+    void notifyOutgoingEmergencyCall(in int phoneId, in int subId,
+            in EmergencyNumber emergencyNumber);
+    void notifyOutgoingEmergencySms(in int phoneId, in int subId,
+            in EmergencyNumber emergencyNumber);
     void notifyCallQualityChanged(in CallQuality callQuality, int phoneId, int subId,
             int callNetworkType);
     void notifyImsDisconnectCause(int subId, in ImsReasonInfo imsReasonInfo);
diff --git a/telephony/java/com/android/internal/telephony/PhoneConstants.java b/telephony/java/com/android/internal/telephony/PhoneConstants.java
index ee1a476..c19ae7b 100644
--- a/telephony/java/com/android/internal/telephony/PhoneConstants.java
+++ b/telephony/java/com/android/internal/telephony/PhoneConstants.java
@@ -89,10 +89,6 @@
     @UnsupportedAppUsage
     public static final int PRESENTATION_PAYPHONE = 4;   // show pay phone info
 
-    // Sim activation type
-    public static final int SIM_ACTIVATION_TYPE_VOICE = 0;
-    public static final int SIM_ACTIVATION_TYPE_DATA = 1;
-
     public static final String PHONE_NAME_KEY = "phoneName";
     public static final String DATA_NETWORK_TYPE_KEY = "networkType";
     public static final String DATA_FAILURE_CAUSE_KEY = "failCause";
@@ -174,7 +170,7 @@
 
     public static final int RIL_CARD_MAX_APPS    = 8;
 
-    public static final int DEFAULT_CARD_INDEX   = 0;
+    public static final int DEFAULT_SLOT_INDEX   = 0;
 
     public static final int MAX_PHONE_COUNT_SINGLE_SIM = 1;
 
diff --git a/telephony/java/com/android/internal/telephony/SmsApplication.java b/telephony/java/com/android/internal/telephony/SmsApplication.java
deleted file mode 100644
index f10398f..0000000
--- a/telephony/java/com/android/internal/telephony/SmsApplication.java
+++ /dev/null
@@ -1,1081 +0,0 @@
-/*
- * Copyright (C) 2013 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.internal.telephony;
-
-import android.Manifest.permission;
-import android.annotation.Nullable;
-import android.app.AppOpsManager;
-import android.app.role.RoleManager;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ActivityInfo;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
-import android.net.Uri;
-import android.os.AsyncTask;
-import android.os.Binder;
-import android.os.Debug;
-import android.os.Process;
-import android.os.UserHandle;
-import android.provider.Telephony;
-import android.provider.Telephony.Sms.Intents;
-import android.telephony.Rlog;
-import android.telephony.SmsManager;
-import android.telephony.TelephonyManager;
-import android.util.Log;
-
-import com.android.internal.content.PackageMonitor;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-import dalvik.annotation.compat.UnsupportedAppUsage;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.function.Consumer;
-
-/**
- * Class for managing the primary application that we will deliver SMS/MMS messages to
- *
- * {@hide}
- */
-public final class SmsApplication {
-    static final String LOG_TAG = "SmsApplication";
-    private static final String PHONE_PACKAGE_NAME = "com.android.phone";
-    private static final String BLUETOOTH_PACKAGE_NAME = "com.android.bluetooth";
-    private static final String MMS_SERVICE_PACKAGE_NAME = "com.android.mms.service";
-    private static final String TELEPHONY_PROVIDER_PACKAGE_NAME = "com.android.providers.telephony";
-
-    private static final String SCHEME_SMS = "sms";
-    private static final String SCHEME_SMSTO = "smsto";
-    private static final String SCHEME_MMS = "mms";
-    private static final String SCHEME_MMSTO = "mmsto";
-    private static final boolean DEBUG = false;
-    private static final boolean DEBUG_MULTIUSER = false;
-
-    private static final int[] DEFAULT_APP_EXCLUSIVE_APPOPS = {
-            AppOpsManager.OP_READ_SMS,
-            AppOpsManager.OP_WRITE_SMS,
-            AppOpsManager.OP_RECEIVE_SMS,
-            AppOpsManager.OP_RECEIVE_WAP_PUSH,
-            AppOpsManager.OP_SEND_SMS,
-            AppOpsManager.OP_READ_CELL_BROADCASTS
-    };
-
-    private static SmsPackageMonitor sSmsPackageMonitor = null;
-
-    public static class SmsApplicationData {
-        /**
-         * Name of this SMS app for display.
-         */
-        @UnsupportedAppUsage
-        private String mApplicationName;
-
-        /**
-         * Package name for this SMS app.
-         */
-        public String mPackageName;
-
-        /**
-         * The class name of the SMS_DELIVER_ACTION receiver in this app.
-         */
-        private String mSmsReceiverClass;
-
-        /**
-         * The class name of the WAP_PUSH_DELIVER_ACTION receiver in this app.
-         */
-        private String mMmsReceiverClass;
-
-        /**
-         * The class name of the ACTION_RESPOND_VIA_MESSAGE intent in this app.
-         */
-        private String mRespondViaMessageClass;
-
-        /**
-         * The class name of the ACTION_SENDTO intent in this app.
-         */
-        private String mSendToClass;
-
-        /**
-         * The class name of the ACTION_DEFAULT_SMS_PACKAGE_CHANGED receiver in this app.
-         */
-        private String mSmsAppChangedReceiverClass;
-
-        /**
-         * The class name of the ACTION_EXTERNAL_PROVIDER_CHANGE receiver in this app.
-         */
-        private String mProviderChangedReceiverClass;
-
-        /**
-         * The class name of the SIM_FULL_ACTION receiver in this app.
-         */
-        private String mSimFullReceiverClass;
-
-        /**
-         * The user-id for this application
-         */
-        private int mUid;
-
-        /**
-         * Returns true if this SmsApplicationData is complete (all intents handled).
-         * @return
-         */
-        public boolean isComplete() {
-            return (mSmsReceiverClass != null && mMmsReceiverClass != null
-                    && mRespondViaMessageClass != null && mSendToClass != null);
-        }
-
-        public SmsApplicationData(String packageName, int uid) {
-            mPackageName = packageName;
-            mUid = uid;
-        }
-
-        public String getApplicationName(Context context) {
-            if (mApplicationName == null) {
-                PackageManager pm = context.getPackageManager();
-                ApplicationInfo appInfo;
-                try {
-                    appInfo = pm.getApplicationInfoAsUser(mPackageName, 0,
-                            UserHandle.getUserHandleForUid(mUid));
-                } catch (NameNotFoundException e) {
-                    return null;
-                }
-                if (appInfo != null) {
-                    CharSequence label  = pm.getApplicationLabel(appInfo);
-                    mApplicationName = (label == null) ? null : label.toString();
-                }
-            }
-            return mApplicationName;
-        }
-
-        @Override
-        public String toString() {
-            return " mPackageName: " + mPackageName
-                    + " mSmsReceiverClass: " + mSmsReceiverClass
-                    + " mMmsReceiverClass: " + mMmsReceiverClass
-                    + " mRespondViaMessageClass: " + mRespondViaMessageClass
-                    + " mSendToClass: " + mSendToClass
-                    + " mSmsAppChangedClass: " + mSmsAppChangedReceiverClass
-                    + " mProviderChangedReceiverClass: " + mProviderChangedReceiverClass
-                    + " mSimFullReceiverClass: " + mSimFullReceiverClass
-                    + " mUid: " + mUid;
-        }
-    }
-
-    /**
-     * Returns the userId of the Context object, if called from a system app,
-     * otherwise it returns the caller's userId
-     * @param context The context object passed in by the caller.
-     * @return
-     */
-    private static int getIncomingUserId(Context context) {
-        int contextUserId = UserHandle.myUserId();
-        final int callingUid = Binder.getCallingUid();
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getIncomingUserHandle caller=" + callingUid + ", myuid="
-                    + android.os.Process.myUid() + "\n\t" + Debug.getCallers(4));
-        }
-        if (UserHandle.getAppId(callingUid)
-                < android.os.Process.FIRST_APPLICATION_UID) {
-            return contextUserId;
-        } else {
-            return UserHandle.getUserId(callingUid);
-        }
-    }
-
-    /**
-     * Returns the list of available SMS apps defined as apps that are registered for both the
-     * SMS_RECEIVED_ACTION (SMS) and WAP_PUSH_RECEIVED_ACTION (MMS) broadcasts (and their broadcast
-     * receivers are enabled)
-     *
-     * Requirements to be an SMS application:
-     * Implement SMS_DELIVER_ACTION broadcast receiver.
-     * Require BROADCAST_SMS permission.
-     *
-     * Implement WAP_PUSH_DELIVER_ACTION broadcast receiver.
-     * Require BROADCAST_WAP_PUSH permission.
-     *
-     * Implement RESPOND_VIA_MESSAGE intent.
-     * Support smsto Uri scheme.
-     * Require SEND_RESPOND_VIA_MESSAGE permission.
-     *
-     * Implement ACTION_SENDTO intent.
-     * Support smsto Uri scheme.
-     */
-    @UnsupportedAppUsage
-    public static Collection<SmsApplicationData> getApplicationCollection(Context context) {
-        return getApplicationCollectionAsUser(context, getIncomingUserId(context));
-    }
-
-    /**
-     * Same as {@link #getApplicationCollection} but it takes a target user ID.
-     */
-    public static Collection<SmsApplicationData> getApplicationCollectionAsUser(Context context,
-            int userId) {
-        final long token = Binder.clearCallingIdentity();
-        try {
-            return getApplicationCollectionInternal(context, userId);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    private static Collection<SmsApplicationData> getApplicationCollectionInternal(
-            Context context, int userId) {
-        PackageManager packageManager = context.getPackageManager();
-
-        // Get the list of apps registered for SMS
-        Intent intent = new Intent(Intents.SMS_DELIVER_ACTION);
-        if (DEBUG) {
-            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
-        }
-        List<ResolveInfo> smsReceivers = packageManager.queryBroadcastReceiversAsUser(intent,
-                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
-                userId);
-
-        HashMap<String, SmsApplicationData> receivers = new HashMap<String, SmsApplicationData>();
-
-        // Add one entry to the map for every sms receiver (ignoring duplicate sms receivers)
-        for (ResolveInfo resolveInfo : smsReceivers) {
-            final ActivityInfo activityInfo = resolveInfo.activityInfo;
-            if (activityInfo == null) {
-                continue;
-            }
-            if (!permission.BROADCAST_SMS.equals(activityInfo.permission)) {
-                continue;
-            }
-            final String packageName = activityInfo.packageName;
-            if (!receivers.containsKey(packageName)) {
-                final SmsApplicationData smsApplicationData = new SmsApplicationData(packageName,
-                        activityInfo.applicationInfo.uid);
-                smsApplicationData.mSmsReceiverClass = activityInfo.name;
-                receivers.put(packageName, smsApplicationData);
-            }
-        }
-
-        // Update any existing entries with mms receiver class
-        intent = new Intent(Intents.WAP_PUSH_DELIVER_ACTION);
-        intent.setDataAndType(null, "application/vnd.wap.mms-message");
-        List<ResolveInfo> mmsReceivers = packageManager.queryBroadcastReceiversAsUser(intent,
-                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
-                userId);
-        for (ResolveInfo resolveInfo : mmsReceivers) {
-            final ActivityInfo activityInfo = resolveInfo.activityInfo;
-            if (activityInfo == null) {
-                continue;
-            }
-            if (!permission.BROADCAST_WAP_PUSH.equals(activityInfo.permission)) {
-                continue;
-            }
-            final String packageName = activityInfo.packageName;
-            final SmsApplicationData smsApplicationData = receivers.get(packageName);
-            if (smsApplicationData != null) {
-                smsApplicationData.mMmsReceiverClass = activityInfo.name;
-            }
-        }
-
-        // Update any existing entries with respond via message intent class.
-        intent = new Intent(TelephonyManager.ACTION_RESPOND_VIA_MESSAGE,
-                Uri.fromParts(SCHEME_SMSTO, "", null));
-        List<ResolveInfo> respondServices = packageManager.queryIntentServicesAsUser(intent,
-                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
-                UserHandle.of(userId));
-        for (ResolveInfo resolveInfo : respondServices) {
-            final ServiceInfo serviceInfo = resolveInfo.serviceInfo;
-            if (serviceInfo == null) {
-                continue;
-            }
-            if (!permission.SEND_RESPOND_VIA_MESSAGE.equals(serviceInfo.permission)) {
-                continue;
-            }
-            final String packageName = serviceInfo.packageName;
-            final SmsApplicationData smsApplicationData = receivers.get(packageName);
-            if (smsApplicationData != null) {
-                smsApplicationData.mRespondViaMessageClass = serviceInfo.name;
-            }
-        }
-
-        // Update any existing entries with supports send to.
-        intent = new Intent(Intent.ACTION_SENDTO,
-                Uri.fromParts(SCHEME_SMSTO, "", null));
-        List<ResolveInfo> sendToActivities = packageManager.queryIntentActivitiesAsUser(intent,
-                PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
-                userId);
-        for (ResolveInfo resolveInfo : sendToActivities) {
-            final ActivityInfo activityInfo = resolveInfo.activityInfo;
-            if (activityInfo == null) {
-                continue;
-            }
-            final String packageName = activityInfo.packageName;
-            final SmsApplicationData smsApplicationData = receivers.get(packageName);
-            if (smsApplicationData != null) {
-                smsApplicationData.mSendToClass = activityInfo.name;
-            }
-        }
-
-        // Update any existing entries with the default sms changed handler.
-        intent = new Intent(Telephony.Sms.Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED);
-        List<ResolveInfo> smsAppChangedReceivers =
-                packageManager.queryBroadcastReceiversAsUser(intent,
-                        PackageManager.MATCH_DIRECT_BOOT_AWARE
-                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getApplicationCollectionInternal smsAppChangedActivities=" +
-                    smsAppChangedReceivers);
-        }
-        for (ResolveInfo resolveInfo : smsAppChangedReceivers) {
-            final ActivityInfo activityInfo = resolveInfo.activityInfo;
-            if (activityInfo == null) {
-                continue;
-            }
-            final String packageName = activityInfo.packageName;
-            final SmsApplicationData smsApplicationData = receivers.get(packageName);
-            if (DEBUG_MULTIUSER) {
-                Log.i(LOG_TAG, "getApplicationCollectionInternal packageName=" +
-                        packageName + " smsApplicationData: " + smsApplicationData +
-                        " activityInfo.name: " + activityInfo.name);
-            }
-            if (smsApplicationData != null) {
-                smsApplicationData.mSmsAppChangedReceiverClass = activityInfo.name;
-            }
-        }
-
-        // Update any existing entries with the external provider changed handler.
-        intent = new Intent(Telephony.Sms.Intents.ACTION_EXTERNAL_PROVIDER_CHANGE);
-        List<ResolveInfo> providerChangedReceivers =
-                packageManager.queryBroadcastReceiversAsUser(intent,
-                        PackageManager.MATCH_DIRECT_BOOT_AWARE
-                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getApplicationCollectionInternal providerChangedActivities=" +
-                    providerChangedReceivers);
-        }
-        for (ResolveInfo resolveInfo : providerChangedReceivers) {
-            final ActivityInfo activityInfo = resolveInfo.activityInfo;
-            if (activityInfo == null) {
-                continue;
-            }
-            final String packageName = activityInfo.packageName;
-            final SmsApplicationData smsApplicationData = receivers.get(packageName);
-            if (DEBUG_MULTIUSER) {
-                Log.i(LOG_TAG, "getApplicationCollectionInternal packageName=" +
-                        packageName + " smsApplicationData: " + smsApplicationData +
-                        " activityInfo.name: " + activityInfo.name);
-            }
-            if (smsApplicationData != null) {
-                smsApplicationData.mProviderChangedReceiverClass = activityInfo.name;
-            }
-        }
-
-        // Update any existing entries with the sim full handler.
-        intent = new Intent(Intents.SIM_FULL_ACTION);
-        List<ResolveInfo> simFullReceivers =
-                packageManager.queryBroadcastReceiversAsUser(intent,
-                        PackageManager.MATCH_DIRECT_BOOT_AWARE
-                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId);
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getApplicationCollectionInternal simFullReceivers="
-                    + simFullReceivers);
-        }
-        for (ResolveInfo resolveInfo : simFullReceivers) {
-            final ActivityInfo activityInfo = resolveInfo.activityInfo;
-            if (activityInfo == null) {
-                continue;
-            }
-            final String packageName = activityInfo.packageName;
-            final SmsApplicationData smsApplicationData = receivers.get(packageName);
-            if (DEBUG_MULTIUSER) {
-                Log.i(LOG_TAG, "getApplicationCollectionInternal packageName="
-                        + packageName + " smsApplicationData: " + smsApplicationData
-                        + " activityInfo.name: " + activityInfo.name);
-            }
-            if (smsApplicationData != null) {
-                smsApplicationData.mSimFullReceiverClass = activityInfo.name;
-            }
-        }
-
-        // Remove any entries for which we did not find all required intents.
-        for (ResolveInfo resolveInfo : smsReceivers) {
-            final ActivityInfo activityInfo = resolveInfo.activityInfo;
-            if (activityInfo == null) {
-                continue;
-            }
-            final String packageName = activityInfo.packageName;
-            final SmsApplicationData smsApplicationData = receivers.get(packageName);
-            if (smsApplicationData != null) {
-                if (!smsApplicationData.isComplete()) {
-                    receivers.remove(packageName);
-                }
-            }
-        }
-        return receivers.values();
-    }
-
-    /**
-     * Checks to see if we have a valid installed SMS application for the specified package name
-     * @return Data for the specified package name or null if there isn't one
-     */
-    public static SmsApplicationData getApplicationForPackage(
-            Collection<SmsApplicationData> applications, String packageName) {
-        if (packageName == null) {
-            return null;
-        }
-        // Is there an entry in the application list for the specified package?
-        for (SmsApplicationData application : applications) {
-            if (application.mPackageName.contentEquals(packageName)) {
-                return application;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Get the application we will use for delivering SMS/MMS messages.
-     *
-     * We return the preferred sms application with the following order of preference:
-     * (1) User selected SMS app (if selected, and if still valid)
-     * (2) Android Messaging (if installed)
-     * (3) The currently configured highest priority broadcast receiver
-     * (4) Null
-     */
-    private static SmsApplicationData getApplication(Context context, boolean updateIfNeeded,
-            int userId) {
-        TelephonyManager tm = (TelephonyManager)
-                context.getSystemService(Context.TELEPHONY_SERVICE);
-        RoleManager roleManager = (RoleManager) context.getSystemService(Context.ROLE_SERVICE);
-        // (b/134400042) RoleManager might be null in unit tests running older mockito versions
-        // that do not support mocking final classes.
-        if (!tm.isSmsCapable() && (roleManager == null || !roleManager.isRoleAvailable(
-                RoleManager.ROLE_SMS))) {
-            // No phone, no SMS
-            return null;
-        }
-
-        Collection<SmsApplicationData> applications = getApplicationCollectionInternal(context,
-                userId);
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getApplication userId=" + userId);
-        }
-        // Determine which application receives the broadcast
-        String defaultApplication = getDefaultSmsPackage(context, userId);
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getApplication defaultApp=" + defaultApplication);
-        }
-
-        SmsApplicationData applicationData = null;
-        if (defaultApplication != null) {
-            applicationData = getApplicationForPackage(applications, defaultApplication);
-        }
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getApplication appData=" + applicationData);
-        }
-
-        // If we found a package, make sure AppOps permissions are set up correctly
-        if (applicationData != null) {
-            // We can only call checkOp if we are privileged (updateIfNeeded) or if the app we
-            // are checking is for our current uid. Doing this check from the unprivileged current
-            // SMS app allows us to tell the current SMS app that it is not in a good state and
-            // needs to ask to be the current SMS app again to work properly.
-            if (updateIfNeeded || applicationData.mUid == android.os.Process.myUid()) {
-                // Verify that the SMS app has permissions
-                boolean appOpsFixed =
-                        tryFixExclusiveSmsAppops(context, applicationData, updateIfNeeded);
-                if (!appOpsFixed) {
-                    // We can not return a package if permissions are not set up correctly
-                    applicationData = null;
-                }
-            }
-
-            // We can only verify the phone and BT app's permissions from a privileged caller
-            if (applicationData != null && updateIfNeeded) {
-                // Ensure this component is still configured as the preferred activity. Usually the
-                // current SMS app will already be the preferred activity - but checking whether or
-                // not this is true is just as expensive as reconfiguring the preferred activity so
-                // we just reconfigure every time.
-                defaultSmsAppChanged(context);
-            }
-        }
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "getApplication returning appData=" + applicationData);
-        }
-        return applicationData;
-    }
-
-    private static String getDefaultSmsPackage(Context context, int userId) {
-        return context.getSystemService(RoleManager.class).getDefaultSmsPackage(userId);
-    }
-
-    /**
-     * Grants various permissions and appops on sms app change
-     */
-    private static void defaultSmsAppChanged(Context context) {
-        PackageManager packageManager = context.getPackageManager();
-        AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
-
-        // Assign permission to special system apps
-        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
-                PHONE_PACKAGE_NAME);
-        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
-                BLUETOOTH_PACKAGE_NAME);
-        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
-                MMS_SERVICE_PACKAGE_NAME);
-        assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps,
-                TELEPHONY_PROVIDER_PACKAGE_NAME);
-
-        // Give AppOps permission to UID 1001 which contains multiple
-        // apps, all of them should be able to write to telephony provider.
-        // This is to allow the proxy package permission check in telephony provider
-        // to pass.
-        for (int appop : DEFAULT_APP_EXCLUSIVE_APPOPS) {
-            appOps.setUidMode(appop, Process.PHONE_UID, AppOpsManager.MODE_ALLOWED);
-        }
-    }
-
-    private static boolean tryFixExclusiveSmsAppops(Context context,
-            SmsApplicationData applicationData, boolean updateIfNeeded) {
-        AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
-        for (int appOp : DEFAULT_APP_EXCLUSIVE_APPOPS) {
-            int mode = appOps.checkOp(appOp, applicationData.mUid,
-                    applicationData.mPackageName);
-            if (mode != AppOpsManager.MODE_ALLOWED) {
-                Rlog.e(LOG_TAG, applicationData.mPackageName + " lost "
-                        + AppOpsManager.modeToName(appOp) + ": "
-                        + (updateIfNeeded ? " (fixing)" : " (no permission to fix)"));
-                if (updateIfNeeded) {
-                    appOps.setUidMode(appOp, applicationData.mUid, AppOpsManager.MODE_ALLOWED);
-                } else {
-                    return false;
-                }
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Sets the specified package as the default SMS/MMS application. The caller of this method
-     * needs to have permission to set AppOps and write to secure settings.
-     */
-    @UnsupportedAppUsage
-    public static void setDefaultApplication(String packageName, Context context) {
-        setDefaultApplicationAsUser(packageName, context, getIncomingUserId(context));
-    }
-
-    /**
-     * Same as {@link #setDefaultApplication} but takes a target user id.
-     */
-    public static void setDefaultApplicationAsUser(String packageName, Context context,
-            int userId) {
-        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
-        RoleManager roleManager = (RoleManager) context.getSystemService(Context.ROLE_SERVICE);
-        // (b/134400042) RoleManager might be null in unit tests running older mockito versions
-        // that do not support mocking final classes.
-        if (!tm.isSmsCapable() && (roleManager == null || !roleManager.isRoleAvailable(
-                RoleManager.ROLE_SMS))) {
-            // No phone, no SMS
-            return;
-        }
-
-        final long token = Binder.clearCallingIdentity();
-        try {
-            setDefaultApplicationInternal(packageName, context, userId);
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    private static void setDefaultApplicationInternal(String packageName, Context context,
-            int userId) {
-        final UserHandle userHandle = UserHandle.of(userId);
-
-        // Get old package name
-        String oldPackageName = getDefaultSmsPackage(context, userId);
-
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "setDefaultApplicationInternal old=" + oldPackageName +
-                    " new=" + packageName);
-        }
-
-        if (packageName != null && oldPackageName != null && packageName.equals(oldPackageName)) {
-            // No change
-            return;
-        }
-
-        // We only make the change if the new package is valid
-        PackageManager packageManager = context.getPackageManager();
-        Collection<SmsApplicationData> applications = getApplicationCollectionInternal(
-                context, userId);
-        SmsApplicationData oldAppData = oldPackageName != null ?
-                getApplicationForPackage(applications, oldPackageName) : null;
-        SmsApplicationData applicationData = getApplicationForPackage(applications, packageName);
-        if (applicationData != null) {
-            // Ignore relevant appops for the previously configured default SMS app.
-            AppOpsManager appOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
-            if (oldPackageName != null) {
-                try {
-                    int uid = packageManager.getPackageInfoAsUser(
-                            oldPackageName, 0, userId).applicationInfo.uid;
-                    setExclusiveAppops(oldPackageName, appOps, uid, AppOpsManager.MODE_DEFAULT);
-                } catch (NameNotFoundException e) {
-                    Rlog.w(LOG_TAG, "Old SMS package not found: " + oldPackageName);
-                }
-            }
-
-            // Update the setting.
-            CompletableFuture<Void> future = new CompletableFuture<>();
-            Consumer<Boolean> callback = successful -> {
-                if (successful) {
-                    future.complete(null);
-                } else {
-                    future.completeExceptionally(new RuntimeException());
-                }
-            };
-            context.getSystemService(RoleManager.class).addRoleHolderAsUser(
-                    RoleManager.ROLE_SMS, applicationData.mPackageName, 0, UserHandle.of(userId),
-                    AsyncTask.THREAD_POOL_EXECUTOR, callback);
-            try {
-                future.get(5, TimeUnit.SECONDS);
-            } catch (InterruptedException | ExecutionException | TimeoutException e) {
-                Log.e(LOG_TAG, "Exception while adding sms role holder " + applicationData, e);
-                return;
-            }
-
-            defaultSmsAppChanged(context);
-        }
-    }
-
-    /**
-     * Sends broadcasts on sms app change:
-     * {@link Intent#ACTION_DEFAULT_SMS_PACKAGE_CHANGED}
-     * {@link Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED_INTERNAL}
-     */
-    public static void broadcastSmsAppChange(Context context,
-            UserHandle userHandle, @Nullable String oldPackage, @Nullable String newPackage) {
-        Collection<SmsApplicationData> apps = getApplicationCollection(context);
-
-        broadcastSmsAppChange(context, userHandle,
-                getApplicationForPackage(apps, oldPackage),
-                getApplicationForPackage(apps, newPackage));
-    }
-
-    private static void broadcastSmsAppChange(Context context, UserHandle userHandle,
-            @Nullable SmsApplicationData oldAppData,
-            @Nullable SmsApplicationData applicationData) {
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "setDefaultApplicationInternal oldAppData=" + oldAppData);
-        }
-        if (oldAppData != null && oldAppData.mSmsAppChangedReceiverClass != null) {
-            // Notify the old sms app that it's no longer the default
-            final Intent oldAppIntent =
-                    new Intent(Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED);
-            final ComponentName component = new ComponentName(oldAppData.mPackageName,
-                    oldAppData.mSmsAppChangedReceiverClass);
-            oldAppIntent.setComponent(component);
-            oldAppIntent.putExtra(Intents.EXTRA_IS_DEFAULT_SMS_APP, false);
-            if (DEBUG_MULTIUSER) {
-                Log.i(LOG_TAG, "setDefaultApplicationInternal old=" + oldAppData.mPackageName);
-            }
-            context.sendBroadcastAsUser(oldAppIntent, userHandle);
-        }
-        // Notify the new sms app that it's now the default (if the new sms app has a receiver
-        // to handle the changed default sms intent).
-        if (DEBUG_MULTIUSER) {
-            Log.i(LOG_TAG, "setDefaultApplicationInternal new applicationData=" +
-                    applicationData);
-        }
-        if (applicationData != null && applicationData.mSmsAppChangedReceiverClass != null) {
-            final Intent intent =
-                    new Intent(Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED);
-            final ComponentName component = new ComponentName(applicationData.mPackageName,
-                    applicationData.mSmsAppChangedReceiverClass);
-            intent.setComponent(component);
-            intent.putExtra(Intents.EXTRA_IS_DEFAULT_SMS_APP, true);
-            if (DEBUG_MULTIUSER) {
-                Log.i(LOG_TAG, "setDefaultApplicationInternal new=" + applicationData.mPackageName);
-            }
-            context.sendBroadcastAsUser(intent, userHandle);
-        }
-
-        // Send an implicit broadcast for the system server.
-        // (or anyone with MONITOR_DEFAULT_SMS_PACKAGE, really.)
-        final Intent intent =
-                new Intent(Intents.ACTION_DEFAULT_SMS_PACKAGE_CHANGED_INTERNAL);
-        context.sendBroadcastAsUser(intent, userHandle,
-                permission.MONITOR_DEFAULT_SMS_PACKAGE);
-
-        if (applicationData != null) {
-            MetricsLogger.action(context, MetricsEvent.ACTION_DEFAULT_SMS_APP_CHANGED,
-                    applicationData.mPackageName);
-        }
-    }
-
-    /**
-     * Assign WRITE_SMS AppOps permission to some special system apps.
-     *
-     * @param context The context
-     * @param packageManager The package manager instance
-     * @param appOps The AppOps manager instance
-     * @param packageName The package name of the system app
-     */
-    private static void assignExclusiveSmsPermissionsToSystemApp(Context context,
-            PackageManager packageManager, AppOpsManager appOps, String packageName) {
-        // First check package signature matches the caller's package signature.
-        // Since this class is only used internally by the system, this check makes sure
-        // the package signature matches system signature.
-        final int result = packageManager.checkSignatures(context.getPackageName(), packageName);
-        if (result != PackageManager.SIGNATURE_MATCH) {
-            Rlog.e(LOG_TAG, packageName + " does not have system signature");
-            return;
-        }
-        try {
-            PackageInfo info = packageManager.getPackageInfo(packageName, 0);
-            int mode = appOps.checkOp(AppOpsManager.OP_WRITE_SMS, info.applicationInfo.uid,
-                    packageName);
-            if (mode != AppOpsManager.MODE_ALLOWED) {
-                Rlog.w(LOG_TAG, packageName + " does not have OP_WRITE_SMS:  (fixing)");
-                setExclusiveAppops(packageName, appOps, info.applicationInfo.uid,
-                        AppOpsManager.MODE_ALLOWED);
-            }
-        } catch (NameNotFoundException e) {
-            // No whitelisted system app on this device
-            Rlog.e(LOG_TAG, "Package not found: " + packageName);
-        }
-
-    }
-
-    private static void setExclusiveAppops(String pkg, AppOpsManager appOpsManager, int uid,
-            int mode) {
-        for (int appop : DEFAULT_APP_EXCLUSIVE_APPOPS) {
-            appOpsManager.setUidMode(appop, uid, mode);
-        }
-    }
-
-    /**
-     * Tracks package changes and ensures that the default SMS app is always configured to be the
-     * preferred activity for SENDTO sms/mms intents.
-     */
-    private static final class SmsPackageMonitor extends PackageMonitor {
-        final Context mContext;
-
-        public SmsPackageMonitor(Context context) {
-            super();
-            mContext = context;
-        }
-
-        @Override
-        public void onPackageDisappeared(String packageName, int reason) {
-            onPackageChanged();
-        }
-
-        @Override
-        public void onPackageAppeared(String packageName, int reason) {
-            onPackageChanged();
-        }
-
-        @Override
-        public void onPackageModified(String packageName) {
-            onPackageChanged();
-        }
-
-        private void onPackageChanged() {
-            PackageManager packageManager = mContext.getPackageManager();
-            Context userContext = mContext;
-            final int userId = getSendingUserId();
-            if (userId != UserHandle.USER_SYSTEM) {
-                try {
-                    userContext = mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
-                        UserHandle.of(userId));
-                } catch (NameNotFoundException nnfe) {
-                    if (DEBUG_MULTIUSER) {
-                        Log.w(LOG_TAG, "Unable to create package context for user " + userId);
-                    }
-                }
-            }
-            // Ensure this component is still configured as the preferred activity
-            ComponentName componentName = getDefaultSendToApplication(userContext, true);
-            if (componentName != null) {
-                configurePreferredActivity(packageManager, componentName, userId);
-            }
-        }
-    }
-
-    public static void initSmsPackageMonitor(Context context) {
-        sSmsPackageMonitor = new SmsPackageMonitor(context);
-        sSmsPackageMonitor.register(context, context.getMainLooper(), UserHandle.ALL, false);
-    }
-
-    @UnsupportedAppUsage
-    private static void configurePreferredActivity(PackageManager packageManager,
-            ComponentName componentName, int userId) {
-        // Add the four activity preferences we want to direct to this app.
-        replacePreferredActivity(packageManager, componentName, userId, SCHEME_SMS);
-        replacePreferredActivity(packageManager, componentName, userId, SCHEME_SMSTO);
-        replacePreferredActivity(packageManager, componentName, userId, SCHEME_MMS);
-        replacePreferredActivity(packageManager, componentName, userId, SCHEME_MMSTO);
-    }
-
-    /**
-     * Updates the ACTION_SENDTO activity to the specified component for the specified scheme.
-     */
-    private static void replacePreferredActivity(PackageManager packageManager,
-            ComponentName componentName, int userId, String scheme) {
-        // Build the set of existing activities that handle this scheme
-        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(scheme, "", null));
-        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivitiesAsUser(
-                intent, PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER,
-                userId);
-
-        // Build the set of ComponentNames for these activities
-        final int n = resolveInfoList.size();
-        ComponentName[] set = new ComponentName[n];
-        for (int i = 0; i < n; i++) {
-            ResolveInfo info = resolveInfoList.get(i);
-            set[i] = new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
-        }
-
-        // Update the preferred SENDTO activity for the specified scheme
-        IntentFilter intentFilter = new IntentFilter();
-        intentFilter.addAction(Intent.ACTION_SENDTO);
-        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
-        intentFilter.addDataScheme(scheme);
-        packageManager.replacePreferredActivityAsUser(intentFilter,
-                IntentFilter.MATCH_CATEGORY_SCHEME + IntentFilter.MATCH_ADJUSTMENT_NORMAL,
-                set, componentName, userId);
-    }
-
-    /**
-     * Returns SmsApplicationData for this package if this package is capable of being set as the
-     * default SMS application.
-     */
-    @UnsupportedAppUsage
-    public static SmsApplicationData getSmsApplicationData(String packageName, Context context) {
-        Collection<SmsApplicationData> applications = getApplicationCollection(context);
-        return getApplicationForPackage(applications, packageName);
-    }
-
-    /**
-     * Gets the default SMS application
-     * @param context context from the calling app
-     * @param updateIfNeeded update the default app if there is no valid default app configured.
-     * @return component name of the app and class to deliver SMS messages to
-     */
-    @UnsupportedAppUsage
-    public static ComponentName getDefaultSmsApplication(Context context, boolean updateIfNeeded) {
-        return getDefaultSmsApplicationAsUser(context, updateIfNeeded, getIncomingUserId(context));
-    }
-
-    /**
-     * Gets the default SMS application on a given user
-     * @param context context from the calling app
-     * @param updateIfNeeded update the default app if there is no valid default app configured.
-     * @param userId target user ID.
-     * @return component name of the app and class to deliver SMS messages to
-     */
-    public static ComponentName getDefaultSmsApplicationAsUser(Context context,
-            boolean updateIfNeeded, int userId) {
-        final long token = Binder.clearCallingIdentity();
-        try {
-            ComponentName component = null;
-            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
-                    userId);
-            if (smsApplicationData != null) {
-                component = new ComponentName(smsApplicationData.mPackageName,
-                        smsApplicationData.mSmsReceiverClass);
-            }
-            return component;
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    /**
-     * Gets the default MMS application
-     * @param context context from the calling app
-     * @param updateIfNeeded update the default app if there is no valid default app configured.
-     * @return component name of the app and class to deliver MMS messages to
-     */
-    @UnsupportedAppUsage
-    public static ComponentName getDefaultMmsApplication(Context context, boolean updateIfNeeded) {
-        int userId = getIncomingUserId(context);
-        final long token = Binder.clearCallingIdentity();
-        try {
-            ComponentName component = null;
-            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
-                    userId);
-            if (smsApplicationData != null) {
-                component = new ComponentName(smsApplicationData.mPackageName,
-                        smsApplicationData.mMmsReceiverClass);
-            }
-            return component;
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    /**
-     * Gets the default Respond Via Message application
-     * @param context context from the calling app
-     * @param updateIfNeeded update the default app if there is no valid default app configured.
-     * @return component name of the app and class to direct Respond Via Message intent to
-     */
-    @UnsupportedAppUsage
-    public static ComponentName getDefaultRespondViaMessageApplication(Context context,
-            boolean updateIfNeeded) {
-        int userId = getIncomingUserId(context);
-        final long token = Binder.clearCallingIdentity();
-        try {
-            ComponentName component = null;
-            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
-                    userId);
-            if (smsApplicationData != null) {
-                component = new ComponentName(smsApplicationData.mPackageName,
-                        smsApplicationData.mRespondViaMessageClass);
-            }
-            return component;
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    /**
-     * Gets the default Send To (smsto) application.
-     * <p>
-     * Caller must pass in the correct user context if calling from a singleton service.
-     * @param context context from the calling app
-     * @param updateIfNeeded update the default app if there is no valid default app configured.
-     * @return component name of the app and class to direct SEND_TO (smsto) intent to
-     */
-    public static ComponentName getDefaultSendToApplication(Context context,
-            boolean updateIfNeeded) {
-        int userId = getIncomingUserId(context);
-        final long token = Binder.clearCallingIdentity();
-        try {
-            ComponentName component = null;
-            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
-                    userId);
-            if (smsApplicationData != null) {
-                component = new ComponentName(smsApplicationData.mPackageName,
-                        smsApplicationData.mSendToClass);
-            }
-            return component;
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    /**
-     * Gets the default application that handles external changes to the SmsProvider and
-     * MmsProvider.
-     * @param context context from the calling app
-     * @param updateIfNeeded update the default app if there is no valid default app configured.
-     * @return component name of the app and class to deliver change intents to
-     */
-    public static ComponentName getDefaultExternalTelephonyProviderChangedApplication(
-            Context context, boolean updateIfNeeded) {
-        int userId = getIncomingUserId(context);
-        final long token = Binder.clearCallingIdentity();
-        try {
-            ComponentName component = null;
-            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
-                    userId);
-            if (smsApplicationData != null
-                    && smsApplicationData.mProviderChangedReceiverClass != null) {
-                component = new ComponentName(smsApplicationData.mPackageName,
-                        smsApplicationData.mProviderChangedReceiverClass);
-            }
-            return component;
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    /**
-     * Gets the default application that handles sim full event.
-     * @param context context from the calling app
-     * @param updateIfNeeded update the default app if there is no valid default app configured.
-     * @return component name of the app and class to deliver change intents to
-     */
-    public static ComponentName getDefaultSimFullApplication(
-            Context context, boolean updateIfNeeded) {
-        int userId = getIncomingUserId(context);
-        final long token = Binder.clearCallingIdentity();
-        try {
-            ComponentName component = null;
-            SmsApplicationData smsApplicationData = getApplication(context, updateIfNeeded,
-                    userId);
-            if (smsApplicationData != null
-                    && smsApplicationData.mSimFullReceiverClass != null) {
-                component = new ComponentName(smsApplicationData.mPackageName,
-                        smsApplicationData.mSimFullReceiverClass);
-            }
-            return component;
-        } finally {
-            Binder.restoreCallingIdentity(token);
-        }
-    }
-
-    /**
-     * Returns whether need to write the SMS message to SMS database for this package.
-     * <p>
-     * Caller must pass in the correct user context if calling from a singleton service.
-     */
-    @UnsupportedAppUsage
-    public static boolean shouldWriteMessageForPackage(String packageName, Context context) {
-        if (SmsManager.getDefault().getAutoPersisting()) {
-            return true;
-        }
-        return !isDefaultSmsApplication(context, packageName);
-    }
-
-    /**
-     * Check if a package is default sms app (or equivalent, like bluetooth)
-     *
-     * @param context context from the calling app
-     * @param packageName the name of the package to be checked
-     * @return true if the package is default sms app or bluetooth
-     */
-    @UnsupportedAppUsage
-    public static boolean isDefaultSmsApplication(Context context, String packageName) {
-        if (packageName == null) {
-            return false;
-        }
-        final String defaultSmsPackage = getDefaultSmsApplicationPackageName(context);
-        if ((defaultSmsPackage != null && defaultSmsPackage.equals(packageName))
-                || BLUETOOTH_PACKAGE_NAME.equals(packageName)) {
-            return true;
-        }
-        return false;
-    }
-
-    private static String getDefaultSmsApplicationPackageName(Context context) {
-        final ComponentName component = getDefaultSmsApplication(context, false);
-        if (component != null) {
-            return component.getPackageName();
-        }
-        return null;
-    }
-}
diff --git a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
index d892e55..4654437 100644
--- a/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/cdma/SmsMessage.java
@@ -878,8 +878,9 @@
      * Parses a broadcast SMS, possibly containing a CMAS alert.
      *
      * @param plmn the PLMN for a broadcast SMS
+     * @param subId
      */
-    public SmsCbMessage parseBroadcastSms(String plmn) {
+    public SmsCbMessage parseBroadcastSms(String plmn, int subId) {
         BearerData bData = BearerData.decode(mEnvelope.bearerData, mEnvelope.serviceCategory);
         if (bData == null) {
             Rlog.w(LOG_TAG, "BearerData.decode() returned null");
@@ -895,7 +896,7 @@
         return new SmsCbMessage(SmsCbMessage.MESSAGE_FORMAT_3GPP2,
                 SmsCbMessage.GEOGRAPHICAL_SCOPE_PLMN_WIDE, bData.messageId, location,
                 mEnvelope.serviceCategory, bData.getLanguage(), bData.userData.payloadStr,
-                bData.priority, null, bData.cmasWarningInfo);
+                bData.priority, null, bData.cmasWarningInfo, subId);
     }
 
     /**
diff --git a/telephony/java/com/android/internal/telephony/cdma/sms/SmsEnvelope.java b/telephony/java/com/android/internal/telephony/cdma/sms/SmsEnvelope.java
index 3440c65..2787b24 100644
--- a/telephony/java/com/android/internal/telephony/cdma/sms/SmsEnvelope.java
+++ b/telephony/java/com/android/internal/telephony/cdma/sms/SmsEnvelope.java
@@ -18,6 +18,7 @@
 
 
 import android.annotation.UnsupportedAppUsage;
+import android.telephony.cdma.CdmaSmsCbProgramData;
 
 public final class SmsEnvelope {
     /**
@@ -55,12 +56,18 @@
     //...
 
     // CMAS alert service category assignments, see 3GPP2 C.R1001 table 9.3.3-1
-    public static final int SERVICE_CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT  = 0x1000;
-    public static final int SERVICE_CATEGORY_CMAS_EXTREME_THREAT            = 0x1001;
-    public static final int SERVICE_CATEGORY_CMAS_SEVERE_THREAT             = 0x1002;
-    public static final int SERVICE_CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY = 0x1003;
-    public static final int SERVICE_CATEGORY_CMAS_TEST_MESSAGE              = 0x1004;
-    public static final int SERVICE_CATEGORY_CMAS_LAST_RESERVED_VALUE       = 0x10ff;
+    public static final int SERVICE_CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT  =
+            CdmaSmsCbProgramData.CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT;
+    public static final int SERVICE_CATEGORY_CMAS_EXTREME_THREAT            =
+            CdmaSmsCbProgramData.CATEGORY_CMAS_EXTREME_THREAT;
+    public static final int SERVICE_CATEGORY_CMAS_SEVERE_THREAT             =
+            CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT;
+    public static final int SERVICE_CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY =
+            CdmaSmsCbProgramData.CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY;
+    public static final int SERVICE_CATEGORY_CMAS_TEST_MESSAGE              =
+            CdmaSmsCbProgramData.CATEGORY_CMAS_TEST_MESSAGE;
+    public static final int SERVICE_CATEGORY_CMAS_LAST_RESERVED_VALUE       =
+            CdmaSmsCbProgramData.CATEGORY_CMAS_LAST_RESERVED_VALUE;
 
     /**
      * Provides the type of a SMS message like point to point, broadcast or acknowledge
diff --git a/telephony/java/com/android/internal/telephony/euicc/IEuiccController.aidl b/telephony/java/com/android/internal/telephony/euicc/IEuiccController.aidl
index 2016915..7422863 100644
--- a/telephony/java/com/android/internal/telephony/euicc/IEuiccController.aidl
+++ b/telephony/java/com/android/internal/telephony/euicc/IEuiccController.aidl
@@ -44,5 +44,7 @@
     oneway void updateSubscriptionNickname(int cardId, int subscriptionId, String nickname,
         String callingPackage, in PendingIntent callbackIntent);
     oneway void eraseSubscriptions(int cardId, in PendingIntent callbackIntent);
+    oneway void eraseSubscriptionsWithOptions(
+        int cardId, int options, in PendingIntent callbackIntent);
     oneway void retainSubscriptionsForFactoryReset(int cardId, in PendingIntent callbackIntent);
 }
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java b/telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java
index 6eea118..c3d490a 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmSmsCbMessage.java
@@ -90,9 +90,10 @@
      * Create a new SmsCbMessage object from a header object plus one or more received PDUs.
      *
      * @param pdus PDU bytes
+     * @slotIndex slotIndex for which received sms cb message
      */
     public static SmsCbMessage createSmsCbMessage(Context context, SmsCbHeader header,
-            SmsCbLocation location, byte[][] pdus)
+            SmsCbLocation location, byte[][] pdus, int slotIndex)
             throws IllegalArgumentException {
         long receivedTimeMillis = System.currentTimeMillis();
         if (header.isEtwsPrimaryNotification()) {
@@ -104,7 +105,7 @@
                     header.getSerialNumber(), location, header.getServiceCategory(), null,
                     getEtwsPrimaryMessage(context, header.getEtwsInfo().getWarningType()),
                     SmsCbMessage.MESSAGE_PRIORITY_EMERGENCY, header.getEtwsInfo(),
-                    header.getCmasInfo(), 0, null /* geometries */, receivedTimeMillis);
+                    header.getCmasInfo(), 0, null /* geometries */, receivedTimeMillis, slotIndex);
         } else if (header.isUmtsFormat()) {
             // UMTS format has only 1 PDU
             byte[] pdu = pdus[0];
@@ -138,7 +139,7 @@
                     header.getGeographicalScope(), header.getSerialNumber(), location,
                     header.getServiceCategory(), language, body, priority,
                     header.getEtwsInfo(), header.getCmasInfo(), maximumWaitingTimeSec, geometries,
-                    receivedTimeMillis);
+                    receivedTimeMillis, slotIndex);
         } else {
             String language = null;
             StringBuilder sb = new StringBuilder();
@@ -154,7 +155,7 @@
                     header.getGeographicalScope(), header.getSerialNumber(), location,
                     header.getServiceCategory(), language, sb.toString(), priority,
                     header.getEtwsInfo(), header.getCmasInfo(), 0, null /* geometries */,
-                    receivedTimeMillis);
+                    receivedTimeMillis, slotIndex);
         }
     }
 
@@ -461,7 +462,11 @@
         }
     }
 
-    static final class GeoFencingTriggerMessage {
+    /**
+     * Part of a GSM SMS cell broadcast message which may trigger geo-fencing logic.
+     * @hide
+     */
+    public static final class GeoFencingTriggerMessage {
         /**
          * Indicate the list of active alerts share their warning area coordinates which means the
          * broadcast area is the union of the broadcast areas of the active alerts in this list.
@@ -476,6 +481,11 @@
             this.cbIdentifiers = cbIdentifiers;
         }
 
+        /**
+         * Whether the trigger message indicates that the broadcast areas are shared between all
+         * active alerts.
+         * @return true if broadcast areas are to be shared
+         */
         boolean shouldShareBroadcastArea() {
             return type == TYPE_ACTIVE_ALERT_SHARE_WAC;
         }
diff --git a/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java b/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java
index 6bbff4b..cbe5211 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SmsCbHeader.java
@@ -74,22 +74,22 @@
     /**
      * Length of SMS-CB header
      */
-    static final int PDU_HEADER_LENGTH = 6;
+    public static final int PDU_HEADER_LENGTH = 6;
 
     /**
      * GSM pdu format, as defined in 3gpp TS 23.041, section 9.4.1
      */
-    static final int FORMAT_GSM = 1;
+    public static final int FORMAT_GSM = 1;
 
     /**
      * UMTS pdu format, as defined in 3gpp TS 23.041, section 9.4.2
      */
-    static final int FORMAT_UMTS = 2;
+    public static final int FORMAT_UMTS = 2;
 
     /**
-     * GSM pdu format, as defined in 3gpp TS 23.041, section 9.4.1.3
+     * ETWS pdu format, as defined in 3gpp TS 23.041, section 9.4.1.3
      */
-    static final int FORMAT_ETWS_PRIMARY = 3;
+    public static final int FORMAT_ETWS_PRIMARY = 3;
 
     /**
      * Message type value as defined in 3gpp TS 25.324, section 11.1.
@@ -230,43 +230,43 @@
     }
 
     @UnsupportedAppUsage
-    int getGeographicalScope() {
+    public int getGeographicalScope() {
         return mGeographicalScope;
     }
 
     @UnsupportedAppUsage
-    int getSerialNumber() {
+    public int getSerialNumber() {
         return mSerialNumber;
     }
 
     @UnsupportedAppUsage
-    int getServiceCategory() {
+    public int getServiceCategory() {
         return mMessageIdentifier;
     }
 
-    int getDataCodingScheme() {
+    public int getDataCodingScheme() {
         return mDataCodingScheme;
     }
 
-    DataCodingScheme getDataCodingSchemeStructedData() {
+    public DataCodingScheme getDataCodingSchemeStructedData() {
         return mDataCodingSchemeStructedData;
     }
 
     @UnsupportedAppUsage
-    int getPageIndex() {
+    public int getPageIndex() {
         return mPageIndex;
     }
 
     @UnsupportedAppUsage
-    int getNumberOfPages() {
+    public int getNumberOfPages() {
         return mNrOfPages;
     }
 
-    SmsCbEtwsInfo getEtwsInfo() {
+    public SmsCbEtwsInfo getEtwsInfo() {
         return mEtwsInfo;
     }
 
-    SmsCbCmasInfo getCmasInfo() {
+    public SmsCbCmasInfo getCmasInfo() {
         return mCmasInfo;
     }
 
@@ -274,7 +274,7 @@
      * Return whether this broadcast is an emergency (PWS) message type.
      * @return true if this message is emergency type; false otherwise
      */
-    boolean isEmergencyMessage() {
+    public boolean isEmergencyMessage() {
         return mMessageIdentifier >= SmsCbConstants.MESSAGE_ID_PWS_FIRST_IDENTIFIER
                 && mMessageIdentifier <= SmsCbConstants.MESSAGE_ID_PWS_LAST_IDENTIFIER;
     }
@@ -292,7 +292,7 @@
      * Return whether this broadcast is an ETWS primary notification.
      * @return true if this message is an ETWS primary notification; false otherwise
      */
-    boolean isEtwsPrimaryNotification() {
+    public boolean isEtwsPrimaryNotification() {
         return mFormat == FORMAT_ETWS_PRIMARY;
     }
 
@@ -300,7 +300,7 @@
      * Return whether this broadcast is in UMTS format.
      * @return true if this message is in UMTS format; false otherwise
      */
-    boolean isUmtsFormat() {
+    public boolean isUmtsFormat() {
         return mFormat == FORMAT_UMTS;
     }
 
diff --git a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
index 28b331b..da32c8c 100644
--- a/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
+++ b/telephony/java/com/android/internal/telephony/gsm/SmsMessage.java
@@ -1496,7 +1496,7 @@
      *
      * @return true if this is a USIM data download message; false otherwise
      */
-    public boolean isUsimDataDownload() {
+    boolean isUsimDataDownload() {
         return messageClass == MessageClass.CLASS_2 &&
                 (mProtocolIdentifier == 0x7f || mProtocolIdentifier == 0x7c);
     }
diff --git a/telephony/java/com/android/internal/telephony/uicc/IccUtils.java b/telephony/java/com/android/internal/telephony/uicc/IccUtils.java
index 9c69e2d..f2d4624 100644
--- a/telephony/java/com/android/internal/telephony/uicc/IccUtils.java
+++ b/telephony/java/com/android/internal/telephony/uicc/IccUtils.java
@@ -22,11 +22,13 @@
 import android.graphics.Color;
 import android.telephony.Rlog;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.telephony.GsmAlphabet;
 
 import dalvik.annotation.compat.UnsupportedAppUsage;
 
 import java.io.UnsupportedEncodingException;
+import java.util.List;
 
 /**
  * Various methods, useful for dealing with SIM data.
@@ -34,6 +36,11 @@
 public class IccUtils {
     static final String LOG_TAG="IccUtils";
 
+    // 3GPP specification constants
+    // Spec reference TS 31.102 section 4.2.16
+    @VisibleForTesting
+    static final int FPLMN_BYTE_SIZE = 3;
+
     // A table mapping from a number to a hex character for fast encoding hex strings.
     private static final char[] HEX_CHARS = {
             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
@@ -896,4 +903,27 @@
         }
         return 0;
     }
+
+    /**
+     * Encode the Fplmns into byte array to write to EF.
+     *
+     * @param fplmns Array of fplmns to be serialized.
+     * @param dataLength the size of the EF file.
+     * @return the encoded byte array in the correct format for FPLMN file.
+     */
+    public static byte[] encodeFplmns(List<String> fplmns, int dataLength) {
+        byte[] serializedFplmns = new byte[dataLength];
+        int offset = 0;
+        for (String fplmn : fplmns) {
+            if (offset >= dataLength) break;
+            stringToBcdPlmn(fplmn, serializedFplmns, offset);
+            offset += FPLMN_BYTE_SIZE;
+        }
+        //pads to the length of the EF file.
+        while (offset < dataLength) {
+            // required by 3GPP TS 31.102 spec 4.2.16
+            serializedFplmns[offset++] = (byte) 0xff;
+        }
+        return serializedFplmns;
+    }
 }
diff --git a/test-mock/Android.bp b/test-mock/Android.bp
index adc9e22..81b1e49 100644
--- a/test-mock/Android.bp
+++ b/test-mock/Android.bp
@@ -19,10 +19,9 @@
 java_sdk_library {
     name: "android.test.mock",
 
-    srcs: [
-        "src/**/*.java",
-        ":framework-all-sources",
-    ],
+    srcs: ["src/**/*.java"],
+    api_srcs: [":framework-all-sources"],
+    libs: ["framework-all"],
 
     api_packages: [
         "android.test.mock",
diff --git a/tests/ApkVerityTest/Android.bp b/tests/ApkVerityTest/Android.bp
new file mode 100644
index 0000000..adcbb428
--- /dev/null
+++ b/tests/ApkVerityTest/Android.bp
@@ -0,0 +1,34 @@
+// Copyright (C) 2019 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.
+
+java_test_host {
+    name: "ApkVerityTests",
+    srcs: ["src/**/*.java"],
+    libs: ["tradefed", "compatibility-tradefed", "compatibility-host-util"],
+    test_suites: ["general-tests"],
+    target_required: [
+        "block_device_writer_module",
+        "ApkVerityTestApp",
+        "ApkVerityTestAppSplit",
+    ],
+    data: [
+        ":ApkVerityTestCertDer",
+        ":ApkVerityTestAppFsvSig",
+        ":ApkVerityTestAppDm",
+        ":ApkVerityTestAppDmFsvSig",
+        ":ApkVerityTestAppSplitFsvSig",
+        ":ApkVerityTestAppSplitDm",
+        ":ApkVerityTestAppSplitDmFsvSig",
+    ],
+}
diff --git a/tests/ApkVerityTest/AndroidTest.xml b/tests/ApkVerityTest/AndroidTest.xml
new file mode 100644
index 0000000..73779cb
--- /dev/null
+++ b/tests/ApkVerityTest/AndroidTest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<configuration description="APK fs-verity integration/regression test">
+    <option name="test-suite-tag" value="apct" />
+
+    <!-- This test requires root to write against block device. -->
+    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer" />
+
+    <target_preparer class="com.android.tradefed.targetprep.DeviceSetup">
+        <!-- Disable package verifier prevents it holding the target APK's fd that prevents cache
+             eviction. -->
+        <option name="set-global-setting" key="package_verifier_enable" value="0" />
+        <option name="restore-settings" value="true" />
+
+        <!-- Skip in order to prevent reboot that confuses the test flow. -->
+        <option name="force-skip-system-props" value="true" />
+    </target_preparer>
+
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="block_device_writer->/data/local/tmp/block_device_writer" />
+        <option name="push" value="ApkVerityTestCert.der->/data/local/tmp/ApkVerityTestCert.der" />
+    </target_preparer>
+
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="ApkVerityTests.jar" />
+    </test>
+</configuration>
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/Android.bp b/tests/ApkVerityTest/ApkVerityTestApp/Android.bp
new file mode 100644
index 0000000..69632b2
--- /dev/null
+++ b/tests/ApkVerityTest/ApkVerityTestApp/Android.bp
@@ -0,0 +1,29 @@
+// Copyright (C) 2019 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.
+
+android_test_helper_app {
+  name: "ApkVerityTestApp",
+  manifest: "AndroidManifest.xml",
+  srcs: ["src/**/*.java"],
+}
+
+android_test_helper_app {
+  name: "ApkVerityTestAppSplit",
+  manifest: "feature_split/AndroidManifest.xml",
+  srcs: ["src/**/*.java"],
+  aaptflags: [
+      "--custom-package com.android.apkverity.feature_x",
+      "--package-id 0x80",
+  ],
+}
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/AndroidManifest.xml b/tests/ApkVerityTest/ApkVerityTestApp/AndroidManifest.xml
new file mode 100644
index 0000000..0b3ff77
--- /dev/null
+++ b/tests/ApkVerityTest/ApkVerityTestApp/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.apkverity">
+    <application>
+        <activity android:name=".DummyActivity"/>
+    </application>
+</manifest>
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/feature_split/AndroidManifest.xml b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/AndroidManifest.xml
new file mode 100644
index 0000000..3f1a4f3
--- /dev/null
+++ b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.apkverity"
+    android:isFeatureSplit="true"
+    split="feature_x">
+    <application>
+        <activity android:name=".feature_x.DummyActivity"/>
+    </application>
+</manifest>
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java
new file mode 100644
index 0000000..0f694c2
--- /dev/null
+++ b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2019 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.apkverity.feature_x;
+
+import android.app.Activity;
+
+/** Dummy class just to generate some dex */
+public class DummyActivity extends Activity {}
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java b/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java
new file mode 100644
index 0000000..837c7be
--- /dev/null
+++ b/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2019 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.apkverity;
+
+import android.app.Activity;
+
+/** Dummy class just to generate some dex */
+public class DummyActivity extends Activity {}
diff --git a/tests/ApkVerityTest/block_device_writer/Android.bp b/tests/ApkVerityTest/block_device_writer/Android.bp
new file mode 100644
index 0000000..deed3a0
--- /dev/null
+++ b/tests/ApkVerityTest/block_device_writer/Android.bp
@@ -0,0 +1,30 @@
+// Copyright (C) 2019 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.
+
+// This is a cc_test just because it supports test_suites. This should be converted to something
+// like cc_binary_test_helper once supported.
+cc_test {
+    // Depending on how the test runs, the executable may be uploaded to different location.
+    // Before the bug in the file pusher is fixed, workaround by making the name unique.
+    // See b/124718249#comment12.
+    name: "block_device_writer_module",
+    stem: "block_device_writer",
+
+    srcs: ["block_device_writer.cpp"],
+    cflags: ["-Wall", "-Werror", "-Wextra", "-g"],
+    shared_libs: ["libbase", "libutils"],
+
+    test_suites: ["general-tests"],
+    gtest: false,
+}
diff --git a/tests/ApkVerityTest/block_device_writer/block_device_writer.cpp b/tests/ApkVerityTest/block_device_writer/block_device_writer.cpp
new file mode 100644
index 0000000..b0c7251
--- /dev/null
+++ b/tests/ApkVerityTest/block_device_writer/block_device_writer.cpp
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/fiemap.h>
+#include <linux/fs.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/unique_fd.h>
+
+// This program modifies a file at given offset, but directly against the block
+// device, purposely to bypass the filesystem. Note that the change on block
+// device may not reflect the same way when read from filesystem, for example,
+// when the file is encrypted on disk.
+//
+// Only one byte is supported for now just so that we don't need to handle the
+// case when the range crosses different "extents".
+//
+// References:
+//  https://www.kernel.org/doc/Documentation/filesystems/fiemap.txt
+//  https://git.kernel.org/pub/scm/fs/xfs/xfsprogs-dev.git/tree/io/fiemap.c
+
+ssize_t get_logical_block_size(const char* block_device) {
+  android::base::unique_fd fd(open(block_device, O_RDONLY));
+  if (fd.get() < 0) {
+    fprintf(stderr, "open %s failed\n", block_device);
+    return -1;
+  }
+
+  int size;
+  if (ioctl(fd, BLKSSZGET, &size) < 0) {
+    fprintf(stderr, "ioctl(BLKSSZGET) failed: %s\n", strerror(errno));
+    return -1;
+  }
+  return size;
+}
+
+int64_t get_physical_offset(const char* file_name, uint64_t byte_offset) {
+  android::base::unique_fd fd(open(file_name, O_RDONLY));
+  if (fd.get() < 0) {
+    fprintf(stderr, "open %s failed\n", file_name);
+    return -1;
+  }
+
+  const int map_size = sizeof(struct fiemap) + sizeof(struct fiemap_extent);
+  char fiemap_buffer[map_size] = {0};
+  struct fiemap* fiemap = reinterpret_cast<struct fiemap*>(&fiemap_buffer);
+
+  fiemap->fm_flags = FIEMAP_FLAG_SYNC;
+  fiemap->fm_start = byte_offset;
+  fiemap->fm_length = 1;
+  fiemap->fm_extent_count = 1;
+
+  int ret = ioctl(fd.get(), FS_IOC_FIEMAP, fiemap);
+  if (ret < 0) {
+    fprintf(stderr, "ioctl(FS_IOC_FIEMAP) failed: %s\n", strerror(errno));
+    return -1;
+  }
+
+  if (fiemap->fm_mapped_extents != 1) {
+    fprintf(stderr, "fm_mapped_extents != 1 (is %d)\n",
+            fiemap->fm_mapped_extents);
+    return -1;
+  }
+
+  struct fiemap_extent* extent = &fiemap->fm_extents[0];
+  printf(
+      "logical offset: %llu, physical offset: %llu, length: %llu, "
+      "flags: %x\n",
+      extent->fe_logical, extent->fe_physical, extent->fe_length,
+      extent->fe_flags);
+  if (extent->fe_flags & (FIEMAP_EXTENT_UNKNOWN |
+                          FIEMAP_EXTENT_UNWRITTEN)) {
+    fprintf(stderr, "Failed to locate physical offset safely\n");
+    return -1;
+  }
+
+  return extent->fe_physical + (byte_offset - extent->fe_logical);
+}
+
+int read_block_from_device(const char* device_path, uint64_t block_offset,
+                           ssize_t block_size, char* block_buffer) {
+  assert(block_offset % block_size == 0);
+  android::base::unique_fd fd(open(device_path, O_RDONLY | O_DIRECT));
+  if (fd.get() < 0) {
+    fprintf(stderr, "open %s failed\n", device_path);
+    return -1;
+  }
+
+  ssize_t retval =
+      TEMP_FAILURE_RETRY(pread(fd, block_buffer, block_size, block_offset));
+  if (retval != block_size) {
+    fprintf(stderr, "read returns error or incomplete result (%zu): %s\n",
+            retval, strerror(errno));
+    return -1;
+  }
+  return 0;
+}
+
+int write_block_to_device(const char* device_path, uint64_t block_offset,
+                          ssize_t block_size, char* block_buffer) {
+  assert(block_offset % block_size == 0);
+  android::base::unique_fd fd(open(device_path, O_WRONLY | O_DIRECT));
+  if (fd.get() < 0) {
+    fprintf(stderr, "open %s failed\n", device_path);
+    return -1;
+  }
+
+  ssize_t retval = TEMP_FAILURE_RETRY(
+      pwrite(fd.get(), block_buffer, block_size, block_offset));
+  if (retval != block_size) {
+    fprintf(stderr, "write returns error or incomplete result (%zu): %s\n",
+            retval, strerror(errno));
+    return -1;
+  }
+  return 0;
+}
+
+int main(int argc, const char** argv) {
+  if (argc != 4) {
+    fprintf(stderr,
+            "Usage: %s block_dev filename byte_offset\n"
+            "\n"
+            "This program bypasses filesystem and damages the specified byte\n"
+            "at the physical position on <block_dev> corresponding to the\n"
+            "logical byte location in <filename>.\n",
+            argv[0]);
+    return -1;
+  }
+
+  const char* block_device = argv[1];
+  const char* file_name = argv[2];
+  uint64_t byte_offset = strtoull(argv[3], nullptr, 10);
+
+  ssize_t block_size = get_logical_block_size(block_device);
+  if (block_size < 0) {
+    return -1;
+  }
+
+  int64_t physical_offset_signed = get_physical_offset(file_name, byte_offset);
+  if (physical_offset_signed < 0) {
+    return -1;
+  }
+
+  uint64_t physical_offset = static_cast<uint64_t>(physical_offset_signed);
+  uint64_t offset_within_block = physical_offset % block_size;
+  uint64_t physical_block_offset = physical_offset - offset_within_block;
+
+  // Direct I/O requires aligned buffer
+  std::unique_ptr<char> buf(static_cast<char*>(
+      aligned_alloc(block_size /* alignment */, block_size /* size */)));
+
+  if (read_block_from_device(block_device, physical_block_offset, block_size,
+                             buf.get()) < 0) {
+    return -1;
+  }
+  char* p = buf.get() + offset_within_block;
+  printf("before: %hhx\n", *p);
+  *p ^= 0xff;
+  printf("after: %hhx\n", *p);
+  if (write_block_to_device(block_device, physical_block_offset, block_size,
+                            buf.get()) < 0) {
+    return -1;
+  }
+
+  return 0;
+}
diff --git a/tests/ApkVerityTest/src/com/android/apkverity/ApkVerityTest.java b/tests/ApkVerityTest/src/com/android/apkverity/ApkVerityTest.java
new file mode 100644
index 0000000..761c5ce
--- /dev/null
+++ b/tests/ApkVerityTest/src/com/android/apkverity/ApkVerityTest.java
@@ -0,0 +1,496 @@
+/*
+ * Copyright (C) 2019 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.apkverity;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import android.platform.test.annotations.RootPermissionTest;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.CommandStatus;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.FileNotFoundException;
+import java.util.Arrays;
+import java.util.HashSet;
+
+/**
+ * This test makes sure app installs with fs-verity signature, and on-access verification works.
+ *
+ * <p>When an app is installed, all or none of the files should have their corresponding .fsv_sig
+ * signature file. Otherwise, install will fail.
+ *
+ * <p>Once installed, file protected by fs-verity is verified by kernel every time a block is loaded
+ * from disk to memory. The file is immutable by design, enforced by filesystem.
+ *
+ * <p>In order to make sure a block of the file is readable only if the underlying block on disk
+ * stay intact, the test needs to bypass the filesystem and tampers with the corresponding physical
+ * address against the block device.
+ *
+ * <p>Requirements to run this test:
+ * <ul>
+ *   <li>Device is rootable</li>
+ *   <li>The filesystem supports fs-verity</li>
+ *   <li>The feature flag is enabled</li>
+ * </ul>
+ */
+@RootPermissionTest
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class ApkVerityTest extends BaseHostJUnit4Test {
+    private static final String TARGET_PACKAGE = "com.android.apkverity";
+
+    private static final String BASE_APK = "ApkVerityTestApp.apk";
+    private static final String BASE_APK_DM = "ApkVerityTestApp.dm";
+    private static final String SPLIT_APK = "ApkVerityTestAppSplit.apk";
+    private static final String SPLIT_APK_DM = "ApkVerityTestAppSplit.dm";
+
+    private static final String INSTALLED_BASE_APK = "base.apk";
+    private static final String INSTALLED_BASE_DM = "base.dm";
+    private static final String INSTALLED_SPLIT_APK = "split_feature_x.apk";
+    private static final String INSTALLED_SPLIT_DM = "split_feature_x.dm";
+    private static final String INSTALLED_BASE_APK_FSV_SIG = "base.apk.fsv_sig";
+    private static final String INSTALLED_BASE_DM_FSV_SIG = "base.dm.fsv_sig";
+    private static final String INSTALLED_SPLIT_APK_FSV_SIG = "split_feature_x.apk.fsv_sig";
+    private static final String INSTALLED_SPLIT_DM_FSV_SIG = "split_feature_x.dm.fsv_sig";
+
+    private static final String DAMAGING_EXECUTABLE = "/data/local/tmp/block_device_writer";
+    private static final String CERT_PATH = "/data/local/tmp/ApkVerityTestCert.der";
+
+    private static final String APK_VERITY_STANDARD_MODE = "2";
+
+    /** Only 4K page is supported by fs-verity currently. */
+    private static final int FSVERITY_PAGE_SIZE = 4096;
+
+    private ITestDevice mDevice;
+    private String mKeyId;
+
+    @Before
+    public void setUp() throws DeviceNotAvailableException {
+        mDevice = getDevice();
+
+        String apkVerityMode = mDevice.getProperty("ro.apk_verity.mode");
+        assumeTrue(APK_VERITY_STANDARD_MODE.equals(apkVerityMode));
+
+        mKeyId = expectRemoteCommandToSucceed(
+                "mini-keyctl padd asymmetric fsv_test .fs-verity < " + CERT_PATH).trim();
+        if (!mKeyId.matches("^\\d+$")) {
+            String keyId = mKeyId;
+            mKeyId = null;
+            fail("Key ID is not decimal: " + keyId);
+        }
+
+        uninstallPackage(TARGET_PACKAGE);
+    }
+
+    @After
+    public void tearDown() throws DeviceNotAvailableException {
+        uninstallPackage(TARGET_PACKAGE);
+
+        if (mKeyId != null) {
+            expectRemoteCommandToSucceed("mini-keyctl unlink " + mKeyId + " .fs-verity");
+        }
+    }
+
+    @Test
+    public void testFsverityKernelSupports() throws DeviceNotAvailableException {
+        ITestDevice.MountPointInfo mountPoint = mDevice.getMountPointInfo("/data");
+        expectRemoteCommandToSucceed("test -f /sys/fs/" + mountPoint.type + "/features/verity");
+    }
+
+    @Test
+    public void testInstallBase() throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG);
+        verifyInstalledFilesHaveFsverity();
+    }
+
+    @Test
+    public void testInstallBaseWithWrongSignature()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFile(BASE_APK)
+                .addFile(SPLIT_APK_DM + ".fsv_sig",
+                        BASE_APK + ".fsv_sig")
+                .runExpectingFailure();
+    }
+
+    @Test
+    public void testInstallBaseWithSplit()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .addFileAndSignature(SPLIT_APK)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG,
+                INSTALLED_SPLIT_APK,
+                INSTALLED_SPLIT_APK_FSV_SIG);
+        verifyInstalledFilesHaveFsverity();
+    }
+
+    @Test
+    public void testInstallBaseWithDm() throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .addFileAndSignature(BASE_APK_DM)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG,
+                INSTALLED_BASE_DM,
+                INSTALLED_BASE_DM_FSV_SIG);
+        verifyInstalledFilesHaveFsverity();
+    }
+
+    @Test
+    public void testInstallEverything() throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .addFileAndSignature(BASE_APK_DM)
+                .addFileAndSignature(SPLIT_APK)
+                .addFileAndSignature(SPLIT_APK_DM)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG,
+                INSTALLED_BASE_DM,
+                INSTALLED_BASE_DM_FSV_SIG,
+                INSTALLED_SPLIT_APK,
+                INSTALLED_SPLIT_APK_FSV_SIG,
+                INSTALLED_SPLIT_DM,
+                INSTALLED_SPLIT_DM_FSV_SIG);
+        verifyInstalledFilesHaveFsverity();
+    }
+
+    @Test
+    public void testInstallSplitOnly()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG);
+
+        new InstallMultiple()
+                .inheritFrom(TARGET_PACKAGE)
+                .addFileAndSignature(SPLIT_APK)
+                .run();
+
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG,
+                INSTALLED_SPLIT_APK,
+                INSTALLED_SPLIT_APK_FSV_SIG);
+        verifyInstalledFilesHaveFsverity();
+    }
+
+    @Test
+    public void testInstallSplitOnlyMissingSignature()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG);
+
+        new InstallMultiple()
+                .inheritFrom(TARGET_PACKAGE)
+                .addFile(SPLIT_APK)
+                .runExpectingFailure();
+    }
+
+    @Test
+    public void testInstallSplitOnlyWithoutBaseSignature()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFile(BASE_APK)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+        verifyInstalledFiles(INSTALLED_BASE_APK);
+
+        new InstallMultiple()
+                .inheritFrom(TARGET_PACKAGE)
+                .addFileAndSignature(SPLIT_APK)
+                .run();
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_SPLIT_APK,
+                INSTALLED_SPLIT_APK_FSV_SIG);
+
+    }
+
+    @Test
+    public void testInstallOnlyBaseHasFsvSig()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .addFile(BASE_APK_DM)
+                .addFile(SPLIT_APK)
+                .addFile(SPLIT_APK_DM)
+                .runExpectingFailure();
+    }
+
+    @Test
+    public void testInstallOnlyDmHasFsvSig()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFile(BASE_APK)
+                .addFileAndSignature(BASE_APK_DM)
+                .addFile(SPLIT_APK)
+                .addFile(SPLIT_APK_DM)
+                .runExpectingFailure();
+    }
+
+    @Test
+    public void testInstallOnlySplitHasFsvSig()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFile(BASE_APK)
+                .addFile(BASE_APK_DM)
+                .addFileAndSignature(SPLIT_APK)
+                .addFile(SPLIT_APK_DM)
+                .runExpectingFailure();
+    }
+
+    @Test
+    public void testInstallBaseWithFsvSigThenSplitWithout()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFileAndSignature(BASE_APK)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+        verifyInstalledFiles(
+                INSTALLED_BASE_APK,
+                INSTALLED_BASE_APK_FSV_SIG);
+
+        new InstallMultiple()
+                .addFile(SPLIT_APK)
+                .runExpectingFailure();
+    }
+
+    @Test
+    public void testInstallBaseWithoutFsvSigThenSplitWith()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        new InstallMultiple()
+                .addFile(BASE_APK)
+                .run();
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+        verifyInstalledFiles(INSTALLED_BASE_APK);
+
+        new InstallMultiple()
+                .addFileAndSignature(SPLIT_APK)
+                .runExpectingFailure();
+    }
+
+    @Test
+    public void testFsverityFileIsImmutableAndReadable() throws DeviceNotAvailableException {
+        new InstallMultiple().addFileAndSignature(BASE_APK).run();
+        String apkPath = getApkPath(TARGET_PACKAGE);
+
+        assertNotNull(getDevice().getAppPackageInfo(TARGET_PACKAGE));
+        expectRemoteCommandToFail("echo -n '' >> " + apkPath);
+        expectRemoteCommandToSucceed("cat " + apkPath + " > /dev/null");
+    }
+
+    @Test
+    public void testFsverityFailToReadModifiedBlockAtFront() throws DeviceNotAvailableException {
+        new InstallMultiple().addFileAndSignature(BASE_APK).run();
+        String apkPath = getApkPath(TARGET_PACKAGE);
+
+        long apkSize = getFileSizeInBytes(apkPath);
+        long offsetFirstByte = 0;
+
+        // The first two pages should be both readable at first.
+        assertTrue(canReadByte(apkPath, offsetFirstByte));
+        if (apkSize > offsetFirstByte + FSVERITY_PAGE_SIZE) {
+            assertTrue(canReadByte(apkPath, offsetFirstByte + FSVERITY_PAGE_SIZE));
+        }
+
+        // Damage the file directly against the block device.
+        damageFileAgainstBlockDevice(apkPath, offsetFirstByte);
+
+        // Expect actual read from disk to fail but only at damaged page.
+        dropCaches();
+        assertFalse(canReadByte(apkPath, offsetFirstByte));
+        if (apkSize > offsetFirstByte + FSVERITY_PAGE_SIZE) {
+            long lastByteOfTheSamePage =
+                    offsetFirstByte % FSVERITY_PAGE_SIZE + FSVERITY_PAGE_SIZE - 1;
+            assertFalse(canReadByte(apkPath, lastByteOfTheSamePage));
+            assertTrue(canReadByte(apkPath, lastByteOfTheSamePage + 1));
+        }
+    }
+
+    @Test
+    public void testFsverityFailToReadModifiedBlockAtBack() throws DeviceNotAvailableException {
+        new InstallMultiple().addFileAndSignature(BASE_APK).run();
+        String apkPath = getApkPath(TARGET_PACKAGE);
+
+        long apkSize = getFileSizeInBytes(apkPath);
+        long offsetOfLastByte = apkSize - 1;
+
+        // The first two pages should be both readable at first.
+        assertTrue(canReadByte(apkPath, offsetOfLastByte));
+        if (offsetOfLastByte - FSVERITY_PAGE_SIZE > 0) {
+            assertTrue(canReadByte(apkPath, offsetOfLastByte - FSVERITY_PAGE_SIZE));
+        }
+
+        // Damage the file directly against the block device.
+        damageFileAgainstBlockDevice(apkPath, offsetOfLastByte);
+
+        // Expect actual read from disk to fail but only at damaged page.
+        dropCaches();
+        assertFalse(canReadByte(apkPath, offsetOfLastByte));
+        if (offsetOfLastByte - FSVERITY_PAGE_SIZE > 0) {
+            long firstByteOfTheSamePage = offsetOfLastByte - offsetOfLastByte % FSVERITY_PAGE_SIZE;
+            assertFalse(canReadByte(apkPath, firstByteOfTheSamePage));
+            assertTrue(canReadByte(apkPath, firstByteOfTheSamePage - 1));
+        }
+    }
+
+    private void verifyInstalledFilesHaveFsverity() throws DeviceNotAvailableException {
+        // Verify that all files are protected by fs-verity
+        String apkPath = getApkPath(TARGET_PACKAGE);
+        String appDir = apkPath.substring(0, apkPath.lastIndexOf("/"));
+        long kTargetOffset = 0;
+        for (String basename : expectRemoteCommandToSucceed("ls " + appDir).split("\n")) {
+            if (basename.endsWith(".apk") || basename.endsWith(".dm")) {
+                String path = appDir + "/" + basename;
+                damageFileAgainstBlockDevice(path, kTargetOffset);
+
+                // Retry is sometimes needed to pass the test. Package manager may have FD leaks
+                // (see b/122744005 as example) that prevents the file in question to be evicted
+                // from filesystem cache. Forcing GC workarounds the problem.
+                int retry = 5;
+                for (; retry > 0; retry--) {
+                    dropCaches();
+                    if (!canReadByte(path, kTargetOffset)) {
+                        break;
+                    }
+                    try {
+                        Thread.sleep(1000);
+                        String pid = expectRemoteCommandToSucceed("pidof system_server");
+                        mDevice.executeShellV2Command("kill -10 " + pid);  // force GC
+                    } catch (InterruptedException e) {
+                        Thread.currentThread().interrupt();
+                        return;
+                    }
+                }
+                assertTrue("Read from " + path + " should fail", retry > 0);
+            }
+        }
+    }
+
+    private void verifyInstalledFiles(String... filenames) throws DeviceNotAvailableException {
+        String apkPath = getApkPath(TARGET_PACKAGE);
+        String appDir = apkPath.substring(0, apkPath.lastIndexOf("/"));
+        HashSet<String> actualFiles = new HashSet<>(Arrays.asList(
+                expectRemoteCommandToSucceed("ls " + appDir).split("\n")));
+        assertTrue(actualFiles.remove("lib"));
+        assertTrue(actualFiles.remove("oat"));
+
+        HashSet<String> expectedFiles = new HashSet<>(Arrays.asList(filenames));
+        assertEquals(expectedFiles, actualFiles);
+    }
+
+    private void damageFileAgainstBlockDevice(String path, long offsetOfTargetingByte)
+            throws DeviceNotAvailableException {
+        assertTrue(path.startsWith("/data/"));
+        ITestDevice.MountPointInfo mountPoint = mDevice.getMountPointInfo("/data");
+        expectRemoteCommandToSucceed(String.join(" ", DAMAGING_EXECUTABLE,
+                    mountPoint.filesystem, path, Long.toString(offsetOfTargetingByte)));
+    }
+
+    private String getApkPath(String packageName) throws DeviceNotAvailableException {
+        String line = expectRemoteCommandToSucceed("pm path " + packageName + " | grep base.apk");
+        int index = line.trim().indexOf(":");
+        assertTrue(index >= 0);
+        return line.substring(index + 1);
+    }
+
+    private long getFileSizeInBytes(String packageName) throws DeviceNotAvailableException {
+        return Long.parseLong(expectRemoteCommandToSucceed("stat -c '%s' " + packageName).trim());
+    }
+
+    private void dropCaches() throws DeviceNotAvailableException {
+        expectRemoteCommandToSucceed("sync && echo 1 > /proc/sys/vm/drop_caches");
+    }
+
+    private boolean canReadByte(String filePath, long offset) throws DeviceNotAvailableException {
+        CommandResult result = mDevice.executeShellV2Command(
+                "dd if=" + filePath + " bs=1 count=1 skip=" + Long.toString(offset));
+        return result.getStatus() == CommandStatus.SUCCESS;
+    }
+
+    private String expectRemoteCommandToSucceed(String cmd) throws DeviceNotAvailableException {
+        CommandResult result = mDevice.executeShellV2Command(cmd);
+        assertEquals("`" + cmd + "` failed: " + result.getStderr(), CommandStatus.SUCCESS,
+                result.getStatus());
+        return result.getStdout();
+    }
+
+    private void expectRemoteCommandToFail(String cmd) throws DeviceNotAvailableException {
+        CommandResult result = mDevice.executeShellV2Command(cmd);
+        assertTrue("Unexpected success from `" + cmd + "`: " + result.getStderr(),
+                result.getStatus() != CommandStatus.SUCCESS);
+    }
+
+    private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
+        InstallMultiple() {
+            super(getDevice(), getBuild());
+        }
+
+        InstallMultiple addFileAndSignature(String filename) {
+            try {
+                addFile(filename);
+                addFile(filename + ".fsv_sig");
+            } catch (FileNotFoundException e) {
+                fail("Missing test file: " + e);
+            }
+            return this;
+        }
+    }
+}
diff --git a/tests/ApkVerityTest/src/com/android/apkverity/BaseInstallMultiple.java b/tests/ApkVerityTest/src/com/android/apkverity/BaseInstallMultiple.java
new file mode 100644
index 0000000..02e73d1
--- /dev/null
+++ b/tests/ApkVerityTest/src/com/android/apkverity/BaseInstallMultiple.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2019 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.apkverity;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Base class for invoking the install-multiple command via ADB. Subclass this for less typing:
+ *
+ * <code> private class InstallMultiple extends BaseInstallMultiple&lt;InstallMultiple&gt; { public
+ * InstallMultiple() { super(getDevice(), null); } } </code>
+ */
+/*package*/ class BaseInstallMultiple<T extends BaseInstallMultiple<?>> {
+
+    private final ITestDevice mDevice;
+    private final IBuildInfo mBuild;
+
+    private final List<String> mArgs = new ArrayList<>();
+    private final Map<File, String> mFileToRemoteMap = new HashMap<>();
+
+    /*package*/ BaseInstallMultiple(ITestDevice device, IBuildInfo buildInfo) {
+        mDevice = device;
+        mBuild = buildInfo;
+        addArg("-g");
+    }
+
+    T addArg(String arg) {
+        mArgs.add(arg);
+        return (T) this;
+    }
+
+    T addFile(String filename) throws FileNotFoundException {
+        return addFile(filename, filename);
+    }
+
+    T addFile(String filename, String remoteName) throws FileNotFoundException {
+        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mBuild);
+        mFileToRemoteMap.put(buildHelper.getTestFile(filename), remoteName);
+        return (T) this;
+    }
+
+    T inheritFrom(String packageName) {
+        addArg("-r");
+        addArg("-p " + packageName);
+        return (T) this;
+    }
+
+    void run() throws DeviceNotAvailableException {
+        run(true);
+    }
+
+    void runExpectingFailure() throws DeviceNotAvailableException {
+        run(false);
+    }
+
+    private void run(boolean expectingSuccess) throws DeviceNotAvailableException {
+        final ITestDevice device = mDevice;
+
+        // Create an install session
+        final StringBuilder cmd = new StringBuilder();
+        cmd.append("pm install-create");
+        for (String arg : mArgs) {
+            cmd.append(' ').append(arg);
+        }
+
+        String result = device.executeShellCommand(cmd.toString());
+        TestCase.assertTrue(result, result.startsWith("Success"));
+
+        final int start = result.lastIndexOf("[");
+        final int end = result.lastIndexOf("]");
+        int sessionId = -1;
+        try {
+            if (start != -1 && end != -1 && start < end) {
+                sessionId = Integer.parseInt(result.substring(start + 1, end));
+            }
+        } catch (NumberFormatException e) {
+            throw new IllegalStateException("Failed to parse install session: " + result);
+        }
+        if (sessionId == -1) {
+            throw new IllegalStateException("Failed to create install session: " + result);
+        }
+
+        // Push our files into session. Ideally we'd use stdin streaming,
+        // but ddmlib doesn't support it yet.
+        for (final Map.Entry<File, String> entry : mFileToRemoteMap.entrySet()) {
+            final File file = entry.getKey();
+            final String remoteName  = entry.getValue();
+            final String remotePath = "/data/local/tmp/" + file.getName();
+            if (!device.pushFile(file, remotePath)) {
+                throw new IllegalStateException("Failed to push " + file);
+            }
+
+            cmd.setLength(0);
+            cmd.append("pm install-write");
+            cmd.append(' ').append(sessionId);
+            cmd.append(' ').append(remoteName);
+            cmd.append(' ').append(remotePath);
+
+            result = device.executeShellCommand(cmd.toString());
+            TestCase.assertTrue(result, result.startsWith("Success"));
+        }
+
+        // Everything staged; let's pull trigger
+        cmd.setLength(0);
+        cmd.append("pm install-commit");
+        cmd.append(' ').append(sessionId);
+
+        result = device.executeShellCommand(cmd.toString());
+        if (expectingSuccess) {
+            TestCase.assertTrue(result, result.contains("Success"));
+        } else {
+            TestCase.assertFalse(result, result.contains("Success"));
+        }
+    }
+}
diff --git a/tests/ApkVerityTest/testdata/Android.bp b/tests/ApkVerityTest/testdata/Android.bp
new file mode 100644
index 0000000..c10b0ce
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/Android.bp
@@ -0,0 +1,77 @@
+// Copyright (C) 2019 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.
+
+filegroup {
+    name: "ApkVerityTestKeyPem",
+    srcs: ["ApkVerityTestKey.pem"],
+}
+
+filegroup {
+    name: "ApkVerityTestCertPem",
+    srcs: ["ApkVerityTestCert.pem"],
+}
+
+filegroup {
+    name: "ApkVerityTestCertDer",
+    srcs: ["ApkVerityTestCert.der"],
+}
+
+filegroup {
+    name: "ApkVerityTestAppDm",
+    srcs: ["ApkVerityTestApp.dm"],
+}
+
+filegroup {
+    name: "ApkVerityTestAppSplitDm",
+    srcs: ["ApkVerityTestAppSplit.dm"],
+}
+
+genrule_defaults {
+    name: "apk_verity_sig_gen_default",
+    tools: ["fsverity"],
+    tool_files: [":ApkVerityTestKeyPem", ":ApkVerityTestCertPem"],
+    cmd: "$(location fsverity) sign $(in) $(out) " +
+        "--key=$(location :ApkVerityTestKeyPem) " +
+        "--cert=$(location :ApkVerityTestCertPem) " +
+        "> /dev/null",
+}
+
+genrule {
+    name: "ApkVerityTestAppFsvSig",
+    defaults: ["apk_verity_sig_gen_default"],
+    srcs: [":ApkVerityTestApp"],
+    out: ["ApkVerityTestApp.apk.fsv_sig"],
+}
+
+genrule {
+    name: "ApkVerityTestAppDmFsvSig",
+    defaults: ["apk_verity_sig_gen_default"],
+    srcs: [":ApkVerityTestAppDm"],
+    out: ["ApkVerityTestApp.dm.fsv_sig"],
+}
+
+genrule {
+    name: "ApkVerityTestAppSplitFsvSig",
+    defaults: ["apk_verity_sig_gen_default"],
+    srcs: [":ApkVerityTestAppSplit"],
+    out: ["ApkVerityTestAppSplit.apk.fsv_sig"],
+}
+
+genrule {
+    name: "ApkVerityTestAppSplitDmFsvSig",
+    defaults: ["apk_verity_sig_gen_default"],
+    srcs: [":ApkVerityTestAppSplitDm"],
+    out: ["ApkVerityTestAppSplit.dm.fsv_sig"],
+}
+
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestApp.dm b/tests/ApkVerityTest/testdata/ApkVerityTestApp.dm
new file mode 100644
index 0000000..e53a861
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestApp.dm
Binary files differ
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestAppSplit.dm b/tests/ApkVerityTest/testdata/ApkVerityTestAppSplit.dm
new file mode 100644
index 0000000..75396f1
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestAppSplit.dm
Binary files differ
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestCert.der b/tests/ApkVerityTest/testdata/ApkVerityTestCert.der
new file mode 100644
index 0000000..fe9029b
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestCert.der
Binary files differ
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestCert.pem b/tests/ApkVerityTest/testdata/ApkVerityTestCert.pem
new file mode 100644
index 0000000..6c0b7b1
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestCert.pem
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFLjCCAxagAwIBAgIJAKZbtMlZZwtdMA0GCSqGSIb3DQEBCwUAMCwxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIDAJDQTEQMA4GA1UECgwHQW5kcm9pZDAeFw0xODEyMTky
+MTA5MzVaFw0xOTAxMTgyMTA5MzVaMCwxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJD
+QTEQMA4GA1UECgwHQW5kcm9pZDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC
+ggIBAKnrw4WiFgFBq6vXqcLc97iwvcYPZmeIjQqYRF+CHwXBXx8IyDlMfPrgyIYo
+ZLkosnUK/Exuypdu6UEtdqtYPknC6w9z4YkxqsKtyxyB1b13ptcTHh3bf2N8bqGr
+8gWWLxj0QjumCtFi7Z/TCwB5t3b3gtC+0jVfABSWrm5PNkgk7jIP+4KeYLDCDfiJ
+XH3uHu6OASiSHTOnrmLWSaSw0y6G4OFthHqQnMywasly0r6m+Mif+K0ZUV7hBRi/
+SfqcJ1HTCXTJMskEyV6Qx2sHF/VbK2gdUv56z6OVRNSs/FxPBiWVMuZZKh1FpBVI
+gbGxusf2Awwtc+Soxr4/P1YFcrwfA/ff9FK3Yg/Cd3ZMGbzUkbEMEkE5BW7Gbjmx
+wz3mYTiRfa2L/Bl4MiMqNi0tfORLkmg+V/EItzfhZ/HsXMOCBsnuj4KnFslmbamz
+t9opypj2JLGk+lXhZ5gFNFw8tYH1AnG1AIXe5u+6Fq2nQ1y/ncGUTR5Sw4de/Gee
+C0UgR+KiFEdKupMKbXgSKl+0QPz/i2eSpcDOKMwZ4WiNrkbccbCyr38so+j5DfWF
+IeZA9a/IlysA6G8yU2TfXBc65VCIEQRJOQdUOZFDO8OSoqGP+fbA6edpmovGw+TH
+sM/NkmpEXpQm7BVOI4oVjdf4pKPp0zaW2YcaA3xU2w6eF17pAgMBAAGjUzBRMB0G
+A1UdDgQWBBRGpHYy7yiLEYalGuF1va6zJKGD/zAfBgNVHSMEGDAWgBRGpHYy7yiL
+EYalGuF1va6zJKGD/zAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IC
+AQAao6ZBM122F0pYb2QLahIyyGEr3LfSdBGID4068pVik4ncIefFz36Xf9AFxRQd
+KHmwRYNPHiLRIEGdtqplC5pZDeHz41txIArNIZKzDWOYtdcFyCz8umuj912BmsoM
+YUQhT6F1sX53SWcKxEP/aJ2kltSlPFX99e3Vx9eRkceV1oe2NM6ZG8hnYCfCAMeJ
+jRTpbqCGaAsEHFtIx6wt3zEtUXIVg4aYFQs/qjTjeP8ByIj0b4lZrceEoTeRimuj
++4aAI+jBxLkwaN3hseQHzRNpgPehIVV/0RU92yzOD/WN4YwE6rwjKEI1lihHNBDa
++DwGtGbHmIUzjW1qArig+mzUIhfYIJAxrx20ynPz/Q+C7+iXhTDAYQlxTle0pX8m
+yM2DUdPo97eLOzQ4JDHxtcN3ntTEJKKvrmzKvWuxy/yoLwS7MtLH6RETTHabH3Qd
+CP83X7z8zTyxgPxHdfHo9sgR/4C9RHGJx4OpBTQaiqfjSpDqJSIQdbrHGOQDgYwL
+KQyiQuhukmNgRCB6dJoZJ/MyaNuMsXV9QobsDHW1oSuCvPAihVoWHJxt8m4Ma0jJ
+EIbEPT2Umw1F/P+CeXnVQwhPvzQKHCa+6cC/YdjTqIKLmQV8X3HUBUIMhP2JGDic
+MnUipTm/RwWZVOjCJaFqk5sVq3L0Lyd0XVUWSK1a4IcrsA==
+-----END CERTIFICATE-----
diff --git a/tests/ApkVerityTest/testdata/ApkVerityTestKey.pem b/tests/ApkVerityTest/testdata/ApkVerityTestKey.pem
new file mode 100644
index 0000000..f0746c1
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/ApkVerityTestKey.pem
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCp68OFohYBQaur
+16nC3Pe4sL3GD2ZniI0KmERfgh8FwV8fCMg5THz64MiGKGS5KLJ1CvxMbsqXbulB
+LXarWD5JwusPc+GJMarCrcscgdW9d6bXEx4d239jfG6hq/IFli8Y9EI7pgrRYu2f
+0wsAebd294LQvtI1XwAUlq5uTzZIJO4yD/uCnmCwwg34iVx97h7ujgEokh0zp65i
+1kmksNMuhuDhbYR6kJzMsGrJctK+pvjIn/itGVFe4QUYv0n6nCdR0wl0yTLJBMle
+kMdrBxf1WytoHVL+es+jlUTUrPxcTwYllTLmWSodRaQVSIGxsbrH9gMMLXPkqMa+
+Pz9WBXK8HwP33/RSt2IPwnd2TBm81JGxDBJBOQVuxm45scM95mE4kX2ti/wZeDIj
+KjYtLXzkS5JoPlfxCLc34Wfx7FzDggbJ7o+CpxbJZm2ps7faKcqY9iSxpPpV4WeY
+BTRcPLWB9QJxtQCF3ubvuhatp0Ncv53BlE0eUsOHXvxnngtFIEfiohRHSrqTCm14
+EipftED8/4tnkqXAzijMGeFoja5G3HGwsq9/LKPo+Q31hSHmQPWvyJcrAOhvMlNk
+31wXOuVQiBEESTkHVDmRQzvDkqKhj/n2wOnnaZqLxsPkx7DPzZJqRF6UJuwVTiOK
+FY3X+KSj6dM2ltmHGgN8VNsOnhde6QIDAQABAoICAGT21tWnisWyXKwd2BwWKgeO
+1SRDcEiihZO/CBlr+rzzum55TGdngHedauj0RW0Ttn3/SgysZCp415ZHylRjeZdg
+f0VOSLu5TEqi86X7q6IJ35O6I1IAY4AcpqvfvE3/f/qm4FgLADCMRL+LqeTdbdr9
+lLguOj9GNIkHQ5v96zYQ44vRnVNugetlUuHT1KZq/+wlaqDNuRZBU0gdJeL6wnDJ
+6gNojKg7F0A0ry8F0B1Cn16uVxebjJMAx4N93hpQALkI2XyQNGHnOzO6eROqQl0i
+j/csPW1CUfBUOHLaWpUKy483SOhAINsFz0pqK84G2gIItqTcuRksA/N1J1AYqqQO
++/8IK5Mb9j0RaYYrBG83luGCWYauAsWg2Yol6fUGju8IY/zavOaES42XogY588Ad
+JzW+njjxXcnoD/u5keWrGwbPdGfoaLLg4eMlRBT4yNicyT04knXjFG4QTfLY5lF/
+VKdvZk6RMoCLdAtgN6EKHtcwuoYR967otsbavshngZ9HE/ic5/TdNFCBjxs6q9bm
+docC4CLHU/feXvOCYSnIfUpDzEPV96Gbk6o0qeYn3RUSGzRpXQHxXXfszEESUWnd
+2rtfXxqA7C5n8CshBfKJND7/LKRGpBRaYWJtc4hFmo8prhXfOb40PEZNlx8mcsEz
+WYZpmvFQHU8+bZIm0a5RAoIBAQDaCAje9xLKN1CYzygA/U3x2CsGuWWyh9xM1oR5
+5t+nn0EeIMrzGuHrD4hdbZiTiJcO5dpSg/3dssc/QLJEdv+BoMEgSYTf3TX03dIb
+kSlj+ONobejO4nVoUP0axTvVe/nuMYvLguTM6OCFvgV752TFxVyVHl6RM+rQYGCl
+ajbBCsCRg4QgpZ/RHWf+3KMJunzwWBlsAXcjOudneYqEl713h/q1lc5cONIglQDU
+E+bc5q6q++c/H8dYaWq4QE4CQU8wsq77/bZk8z1jheOV0HkwaH5ShtKD7bk/4MA9
+jWQUDW6/LRXkNiPExsAZxnP3mxhtUToWq1nedF6kPmNBko+9AoIBAQDHgvAql6i7
+osTYUcY/GldPmnrvfqbKmD0nI8mnaJfN2vGwjB/ol3lm+pviKIQ4ER80xsdn4xK0
+2cC9OdkY2UX7zilKohxvKVsbVOYpUwfpoRQO1Euddb6iAMqgGDyDzRBDTzTx5pB5
+XL9B/XuJVCMkjsNdD9iEbjdY1Epv7kYf53zfvrXdqv24uSNAszPFBLLPHSC9yONE
+a/t3mHGZ2cjr52leGNGY7ib6GNGBUeA34SM9g97tU9pAgy712RfZhH6fA93CLk6T
+DKoch56YId71vZt2J0Lrk4TWnnpidSoRmzKfVIJwjCmgYbI+2eDp7h0Z0DnDbji6
+9BPt3RWsoZidAoIBAA2A7+O3U7+Ye3JraiPdjGVNKSUKeIT9KyTLKHtQVEvSbjsK
+dudlo9ZmKOD4d7mzfP+cNtBjgmanuvVs8V2SLTL/HNb+Fq+yyLO4xVmVvQWHFbaT
+EBc4KWNjmLl+u7z2J72b7feVzMvwJG/EHBzXcQNavOgzcFH38DQls/aqxGdiXhjl
+F1raRzKxao57ZdGlbjWIj1KEKLfS3yAmg/DAYSi1EE8MzzIhBsqjz+BStzq5Qtou
+Ld1X/4W3SbfNq8cx+lCe0H2k8hYAhq3STg0qU0cvQZuk5Abtw0p0hhOJ3UfsqQ5I
+IZH31HFMiftOskIEphenLzzWMgO4G2B6yLT3+dUCggEAOLF1i7Ti5sbfBtVd70qN
+6vnr2yhzPvi5z+h0ghTPpliD+3YmDxMUFXY7W63FvKTo6DdgLJ4zD58dDOhmT5BW
+ObKguyuLxu7Ki965NJ76jaIPMBOVlR4DWMe+zHV2pMFd0LKuSdsJzOLVGmxscV6u
+SdIjo8s/7InhQmW47UuZM7G1I2NvDJltVdOON/F0UZT/NqmBR0zRf/zrTVXNWjmv
+xZFRuMJ2tO1fuAvbZNMeUuKv/+f8LhZ424IrkwLoqw/iZ09S8b306AZeRJMpNvPR
+BqWlipKnioe15MLN5jKDDNO8M9hw5Ih/v6pjW0bQicj3DgHEmEs25bE8BIihgxe8
+ZQKCAQEAsWKsUv13OEbYYAoJgbzDesWF9NzamFB0NLyno9SChvFPH/d8RmAuti7Y
+BQUoBswLK24DF/TKf1YocsZq8tu+pnv0Nx1wtK4K+J3A1BYDm7ElpO3Km+HPUBtf
+C9KGT5hotlMQVTpYSDG/QeWbfl4UnNZcbg8pmv38NwV1eDoVDfaVrRYJzQn75+Tf
+s/WUq1x5PElR/4pNIU2i6pJGd6FimhRweJu/INR36spWmbMRNX8fyXx+9EBqMbVp
+vS2xGgxxQT6bAvBfRlpgi87T9v5Gqoy6/jM/wX9smH9PfUV1vK32n3Zrbd46gwZW
+p2aUlQOLXU9SjQTirZbdCZP0XHtFsg==
+-----END PRIVATE KEY-----
diff --git a/tests/ApkVerityTest/testdata/README.md b/tests/ApkVerityTest/testdata/README.md
new file mode 100644
index 0000000..163cb18
--- /dev/null
+++ b/tests/ApkVerityTest/testdata/README.md
@@ -0,0 +1,13 @@
+This test only runs on rooted / debuggable device.
+
+The test tries to install subsets of base.{apk,dm}, split.{apk,dm} and their
+corresponding .fsv_sig files (generated by build rule). If installed, the
+tests also tries to tamper with the file at absolute disk offset to verify
+if fs-verity is effective.
+
+How to generate dex metadata (.dm)
+==================================
+
+  adb shell profman --generate-test-profile=/data/local/tmp/primary.prof
+  adb pull /data/local/tmp/primary.prof
+  zip foo.dm primary.prof
diff --git a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
index 17986a3..fe1d9d2 100644
--- a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
+++ b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
@@ -66,10 +66,18 @@
         String res;
         res = mTestDevice.executeShellCommand("truncate -s 0 " + SYSTEM_SERVER_PROFILE).trim();
         assertTrue(res, res.length() == 0);
-        // Force save profiles in case the system just started.
+        // Wait up to 20 seconds for the profile to be saved.
+        for (int i = 0; i < 20; ++i) {
+            // Force save the profile since we truncated it.
+            forceSaveProfile("system_server");
+            String s = mTestDevice.executeShellCommand("wc -c <" + SYSTEM_SERVER_PROFILE).trim();
+            if (!"0".equals(s)) {
+                break;
+            }
+            Thread.sleep(1000);
+        }
+        // In case the profile is partially saved, wait an extra second.
         Thread.sleep(1000);
-        forceSaveProfile("system_server");
-        Thread.sleep(2000);
         // Validate that the profile is non empty.
         res = mTestDevice.executeShellCommand("profman --dump-only --profile-file="
                 + SYSTEM_SERVER_PROFILE);
@@ -84,5 +92,18 @@
         }
         assertTrue("Did not see framework.jar in " + res, sawFramework);
         assertTrue("Did not see services.jar in " + res, sawServices);
+
+
+        // Test the profile contents contain common methods for core-oj that would normally be AOT
+        // compiled.
+        res = mTestDevice.executeShellCommand("profman --dump-classes-and-methods --profile-file="
+                + SYSTEM_SERVER_PROFILE + " --apk=/apex/com.android.art/javalib/core-oj.jar");
+        boolean sawObjectInit = false;
+        for (String line : res.split("\n")) {
+            if (line.contains("Ljava/lang/Object;-><init>()V")) {
+                sawObjectInit = true;
+            }
+        }
+        assertTrue("Did not see Object.<init> in " + res, sawObjectInit);
     }
 }
diff --git a/tests/Codegen/runTest.sh b/tests/Codegen/runTest.sh
index 614cbb7..0e90dea 100755
--- a/tests/Codegen/runTest.sh
+++ b/tests/Codegen/runTest.sh
@@ -13,9 +13,13 @@
     header_and_eval m -j16 codegen_cli && \
         header_and_eval codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/SampleDataClass.java && \
         header_and_eval codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java && \
+        header_and_eval codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java && \
+        header_and_eval codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java && \
+        header_and_eval codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java && \
+        header_and_eval codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java && \
         cd $ANDROID_BUILD_TOP &&
         header_and_eval mmma -j16 frameworks/base/tests/Codegen && \
-        header_and_eval adb install -r -t $ANDROID_PRODUCT_OUT/testcases/CodegenTests/arm64/CodegenTests.apk && \
+        header_and_eval adb install -r -t "$(find $ANDROID_TARGET_OUT_TESTCASES -name 'CodegenTests.apk')" && \
         # header_and_eval adb shell am set-debug-app -w com.android.codegentest && \
         header_and_eval adb shell am instrument -w -e package com.android.codegentest com.android.codegentest/androidx.test.runner.AndroidJUnitRunner
 
diff --git a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.aidl b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.aidl
new file mode 100644
index 0000000..ab62c83
--- /dev/null
+++ b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2019 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.codegentest;
+
+parcelable HierrarchicalDataClassBase;
diff --git a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java
new file mode 100644
index 0000000..10eba6a
--- /dev/null
+++ b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2019 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.codegentest;
+
+import android.os.Parcelable;
+
+import com.android.internal.util.DataClass;
+
+/**
+ * @see HierrarchicalDataClassChild
+ */
+@DataClass(
+        genConstructor = false,
+        genSetters = true)
+public class HierrarchicalDataClassBase implements Parcelable {
+
+    private int mBaseData;
+
+
+
+    // Code below generated by codegen v1.0.7.
+    //
+    // DO NOT MODIFY!
+    // CHECKSTYLE:OFF Generated code
+    //
+    // To regenerate run:
+    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java
+
+
+    @DataClass.Generated.Member
+    public int getBaseData() {
+        return mBaseData;
+    }
+
+    @DataClass.Generated.Member
+    public HierrarchicalDataClassBase setBaseData(int value) {
+        mBaseData = value;
+        return this;
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public void writeToParcel(android.os.Parcel dest, int flags) {
+        // You can override field parcelling by defining methods like:
+        // void parcelFieldName(Parcel dest, int flags) { ... }
+
+        dest.writeInt(mBaseData);
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public int describeContents() { return 0; }
+
+    /** @hide */
+    @SuppressWarnings({"unchecked", "RedundantCast"})
+    @DataClass.Generated.Member
+    protected HierrarchicalDataClassBase(android.os.Parcel in) {
+        // You can override field unparcelling by defining methods like:
+        // static FieldType unparcelFieldName(Parcel in) { ... }
+
+        int baseData = in.readInt();
+
+        this.mBaseData = baseData;
+
+        // onConstructed(); // You can define this method to get a callback
+    }
+
+    @DataClass.Generated.Member
+    public static final @android.annotation.NonNull Parcelable.Creator<HierrarchicalDataClassBase> CREATOR
+            = new Parcelable.Creator<HierrarchicalDataClassBase>() {
+        @Override
+        public HierrarchicalDataClassBase[] newArray(int size) {
+            return new HierrarchicalDataClassBase[size];
+        }
+
+        @Override
+        public HierrarchicalDataClassBase createFromParcel(android.os.Parcel in) {
+            return new HierrarchicalDataClassBase(in);
+        }
+    };
+
+    @DataClass.Generated(
+            time = 1570576455287L,
+            codegenVersion = "1.0.7",
+            sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java",
+            inputSignatures = "private  int mBaseData\nclass HierrarchicalDataClassBase extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genConstructor=false, genSetters=true)")
+    @Deprecated
+    private void __metadata() {}
+
+}
diff --git a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.aidl b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.aidl
new file mode 100644
index 0000000..a099722
--- /dev/null
+++ b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2019 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.codegentest;
+
+parcelable HierrarchicalDataClassChild;
diff --git a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java
new file mode 100644
index 0000000..1085a6a
--- /dev/null
+++ b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2019 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.codegentest;
+
+import android.annotation.NonNull;
+import android.os.Parcelable;
+
+import com.android.internal.util.DataClass;
+
+/**
+ * An example of data classes that extend one another.
+ *
+ * Note that some features like constructor generation might not work well due to lack of
+ * information about the superclass when generating code for subclass.
+ *
+ * It is recommended to avoid inheritance in favor of composition for new data classes,
+ * particularly parcelable ones.
+ *
+ * However for legacy classes or where inheritance is desired for allocation efficiency,
+ * you can either use a technique from this example, opting for mutability/setters, or just write
+ * constructors by hand.
+ *
+ * @see HierrarchicalDataClassBase
+ */
+@DataClass(
+        genParcelable = true,
+        genConstructor = false,
+        genSetters = true)
+public class HierrarchicalDataClassChild extends HierrarchicalDataClassBase {
+
+    private @NonNull String mChildData;
+
+
+
+    // Code below generated by codegen v1.0.7.
+    //
+    // DO NOT MODIFY!
+    // CHECKSTYLE:OFF Generated code
+    //
+    // To regenerate run:
+    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java
+
+
+    @DataClass.Generated.Member
+    public @NonNull String getChildData() {
+        return mChildData;
+    }
+
+    @DataClass.Generated.Member
+    public HierrarchicalDataClassChild setChildData(@NonNull String value) {
+        mChildData = value;
+        com.android.internal.util.AnnotationValidations.validate(
+                NonNull.class, null, mChildData);
+        return this;
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public void writeToParcel(android.os.Parcel dest, int flags) {
+        // You can override field parcelling by defining methods like:
+        // void parcelFieldName(Parcel dest, int flags) { ... }
+
+        super.writeToParcel(dest, flags);
+
+        dest.writeString(mChildData);
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public int describeContents() { return 0; }
+
+    /** @hide */
+    @SuppressWarnings({"unchecked", "RedundantCast"})
+    @DataClass.Generated.Member
+    protected HierrarchicalDataClassChild(android.os.Parcel in) {
+        // You can override field unparcelling by defining methods like:
+        // static FieldType unparcelFieldName(Parcel in) { ... }
+
+        super(in);
+
+        String childData = in.readString();
+
+        this.mChildData = childData;
+        com.android.internal.util.AnnotationValidations.validate(
+                NonNull.class, null, mChildData);
+
+        // onConstructed(); // You can define this method to get a callback
+    }
+
+    @DataClass.Generated.Member
+    public static final @NonNull Parcelable.Creator<HierrarchicalDataClassChild> CREATOR
+            = new Parcelable.Creator<HierrarchicalDataClassChild>() {
+        @Override
+        public HierrarchicalDataClassChild[] newArray(int size) {
+            return new HierrarchicalDataClassChild[size];
+        }
+
+        @Override
+        public HierrarchicalDataClassChild createFromParcel(android.os.Parcel in) {
+            return new HierrarchicalDataClassChild(in);
+        }
+    };
+
+    @DataClass.Generated(
+            time = 1570576456245L,
+            codegenVersion = "1.0.7",
+            sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java",
+            inputSignatures = "private @android.annotation.NonNull java.lang.String mChildData\nclass HierrarchicalDataClassChild extends com.android.codegentest.HierrarchicalDataClassBase implements []\n@com.android.internal.util.DataClass(genParcelable=true, genConstructor=false, genSetters=true)")
+    @Deprecated
+    private void __metadata() {}
+
+}
diff --git a/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java b/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java
new file mode 100644
index 0000000..75ef963
--- /dev/null
+++ b/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java
@@ -0,0 +1,384 @@
+/*
+ * Copyright (C) 2019 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.codegentest;
+
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.SparseArray;
+import android.util.SparseIntArray;
+
+import com.android.internal.util.AnnotationValidations;
+import com.android.internal.util.DataClass;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Additional test for various parcelling corner-cases.
+ */
+@DataClass(
+        genBuilder = true,
+        genAidl = false,
+        genToString = true)
+public class ParcelAllTheThingsDataClass implements Parcelable {
+
+    @NonNull String[] mStringArray = null;
+    @NonNull int[] mIntArray = null;
+    @NonNull List<String> mStringList = null;
+
+    @NonNull Map<String, SampleWithCustomBuilder> mMap = null;
+    @NonNull Map<String, String> mStringMap = null;
+
+    @NonNull SparseArray<SampleWithCustomBuilder> mSparseArray = null;
+    @NonNull SparseIntArray mSparseIntArray = null;
+
+
+
+    // Code below generated by codegen v1.0.7.
+    //
+    // DO NOT MODIFY!
+    // CHECKSTYLE:OFF Generated code
+    //
+    // To regenerate run:
+    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java
+
+
+    @DataClass.Generated.Member
+    /* package-private */ ParcelAllTheThingsDataClass(
+            @NonNull String[] stringArray,
+            @NonNull int[] intArray,
+            @NonNull List<String> stringList,
+            @NonNull Map<String,SampleWithCustomBuilder> map,
+            @NonNull Map<String,String> stringMap,
+            @NonNull SparseArray<SampleWithCustomBuilder> sparseArray,
+            @NonNull SparseIntArray sparseIntArray) {
+        this.mStringArray = stringArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mStringArray);
+        this.mIntArray = intArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mIntArray);
+        this.mStringList = stringList;
+        AnnotationValidations.validate(
+                NonNull.class, null, mStringList);
+        this.mMap = map;
+        AnnotationValidations.validate(
+                NonNull.class, null, mMap);
+        this.mStringMap = stringMap;
+        AnnotationValidations.validate(
+                NonNull.class, null, mStringMap);
+        this.mSparseArray = sparseArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mSparseArray);
+        this.mSparseIntArray = sparseIntArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mSparseIntArray);
+
+        // onConstructed(); // You can define this method to get a callback
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull String[] getStringArray() {
+        return mStringArray;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull int[] getIntArray() {
+        return mIntArray;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull List<String> getStringList() {
+        return mStringList;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull Map<String,SampleWithCustomBuilder> getMap() {
+        return mMap;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull Map<String,String> getStringMap() {
+        return mStringMap;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull SparseArray<SampleWithCustomBuilder> getSparseArray() {
+        return mSparseArray;
+    }
+
+    @DataClass.Generated.Member
+    public @NonNull SparseIntArray getSparseIntArray() {
+        return mSparseIntArray;
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public String toString() {
+        // You can override field toString logic by defining methods like:
+        // String fieldNameToString() { ... }
+
+        return "ParcelAllTheThingsDataClass { " +
+                "stringArray = " + java.util.Arrays.toString(mStringArray) + ", " +
+                "intArray = " + java.util.Arrays.toString(mIntArray) + ", " +
+                "stringList = " + mStringList + ", " +
+                "map = " + mMap + ", " +
+                "stringMap = " + mStringMap + ", " +
+                "sparseArray = " + mSparseArray + ", " +
+                "sparseIntArray = " + mSparseIntArray +
+        " }";
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public void writeToParcel(Parcel dest, int flags) {
+        // You can override field parcelling by defining methods like:
+        // void parcelFieldName(Parcel dest, int flags) { ... }
+
+        dest.writeStringArray(mStringArray);
+        dest.writeIntArray(mIntArray);
+        dest.writeStringList(mStringList);
+        dest.writeMap(mMap);
+        dest.writeMap(mStringMap);
+        dest.writeSparseArray(mSparseArray);
+        dest.writeSparseIntArray(mSparseIntArray);
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public int describeContents() { return 0; }
+
+    /** @hide */
+    @SuppressWarnings({"unchecked", "RedundantCast"})
+    @DataClass.Generated.Member
+    protected ParcelAllTheThingsDataClass(Parcel in) {
+        // You can override field unparcelling by defining methods like:
+        // static FieldType unparcelFieldName(Parcel in) { ... }
+
+        String[] stringArray = in.createStringArray();
+        int[] intArray = in.createIntArray();
+        List<String> stringList = new java.util.ArrayList<>();
+        in.readStringList(stringList);
+        Map<String,SampleWithCustomBuilder> map = new java.util.LinkedHashMap<>();
+        in.readMap(map, SampleWithCustomBuilder.class.getClassLoader());
+        Map<String,String> stringMap = new java.util.LinkedHashMap<>();
+        in.readMap(stringMap, String.class.getClassLoader());
+        SparseArray<SampleWithCustomBuilder> sparseArray = (SparseArray) in.readSparseArray(SampleWithCustomBuilder.class.getClassLoader());
+        SparseIntArray sparseIntArray = (SparseIntArray) in.readSparseIntArray();
+
+        this.mStringArray = stringArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mStringArray);
+        this.mIntArray = intArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mIntArray);
+        this.mStringList = stringList;
+        AnnotationValidations.validate(
+                NonNull.class, null, mStringList);
+        this.mMap = map;
+        AnnotationValidations.validate(
+                NonNull.class, null, mMap);
+        this.mStringMap = stringMap;
+        AnnotationValidations.validate(
+                NonNull.class, null, mStringMap);
+        this.mSparseArray = sparseArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mSparseArray);
+        this.mSparseIntArray = sparseIntArray;
+        AnnotationValidations.validate(
+                NonNull.class, null, mSparseIntArray);
+
+        // onConstructed(); // You can define this method to get a callback
+    }
+
+    @DataClass.Generated.Member
+    public static final @NonNull Parcelable.Creator<ParcelAllTheThingsDataClass> CREATOR
+            = new Parcelable.Creator<ParcelAllTheThingsDataClass>() {
+        @Override
+        public ParcelAllTheThingsDataClass[] newArray(int size) {
+            return new ParcelAllTheThingsDataClass[size];
+        }
+
+        @Override
+        public ParcelAllTheThingsDataClass createFromParcel(Parcel in) {
+            return new ParcelAllTheThingsDataClass(in);
+        }
+    };
+
+    /**
+     * A builder for {@link ParcelAllTheThingsDataClass}
+     */
+    @SuppressWarnings("WeakerAccess")
+    @DataClass.Generated.Member
+    public static class Builder {
+
+        private @NonNull String[] mStringArray;
+        private @NonNull int[] mIntArray;
+        private @NonNull List<String> mStringList;
+        private @NonNull Map<String,SampleWithCustomBuilder> mMap;
+        private @NonNull Map<String,String> mStringMap;
+        private @NonNull SparseArray<SampleWithCustomBuilder> mSparseArray;
+        private @NonNull SparseIntArray mSparseIntArray;
+
+        private long mBuilderFieldsSet = 0L;
+
+        public Builder() {
+        }
+
+        @DataClass.Generated.Member
+        public @NonNull Builder setStringArray(@NonNull String... value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x1;
+            mStringArray = value;
+            return this;
+        }
+
+        @DataClass.Generated.Member
+        public @NonNull Builder setIntArray(@NonNull int... value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x2;
+            mIntArray = value;
+            return this;
+        }
+
+        @DataClass.Generated.Member
+        public @NonNull Builder setStringList(@NonNull List<String> value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x4;
+            mStringList = value;
+            return this;
+        }
+
+        /** @see #setStringList */
+        @DataClass.Generated.Member
+        public @NonNull Builder addStringList(String value) {
+            // You can refine this method's name by providing item's singular name, e.g.:
+            // @DataClass.PluralOf("item")) mItems = ...
+
+            if (mStringList == null) setStringList(new java.util.ArrayList<>());
+            mStringList.add(value);
+            return this;
+        }
+
+        @DataClass.Generated.Member
+        public @NonNull Builder setMap(@NonNull Map<String,SampleWithCustomBuilder> value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x8;
+            mMap = value;
+            return this;
+        }
+
+        /** @see #setMap */
+        @DataClass.Generated.Member
+        public @NonNull Builder addMap(String key, SampleWithCustomBuilder value) {
+            // You can refine this method's name by providing item's singular name, e.g.:
+            // @DataClass.PluralOf("item")) mItems = ...
+
+            if (mMap == null) setMap(new java.util.LinkedHashMap());
+            mMap.put(key, value);
+            return this;
+        }
+
+        @DataClass.Generated.Member
+        public @NonNull Builder setStringMap(@NonNull Map<String,String> value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x10;
+            mStringMap = value;
+            return this;
+        }
+
+        /** @see #setStringMap */
+        @DataClass.Generated.Member
+        public @NonNull Builder addStringMap(String key, String value) {
+            // You can refine this method's name by providing item's singular name, e.g.:
+            // @DataClass.PluralOf("item")) mItems = ...
+
+            if (mStringMap == null) setStringMap(new java.util.LinkedHashMap());
+            mStringMap.put(key, value);
+            return this;
+        }
+
+        @DataClass.Generated.Member
+        public @NonNull Builder setSparseArray(@NonNull SparseArray<SampleWithCustomBuilder> value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x20;
+            mSparseArray = value;
+            return this;
+        }
+
+        @DataClass.Generated.Member
+        public @NonNull Builder setSparseIntArray(@NonNull SparseIntArray value) {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x40;
+            mSparseIntArray = value;
+            return this;
+        }
+
+        /** Builds the instance. This builder should not be touched after calling this! */
+        public ParcelAllTheThingsDataClass build() {
+            checkNotUsed();
+            mBuilderFieldsSet |= 0x80; // Mark builder used
+
+            if ((mBuilderFieldsSet & 0x1) == 0) {
+                mStringArray = null;
+            }
+            if ((mBuilderFieldsSet & 0x2) == 0) {
+                mIntArray = null;
+            }
+            if ((mBuilderFieldsSet & 0x4) == 0) {
+                mStringList = null;
+            }
+            if ((mBuilderFieldsSet & 0x8) == 0) {
+                mMap = null;
+            }
+            if ((mBuilderFieldsSet & 0x10) == 0) {
+                mStringMap = null;
+            }
+            if ((mBuilderFieldsSet & 0x20) == 0) {
+                mSparseArray = null;
+            }
+            if ((mBuilderFieldsSet & 0x40) == 0) {
+                mSparseIntArray = null;
+            }
+            ParcelAllTheThingsDataClass o = new ParcelAllTheThingsDataClass(
+                    mStringArray,
+                    mIntArray,
+                    mStringList,
+                    mMap,
+                    mStringMap,
+                    mSparseArray,
+                    mSparseIntArray);
+            return o;
+        }
+
+        private void checkNotUsed() {
+            if ((mBuilderFieldsSet & 0x80) != 0) {
+                throw new IllegalStateException(
+                        "This Builder should not be reused. Use a new Builder instance instead");
+            }
+        }
+    }
+
+    @DataClass.Generated(
+            time = 1570576454326L,
+            codegenVersion = "1.0.7",
+            sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java",
+            inputSignatures = " @android.annotation.NonNull java.lang.String[] mStringArray\n @android.annotation.NonNull int[] mIntArray\n @android.annotation.NonNull java.util.List<java.lang.String> mStringList\n @android.annotation.NonNull java.util.Map<java.lang.String,com.android.codegentest.SampleWithCustomBuilder> mMap\n @android.annotation.NonNull java.util.Map<java.lang.String,java.lang.String> mStringMap\n @android.annotation.NonNull android.util.SparseArray<com.android.codegentest.SampleWithCustomBuilder> mSparseArray\n @android.annotation.NonNull android.util.SparseIntArray mSparseIntArray\nclass ParcelAllTheThingsDataClass extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genAidl=false, genToString=true)")
+    @Deprecated
+    private void __metadata() {}
+
+}
diff --git a/tests/Codegen/src/com/android/codegentest/SampleDataClass.java b/tests/Codegen/src/com/android/codegentest/SampleDataClass.java
index f0c5baa..14010a9 100644
--- a/tests/Codegen/src/com/android/codegentest/SampleDataClass.java
+++ b/tests/Codegen/src/com/android/codegentest/SampleDataClass.java
@@ -342,14 +342,14 @@
 
 
 
-    // Code below generated by codegen v1.0.1.
+    // Code below generated by codegen v1.0.7.
     //
     // DO NOT MODIFY!
+    // CHECKSTYLE:OFF Generated code
     //
     // To regenerate run:
     // $ codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/SampleDataClass.java
-    //
-    // CHECKSTYLE:OFF Generated code
+
 
     @IntDef(prefix = "STATE_", value = {
         STATE_UNDEFINED,
@@ -1290,6 +1290,123 @@
     @DataClass.Generated.Member
     public int describeContents() { return 0; }
 
+    /** @hide */
+    @SuppressWarnings({"unchecked", "RedundantCast"})
+    @DataClass.Generated.Member
+    /* package-private */ SampleDataClass(Parcel in) {
+        // You can override field unparcelling by defining methods like:
+        // static FieldType unparcelFieldName(Parcel in) { ... }
+
+        long flg = in.readLong();
+        int num = in.readInt();
+        int num2 = in.readInt();
+        int num4 = in.readInt();
+        String name = (flg & 0x8) == 0 ? null : in.readString();
+        String name2 = in.readString();
+        String name4 = in.readString();
+        AccessibilityNodeInfo otherParcelable = (flg & 0x40) == 0 ? null : (AccessibilityNodeInfo) in.readTypedObject(AccessibilityNodeInfo.CREATOR);
+        Date date = sParcellingForDate.unparcel(in);
+        Pattern pattern = sParcellingForPattern.unparcel(in);
+        List<LinkAddress> linkAddresses2 = new ArrayList<>();
+        in.readParcelableList(linkAddresses2, LinkAddress.class.getClassLoader());
+        ArrayList<LinkAddress> linkAddresses = new ArrayList<>();
+        in.readParcelableList(linkAddresses, LinkAddress.class.getClassLoader());
+        LinkAddress[] linkAddresses4 = (flg & 0x800) == 0 ? null : (LinkAddress[]) in.createTypedArray(LinkAddress.CREATOR);
+        String stateName = in.readString();
+        int flags = in.readInt();
+        int state = in.readInt();
+        CharSequence _charSeq = (CharSequence) in.readCharSequence();
+        LinkAddress[] linkAddresses5 = (flg & 0x10000) == 0 ? null : (LinkAddress[]) in.createTypedArray(LinkAddress.CREATOR);
+        int stringRes = in.readInt();
+        int dayOfWeek = in.readInt();
+        float[] coords = in.createFloatArray();
+
+        this.mNum = num;
+        this.mNum2 = num2;
+        this.mNum4 = num4;
+        this.mName = name;
+        this.mName2 = name2;
+        AnnotationValidations.validate(
+                NonNull.class, null, mName2);
+        this.mName4 = name4;
+        AnnotationValidations.validate(
+                NonNull.class, null, mName4);
+        this.mOtherParcelable = otherParcelable;
+        this.mDate = date;
+        AnnotationValidations.validate(
+                NonNull.class, null, mDate);
+        this.mPattern = pattern;
+        AnnotationValidations.validate(
+                NonNull.class, null, mPattern);
+        this.mLinkAddresses2 = linkAddresses2;
+        AnnotationValidations.validate(
+                NonNull.class, null, mLinkAddresses2);
+        this.mLinkAddresses = linkAddresses;
+        AnnotationValidations.validate(
+                NonNull.class, null, mLinkAddresses);
+        this.mLinkAddresses4 = linkAddresses4;
+        this.mStateName = stateName;
+
+        if (!(Objects.equals(mStateName, STATE_NAME_UNDEFINED))
+                && !(Objects.equals(mStateName, STATE_NAME_ON))
+                && !(Objects.equals(mStateName, STATE_NAME_OFF))) {
+            throw new java.lang.IllegalArgumentException(
+                    "stateName was " + mStateName + " but must be one of: "
+                            + "STATE_NAME_UNDEFINED(" + STATE_NAME_UNDEFINED + "), "
+                            + "STATE_NAME_ON(" + STATE_NAME_ON + "), "
+                            + "STATE_NAME_OFF(" + STATE_NAME_OFF + ")");
+        }
+
+        AnnotationValidations.validate(
+                NonNull.class, null, mStateName);
+        this.mFlags = flags;
+
+        Preconditions.checkFlagsArgument(
+                mFlags,
+                FLAG_MANUAL_REQUEST
+                        | FLAG_COMPATIBILITY_MODE_REQUEST
+                        | FLAG_AUGMENTED_REQUEST);
+        this.mState = state;
+
+        if (!(mState == STATE_UNDEFINED)
+                && !(mState == STATE_ON)
+                && !(mState == STATE_OFF)) {
+            throw new java.lang.IllegalArgumentException(
+                    "state was " + mState + " but must be one of: "
+                            + "STATE_UNDEFINED(" + STATE_UNDEFINED + "), "
+                            + "STATE_ON(" + STATE_ON + "), "
+                            + "STATE_OFF(" + STATE_OFF + ")");
+        }
+
+        this.charSeq = _charSeq;
+        AnnotationValidations.validate(
+                NonNull.class, null, charSeq);
+        this.mLinkAddresses5 = linkAddresses5;
+        this.mStringRes = stringRes;
+        AnnotationValidations.validate(
+                StringRes.class, null, mStringRes);
+        this.mDayOfWeek = dayOfWeek;
+        AnnotationValidations.validate(
+                android.annotation.IntRange.class, null, mDayOfWeek,
+                "from", 0,
+                "to", 6);
+        this.mCoords = coords;
+        AnnotationValidations.validate(
+                Size.class, null, mCoords.length,
+                "value", 2);
+        AnnotationValidations.validate(
+                NonNull.class, null, mCoords);
+        int coordsSize = mCoords.length;
+        for (int i = 0; i < coordsSize; i++) {
+            AnnotationValidations.validate(
+                    FloatRange.class, null, mCoords[i],
+                    "from", 0f);
+        }
+
+
+        onConstructed();
+    }
+
     @DataClass.Generated.Member
     public static final @NonNull Parcelable.Creator<SampleDataClass> CREATOR
             = new Parcelable.Creator<SampleDataClass>() {
@@ -1299,55 +1416,8 @@
         }
 
         @Override
-        @SuppressWarnings({"unchecked", "RedundantCast"})
         public SampleDataClass createFromParcel(Parcel in) {
-            // You can override field unparcelling by defining methods like:
-            // static FieldType unparcelFieldName(Parcel in) { ... }
-
-            long flg = in.readLong();
-            int num = in.readInt();
-            int num2 = in.readInt();
-            int num4 = in.readInt();
-            String name = (flg & 0x8) == 0 ? null : in.readString();
-            String name2 = in.readString();
-            String name4 = in.readString();
-            AccessibilityNodeInfo otherParcelable = (flg & 0x40) == 0 ? null : (AccessibilityNodeInfo) in.readTypedObject(AccessibilityNodeInfo.CREATOR);
-            Date date = sParcellingForDate.unparcel(in);
-            Pattern pattern = sParcellingForPattern.unparcel(in);
-            List<LinkAddress> linkAddresses2 = new ArrayList<>();
-            in.readParcelableList(linkAddresses2, LinkAddress.class.getClassLoader());
-            ArrayList<LinkAddress> linkAddresses = new ArrayList<>();
-            in.readParcelableList(linkAddresses, LinkAddress.class.getClassLoader());
-            LinkAddress[] linkAddresses4 = (flg & 0x800) == 0 ? null : (LinkAddress[]) in.createTypedArray(LinkAddress.CREATOR);
-            String stateName = in.readString();
-            int flags = in.readInt();
-            int state = in.readInt();
-            CharSequence _charSeq = (CharSequence) in.readCharSequence();
-            LinkAddress[] linkAddresses5 = (flg & 0x10000) == 0 ? null : (LinkAddress[]) in.createTypedArray(LinkAddress.CREATOR);
-            int stringRes = in.readInt();
-            int dayOfWeek = in.readInt();
-            float[] coords = in.createFloatArray();
-            return new SampleDataClass(
-                    num,
-                    num2,
-                    num4,
-                    name,
-                    name2,
-                    name4,
-                    otherParcelable,
-                    date,
-                    pattern,
-                    linkAddresses2,
-                    linkAddresses,
-                    linkAddresses4,
-                    stateName,
-                    flags,
-                    state,
-                    _charSeq,
-                    linkAddresses5,
-                    stringRes,
-                    dayOfWeek,
-                    coords);
+            return new SampleDataClass(in);
         }
     };
 
@@ -1798,8 +1868,8 @@
     }
 
     @DataClass.Generated(
-            time = 1568235365376L,
-            codegenVersion = "1.0.1",
+            time = 1570576452225L,
+            codegenVersion = "1.0.7",
             sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/SampleDataClass.java",
             inputSignatures = "public static final  java.lang.String STATE_NAME_UNDEFINED\npublic static final  java.lang.String STATE_NAME_ON\npublic static final  java.lang.String STATE_NAME_OFF\npublic static final  int STATE_UNDEFINED\npublic static final  int STATE_ON\npublic static final  int STATE_OFF\npublic static final @com.android.codegentest.SampleDataClass.RequestFlags int FLAG_MANUAL_REQUEST\npublic static final @com.android.codegentest.SampleDataClass.RequestFlags int FLAG_COMPATIBILITY_MODE_REQUEST\npublic static final @com.android.codegentest.SampleDataClass.RequestFlags int FLAG_AUGMENTED_REQUEST\nprivate  int mNum\nprivate  int mNum2\nprivate  int mNum4\nprivate @android.annotation.Nullable java.lang.String mName\nprivate @android.annotation.NonNull java.lang.String mName2\nprivate @android.annotation.NonNull java.lang.String mName4\nprivate @android.annotation.Nullable android.view.accessibility.AccessibilityNodeInfo mOtherParcelable\nprivate @com.android.internal.util.DataClass.ParcelWith(com.android.codegentest.MyDateParcelling.class) @android.annotation.NonNull java.util.Date mDate\nprivate @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForPattern.class) @android.annotation.NonNull java.util.regex.Pattern mPattern\nprivate @android.annotation.NonNull java.util.List<android.net.LinkAddress> mLinkAddresses2\nprivate @com.android.internal.util.DataClass.PluralOf(\"linkAddress\") @android.annotation.NonNull java.util.ArrayList<android.net.LinkAddress> mLinkAddresses\nprivate @android.annotation.Nullable android.net.LinkAddress[] mLinkAddresses4\nprivate @com.android.codegentest.SampleDataClass.StateName @android.annotation.NonNull java.lang.String mStateName\nprivate @com.android.codegentest.SampleDataClass.RequestFlags int mFlags\nprivate @com.android.codegentest.SampleDataClass.State int mState\npublic @android.annotation.NonNull java.lang.CharSequence charSeq\nprivate final @android.annotation.Nullable android.net.LinkAddress[] mLinkAddresses5\nprivate transient  android.net.LinkAddress[] mLinkAddresses6\ntransient  int[] mTmpStorage\nprivate @android.annotation.StringRes int mStringRes\nprivate @android.annotation.IntRange(from=0L, to=6L) int mDayOfWeek\nprivate @android.annotation.Size(2L) @android.annotation.NonNull @com.android.internal.util.DataClass.Each @android.annotation.FloatRange(from=0.0) float[] mCoords\nprivate static  java.lang.String defaultName4()\nprivate  int[] lazyInitTmpStorage()\npublic  android.net.LinkAddress[] getLinkAddresses4()\nprivate  boolean patternEquals(java.util.regex.Pattern)\nprivate  int patternHashCode()\nprivate  void onConstructed()\npublic  void dump(java.io.PrintWriter)\nclass SampleDataClass extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genConstructor=true, genEqualsHashCode=true, genToString=true, genForEachField=true, genSetters=true)")
     @Deprecated
diff --git a/tests/Codegen/src/com/android/codegentest/SampleDataClassTest.java b/tests/Codegen/src/com/android/codegentest/SampleDataClassTest.java
index 6636207..c7a7735 100644
--- a/tests/Codegen/src/com/android/codegentest/SampleDataClassTest.java
+++ b/tests/Codegen/src/com/android/codegentest/SampleDataClassTest.java
@@ -25,9 +25,14 @@
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertThat;
 
+import static java.util.concurrent.TimeUnit.SECONDS;
+
 import android.net.LinkAddress;
+import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
+import android.util.SparseArray;
+import android.util.SparseIntArray;
 
 import androidx.test.runner.AndroidJUnit4;
 
@@ -36,6 +41,9 @@
 
 import java.util.Arrays;
 import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
 
 /**
@@ -209,6 +217,32 @@
         newBuilder().setDayOfWeek(42).build();
     }
 
+    @Test
+    public void testDataStructures_parcelCorrectly() {
+        SampleWithCustomBuilder otherParcelable = new SampleWithCustomBuilder.Builder().setDelay(3, SECONDS).build();
+
+        ParcelAllTheThingsDataClass instance = new ParcelAllTheThingsDataClass.Builder()
+                .setIntArray(40, 41)
+                .addMap("foo", otherParcelable)
+                .setSparseArray(new SparseArray<SampleWithCustomBuilder>() {{
+                    put(45, otherParcelable);
+                }})
+                .setSparseIntArray(new SparseIntArray() {{
+                    put(48, 49);
+                }})
+                .addStringMap("foo2", "fooValue")
+                .setStringArray("foo", "bar")
+                .addStringList("foo")
+                .build();
+
+        ParcelAllTheThingsDataClass unparceledInstance =
+                parcelAndUnparcel(instance, ParcelAllTheThingsDataClass.CREATOR);
+
+        // SparseArray and friends don't implement equals
+        // so just compare string representations instead
+        assertEquals(instance.toString(), unparceledInstance.toString());
+    }
+
     private static <T extends Parcelable> T parcelAndUnparcel(
             T original, Parcelable.Creator<T> creator) {
         Parcel p = Parcel.obtain();
diff --git a/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java b/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java
index 86f37fe..b5f6c73 100644
--- a/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java
+++ b/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java
@@ -17,14 +17,16 @@
 package com.android.codegentest;
 
 import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
 import android.os.SystemClock;
 
 import com.android.internal.util.DataClass;
 
 import java.util.concurrent.TimeUnit;
 
-@DataClass(genBuilder = true)
-public class SampleWithCustomBuilder {
+@DataClass(genBuilder = true, genAidl = false, genToString = true)
+public class SampleWithCustomBuilder implements Parcelable {
 
     long delayAmount = 0;
     @NonNull
@@ -73,15 +75,24 @@
     }
 
 
+    private static TimeUnit unparcelDelayUnit(Parcel p) {
+        return TimeUnit.values()[p.readInt()];
+    }
 
-    // Code below generated by codegen v1.0.1.
+    private void parcelDelayUnit(Parcel p, int flags) {
+        p.writeInt(delayUnit.ordinal());
+    }
+
+
+
+    // Code below generated by codegen v1.0.7.
     //
     // DO NOT MODIFY!
+    // CHECKSTYLE:OFF Generated code
     //
     // To regenerate run:
     // $ codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java
-    //
-    // CHECKSTYLE:OFF Generated code
+
 
     @DataClass.Generated.Member
     /* package-private */ SampleWithCustomBuilder(
@@ -112,6 +123,68 @@
         return creationTimestamp;
     }
 
+    @Override
+    @DataClass.Generated.Member
+    public String toString() {
+        // You can override field toString logic by defining methods like:
+        // String fieldNameToString() { ... }
+
+        return "SampleWithCustomBuilder { " +
+                "delayAmount = " + delayAmount + ", " +
+                "delayUnit = " + delayUnit + ", " +
+                "creationTimestamp = " + creationTimestamp +
+        " }";
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public void writeToParcel(Parcel dest, int flags) {
+        // You can override field parcelling by defining methods like:
+        // void parcelFieldName(Parcel dest, int flags) { ... }
+
+        dest.writeLong(delayAmount);
+        parcelDelayUnit(dest, flags);
+        dest.writeLong(creationTimestamp);
+    }
+
+    @Override
+    @DataClass.Generated.Member
+    public int describeContents() { return 0; }
+
+    /** @hide */
+    @SuppressWarnings({"unchecked", "RedundantCast"})
+    @DataClass.Generated.Member
+    protected SampleWithCustomBuilder(Parcel in) {
+        // You can override field unparcelling by defining methods like:
+        // static FieldType unparcelFieldName(Parcel in) { ... }
+
+        long _delayAmount = in.readLong();
+        TimeUnit _delayUnit = unparcelDelayUnit(in);
+        long _creationTimestamp = in.readLong();
+
+        this.delayAmount = _delayAmount;
+        this.delayUnit = _delayUnit;
+        com.android.internal.util.AnnotationValidations.validate(
+                NonNull.class, null, delayUnit);
+        this.creationTimestamp = _creationTimestamp;
+
+        // onConstructed(); // You can define this method to get a callback
+    }
+
+    @DataClass.Generated.Member
+    public static final @NonNull Parcelable.Creator<SampleWithCustomBuilder> CREATOR
+            = new Parcelable.Creator<SampleWithCustomBuilder>() {
+        @Override
+        public SampleWithCustomBuilder[] newArray(int size) {
+            return new SampleWithCustomBuilder[size];
+        }
+
+        @Override
+        public SampleWithCustomBuilder createFromParcel(Parcel in) {
+            return new SampleWithCustomBuilder(in);
+        }
+    };
+
     /**
      * A builder for {@link SampleWithCustomBuilder}
      */
@@ -176,10 +249,10 @@
     }
 
     @DataClass.Generated(
-            time = 1568235366386L,
-            codegenVersion = "1.0.1",
+            time = 1570576453295L,
+            codegenVersion = "1.0.7",
             sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java",
-            inputSignatures = "  long delayAmount\n @android.annotation.NonNull java.util.concurrent.TimeUnit delayUnit\n  long creationTimestamp\nclass SampleWithCustomBuilder extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genBuilder=true)\nabstract  com.android.codegentest.SampleWithCustomBuilder.Builder setDelayAmount(long)\npublic abstract  com.android.codegentest.SampleWithCustomBuilder.Builder setDelayUnit(java.util.concurrent.TimeUnit)\npublic  com.android.codegentest.SampleWithCustomBuilder.Builder setDelay(long,java.util.concurrent.TimeUnit)\nclass BaseBuilder extends java.lang.Object implements []")
+            inputSignatures = "  long delayAmount\n @android.annotation.NonNull java.util.concurrent.TimeUnit delayUnit\n  long creationTimestamp\nprivate static  java.util.concurrent.TimeUnit unparcelDelayUnit(android.os.Parcel)\nprivate  void parcelDelayUnit(android.os.Parcel,int)\nclass SampleWithCustomBuilder extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genAidl=false, genToString=true)\nabstract  com.android.codegentest.SampleWithCustomBuilder.Builder setDelayAmount(long)\npublic abstract  com.android.codegentest.SampleWithCustomBuilder.Builder setDelayUnit(java.util.concurrent.TimeUnit)\npublic  com.android.codegentest.SampleWithCustomBuilder.Builder setDelay(long,java.util.concurrent.TimeUnit)\nclass BaseBuilder extends java.lang.Object implements []")
     @Deprecated
     private void __metadata() {}
 
diff --git a/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java b/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java
new file mode 100644
index 0000000..0ce8aba
--- /dev/null
+++ b/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2019 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.codegentest;
+
+import android.annotation.NonNull;
+
+import com.android.internal.util.DataClass;
+
+/**
+ * Test for some false positive pitfalls for
+ * {@link android.processor.staledataclass.StaleDataclassProcessor}
+ *
+ * Relies on the detector being run, failing the build should any of things here falsely
+ * register as stale.
+ */
+@DataClass(genConstructor = false, genBuilder = false)
+public class StaleDataclassDetectorFalsePositivesTest {
+
+    /** Interfaces should be ignored */
+    public interface SomeListener {
+        void onEvent();
+    }
+
+    /** Enums should be ignored */
+    private enum SomeEnum { ONE, TWO }
+
+    /** Annotations should be ignored */
+    public @interface SomeAnnotation {}
+
+    /* Static initializers should be ignored */
+    static {}
+
+    /* Initializers should be ignored */
+    {}
+
+    /** Unrelated methods should be noted, without triggering staleness false positives */
+    public @NonNull String someMethod(int param) { return null; }
+
+
+
+    // Code below generated by codegen v1.0.7.
+    //
+    // DO NOT MODIFY!
+    // CHECKSTYLE:OFF Generated code
+    //
+    // To regenerate run:
+    // $ codegen $ANDROID_BUILD_TOP/frameworks/base/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java
+
+
+    @DataClass.Generated(
+            time = 1570576457249L,
+            codegenVersion = "1.0.7",
+            sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java",
+            inputSignatures = "public @android.annotation.NonNull java.lang.String someMethod(int)\nclass StaleDataclassDetectorFalsePositivesTest extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genConstructor=false, genBuilder=false)")
+    @Deprecated
+    private void __metadata() {}
+
+}
diff --git a/tests/FlickerTests/AndroidManifest.xml b/tests/FlickerTests/AndroidManifest.xml
index 5b1a36b..91fb7c1 100644
--- a/tests/FlickerTests/AndroidManifest.xml
+++ b/tests/FlickerTests/AndroidManifest.xml
@@ -21,8 +21,12 @@
     <!-- Read and write traces from external storage -->
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <!-- Write secure settings -->
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
     <!-- Capture screen contents -->
     <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
+    <!-- Enable / Disable tracing !-->
+    <uses-permission android:name="android.permission.DUMP" />
     <!-- Run layers trace -->
     <uses-permission android:name="android.permission.HARDWARE_TEST"/>
     <application>
@@ -33,4 +37,4 @@
                      android:targetPackage="com.android.server.wm.flicker"
                      android:label="WindowManager Flicker Tests">
     </instrumentation>
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/tests/FlickerTests/AndroidTest.xml b/tests/FlickerTests/AndroidTest.xml
index e36f976..d433df5 100644
--- a/tests/FlickerTests/AndroidTest.xml
+++ b/tests/FlickerTests/AndroidTest.xml
@@ -25,5 +25,6 @@
     <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector">
         <option name="directory-keys" value="/sdcard/flicker" />
         <option name="collect-on-run-ended-only" value="true" />
+        <option name="clean-up" value="false" />
     </metrics_collector>
 </configuration>
diff --git a/tests/FlickerTests/lib/Android.bp b/tests/FlickerTests/lib/Android.bp
deleted file mode 100644
index e0f0188..0000000
--- a/tests/FlickerTests/lib/Android.bp
+++ /dev/null
@@ -1,57 +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.
-//
-
-java_test {
-    name: "flickerlib",
-    platform_apis: true,
-    srcs: ["src/**/*.java"],
-    static_libs: [
-        "androidx.test.janktesthelper",
-        "cts-wm-util",
-        "platformprotosnano",
-        "layersprotosnano",
-        "truth-prebuilt",
-        "sysui-helper",
-        "launcher-helper-lib",
-    ],
-}
-
-java_library {
-    name: "flickerlib_without_helpers",
-    platform_apis: true,
-    srcs: ["src/**/*.java"],
-    exclude_srcs: ["src/**/helpers/*.java"],
-    static_libs: [
-        "cts-wm-util",
-        "platformprotosnano",
-        "layersprotosnano",
-        "truth-prebuilt"
-    ],
-}
-
-java_library {
-    name: "flickerautomationhelperlib",
-    sdk_version: "test_current",
-    srcs: [
-        "src/com/android/server/wm/flicker/helpers/AutomationUtils.java",
-        "src/com/android/server/wm/flicker/WindowUtils.java",
-    ],
-    static_libs: [
-        "sysui-helper",
-        "launcher-helper-lib",
-        "compatibility-device-util-axt",
-    ],
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/Assertions.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/Assertions.java
deleted file mode 100644
index 38255ee..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/Assertions.java
+++ /dev/null
@@ -1,134 +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.flicker;
-
-import java.util.concurrent.TimeUnit;
-import java.util.function.Function;
-
-/**
- * Collection of functional interfaces and classes representing assertions and their associated
- * results. Assertions are functions that are applied over a single trace entry and returns a
- * result which includes a detailed reason if the assertion fails.
- */
-public class Assertions {
-    /**
-     * Checks assertion on a single trace entry.
-     *
-     * @param <T> trace entry type to perform the assertion on.
-     */
-    @FunctionalInterface
-    public interface TraceAssertion<T> extends Function<T, Result> {
-        /**
-         * Returns an assertion that represents the logical negation of this assertion.
-         *
-         * @return a assertion that represents the logical negation of this assertion
-         */
-        default TraceAssertion<T> negate() {
-            return (T t) -> apply(t).negate();
-        }
-    }
-
-    /**
-     * Checks assertion on a single layers trace entry.
-     */
-    @FunctionalInterface
-    public interface LayersTraceAssertion extends TraceAssertion<LayersTrace.Entry> {
-
-    }
-
-    /**
-     * Utility class to store assertions with an identifier to help generate more useful debug
-     * data when dealing with multiple assertions.
-     */
-    public static class NamedAssertion<T> {
-        public final TraceAssertion<T> assertion;
-        public final String name;
-
-        public NamedAssertion(TraceAssertion<T> assertion, String name) {
-            this.assertion = assertion;
-            this.name = name;
-        }
-    }
-
-    /**
-     * Contains the result of an assertion including the reason for failed assertions.
-     */
-    public static class Result {
-        public static final String NEGATION_PREFIX = "!";
-        public final boolean success;
-        public final long timestamp;
-        public final String assertionName;
-        public final String reason;
-
-        public Result(boolean success, long timestamp, String assertionName, String reason) {
-            this.success = success;
-            this.timestamp = timestamp;
-            this.assertionName = assertionName;
-            this.reason = reason;
-        }
-
-        public Result(boolean success, String reason) {
-            this.success = success;
-            this.reason = reason;
-            this.assertionName = "";
-            this.timestamp = 0;
-        }
-
-        /**
-         * Returns the negated {@code Result} and adds a negation prefix to the assertion name.
-         */
-        public Result negate() {
-            String negatedAssertionName;
-            if (this.assertionName.startsWith(NEGATION_PREFIX)) {
-                negatedAssertionName = this.assertionName.substring(NEGATION_PREFIX.length() + 1);
-            } else {
-                negatedAssertionName = NEGATION_PREFIX + this.assertionName;
-            }
-            return new Result(!this.success, this.timestamp, negatedAssertionName, this.reason);
-        }
-
-        public boolean passed() {
-            return this.success;
-        }
-
-        public boolean failed() {
-            return !this.success;
-        }
-
-        @Override
-        public String toString() {
-            return "Timestamp: " + prettyTimestamp(timestamp)
-                    + "\nAssertion: " + assertionName
-                    + "\nReason:   " + reason;
-        }
-
-        private String prettyTimestamp(long timestamp_ns) {
-            StringBuilder prettyTimestamp = new StringBuilder();
-            TimeUnit[] timeUnits = {TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS, TimeUnit
-                    .MILLISECONDS};
-            String[] unitSuffixes = {"h", "m", "s", "ms"};
-
-            for (int i = 0; i < timeUnits.length; i++) {
-                long convertedTime = timeUnits[i].convert(timestamp_ns, TimeUnit.NANOSECONDS);
-                timestamp_ns -= TimeUnit.NANOSECONDS.convert(convertedTime, timeUnits[i]);
-                prettyTimestamp.append(convertedTime).append(unitSuffixes[i]);
-            }
-
-            return prettyTimestamp.toString();
-        }
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AssertionsChecker.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AssertionsChecker.java
deleted file mode 100644
index 5c4df81..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/AssertionsChecker.java
+++ /dev/null
@@ -1,183 +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.flicker;
-
-import com.android.server.wm.flicker.Assertions.NamedAssertion;
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.flicker.Assertions.TraceAssertion;
-
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Captures some of the common logic in {@link LayersTraceSubject} and {@link WmTraceSubject}
- * used to filter trace entries and combine multiple assertions.
- *
- * @param <T> trace entry type
- */
-public class AssertionsChecker<T extends ITraceEntry> {
-    private boolean mFilterEntriesByRange = false;
-    private long mFilterStartTime = 0;
-    private long mFilterEndTime = 0;
-    private AssertionOption mOption = AssertionOption.NONE;
-    private List<NamedAssertion<T>> mAssertions = new LinkedList<>();
-
-    public void add(Assertions.TraceAssertion<T> assertion, String name) {
-        mAssertions.add(new NamedAssertion<>(assertion, name));
-    }
-
-    public void filterByRange(long startTime, long endTime) {
-        mFilterEntriesByRange = true;
-        mFilterStartTime = startTime;
-        mFilterEndTime = endTime;
-    }
-
-    private void setOption(AssertionOption option) {
-        if (mOption != AssertionOption.NONE && option != mOption) {
-            throw new IllegalArgumentException("Cannot use " + mOption + " option with "
-                    + option + " option.");
-        }
-        mOption = option;
-    }
-
-    public void checkFirstEntry() {
-        setOption(AssertionOption.CHECK_FIRST_ENTRY);
-    }
-
-    public void checkLastEntry() {
-        setOption(AssertionOption.CHECK_LAST_ENTRY);
-    }
-
-    public void checkChangingAssertions() {
-        setOption(AssertionOption.CHECK_CHANGING_ASSERTIONS);
-    }
-
-
-    /**
-     * Filters trace entries then runs assertions returning a list of failures.
-     *
-     * @param entries list of entries to perform assertions on
-     * @return list of failed assertion results
-     */
-    public List<Result> test(List<T> entries) {
-        List<T> filteredEntries;
-        List<Result> failures;
-
-        if (mFilterEntriesByRange) {
-            filteredEntries = entries.stream()
-                    .filter(e -> ((e.getTimestamp() >= mFilterStartTime)
-                            && (e.getTimestamp() <= mFilterEndTime)))
-                    .collect(Collectors.toList());
-        } else {
-            filteredEntries = entries;
-        }
-
-        switch (mOption) {
-            case CHECK_CHANGING_ASSERTIONS:
-                return assertChanges(filteredEntries);
-            case CHECK_FIRST_ENTRY:
-                return assertEntry(filteredEntries.get(0));
-            case CHECK_LAST_ENTRY:
-                return assertEntry(filteredEntries.get(filteredEntries.size() - 1));
-        }
-        return assertAll(filteredEntries);
-    }
-
-    /**
-     * Steps through each trace entry checking if provided assertions are true in the order they
-     * are added. Each assertion must be true for at least a single trace entry.
-     *
-     * This can be used to check for asserting a change in property over a trace. Such as visibility
-     * for a window changes from true to false or top-most window changes from A to Bb and back to A
-     * again.
-     */
-    private List<Result> assertChanges(List<T> entries) {
-        List<Result> failures = new ArrayList<>();
-        int entryIndex = 0;
-        int assertionIndex = 0;
-        int lastPassedAssertionIndex = -1;
-
-        if (mAssertions.size() == 0) {
-            return failures;
-        }
-
-        while (assertionIndex < mAssertions.size() && entryIndex < entries.size()) {
-            TraceAssertion<T> currentAssertion = mAssertions.get(assertionIndex).assertion;
-            Result result = currentAssertion.apply(entries.get(entryIndex));
-            if (result.passed()) {
-                lastPassedAssertionIndex = assertionIndex;
-                entryIndex++;
-                continue;
-            }
-
-            if (lastPassedAssertionIndex != assertionIndex) {
-                failures.add(result);
-                break;
-            }
-            assertionIndex++;
-
-            if (assertionIndex == mAssertions.size()) {
-                failures.add(result);
-                break;
-            }
-        }
-
-        if (failures.isEmpty()) {
-            if (assertionIndex != mAssertions.size() - 1) {
-                String reason = "\nAssertion " + mAssertions.get(assertionIndex).name
-                        + " never became false";
-                reason += "\nPassed assertions: " + mAssertions.stream().limit(assertionIndex)
-                        .map(assertion -> assertion.name).collect(Collectors.joining(","));
-                reason += "\nUntested assertions: " + mAssertions.stream().skip(assertionIndex + 1)
-                        .map(assertion -> assertion.name).collect(Collectors.joining(","));
-
-                Result result = new Result(false /* success */, 0 /* timestamp */,
-                        "assertChanges", "Not all assertions passed." + reason);
-                failures.add(result);
-            }
-        }
-        return failures;
-    }
-
-    private List<Result> assertEntry(T entry) {
-        List<Result> failures = new ArrayList<>();
-        for (NamedAssertion<T> assertion : mAssertions) {
-            Result result = assertion.assertion.apply(entry);
-            if (result.failed()) {
-                failures.add(result);
-            }
-        }
-        return failures;
-    }
-
-    private List<Result> assertAll(List<T> entries) {
-        return mAssertions.stream().flatMap(
-                assertion -> entries.stream()
-                        .map(assertion.assertion)
-                        .filter(Result::failed))
-                .collect(Collectors.toList());
-    }
-
-    private enum AssertionOption {
-        NONE,
-        CHECK_CHANGING_ASSERTIONS,
-        CHECK_FIRST_ENTRY,
-        CHECK_LAST_ENTRY,
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/ITraceEntry.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/ITraceEntry.java
deleted file mode 100644
index c47f7f4..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/ITraceEntry.java
+++ /dev/null
@@ -1,27 +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.flicker;
-
-/**
- * Common interface for Layer and WindowManager trace entries.
- */
-public interface ITraceEntry {
-    /**
-     * @return timestamp of current entry
-     */
-    long getTimestamp();
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTrace.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTrace.java
deleted file mode 100644
index 68986d4..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTrace.java
+++ /dev/null
@@ -1,420 +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.flicker;
-
-import android.graphics.Rect;
-import android.surfaceflinger.nano.Layers.LayerProto;
-import android.surfaceflinger.nano.Layers.RectProto;
-import android.surfaceflinger.nano.Layers.RegionProto;
-import android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto;
-import android.surfaceflinger.nano.Layerstrace.LayersTraceProto;
-import android.util.SparseArray;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-/**
- * Contains a collection of parsed Layers trace entries and assertions to apply over
- * a single entry.
- *
- * Each entry is parsed into a list of {@link LayersTrace.Entry} objects.
- */
-public class LayersTrace {
-    final private List<Entry> mEntries;
-    @Nullable
-    final private Path mSource;
-
-    private LayersTrace(List<Entry> entries, Path source) {
-        this.mEntries = entries;
-        this.mSource = source;
-    }
-
-    /**
-     * Parses {@code LayersTraceFileProto} from {@code data} and uses the proto to generates a list
-     * of trace entries, storing the flattened layers into its hierarchical structure.
-     *
-     * @param data   binary proto data
-     * @param source Path to source of data for additional debug information
-     */
-    public static LayersTrace parseFrom(byte[] data, Path source) {
-        List<Entry> entries = new ArrayList<>();
-        LayersTraceFileProto fileProto;
-        try {
-            fileProto = LayersTraceFileProto.parseFrom(data);
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-        for (LayersTraceProto traceProto : fileProto.entry) {
-            Entry entry = Entry.fromFlattenedLayers(traceProto.elapsedRealtimeNanos,
-                    traceProto.layers.layers);
-            entries.add(entry);
-        }
-        return new LayersTrace(entries, source);
-    }
-
-    /**
-     * Parses {@code LayersTraceFileProto} from {@code data} and uses the proto to generates a list
-     * of trace entries, storing the flattened layers into its hierarchical structure.
-     *
-     * @param data binary proto data
-     */
-    public static LayersTrace parseFrom(byte[] data) {
-        return parseFrom(data, null);
-    }
-
-    public List<Entry> getEntries() {
-        return mEntries;
-    }
-
-    public Entry getEntry(long timestamp) {
-        Optional<Entry> entry = mEntries.stream()
-                .filter(e -> e.getTimestamp() == timestamp)
-                .findFirst();
-        if (!entry.isPresent()) {
-            throw new RuntimeException("Entry does not exist for timestamp " + timestamp);
-        }
-        return entry.get();
-    }
-
-    public Optional<Path> getSource() {
-        return Optional.ofNullable(mSource);
-    }
-
-    /**
-     * Represents a single Layer trace entry.
-     */
-    public static class Entry implements ITraceEntry {
-        private long mTimestamp;
-        private List<Layer> mRootLayers; // hierarchical representation of layers
-        private List<Layer> mFlattenedLayers = null;
-
-        private Entry(long timestamp, List<Layer> rootLayers) {
-            this.mTimestamp = timestamp;
-            this.mRootLayers = rootLayers;
-        }
-
-        /**
-         * Constructs the layer hierarchy from a flattened list of layers.
-         */
-        public static Entry fromFlattenedLayers(long timestamp, LayerProto[] protos) {
-            SparseArray<Layer> layerMap = new SparseArray<>();
-            ArrayList<Layer> orphans = new ArrayList<>();
-            for (LayerProto proto : protos) {
-                int id = proto.id;
-                int parentId = proto.parent;
-
-                Layer newLayer = layerMap.get(id);
-                if (newLayer == null) {
-                    newLayer = new Layer(proto);
-                    layerMap.append(id, newLayer);
-                } else if (newLayer.mProto != null) {
-                    throw new RuntimeException("Duplicate layer id found:" + id);
-                } else {
-                    newLayer.mProto = proto;
-                    orphans.remove(newLayer);
-                }
-
-                // add parent placeholder
-                if (layerMap.get(parentId) == null) {
-                    Layer orphanLayer = new Layer(null);
-                    layerMap.append(parentId, orphanLayer);
-                    orphans.add(orphanLayer);
-                }
-                layerMap.get(parentId).addChild(newLayer);
-                newLayer.addParent(layerMap.get(parentId));
-            }
-
-            // Fail if we find orphan layers.
-            orphans.remove(layerMap.get(-1));
-            orphans.forEach(orphan -> {
-                String childNodes = orphan.mChildren.stream().map(node ->
-                        Integer.toString(node.getId())).collect(Collectors.joining(", "));
-                int orphanId = orphan.mChildren.get(0).mProto.parent;
-                throw new RuntimeException(
-                        "Failed to parse layers trace. Found orphan layers with parent "
-                                + "layer id:" + orphanId + " : " + childNodes);
-            });
-
-            return new Entry(timestamp, layerMap.get(-1).mChildren);
-        }
-
-        /**
-         * Extracts {@link Rect} from {@link RectProto}.
-         */
-        private static Rect extract(RectProto proto) {
-            return new Rect(proto.left, proto.top, proto.right, proto.bottom);
-        }
-
-        /**
-         * Extracts {@link Rect} from {@link RegionProto} by returning a rect that encompasses all
-         * the rects making up the region.
-         */
-        private static Rect extract(RegionProto regionProto) {
-            Rect region = new Rect();
-            for (RectProto proto : regionProto.rect) {
-                region.union(proto.left, proto.top, proto.right, proto.bottom);
-            }
-            return region;
-        }
-
-        /**
-         * Checks if a region specified by {@code testRect} is covered by all visible layers.
-         */
-        public Result coversRegion(Rect testRect) {
-            String assertionName = "coversRegion";
-            Collection<Layer> layers = asFlattenedLayers();
-
-            for (int x = testRect.left; x < testRect.right; x++) {
-                for (int y = testRect.top; y < testRect.bottom; y++) {
-                    boolean emptyRegionFound = true;
-                    for (Layer layer : layers) {
-                        if (layer.isInvisible() || layer.isHiddenByParent()) {
-                            continue;
-                        }
-                        for (RectProto rectProto : layer.mProto.visibleRegion.rect) {
-                            Rect r = extract(rectProto);
-                            if (r.contains(x, y)) {
-                                y = r.bottom;
-                                emptyRegionFound = false;
-                            }
-                        }
-                    }
-                    if (emptyRegionFound) {
-                        String reason = "Region to test: " + testRect
-                                + "\nfirst empty point: " + x + ", " + y;
-                        reason += "\nvisible regions:";
-                        for (Layer layer : layers) {
-                            if (layer.isInvisible() || layer.isHiddenByParent()) {
-                                continue;
-                            }
-                            Rect r = extract(layer.mProto.visibleRegion);
-                            reason += "\n" + layer.mProto.name + r.toString();
-                        }
-                        return new Result(false /* success */, this.mTimestamp, assertionName,
-                                reason);
-                    }
-                }
-            }
-            String info = "Region covered: " + testRect;
-            return new Result(true /* success */, this.mTimestamp, assertionName, info);
-        }
-
-        /**
-         * Checks if a layer with name {@code layerName} has a visible region
-         * {@code expectedVisibleRegion}.
-         */
-        public Result hasVisibleRegion(String layerName, Rect expectedVisibleRegion) {
-            String assertionName = "hasVisibleRegion";
-            String reason = "Could not find " + layerName;
-            for (Layer layer : asFlattenedLayers()) {
-                if (layer.mProto.name.contains(layerName)) {
-                    if (layer.isHiddenByParent()) {
-                        reason = layer.getHiddenByParentReason();
-                        continue;
-                    }
-                    if (layer.isInvisible()) {
-                        reason = layer.getVisibilityReason();
-                        continue;
-                    }
-                    Rect visibleRegion = extract(layer.mProto.visibleRegion);
-                    if (visibleRegion.equals(expectedVisibleRegion)) {
-                        return new Result(true /* success */, this.mTimestamp, assertionName,
-                                layer.mProto.name + "has visible region " + expectedVisibleRegion);
-                    }
-                    reason = layer.mProto.name + " has visible region:" + visibleRegion + " "
-                            + "expected:" + expectedVisibleRegion;
-                }
-            }
-            return new Result(false /* success */, this.mTimestamp, assertionName, reason);
-        }
-
-        /**
-         * Checks if a layer with name {@code layerName} is visible.
-         */
-        public Result isVisible(String layerName) {
-            String assertionName = "isVisible";
-            String reason = "Could not find " + layerName;
-            for (Layer layer : asFlattenedLayers()) {
-                if (layer.mProto.name.contains(layerName)) {
-                    if (layer.isHiddenByParent()) {
-                        reason = layer.getHiddenByParentReason();
-                        continue;
-                    }
-                    if (layer.isInvisible()) {
-                        reason = layer.getVisibilityReason();
-                        continue;
-                    }
-                    return new Result(true /* success */, this.mTimestamp, assertionName,
-                            layer.mProto.name + " is visible");
-                }
-            }
-            return new Result(false /* success */, this.mTimestamp, assertionName, reason);
-        }
-
-        @Override
-        public long getTimestamp() {
-            return mTimestamp;
-        }
-
-        public List<Layer> getRootLayers() {
-            return mRootLayers;
-        }
-
-        /**
-         * Returns all layers as a flattened list using a depth first traversal.
-         */
-        public List<Layer> asFlattenedLayers() {
-            if (mFlattenedLayers == null) {
-                mFlattenedLayers = new LinkedList<>();
-                ArrayList<Layer> pendingLayers = new ArrayList<>(this.mRootLayers);
-                while (!pendingLayers.isEmpty()) {
-                    Layer layer = pendingLayers.remove(0);
-                    mFlattenedLayers.add(layer);
-                    pendingLayers.addAll(0, layer.mChildren);
-                }
-            }
-            return mFlattenedLayers;
-        }
-
-        public Rect getVisibleBounds(String layerName) {
-            List<Layer> layers = asFlattenedLayers();
-            for (Layer layer : layers) {
-                if (layer.mProto.name.contains(layerName) && layer.isVisible()) {
-                    return extract(layer.mProto.visibleRegion);
-                }
-            }
-            return new Rect(0, 0, 0, 0);
-        }
-    }
-
-    /**
-     * Represents a single layer with links to its parent and child layers.
-     */
-    public static class Layer {
-        @Nullable
-        public LayerProto mProto;
-        public List<Layer> mChildren;
-        @Nullable
-        public Layer mParent = null;
-
-        private Layer(LayerProto proto) {
-            this.mProto = proto;
-            this.mChildren = new ArrayList<>();
-        }
-
-        private void addChild(Layer childLayer) {
-            this.mChildren.add(childLayer);
-        }
-
-        private void addParent(Layer parentLayer) {
-            this.mParent = parentLayer;
-        }
-
-        public int getId() {
-            return mProto.id;
-        }
-
-        public boolean isActiveBufferEmpty() {
-            return this.mProto.activeBuffer == null || this.mProto.activeBuffer.height == 0
-                    || this.mProto.activeBuffer.width == 0;
-        }
-
-        public boolean isVisibleRegionEmpty() {
-            if (this.mProto.visibleRegion == null) {
-                return true;
-            }
-            Rect visibleRect = Entry.extract(this.mProto.visibleRegion);
-            return visibleRect.height() == 0 || visibleRect.width() == 0;
-        }
-
-        public boolean isHidden() {
-            return (this.mProto.flags & /* FLAG_HIDDEN */ 0x1) != 0x0;
-        }
-
-        public boolean isVisible() {
-            return (!isActiveBufferEmpty() || isColorLayer())
-                    && !isHidden()
-                    && this.mProto.color != null
-                    && this.mProto.color.a > 0
-                    && !isVisibleRegionEmpty();
-        }
-
-        public boolean isColorLayer() {
-            return this.mProto.type.equals("ColorLayer");
-        }
-
-        public boolean isRootLayer() {
-            return mParent == null || mParent.mProto == null;
-        }
-
-        public boolean isInvisible() {
-            return !isVisible();
-        }
-
-        public boolean isHiddenByParent() {
-            return !isRootLayer() && (mParent.isHidden() || mParent.isHiddenByParent());
-        }
-
-        public String getHiddenByParentReason() {
-            String reason = "Layer " + mProto.name;
-            if (isHiddenByParent()) {
-                reason += " is hidden by parent: " + mParent.mProto.name;
-            } else {
-                reason += " is not hidden by parent: " + mParent.mProto.name;
-            }
-            return reason;
-        }
-
-        public String getVisibilityReason() {
-            String reason = "Layer " + mProto.name;
-            if (isVisible()) {
-                reason += " is visible:";
-            } else {
-                reason += " is invisible:";
-                if (this.mProto.activeBuffer == null) {
-                    reason += " activeBuffer=null";
-                } else if (this.mProto.activeBuffer.height == 0) {
-                    reason += " activeBuffer.height=0";
-                } else if (this.mProto.activeBuffer.width == 0) {
-                    reason += " activeBuffer.width=0";
-                }
-                if (!isColorLayer()) {
-                    reason += " type != ColorLayer";
-                }
-                if (isHidden()) {
-                    reason += " flags=" + this.mProto.flags + " (FLAG_HIDDEN set)";
-                }
-                if (this.mProto.color == null || this.mProto.color.a == 0) {
-                    reason += " color.a=0";
-                }
-                if (isVisibleRegionEmpty()) {
-                    reason += " visible region is empty";
-                }
-            }
-            return reason;
-        }
-    }
-}
\ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTraceSubject.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTraceSubject.java
deleted file mode 100644
index 4a5129e..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/LayersTraceSubject.java
+++ /dev/null
@@ -1,140 +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.flicker;
-
-import static com.google.common.truth.Truth.assertAbout;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.graphics.Rect;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.flicker.LayersTrace.Entry;
-import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
-
-import com.google.common.truth.FailureMetadata;
-import com.google.common.truth.Subject;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Truth subject for {@link LayersTrace} objects.
- */
-public class LayersTraceSubject extends Subject<LayersTraceSubject, LayersTrace> {
-    // Boiler-plate Subject.Factory for LayersTraceSubject
-    private static final Subject.Factory<LayersTraceSubject, LayersTrace> FACTORY =
-            new Subject.Factory<LayersTraceSubject, LayersTrace>() {
-                @Override
-                public LayersTraceSubject createSubject(
-                        FailureMetadata fm, @Nullable LayersTrace target) {
-                    return new LayersTraceSubject(fm, target);
-                }
-            };
-
-    private AssertionsChecker<Entry> mChecker = new AssertionsChecker<>();
-
-    private LayersTraceSubject(FailureMetadata fm, @Nullable LayersTrace subject) {
-        super(fm, subject);
-    }
-
-    // User-defined entry point
-    public static LayersTraceSubject assertThat(@Nullable LayersTrace entry) {
-        return assertAbout(FACTORY).that(entry);
-    }
-
-    // User-defined entry point
-    public static LayersTraceSubject assertThat(@Nullable TransitionResult result) {
-        LayersTrace entries = LayersTrace.parseFrom(result.getLayersTrace(),
-                result.getLayersTracePath());
-        return assertWithMessage(result.toString()).about(FACTORY).that(entries);
-    }
-
-    // Static method for getting the subject factory (for use with assertAbout())
-    public static Subject.Factory<LayersTraceSubject, LayersTrace> entries() {
-        return FACTORY;
-    }
-
-    public void forAllEntries() {
-        test();
-    }
-
-    public void forRange(long startTime, long endTime) {
-        mChecker.filterByRange(startTime, endTime);
-        test();
-    }
-
-    public LayersTraceSubject then() {
-        mChecker.checkChangingAssertions();
-        return this;
-    }
-
-    public void inTheBeginning() {
-        if (getSubject().getEntries().isEmpty()) {
-            fail("No entries found.");
-        }
-        mChecker.checkFirstEntry();
-        test();
-    }
-
-    public void atTheEnd() {
-        if (getSubject().getEntries().isEmpty()) {
-            fail("No entries found.");
-        }
-        mChecker.checkLastEntry();
-        test();
-    }
-
-    private void test() {
-        List<Result> failures = mChecker.test(getSubject().getEntries());
-        if (!failures.isEmpty()) {
-            String failureLogs = failures.stream().map(Result::toString)
-                    .collect(Collectors.joining("\n"));
-            String tracePath = "";
-            if (getSubject().getSource().isPresent()) {
-                tracePath = "\nLayers Trace can be found in: "
-                        + getSubject().getSource().get().toAbsolutePath() + "\n";
-            }
-            fail(tracePath + failureLogs);
-        }
-    }
-
-    public LayersTraceSubject coversRegion(Rect rect) {
-        mChecker.add(entry -> entry.coversRegion(rect),
-                "coversRegion(" + rect + ")");
-        return this;
-    }
-
-    public LayersTraceSubject hasVisibleRegion(String layerName, Rect size) {
-        mChecker.add(entry -> entry.hasVisibleRegion(layerName, size),
-                "hasVisibleRegion(" + layerName + size + ")");
-        return this;
-    }
-
-    public LayersTraceSubject showsLayer(String layerName) {
-        mChecker.add(entry -> entry.isVisible(layerName),
-                "showsLayer(" + layerName + ")");
-        return this;
-    }
-
-    public LayersTraceSubject hidesLayer(String layerName) {
-        mChecker.add(entry -> entry.isVisible(layerName).negate(),
-                "hidesLayer(" + layerName + ")");
-        return this;
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/TransitionRunner.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/TransitionRunner.java
deleted file mode 100644
index 241a1c0..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/TransitionRunner.java
+++ /dev/null
@@ -1,433 +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.flicker;
-
-import static com.android.server.wm.flicker.monitor.ITransitionMonitor.OUTPUT_DIR;
-
-import android.util.Log;
-
-import androidx.annotation.Nullable;
-import androidx.annotation.VisibleForTesting;
-import androidx.test.InstrumentationRegistry;
-
-import com.android.server.wm.flicker.monitor.ITransitionMonitor;
-import com.android.server.wm.flicker.monitor.LayersTraceMonitor;
-import com.android.server.wm.flicker.monitor.ScreenRecorder;
-import com.android.server.wm.flicker.monitor.WindowAnimationFrameStatsMonitor;
-import com.android.server.wm.flicker.monitor.WindowManagerTraceMonitor;
-
-import com.google.common.io.Files;
-
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * Builds and runs UI transitions capturing test artifacts.
- *
- * User can compose a transition from simpler steps, specifying setup and teardown steps. During
- * a transition, Layers trace, WindowManager trace, screen recordings and window animation frame
- * stats can be captured.
- *
- * <pre>
- * Transition builder options:
- *  {@link TransitionBuilder#run(Runnable)} run transition under test. Monitors will be started
- *  before the transition and stopped after the transition is completed.
- *  {@link TransitionBuilder#repeat(int)} repeat transitions under test multiple times recording
- *  result for each run.
- *  {@link TransitionBuilder#withTag(String)} specify a string identifier used to prefix logs and
- *  artifacts generated.
- *  {@link TransitionBuilder#runBeforeAll(Runnable)} run setup transitions once before all other
- *  transition are run to set up an initial state on device.
- *  {@link TransitionBuilder#runBefore(Runnable)} run setup transitions before each test transition
- *  run.
- *  {@link TransitionBuilder#runAfter(Runnable)} run teardown transitions after each test
- *  transition.
- *  {@link TransitionBuilder#runAfter(Runnable)} run teardown transitions once after all
- *  other transition  are run.
- *  {@link TransitionBuilder#includeJankyRuns()} disables {@link WindowAnimationFrameStatsMonitor}
- *  to monitor janky frames. If janky frames are detected, then the test run is skipped. This
- *  monitor is enabled by default.
- *  {@link TransitionBuilder#skipLayersTrace()} disables {@link LayersTraceMonitor} used to
- *  capture Layers trace during a transition. This monitor is enabled by default.
- *  {@link TransitionBuilder#skipWindowManagerTrace()} disables {@link WindowManagerTraceMonitor}
- *  used to capture WindowManager trace during a transition. This monitor is enabled by
- *  default.
- *  {@link TransitionBuilder#recordAllRuns()} records the screen contents and saves it to a file.
- *  All the runs including setup and teardown transitions are included in the recording. This
- *  monitor is used for debugging purposes.
- *  {@link TransitionBuilder#recordEachRun()} records the screen contents during test transitions
- *  and saves it to a file for each run. This monitor is used for debugging purposes.
- *
- * Example transition to capture WindowManager and Layers trace when opening a test app:
- * {@code
- * TransitionRunner.newBuilder()
- *      .withTag("OpenTestAppFast")
- *      .runBeforeAll(UiAutomationLib::wakeUp)
- *      .runBeforeAll(UiAutomationLib::UnlockDevice)
- *      .runBeforeAll(UiAutomationLib::openTestApp)
- *      .runBefore(UiAutomationLib::closeTestApp)
- *      .run(UiAutomationLib::openTestApp)
- *      .runAfterAll(UiAutomationLib::closeTestApp)
- *      .repeat(5)
- *      .build()
- *      .run();
- * }
- * </pre>
- */
-public class TransitionRunner {
-    private static final String TAG = "FLICKER";
-    private final ScreenRecorder mScreenRecorder;
-    private final WindowManagerTraceMonitor mWmTraceMonitor;
-    private final LayersTraceMonitor mLayersTraceMonitor;
-    private final WindowAnimationFrameStatsMonitor mFrameStatsMonitor;
-
-    private final List<ITransitionMonitor> mAllRunsMonitors;
-    private final List<ITransitionMonitor> mPerRunMonitors;
-    private final List<Runnable> mBeforeAlls;
-    private final List<Runnable> mBefores;
-    private final List<Runnable> mTransitions;
-    private final List<Runnable> mAfters;
-    private final List<Runnable> mAfterAlls;
-
-    private final int mIterations;
-    private final String mTestTag;
-
-    @Nullable
-    private List<TransitionResult> mResults = null;
-
-    private TransitionRunner(TransitionBuilder builder) {
-        mScreenRecorder = builder.mScreenRecorder;
-        mWmTraceMonitor = builder.mWmTraceMonitor;
-        mLayersTraceMonitor = builder.mLayersTraceMonitor;
-        mFrameStatsMonitor = builder.mFrameStatsMonitor;
-
-        mAllRunsMonitors = builder.mAllRunsMonitors;
-        mPerRunMonitors = builder.mPerRunMonitors;
-        mBeforeAlls = builder.mBeforeAlls;
-        mBefores = builder.mBefores;
-        mTransitions = builder.mTransitions;
-        mAfters = builder.mAfters;
-        mAfterAlls = builder.mAfterAlls;
-
-        mIterations = builder.mIterations;
-        mTestTag = builder.mTestTag;
-    }
-
-    public static TransitionBuilder newBuilder() {
-        return newBuilder(OUTPUT_DIR.toString());
-    }
-
-    public static TransitionBuilder newBuilder(String outputDir) {
-        return new TransitionBuilder(outputDir);
-    }
-
-    /**
-     * Runs the composed transition and calls monitors at the appropriate stages. If jank monitor
-     * is enabled, transitions with jank are skipped.
-     *
-     * @return itself
-     */
-    public TransitionRunner run() {
-        mResults = new ArrayList<>();
-        mAllRunsMonitors.forEach(ITransitionMonitor::start);
-        mBeforeAlls.forEach(Runnable::run);
-        for (int iteration = 0; iteration < mIterations; iteration++) {
-            mBefores.forEach(Runnable::run);
-            mPerRunMonitors.forEach(ITransitionMonitor::start);
-            mTransitions.forEach(Runnable::run);
-            mPerRunMonitors.forEach(ITransitionMonitor::stop);
-            mAfters.forEach(Runnable::run);
-            if (runJankFree() && mFrameStatsMonitor.jankyFramesDetected()) {
-                String msg = String.format("Skipping iteration %d/%d for test %s due to jank. %s",
-                        iteration, mIterations - 1, mTestTag, mFrameStatsMonitor.toString());
-                Log.e(TAG, msg);
-                continue;
-            }
-            mResults.add(saveResult(iteration));
-        }
-        mAfterAlls.forEach(Runnable::run);
-        mAllRunsMonitors.forEach(monitor -> {
-            monitor.stop();
-            monitor.save(mTestTag);
-        });
-        return this;
-    }
-
-    /**
-     * Returns a list of transition results.
-     *
-     * @return list of transition results.
-     */
-    public List<TransitionResult> getResults() {
-        if (mResults == null) {
-            throw new IllegalStateException("Results do not exist!");
-        }
-        return mResults;
-    }
-
-    /**
-     * Deletes all transition results that are not marked for saving.
-     *
-     * @return list of transition results.
-     */
-    public void deleteResults() {
-        if (mResults == null) {
-            return;
-        }
-        mResults.stream()
-                .filter(TransitionResult::canDelete)
-                .forEach(TransitionResult::delete);
-        mResults = null;
-    }
-
-    /**
-     * Saves monitor results to file.
-     *
-     * @return object containing paths to test artifacts
-     */
-    private TransitionResult saveResult(int iteration) {
-        Path windowTrace = null;
-        Path layerTrace = null;
-        Path screenCaptureVideo = null;
-
-        if (mPerRunMonitors.contains(mWmTraceMonitor)) {
-            windowTrace = mWmTraceMonitor.save(mTestTag, iteration);
-        }
-        if (mPerRunMonitors.contains(mLayersTraceMonitor)) {
-            layerTrace = mLayersTraceMonitor.save(mTestTag, iteration);
-        }
-        if (mPerRunMonitors.contains(mScreenRecorder)) {
-            screenCaptureVideo = mScreenRecorder.save(mTestTag, iteration);
-        }
-        return new TransitionResult(layerTrace, windowTrace, screenCaptureVideo);
-    }
-
-    private boolean runJankFree() {
-        return mPerRunMonitors.contains(mFrameStatsMonitor);
-    }
-
-    public String getTestTag() {
-        return mTestTag;
-    }
-
-    /**
-     * Stores paths to all test artifacts.
-     */
-    @VisibleForTesting
-    public static class TransitionResult {
-        @Nullable
-        public final Path layersTrace;
-        @Nullable
-        public final Path windowManagerTrace;
-        @Nullable
-        public final Path screenCaptureVideo;
-        private boolean flaggedForSaving;
-
-        public TransitionResult(@Nullable Path layersTrace, @Nullable Path windowManagerTrace,
-                @Nullable Path screenCaptureVideo) {
-            this.layersTrace = layersTrace;
-            this.windowManagerTrace = windowManagerTrace;
-            this.screenCaptureVideo = screenCaptureVideo;
-        }
-
-        public void flagForSaving() {
-            flaggedForSaving = true;
-        }
-
-        public boolean canDelete() {
-            return !flaggedForSaving;
-        }
-
-        public boolean layersTraceExists() {
-            return layersTrace != null && layersTrace.toFile().exists();
-        }
-
-        public byte[] getLayersTrace() {
-            try {
-                return Files.toByteArray(this.layersTrace.toFile());
-            } catch (IOException e) {
-                throw new RuntimeException(e);
-            }
-        }
-
-        public Path getLayersTracePath() {
-            return layersTrace;
-        }
-
-        public boolean windowManagerTraceExists() {
-            return windowManagerTrace != null && windowManagerTrace.toFile().exists();
-        }
-
-        public byte[] getWindowManagerTrace() {
-            try {
-                return Files.toByteArray(this.windowManagerTrace.toFile());
-            } catch (IOException e) {
-                throw new RuntimeException(e);
-            }
-        }
-
-        public Path getWindowManagerTracePath() {
-            return windowManagerTrace;
-        }
-
-        public boolean screenCaptureVideoExists() {
-            return screenCaptureVideo != null && screenCaptureVideo.toFile().exists();
-        }
-
-        public Path screenCaptureVideoPath() {
-            return screenCaptureVideo;
-        }
-
-        public void delete() {
-            if (layersTraceExists()) layersTrace.toFile().delete();
-            if (windowManagerTraceExists()) windowManagerTrace.toFile().delete();
-            if (screenCaptureVideoExists()) screenCaptureVideo.toFile().delete();
-        }
-    }
-
-    /**
-     * Builds a {@link TransitionRunner} instance.
-     */
-    public static class TransitionBuilder {
-        private ScreenRecorder mScreenRecorder;
-        private WindowManagerTraceMonitor mWmTraceMonitor;
-        private LayersTraceMonitor mLayersTraceMonitor;
-        private WindowAnimationFrameStatsMonitor mFrameStatsMonitor;
-
-        private List<ITransitionMonitor> mAllRunsMonitors = new LinkedList<>();
-        private List<ITransitionMonitor> mPerRunMonitors = new LinkedList<>();
-        private List<Runnable> mBeforeAlls = new LinkedList<>();
-        private List<Runnable> mBefores = new LinkedList<>();
-        private List<Runnable> mTransitions = new LinkedList<>();
-        private List<Runnable> mAfters = new LinkedList<>();
-        private List<Runnable> mAfterAlls = new LinkedList<>();
-
-        private boolean mRunJankFree = true;
-        private boolean mCaptureWindowManagerTrace = true;
-        private boolean mCaptureLayersTrace = true;
-        private boolean mRecordEachRun = false;
-        private int mIterations = 1;
-        private String mTestTag = "";
-
-        private boolean mRecordAllRuns = false;
-
-        public TransitionBuilder(String outputDir) {
-            mScreenRecorder = new ScreenRecorder();
-            mWmTraceMonitor = new WindowManagerTraceMonitor(outputDir);
-            mLayersTraceMonitor = new LayersTraceMonitor(outputDir);
-            mFrameStatsMonitor = new
-                    WindowAnimationFrameStatsMonitor(InstrumentationRegistry.getInstrumentation());
-        }
-
-        public TransitionRunner build() {
-            if (mCaptureWindowManagerTrace) {
-                mPerRunMonitors.add(mWmTraceMonitor);
-            }
-
-            if (mCaptureLayersTrace) {
-                mPerRunMonitors.add(mLayersTraceMonitor);
-            }
-
-            if (mRunJankFree) {
-                mPerRunMonitors.add(mFrameStatsMonitor);
-            }
-
-            if (mRecordAllRuns) {
-                mAllRunsMonitors.add(mScreenRecorder);
-            }
-
-            if (mRecordEachRun) {
-                mPerRunMonitors.add(mScreenRecorder);
-            }
-
-            return new TransitionRunner(this);
-        }
-
-        public TransitionBuilder runBeforeAll(Runnable runnable) {
-            mBeforeAlls.add(runnable);
-            return this;
-        }
-
-        public TransitionBuilder runBefore(Runnable runnable) {
-            mBefores.add(runnable);
-            return this;
-        }
-
-        public TransitionBuilder run(Runnable runnable) {
-            mTransitions.add(runnable);
-            return this;
-        }
-
-        public TransitionBuilder runAfter(Runnable runnable) {
-            mAfters.add(runnable);
-            return this;
-        }
-
-        public TransitionBuilder runAfterAll(Runnable runnable) {
-            mAfterAlls.add(runnable);
-            return this;
-        }
-
-        public TransitionBuilder repeat(int iterations) {
-            mIterations = iterations;
-            return this;
-        }
-
-        public TransitionBuilder skipWindowManagerTrace() {
-            mCaptureWindowManagerTrace = false;
-            return this;
-        }
-
-        public TransitionBuilder skipLayersTrace() {
-            mCaptureLayersTrace = false;
-            return this;
-        }
-
-        public TransitionBuilder includeJankyRuns() {
-            mRunJankFree = false;
-            return this;
-        }
-
-        public TransitionBuilder recordEachRun() {
-            if (mRecordAllRuns) {
-                throw new IllegalArgumentException("Invalid option with recordAllRuns");
-            }
-            mRecordEachRun = true;
-            return this;
-        }
-
-        public TransitionBuilder recordAllRuns() {
-            if (mRecordEachRun) {
-                throw new IllegalArgumentException("Invalid option with recordEachRun");
-            }
-            mRecordAllRuns = true;
-            return this;
-        }
-
-        public TransitionBuilder withTag(String testTag) {
-            if (testTag.contains(" ")) {
-                throw new IllegalArgumentException("The test tag can not contain spaces since it "
-                        + "is a part of the file name");
-            }
-            mTestTag = testTag;
-            return this;
-        }
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowManagerTrace.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowManagerTrace.java
deleted file mode 100644
index 412e72d8..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowManagerTrace.java
+++ /dev/null
@@ -1,240 +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.flicker;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.nano.AppWindowTokenProto;
-import com.android.server.wm.nano.StackProto;
-import com.android.server.wm.nano.TaskProto;
-import com.android.server.wm.nano.WindowManagerTraceFileProto;
-import com.android.server.wm.nano.WindowManagerTraceProto;
-import com.android.server.wm.nano.WindowStateProto;
-import com.android.server.wm.nano.WindowTokenProto;
-
-import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
-
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-
-/**
- * Contains a collection of parsed WindowManager trace entries and assertions to apply over
- * a single entry.
- *
- * Each entry is parsed into a list of {@link WindowManagerTrace.Entry} objects.
- */
-public class WindowManagerTrace {
-    private static final int DEFAULT_DISPLAY = 0;
-    private final List<Entry> mEntries;
-    @Nullable
-    final private Path mSource;
-
-    private WindowManagerTrace(List<Entry> entries, Path source) {
-        this.mEntries = entries;
-        this.mSource = source;
-    }
-
-    /**
-     * Parses {@code WindowManagerTraceFileProto} from {@code data} and uses the proto to
-     * generates a list of trace entries.
-     *
-     * @param data   binary proto data
-     * @param source Path to source of data for additional debug information
-     */
-    public static WindowManagerTrace parseFrom(byte[] data, Path source) {
-        List<Entry> entries = new ArrayList<>();
-
-        WindowManagerTraceFileProto fileProto;
-        try {
-            fileProto = WindowManagerTraceFileProto.parseFrom(data);
-        } catch (InvalidProtocolBufferNanoException e) {
-            throw new RuntimeException(e);
-        }
-        for (WindowManagerTraceProto entryProto : fileProto.entry) {
-            entries.add(new Entry(entryProto));
-        }
-        return new WindowManagerTrace(entries, source);
-    }
-
-    public static WindowManagerTrace parseFrom(byte[] data) {
-        return parseFrom(data, null);
-    }
-
-    public List<Entry> getEntries() {
-        return mEntries;
-    }
-
-    public Entry getEntry(long timestamp) {
-        Optional<Entry> entry = mEntries.stream()
-                .filter(e -> e.getTimestamp() == timestamp)
-                .findFirst();
-        if (!entry.isPresent()) {
-            throw new RuntimeException("Entry does not exist for timestamp " + timestamp);
-        }
-        return entry.get();
-    }
-
-    public Optional<Path> getSource() {
-        return Optional.ofNullable(mSource);
-    }
-
-    /**
-     * Represents a single WindowManager trace entry.
-     */
-    public static class Entry implements ITraceEntry {
-        private final WindowManagerTraceProto mProto;
-
-        public Entry(WindowManagerTraceProto proto) {
-            mProto = proto;
-        }
-
-        private static Result isWindowVisible(String windowTitle,
-                WindowTokenProto[] windowTokenProtos) {
-            boolean titleFound = false;
-            for (WindowTokenProto windowToken : windowTokenProtos) {
-                for (WindowStateProto windowState : windowToken.windows) {
-                    if (windowState.identifier.title.contains(windowTitle)) {
-                        titleFound = true;
-                        if (isVisible(windowState)) {
-                            return new Result(true /* success */,
-                                    windowState.identifier.title + " is visible");
-                        }
-                    }
-                }
-            }
-
-            String reason;
-            if (!titleFound) {
-                reason = windowTitle + " cannot be found";
-            } else {
-                reason = windowTitle + " is invisible";
-            }
-            return new Result(false /* success */, reason);
-        }
-
-        private static boolean isVisible(WindowStateProto windowState) {
-            return windowState.windowContainer.visible;
-        }
-
-        @Override
-        public long getTimestamp() {
-            return mProto.elapsedRealtimeNanos;
-        }
-
-        /**
-         * Returns window title of the top most visible app window.
-         */
-        private String getTopVisibleAppWindow() {
-            StackProto[] stacks = mProto.windowManagerService.rootWindowContainer
-                    .displays[DEFAULT_DISPLAY].stacks;
-            for (StackProto stack : stacks) {
-                for (TaskProto task : stack.tasks) {
-                    for (AppWindowTokenProto token : task.appWindowTokens) {
-                        for (WindowStateProto windowState : token.windowToken.windows) {
-                            if (windowState.windowContainer.visible) {
-                                return task.appWindowTokens[0].name;
-                            }
-                        }
-                    }
-                }
-            }
-
-            return "";
-        }
-
-        /**
-         * Checks if aboveAppWindow with {@code windowTitle} is visible.
-         */
-        public Result isAboveAppWindowVisible(String windowTitle) {
-            WindowTokenProto[] windowTokenProtos = mProto.windowManagerService
-                    .rootWindowContainer
-                    .displays[DEFAULT_DISPLAY].aboveAppWindows;
-            Result result = isWindowVisible(windowTitle, windowTokenProtos);
-            return new Result(result.success, getTimestamp(), "showsAboveAppWindow", result.reason);
-        }
-
-        /**
-         * Checks if belowAppWindow with {@code windowTitle} is visible.
-         */
-        public Result isBelowAppWindowVisible(String windowTitle) {
-            WindowTokenProto[] windowTokenProtos = mProto.windowManagerService
-                    .rootWindowContainer
-                    .displays[DEFAULT_DISPLAY].belowAppWindows;
-            Result result = isWindowVisible(windowTitle, windowTokenProtos);
-            return new Result(result.success, getTimestamp(), "isBelowAppWindowVisible",
-                    result.reason);
-        }
-
-        /**
-         * Checks if imeWindow with {@code windowTitle} is visible.
-         */
-        public Result isImeWindowVisible(String windowTitle) {
-            WindowTokenProto[] windowTokenProtos = mProto.windowManagerService
-                    .rootWindowContainer
-                    .displays[DEFAULT_DISPLAY].imeWindows;
-            Result result = isWindowVisible(windowTitle, windowTokenProtos);
-            return new Result(result.success, getTimestamp(), "isImeWindowVisible",
-                    result.reason);
-        }
-
-        /**
-         * Checks if app window with {@code windowTitle} is on top.
-         */
-        public Result isVisibleAppWindowOnTop(String windowTitle) {
-            String topAppWindow = getTopVisibleAppWindow();
-            boolean success = topAppWindow.contains(windowTitle);
-            String reason = "wanted=" + windowTitle + " found=" + topAppWindow;
-            return new Result(success, getTimestamp(), "isAppWindowOnTop", reason);
-        }
-
-        /**
-         * Checks if app window with {@code windowTitle} is visible.
-         */
-        public Result isAppWindowVisible(String windowTitle) {
-            final String assertionName = "isAppWindowVisible";
-            boolean titleFound = false;
-            StackProto[] stacks = mProto.windowManagerService.rootWindowContainer
-                    .displays[DEFAULT_DISPLAY].stacks;
-            for (StackProto stack : stacks) {
-                for (TaskProto task : stack.tasks) {
-                    for (AppWindowTokenProto token : task.appWindowTokens) {
-                        if (token.name.contains(windowTitle)) {
-                            titleFound = true;
-                            for (WindowStateProto windowState : token.windowToken.windows) {
-                                if (windowState.windowContainer.visible) {
-                                    return new Result(true /* success */, getTimestamp(),
-                                            assertionName, "Window " + token.name +
-                                            "is visible");
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-            String reason;
-            if (!titleFound) {
-                reason = "Window " + windowTitle + " cannot be found";
-            } else {
-                reason = "Window " + windowTitle + " is invisible";
-            }
-            return new Result(false /* success */, getTimestamp(), assertionName, reason);
-        }
-    }
-}
\ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowUtils.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowUtils.java
deleted file mode 100644
index 3d25fbe..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WindowUtils.java
+++ /dev/null
@@ -1,144 +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.flicker;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.view.Surface;
-import android.view.WindowManager;
-
-import androidx.test.InstrumentationRegistry;
-
-/**
- * Helper functions to retrieve system window sizes and positions.
- */
-public class WindowUtils {
-
-    public static Rect getDisplayBounds() {
-        Point display = new Point();
-        WindowManager wm =
-                (WindowManager) InstrumentationRegistry.getContext().getSystemService(
-                        Context.WINDOW_SERVICE);
-        wm.getDefaultDisplay().getRealSize(display);
-        return new Rect(0, 0, display.x, display.y);
-    }
-
-    private static int getCurrentRotation() {
-        WindowManager wm =
-                (WindowManager) InstrumentationRegistry.getContext().getSystemService(
-                        Context.WINDOW_SERVICE);
-        return wm.getDefaultDisplay().getRotation();
-    }
-
-    public static Rect getDisplayBounds(int requestedRotation) {
-        Rect displayBounds = getDisplayBounds();
-        int currentDisplayRotation = getCurrentRotation();
-
-        boolean displayIsRotated = (currentDisplayRotation == Surface.ROTATION_90 ||
-                currentDisplayRotation == Surface.ROTATION_270);
-
-        boolean requestedDisplayIsRotated = requestedRotation == Surface.ROTATION_90 ||
-                requestedRotation == Surface.ROTATION_270;
-
-        // if the current orientation changes with the requested rotation,
-        // flip height and width of display bounds.
-        if (displayIsRotated != requestedDisplayIsRotated) {
-            return new Rect(0, 0, displayBounds.height(), displayBounds.width());
-        }
-
-        return new Rect(0, 0, displayBounds.width(), displayBounds.height());
-    }
-
-
-    public static Rect getAppPosition(int requestedRotation) {
-        Rect displayBounds = getDisplayBounds();
-        int currentDisplayRotation = getCurrentRotation();
-
-        boolean displayIsRotated = currentDisplayRotation == Surface.ROTATION_90 ||
-                currentDisplayRotation == Surface.ROTATION_270;
-
-        boolean requestedAppIsRotated = requestedRotation == Surface.ROTATION_90 ||
-                requestedRotation == Surface.ROTATION_270;
-
-        // display size will change if the display is reflected. Flip height and width of app if the
-        // requested rotation is different from the current rotation.
-        if (displayIsRotated != requestedAppIsRotated) {
-            return new Rect(0, 0, displayBounds.height(), displayBounds.width());
-        }
-
-        return new Rect(0, 0, displayBounds.width(), displayBounds.height());
-    }
-
-    public static Rect getStatusBarPosition(int requestedRotation) {
-        Resources resources = InstrumentationRegistry.getContext().getResources();
-        String resourceName;
-        Rect displayBounds = getDisplayBounds();
-        int width;
-        if (requestedRotation == Surface.ROTATION_0 || requestedRotation == Surface.ROTATION_180) {
-            resourceName = "status_bar_height_portrait";
-            width = Math.min(displayBounds.width(), displayBounds.height());
-        } else {
-            resourceName = "status_bar_height_landscape";
-            width = Math.max(displayBounds.width(), displayBounds.height());
-        }
-
-        int resourceId = resources.getIdentifier(resourceName, "dimen", "android");
-        int height = resources.getDimensionPixelSize(resourceId);
-
-        return new Rect(0, 0, width, height);
-    }
-
-    public static Rect getNavigationBarPosition(int requestedRotation) {
-        Resources resources = InstrumentationRegistry.getContext().getResources();
-        Rect displayBounds = getDisplayBounds();
-        int displayWidth = Math.min(displayBounds.width(), displayBounds.height());
-        int displayHeight = Math.max(displayBounds.width(), displayBounds.height());
-        int resourceId;
-        if (requestedRotation == Surface.ROTATION_0 || requestedRotation == Surface.ROTATION_180) {
-            resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
-            int height = resources.getDimensionPixelSize(resourceId);
-            return new Rect(0, displayHeight - height, displayWidth, displayHeight);
-        } else {
-            resourceId = resources.getIdentifier("navigation_bar_width", "dimen", "android");
-            int width = resources.getDimensionPixelSize(resourceId);
-            // swap display dimensions in landscape or seascape mode
-            int temp = displayHeight;
-            displayHeight = displayWidth;
-            displayWidth = temp;
-            if (requestedRotation == Surface.ROTATION_90) {
-                return new Rect(0, 0, width, displayHeight);
-            } else {
-                return new Rect(displayWidth - width, 0, displayWidth, displayHeight);
-            }
-        }
-    }
-
-    public static int getNavigationBarHeight() {
-        Resources resources = InstrumentationRegistry.getContext().getResources();
-        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
-        return resources.getDimensionPixelSize(resourceId);
-    }
-
-    public static int getDockedStackDividerInset() {
-        Resources resources = InstrumentationRegistry.getContext().getResources();
-        int resourceId = resources.getIdentifier("docked_stack_divider_insets", "dimen",
-                "android");
-        return resources.getDimensionPixelSize(resourceId);
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WmTraceSubject.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WmTraceSubject.java
deleted file mode 100644
index 064cc27..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/WmTraceSubject.java
+++ /dev/null
@@ -1,192 +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.flicker;
-
-import static com.google.common.truth.Truth.assertAbout;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import androidx.annotation.Nullable;
-
-import com.android.server.wm.flicker.Assertions.Result;
-import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
-
-import com.google.common.truth.FailureMetadata;
-import com.google.common.truth.Subject;
-
-import java.nio.file.Path;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-/**
- * Truth subject for {@link WindowManagerTrace} objects.
- */
-public class WmTraceSubject extends Subject<WmTraceSubject, WindowManagerTrace> {
-    // Boiler-plate Subject.Factory for WmTraceSubject
-    private static final Subject.Factory<WmTraceSubject, WindowManagerTrace> FACTORY =
-            new Subject.Factory<WmTraceSubject, WindowManagerTrace>() {
-                @Override
-                public WmTraceSubject createSubject(
-                        FailureMetadata fm, @Nullable WindowManagerTrace target) {
-                    return new WmTraceSubject(fm, target);
-                }
-            };
-
-    private AssertionsChecker<WindowManagerTrace.Entry> mChecker = new AssertionsChecker<>();
-
-    private WmTraceSubject(FailureMetadata fm, @Nullable WindowManagerTrace subject) {
-        super(fm, subject);
-    }
-
-    // User-defined entry point
-    public static WmTraceSubject assertThat(@Nullable WindowManagerTrace entry) {
-        return assertAbout(FACTORY).that(entry);
-    }
-
-    // User-defined entry point
-    public static WmTraceSubject assertThat(@Nullable TransitionResult result) {
-        WindowManagerTrace entries = WindowManagerTrace.parseFrom(result.getWindowManagerTrace(),
-                result.getWindowManagerTracePath());
-        return assertWithMessage(result.toString()).about(FACTORY).that(entries);
-    }
-
-    // Static method for getting the subject factory (for use with assertAbout())
-    public static Subject.Factory<WmTraceSubject, WindowManagerTrace> entries() {
-        return FACTORY;
-    }
-
-    public void forAllEntries() {
-        test();
-    }
-
-    public void forRange(long startTime, long endTime) {
-        mChecker.filterByRange(startTime, endTime);
-        test();
-    }
-
-    public WmTraceSubject then() {
-        mChecker.checkChangingAssertions();
-        return this;
-    }
-
-    public void inTheBeginning() {
-        if (getSubject().getEntries().isEmpty()) {
-            fail("No entries found.");
-        }
-        mChecker.checkFirstEntry();
-        test();
-    }
-
-    public void atTheEnd() {
-        if (getSubject().getEntries().isEmpty()) {
-            fail("No entries found.");
-        }
-        mChecker.checkLastEntry();
-        test();
-    }
-
-    private void test() {
-        List<Result> failures = mChecker.test(getSubject().getEntries());
-        if (!failures.isEmpty()) {
-            Optional<Path> failureTracePath = getSubject().getSource();
-            String failureLogs = failures.stream().map(Result::toString)
-                    .collect(Collectors.joining("\n"));
-            String tracePath = "";
-            if (failureTracePath.isPresent()) {
-                tracePath = "\nWindowManager Trace can be found in: "
-                        + failureTracePath.get().toAbsolutePath() + "\n";
-            }
-            fail(tracePath + failureLogs);
-        }
-    }
-
-    public WmTraceSubject showsAboveAppWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isAboveAppWindowVisible(partialWindowTitle),
-                "showsAboveAppWindow(" + partialWindowTitle + ")");
-        return this;
-    }
-
-    public WmTraceSubject hidesAboveAppWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isAboveAppWindowVisible(partialWindowTitle).negate(),
-                "hidesAboveAppWindow" + "(" + partialWindowTitle + ")");
-        return this;
-    }
-
-    public WmTraceSubject showsBelowAppWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isBelowAppWindowVisible(partialWindowTitle),
-                "showsBelowAppWindow(" + partialWindowTitle + ")");
-        return this;
-    }
-
-    public WmTraceSubject hidesBelowAppWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isBelowAppWindowVisible(partialWindowTitle).negate(),
-                "hidesBelowAppWindow" + "(" + partialWindowTitle + ")");
-        return this;
-    }
-
-    public WmTraceSubject showsImeWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isImeWindowVisible(partialWindowTitle),
-                "showsBelowAppWindow(" + partialWindowTitle + ")");
-        return this;
-    }
-
-    public WmTraceSubject hidesImeWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isImeWindowVisible(partialWindowTitle).negate(),
-                "hidesImeWindow" + "(" + partialWindowTitle + ")");
-        return this;
-    }
-
-    public WmTraceSubject showsAppWindowOnTop(String partialWindowTitle) {
-        mChecker.add(
-                entry -> {
-                    Result result = entry.isAppWindowVisible(partialWindowTitle);
-                    if (result.passed()) {
-                        result = entry.isVisibleAppWindowOnTop(partialWindowTitle);
-                    }
-                    return result;
-                },
-                "showsAppWindowOnTop(" + partialWindowTitle + ")"
-        );
-        return this;
-    }
-
-    public WmTraceSubject hidesAppWindowOnTop(String partialWindowTitle) {
-        mChecker.add(
-                entry -> {
-                    Result result = entry.isAppWindowVisible(partialWindowTitle).negate();
-                    if (result.failed()) {
-                        result = entry.isVisibleAppWindowOnTop(partialWindowTitle).negate();
-                    }
-                    return result;
-                },
-                "hidesAppWindowOnTop(" + partialWindowTitle + ")"
-        );
-        return this;
-    }
-
-    public WmTraceSubject showsAppWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isAppWindowVisible(partialWindowTitle),
-                "showsAppWindow(" + partialWindowTitle + ")");
-        return this;
-    }
-
-    public WmTraceSubject hidesAppWindow(String partialWindowTitle) {
-        mChecker.add(entry -> entry.isAppWindowVisible(partialWindowTitle).negate(),
-                "hidesAppWindow(" + partialWindowTitle + ")");
-        return this;
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/helpers/AutomationUtils.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/helpers/AutomationUtils.java
deleted file mode 100644
index 6821ff0..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/helpers/AutomationUtils.java
+++ /dev/null
@@ -1,263 +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.flicker.helpers;
-
-import static android.os.SystemClock.sleep;
-import static android.system.helpers.OverviewHelper.isRecentsInLauncher;
-import static android.view.Surface.ROTATION_0;
-
-import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.os.RemoteException;
-import android.support.test.launcherhelper.LauncherStrategyFactory;
-import android.support.test.uiautomator.By;
-import android.support.test.uiautomator.BySelector;
-import android.support.test.uiautomator.Configurator;
-import android.support.test.uiautomator.UiDevice;
-import android.support.test.uiautomator.UiObject2;
-import android.support.test.uiautomator.Until;
-import android.util.Log;
-import android.util.Rational;
-import android.view.View;
-import android.view.ViewConfiguration;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.android.server.wm.flicker.WindowUtils;
-
-/**
- * Collection of UI Automation helper functions.
- */
-public class AutomationUtils {
-    private static final String SYSTEMUI_PACKAGE = "com.android.systemui";
-    private static final long FIND_TIMEOUT = 10000;
-    private static final long LONG_PRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout() * 2L;
-    private static final String TAG = "FLICKER";
-
-    public static void wakeUpAndGoToHomeScreen() {
-        UiDevice device = UiDevice.getInstance(InstrumentationRegistry
-                .getInstrumentation());
-        try {
-            device.wakeUp();
-        } catch (RemoteException e) {
-            throw new RuntimeException(e);
-        }
-        device.pressHome();
-    }
-
-    /**
-     * Sets {@link android.app.UiAutomation#waitForIdle(long, long)} global timeout to 0 causing
-     * the {@link android.app.UiAutomation#waitForIdle(long, long)} function to timeout instantly.
-     * This removes some delays when using the UIAutomator library required to create fast UI
-     * transitions.
-     */
-    public static void setFastWait() {
-        Configurator.getInstance().setWaitForIdleTimeout(0);
-    }
-
-    /**
-     * Reverts {@link android.app.UiAutomation#waitForIdle(long, long)} to default behavior.
-     */
-    public static void setDefaultWait() {
-        Configurator.getInstance().setWaitForIdleTimeout(10000);
-    }
-
-    public static boolean isQuickstepEnabled(UiDevice device) {
-        return device.findObject(By.res(SYSTEMUI_PACKAGE, "recent_apps")) == null;
-    }
-
-    public static void openQuickstep(UiDevice device) {
-        if (isQuickstepEnabled(device)) {
-            int height = device.getDisplayHeight();
-            UiObject2 navBar = device.findObject(By.res(SYSTEMUI_PACKAGE, "navigation_bar_frame"));
-
-            Rect navBarVisibleBounds;
-
-            // TODO(vishnun) investigate why this object cannot be found.
-            if (navBar != null) {
-                navBarVisibleBounds = navBar.getVisibleBounds();
-            } else {
-                Log.e(TAG, "Could not find nav bar, infer location");
-                navBarVisibleBounds = WindowUtils.getNavigationBarPosition(ROTATION_0);
-            }
-
-            // Swipe from nav bar to 2/3rd down the screen.
-            device.swipe(
-                    navBarVisibleBounds.centerX(), navBarVisibleBounds.centerY(),
-                    navBarVisibleBounds.centerX(), height * 2 / 3,
-                    (navBarVisibleBounds.centerY() - height * 2 / 3) / 100); // 100 px/step
-        } else {
-            try {
-                device.pressRecentApps();
-            } catch (RemoteException e) {
-                throw new RuntimeException(e);
-            }
-        }
-        BySelector RECENTS = By.res(SYSTEMUI_PACKAGE, "recents_view");
-
-        // use a long timeout to wait until recents populated
-        if (device.wait(
-                Until.findObject(isRecentsInLauncher()
-                        ? getLauncherOverviewSelector(device) : RECENTS),
-                10000) == null) {
-            fail("Recents didn't appear");
-        }
-        device.waitForIdle();
-    }
-
-    public static void clearRecents(UiDevice device) {
-        if (isQuickstepEnabled(device)) {
-            openQuickstep(device);
-
-            for (int i = 0; i < 5; i++) {
-                device.swipe(device.getDisplayWidth() / 2,
-                        device.getDisplayHeight() / 2, device.getDisplayWidth(),
-                        device.getDisplayHeight() / 2,
-                        5);
-
-                BySelector clearAllSelector = By.res("com.google.android.apps.nexuslauncher",
-                        "clear_all_button");
-                UiObject2 clearAllButton = device.wait(Until.findObject(clearAllSelector), 100);
-                if (clearAllButton != null) {
-                    clearAllButton.click();
-                    return;
-                }
-            }
-        }
-    }
-
-    private static BySelector getLauncherOverviewSelector(UiDevice device) {
-        return By.res(device.getLauncherPackageName(), "overview_panel");
-    }
-
-    private static void longPressRecents(UiDevice device) {
-        BySelector recentsSelector = By.res(SYSTEMUI_PACKAGE, "recent_apps");
-        UiObject2 recentsButton = device.wait(Until.findObject(recentsSelector), FIND_TIMEOUT);
-        assertNotNull("Unable to find recents button", recentsButton);
-        recentsButton.click(LONG_PRESS_TIMEOUT);
-    }
-
-    public static void launchSplitScreen(UiDevice device) {
-        String mLauncherPackage = LauncherStrategyFactory.getInstance(device)
-                .getLauncherStrategy().getSupportedLauncherPackage();
-
-        if (isQuickstepEnabled(device)) {
-            // Quickstep enabled
-            openQuickstep(device);
-
-            BySelector overviewIconSelector = By.res(mLauncherPackage, "icon")
-                    .clazz(View.class);
-            UiObject2 overviewIcon = device.wait(Until.findObject(overviewIconSelector),
-                    FIND_TIMEOUT);
-            assertNotNull("Unable to find app icon in Overview", overviewIcon);
-            overviewIcon.click();
-
-            BySelector splitscreenButtonSelector = By.text("Split screen");
-            UiObject2 splitscreenButton = device.wait(Until.findObject(splitscreenButtonSelector),
-                    FIND_TIMEOUT);
-            assertNotNull("Unable to find Split screen button in Overview", splitscreenButton);
-            splitscreenButton.click();
-        } else {
-            // Classic long press recents
-            longPressRecents(device);
-        }
-        // Wait for animation to complete.
-        sleep(2000);
-    }
-
-    public static void exitSplitScreen(UiDevice device) {
-        if (isQuickstepEnabled(device)) {
-            // Quickstep enabled
-            BySelector dividerSelector = By.res(SYSTEMUI_PACKAGE, "docked_divider_handle");
-            UiObject2 divider = device.wait(Until.findObject(dividerSelector), FIND_TIMEOUT);
-            assertNotNull("Unable to find Split screen divider", divider);
-
-            // Drag the split screen divider to the top of the screen
-            divider.drag(new Point(device.getDisplayWidth() / 2, 0), 400);
-        } else {
-            // Classic long press recents
-            longPressRecents(device);
-        }
-        // Wait for animation to complete.
-        sleep(2000);
-    }
-
-    public static void resizeSplitScreen(UiDevice device, Rational windowHeightRatio) {
-        BySelector dividerSelector = By.res(SYSTEMUI_PACKAGE, "docked_divider_handle");
-        UiObject2 divider = device.wait(Until.findObject(dividerSelector), FIND_TIMEOUT);
-        assertNotNull("Unable to find Split screen divider", divider);
-        int destHeight =
-                (int) (WindowUtils.getDisplayBounds().height() * windowHeightRatio.floatValue());
-        // Drag the split screen divider to so that the ratio of top window height and bottom
-        // window height is windowHeightRatio
-        device.drag(divider.getVisibleBounds().centerX(), divider.getVisibleBounds().centerY(),
-                device.getDisplayWidth() / 2, destHeight, 10);
-        //divider.drag(new Point(device.getDisplayWidth() / 2, destHeight), 400)
-        divider = device.wait(Until.findObject(dividerSelector), FIND_TIMEOUT);
-
-        // Wait for animation to complete.
-        sleep(2000);
-    }
-
-    public static void closePipWindow(UiDevice device) {
-        UiObject2 pipWindow = device.findObject(
-                By.res(SYSTEMUI_PACKAGE, "background"));
-        pipWindow.click();
-        UiObject2 exitPipObject = device.findObject(
-                By.res(SYSTEMUI_PACKAGE, "dismiss"));
-        exitPipObject.click();
-        // Wait for animation to complete.
-        sleep(2000);
-    }
-
-    public static void expandPipWindow(UiDevice device) {
-        UiObject2 pipWindow = device.findObject(
-                By.res(SYSTEMUI_PACKAGE, "background"));
-        pipWindow.click();
-        pipWindow.click();
-    }
-
-    public static void stopPackage(Context context, String packageName) {
-        runShellCommand("am force-stop " + packageName);
-        int packageUid;
-        try {
-            packageUid = context.getPackageManager().getPackageUid(packageName, /* flags= */0);
-        } catch (PackageManager.NameNotFoundException e) {
-            return;
-        }
-        while (targetPackageIsRunning(packageUid)) {
-            try {
-                Thread.sleep(100);
-            } catch (InterruptedException e) {
-                //ignore
-            }
-        }
-    }
-
-    private static boolean targetPackageIsRunning(int uid) {
-        final String result = runShellCommand(
-                String.format("cmd activity get-uid-state %d", uid));
-        return !result.contains("(NONEXISTENT)");
-    }
-}
\ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ITransitionMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ITransitionMonitor.java
deleted file mode 100644
index 67e0ecc..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ITransitionMonitor.java
+++ /dev/null
@@ -1,63 +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.flicker.monitor;
-
-import android.os.Environment;
-
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-/**
- * Collects test artifacts during a UI transition.
- */
-public interface ITransitionMonitor {
-    Path OUTPUT_DIR = Paths.get(Environment.getExternalStorageDirectory().toString(), "flicker");
-
-    /**
-     * Starts monitor.
-     */
-    void start();
-
-    /**
-     * Stops monitor.
-     */
-    void stop();
-
-    /**
-     * Saves any monitor artifacts to file adding {@code testTag} and {@code iteration}
-     * to the file name.
-     *
-     * @param testTag   suffix added to artifact name
-     * @param iteration suffix added to artifact name
-     *
-     * @return Path to saved artifact
-     */
-    default Path save(String testTag, int iteration) {
-        return save(testTag + "_" + iteration);
-    }
-
-    /**
-     * Saves any monitor artifacts to file adding {@code testTag} to the file name.
-     *
-     * @param testTag suffix added to artifact name
-     *
-     * @return Path to saved artifact
-     */
-    default Path save(String testTag) {
-        throw new UnsupportedOperationException("Save not implemented for this monitor");
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/LayersTraceMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/LayersTraceMonitor.java
deleted file mode 100644
index da75b3e..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/LayersTraceMonitor.java
+++ /dev/null
@@ -1,64 +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.flicker.monitor;
-
-import android.os.RemoteException;
-import android.view.IWindowManager;
-import android.view.WindowManagerGlobal;
-
-/**
- * Captures Layers trace from SurfaceFlinger.
- */
-public class LayersTraceMonitor extends TraceMonitor {
-    private IWindowManager mWm = WindowManagerGlobal.getWindowManagerService();
-
-    public LayersTraceMonitor() {
-        this(OUTPUT_DIR.toString());
-    }
-
-    public LayersTraceMonitor(String outputDir) {
-        super(outputDir, "layers_trace.pb");
-    }
-
-    @Override
-    public void start() {
-        setEnabled(true);
-    }
-
-    @Override
-    public void stop() {
-        setEnabled(false);
-    }
-
-    @Override
-    public boolean isEnabled() throws RemoteException {
-        try {
-            return mWm.isLayerTracing();
-        } catch (RemoteException e) {
-            e.printStackTrace();
-        }
-        return false;
-    }
-
-    private void setEnabled(boolean isEnabled) {
-        try {
-            mWm.setLayerTracing(isEnabled);
-        } catch (RemoteException e) {
-            e.printStackTrace();
-        }
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ScreenRecorder.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ScreenRecorder.java
deleted file mode 100644
index dce1c27..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/ScreenRecorder.java
+++ /dev/null
@@ -1,80 +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.flicker.monitor;
-
-import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
-
-import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
-
-import android.util.Log;
-
-import androidx.annotation.VisibleForTesting;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-
-/**
- * Captures screen contents and saves it as a mp4 video file.
- */
-public class ScreenRecorder implements ITransitionMonitor {
-    @VisibleForTesting
-    public static final Path DEFAULT_OUTPUT_PATH = OUTPUT_DIR.resolve("transition.mp4");
-    private static final String TAG = "FLICKER";
-    private Thread recorderThread;
-
-    @VisibleForTesting
-    public static Path getPath(String testTag) {
-        return OUTPUT_DIR.resolve(testTag + ".mp4");
-    }
-
-    @Override
-    public void start() {
-        OUTPUT_DIR.toFile().mkdirs();
-        String command = "screenrecord " + DEFAULT_OUTPUT_PATH;
-        recorderThread = new Thread(() -> {
-            try {
-                Runtime.getRuntime().exec(command);
-            } catch (IOException e) {
-                Log.e(TAG, "Error executing " + command, e);
-            }
-        });
-        recorderThread.start();
-    }
-
-    @Override
-    public void stop() {
-        runShellCommand("killall -s 2 screenrecord");
-        try {
-            recorderThread.join();
-        } catch (InterruptedException e) {
-            // ignore
-        }
-    }
-
-    @Override
-    public Path save(String testTag) {
-        try {
-            Path targetPath = Files.move(DEFAULT_OUTPUT_PATH, getPath(testTag),
-                    REPLACE_EXISTING);
-            Log.i(TAG, "Video saved to " + targetPath.toString());
-            return targetPath;
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/TraceMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/TraceMonitor.java
deleted file mode 100644
index 1ba36bb..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/TraceMonitor.java
+++ /dev/null
@@ -1,74 +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.flicker.monitor;
-
-import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
-
-import android.os.RemoteException;
-
-import androidx.annotation.VisibleForTesting;
-
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Locale;
-
-/**
- * Base class for monitors containing common logic to read the trace
- * as a byte array and save the trace to another location.
- */
-public abstract class TraceMonitor implements ITransitionMonitor {
-    public static final String TAG = "FLICKER";
-    private static final String TRACE_DIR = "/data/misc/wmtrace/";
-
-    private Path mOutputDir;
-    public String mTraceFileName;
-
-    public abstract boolean isEnabled() throws RemoteException;
-
-    public TraceMonitor(String outputDir, String traceFileName) {
-        mOutputDir = Paths.get(outputDir);
-        mTraceFileName = traceFileName;
-    }
-
-    /**
-     * Saves trace file to the external storage directory suffixing the name with the testtag
-     * and iteration.
-     *
-     * Moves the trace file from the default location via a shell command since the test app
-     * does not have security privileges to access /data/misc/wmtrace.
-     *
-     * @param testTag suffix added to trace name used to identify trace
-     *
-     * @return Path to saved trace file
-     */
-    @Override
-    public Path save(String testTag) {
-        OUTPUT_DIR.toFile().mkdirs();
-        Path traceFileCopy = getOutputTraceFilePath(testTag);
-
-        // Read the input stream fully.
-        String copyCommand = String.format(Locale.getDefault(), "mv %s%s %s", TRACE_DIR,
-                mTraceFileName, traceFileCopy.toString());
-        runShellCommand(copyCommand);
-        return traceFileCopy;
-    }
-
-    @VisibleForTesting
-    public Path getOutputTraceFilePath(String testTag) {
-        return mOutputDir.resolve(mTraceFileName + "_" + testTag);
-    }
-}
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitor.java
deleted file mode 100644
index 3f86f0d..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitor.java
+++ /dev/null
@@ -1,100 +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.flicker.monitor;
-
-import static android.view.FrameStats.UNDEFINED_TIME_NANO;
-
-import android.app.Instrumentation;
-import android.util.Log;
-import android.view.FrameStats;
-
-/**
- * Monitors {@link android.view.WindowAnimationFrameStats} to detect janky frames.
- *
- * Adapted from {@link androidx.test.jank.internal.WindowAnimationFrameStatsMonitorImpl}
- * using the same threshold to determine jank.
- */
-public class WindowAnimationFrameStatsMonitor implements ITransitionMonitor {
-
-    private static final String TAG = "FLICKER";
-    // Maximum normalized error in frame duration before the frame is considered janky
-    private static final double MAX_ERROR = 0.5f;
-    // Maximum normalized frame duration before the frame is considered a pause
-    private static final double PAUSE_THRESHOLD = 15.0f;
-    private Instrumentation mInstrumentation;
-    private FrameStats stats;
-    private int numJankyFrames;
-    private long mLongestFrameNano = 0L;
-
-
-    /**
-     * Constructs a WindowAnimationFrameStatsMonitor instance.
-     */
-    public WindowAnimationFrameStatsMonitor(Instrumentation instrumentation) {
-        mInstrumentation = instrumentation;
-    }
-
-    private void analyze() {
-        int frameCount = stats.getFrameCount();
-        long refreshPeriodNano = stats.getRefreshPeriodNano();
-
-        // Skip first frame
-        for (int i = 2; i < frameCount; i++) {
-            // Handle frames that have not been presented.
-            if (stats.getFramePresentedTimeNano(i) == UNDEFINED_TIME_NANO) {
-                // The animation must not have completed. Warn and break out of the loop.
-                Log.w(TAG, "Skipping fenced frame.");
-                break;
-            }
-            long frameDurationNano = stats.getFramePresentedTimeNano(i) -
-                    stats.getFramePresentedTimeNano(i - 1);
-            double normalized = (double) frameDurationNano / refreshPeriodNano;
-            if (normalized < PAUSE_THRESHOLD) {
-                if (normalized > 1.0f + MAX_ERROR) {
-                    numJankyFrames++;
-                }
-                mLongestFrameNano = Math.max(mLongestFrameNano, frameDurationNano);
-            }
-        }
-    }
-
-    @Override
-    public void start() {
-        // Clear out any previous data
-        numJankyFrames = 0;
-        mLongestFrameNano = 0;
-        mInstrumentation.getUiAutomation().clearWindowAnimationFrameStats();
-    }
-
-    @Override
-    public void stop() {
-        stats = mInstrumentation.getUiAutomation().getWindowAnimationFrameStats();
-        analyze();
-    }
-
-    public boolean jankyFramesDetected() {
-        return stats.getFrameCount() > 0 && numJankyFrames > 0;
-    }
-
-    @Override
-    public String toString() {
-        return stats.toString() +
-                " RefreshPeriodNano:" + stats.getRefreshPeriodNano() +
-                " NumJankyFrames:" + numJankyFrames +
-                " LongestFrameNano:" + mLongestFrameNano;
-    }
-}
\ No newline at end of file
diff --git a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitor.java b/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitor.java
deleted file mode 100644
index 11de4aa..0000000
--- a/tests/FlickerTests/lib/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitor.java
+++ /dev/null
@@ -1,59 +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.flicker.monitor;
-
-import android.os.RemoteException;
-import android.view.IWindowManager;
-import android.view.WindowManagerGlobal;
-
-/**
- * Captures WindowManager trace from WindowManager.
- */
-public class WindowManagerTraceMonitor extends TraceMonitor {
-    private IWindowManager mWm = WindowManagerGlobal.getWindowManagerService();
-
-    public WindowManagerTraceMonitor() {
-        this(OUTPUT_DIR.toString());
-    }
-
-    public WindowManagerTraceMonitor(String outputDir) {
-        super(outputDir, "wm_trace.pb");
-    }
-
-    @Override
-    public void start() {
-        try {
-            mWm.startWindowTrace();
-        } catch (RemoteException e) {
-            throw new RuntimeException("Could not start trace", e);
-        }
-    }
-
-    @Override
-    public void stop() {
-        try {
-            mWm.stopWindowTrace();
-        } catch (RemoteException e) {
-            throw new RuntimeException("Could not stop trace", e);
-        }
-    }
-
-    @Override
-    public boolean isEnabled() throws RemoteException{
-        return mWm.isWindowTraceEnabled();
-    }
-}
diff --git a/tests/FlickerTests/lib/test/Android.bp b/tests/FlickerTests/lib/test/Android.bp
deleted file mode 100644
index bfeb75b2..0000000
--- a/tests/FlickerTests/lib/test/Android.bp
+++ /dev/null
@@ -1,33 +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.
-//
-
-android_test {
-    name: "FlickerLibTest",
-    // sign this with platform cert, so this test is allowed to call private platform apis
-    certificate: "platform",
-    platform_apis: true,
-    test_suites: ["tests"],
-    srcs: ["src/**/*.java"],
-    libs: ["android.test.runner"],
-    static_libs: [
-        "androidx.test.rules",
-        "platform-test-annotations",
-        "truth-prebuilt",
-        "platformprotosnano",
-        "layersprotosnano",
-        "flickerlib",
-    ],
-}
diff --git a/tests/FlickerTests/lib/test/AndroidManifest.xml b/tests/FlickerTests/lib/test/AndroidManifest.xml
deleted file mode 100644
index 6451a57..0000000
--- a/tests/FlickerTests/lib/test/AndroidManifest.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright 2018 Google Inc. All Rights Reserved.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="com.android.server.wm.flicker">
-
-    <uses-sdk android:minSdkVersion="27" android:targetSdkVersion="27"/>
-    <!-- Read and write traces from external storage -->
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-    <!-- Capture screen contents -->
-    <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
-    <!-- Run layers trace -->
-    <uses-permission android:name="android.permission.HARDWARE_TEST"/>
-    <application android:label="FlickerLibTest">
-        <uses-library android:name="android.test.runner"/>
-    </application>
-
-    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
-                     android:targetPackage="com.android.server.wm.flicker"
-                     android:label="WindowManager Flicker Lib Test">
-    </instrumentation>
-
-</manifest>
\ No newline at end of file
diff --git a/tests/FlickerTests/lib/test/AndroidTest.xml b/tests/FlickerTests/lib/test/AndroidTest.xml
deleted file mode 100644
index e4cc298..0000000
--- a/tests/FlickerTests/lib/test/AndroidTest.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright 2018 Google Inc. All Rights Reserved.
- -->
-<configuration description="Config for WindowManager Flicker Tests">
-    <target_preparer class="com.google.android.tradefed.targetprep.GoogleDeviceSetup">
-        <!-- keeps the screen on during tests -->
-        <option name="screen-always-on" value="on" />
-        <!-- prevents the phone from restarting -->
-        <option name="force-skip-system-props" value="true" />
-    </target_preparer>
-    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
-        <option name="cleanup-apks" value="true"/>
-        <option name="test-file-name" value="FlickerLibTest.apk"/>
-    </target_preparer>
-    <test class="com.android.tradefed.testtype.AndroidJUnitTest">
-        <option name="package" value="com.android.server.wm.flicker"/>
-        <option name="hidden-api-checks" value="false" />
-    </test>
-</configuration>
diff --git a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_emptyregion.pb b/tests/FlickerTests/lib/test/assets/testdata/layers_trace_emptyregion.pb
deleted file mode 100644
index 98ee6f3..0000000
--- a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_emptyregion.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_invalid_layer_visibility.pb b/tests/FlickerTests/lib/test/assets/testdata/layers_trace_invalid_layer_visibility.pb
deleted file mode 100644
index 20572d7..0000000
--- a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_invalid_layer_visibility.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_orphanlayers.pb b/tests/FlickerTests/lib/test/assets/testdata/layers_trace_orphanlayers.pb
deleted file mode 100644
index af40797..0000000
--- a/tests/FlickerTests/lib/test/assets/testdata/layers_trace_orphanlayers.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome.pb b/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome.pb
deleted file mode 100644
index b3f3170..0000000
--- a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome2.pb b/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome2.pb
deleted file mode 100644
index b3b73ce..0000000
--- a/tests/FlickerTests/lib/test/assets/testdata/wm_trace_openchrome2.pb
+++ /dev/null
Binary files differ
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsCheckerTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsCheckerTest.java
deleted file mode 100644
index 8e7fe1b..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsCheckerTest.java
+++ /dev/null
@@ -1,181 +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.flicker;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Contains {@link AssertionsChecker} tests.
- * To run this test: {@code atest FlickerLibTest:AssertionsCheckerTest}
- */
-public class AssertionsCheckerTest {
-
-    /**
-     * Returns a list of SimpleEntry objects with {@code data} and incremental timestamps starting
-     * at 0.
-     */
-    private static List<SimpleEntry> getTestEntries(int... data) {
-        List<SimpleEntry> entries = new ArrayList<>();
-        for (int i = 0; i < data.length; i++) {
-            entries.add(new SimpleEntry(i, data[i]));
-        }
-        return entries;
-    }
-
-    @Test
-    public void canCheckAllEntries() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.add(SimpleEntry::isData42, "isData42");
-
-        List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
-        assertThat(failures).hasSize(5);
-    }
-
-    @Test
-    public void canCheckFirstEntry() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.checkFirstEntry();
-        checker.add(SimpleEntry::isData42, "isData42");
-
-        List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
-        assertThat(failures).hasSize(1);
-        assertThat(failures.get(0).timestamp).isEqualTo(0);
-    }
-
-    @Test
-    public void canCheckLastEntry() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.checkLastEntry();
-        checker.add(SimpleEntry::isData42, "isData42");
-
-        List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
-        assertThat(failures).hasSize(1);
-        assertThat(failures.get(0).timestamp).isEqualTo(4);
-    }
-
-    @Test
-    public void canCheckRangeOfEntries() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.filterByRange(1, 2);
-        checker.add(SimpleEntry::isData42, "isData42");
-
-        List<Result> failures = checker.test(getTestEntries(1, 42, 42, 1, 1));
-
-        assertThat(failures).hasSize(0);
-    }
-
-    @Test
-    public void emptyRangePasses() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.filterByRange(9, 10);
-        checker.add(SimpleEntry::isData42, "isData42");
-
-        List<Result> failures = checker.test(getTestEntries(1, 1, 1, 1, 1));
-
-        assertThat(failures).isEmpty();
-    }
-
-    @Test
-    public void canCheckChangingAssertions() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.add(SimpleEntry::isData42, "isData42");
-        checker.add(SimpleEntry::isData0, "isData0");
-        checker.checkChangingAssertions();
-
-        List<Result> failures = checker.test(getTestEntries(42, 0, 0, 0, 0));
-
-        assertThat(failures).isEmpty();
-    }
-
-    @Test
-    public void canCheckChangingAssertions_withNoAssertions() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.checkChangingAssertions();
-
-        List<Result> failures = checker.test(getTestEntries(42, 0, 0, 0, 0));
-
-        assertThat(failures).isEmpty();
-    }
-
-    @Test
-    public void canCheckChangingAssertions_withSingleAssertion() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.add(SimpleEntry::isData42, "isData42");
-        checker.checkChangingAssertions();
-
-        List<Result> failures = checker.test(getTestEntries(42, 42, 42, 42, 42));
-
-        assertThat(failures).isEmpty();
-    }
-
-    @Test
-    public void canFailCheckChangingAssertions_ifStartingAssertionFails() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.add(SimpleEntry::isData42, "isData42");
-        checker.add(SimpleEntry::isData0, "isData0");
-        checker.checkChangingAssertions();
-
-        List<Result> failures = checker.test(getTestEntries(0, 0, 0, 0, 0));
-
-        assertThat(failures).hasSize(1);
-    }
-
-    @Test
-    public void canFailCheckChangingAssertions_ifStartingAssertionAlwaysPasses() {
-        AssertionsChecker<SimpleEntry> checker = new AssertionsChecker<>();
-        checker.add(SimpleEntry::isData42, "isData42");
-        checker.add(SimpleEntry::isData0, "isData0");
-        checker.checkChangingAssertions();
-
-        List<Result> failures = checker.test(getTestEntries(0, 0, 0, 0, 0));
-
-        assertThat(failures).hasSize(1);
-    }
-
-    static class SimpleEntry implements ITraceEntry {
-        long timestamp;
-        int data;
-
-        SimpleEntry(long timestamp, int data) {
-            this.timestamp = timestamp;
-            this.data = data;
-        }
-
-        @Override
-        public long getTimestamp() {
-            return timestamp;
-        }
-
-        Result isData42() {
-            return new Result(this.data == 42, this.timestamp, "is42", "");
-        }
-
-        Result isData0() {
-            return new Result(this.data == 0, this.timestamp, "is42", "");
-        }
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsTest.java
deleted file mode 100644
index 7fd178c..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/AssertionsTest.java
+++ /dev/null
@@ -1,60 +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.flicker;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import org.junit.Test;
-
-/**
- * Contains {@link Assertions} tests.
- * To run this test: {@code atest FlickerLibTest:AssertionsTest}
- */
-public class AssertionsTest {
-    @Test
-    public void traceEntryAssertionCanNegateResult() {
-        Assertions.TraceAssertion<Integer> assertNumEquals42 =
-                getIntegerTraceEntryAssertion();
-
-        assertThat(assertNumEquals42.apply(1).success).isFalse();
-        assertThat(assertNumEquals42.negate().apply(1).success).isTrue();
-
-        assertThat(assertNumEquals42.apply(42).success).isTrue();
-        assertThat(assertNumEquals42.negate().apply(42).success).isFalse();
-    }
-
-    @Test
-    public void resultCanBeNegated() {
-        String reason = "Everything is fine!";
-        Result result = new Result(true, 0, "TestAssert", reason);
-        Result negatedResult = result.negate();
-        assertThat(negatedResult.success).isFalse();
-        assertThat(negatedResult.reason).isEqualTo(reason);
-        assertThat(negatedResult.assertionName).isEqualTo("!TestAssert");
-    }
-
-    private Assertions.TraceAssertion<Integer> getIntegerTraceEntryAssertion() {
-        return (num) -> {
-            if (num == 42) {
-                return new Result(true, "Num equals 42");
-            }
-            return new Result(false, "Num doesn't equal 42, actual:" + num);
-        };
-    }
-}
\ No newline at end of file
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceSubjectTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceSubjectTest.java
deleted file mode 100644
index d06c5d7..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceSubjectTest.java
+++ /dev/null
@@ -1,88 +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.flicker;
-
-import static com.android.server.wm.flicker.LayersTraceSubject.assertThat;
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import static org.junit.Assert.fail;
-
-import android.graphics.Rect;
-
-import org.junit.Test;
-
-import java.nio.file.Paths;
-
-/**
- * Contains {@link LayersTraceSubject} tests.
- * To run this test: {@code atest FlickerLibTest:LayersTraceSubjectTest}
- */
-public class LayersTraceSubjectTest {
-    private static final Rect displayRect = new Rect(0, 0, 1440, 2880);
-
-    private static LayersTrace readLayerTraceFromFile(String relativePath) {
-        try {
-            return LayersTrace.parseFrom(readTestFile(relativePath), Paths.get(relativePath));
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    @Test
-    public void testCanDetectEmptyRegionFromLayerTrace() {
-        LayersTrace layersTraceEntries = readLayerTraceFromFile("layers_trace_emptyregion.pb");
-        try {
-            assertThat(layersTraceEntries).coversRegion(displayRect).forAllEntries();
-            fail("Assertion passed");
-        } catch (AssertionError e) {
-            assertWithMessage("Contains path to trace")
-                    .that(e.getMessage()).contains("layers_trace_emptyregion.pb");
-            assertWithMessage("Contains timestamp")
-                    .that(e.getMessage()).contains("0h38m28s8ms");
-            assertWithMessage("Contains assertion function")
-                    .that(e.getMessage()).contains("coversRegion");
-            assertWithMessage("Contains debug info")
-                    .that(e.getMessage()).contains("Region to test: " + displayRect);
-            assertWithMessage("Contains debug info")
-                    .that(e.getMessage()).contains("first empty point: 0, 99");
-        }
-    }
-
-    @Test
-    public void testCanDetectIncorrectVisibilityFromLayerTrace() {
-        LayersTrace layersTraceEntries = readLayerTraceFromFile(
-                "layers_trace_invalid_layer_visibility.pb");
-        try {
-            assertThat(layersTraceEntries).showsLayer("com.android.server.wm.flicker.testapp")
-                    .then().hidesLayer("com.android.server.wm.flicker.testapp").forAllEntries();
-            fail("Assertion passed");
-        } catch (AssertionError e) {
-            assertWithMessage("Contains path to trace")
-                    .that(e.getMessage()).contains("layers_trace_invalid_layer_visibility.pb");
-            assertWithMessage("Contains timestamp")
-                    .that(e.getMessage()).contains("70h13m14s303ms");
-            assertWithMessage("Contains assertion function")
-                    .that(e.getMessage()).contains("!isVisible");
-            assertWithMessage("Contains debug info")
-                    .that(e.getMessage()).contains(
-                    "com.android.server.wm.flicker.testapp/com.android.server.wm.flicker.testapp"
-                            + ".SimpleActivity#0 is visible");
-        }
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceTest.java
deleted file mode 100644
index 7d77126..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/LayersTraceTest.java
+++ /dev/null
@@ -1,230 +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.flicker;
-
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import static org.junit.Assert.fail;
-
-import android.content.Context;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.view.WindowManager;
-
-import androidx.test.InstrumentationRegistry;
-
-import org.junit.Test;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Contains {@link LayersTrace} tests.
- * To run this test: {@code atest FlickerLibTest:LayersTraceTest}
- */
-public class LayersTraceTest {
-    private static LayersTrace readLayerTraceFromFile(String relativePath) {
-        try {
-            return LayersTrace.parseFrom(readTestFile(relativePath));
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    private static Rect getDisplayBounds() {
-        Point display = new Point();
-        WindowManager wm =
-                (WindowManager) InstrumentationRegistry.getContext().getSystemService(
-                        Context.WINDOW_SERVICE);
-        wm.getDefaultDisplay().getRealSize(display);
-        return new Rect(0, 0, display.x, display.y);
-    }
-
-    @Test
-    public void canParseAllLayers() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        assertThat(trace.getEntries()).isNotEmpty();
-        assertThat(trace.getEntries().get(0).getTimestamp()).isEqualTo(2307984557311L);
-        assertThat(trace.getEntries().get(trace.getEntries().size() - 1).getTimestamp())
-                .isEqualTo(2308521813510L);
-        List<LayersTrace.Layer> flattenedLayers = trace.getEntries().get(0).asFlattenedLayers();
-        String msg = "Layers:\n" + flattenedLayers.stream().map(layer -> layer.mProto.name)
-                .collect(Collectors.joining("\n\t"));
-        assertWithMessage(msg).that(flattenedLayers).hasSize(47);
-    }
-
-    @Test
-    public void canParseVisibleLayers() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        assertThat(trace.getEntries()).isNotEmpty();
-        assertThat(trace.getEntries().get(0).getTimestamp()).isEqualTo(2307984557311L);
-        assertThat(trace.getEntries().get(trace.getEntries().size() - 1).getTimestamp())
-                .isEqualTo(2308521813510L);
-        List<LayersTrace.Layer> flattenedLayers = trace.getEntries().get(0).asFlattenedLayers();
-        List<LayersTrace.Layer> visibleLayers = flattenedLayers.stream()
-                .filter(layer -> layer.isVisible() && !layer.isHiddenByParent())
-                .collect(Collectors.toList());
-
-        String msg = "Visible Layers:\n" + visibleLayers.stream()
-                .map(layer -> layer.mProto.name)
-                .collect(Collectors.joining("\n\t"));
-
-        assertWithMessage(msg).that(visibleLayers).hasSize(9);
-    }
-
-    @Test
-    public void canParseLayerHierarchy() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        assertThat(trace.getEntries()).isNotEmpty();
-        assertThat(trace.getEntries().get(0).getTimestamp()).isEqualTo(2307984557311L);
-        assertThat(trace.getEntries().get(trace.getEntries().size() - 1).getTimestamp())
-                .isEqualTo(2308521813510L);
-        List<LayersTrace.Layer> layers = trace.getEntries().get(0).getRootLayers();
-        assertThat(layers).hasSize(2);
-        assertThat(layers.get(0).mChildren).hasSize(layers.get(0).mProto.children.length);
-        assertThat(layers.get(1).mChildren).hasSize(layers.get(1).mProto.children.length);
-    }
-
-    // b/76099859
-    @Test
-    public void canDetectOrphanLayers() {
-        try {
-            readLayerTraceFromFile(
-                    "layers_trace_orphanlayers.pb");
-            fail("Failed to detect orphaned layers.");
-        } catch (RuntimeException exception) {
-            assertThat(exception.getMessage()).contains(
-                    "Failed to parse layers trace. Found orphan layers "
-                            + "with parent layer id:1006 : 49");
-        }
-    }
-
-    // b/75276931
-    @Test
-    public void canDetectUncoveredRegion() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
-        Assertions.Result result = entry.coversRegion(getDisplayBounds());
-
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains("Region to test: Rect(0, 0 - 1440, 2880)");
-        assertThat(result.reason).contains("first empty point: 0, 99");
-        assertThat(result.reason).contains("visible regions:");
-        assertWithMessage("Reason contains list of visible regions")
-                .that(result.reason).contains("StatusBar#0Rect(0, 0 - 1440, 98");
-    }
-
-    // Visible region tests
-    @Test
-    public void canTestLayerVisibleRegion_layerDoesNotExist() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
-        final Rect expectedVisibleRegion = new Rect(0, 0, 1, 1);
-        Assertions.Result result = entry.hasVisibleRegion("ImaginaryLayer",
-                expectedVisibleRegion);
-
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains("Could not find ImaginaryLayer");
-    }
-
-    @Test
-    public void canTestLayerVisibleRegion_layerDoesNotHaveExpectedVisibleRegion() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        LayersTrace.Entry entry = trace.getEntry(2307993020072L);
-
-        final Rect expectedVisibleRegion = new Rect(0, 0, 1, 1);
-        Assertions.Result result = entry.hasVisibleRegion("NexusLauncherActivity#2",
-                expectedVisibleRegion);
-
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains(
-                "Layer com.google.android.apps.nexuslauncher/com.google.android.apps"
-                        + ".nexuslauncher.NexusLauncherActivity#2 is invisible: activeBuffer=null"
-                        + " type != ColorLayer flags=1 (FLAG_HIDDEN set) visible region is empty");
-    }
-
-    @Test
-    public void canTestLayerVisibleRegion_layerIsHiddenByParent() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        LayersTrace.Entry entry = trace.getEntry(2308455948035L);
-
-        final Rect expectedVisibleRegion = new Rect(0, 0, 1, 1);
-        Assertions.Result result = entry.hasVisibleRegion(
-                "SurfaceView - com.android.chrome/com.google.android.apps.chrome.Main",
-                expectedVisibleRegion);
-
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains(
-                "Layer SurfaceView - com.android.chrome/com.google.android.apps.chrome.Main#0 is "
-                        + "hidden by parent: com.android.chrome/com.google.android.apps.chrome"
-                        + ".Main#0");
-    }
-
-    @Test
-    public void canTestLayerVisibleRegion_incorrectRegionSize() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
-        final Rect expectedVisibleRegion = new Rect(0, 0, 1440, 99);
-        Assertions.Result result = entry.hasVisibleRegion(
-                "StatusBar",
-                expectedVisibleRegion);
-
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains("StatusBar#0 has visible "
-                + "region:Rect(0, 0 - 1440, 98) expected:Rect(0, 0 - 1440, 99)");
-    }
-
-    @Test
-    public void canTestLayerVisibleRegion() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_emptyregion.pb");
-        LayersTrace.Entry entry = trace.getEntry(2308008331271L);
-
-        final Rect expectedVisibleRegion = new Rect(0, 0, 1440, 98);
-        Assertions.Result result = entry.hasVisibleRegion("StatusBar", expectedVisibleRegion);
-
-        assertThat(result.passed()).isTrue();
-    }
-
-    @Test
-    public void canTestLayerVisibleRegion_layerIsNotVisible() {
-        LayersTrace trace = readLayerTraceFromFile(
-                "layers_trace_invalid_layer_visibility.pb");
-        LayersTrace.Entry entry = trace.getEntry(252794268378458L);
-
-        Assertions.Result result = entry.isVisible("com.android.server.wm.flicker.testapp");
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains(
-                "Layer com.android.server.wm.flicker.testapp/com.android.server.wm.flicker"
-                        + ".testapp.SimpleActivity#0 is invisible: type != ColorLayer visible "
-                        + "region is empty");
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TestFileUtils.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TestFileUtils.java
deleted file mode 100644
index c46175c..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TestFileUtils.java
+++ /dev/null
@@ -1,36 +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.flicker;
-
-import android.content.Context;
-
-import androidx.test.InstrumentationRegistry;
-
-import com.google.common.io.ByteStreams;
-
-import java.io.InputStream;
-
-/**
- * Helper functions for test file resources.
- */
-class TestFileUtils {
-    static byte[] readTestFile(String relativePath) throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        InputStream in = context.getResources().getAssets().open("testdata/" + relativePath);
-        return ByteStreams.toByteArray(in);
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TransitionRunnerTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TransitionRunnerTest.java
deleted file mode 100644
index 9c5e2059a..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/TransitionRunnerTest.java
+++ /dev/null
@@ -1,258 +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.flicker;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.inOrder;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-
-import android.os.Environment;
-
-import com.android.server.wm.flicker.TransitionRunner.TransitionBuilder;
-import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
-import com.android.server.wm.flicker.monitor.LayersTraceMonitor;
-import com.android.server.wm.flicker.monitor.ScreenRecorder;
-import com.android.server.wm.flicker.monitor.WindowAnimationFrameStatsMonitor;
-import com.android.server.wm.flicker.monitor.WindowManagerTraceMonitor;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InOrder;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.IOException;
-import java.nio.file.Paths;
-import java.util.List;
-
-/**
- * Contains {@link TransitionRunner} tests.
- * {@code atest FlickerLibTest:TransitionRunnerTest}
- */
-public class TransitionRunnerTest {
-    @Mock
-    private SimpleUiTransitions mTransitionsMock;
-    @Mock
-    private ScreenRecorder mScreenRecorderMock;
-    @Mock
-    private WindowManagerTraceMonitor mWindowManagerTraceMonitorMock;
-    @Mock
-    private LayersTraceMonitor mLayersTraceMonitorMock;
-    @Mock
-    private WindowAnimationFrameStatsMonitor mWindowAnimationFrameStatsMonitor;
-    @InjectMocks
-    private TransitionBuilder mTransitionBuilder;
-
-    @Before
-    public void init() {
-        MockitoAnnotations.initMocks(this);
-    }
-
-    @Test
-    public void transitionsRunInOrder() {
-        TransitionRunner.newBuilder()
-                .runBeforeAll(mTransitionsMock::turnOnDevice)
-                .runBefore(mTransitionsMock::openApp)
-                .run(mTransitionsMock::performMagic)
-                .runAfter(mTransitionsMock::closeApp)
-                .runAfterAll(mTransitionsMock::cleanUpTracks)
-                .skipLayersTrace()
-                .skipWindowManagerTrace()
-                .build()
-                .run();
-
-        InOrder orderVerifier = inOrder(mTransitionsMock);
-        orderVerifier.verify(mTransitionsMock).turnOnDevice();
-        orderVerifier.verify(mTransitionsMock).openApp();
-        orderVerifier.verify(mTransitionsMock).performMagic();
-        orderVerifier.verify(mTransitionsMock).closeApp();
-        orderVerifier.verify(mTransitionsMock).cleanUpTracks();
-    }
-
-    @Test
-    public void canCombineTransitions() {
-        TransitionRunner.newBuilder()
-                .runBeforeAll(mTransitionsMock::turnOnDevice)
-                .runBeforeAll(mTransitionsMock::turnOnDevice)
-                .runBefore(mTransitionsMock::openApp)
-                .runBefore(mTransitionsMock::openApp)
-                .run(mTransitionsMock::performMagic)
-                .run(mTransitionsMock::performMagic)
-                .runAfter(mTransitionsMock::closeApp)
-                .runAfter(mTransitionsMock::closeApp)
-                .runAfterAll(mTransitionsMock::cleanUpTracks)
-                .runAfterAll(mTransitionsMock::cleanUpTracks)
-                .skipLayersTrace()
-                .skipWindowManagerTrace()
-                .build()
-                .run();
-
-        final int wantedNumberOfInvocations = 2;
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).turnOnDevice();
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).openApp();
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).performMagic();
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).closeApp();
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).cleanUpTracks();
-    }
-
-    @Test
-    public void emptyTransitionPasses() {
-        List<TransitionResult> results = TransitionRunner.newBuilder()
-                .skipLayersTrace()
-                .skipWindowManagerTrace()
-                .build()
-                .run()
-                .getResults();
-        assertThat(results).hasSize(1);
-        assertThat(results.get(0).layersTraceExists()).isFalse();
-        assertThat(results.get(0).windowManagerTraceExists()).isFalse();
-        assertThat(results.get(0).screenCaptureVideoExists()).isFalse();
-    }
-
-    @Test
-    public void canRepeatTransitions() {
-        final int wantedNumberOfInvocations = 10;
-        TransitionRunner.newBuilder()
-                .runBeforeAll(mTransitionsMock::turnOnDevice)
-                .runBefore(mTransitionsMock::openApp)
-                .run(mTransitionsMock::performMagic)
-                .runAfter(mTransitionsMock::closeApp)
-                .runAfterAll(mTransitionsMock::cleanUpTracks)
-                .repeat(wantedNumberOfInvocations)
-                .skipLayersTrace()
-                .skipWindowManagerTrace()
-                .build()
-                .run();
-        verify(mTransitionsMock).turnOnDevice();
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).openApp();
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).performMagic();
-        verify(mTransitionsMock, times(wantedNumberOfInvocations)).closeApp();
-        verify(mTransitionsMock).cleanUpTracks();
-    }
-
-    private void emptyTask() {
-
-    }
-
-    @Test
-    public void canCaptureWindowManagerTrace() {
-        mTransitionBuilder
-                .run(this::emptyTask)
-                .includeJankyRuns()
-                .skipLayersTrace()
-                .withTag("mCaptureWmTraceTransitionRunner")
-                .build().run();
-        InOrder orderVerifier = inOrder(mWindowManagerTraceMonitorMock);
-        orderVerifier.verify(mWindowManagerTraceMonitorMock).start();
-        orderVerifier.verify(mWindowManagerTraceMonitorMock).stop();
-        orderVerifier.verify(mWindowManagerTraceMonitorMock)
-                .save("mCaptureWmTraceTransitionRunner", 0);
-        verifyNoMoreInteractions(mWindowManagerTraceMonitorMock);
-    }
-
-    @Test
-    public void canCaptureLayersTrace() {
-        mTransitionBuilder
-                .run(this::emptyTask)
-                .includeJankyRuns()
-                .skipWindowManagerTrace()
-                .withTag("mCaptureLayersTraceTransitionRunner")
-                .build().run();
-        InOrder orderVerifier = inOrder(mLayersTraceMonitorMock);
-        orderVerifier.verify(mLayersTraceMonitorMock).start();
-        orderVerifier.verify(mLayersTraceMonitorMock).stop();
-        orderVerifier.verify(mLayersTraceMonitorMock)
-                .save("mCaptureLayersTraceTransitionRunner", 0);
-        verifyNoMoreInteractions(mLayersTraceMonitorMock);
-    }
-
-    @Test
-    public void canRecordEachRun() throws IOException {
-        mTransitionBuilder
-                .run(this::emptyTask)
-                .withTag("mRecordEachRun")
-                .recordEachRun()
-                .includeJankyRuns()
-                .skipLayersTrace()
-                .skipWindowManagerTrace()
-                .repeat(2)
-                .build().run();
-        InOrder orderVerifier = inOrder(mScreenRecorderMock);
-        orderVerifier.verify(mScreenRecorderMock).start();
-        orderVerifier.verify(mScreenRecorderMock).stop();
-        orderVerifier.verify(mScreenRecorderMock).save("mRecordEachRun", 0);
-        orderVerifier.verify(mScreenRecorderMock).start();
-        orderVerifier.verify(mScreenRecorderMock).stop();
-        orderVerifier.verify(mScreenRecorderMock).save("mRecordEachRun", 1);
-        verifyNoMoreInteractions(mScreenRecorderMock);
-    }
-
-    @Test
-    public void canRecordAllRuns() throws IOException {
-        doReturn(Paths.get(Environment.getExternalStorageDirectory().getAbsolutePath(),
-                "mRecordAllRuns.mp4")).when(mScreenRecorderMock).save("mRecordAllRuns");
-        mTransitionBuilder
-                .run(this::emptyTask)
-                .recordAllRuns()
-                .includeJankyRuns()
-                .skipLayersTrace()
-                .skipWindowManagerTrace()
-                .withTag("mRecordAllRuns")
-                .repeat(2)
-                .build().run();
-        InOrder orderVerifier = inOrder(mScreenRecorderMock);
-        orderVerifier.verify(mScreenRecorderMock).start();
-        orderVerifier.verify(mScreenRecorderMock).stop();
-        orderVerifier.verify(mScreenRecorderMock).save("mRecordAllRuns");
-        verifyNoMoreInteractions(mScreenRecorderMock);
-    }
-
-    @Test
-    public void canSkipJankyRuns() {
-        doReturn(false).doReturn(true).doReturn(false)
-                .when(mWindowAnimationFrameStatsMonitor).jankyFramesDetected();
-        List<TransitionResult> results = mTransitionBuilder
-                .run(this::emptyTask)
-                .skipLayersTrace()
-                .skipWindowManagerTrace()
-                .repeat(3)
-                .build().run().getResults();
-        assertThat(results).hasSize(2);
-    }
-
-    public static class SimpleUiTransitions {
-        public void turnOnDevice() {
-        }
-
-        public void openApp() {
-        }
-
-        public void performMagic() {
-        }
-
-        public void closeApp() {
-        }
-
-        public void cleanUpTracks() {
-        }
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WindowManagerTraceTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WindowManagerTraceTest.java
deleted file mode 100644
index 4927871..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WindowManagerTraceTest.java
+++ /dev/null
@@ -1,108 +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.flicker;
-
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.flicker.Assertions.Result;
-
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Contains {@link WindowManagerTrace} tests.
- * To run this test: {@code atest FlickerLibTest:WindowManagerTraceTest}
- */
-public class WindowManagerTraceTest {
-    private WindowManagerTrace mTrace;
-
-    private static WindowManagerTrace readWindowManagerTraceFromFile(String relativePath) {
-        try {
-            return WindowManagerTrace.parseFrom(readTestFile(relativePath));
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    @Before
-    public void setup() {
-        mTrace = readWindowManagerTraceFromFile("wm_trace_openchrome.pb");
-    }
-
-    @Test
-    public void canParseAllEntries() {
-        assertThat(mTrace.getEntries().get(0).getTimestamp()).isEqualTo(241777211939236L);
-        assertThat(mTrace.getEntries().get(mTrace.getEntries().size() - 1).getTimestamp()).isEqualTo
-                (241779809471942L);
-    }
-
-    @Test
-    public void canDetectAboveAppWindowVisibility() {
-        WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
-        Result result = entry.isAboveAppWindowVisible("NavigationBar");
-        assertThat(result.passed()).isTrue();
-    }
-
-    @Test
-    public void canDetectBelowAppWindowVisibility() {
-        WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
-        Result result = entry.isBelowAppWindowVisible("wallpaper");
-        assertThat(result.passed()).isTrue();
-    }
-
-    @Test
-    public void canDetectAppWindowVisibility() {
-        WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
-        Result result = entry.isAppWindowVisible("com.google.android.apps.nexuslauncher");
-        assertThat(result.passed()).isTrue();
-    }
-
-    @Test
-    public void canFailWithReasonForVisibilityChecks_windowNotFound() {
-        WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
-        Result result = entry.isAboveAppWindowVisible("ImaginaryWindow");
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains("ImaginaryWindow cannot be found");
-    }
-
-    @Test
-    public void canFailWithReasonForVisibilityChecks_windowNotVisible() {
-        WindowManagerTrace.Entry entry = mTrace.getEntry(241777211939236L);
-        Result result = entry.isAboveAppWindowVisible("AssistPreviewPanel");
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains("AssistPreviewPanel is invisible");
-    }
-
-    @Test
-    public void canDetectAppZOrder() {
-        WindowManagerTrace.Entry entry = mTrace.getEntry(241778130296410L);
-        Result result = entry.isVisibleAppWindowOnTop("com.google.android.apps.chrome");
-        assertThat(result.passed()).isTrue();
-    }
-
-    @Test
-    public void canFailWithReasonForZOrderChecks_windowNotOnTop() {
-        WindowManagerTrace.Entry entry = mTrace.getEntry(241778130296410L);
-        Result result = entry.isVisibleAppWindowOnTop("com.google.android.apps.nexuslauncher");
-        assertThat(result.failed()).isTrue();
-        assertThat(result.reason).contains("wanted=com.google.android.apps.nexuslauncher");
-        assertThat(result.reason).contains("found=com.android.chrome/"
-                + "com.google.android.apps.chrome.Main");
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WmTraceSubjectTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WmTraceSubjectTest.java
deleted file mode 100644
index d547a18..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/WmTraceSubjectTest.java
+++ /dev/null
@@ -1,49 +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.flicker;
-
-import static com.android.server.wm.flicker.TestFileUtils.readTestFile;
-import static com.android.server.wm.flicker.WmTraceSubject.assertThat;
-
-import org.junit.Test;
-
-/**
- * Contains {@link WmTraceSubject} tests.
- * To run this test: {@code atest FlickerLibTest:WmTraceSubjectTest}
- */
-public class WmTraceSubjectTest {
-    private static WindowManagerTrace readWmTraceFromFile(String relativePath) {
-        try {
-            return WindowManagerTrace.parseFrom(readTestFile(relativePath));
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    @Test
-    public void testCanTransitionInAppWindow() {
-        WindowManagerTrace trace = readWmTraceFromFile("wm_trace_openchrome2.pb");
-
-        assertThat(trace).showsAppWindowOnTop("com.google.android.apps.nexuslauncher/"
-                + ".NexusLauncherActivity").forRange(174684850717208L, 174685957511016L);
-        assertThat(trace).showsAppWindowOnTop(
-                "com.google.android.apps.nexuslauncher/.NexusLauncherActivity")
-                .then()
-                .showsAppWindowOnTop("com.android.chrome")
-                .forAllEntries();
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/LayersTraceMonitorTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/LayersTraceMonitorTest.java
deleted file mode 100644
index dbd6761..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/LayersTraceMonitorTest.java
+++ /dev/null
@@ -1,78 +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.flicker.monitor;
-
-import static android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto.MAGIC_NUMBER_H;
-import static android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto.MAGIC_NUMBER_L;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.surfaceflinger.nano.Layerstrace.LayersTraceFileProto;
-
-import com.google.common.io.Files;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-
-/**
- * Contains {@link LayersTraceMonitor} tests.
- * To run this test: {@code atest FlickerLibTest:LayersTraceMonitorTest}
- */
-public class LayersTraceMonitorTest {
-    private LayersTraceMonitor mLayersTraceMonitor;
-
-    @Before
-    public void setup() {
-        mLayersTraceMonitor = new LayersTraceMonitor();
-    }
-
-    @After
-    public void teardown() {
-        mLayersTraceMonitor.stop();
-        mLayersTraceMonitor.getOutputTraceFilePath("captureLayersTrace").toFile().delete();
-    }
-
-    @Test
-    public void canStartLayersTrace() throws Exception {
-        mLayersTraceMonitor.start();
-        assertThat(mLayersTraceMonitor.isEnabled()).isTrue();
-    }
-
-    @Test
-    public void canStopLayersTrace() throws Exception {
-        mLayersTraceMonitor.start();
-        assertThat(mLayersTraceMonitor.isEnabled()).isTrue();
-        mLayersTraceMonitor.stop();
-        assertThat(mLayersTraceMonitor.isEnabled()).isFalse();
-    }
-
-    @Test
-    public void captureLayersTrace() throws Exception {
-        mLayersTraceMonitor.start();
-        mLayersTraceMonitor.stop();
-        File testFile = mLayersTraceMonitor.save("captureLayersTrace").toFile();
-        assertThat(testFile.exists()).isTrue();
-        byte[] trace = Files.toByteArray(testFile);
-        assertThat(trace.length).isGreaterThan(0);
-        LayersTraceFileProto mLayerTraceFileProto = LayersTraceFileProto.parseFrom(trace);
-        assertThat(mLayerTraceFileProto.magicNumber).isEqualTo(
-                (long) MAGIC_NUMBER_H << 32 | MAGIC_NUMBER_L);
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/ScreenRecorderTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/ScreenRecorderTest.java
deleted file mode 100644
index e73eecc..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/ScreenRecorderTest.java
+++ /dev/null
@@ -1,70 +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.flicker.monitor;
-
-import static android.os.SystemClock.sleep;
-
-import static com.android.server.wm.flicker.monitor.ScreenRecorder.DEFAULT_OUTPUT_PATH;
-import static com.android.server.wm.flicker.monitor.ScreenRecorder.getPath;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-import java.io.IOException;
-
-/**
- * Contains {@link ScreenRecorder} tests.
- * To run this test: {@code atest FlickerLibTest:ScreenRecorderTest}
- */
-public class ScreenRecorderTest {
-    private static final String TEST_VIDEO_FILENAME = "test.mp4";
-    private ScreenRecorder mScreenRecorder;
-
-    @Before
-    public void setup() {
-        mScreenRecorder = new ScreenRecorder();
-    }
-
-    @After
-    public void teardown() {
-        DEFAULT_OUTPUT_PATH.toFile().delete();
-        getPath(TEST_VIDEO_FILENAME).toFile().delete();
-    }
-
-    @Test
-    public void videoIsRecorded() {
-        mScreenRecorder.start();
-        sleep(100);
-        mScreenRecorder.stop();
-        File file = DEFAULT_OUTPUT_PATH.toFile();
-        assertThat(file.exists()).isTrue();
-    }
-
-    @Test
-    public void videoCanBeSaved() {
-        mScreenRecorder.start();
-        sleep(100);
-        mScreenRecorder.stop();
-        mScreenRecorder.save(TEST_VIDEO_FILENAME);
-        File file = getPath(TEST_VIDEO_FILENAME).toFile();
-        assertThat(file.exists()).isTrue();
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitorTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitorTest.java
deleted file mode 100644
index f312384..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowAnimationFrameStatsMonitorTest.java
+++ /dev/null
@@ -1,50 +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.flicker.monitor;
-
-import static com.android.server.wm.flicker.helpers.AutomationUtils.wakeUpAndGoToHomeScreen;
-
-import androidx.test.InstrumentationRegistry;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * Contains {@link WindowAnimationFrameStatsMonitor} tests.
- * To run this test: {@code atest FlickerLibTest:WindowAnimationFrameStatsMonitorTest}
- */
-public class WindowAnimationFrameStatsMonitorTest {
-    private WindowAnimationFrameStatsMonitor mWindowAnimationFrameStatsMonitor;
-
-    @Before
-    public void setup() {
-        mWindowAnimationFrameStatsMonitor = new WindowAnimationFrameStatsMonitor(
-                InstrumentationRegistry.getInstrumentation());
-        wakeUpAndGoToHomeScreen();
-    }
-
-    // TODO(vishnun)
-    @Ignore("Disabled until app-helper libraries are available.")
-    @Test
-    public void captureWindowAnimationFrameStats() throws Exception {
-        mWindowAnimationFrameStatsMonitor.start();
-        //AppHelperWrapper.getInstance().getHelper(CHROME).open();
-        //AppHelperWrapper.getInstance().getHelper(CHROME).exit();
-        mWindowAnimationFrameStatsMonitor.stop();
-    }
-}
diff --git a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitorTest.java b/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitorTest.java
deleted file mode 100644
index 56284d7..0000000
--- a/tests/FlickerTests/lib/test/src/com/android/server/wm/flicker/monitor/WindowManagerTraceMonitorTest.java
+++ /dev/null
@@ -1,79 +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.flicker.monitor;
-
-import static com.android.server.wm.nano.WindowManagerTraceFileProto.MAGIC_NUMBER_H;
-import static com.android.server.wm.nano.WindowManagerTraceFileProto.MAGIC_NUMBER_L;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.android.server.wm.nano.WindowManagerTraceFileProto;
-
-import com.google.common.io.Files;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-
-/**
- * Contains {@link WindowManagerTraceMonitor} tests.
- * To run this test: {@code atest FlickerLibTest:WindowManagerTraceMonitorTest}
- */
-public class WindowManagerTraceMonitorTest {
-    private WindowManagerTraceMonitor mWindowManagerTraceMonitor;
-
-    @Before
-    public void setup() {
-        mWindowManagerTraceMonitor = new WindowManagerTraceMonitor();
-    }
-
-    @After
-    public void teardown() {
-        mWindowManagerTraceMonitor.stop();
-        mWindowManagerTraceMonitor.getOutputTraceFilePath("captureWindowTrace").toFile().delete();
-    }
-
-    @Test
-    public void canStartWindowTrace() throws Exception {
-        mWindowManagerTraceMonitor.start();
-        assertThat(mWindowManagerTraceMonitor.isEnabled()).isTrue();
-    }
-
-    @Test
-    public void canStopWindowTrace() throws Exception {
-        mWindowManagerTraceMonitor.start();
-        assertThat(mWindowManagerTraceMonitor.isEnabled()).isTrue();
-        mWindowManagerTraceMonitor.stop();
-        assertThat(mWindowManagerTraceMonitor.isEnabled()).isFalse();
-    }
-
-    @Test
-    public void captureWindowTrace() throws Exception {
-        mWindowManagerTraceMonitor.start();
-        mWindowManagerTraceMonitor.stop();
-        File testFile = mWindowManagerTraceMonitor.save("captureWindowTrace").toFile();
-        assertThat(testFile.exists()).isTrue();
-        byte[] trace = Files.toByteArray(testFile);
-        assertThat(trace.length).isGreaterThan(0);
-        WindowManagerTraceFileProto mWindowTraceFileProto = WindowManagerTraceFileProto.parseFrom(
-                trace);
-        assertThat(mWindowTraceFileProto.magicNumber).isEqualTo(
-                (long) MAGIC_NUMBER_H << 32 | MAGIC_NUMBER_L);
-    }
-}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java
index b6860cb..aa591d9 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/ChangeAppRotationTest.java
@@ -29,11 +29,15 @@
 import android.view.Surface;
 
 import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
 import androidx.test.filters.LargeTest;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
 import org.junit.runners.Parameterized;
 import org.junit.runners.Parameterized.Parameters;
 
@@ -44,18 +48,19 @@
  * Cycle through supported app rotations.
  * To run this test: {@code atest FlickerTest:ChangeAppRotationTest}
  */
-@RunWith(Parameterized.class)
 @LargeTest
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class ChangeAppRotationTest extends FlickerTestBase {
-    private int beginRotation;
-    private int endRotation;
+    private int mBeginRotation;
+    private int mEndRotation;
 
     public ChangeAppRotationTest(String beginRotationName, String endRotationName,
             int beginRotation, int endRotation) {
-        this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+        this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
                 "com.android.server.wm.flicker.testapp", "SimpleApp");
-        this.beginRotation = beginRotation;
-        this.endRotation = endRotation;
+        this.mBeginRotation = beginRotation;
+        this.mEndRotation = endRotation;
     }
 
     @Parameters(name = "{0}-{1}")
@@ -77,15 +82,19 @@
     @Before
     public void runTransition() {
         super.runTransition(
-                changeAppRotation(testApp, uiDevice, beginRotation, endRotation).build());
+                changeAppRotation(mTestApp, mUiDevice, mBeginRotation, mEndRotation).build());
     }
 
+    @FlakyTest(bugId = 140855415)
+    @Ignore("Waiting bug feedback")
     @Test
     public void checkVisibility_navBarWindowIsAlwaysVisible() {
         checkResults(result -> assertThat(result)
                 .showsAboveAppWindow(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
     }
 
+    @FlakyTest(bugId = 140855415)
+    @Ignore("Waiting bug feedback")
     @Test
     public void checkVisibility_statusBarWindowIsAlwaysVisible() {
         checkResults(result -> assertThat(result)
@@ -94,8 +103,8 @@
 
     @Test
     public void checkPosition_navBarLayerRotatesAndScales() {
-        Rect startingPos = getNavigationBarPosition(beginRotation);
-        Rect endingPos = getNavigationBarPosition(endRotation);
+        Rect startingPos = getNavigationBarPosition(mBeginRotation);
+        Rect endingPos = getNavigationBarPosition(mEndRotation);
         checkResults(result -> {
                     LayersTraceSubject.assertThat(result)
                             .hasVisibleRegion(NAVIGATION_BAR_WINDOW_TITLE, startingPos)
@@ -108,22 +117,22 @@
 
     @Test
     public void checkPosition_appLayerRotates() {
-        Rect startingPos = getAppPosition(beginRotation);
-        Rect endingPos = getAppPosition(endRotation);
+        Rect startingPos = getAppPosition(mBeginRotation);
+        Rect endingPos = getAppPosition(mEndRotation);
         Log.e(TAG, "startingPos=" + startingPos + " endingPos=" + endingPos);
         checkResults(result -> {
                     LayersTraceSubject.assertThat(result)
-                            .hasVisibleRegion(testApp.getPackage(), startingPos).inTheBeginning();
+                            .hasVisibleRegion(mTestApp.getPackage(), startingPos).inTheBeginning();
                     LayersTraceSubject.assertThat(result)
-                            .hasVisibleRegion(testApp.getPackage(), endingPos).atTheEnd();
+                            .hasVisibleRegion(mTestApp.getPackage(), endingPos).atTheEnd();
                 }
         );
     }
 
     @Test
     public void checkPosition_statusBarLayerScales() {
-        Rect startingPos = getStatusBarPosition(beginRotation);
-        Rect endingPos = getStatusBarPosition(endRotation);
+        Rect startingPos = getStatusBarPosition(mBeginRotation);
+        Rect endingPos = getStatusBarPosition(mEndRotation);
         checkResults(result -> {
                     LayersTraceSubject.assertThat(result)
                             .hasVisibleRegion(STATUS_BAR_WINDOW_TITLE, startingPos)
@@ -134,12 +143,16 @@
         );
     }
 
+    @FlakyTest(bugId = 140855415)
+    @Ignore("Waiting bug feedback")
     @Test
     public void checkVisibility_navBarLayerIsAlwaysVisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
                 .showsLayer(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
     }
 
+    @FlakyTest(bugId = 140855415)
+    @Ignore("Waiting bug feedback")
     @Test
     public void checkVisibility_statusBarLayerIsAlwaysVisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeAutoOpenWindowToAppTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeAutoOpenWindowToAppTest.java
new file mode 100644
index 0000000..022f798
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeAutoOpenWindowToAppTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2019 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.flicker;
+
+import static com.android.server.wm.flicker.CommonTransitions.editTextLoseFocusToApp;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.LargeTest;
+
+import com.android.server.wm.flicker.helpers.ImeAppAutoFocusHelper;
+
+import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
+
+/**
+ * Test IME window closing back to app window transitions.
+ * To run this test: {@code atest FlickerTests:CloseImeWindowToAppTest}
+ */
+@LargeTest
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class CloseImeAutoOpenWindowToAppTest extends CloseImeWindowToAppTest {
+
+    public CloseImeAutoOpenWindowToAppTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        mTestApp = new ImeAppAutoFocusHelper(InstrumentationRegistry.getInstrumentation());
+    }
+
+    @Before
+    public void runTransition() {
+        run(editTextLoseFocusToApp((ImeAppAutoFocusHelper) mTestApp, mUiDevice, mBeginRotation)
+                .includeJankyRuns().build());
+    }
+
+    @FlakyTest(bugId = 141458352)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkVisibility_imeLayerBecomesInvisible() {
+        super.checkVisibility_imeLayerBecomesInvisible();
+    }
+
+    @FlakyTest(bugId = 141458352)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkVisibility_imeAppLayerIsAlwaysVisible() {
+        super.checkVisibility_imeAppLayerIsAlwaysVisible();
+    }
+
+    @FlakyTest(bugId = 141458352)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkVisibility_imeAppWindowIsAlwaysVisible() {
+        super.checkVisibility_imeAppWindowIsAlwaysVisible();
+    }
+
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeAutoOpenWindowToHomeTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeAutoOpenWindowToHomeTest.java
new file mode 100644
index 0000000..d6f994b
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeAutoOpenWindowToHomeTest.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2019 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.flicker;
+
+import static com.android.server.wm.flicker.CommonTransitions.editTextLoseFocusToHome;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.LargeTest;
+
+import com.android.server.wm.flicker.helpers.ImeAppAutoFocusHelper;
+
+import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
+
+/**
+ * Test IME window closing back to app window transitions.
+ * To run this test: {@code atest FlickerTests:CloseImeWindowToAppTest}
+ */
+@LargeTest
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class CloseImeAutoOpenWindowToHomeTest extends CloseImeWindowToHomeTest {
+
+    public CloseImeAutoOpenWindowToHomeTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        mTestApp = new ImeAppAutoFocusHelper(InstrumentationRegistry.getInstrumentation());
+    }
+
+    @Before
+    public void runTransition() {
+        run(editTextLoseFocusToHome((ImeAppAutoFocusHelper) mTestApp, mUiDevice, mBeginRotation)
+                .includeJankyRuns().build());
+    }
+
+    @FlakyTest(bugId = 141458352)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkVisibility_imeWindowBecomesInvisible() {
+        super.checkVisibility_imeWindowBecomesInvisible();
+    }
+
+    @FlakyTest(bugId = 141458352)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkVisibility_imeLayerBecomesInvisible() {
+        super.checkVisibility_imeLayerBecomesInvisible();
+    }
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java
index 6590b86..28da3af 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToAppTest.java
@@ -17,34 +17,39 @@
 package com.android.server.wm.flicker;
 
 import static com.android.server.wm.flicker.CommonTransitions.editTextLoseFocusToApp;
-import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
-
-import android.platform.helpers.IAppHelper;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.LargeTest;
-import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.wm.flicker.helpers.ImeAppHelper;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
 
 /**
  * Test IME window closing back to app window transitions.
  * To run this test: {@code atest FlickerTests:CloseImeWindowToAppTest}
  */
 @LargeTest
-@RunWith(AndroidJUnit4.class)
-public class CloseImeWindowToAppTest extends FlickerTestBase {
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class CloseImeWindowToAppTest extends NonRotationTestBase {
 
-    private static final String IME_WINDOW_TITLE = "InputMethod";
-    private IAppHelper mImeTestApp = new StandardAppHelper(
-            InstrumentationRegistry.getInstrumentation(),
-            "com.android.server.wm.flicker.testapp", "ImeApp");
+    static final String IME_WINDOW_TITLE = "InputMethod";
+
+    public CloseImeWindowToAppTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        mTestApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+    }
 
     @Before
     public void runTransition() {
-        super.runTransition(editTextLoseFocusToApp(uiDevice)
+        run(editTextLoseFocusToApp((ImeAppHelper) mTestApp, mUiDevice, mBeginRotation)
                 .includeJankyRuns().build());
     }
 
@@ -60,20 +65,14 @@
     @Test
     public void checkVisibility_imeAppLayerIsAlwaysVisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(mImeTestApp.getPackage())
+                .showsLayer(mTestApp.getPackage())
                 .forAllEntries());
     }
 
     @Test
     public void checkVisibility_imeAppWindowIsAlwaysVisible() {
         checkResults(result -> WmTraceSubject.assertThat(result)
-                .showsAppWindowOnTop(mImeTestApp.getPackage())
+                .showsAppWindowOnTop(mTestApp.getPackage())
                 .forAllEntries());
     }
-
-    @Test
-    public void checkCoveredRegion_noUncoveredRegions() {
-        checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
-                getDisplayBounds()).forAllEntries());
-    }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java
index 4771b02..fc6719e 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CloseImeWindowToHomeTest.java
@@ -17,34 +17,39 @@
 package com.android.server.wm.flicker;
 
 import static com.android.server.wm.flicker.CommonTransitions.editTextLoseFocusToHome;
-import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
-
-import android.platform.helpers.IAppHelper;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.LargeTest;
-import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.wm.flicker.helpers.ImeAppHelper;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
 
 /**
  * Test IME window closing to home transitions.
  * To run this test: {@code atest FlickerTests:CloseImeWindowToHomeTest}
  */
 @LargeTest
-@RunWith(AndroidJUnit4.class)
-public class CloseImeWindowToHomeTest extends FlickerTestBase {
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class CloseImeWindowToHomeTest extends NonRotationTestBase {
 
-    private static final String IME_WINDOW_TITLE = "InputMethod";
-    private IAppHelper mImeTestApp = new StandardAppHelper(
-            InstrumentationRegistry.getInstrumentation(),
-            "com.android.server.wm.flicker.testapp", "ImeApp");
+    static final String IME_WINDOW_TITLE = "InputMethod";
+
+    public CloseImeWindowToHomeTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        mTestApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+    }
 
     @Before
     public void runTransition() {
-        super.runTransition(editTextLoseFocusToHome(uiDevice)
+        run(editTextLoseFocusToHome((ImeAppHelper) mTestApp, mUiDevice, mBeginRotation)
                 .includeJankyRuns().build());
     }
 
@@ -69,24 +74,18 @@
     @Test
     public void checkVisibility_imeAppLayerBecomesInvisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(mImeTestApp.getPackage())
+                .showsLayer(mTestApp.getPackage())
                 .then()
-                .hidesLayer(mImeTestApp.getPackage())
+                .hidesLayer(mTestApp.getPackage())
                 .forAllEntries());
     }
 
     @Test
     public void checkVisibility_imeAppWindowBecomesInvisible() {
         checkResults(result -> WmTraceSubject.assertThat(result)
-                .showsAppWindowOnTop(mImeTestApp.getPackage())
+                .showsAppWindowOnTop(mTestApp.getPackage())
                 .then()
-                .hidesAppWindowOnTop(mImeTestApp.getPackage())
+                .hidesAppWindowOnTop(mTestApp.getPackage())
                 .forAllEntries());
     }
-
-    @Test
-    public void checkCoveredRegion_noUncoveredRegions() {
-        checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
-                getDisplayBounds()).forAllEntries());
-    }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java b/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java
index 5cf2c1c..fd31aa5 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/CommonTransitions.java
@@ -37,10 +37,10 @@
 import android.util.Rational;
 import android.view.Surface;
 
-import androidx.test.InstrumentationRegistry;
-
 import com.android.server.wm.flicker.TransitionRunner.TransitionBuilder;
 import com.android.server.wm.flicker.helpers.AutomationUtils;
+import com.android.server.wm.flicker.helpers.ImeAppHelper;
+import com.android.server.wm.flicker.helpers.PipAppHelper;
 
 /**
  * Collection of common transitions which can be used to test different apps or scenarios.
@@ -67,32 +67,23 @@
                     device.setOrientationNatural();
             }
             // Wait for animation to complete
-            sleep(3000);
+            sleep(1000);
         } catch (RemoteException e) {
             throw new RuntimeException(e);
         }
     }
 
-    private static void clickEditTextWidget(UiDevice device, IAppHelper testApp) {
-        UiObject2 editText = device.findObject(By.res(testApp.getPackage(), "plain_text_input"));
-        editText.click();
-        sleep(500);
-    }
-
-    private static void clickEnterPipButton(UiDevice device, IAppHelper testApp) {
-        UiObject2 enterPipButton = device.findObject(By.res(testApp.getPackage(), "enter_pip"));
-        enterPipButton.click();
-        sleep(500);
-    }
-
     static TransitionBuilder openAppWarm(IAppHelper testApp, UiDevice
-            device) {
+            device, int beginRotation) {
         return TransitionRunner.newBuilder()
-                .withTag("OpenAppWarm_" + testApp.getLauncherName())
+                .withTag("OpenAppWarm_" + testApp.getLauncherName()
+                        + rotationToString(beginRotation))
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
+                .runBeforeAll(() -> setRotation(device, beginRotation))
                 .runBeforeAll(testApp::open)
                 .runBefore(device::pressHome)
                 .runBefore(device::waitForIdle)
+                .runBefore(() -> setRotation(device, beginRotation))
                 .run(testApp::open)
                 .runAfterAll(testApp::exit)
                 .runAfterAll(AutomationUtils::setDefaultWait)
@@ -127,16 +118,19 @@
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder getOpenAppCold(IAppHelper testApp,
-            UiDevice device) {
+    static TransitionBuilder openAppCold(IAppHelper testApp,
+            UiDevice device, int beginRotation) {
         return TransitionRunner.newBuilder()
-                .withTag("OpenAppCold_" + testApp.getLauncherName())
+                .withTag("OpenAppCold_" + testApp.getLauncherName()
+                        + rotationToString(beginRotation))
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
                 .runBefore(device::pressHome)
+                .runBeforeAll(() -> setRotation(device, beginRotation))
                 .runBefore(testApp::exit)
                 .runBefore(device::waitForIdle)
                 .run(testApp::open)
                 .runAfterAll(testApp::exit)
+                .runAfterAll(() -> setRotation(device, Surface.ROTATION_0))
                 .repeat(ITERATIONS);
     }
 
@@ -201,28 +195,31 @@
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder editTextSetFocus(UiDevice device) {
-        IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "ImeApp");
+    static TransitionBuilder editTextSetFocus(ImeAppHelper testApp, UiDevice device,
+            int beginRotation) {
         return TransitionRunner.newBuilder()
-                .withTag("editTextSetFocus_" + testApp.getLauncherName())
+                .withTag("editTextSetFocus_" + testApp.getLauncherName()
+                        + rotationToString(beginRotation))
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
                 .runBefore(device::pressHome)
+                .runBefore(() -> setRotation(device, beginRotation))
                 .runBefore(testApp::open)
-                .run(() -> clickEditTextWidget(device, testApp))
+                .run(() -> testApp.clickEditTextWidget(device))
                 .runAfterAll(testApp::exit)
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder resizeSplitScreen(IAppHelper testAppTop, IAppHelper testAppBottom,
-            UiDevice device, Rational startRatio, Rational stopRatio) {
-        String testTag = "resizeSplitScreen_" + testAppTop.getLauncherName() + "_" +
-                testAppBottom.getLauncherName() + "_" +
-                startRatio.toString().replace("/", ":") + "_to_" +
-                stopRatio.toString().replace("/", ":");
+    static TransitionBuilder resizeSplitScreen(IAppHelper testAppTop, ImeAppHelper testAppBottom,
+            UiDevice device, int beginRotation, Rational startRatio, Rational stopRatio) {
+        String testTag = "resizeSplitScreen_" + testAppTop.getLauncherName() + "_"
+                + testAppBottom.getLauncherName() + "_"
+                + startRatio.toString().replace("/", ":") + "_to_"
+                + stopRatio.toString().replace("/", ":") + "_"
+                + rotationToString(beginRotation);
         return TransitionRunner.newBuilder()
                 .withTag(testTag)
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
+                .runBeforeAll(() -> setRotation(device, beginRotation))
                 .runBeforeAll(() -> clearRecents(device))
                 .runBefore(testAppBottom::open)
                 .runBefore(device::pressHome)
@@ -231,9 +228,10 @@
                 .runBefore(() -> launchSplitScreen(device))
                 .runBefore(() -> {
                     UiObject2 snapshot = device.findObject(
-                            By.res("com.google.android.apps.nexuslauncher", "snapshot"));
+                            By.res(device.getLauncherPackageName(), "snapshot"));
                     snapshot.click();
                 })
+                .runBefore(() -> testAppBottom.clickEditTextWidget(device))
                 .runBefore(() -> AutomationUtils.resizeSplitScreen(device, startRatio))
                 .run(() -> AutomationUtils.resizeSplitScreen(device, stopRatio))
                 .runAfter(() -> exitSplitScreen(device))
@@ -243,77 +241,73 @@
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder editTextLoseFocusToHome(UiDevice device) {
-        IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "ImeApp");
+    static TransitionBuilder editTextLoseFocusToHome(ImeAppHelper testApp, UiDevice device,
+            int beginRotation) {
         return TransitionRunner.newBuilder()
-                .withTag("editTextLoseFocusToHome_" + testApp.getLauncherName())
+                .withTag("editTextLoseFocusToHome_" + testApp.getLauncherName()
+                        + rotationToString(beginRotation))
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
                 .runBefore(device::pressHome)
+                .runBefore(() -> setRotation(device, beginRotation))
                 .runBefore(testApp::open)
-                .runBefore(() -> clickEditTextWidget(device, testApp))
+                .runBefore(() -> testApp.clickEditTextWidget(device))
                 .run(device::pressHome)
                 .run(device::waitForIdle)
                 .runAfterAll(testApp::exit)
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder editTextLoseFocusToApp(UiDevice device) {
-        IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "ImeApp");
+    static TransitionBuilder editTextLoseFocusToApp(ImeAppHelper testApp, UiDevice device,
+            int beginRotation) {
         return TransitionRunner.newBuilder()
-                .withTag("editTextLoseFocusToApp_" + testApp.getLauncherName())
+                .withTag("editTextLoseFocusToApp_" + testApp.getLauncherName()
+                        + rotationToString(beginRotation))
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
                 .runBefore(device::pressHome)
+                .runBefore(() -> setRotation(device, beginRotation))
                 .runBefore(testApp::open)
-                .runBefore(() -> clickEditTextWidget(device, testApp))
+                .runBefore(() -> testApp.clickEditTextWidget(device))
                 .run(device::pressBack)
                 .run(device::waitForIdle)
                 .runAfterAll(testApp::exit)
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder enterPipMode(UiDevice device) {
-        IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "PipApp");
+    static TransitionBuilder enterPipMode(PipAppHelper testApp, UiDevice device) {
         return TransitionRunner.newBuilder()
                 .withTag("enterPipMode_" + testApp.getLauncherName())
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
                 .runBefore(device::pressHome)
                 .runBefore(testApp::open)
-                .run(() -> clickEnterPipButton(device, testApp))
+                .run(() -> testApp.clickEnterPipButton(device))
                 .runAfter(() -> closePipWindow(device))
                 .runAfterAll(testApp::exit)
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder exitPipModeToHome(UiDevice device) {
-        IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "PipApp");
+    static TransitionBuilder exitPipModeToHome(PipAppHelper testApp, UiDevice device) {
         return TransitionRunner.newBuilder()
                 .withTag("exitPipModeToHome_" + testApp.getLauncherName())
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
                 .runBefore(device::pressHome)
                 .runBefore(testApp::open)
-                .runBefore(() -> clickEnterPipButton(device, testApp))
+                .runBefore(() -> testApp.clickEnterPipButton(device))
                 .run(() -> closePipWindow(device))
                 .run(device::waitForIdle)
                 .runAfterAll(testApp::exit)
                 .repeat(ITERATIONS);
     }
 
-    static TransitionBuilder exitPipModeToApp(UiDevice device) {
-        IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "PipApp");
+    static TransitionBuilder exitPipModeToApp(PipAppHelper testApp, UiDevice device) {
         return TransitionRunner.newBuilder()
                 .withTag("exitPipModeToApp_" + testApp.getLauncherName())
                 .runBeforeAll(AutomationUtils::wakeUpAndGoToHomeScreen)
                 .runBefore(device::pressHome)
                 .runBefore(testApp::open)
-                .runBefore(() -> clickEnterPipButton(device, testApp))
+                .runBefore(() -> testApp.clickEnterPipButton(device))
                 .run(() -> expandPipWindow(device))
                 .run(device::waitForIdle)
                 .runAfterAll(testApp::exit)
                 .repeat(ITERATIONS);
     }
-}
\ No newline at end of file
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java
index 61cca0d..8f0177c 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/DebugTest.java
@@ -22,40 +22,50 @@
 import android.view.Surface;
 
 import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.LargeTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.server.wm.flicker.helpers.ImeAppHelper;
+import com.android.server.wm.flicker.helpers.PipAppHelper;
+
+import org.junit.FixMethodOrder;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
 
 /**
  * Tests to help debug individual transitions, capture video recordings and create test cases.
  */
+@LargeTest
 @Ignore("Used for debugging transitions used in FlickerTests.")
 @RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class DebugTest {
     private IAppHelper testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
             "com.android.server.wm.flicker.testapp", "SimpleApp");
     private UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
 
     /**
-     * atest FlickerTest:DebugTests#openAppCold
+     * atest FlickerTests:DebugTest#openAppCold
      */
     @Test
     public void openAppCold() {
-        CommonTransitions.getOpenAppCold(testApp, uiDevice).recordAllRuns().build().run();
+        CommonTransitions.openAppCold(testApp, uiDevice, Surface.ROTATION_0)
+                .recordAllRuns().build().run();
     }
 
     /**
-     * atest FlickerTest:DebugTests#openAppWarm
+     * atest FlickerTests:DebugTest#openAppWarm
      */
     @Test
     public void openAppWarm() {
-        CommonTransitions.openAppWarm(testApp, uiDevice).recordAllRuns().build().run();
+        CommonTransitions.openAppWarm(testApp, uiDevice, Surface.ROTATION_0)
+                .recordAllRuns().build().run();
     }
 
     /**
-     * atest FlickerTest:DebugTests#changeOrientationFromNaturalToLeft
+     * atest FlickerTests:DebugTest#changeOrientationFromNaturalToLeft
      */
     @Test
     public void changeOrientationFromNaturalToLeft() {
@@ -64,7 +74,7 @@
     }
 
     /**
-     * atest FlickerTest:DebugTests#closeAppWithBackKey
+     * atest FlickerTests:DebugTest#closeAppWithBackKey
      */
     @Test
     public void closeAppWithBackKey() {
@@ -72,7 +82,7 @@
     }
 
     /**
-     * atest FlickerTest:DebugTests#closeAppWithHomeKey
+     * atest FlickerTests:DebugTest#closeAppWithHomeKey
      */
     @Test
     public void closeAppWithHomeKey() {
@@ -80,7 +90,7 @@
     }
 
     /**
-     * atest FlickerTest:DebugTests#openAppToSplitScreen
+     * atest FlickerTests:DebugTest#openAppToSplitScreen
      */
     @Test
     public void openAppToSplitScreen() {
@@ -89,7 +99,7 @@
     }
 
     /**
-     * atest FlickerTest:DebugTests#splitScreenToLauncher
+     * atest FlickerTests:DebugTest#splitScreenToLauncher
      */
     @Test
     public void splitScreenToLauncher() {
@@ -99,70 +109,80 @@
     }
 
     /**
-     * atest FlickerTest:DebugTests#resizeSplitScreen
+     * atest FlickerTests:DebugTest#resizeSplitScreen
      */
     @Test
     public void resizeSplitScreen() {
-        IAppHelper bottomApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "ImeApp");
-        CommonTransitions.resizeSplitScreen(testApp, bottomApp, uiDevice, new Rational(1, 3),
-                new Rational(2, 3)).includeJankyRuns().recordEachRun().build().run();
+        ImeAppHelper bottomApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+        CommonTransitions.resizeSplitScreen(testApp, bottomApp, uiDevice, Surface.ROTATION_0,
+                new Rational(1, 3), new Rational(2, 3))
+                .includeJankyRuns().recordEachRun().build().run();
     }
 
     // IME tests
 
     /**
-     * atest FlickerTest:DebugTests#editTextSetFocus
+     * atest FlickerTests:DebugTest#editTextSetFocus
      */
     @Test
     public void editTextSetFocus() {
-        CommonTransitions.editTextSetFocus(uiDevice).includeJankyRuns().recordEachRun()
+        ImeAppHelper testApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+        CommonTransitions.editTextSetFocus(testApp, uiDevice, Surface.ROTATION_0)
+                .includeJankyRuns().recordEachRun()
                 .build().run();
     }
 
     /**
-     * atest FlickerTest:DebugTests#editTextLoseFocusToHome
+     * atest FlickerTests:DebugTest#editTextLoseFocusToHome
      */
     @Test
     public void editTextLoseFocusToHome() {
-        CommonTransitions.editTextLoseFocusToHome(uiDevice).includeJankyRuns().recordEachRun()
+        ImeAppHelper testApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+        CommonTransitions.editTextLoseFocusToHome(testApp, uiDevice, Surface.ROTATION_0)
+                .includeJankyRuns().recordEachRun()
                 .build().run();
     }
 
     /**
-     * atest FlickerTest:DebugTests#editTextLoseFocusToApp
+     * atest FlickerTests:DebugTest#editTextLoseFocusToApp
      */
     @Test
     public void editTextLoseFocusToApp() {
-        CommonTransitions.editTextLoseFocusToHome(uiDevice).includeJankyRuns().recordEachRun()
+        ImeAppHelper testApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+        CommonTransitions.editTextLoseFocusToHome(testApp, uiDevice, Surface.ROTATION_0)
+                .includeJankyRuns().recordEachRun()
                 .build().run();
     }
 
     // PIP tests
 
     /**
-     * atest FlickerTest:DebugTests#enterPipMode
+     * atest FlickerTests:DebugTest#enterPipMode
      */
     @Test
     public void enterPipMode() {
-        CommonTransitions.enterPipMode(uiDevice).includeJankyRuns().recordEachRun().build().run();
-    }
-
-    /**
-     * atest FlickerTest:DebugTests#exitPipModeToHome
-     */
-    @Test
-    public void exitPipModeToHome() {
-        CommonTransitions.exitPipModeToHome(uiDevice).includeJankyRuns().recordEachRun()
+        PipAppHelper testApp = new PipAppHelper(InstrumentationRegistry.getInstrumentation());
+        CommonTransitions.enterPipMode(testApp, uiDevice).includeJankyRuns().recordEachRun()
                 .build().run();
     }
 
     /**
-     * atest FlickerTest:DebugTests#exitPipModeToApp
+     * atest FlickerTests:DebugTest#exitPipModeToHome
+     */
+    @Test
+    public void exitPipModeToHome() {
+        PipAppHelper testApp = new PipAppHelper(InstrumentationRegistry.getInstrumentation());
+        CommonTransitions.exitPipModeToHome(testApp, uiDevice).includeJankyRuns().recordEachRun()
+                .build().run();
+    }
+
+    /**
+     * atest FlickerTests:DebugTest#exitPipModeToApp
      */
     @Test
     public void exitPipModeToApp() {
-        CommonTransitions.exitPipModeToApp(uiDevice).includeJankyRuns().recordEachRun()
+        PipAppHelper testApp = new PipAppHelper(InstrumentationRegistry.getInstrumentation());
+        CommonTransitions.exitPipModeToApp(testApp, uiDevice).includeJankyRuns().recordEachRun()
                 .build().run();
     }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java b/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java
index 8c9d6b4d..883d59e 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/FlickerTestBase.java
@@ -16,20 +16,23 @@
 
 package com.android.server.wm.flicker;
 
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
 import static com.android.server.wm.flicker.helpers.AutomationUtils.setDefaultWait;
 
 import static com.google.common.truth.Truth.assertWithMessage;
 
+import android.os.Bundle;
 import android.platform.helpers.IAppHelper;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.uiautomator.UiDevice;
 import android.util.Log;
 
-import androidx.test.InstrumentationRegistry;
-
 import com.android.server.wm.flicker.TransitionRunner.TransitionResult;
 
 import org.junit.After;
 import org.junit.AfterClass;
+import org.junit.Before;
 
 import java.util.HashMap;
 import java.util.List;
@@ -51,10 +54,16 @@
     static final String DOCKED_STACK_DIVIDER = "DockedStackDivider";
     private static HashMap<String, List<TransitionResult>> transitionResults =
             new HashMap<>();
-    IAppHelper testApp;
-    UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
-    private List<TransitionResult> results;
-    private TransitionResult lastResult = null;
+    IAppHelper mTestApp;
+    UiDevice mUiDevice;
+    private List<TransitionResult> mResults;
+    private TransitionResult mLastResult = null;
+
+    @Before
+    public void setUp() {
+        InstrumentationRegistry.registerInstance(getInstrumentation(), new Bundle());
+        mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+    }
 
     /**
      * Teardown any system settings and clean up test artifacts from the file system.
@@ -89,16 +98,23 @@
     /**
      * Runs a transition, returns a cached result if the transition has run before.
      */
-    void runTransition(TransitionRunner transition) {
+    void run(TransitionRunner transition) {
         if (transitionResults.containsKey(transition.getTestTag())) {
-            results = transitionResults.get(transition.getTestTag());
+            mResults = transitionResults.get(transition.getTestTag());
             return;
         }
-        results = transition.run().getResults();
+        mResults = transition.run().getResults();
         /* Fail if we don't have any results due to jank */
         assertWithMessage("No results to test because all transition runs were invalid because "
-                + "of Jank").that(results).isNotEmpty();
-        transitionResults.put(transition.getTestTag(), results);
+                + "of Jank").that(mResults).isNotEmpty();
+        transitionResults.put(transition.getTestTag(), mResults);
+    }
+
+    /**
+     * Runs a transition, returns a cached result if the transition has run before.
+     */
+    void runTransition(TransitionRunner transition) {
+        run(transition);
     }
 
     /**
@@ -106,11 +122,11 @@
      */
     void checkResults(Consumer<TransitionResult> assertion) {
 
-        for (TransitionResult result : results) {
-            lastResult = result;
+        for (TransitionResult result : mResults) {
+            mLastResult = result;
             assertion.accept(result);
         }
-        lastResult = null;
+        mLastResult = null;
     }
 
     /**
@@ -119,8 +135,8 @@
      */
     @After
     public void markArtifactsForSaving() {
-        if (lastResult != null) {
-            lastResult.flagForSaving();
+        if (mLastResult != null) {
+            mLastResult.flagForSaving();
         }
     }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/NonRotationTestBase.java b/tests/FlickerTests/src/com/android/server/wm/flicker/NonRotationTestBase.java
new file mode 100644
index 0000000..54941dc
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/NonRotationTestBase.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2019 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.flicker;
+
+import static android.view.Surface.rotationToString;
+
+import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
+
+import android.graphics.Rect;
+import android.view.Surface;
+
+import androidx.test.filters.FlakyTest;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runners.Parameterized.Parameters;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public abstract class NonRotationTestBase extends FlickerTestBase {
+
+    int mBeginRotation;
+
+    public NonRotationTestBase(String beginRotationName, int beginRotation) {
+        this.mBeginRotation = beginRotation;
+    }
+
+    @Parameters(name = "{0}")
+    public static Collection<Object[]> getParams() {
+        int[] supportedRotations =
+                {Surface.ROTATION_0, Surface.ROTATION_90};
+        Collection<Object[]> params = new ArrayList<>();
+
+        for (int begin : supportedRotations) {
+            params.add(new Object[]{rotationToString(begin), begin});
+        }
+
+        return params;
+    }
+
+    @FlakyTest(bugId = 141361128)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkCoveredRegion_noUncoveredRegions() {
+        Rect displayBounds = getDisplayBounds(mBeginRotation);
+        checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
+                displayBounds).forAllEntries());
+    }
+
+    @FlakyTest(bugId = 141361128)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkVisibility_navBarLayerIsAlwaysVisible() {
+        checkResults(result -> LayersTraceSubject.assertThat(result)
+                .showsLayer(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
+    }
+
+    @FlakyTest(bugId = 141361128)
+    @Ignore("Waiting bug feedback")
+    @Test
+    public void checkVisibility_statusBarLayerIsAlwaysVisible() {
+        checkResults(result -> LayersTraceSubject.assertThat(result)
+                .showsLayer(STATUS_BAR_WINDOW_TITLE).forAllEntries());
+    }
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java
index 7818c4e..efdfaee 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppColdTest.java
@@ -16,91 +16,70 @@
 
 package com.android.server.wm.flicker;
 
-import static com.android.server.wm.flicker.CommonTransitions.getOpenAppCold;
-import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
+import static com.android.server.wm.flicker.CommonTransitions.openAppCold;
 import static com.android.server.wm.flicker.WmTraceSubject.assertThat;
 
 import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
 import androidx.test.filters.LargeTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
 
 /**
  * Test cold launch app from launcher.
  * To run this test: {@code atest FlickerTests:OpenAppColdTest}
  */
 @LargeTest
-@RunWith(AndroidJUnit4.class)
-public class OpenAppColdTest extends FlickerTestBase {
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class OpenAppColdTest extends NonRotationTestBase {
 
-    public OpenAppColdTest() {
-        this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+    public OpenAppColdTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
                 "com.android.server.wm.flicker.testapp", "SimpleApp");
     }
 
     @Before
     public void runTransition() {
-        super.runTransition(getOpenAppCold(testApp, uiDevice).build());
-    }
-
-    @Test
-    public void checkVisibility_navBarWindowIsAlwaysVisible() {
-        checkResults(result -> assertThat(result)
-                .showsAboveAppWindow(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
-    }
-
-    @Test
-    public void checkVisibility_statusBarWindowIsAlwaysVisible() {
-        checkResults(result -> assertThat(result)
-                .showsAboveAppWindow(STATUS_BAR_WINDOW_TITLE).forAllEntries());
+        run(openAppCold(mTestApp, mUiDevice, mBeginRotation)
+                .includeJankyRuns().build());
     }
 
     @Test
     public void checkVisibility_wallpaperWindowBecomesInvisible() {
         checkResults(result -> assertThat(result)
-                .showsBelowAppWindow("wallpaper")
+                .showsBelowAppWindow("Wallpaper")
                 .then()
-                .hidesBelowAppWindow("wallpaper")
+                .hidesBelowAppWindow("Wallpaper")
                 .forAllEntries());
     }
 
+    @FlakyTest(bugId = 140855415)
+    @Ignore("Waiting bug feedback")
     @Test
     public void checkZOrder_appWindowReplacesLauncherAsTopWindow() {
         checkResults(result -> assertThat(result)
                 .showsAppWindowOnTop(
-                        "com.google.android.apps.nexuslauncher/.NexusLauncherActivity")
+                        "com.android.launcher3/.Launcher")
                 .then()
-                .showsAppWindowOnTop(testApp.getPackage())
+                .showsAppWindowOnTop(mTestApp.getPackage())
                 .forAllEntries());
     }
 
     @Test
-    public void checkCoveredRegion_noUncoveredRegions() {
-        checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
-                getDisplayBounds()).forAllEntries());
-    }
-
-    @Test
-    public void checkVisibility_navBarLayerIsAlwaysVisible() {
-        checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
-    }
-
-    @Test
-    public void checkVisibility_statusBarLayerIsAlwaysVisible() {
-        checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(STATUS_BAR_WINDOW_TITLE).forAllEntries());
-    }
-
-    @Test
     public void checkVisibility_wallpaperLayerBecomesInvisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer("wallpaper")
+                .showsLayer("Wallpaper")
                 .then()
-                .hidesLayer("wallpaper")
+                .hidesLayer("Wallpaper")
                 .forAllEntries());
     }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java
index 63018ec..f8b7938 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppToSplitScreenTest.java
@@ -24,8 +24,10 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
 
 /**
  * Test open app to split screen.
@@ -33,16 +35,17 @@
  */
 @LargeTest
 @RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class OpenAppToSplitScreenTest extends FlickerTestBase {
 
     public OpenAppToSplitScreenTest() {
-        this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+        this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
                 "com.android.server.wm.flicker.testapp", "SimpleApp");
     }
 
     @Before
     public void runTransition() {
-        super.runTransition(appToSplitScreen(testApp, uiDevice).includeJankyRuns().build());
+        super.runTransition(appToSplitScreen(mTestApp, mUiDevice).includeJankyRuns().build());
     }
 
     @Test
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java
index 1aba930..7ce6315 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenAppWarmTest.java
@@ -17,90 +17,69 @@
 package com.android.server.wm.flicker;
 
 import static com.android.server.wm.flicker.CommonTransitions.openAppWarm;
-import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
 import static com.android.server.wm.flicker.WmTraceSubject.assertThat;
 
 import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
 import androidx.test.filters.LargeTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
 
 /**
  * Test warm launch app.
  * To run this test: {@code atest FlickerTests:OpenAppWarmTest}
  */
 @LargeTest
-@RunWith(AndroidJUnit4.class)
-public class OpenAppWarmTest extends FlickerTestBase {
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class OpenAppWarmTest extends NonRotationTestBase {
 
-    public OpenAppWarmTest() {
-        this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+    public OpenAppWarmTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
                 "com.android.server.wm.flicker.testapp", "SimpleApp");
     }
 
     @Before
     public void runTransition() {
-        super.runTransition(openAppWarm(testApp, uiDevice).build());
-    }
-
-    @Test
-    public void checkVisibility_navBarIsAlwaysVisible() {
-        checkResults(result -> assertThat(result)
-                .showsAboveAppWindow(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
-    }
-
-    @Test
-    public void checkVisibility_statusBarIsAlwaysVisible() {
-        checkResults(result -> assertThat(result)
-                .showsAboveAppWindow(STATUS_BAR_WINDOW_TITLE).forAllEntries());
+        super.runTransition(openAppWarm(mTestApp, mUiDevice, mBeginRotation)
+                .includeJankyRuns().build());
     }
 
     @Test
     public void checkVisibility_wallpaperBecomesInvisible() {
         checkResults(result -> assertThat(result)
-                .showsBelowAppWindow("wallpaper")
+                .showsBelowAppWindow("Wallpaper")
                 .then()
-                .hidesBelowAppWindow("wallpaper")
+                .hidesBelowAppWindow("Wallpaper")
                 .forAllEntries());
     }
 
+    @FlakyTest(bugId = 140855415)
+    @Ignore("Waiting bug feedback")
     @Test
     public void checkZOrder_appWindowReplacesLauncherAsTopWindow() {
         checkResults(result -> assertThat(result)
                 .showsAppWindowOnTop(
-                        "com.google.android.apps.nexuslauncher/.NexusLauncherActivity")
+                        "com.android.launcher3/.Launcher")
                 .then()
-                .showsAppWindowOnTop(testApp.getPackage())
+                .showsAppWindowOnTop(mTestApp.getPackage())
                 .forAllEntries());
     }
 
     @Test
-    public void checkCoveredRegion_noUncoveredRegions() {
-        checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
-                getDisplayBounds()).forAllEntries());
-    }
-
-    @Test
-    public void checkVisibility_navBarLayerIsAlwaysVisible() {
-        checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(NAVIGATION_BAR_WINDOW_TITLE).forAllEntries());
-    }
-
-    @Test
-    public void checkVisibility_statusBarLayerIsAlwaysVisible() {
-        checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(STATUS_BAR_WINDOW_TITLE).forAllEntries());
-    }
-
-    @Test
     public void checkVisibility_wallpaperLayerBecomesInvisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer("wallpaper")
+                .showsLayer("Wallpaper")
                 .then()
-                .hidesLayer("wallpaper")
+                .hidesLayer("Wallpaper")
                 .forAllEntries());
     }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java
index a81fa8e..91d4a05 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/OpenImeWindowTest.java
@@ -17,28 +17,39 @@
 package com.android.server.wm.flicker;
 
 import static com.android.server.wm.flicker.CommonTransitions.editTextSetFocus;
-import static com.android.server.wm.flicker.WindowUtils.getDisplayBounds;
 
+import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.LargeTest;
-import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.wm.flicker.helpers.ImeAppHelper;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
 
 /**
  * Test IME window opening transitions.
  * To run this test: {@code atest FlickerTests:OpenImeWindowTest}
  */
 @LargeTest
-@RunWith(AndroidJUnit4.class)
-public class OpenImeWindowTest extends FlickerTestBase {
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class OpenImeWindowTest extends NonRotationTestBase {
 
     private static final String IME_WINDOW_TITLE = "InputMethod";
 
+    public OpenImeWindowTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        mTestApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+    }
+
     @Before
     public void runTransition() {
-        super.runTransition(editTextSetFocus(uiDevice)
+        run(editTextSetFocus((ImeAppHelper) mTestApp, mUiDevice, mBeginRotation)
                 .includeJankyRuns().build());
     }
 
@@ -59,10 +70,4 @@
                 .showsLayer(IME_WINDOW_TITLE)
                 .forAllEntries());
     }
-
-    @Test
-    public void checkCoveredRegion_noUncoveredRegions() {
-        checkResults(result -> LayersTraceSubject.assertThat(result).coversRegion(
-                getDisplayBounds()).forAllEntries());
-    }
 }
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java
index 50dba81..29b6240 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/ResizeSplitScreenTest.java
@@ -24,64 +24,62 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import android.graphics.Rect;
-import android.platform.helpers.IAppHelper;
 import android.util.Rational;
 
 import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.FlakyTest;
 import androidx.test.filters.LargeTest;
-import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.wm.flicker.helpers.ImeAppHelper;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.junit.runners.Parameterized;
 
 /**
  * Test split screen resizing window transitions.
  * To run this test: {@code atest FlickerTests:ResizeSplitScreenTest}
  */
 @LargeTest
-@RunWith(AndroidJUnit4.class)
-public class ResizeSplitScreenTest extends FlickerTestBase {
+@RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@FlakyTest(bugId = 140854698)
+@Ignore("Waiting bug feedback")
+public class ResizeSplitScreenTest extends NonRotationTestBase {
 
-    public ResizeSplitScreenTest() {
-        this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+    private static String sSimpleActivity = "SimpleActivity";
+    private static String sImeActivity = "ImeActivity";
+
+    public ResizeSplitScreenTest(String beginRotationName, int beginRotation) {
+        super(beginRotationName, beginRotation);
+
+        this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
                 "com.android.server.wm.flicker.testapp", "SimpleApp");
     }
 
     @Before
     public void runTransition() {
-        IAppHelper bottomApp = new StandardAppHelper(InstrumentationRegistry
-                .getInstrumentation(),
-                "com.android.server.wm.flicker.testapp", "ImeApp");
-        super.runTransition(resizeSplitScreen(testApp, bottomApp, uiDevice, new Rational(1, 3),
-                new Rational(2, 3)).includeJankyRuns().build());
-    }
-
-    @Test
-    public void checkVisibility_navBarLayerIsAlwaysVisible() {
-        checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(NAVIGATION_BAR_WINDOW_TITLE)
-                .forAllEntries());
-    }
-
-    @Test
-    public void checkVisibility_statusBarLayerIsAlwaysVisible() {
-        checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(STATUS_BAR_WINDOW_TITLE)
-                .forAllEntries());
+        ImeAppHelper bottomApp = new ImeAppHelper(InstrumentationRegistry.getInstrumentation());
+        run(resizeSplitScreen(mTestApp, bottomApp, mUiDevice, mBeginRotation,
+                new Rational(1, 3), new Rational(2, 3))
+                .includeJankyRuns().build());
     }
 
     @Test
     public void checkVisibility_topAppLayerIsAlwaysVisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer("SimpleActivity")
+                .showsLayer(sSimpleActivity)
                 .forAllEntries());
     }
 
     @Test
     public void checkVisibility_bottomAppLayerIsAlwaysVisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer("ImeActivity")
+                .showsLayer(sImeActivity)
                 .forAllEntries());
     }
 
@@ -142,11 +140,11 @@
                     displayBounds.bottom - getNavigationBarHeight());
 
             LayersTraceSubject.assertThat(result)
-                    .hasVisibleRegion("SimpleActivity", startingTopAppBounds)
+                    .hasVisibleRegion(sSimpleActivity, startingTopAppBounds)
                     .atTheEnd();
 
             LayersTraceSubject.assertThat(result)
-                    .hasVisibleRegion("ImeActivity", startingBottomAppBounds)
+                    .hasVisibleRegion(sImeActivity, startingBottomAppBounds)
                     .atTheEnd();
         });
     }
@@ -168,14 +166,14 @@
     @Test
     public void checkVisibility_topAppWindowIsAlwaysVisible() {
         checkResults(result -> WmTraceSubject.assertThat(result)
-                .showsAppWindow("SimpleActivity")
+                .showsAppWindow(sSimpleActivity)
                 .forAllEntries());
     }
 
     @Test
     public void checkVisibility_bottomAppWindowIsAlwaysVisible() {
         checkResults(result -> WmTraceSubject.assertThat(result)
-                .showsAppWindow("ImeActivity")
+                .showsAppWindow(sImeActivity)
                 .forAllEntries());
     }
 
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java
index 117ac5a..ae55a75 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/SeamlessAppRotationTest.java
@@ -33,8 +33,10 @@
 import androidx.test.filters.LargeTest;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
 import org.junit.runners.Parameterized;
 import org.junit.runners.Parameterized.Parameters;
 
@@ -47,6 +49,7 @@
  */
 @LargeTest
 @RunWith(Parameterized.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class SeamlessAppRotationTest extends FlickerTestBase {
     private int mBeginRotation;
     private int mEndRotation;
@@ -105,7 +108,7 @@
 
         super.runTransition(
                 changeAppRotation(mIntent, intentId, InstrumentationRegistry.getContext(),
-                        uiDevice, mBeginRotation, mEndRotation).repeat(5).build());
+                        mUiDevice, mBeginRotation, mEndRotation).repeat(5).build());
     }
 
     @Test
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java b/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java
index 1d30df9..85a1494 100644
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/SplitScreenToLauncherTest.java
@@ -25,8 +25,11 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
 
 /**
  * Test open app to split screen.
@@ -34,16 +37,19 @@
  */
 @LargeTest
 @RunWith(AndroidJUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@FlakyTest(bugId = 140856143)
+@Ignore("Waiting bug feedback")
 public class SplitScreenToLauncherTest extends FlickerTestBase {
 
     public SplitScreenToLauncherTest() {
-        this.testApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
+        this.mTestApp = new StandardAppHelper(InstrumentationRegistry.getInstrumentation(),
                 "com.android.server.wm.flicker.testapp", "SimpleApp");
     }
 
     @Before
     public void runTransition() {
-        super.runTransition(splitScreenToLauncher(testApp, uiDevice).includeJankyRuns().build());
+        super.runTransition(splitScreenToLauncher(mTestApp, mUiDevice).includeJankyRuns().build());
     }
 
     @Test
@@ -62,13 +68,12 @@
                 .forAllEntries());
     }
 
-    @FlakyTest(bugId = 79686616)
     @Test
     public void checkVisibility_appLayerBecomesInVisible() {
         checkResults(result -> LayersTraceSubject.assertThat(result)
-                .showsLayer(testApp.getPackage())
+                .showsLayer(mTestApp.getPackage())
                 .then()
-                .hidesLayer(testApp.getPackage())
+                .hidesLayer(mTestApp.getPackage())
                 .forAllEntries());
     }
 
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/StandardAppHelper.java b/tests/FlickerTests/src/com/android/server/wm/flicker/StandardAppHelper.java
deleted file mode 100644
index 79a0220..0000000
--- a/tests/FlickerTests/src/com/android/server/wm/flicker/StandardAppHelper.java
+++ /dev/null
@@ -1,59 +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.flicker;
-
-import android.app.Instrumentation;
-import android.platform.helpers.AbstractStandardAppHelper;
-
-/**
- * Class to take advantage of {@code IAppHelper} interface so the same test can be run against
- * first party and third party apps.
- */
-public class StandardAppHelper extends AbstractStandardAppHelper {
-    private final String mPackageName;
-    private final String mLauncherName;
-
-    public StandardAppHelper(Instrumentation instr, String packageName, String launcherName) {
-        super(instr);
-        mPackageName = packageName;
-        mLauncherName = launcherName;
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public String getPackage() {
-        return mPackageName;
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public String getLauncherName() {
-        return mLauncherName;
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public void dismissInitialDialogs() {
-
-    }
-}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/FlickerAppHelper.java b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/FlickerAppHelper.java
new file mode 100644
index 0000000..42977f5
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/FlickerAppHelper.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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.flicker.helpers;
+
+import android.app.Instrumentation;
+
+import com.android.server.wm.flicker.StandardAppHelper;
+
+public abstract class FlickerAppHelper extends StandardAppHelper {
+
+    static int sFindTimeout = 10000;
+    static String sFlickerPackage = "com.android.server.wm.flicker.testapp";
+
+    public FlickerAppHelper(Instrumentation instr, String launcherName) {
+        super(instr, sFlickerPackage, launcherName);
+    }
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/ImeAppAutoFocusHelper.java b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/ImeAppAutoFocusHelper.java
new file mode 100644
index 0000000..56e1118
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/ImeAppAutoFocusHelper.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2019 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.flicker.helpers;
+
+import android.app.Instrumentation;
+import android.support.test.uiautomator.UiDevice;
+
+public class ImeAppAutoFocusHelper extends ImeAppHelper {
+
+    public ImeAppAutoFocusHelper(Instrumentation instr) {
+        super(instr, "ImeAppAutoFocus");
+    }
+
+    public void clickEditTextWidget(UiDevice device) {
+        // do nothing (the app is focused automatically)
+    }
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/ImeAppHelper.java b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/ImeAppHelper.java
new file mode 100644
index 0000000..098fd6d
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/ImeAppHelper.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2019 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.flicker.helpers;
+
+import static android.os.SystemClock.sleep;
+
+import android.app.Instrumentation;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObject2;
+
+public class ImeAppHelper extends FlickerAppHelper {
+
+    ImeAppHelper(Instrumentation instr, String launcherName) {
+        super(instr, launcherName);
+    }
+
+    public ImeAppHelper(Instrumentation instr) {
+        this(instr, "ImeApp");
+    }
+
+    public void clickEditTextWidget(UiDevice device) {
+        UiObject2 editText = device.findObject(By.res(getPackage(), "plain_text_input"));
+        editText.click();
+        sleep(500);
+    }
+}
diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/PipAppHelper.java b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/PipAppHelper.java
new file mode 100644
index 0000000..d00e11b
--- /dev/null
+++ b/tests/FlickerTests/src/com/android/server/wm/flicker/helpers/PipAppHelper.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2019 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.flicker.helpers;
+
+import static com.android.server.wm.flicker.helpers.AutomationUtils.getPipWindowSelector;
+
+import android.app.Instrumentation;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObject2;
+import android.support.test.uiautomator.Until;
+
+public class PipAppHelper extends FlickerAppHelper {
+
+    public PipAppHelper(Instrumentation instr) {
+        super(instr, "PipApp");
+    }
+
+    public void clickEnterPipButton(UiDevice device) {
+        UiObject2 enterPipButton = device.findObject(By.res(getPackage(), "enter_pip"));
+        enterPipButton.click();
+        UiObject2 pipWindow = device.wait(Until.findObject(getPipWindowSelector()), sFindTimeout);
+
+        if (pipWindow == null) {
+            throw new RuntimeException("Unable to find PIP window");
+        }
+    }
+
+}
diff --git a/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml b/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml
index b694172..0fe9682 100644
--- a/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml
+++ b/tests/FlickerTests/test-apps/flickerapp/AndroidManifest.xml
@@ -38,6 +38,15 @@
                 <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
+        <activity android:name=".ImeActivityAutoFocus"
+                  android:taskAffinity="com.android.server.wm.flicker.testapp.ImeActivityAutoFocus"
+                  android:windowSoftInputMode="stateVisible"
+                  android:label="ImeAppAutoFocus">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
         <activity android:name=".PipActivity"
                   android:resizeableActivity="true"
                   android:supportsPictureInPicture="true"
diff --git a/tests/FlickerTests/test-apps/flickerapp/res/layout/activity_ime.xml b/tests/FlickerTests/test-apps/flickerapp/res/layout/activity_ime.xml
index d5eb023..4708cfd 100644
--- a/tests/FlickerTests/test-apps/flickerapp/res/layout/activity_ime.xml
+++ b/tests/FlickerTests/test-apps/flickerapp/res/layout/activity_ime.xml
@@ -18,6 +18,7 @@
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
+    android:focusableInTouchMode="true"
     android:background="@android:color/holo_green_light">
     <EditText android:id="@+id/plain_text_input"
               android:layout_height="wrap_content"
diff --git a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/ImeActivityAutoFocus.java b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/ImeActivityAutoFocus.java
new file mode 100644
index 0000000..05da717
--- /dev/null
+++ b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/ImeActivityAutoFocus.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2019 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.flicker.testapp;
+
+import android.widget.EditText;
+
+public class ImeActivityAutoFocus extends ImeActivity {
+
+    @Override
+    protected void onStart() {
+        super.onStart();
+
+        EditText editTextField = findViewById(R.id.plain_text_input);
+        editTextField.requestFocus();
+    }
+}
diff --git a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java
index 3a0c1c9..5cf81cb 100644
--- a/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java
+++ b/tests/FlickerTests/test-apps/flickerapp/src/com/android/server/wm/flicker/testapp/SeamlessRotationActivity.java
@@ -17,7 +17,6 @@
 package com.android.server.wm.flicker.testapp;
 
 import static android.os.SystemClock.sleep;
-import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
 
 import static com.android.server.wm.flicker.testapp.ActivityOptions.EXTRA_STARVE_UI_THREAD;
 
@@ -39,8 +38,8 @@
         super.onCreate(savedInstanceState);
         enableSeamlessRotation();
         setContentView(R.layout.activity_simple);
-        boolean starveUiThread = getIntent().getExtras() != null &&
-                getIntent().getExtras().getBoolean(EXTRA_STARVE_UI_THREAD);
+        boolean starveUiThread = getIntent().getExtras() != null
+                && getIntent().getExtras().getBoolean(EXTRA_STARVE_UI_THREAD);
         if (starveUiThread) {
             starveUiThread();
         }
diff --git a/tests/MirrorSurfaceTest/Android.bp b/tests/MirrorSurfaceTest/Android.bp
new file mode 100644
index 0000000..e359c64
--- /dev/null
+++ b/tests/MirrorSurfaceTest/Android.bp
@@ -0,0 +1,6 @@
+android_test {
+    name: "MirrorSurfaceTest",
+    srcs: ["src/**/*.java"],
+    platform_apis: true,
+    certificate: "platform",
+}
diff --git a/tests/MirrorSurfaceTest/AndroidManifest.xml b/tests/MirrorSurfaceTest/AndroidManifest.xml
new file mode 100644
index 0000000..123cd0f
--- /dev/null
+++ b/tests/MirrorSurfaceTest/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.google.android.test.mirrorsurface">
+    <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER"/>
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+
+    <application android:label="MirrorSurfaceTest">
+        <activity android:name=".MirrorSurfaceActivity"
+                  android:label="Mirror Surface"
+                  android:configChanges="orientation|screenSize">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/tests/MirrorSurfaceTest/res/layout/activity_mirror_surface.xml b/tests/MirrorSurfaceTest/res/layout/activity_mirror_surface.xml
new file mode 100644
index 0000000..73b509f
--- /dev/null
+++ b/tests/MirrorSurfaceTest/res/layout/activity_mirror_surface.xml
@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:orientation="vertical">
+
+    <LinearLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center_horizontal"
+        android:layout_marginTop="20dp"
+        android:orientation="horizontal">
+
+        <Button
+            android:id="@+id/mirror_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="20dp"
+            android:text="Mirror"
+            android:textSize="20dp" />
+
+        <Button
+            android:id="@+id/remove_mirror_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="20dp"
+            android:text="Remove Mirror"
+            android:textSize="20dp" />
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginLeft="40dp"
+        android:layout_marginRight="40dp"
+        android:layout_marginTop="10dp"
+        android:orientation="horizontal">
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="20dp"
+            android:text="SCALE: " />
+
+        <EditText
+            android:hint="0.5"
+            android:id="@+id/scale"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:inputType="numberDecimal" />
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginLeft="40dp"
+        android:layout_marginRight="40dp"
+        android:layout_marginTop="10dp"
+        android:orientation="horizontal">
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="20dp"
+            android:text="DISPLAY FRAME: " />
+
+        <EditText
+            android:hint="0, 0, 20, 20"
+            android:id="@+id/displayFrame"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:inputType="numberDecimal|text"/>
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginLeft="40dp"
+        android:layout_marginRight="40dp"
+        android:layout_marginTop="10dp"
+        android:orientation="horizontal">
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginRight="20dp"
+            android:text="SOURCE POSITION: " />
+
+        <TextView
+            android:id="@+id/sourcePosition"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:inputType="numberDecimal|text"/>
+    </LinearLayout>
+</LinearLayout>
diff --git a/tests/MirrorSurfaceTest/res/layout/move_view.xml b/tests/MirrorSurfaceTest/res/layout/move_view.xml
new file mode 100644
index 0000000..5707700
--- /dev/null
+++ b/tests/MirrorSurfaceTest/res/layout/move_view.xml
@@ -0,0 +1,101 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 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.
+  -->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+             android:layout_width="wrap_content"
+             android:layout_height="wrap_content"
+             android:layout_margin="20dp"
+             android:gravity="center">
+
+    <RelativeLayout
+        android:id="@+id/arrows"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content">
+
+        <ImageButton
+            android:id="@+id/up_arrow"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_toEndOf="@+id/right_arrow"
+            android:background="@android:color/holo_green_light"
+            android:padding="10dp"
+            android:src="@android:drawable/arrow_up_float" />
+
+        <ImageButton
+            android:id="@+id/down_arrow"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_below="@+id/up_arrow"
+            android:layout_marginTop="80dp"
+            android:layout_toEndOf="@+id/right_arrow"
+            android:background="@android:color/holo_green_light"
+            android:padding="10dp"
+            android:src="@android:drawable/arrow_down_float" />
+
+        <ImageButton
+            android:id="@+id/right_arrow"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_alignTop="@+id/up_arrow"
+            android:layout_alignBottom="@+id/down_arrow"
+            android:layout_marginTop="55dp"
+            android:layout_marginEnd="15dp"
+            android:layout_marginBottom="55dp"
+            android:background="@android:color/holo_green_light"
+            android:paddingLeft="10dp"
+            android:paddingRight="10dp"
+            android:rotation="90"
+            android:src="@android:drawable/arrow_down_float" />
+
+        <ImageButton
+            android:id="@+id/left_arrow"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_alignTop="@+id/up_arrow"
+            android:layout_alignBottom="@+id/down_arrow"
+            android:layout_marginStart="15dp"
+            android:layout_marginTop="55dp"
+            android:layout_marginBottom="55dp"
+            android:layout_toEndOf="@+id/down_arrow"
+            android:background="@android:color/holo_green_light"
+            android:paddingLeft="10dp"
+            android:paddingRight="10dp"
+            android:rotation="-90"
+            android:src="@android:drawable/arrow_down_float" />
+    </RelativeLayout>
+
+    <RelativeLayout
+
+        android:layout_gravity="center"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content">
+
+        <Button
+            android:id="@+id/zoom_in_button"
+            android:layout_width="40dp"
+            android:layout_marginBottom="-8dp"
+            android:layout_height="40dp"
+            android:text="+" />
+
+        <Button
+            android:layout_below="@+id/zoom_in_button"
+            android:id="@+id/zoom_out_button"
+            android:layout_width="40dp"
+            android:layout_height="40dp"
+            android:text="-" />
+    </RelativeLayout>
+</FrameLayout>
\ No newline at end of file
diff --git a/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java b/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java
new file mode 100644
index 0000000..b863713
--- /dev/null
+++ b/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java
@@ -0,0 +1,441 @@
+/*
+ * Copyright (C) 2019 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.google.android.test.mirrorsurface;
+
+
+import android.app.Activity;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.PixelFormat;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.RemoteException;
+import android.util.DisplayMetrics;
+import android.view.Gravity;
+import android.view.IWindowManager;
+import android.view.MotionEvent;
+import android.view.Surface;
+import android.view.SurfaceControl;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.view.WindowManagerGlobal;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+public class MirrorSurfaceActivity extends Activity implements View.OnClickListener,
+        View.OnLongClickListener, View.OnTouchListener {
+    private static final int BORDER_SIZE = 10;
+    private static final int DEFAULT_SCALE = 2;
+    private static final int DEFAULT_BORDER_COLOR = Color.argb(255, 255, 153, 0);
+    private static final int MOVE_FRAME_AMOUNT = 20;
+
+    private IWindowManager mIWm;
+    private WindowManager mWm;
+
+    private SurfaceControl mSurfaceControl = new SurfaceControl();
+    private SurfaceControl mBorderSc;
+
+    private SurfaceControl.Transaction mTransaction = new SurfaceControl.Transaction();
+    private View mOverlayView;
+    private View mArrowOverlay;
+
+    private Rect mDisplayBounds = new Rect();
+
+    private EditText mScaleText;
+    private EditText mDisplayFrameText;
+    private TextView mSourcePositionText;
+
+    private Rect mTmpRect = new Rect();
+    private final Surface mTmpSurface = new Surface();
+
+    private boolean mHasMirror;
+
+    private Rect mCurrFrame = new Rect();
+    private float mCurrScale = DEFAULT_SCALE;
+
+    private final Handler mHandler = new Handler();
+
+    private MoveMirrorRunnable mMoveMirrorRunnable = new MoveMirrorRunnable();
+    private boolean mIsPressedDown = false;
+
+    private int mDisplayId;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        setContentView(R.layout.activity_mirror_surface);
+        mWm = (WindowManager) getSystemService(WINDOW_SERVICE);
+        mIWm = WindowManagerGlobal.getWindowManagerService();
+
+        DisplayMetrics displayMetrics = new DisplayMetrics();
+        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
+        mDisplayBounds.set(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
+
+        mScaleText = findViewById(R.id.scale);
+        mDisplayFrameText = findViewById(R.id.displayFrame);
+        mSourcePositionText = findViewById(R.id.sourcePosition);
+
+        mCurrFrame.set(0, 0, mDisplayBounds.width() / 2, mDisplayBounds.height() / 2);
+        mCurrScale = DEFAULT_SCALE;
+
+        mDisplayId = getWindowManager().getDefaultDisplay().getDisplayId();
+        updateEditTexts();
+
+        findViewById(R.id.mirror_button).setOnClickListener(view -> {
+            if (mArrowOverlay == null) {
+                createArrowOverlay();
+            }
+            createOrUpdateMirror();
+        });
+
+        findViewById(R.id.remove_mirror_button).setOnClickListener(v -> {
+            removeMirror();
+            removeArrowOverlay();
+        });
+
+        createMirrorOverlay();
+    }
+
+    private void updateEditTexts() {
+        mDisplayFrameText.setText(
+                String.format("%s, %s, %s, %s", mCurrFrame.left, mCurrFrame.top, mCurrFrame.right,
+                        mCurrFrame.bottom));
+        mScaleText.setText(String.valueOf(mCurrScale));
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        if (mOverlayView != null) {
+            removeMirror();
+            mWm.removeView(mOverlayView);
+            mOverlayView = null;
+        }
+        removeArrowOverlay();
+    }
+
+    private void createArrowOverlay() {
+        mArrowOverlay = getLayoutInflater().inflate(R.layout.move_view, null);
+        WindowManager.LayoutParams arrowParams = new WindowManager.LayoutParams(
+                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
+                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
+                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+                PixelFormat.RGBA_8888);
+        arrowParams.gravity = Gravity.RIGHT | Gravity.BOTTOM;
+        mWm.addView(mArrowOverlay, arrowParams);
+
+        View leftArrow = mArrowOverlay.findViewById(R.id.left_arrow);
+        View topArrow = mArrowOverlay.findViewById(R.id.up_arrow);
+        View rightArrow = mArrowOverlay.findViewById(R.id.right_arrow);
+        View bottomArrow = mArrowOverlay.findViewById(R.id.down_arrow);
+
+        leftArrow.setOnClickListener(this);
+        topArrow.setOnClickListener(this);
+        rightArrow.setOnClickListener(this);
+        bottomArrow.setOnClickListener(this);
+
+        leftArrow.setOnLongClickListener(this);
+        topArrow.setOnLongClickListener(this);
+        rightArrow.setOnLongClickListener(this);
+        bottomArrow.setOnLongClickListener(this);
+
+        leftArrow.setOnTouchListener(this);
+        topArrow.setOnTouchListener(this);
+        rightArrow.setOnTouchListener(this);
+        bottomArrow.setOnTouchListener(this);
+
+        mArrowOverlay.findViewById(R.id.zoom_in_button).setOnClickListener(v -> {
+            if (mCurrScale <= 1) {
+                mCurrScale *= 2;
+            } else {
+                mCurrScale += 0.5;
+            }
+
+            updateMirror(mCurrFrame, mCurrScale);
+        });
+        mArrowOverlay.findViewById(R.id.zoom_out_button).setOnClickListener(v -> {
+            if (mCurrScale <= 1) {
+                mCurrScale /= 2;
+            } else {
+                mCurrScale -= 0.5;
+            }
+
+            updateMirror(mCurrFrame, mCurrScale);
+        });
+    }
+
+    private void removeArrowOverlay() {
+        if (mArrowOverlay != null) {
+            mWm.removeView(mArrowOverlay);
+            mArrowOverlay = null;
+        }
+    }
+
+    private void createMirrorOverlay() {
+        mOverlayView = new LinearLayout(this);
+        WindowManager.LayoutParams params = new WindowManager.LayoutParams(mDisplayBounds.width(),
+                mDisplayBounds.height(),
+                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+                PixelFormat.RGBA_8888);
+        params.gravity = Gravity.LEFT | Gravity.TOP;
+        params.setTitle("Mirror Overlay");
+        mOverlayView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+                | View.SYSTEM_UI_FLAG_FULLSCREEN
+                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
+
+        mWm.addView(mOverlayView, params);
+
+    }
+
+    private void removeMirror() {
+        if (mSurfaceControl.isValid()) {
+            mTransaction.remove(mSurfaceControl).apply();
+        }
+        mHasMirror = false;
+    }
+
+    private void createOrUpdateMirror() {
+        if (mHasMirror) {
+            updateMirror(getDisplayFrame(), getScale());
+        } else {
+            createMirror(getDisplayFrame(), getScale());
+        }
+
+    }
+
+    private Rect getDisplayFrame() {
+        mTmpRect.setEmpty();
+        String[] frameVals = mDisplayFrameText.getText().toString().split("\\s*,\\s*");
+        if (frameVals.length != 4) {
+            return mTmpRect;
+        }
+
+        try {
+            mTmpRect.set(Integer.parseInt(frameVals[0]), Integer.parseInt(frameVals[1]),
+                    Integer.parseInt(frameVals[2]), Integer.parseInt(frameVals[3]));
+        } catch (Exception e) {
+            mTmpRect.setEmpty();
+        }
+
+        return mTmpRect;
+    }
+
+    private float getScale() {
+        try {
+            return Float.parseFloat(mScaleText.getText().toString());
+        } catch (Exception e) {
+            return -1;
+        }
+    }
+
+    private void createMirror(Rect displayFrame, float scale) {
+        boolean success = false;
+        try {
+            success = mIWm.mirrorDisplay(mDisplayId, mSurfaceControl);
+        } catch (RemoteException e) {
+        }
+
+        if (!success) {
+            return;
+        }
+
+        if (!mSurfaceControl.isValid()) {
+            return;
+        }
+
+        mHasMirror = true;
+
+        mBorderSc = new SurfaceControl.Builder()
+                .setName("Mirror Border")
+                .setBufferSize(1, 1)
+                .setFormat(PixelFormat.TRANSLUCENT)
+                .build();
+
+        updateMirror(displayFrame, scale);
+
+        mTransaction
+                .show(mSurfaceControl)
+                .reparent(mSurfaceControl, mOverlayView.getViewRootImpl().getSurfaceControl())
+                .setLayer(mBorderSc, 1)
+                .show(mBorderSc)
+                .reparent(mBorderSc, mSurfaceControl)
+                .apply();
+    }
+
+    private void updateMirror(Rect displayFrame, float scale) {
+        if (displayFrame.isEmpty()) {
+            Rect bounds = mDisplayBounds;
+            int defaultCropW = Math.round(bounds.width() / 2);
+            int defaultCropH = Math.round(bounds.height() / 2);
+            displayFrame.set(0, 0, defaultCropW, defaultCropH);
+        }
+
+        if (scale <= 0) {
+            scale = DEFAULT_SCALE;
+        }
+
+        mCurrFrame.set(displayFrame);
+        mCurrScale = scale;
+
+        int width = (int) Math.ceil(displayFrame.width() / scale);
+        int height = (int) Math.ceil(displayFrame.height() / scale);
+
+        Rect sourceBounds = getSourceBounds(displayFrame, scale);
+
+        mTransaction.setGeometry(mSurfaceControl, sourceBounds, displayFrame, Surface.ROTATION_0)
+                .setPosition(mBorderSc, sourceBounds.left, sourceBounds.top)
+                .setBufferSize(mBorderSc, width, height)
+                .apply();
+
+        drawBorder(mBorderSc, width, height, (int) Math.ceil(BORDER_SIZE / scale));
+
+        mSourcePositionText.setText(sourceBounds.left + ", " + sourceBounds.top);
+        mDisplayFrameText.setText(
+                String.format("%s, %s, %s, %s", mCurrFrame.left, mCurrFrame.top, mCurrFrame.right,
+                        mCurrFrame.bottom));
+        mScaleText.setText(String.valueOf(mCurrScale));
+    }
+
+    private void drawBorder(SurfaceControl borderSc, int width, int height, int borderSize) {
+        mTmpSurface.copyFrom(borderSc);
+
+        Canvas c = null;
+        try {
+            c = mTmpSurface.lockCanvas(null);
+        } catch (IllegalArgumentException | Surface.OutOfResourcesException e) {
+        }
+        if (c == null) {
+            return;
+        }
+
+        // Top
+        c.save();
+        c.clipRect(new Rect(0, 0, width, borderSize));
+        c.drawColor(DEFAULT_BORDER_COLOR);
+        c.restore();
+        // Left
+        c.save();
+        c.clipRect(new Rect(0, 0, borderSize, height));
+        c.drawColor(DEFAULT_BORDER_COLOR);
+        c.restore();
+        // Right
+        c.save();
+        c.clipRect(new Rect(width - borderSize, 0, width, height));
+        c.drawColor(DEFAULT_BORDER_COLOR);
+        c.restore();
+        // Bottom
+        c.save();
+        c.clipRect(new Rect(0, height - borderSize, width, height));
+        c.drawColor(DEFAULT_BORDER_COLOR);
+        c.restore();
+
+        mTmpSurface.unlockCanvasAndPost(c);
+    }
+
+    @Override
+    public void onClick(View v) {
+        Point offset = findOffset(v);
+        moveMirrorForArrows(offset.x, offset.y);
+    }
+
+    @Override
+    public boolean onLongClick(View v) {
+        mIsPressedDown = true;
+        Point point = findOffset(v);
+        mMoveMirrorRunnable.mXOffset = point.x;
+        mMoveMirrorRunnable.mYOffset = point.y;
+        mHandler.post(mMoveMirrorRunnable);
+        return false;
+    }
+
+    @Override
+    public boolean onTouch(View v, MotionEvent event) {
+        switch (event.getAction()) {
+            case MotionEvent.ACTION_UP:
+            case MotionEvent.ACTION_CANCEL:
+                mIsPressedDown = false;
+                break;
+        }
+        return false;
+    }
+
+    private Point findOffset(View v) {
+        Point offset = new Point(0, 0);
+
+        switch (v.getId()) {
+            case R.id.up_arrow:
+                offset.y = -MOVE_FRAME_AMOUNT;
+                break;
+            case R.id.down_arrow:
+                offset.y = MOVE_FRAME_AMOUNT;
+                break;
+            case R.id.right_arrow:
+                offset.x = -MOVE_FRAME_AMOUNT;
+                break;
+            case R.id.left_arrow:
+                offset.x = MOVE_FRAME_AMOUNT;
+                break;
+        }
+
+        return offset;
+    }
+
+    private void moveMirrorForArrows(int xOffset, int yOffset) {
+        mCurrFrame.offset(xOffset, yOffset);
+
+        updateMirror(mCurrFrame, mCurrScale);
+    }
+
+    /**
+     * Calculates the desired source bounds. This will be the area under from the center of  the
+     * displayFrame, factoring in scale.
+     */
+    private Rect getSourceBounds(Rect displayFrame, float scale) {
+        int halfWidth = displayFrame.width() / 2;
+        int halfHeight = displayFrame.height() / 2;
+        int left = displayFrame.left + (halfWidth - (int) (halfWidth / scale));
+        int right = displayFrame.right - (halfWidth - (int) (halfWidth / scale));
+        int top = displayFrame.top + (halfHeight - (int) (halfHeight / scale));
+        int bottom = displayFrame.bottom - (halfHeight - (int) (halfHeight / scale));
+        return new Rect(left, top, right, bottom);
+    }
+
+    class MoveMirrorRunnable implements Runnable {
+        int mXOffset = 0;
+        int mYOffset = 0;
+
+        @Override
+        public void run() {
+            if (mIsPressedDown) {
+                moveMirrorForArrows(mXOffset, mYOffset);
+                mHandler.postDelayed(mMoveMirrorRunnable, 150);
+            }
+        }
+    }
+}
diff --git a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
index 79f5095..06b58fd 100644
--- a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
+++ b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
@@ -626,11 +626,40 @@
         // Verify that health check is failed
         assertThat(observer.mMitigatedPackages).containsExactly(APP_A);
 
-        // Then clear failed packages and start observing a random package so requests are synced
-        // and PackageWatchdog#onSupportedPackages is called and APP_A has a chance to fail again
-        // this time due to package expiry.
+        // Clear failed packages and forward time to expire the observation duration
         observer.mMitigatedPackages.clear();
-        watchdog.startObservingHealth(observer, Arrays.asList(APP_B), LONG_DURATION);
+        moveTimeForwardAndDispatch(LONG_DURATION);
+
+        // Verify that health check failure is not notified again
+        assertThat(observer.mMitigatedPackages).isEmpty();
+    }
+
+    /**
+     * Tests failure when health check duration is different from package observation duration
+     * Failure is also notified only once.
+     */
+    @Test
+    public void testExplicitHealthCheckFailureAfterExpiry() {
+        TestController controller = new TestController();
+        PackageWatchdog watchdog = createWatchdog(controller, true /* withPackagesReady */);
+        TestObserver observer = new TestObserver(OBSERVER_NAME_1,
+                PackageHealthObserverImpact.USER_IMPACT_MEDIUM);
+
+        // Start observing with explicit health checks for APP_A and
+        // package observation duration == SHORT_DURATION / 2
+        // health check duration == SHORT_DURATION (set by default in the TestController)
+        controller.setSupportedPackages(Arrays.asList(APP_A));
+        watchdog.startObservingHealth(observer, Arrays.asList(APP_A), SHORT_DURATION / 2);
+
+        // Forward time to expire the observation duration
+        moveTimeForwardAndDispatch(SHORT_DURATION / 2);
+
+        // Verify that health check is failed
+        assertThat(observer.mMitigatedPackages).containsExactly(APP_A);
+
+        // Clear failed packages and forward time to expire the health check duration
+        observer.mMitigatedPackages.clear();
+        moveTimeForwardAndDispatch(SHORT_DURATION);
 
         // Verify that health check failure is not notified again
         assertThat(observer.mMitigatedPackages).isEmpty();
diff --git a/tests/net/common/java/android/net/LinkPropertiesTest.java b/tests/net/common/java/android/net/LinkPropertiesTest.java
index b0464d9..ae8285b 100644
--- a/tests/net/common/java/android/net/LinkPropertiesTest.java
+++ b/tests/net/common/java/android/net/LinkPropertiesTest.java
@@ -99,6 +99,7 @@
         assertFalse(lp.isIpv4Provisioned());
         assertFalse(lp.isIpv6Provisioned());
         assertFalse(lp.isPrivateDnsActive());
+        assertFalse(lp.isWakeOnLanSupported());
     }
 
     private LinkProperties makeTestObject() {
@@ -120,6 +121,7 @@
         lp.setMtu(MTU);
         lp.setTcpBufferSizes(TCP_BUFFER_SIZES);
         lp.setNat64Prefix(new IpPrefix("2001:db8:0:64::/96"));
+        lp.setWakeOnLanSupported(true);
         return lp;
     }
 
@@ -158,6 +160,9 @@
         assertTrue(source.isIdenticalTcpBufferSizes(target));
         assertTrue(target.isIdenticalTcpBufferSizes(source));
 
+        assertTrue(source.isIdenticalWakeOnLan(target));
+        assertTrue(target.isIdenticalWakeOnLan(source));
+
         // Check result of equals().
         assertTrue(source.equals(target));
         assertTrue(target.equals(source));
@@ -1057,4 +1062,13 @@
         lp.clear();
         assertFalse(lp.isPrivateDnsActive());
     }
+
+    @Test
+    public void testWakeOnLanSupported() {
+        final LinkProperties lp = makeTestObject();
+        assertTrue(lp.isWakeOnLanSupported());
+
+        lp.clear();
+        assertFalse(lp.isWakeOnLanSupported());
+    }
 }
diff --git a/tests/net/java/android/net/netlink/InetDiagSocketTest.java b/tests/net/java/android/net/netlink/InetDiagSocketTest.java
index 2adbb06..46e27c1 100644
--- a/tests/net/java/android/net/netlink/InetDiagSocketTest.java
+++ b/tests/net/java/android/net/netlink/InetDiagSocketTest.java
@@ -18,7 +18,6 @@
 
 import static android.net.netlink.StructNlMsgHdr.NLM_F_DUMP;
 import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;
-import static android.os.Process.INVALID_UID;
 import static android.system.OsConstants.AF_INET;
 import static android.system.OsConstants.AF_INET6;
 import static android.system.OsConstants.IPPROTO_TCP;
@@ -28,6 +27,7 @@
 
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
@@ -152,9 +152,13 @@
 
     private void checkConnectionOwnerUid(int protocol, InetSocketAddress local,
                                          InetSocketAddress remote, boolean expectSuccess) {
-        final int expectedUid = expectSuccess ? Process.myUid() : INVALID_UID;
         final int uid = mCm.getConnectionOwnerUid(protocol, local, remote);
-        assertEquals(expectedUid, uid);
+
+        if (expectSuccess) {
+            assertEquals(Process.myUid(), uid);
+        } else {
+            assertNotEquals(Process.myUid(), uid);
+        }
     }
 
     private int findLikelyFreeUdpPort(UdpConnection conn) throws Exception {
@@ -165,11 +169,11 @@
         return localPort;
     }
 
+    /**
+     * Create a test connection for UDP and TCP sockets and verify that this
+     * {protocol, local, remote} socket result in receiving a valid UID.
+     */
     public void checkGetConnectionOwnerUid(String to, String from) throws Exception {
-        /**
-         * For TCP connections, create a test connection and verify that this
-         * {protocol, local, remote} socket result in receiving a valid UID.
-         */
         TcpConnection tcp = new TcpConnection(to, from);
         checkConnectionOwnerUid(tcp.protocol, tcp.local, tcp.remote, true);
         checkConnectionOwnerUid(IPPROTO_UDP, tcp.local, tcp.remote, false);
@@ -177,20 +181,14 @@
         checkConnectionOwnerUid(tcp.protocol, tcp.local, new InetSocketAddress(0), false);
         tcp.close();
 
-        /**
-         * For UDP connections, either a complete match {protocol, local, remote} or a
-         * partial match {protocol, local} should return a valid UID.
-         */
         UdpConnection udp = new UdpConnection(to,from);
         checkConnectionOwnerUid(udp.protocol, udp.local, udp.remote, true);
-        checkConnectionOwnerUid(udp.protocol, udp.local, new InetSocketAddress(0), true);
         checkConnectionOwnerUid(IPPROTO_TCP, udp.local, udp.remote, false);
         checkConnectionOwnerUid(udp.protocol, new InetSocketAddress(findLikelyFreeUdpPort(udp)),
                 udp.remote, false);
         udp.close();
     }
 
-    @Ignore
     @Test
     public void testGetConnectionOwnerUid() throws Exception {
         checkGetConnectionOwnerUid("::", null);
@@ -203,6 +201,17 @@
         checkGetConnectionOwnerUid("::1", "::1");
     }
 
+    @Ignore("Times out on Marlin/Sailfish")
+    /* Verify fix for b/141603906 */
+    @Test
+    public void testB141603906() throws Exception {
+        final InetSocketAddress src = new InetSocketAddress(0);
+        final InetSocketAddress dst = new InetSocketAddress(0);
+        for (int i = 1; i <= 100000; i++) {
+            mCm.getConnectionOwnerUid(IPPROTO_TCP, src, dst);
+        }
+    }
+
     // Hexadecimal representation of InetDiagReqV2 request.
     private static final String INET_DIAG_REQ_V2_UDP_INET4_HEX =
             // struct nlmsghdr
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index f2f258a..bffbbfd 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -207,7 +207,7 @@
 import com.android.server.net.NetworkPolicyManagerInternal;
 import com.android.testutils.ExceptionUtils;
 import com.android.testutils.HandlerUtilsKt;
-import com.android.testutils.RecorderCallback.CallbackRecord;
+import com.android.testutils.RecorderCallback.CallbackEntry;
 import com.android.testutils.TestableNetworkCallback;
 
 import org.junit.After;
@@ -258,13 +258,13 @@
     private static final String TAG = "ConnectivityServiceTest";
 
     private static final int TIMEOUT_MS = 500;
-    private static final int TEST_LINGER_DELAY_MS = 250;
+    private static final int TEST_LINGER_DELAY_MS = 300;
     // Chosen to be less than the linger timeout. This ensures that we can distinguish between a
     // LOST callback that arrives immediately and a LOST callback that arrives after the linger
     // timeout. For this, our assertions should run fast enough to leave less than
     // (mService.mLingerDelayMs - TEST_CALLBACK_TIMEOUT_MS) between the time callbacks are
     // supposedly fired, and the time we call expectCallback.
-    private static final int TEST_CALLBACK_TIMEOUT_MS = 200;
+    private static final int TEST_CALLBACK_TIMEOUT_MS = 250;
     // Chosen to be less than TEST_CALLBACK_TIMEOUT_MS. This ensures that requests have time to
     // complete before callbacks are verified.
     private static final int TEST_REQUEST_TIMEOUT_MS = 150;
@@ -274,6 +274,7 @@
     private static final String CLAT_PREFIX = "v4-";
     private static final String MOBILE_IFNAME = "test_rmnet_data0";
     private static final String WIFI_IFNAME = "test_wlan0";
+    private static final String WIFI_WOL_IFNAME = "test_wlan_wol";
     private static final String[] EMPTY_STRING_ARRAY = new String[0];
 
     private MockContext mServiceContext;
@@ -343,6 +344,12 @@
                             "mobile_mms,2,0,2,60000,true",
                     });
 
+            when(mResources.getStringArray(
+                    com.android.internal.R.array.config_wakeonlan_supported_interfaces))
+                    .thenReturn(new String[]{
+                            WIFI_WOL_IFNAME,
+                    });
+
             mContentResolver = new MockContentResolver();
             mContentResolver.addProvider(Settings.AUTHORITY, settingsProvider);
         }
@@ -504,6 +511,8 @@
             // Waits for the NetworkAgent to be registered, which includes the creation of the
             // NetworkMonitor.
             waitForIdle(TIMEOUT_MS);
+            HandlerUtilsKt.waitForIdle(mCsHandlerThread, TIMEOUT_MS);
+            HandlerUtilsKt.waitForIdle(ConnectivityThread.get(), TIMEOUT_MS);
         }
 
         @Override
@@ -1464,6 +1473,10 @@
      * received. assertNoCallback may be called at any time.
      */
     private class TestNetworkCallback extends TestableNetworkCallback {
+        TestNetworkCallback() {
+            super(TEST_CALLBACK_TIMEOUT_MS);
+        }
+
         @Override
         public void assertNoCallback() {
             // TODO: better support this use case in TestableNetworkCallback
@@ -1472,12 +1485,12 @@
         }
 
         @Override
-        public <T extends CallbackRecord> T expectCallback(final KClass<T> type, final HasNetwork n,
+        public <T extends CallbackEntry> T expectCallback(final KClass<T> type, final HasNetwork n,
                 final long timeoutMs) {
             final T callback = super.expectCallback(type, n, timeoutMs);
-            if (callback instanceof CallbackRecord.Losing) {
+            if (callback instanceof CallbackEntry.Losing) {
                 // TODO : move this to the specific test(s) needing this rather than here.
-                final CallbackRecord.Losing losing = (CallbackRecord.Losing) callback;
+                final CallbackEntry.Losing losing = (CallbackEntry.Losing) callback;
                 final int maxMsToLive = losing.getMaxMsToLive();
                 String msg = String.format(
                         "Invalid linger time value %d, must be between %d and %d",
@@ -1538,16 +1551,16 @@
 
         cv = waitForConnectivityBroadcasts(2);
         mWiFiNetworkAgent.disconnect();
-        genericNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        wifiNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        wifiNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         waitFor(cv);
         assertNoCallbacks(genericNetworkCallback, wifiNetworkCallback, cellNetworkCallback);
 
         cv = waitForConnectivityBroadcasts(1);
         mCellNetworkAgent.disconnect();
-        genericNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         waitFor(cv);
         assertNoCallbacks(genericNetworkCallback, wifiNetworkCallback, cellNetworkCallback);
 
@@ -1568,21 +1581,21 @@
         mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
         mWiFiNetworkAgent.connect(true);
         genericNetworkCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        genericNetworkCallback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         genericNetworkCallback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         wifiNetworkCallback.expectAvailableThenValidatedCallbacks(mWiFiNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         assertNoCallbacks(genericNetworkCallback, wifiNetworkCallback, cellNetworkCallback);
 
         mWiFiNetworkAgent.disconnect();
-        genericNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        wifiNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        wifiNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         assertNoCallbacks(genericNetworkCallback, wifiNetworkCallback, cellNetworkCallback);
 
         mCellNetworkAgent.disconnect();
-        genericNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         assertNoCallbacks(genericNetworkCallback, wifiNetworkCallback, cellNetworkCallback);
     }
 
@@ -1622,7 +1635,7 @@
         // We then get LOSING when wifi validates and cell is outscored.
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         // TODO: Investigate sending validated before losing.
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         defaultCallback.expectAvailableDoubleValidatedCallbacks(mWiFiNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
@@ -1631,15 +1644,15 @@
         mEthernetNetworkAgent.connect(true);
         callback.expectAvailableCallbacksUnvalidated(mEthernetNetworkAgent);
         // TODO: Investigate sending validated before losing.
-        callback.expectCallback(CallbackRecord.LOSING, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mWiFiNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mEthernetNetworkAgent);
         defaultCallback.expectAvailableDoubleValidatedCallbacks(mEthernetNetworkAgent);
         assertEquals(mEthernetNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         mEthernetNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mEthernetNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, mEthernetNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mEthernetNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mEthernetNetworkAgent);
         defaultCallback.expectAvailableCallbacksValidated(mWiFiNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
@@ -1655,7 +1668,7 @@
                 newNetwork = mWiFiNetworkAgent;
 
             }
-            callback.expectCallback(CallbackRecord.LOSING, oldNetwork);
+            callback.expectCallback(CallbackEntry.LOSING, oldNetwork);
             // TODO: should we send an AVAILABLE callback to newNetwork, to indicate that it is no
             // longer lingering?
             defaultCallback.expectAvailableCallbacksValidated(newNetwork);
@@ -1669,7 +1682,7 @@
         // We expect a notification about the capabilities change, and nothing else.
         defaultCallback.expectCapabilitiesWithout(NET_CAPABILITY_NOT_METERED, mWiFiNetworkAgent);
         defaultCallback.assertNoCallback();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         // Wifi no longer satisfies our listen, which is for an unmetered network.
@@ -1678,11 +1691,11 @@
 
         // Disconnect our test networks.
         mWiFiNetworkAgent.disconnect();
-        defaultCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         defaultCallback.expectAvailableCallbacksValidated(mCellNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
         mCellNetworkAgent.disconnect();
-        defaultCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         waitForIdle();
         assertEquals(null, mCm.getActiveNetwork());
 
@@ -1713,8 +1726,8 @@
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         defaultCallback.expectAvailableCallbacksUnvalidated(mCellNetworkAgent);
         assertEquals(mCellNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
@@ -1725,15 +1738,15 @@
         mWiFiNetworkAgent.adjustScore(50);
         mWiFiNetworkAgent.connect(false);   // Score: 70
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         defaultCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         // Tear down wifi.
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         defaultCallback.expectAvailableCallbacksUnvalidated(mCellNetworkAgent);
         assertEquals(mCellNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
@@ -1744,19 +1757,19 @@
         mWiFiNetworkAgent.connect(true);
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         // TODO: Investigate sending validated before losing.
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         defaultCallback.expectAvailableThenValidatedCallbacks(mWiFiNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         defaultCallback.expectAvailableCallbacksUnvalidated(mCellNetworkAgent);
         mCellNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         waitForIdle();
         assertEquals(null, mCm.getActiveNetwork());
 
@@ -1771,7 +1784,7 @@
         defaultCallback.expectAvailableDoubleValidatedCallbacks(mWiFiNetworkAgent);
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         // TODO: Investigate sending validated before losing.
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
@@ -1782,13 +1795,13 @@
         // TODO: should this cause an AVAILABLE callback, to indicate that the network is no longer
         // lingering?
         mCm.unregisterNetworkCallback(noopCallback);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
 
         // Similar to the above: lingering can start even after the lingered request is removed.
         // Disconnect wifi and switch to cell.
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         defaultCallback.expectAvailableCallbacksValidated(mCellNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
@@ -1807,12 +1820,12 @@
         callback.assertNoCallback();
         // Now unregister cellRequest and expect cell to start lingering.
         mCm.unregisterNetworkCallback(noopCallback);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
 
         // Let linger run its course.
         callback.assertNoCallback();
         final int lingerTimeoutMs = mService.mLingerDelayMs + mService.mLingerDelayMs / 4;
-        callback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent, lingerTimeoutMs);
+        callback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent, lingerTimeoutMs);
 
         // Register a TRACK_DEFAULT request and check that it does not affect lingering.
         TestNetworkCallback trackDefaultCallback = new TestNetworkCallback();
@@ -1821,20 +1834,20 @@
         mEthernetNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_ETHERNET);
         mEthernetNetworkAgent.connect(true);
         callback.expectAvailableCallbacksUnvalidated(mEthernetNetworkAgent);
-        callback.expectCallback(CallbackRecord.LOSING, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mWiFiNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mEthernetNetworkAgent);
         trackDefaultCallback.expectAvailableDoubleValidatedCallbacks(mEthernetNetworkAgent);
         defaultCallback.expectAvailableDoubleValidatedCallbacks(mEthernetNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         // Let linger run its course.
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent, lingerTimeoutMs);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent, lingerTimeoutMs);
 
         // Clean up.
         mEthernetNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mEthernetNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, mEthernetNetworkAgent);
-        trackDefaultCallback.expectCallback(CallbackRecord.LOST, mEthernetNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mEthernetNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mEthernetNetworkAgent);
+        trackDefaultCallback.expectCallback(CallbackEntry.LOST, mEthernetNetworkAgent);
 
         mCm.unregisterNetworkCallback(callback);
         mCm.unregisterNetworkCallback(defaultCallback);
@@ -1864,7 +1877,7 @@
         mWiFiNetworkAgent.connect(true);
         defaultCallback.expectAvailableDoubleValidatedCallbacks(mWiFiNetworkAgent);
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
 
         // File a request for cellular, then release it.
@@ -1873,7 +1886,7 @@
         NetworkCallback noopCallback = new NetworkCallback();
         mCm.requestNetwork(cellRequest, noopCallback);
         mCm.unregisterNetworkCallback(noopCallback);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
 
         // Let linger run its course.
         callback.assertNoCallback();
@@ -1917,12 +1930,12 @@
         // If the user chooses yes on the "No Internet access, stay connected?" dialog, we switch to
         // wifi even though it's unvalidated.
         mCm.setAcceptUnvalidated(mWiFiNetworkAgent.getNetwork(), true, false);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
 
         // Disconnect wifi, and then reconnect, again with explicitlySelected=true.
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
         mWiFiNetworkAgent.explicitlySelected(true, false);
         mWiFiNetworkAgent.connect(false);
@@ -1931,14 +1944,14 @@
         // If the user chooses no on the "No Internet access, stay connected?" dialog, we ask the
         // network to disconnect.
         mCm.setAcceptUnvalidated(mWiFiNetworkAgent.getNetwork(), false, false);
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // Reconnect, again with explicitlySelected=true, but this time validate.
         mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
         mWiFiNetworkAgent.explicitlySelected(true, false);
         mWiFiNetworkAgent.connect(true);
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
 
@@ -1954,20 +1967,20 @@
         // (i.e., with explicitlySelected=true and acceptUnvalidated=true). Expect to switch to
         // wifi immediately.
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
         mWiFiNetworkAgent.explicitlySelected(true, true);
         mWiFiNetworkAgent.connect(false);
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        callback.expectCallback(CallbackRecord.LOSING, mEthernetNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mEthernetNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         mEthernetNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mEthernetNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mEthernetNetworkAgent);
 
         // Disconnect and reconnect with explicitlySelected=false and acceptUnvalidated=true.
         // Check that the network is not scored specially and that the device prefers cell data.
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
         mWiFiNetworkAgent.explicitlySelected(false, true);
         mWiFiNetworkAgent.connect(false);
@@ -1978,8 +1991,8 @@
         mWiFiNetworkAgent.disconnect();
         mCellNetworkAgent.disconnect();
 
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        callback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
     }
 
     private int[] makeIntArray(final int size, final int value) {
@@ -2226,7 +2239,7 @@
         // Need a trigger point to let NetworkMonitor tell ConnectivityService that network is
         // validated.
         mCm.reportNetworkConnectivity(mWiFiNetworkAgent.getNetwork(), true);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         NetworkCapabilities nc = callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED,
                 mWiFiNetworkAgent);
         assertTrue(nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY));
@@ -2234,7 +2247,7 @@
 
         // Disconnect and reconnect wifi with partial connectivity again.
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
         mWiFiNetworkAgent.connectWithPartialConnectivity();
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
@@ -2246,7 +2259,7 @@
         // If the user chooses no, disconnect wifi immediately.
         mCm.setAcceptPartialConnectivity(mWiFiNetworkAgent.getNetwork(), false/* accept */,
                 false /* always */);
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // If user accepted partial connectivity before, and device reconnects to that network
         // again, but now the network has full connectivity. The network shouldn't contain
@@ -2262,14 +2275,14 @@
         // ConnectivityService#updateNetworkInfo().
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity();
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         nc = callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         assertFalse(nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY));
 
         // Wifi should be the default network.
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // The user accepted partial connectivity and selected "don't ask again". Now the user
         // reconnects to the partial connectivity network. Switch to wifi as soon as partial
@@ -2283,7 +2296,7 @@
         // ConnectivityService#updateNetworkInfo().
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity();
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
         callback.expectCapabilitiesWith(NET_CAPABILITY_PARTIAL_CONNECTIVITY, mWiFiNetworkAgent);
         mWiFiNetworkAgent.setNetworkValid();
@@ -2293,7 +2306,7 @@
         mCm.reportNetworkConnectivity(mWiFiNetworkAgent.getNetwork(), true);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // If the user accepted partial connectivity, and the device auto-reconnects to the partial
         // connectivity network, it should contain both PARTIAL_CONNECTIVITY and VALIDATED.
@@ -2307,11 +2320,11 @@
         mWiFiNetworkAgent.connectWithPartialValidConnectivity();
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity();
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         callback.expectCapabilitiesWith(
                 NET_CAPABILITY_PARTIAL_CONNECTIVITY | NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
     }
 
     @Test
@@ -2353,7 +2366,7 @@
                 false /* always */);
         waitForIdle();
         mCm.reportNetworkConnectivity(mWiFiNetworkAgent.getNetwork(), true);
-        captivePortalCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        captivePortalCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         validatedCallback.expectAvailableCallbacksValidated(mWiFiNetworkAgent);
         NetworkCapabilities nc =
                 validatedCallback.expectCapabilitiesWith(NET_CAPABILITY_PARTIAL_CONNECTIVITY,
@@ -2386,7 +2399,7 @@
         // Take down network.
         // Expect onLost callback.
         mWiFiNetworkAgent.disconnect();
-        captivePortalCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        captivePortalCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // Bring up a network with a captive portal.
         // Expect onAvailable callback of listen for NET_CAPABILITY_CAPTIVE_PORTAL.
@@ -2400,7 +2413,7 @@
         // Expect onLost callback because network no longer provides NET_CAPABILITY_CAPTIVE_PORTAL.
         mWiFiNetworkAgent.setNetworkValid();
         mCm.reportNetworkConnectivity(mWiFiNetworkAgent.getNetwork(), true);
-        captivePortalCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        captivePortalCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // Expect NET_CAPABILITY_VALIDATED onAvailable callback.
         validatedCallback.expectAvailableDoubleValidatedCallbacks(mWiFiNetworkAgent);
@@ -2412,7 +2425,7 @@
         // Expect NET_CAPABILITY_VALIDATED onLost callback.
         mWiFiNetworkAgent.setNetworkInvalid();
         mCm.reportNetworkConnectivity(mWiFiNetworkAgent.getNetwork(), false);
-        validatedCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        validatedCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
     }
 
     @Test
@@ -2444,7 +2457,7 @@
         mWiFiNetworkAgent.setNetworkPortal("http://example.com");
         mCm.reportNetworkConnectivity(wifiNetwork, false);
         captivePortalCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        validatedCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        validatedCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // Check that startCaptivePortalApp sends the expected command to NetworkMonitor.
         mCm.startCaptivePortalApp(wifiNetwork);
@@ -2465,7 +2478,7 @@
         mWiFiNetworkAgent.setNetworkValid();
         mWiFiNetworkAgent.mNetworkMonitor.forceReevaluation(Process.myUid());
         validatedCallback.expectAvailableCallbacksValidated(mWiFiNetworkAgent);
-        captivePortalCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        captivePortalCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         verify(mNotificationManager, times(1)).notifyAsUser(anyString(),
                 eq(NotificationType.LOGGED_IN.eventId), any(), eq(UserHandle.ALL));
 
@@ -2613,7 +2626,7 @@
         cFoo.assertNoCallback();
 
         mWiFiNetworkAgent.setNetworkSpecifier(nsBar);
-        cFoo.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        cFoo.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         cBar.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         for (TestNetworkCallback c: emptyCallbacks) {
             c.expectCapabilitiesThat(mWiFiNetworkAgent,
@@ -2641,10 +2654,10 @@
         cBar.assertNoCallback();
 
         mWiFiNetworkAgent.setNetworkSpecifier(null);
-        cFoo.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        cBar.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        cFoo.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        cBar.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         for (TestNetworkCallback c: emptyCallbacks) {
-            c.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED, mWiFiNetworkAgent);
+            c.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED, mWiFiNetworkAgent);
         }
 
         assertNoCallbacks(cEmpty1, cEmpty2, cEmpty3, cEmpty4, cFoo, cBar);
@@ -2787,7 +2800,7 @@
 
         // Bring down cell. Expect no default network callback, since it wasn't the default.
         mCellNetworkAgent.disconnect();
-        cellNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         defaultNetworkCallback.assertNoCallback();
         assertEquals(defaultNetworkCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
@@ -2802,11 +2815,11 @@
         // followed by AVAILABLE cell.
         mWiFiNetworkAgent.disconnect();
         cellNetworkCallback.assertNoCallback();
-        defaultNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        defaultNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         defaultNetworkCallback.expectAvailableCallbacksValidated(mCellNetworkAgent);
         mCellNetworkAgent.disconnect();
-        cellNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
-        defaultNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
+        defaultNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         waitForIdle();
         assertEquals(null, mCm.getActiveNetwork());
 
@@ -2823,7 +2836,7 @@
         assertEquals(defaultNetworkCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         vpnNetworkAgent.disconnect();
-        defaultNetworkCallback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
+        defaultNetworkCallback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
         waitForIdle();
         assertEquals(null, mCm.getActiveNetwork());
     }
@@ -2851,7 +2864,7 @@
         lp.setInterfaceName("foonet_data0");
         mCellNetworkAgent.sendLinkProperties(lp);
         // We should get onLinkPropertiesChanged().
-        cellNetworkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED,
+        cellNetworkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED,
                 mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
 
@@ -2859,7 +2872,7 @@
         mCellNetworkAgent.suspend();
         cellNetworkCallback.expectCapabilitiesWithout(NET_CAPABILITY_NOT_SUSPENDED,
                 mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.SUSPENDED, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.SUSPENDED, mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
 
         // Register a garden variety default network request.
@@ -2874,7 +2887,7 @@
         mCellNetworkAgent.resume();
         cellNetworkCallback.expectCapabilitiesWith(NET_CAPABILITY_NOT_SUSPENDED,
                 mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.RESUMED, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.RESUMED, mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
 
         dfltNetworkCallback = new TestNetworkCallback();
@@ -2937,10 +2950,10 @@
 
         // When wifi connects, cell lingers.
         callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        callback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         fgCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        fgCallback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        fgCallback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         fgCallback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         assertTrue(isForegroundNetwork(mCellNetworkAgent));
         assertTrue(isForegroundNetwork(mWiFiNetworkAgent));
@@ -2948,7 +2961,7 @@
         // When lingering is complete, cell is still there but is now in the background.
         waitForIdle();
         int timeoutMs = TEST_LINGER_DELAY_MS + TEST_LINGER_DELAY_MS / 4;
-        fgCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent, timeoutMs);
+        fgCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent, timeoutMs);
         // Expect a network capabilities update sans FOREGROUND.
         callback.expectCapabilitiesWithout(NET_CAPABILITY_FOREGROUND, mCellNetworkAgent);
         assertFalse(isForegroundNetwork(mCellNetworkAgent));
@@ -2974,7 +2987,7 @@
         // Release the request. The network immediately goes into the background, since it was not
         // lingering.
         mCm.unregisterNetworkCallback(cellCallback);
-        fgCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        fgCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         // Expect a network capabilities update sans FOREGROUND.
         callback.expectCapabilitiesWithout(NET_CAPABILITY_FOREGROUND, mCellNetworkAgent);
         assertFalse(isForegroundNetwork(mCellNetworkAgent));
@@ -2982,8 +2995,8 @@
 
         // Disconnect wifi and check that cell is foreground again.
         mWiFiNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        fgCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        fgCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         fgCallback.expectAvailableCallbacksValidated(mCellNetworkAgent);
         assertTrue(isForegroundNetwork(mCellNetworkAgent));
 
@@ -3120,7 +3133,7 @@
         testFactory.waitForNetworkRequests(1);
 
         // ...  and cell data to be torn down.
-        cellNetworkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         assertLength(1, mCm.getAllNetworks());
 
         testFactory.unregister();
@@ -3209,7 +3222,7 @@
         mWiFiNetworkAgent.setNetworkInvalid();
         mCm.reportNetworkConnectivity(wifiNetwork, false);
         defaultCallback.expectCapabilitiesWithout(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
-        validatedWifiCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        validatedWifiCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // Because avoid bad wifi is off, we don't switch to cellular.
         defaultCallback.assertNoCallback();
@@ -3253,7 +3266,7 @@
         mWiFiNetworkAgent.setNetworkInvalid();
         mCm.reportNetworkConnectivity(wifiNetwork, false);
         defaultCallback.expectCapabilitiesWithout(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
-        validatedWifiCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        validatedWifiCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // Simulate the user selecting "switch" and checking the don't ask again checkbox.
         Settings.Global.putInt(cr, Settings.Global.NETWORK_AVOID_BAD_WIFI, 1);
@@ -3280,7 +3293,7 @@
 
         // If cell goes down, we switch to wifi.
         mCellNetworkAgent.disconnect();
-        defaultCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         defaultCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
         validatedWifiCallback.assertNoCallback();
 
@@ -3344,7 +3357,7 @@
         networkCallback.expectAvailableCallbacks(mWiFiNetworkAgent, false, false, false,
                 TEST_CALLBACK_TIMEOUT_MS);
         mWiFiNetworkAgent.disconnect();
-        networkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
 
         // Validate that UNAVAILABLE is not called
         networkCallback.assertNoCallback();
@@ -3364,7 +3377,7 @@
         mCm.requestNetwork(nr, networkCallback, timeoutMs);
 
         // pass timeout and validate that UNAVAILABLE is called
-        networkCallback.expectCallback(CallbackRecord.UNAVAILABLE, null);
+        networkCallback.expectCallback(CallbackEntry.UNAVAILABLE, null);
 
         // create a network satisfying request - validate that request not triggered
         mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
@@ -3455,7 +3468,7 @@
             // Simulate the factory releasing the request as unfulfillable and expect onUnavailable!
             testFactory.triggerUnfulfillable(requests.get(newRequestId));
 
-            networkCallback.expectCallback(CallbackRecord.UNAVAILABLE, null);
+            networkCallback.expectCallback(CallbackEntry.UNAVAILABLE, null);
             testFactory.waitForRequests();
 
             // unregister network callback - a no-op (since already freed by the
@@ -4297,7 +4310,7 @@
 
         // Disconnect wifi aware network.
         wifiAware.disconnect();
-        callback.expectCallbackThat(TIMEOUT_MS, (info) -> info instanceof CallbackRecord.Lost);
+        callback.expectCallbackThat(TIMEOUT_MS, (info) -> info instanceof CallbackEntry.Lost);
         mCm.unregisterNetworkCallback(callback);
 
         verifyNoNetwork();
@@ -4315,16 +4328,16 @@
         assertFalse(mCm.isNetworkSupported(TYPE_NONE));
 
         assertThrows(IllegalArgumentException.class,
-                () -> { mCm.networkCapabilitiesForType(TYPE_NONE); });
+                () -> mCm.networkCapabilitiesForType(TYPE_NONE));
 
         Class<UnsupportedOperationException> unsupported = UnsupportedOperationException.class;
-        assertThrows(unsupported, () -> { mCm.startUsingNetworkFeature(TYPE_WIFI, ""); });
-        assertThrows(unsupported, () -> { mCm.stopUsingNetworkFeature(TYPE_WIFI, ""); });
+        assertThrows(unsupported, () -> mCm.startUsingNetworkFeature(TYPE_WIFI, ""));
+        assertThrows(unsupported, () -> mCm.stopUsingNetworkFeature(TYPE_WIFI, ""));
         // TODO: let test context have configuration application target sdk version
         // and test that pre-M requesting for TYPE_NONE sends back APN_REQUEST_FAILED
-        assertThrows(unsupported, () -> { mCm.startUsingNetworkFeature(TYPE_NONE, ""); });
-        assertThrows(unsupported, () -> { mCm.stopUsingNetworkFeature(TYPE_NONE, ""); });
-        assertThrows(unsupported, () -> { mCm.requestRouteToHostAddress(TYPE_NONE, null); });
+        assertThrows(unsupported, () -> mCm.startUsingNetworkFeature(TYPE_NONE, ""));
+        assertThrows(unsupported, () -> mCm.stopUsingNetworkFeature(TYPE_NONE, ""));
+        assertThrows(unsupported, () -> mCm.requestRouteToHostAddress(TYPE_NONE, null));
     }
 
     @Test
@@ -4346,12 +4359,12 @@
         // ConnectivityService.
         TestNetworkAgentWrapper networkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI, lp);
         networkAgent.connect(true);
-        networkCallback.expectCallback(CallbackRecord.AVAILABLE, networkAgent);
-        networkCallback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED, networkAgent);
-        CallbackRecord.LinkPropertiesChanged cbi =
-                networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED,
+        networkCallback.expectCallback(CallbackEntry.AVAILABLE, networkAgent);
+        networkCallback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED, networkAgent);
+        CallbackEntry.LinkPropertiesChanged cbi =
+                networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED,
                 networkAgent);
-        networkCallback.expectCallback(CallbackRecord.BLOCKED_STATUS, networkAgent);
+        networkCallback.expectCallback(CallbackEntry.BLOCKED_STATUS, networkAgent);
         networkCallback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, networkAgent);
         networkCallback.assertNoCallback();
         checkDirectlyConnectedRoutes(cbi.getLp(), Arrays.asList(myIpv4Address),
@@ -4366,7 +4379,7 @@
         newLp.addLinkAddress(myIpv6Address1);
         newLp.addLinkAddress(myIpv6Address2);
         networkAgent.sendLinkProperties(newLp);
-        cbi = networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, networkAgent);
+        cbi = networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, networkAgent);
         networkCallback.assertNoCallback();
         checkDirectlyConnectedRoutes(cbi.getLp(),
                 Arrays.asList(myIpv4Address, myIpv6Address1, myIpv6Address2),
@@ -4572,12 +4585,12 @@
         assertTrue(ArrayUtils.containsAll(resolvrParams.tlsServers,
                 new String[] { "2001:db8::1", "192.0.2.1" }));
         reset(mMockDnsResolver);
-        cellNetworkCallback.expectCallback(CallbackRecord.AVAILABLE, mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED,
+        cellNetworkCallback.expectCallback(CallbackEntry.AVAILABLE, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED,
                 mCellNetworkAgent);
-        CallbackRecord.LinkPropertiesChanged cbi = cellNetworkCallback.expectCallback(
-                CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.BLOCKED_STATUS, mCellNetworkAgent);
+        CallbackEntry.LinkPropertiesChanged cbi = cellNetworkCallback.expectCallback(
+                CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.BLOCKED_STATUS, mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         assertFalse(cbi.getLp().isPrivateDnsActive());
         assertNull(cbi.getLp().getPrivateDnsServerName());
@@ -4608,7 +4621,7 @@
         setPrivateDnsSettings(PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, "strict.example.com");
         // Can't test dns configuration for strict mode without properly mocking
         // out the DNS lookups, but can test that LinkProperties is updated.
-        cbi = cellNetworkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED,
+        cbi = cellNetworkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED,
                 mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         assertTrue(cbi.getLp().isPrivateDnsActive());
@@ -4631,12 +4644,12 @@
         mCellNetworkAgent.sendLinkProperties(lp);
         mCellNetworkAgent.connect(false);
         waitForIdle();
-        cellNetworkCallback.expectCallback(CallbackRecord.AVAILABLE, mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED,
+        cellNetworkCallback.expectCallback(CallbackEntry.AVAILABLE, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED,
                 mCellNetworkAgent);
-        CallbackRecord.LinkPropertiesChanged cbi = cellNetworkCallback.expectCallback(
-                CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
-        cellNetworkCallback.expectCallback(CallbackRecord.BLOCKED_STATUS, mCellNetworkAgent);
+        CallbackEntry.LinkPropertiesChanged cbi = cellNetworkCallback.expectCallback(
+                CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        cellNetworkCallback.expectCallback(CallbackEntry.BLOCKED_STATUS, mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         assertFalse(cbi.getLp().isPrivateDnsActive());
         assertNull(cbi.getLp().getPrivateDnsServerName());
@@ -4653,7 +4666,7 @@
         LinkProperties lp2 = new LinkProperties(lp);
         lp2.addDnsServer(InetAddress.getByName("145.100.185.16"));
         mCellNetworkAgent.sendLinkProperties(lp2);
-        cbi = cellNetworkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED,
+        cbi = cellNetworkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED,
                 mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         assertFalse(cbi.getLp().isPrivateDnsActive());
@@ -4677,7 +4690,7 @@
         // private dns fields should be sent.
         mService.mNetdEventCallback.onPrivateDnsValidationEvent(
                 mCellNetworkAgent.getNetwork().netId, "145.100.185.16", "", true);
-        cbi = cellNetworkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED,
+        cbi = cellNetworkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED,
                 mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         assertTrue(cbi.getLp().isPrivateDnsActive());
@@ -4689,7 +4702,7 @@
         LinkProperties lp3 = new LinkProperties(lp2);
         lp3.setMtu(1300);
         mCellNetworkAgent.sendLinkProperties(lp3);
-        cbi = cellNetworkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED,
+        cbi = cellNetworkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED,
                 mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         assertTrue(cbi.getLp().isPrivateDnsActive());
@@ -4702,7 +4715,7 @@
         LinkProperties lp4 = new LinkProperties(lp3);
         lp4.removeDnsServer(InetAddress.getByName("145.100.185.16"));
         mCellNetworkAgent.sendLinkProperties(lp4);
-        cbi = cellNetworkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED,
+        cbi = cellNetworkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED,
                 mCellNetworkAgent);
         cellNetworkCallback.assertNoCallback();
         assertFalse(cbi.getLp().isPrivateDnsActive());
@@ -4793,19 +4806,19 @@
         defaultCallback.expectAvailableCallbacksUnvalidated(vpnNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
-        genericNetworkCallback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
         genericNotVpnNetworkCallback.assertNoCallback();
         vpnNetworkCallback.expectCapabilitiesThat(vpnNetworkAgent, nc -> null == nc.getUids());
-        defaultCallback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         ranges.clear();
         vpnNetworkAgent.setUids(ranges);
 
-        genericNetworkCallback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
         genericNotVpnNetworkCallback.assertNoCallback();
         wifiNetworkCallback.assertNoCallback();
-        vpnNetworkCallback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
+        vpnNetworkCallback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
 
         // TODO : The default network callback should actually get a LOST call here (also see the
         // comment below for AVAILABLE). This is because ConnectivityService does not look at UID
@@ -4813,7 +4826,7 @@
         // can't currently update their UIDs without disconnecting, so this does not matter too
         // much, but that is the reason the test here has to check for an update to the
         // capabilities instead of the expected LOST then AVAILABLE.
-        defaultCallback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
 
         ranges.add(new UidRange(uid, uid));
         mMockVpn.setUids(ranges);
@@ -4825,23 +4838,23 @@
         vpnNetworkCallback.expectAvailableCallbacksValidated(vpnNetworkAgent);
         // TODO : Here like above, AVAILABLE would be correct, but because this can't actually
         // happen outside of the test, ConnectivityService does not rematch callbacks.
-        defaultCallback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
 
         mWiFiNetworkAgent.disconnect();
 
-        genericNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        genericNotVpnNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
-        wifiNetworkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        genericNotVpnNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
+        wifiNetworkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         vpnNetworkCallback.assertNoCallback();
         defaultCallback.assertNoCallback();
 
         vpnNetworkAgent.disconnect();
 
-        genericNetworkCallback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
+        genericNetworkCallback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
         genericNotVpnNetworkCallback.assertNoCallback();
         wifiNetworkCallback.assertNoCallback();
-        vpnNetworkCallback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
-        defaultCallback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
+        vpnNetworkCallback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
         assertEquals(null, mCm.getActiveNetwork());
 
         mCm.unregisterNetworkCallback(genericNetworkCallback);
@@ -4907,7 +4920,7 @@
         assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
 
         vpnNetworkAgent.disconnect();
-        defaultCallback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
         defaultCallback.expectAvailableCallbacksValidated(mWiFiNetworkAgent);
 
         mCm.unregisterNetworkCallback(defaultCallback);
@@ -4938,7 +4951,7 @@
         // Even though the VPN is unvalidated, it becomes the default network for our app.
         callback.expectAvailableCallbacksUnvalidated(vpnNetworkAgent);
         // TODO: this looks like a spurious callback.
-        callback.expectCallback(CallbackRecord.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
+        callback.expectCallback(CallbackEntry.NETWORK_CAPS_UPDATED, vpnNetworkAgent);
         callback.assertNoCallback();
 
         assertTrue(vpnNetworkAgent.getScore() > mEthernetNetworkAgent.getScore());
@@ -4963,7 +4976,7 @@
         callback.assertNoCallback();
 
         vpnNetworkAgent.disconnect();
-        callback.expectCallback(CallbackRecord.LOST, vpnNetworkAgent);
+        callback.expectCallback(CallbackEntry.LOST, vpnNetworkAgent);
         callback.expectAvailableCallbacksValidated(mEthernetNetworkAgent);
     }
 
@@ -5405,7 +5418,7 @@
 
         // Switch to METERED network. Restrict the use of the network.
         mWiFiNetworkAgent.disconnect();
-        defaultCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         defaultCallback.expectAvailableCallbacksValidatedAndBlocked(mCellNetworkAgent);
 
         // Network becomes NOT_METERED.
@@ -5419,7 +5432,7 @@
         defaultCallback.assertNoCallback();
 
         mCellNetworkAgent.disconnect();
-        defaultCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        defaultCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         defaultCallback.assertNoCallback();
 
         mCm.unregisterNetworkCallback(defaultCallback);
@@ -5495,7 +5508,7 @@
         // the NAT64 prefix was removed because one was never discovered.
         cellLp.addLinkAddress(myIpv4);
         mCellNetworkAgent.sendLinkProperties(cellLp);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         verify(mMockDnsResolver, times(1)).stopPrefix64Discovery(cellNetId);
         verify(mMockDnsResolver, atLeastOnce()).setResolverConfiguration(any());
 
@@ -5508,7 +5521,7 @@
         cellLp.removeLinkAddress(myIpv4);
         cellLp.removeRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
         mCellNetworkAgent.sendLinkProperties(cellLp);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         verify(mMockDnsResolver, times(1)).startPrefix64Discovery(cellNetId);
 
         // When NAT64 prefix discovery succeeds, LinkProperties are updated and clatd is started.
@@ -5517,14 +5530,14 @@
         mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, true /* added */,
                 kNat64PrefixString, 96);
         LinkProperties lpBeforeClat = networkCallback.expectCallback(
-                CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent).getLp();
+                CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent).getLp();
         assertEquals(0, lpBeforeClat.getStackedLinks().size());
         assertEquals(kNat64Prefix, lpBeforeClat.getNat64Prefix());
         verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME, kNat64Prefix.toString());
 
         // Clat iface comes up. Expect stacked link to be added.
         clat.interfaceLinkStateChanged(CLAT_PREFIX + MOBILE_IFNAME, true);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         List<LinkProperties> stackedLps = mCm.getLinkProperties(mCellNetworkAgent.getNetwork())
                 .getStackedLinks();
         assertEquals(makeClatLinkProperties(myIpv4), stackedLps.get(0));
@@ -5532,7 +5545,7 @@
         // Change trivial linkproperties and see if stacked link is preserved.
         cellLp.addDnsServer(InetAddress.getByName("8.8.8.8"));
         mCellNetworkAgent.sendLinkProperties(cellLp);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
 
         List<LinkProperties> stackedLpsAfterChange =
                 mCm.getLinkProperties(mCellNetworkAgent.getNetwork()).getStackedLinks();
@@ -5550,12 +5563,12 @@
         cellLp.addLinkAddress(myIpv4);
         cellLp.addRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
         mCellNetworkAgent.sendLinkProperties(cellLp);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         verify(mMockNetd, times(1)).clatdStop(MOBILE_IFNAME);
         verify(mMockDnsResolver, times(1)).stopPrefix64Discovery(cellNetId);
 
         // As soon as stop is called, the linkproperties lose the stacked interface.
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         LinkProperties actualLpAfterIpv4 = mCm.getLinkProperties(mCellNetworkAgent.getNetwork());
         LinkProperties expected = new LinkProperties(cellLp);
         expected.setNat64Prefix(kNat64Prefix);
@@ -5582,11 +5595,11 @@
         cellLp.removeRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
         cellLp.removeDnsServer(InetAddress.getByName("8.8.8.8"));
         mCellNetworkAgent.sendLinkProperties(cellLp);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         verify(mMockDnsResolver, times(1)).startPrefix64Discovery(cellNetId);
         mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, true /* added */,
                 kNat64PrefixString, 96);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         verify(mMockNetd, times(1)).clatdStart(MOBILE_IFNAME, kNat64Prefix.toString());
 
 
@@ -5606,7 +5619,7 @@
 
         // Clean up.
         mCellNetworkAgent.disconnect();
-        networkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         networkCallback.assertNoCallback();
         mCm.unregisterNetworkCallback(networkCallback);
     }
@@ -5638,7 +5651,7 @@
         reset(mNetworkManagementService);
         mWiFiNetworkAgent.connect(true);
         networkCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        networkCallback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         networkCallback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
         verify(mNetworkManagementService, times(1)).addIdleTimer(eq(WIFI_IFNAME), anyInt(),
                 eq(ConnectivityManager.TYPE_WIFI));
@@ -5647,7 +5660,7 @@
         // Disconnect wifi and switch back to cell
         reset(mNetworkManagementService);
         mWiFiNetworkAgent.disconnect();
-        networkCallback.expectCallback(CallbackRecord.LOST, mWiFiNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
         assertNoCallbacks(networkCallback);
         verify(mNetworkManagementService, times(1)).removeIdleTimer(eq(WIFI_IFNAME));
         verify(mNetworkManagementService, times(1)).addIdleTimer(eq(MOBILE_IFNAME), anyInt(),
@@ -5659,14 +5672,14 @@
         mWiFiNetworkAgent.sendLinkProperties(wifiLp);
         mWiFiNetworkAgent.connect(true);
         networkCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
-        networkCallback.expectCallback(CallbackRecord.LOSING, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
         networkCallback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
 
         // Disconnect cell
         reset(mNetworkManagementService);
         reset(mMockNetd);
         mCellNetworkAgent.disconnect();
-        networkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         // LOST callback is triggered earlier than removing idle timer. Broadcast should also be
         // sent as network being switched. Ensure rule removal for cell will not be triggered
         // unexpectedly before network being removed.
@@ -5717,12 +5730,12 @@
         LinkProperties lp = new LinkProperties();
         lp.setTcpBufferSizes(testTcpBufferSizes);
         mCellNetworkAgent.sendLinkProperties(lp);
-        networkCallback.expectCallback(CallbackRecord.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
         verifyTcpBufferSizeChange(testTcpBufferSizes);
 
         // Clean up.
         mCellNetworkAgent.disconnect();
-        networkCallback.expectCallback(CallbackRecord.LOST, mCellNetworkAgent);
+        networkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
         networkCallback.assertNoCallback();
         mCm.unregisterNetworkCallback(networkCallback);
     }
@@ -5941,6 +5954,24 @@
         assertContainsExactly(uidCaptor.getValue(), APP2_UID);
     }
 
+    @Test
+    public void testLinkPropertiesWithWakeOnLanForActiveNetwork() throws Exception {
+        mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
+
+        LinkProperties wifiLp = new LinkProperties();
+        wifiLp.setInterfaceName(WIFI_WOL_IFNAME);
+        wifiLp.setWakeOnLanSupported(false);
+
+        // Default network switch should update ifaces.
+        mWiFiNetworkAgent.connect(false);
+        mWiFiNetworkAgent.sendLinkProperties(wifiLp);
+        waitForIdle();
+
+        // ConnectivityService should have changed the WakeOnLanSupported to true
+        wifiLp.setWakeOnLanSupported(true);
+        assertEquals(wifiLp, mService.getActiveLinkProperties());
+    }
+
 
     private TestNetworkAgentWrapper establishVpn(LinkProperties lp, int establishingUid,
             Set<UidRange> vpnRange) throws Exception {
diff --git a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
index cd2bd26..3fdba6e 100644
--- a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
+++ b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
@@ -54,7 +54,6 @@
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
-import android.content.pm.PackageList;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManagerInternal;
 import android.content.pm.UserInfo;
@@ -70,6 +69,7 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.server.LocalServices;
+import com.android.server.pm.PackageList;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -561,11 +561,17 @@
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_NONE, new int[]{SYSTEM_UID1});
     }
 
-    private PackageInfo addPackage(String packageName, int uid, String[] permissions)
+    private PackageInfo setPackagePermissions(String packageName, int uid, String[] permissions)
             throws Exception {
         PackageInfo packageInfo = packageInfoWithPermissions(permissions, PARTITION_SYSTEM);
         when(mPackageManager.getPackageInfo(eq(packageName), anyInt())).thenReturn(packageInfo);
         when(mPackageManager.getPackagesForUid(eq(uid))).thenReturn(new String[]{packageName});
+        return packageInfo;
+    }
+
+    private PackageInfo addPackage(String packageName, int uid, String[] permissions)
+            throws Exception {
+        PackageInfo packageInfo = setPackagePermissions(packageName, uid, permissions);
         mObserver.onPackageAdded(packageName, uid);
         return packageInfo;
     }
@@ -616,14 +622,13 @@
     }
 
     @Test
-    public void testPackageUpdate() throws Exception {
+    public void testPackageRemoveThenAdd() throws Exception {
         final NetdServiceMonitor mNetdServiceMonitor = new NetdServiceMonitor(mNetdService);
 
         addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET, UPDATE_DEVICE_STATS});
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET
                 | INetd.PERMISSION_UPDATE_DEVICE_STATS, new int[]{MOCK_UID1});
 
-        // Remove and install the same package to simulate the update action
         when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{});
         mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_UNINSTALLED, new int[]{MOCK_UID1});
@@ -633,6 +638,20 @@
     }
 
     @Test
+    public void testPackageUpdate() throws Exception {
+        final NetdServiceMonitor mNetdServiceMonitor = new NetdServiceMonitor(mNetdService);
+
+        addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {});
+        mNetdServiceMonitor.expectPermission(INetd.PERMISSION_NONE, new int[]{MOCK_UID1});
+
+        // When updating a package, the broadcast receiver gets two broadcasts (a remove and then an
+        // add), but the observer sees only one callback (an update).
+        setPackagePermissions(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET});
+        mObserver.onPackageChanged(MOCK_PACKAGE1, MOCK_UID1);
+        mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET, new int[]{MOCK_UID1});
+    }
+
+    @Test
     public void testPackageUninstallWithMultiplePackages() throws Exception {
         final NetdServiceMonitor mNetdServiceMonitor = new NetdServiceMonitor(mNetdService);
 
diff --git a/tests/utils/testutils/java/android/os/test/TestLooper.java b/tests/utils/testutils/java/android/os/test/TestLooper.java
index a49eda3..01bd47b 100644
--- a/tests/utils/testutils/java/android/os/test/TestLooper.java
+++ b/tests/utils/testutils/java/android/os/test/TestLooper.java
@@ -210,33 +210,36 @@
         /**
          * Run method for the auto dispatch thread.
          * The thread loops a maximum of MAX_LOOPS times with a 10ms sleep between loops.
-         * The thread continues looping and attempting to dispatch all messages until at
-         * least one message has been dispatched.
+         * The thread continues looping and attempting to dispatch all messages until
+         * {@link #stopAutoDispatch()} has been invoked.
          */
         @Override
         public void run() {
             int dispatchCount = 0;
             for (int i = 0; i < MAX_LOOPS; i++) {
                 try {
-                    dispatchCount = dispatchAll();
+                    dispatchCount += dispatchAll();
                 } catch (RuntimeException e) {
                     mAutoDispatchException = e;
-                }
-                Log.d(TAG, "dispatched " + dispatchCount + " messages");
-                if (dispatchCount > 0) {
                     return;
                 }
+                Log.d(TAG, "dispatched " + dispatchCount + " messages");
                 try {
                     Thread.sleep(LOOP_SLEEP_TIME_MS);
                 } catch (InterruptedException e) {
-                    mAutoDispatchException = new IllegalStateException(
-                            "stopAutoDispatch called before any messages were dispatched.");
+                    if (dispatchCount == 0) {
+                        Log.e(TAG, "stopAutoDispatch called before any messages were dispatched.");
+                        mAutoDispatchException = new IllegalStateException(
+                                "stopAutoDispatch called before any messages were dispatched.");
+                    }
                     return;
                 }
             }
-            Log.e(TAG, "AutoDispatchThread did not dispatch any messages.");
-            mAutoDispatchException = new IllegalStateException(
-                    "TestLooper did not dispatch any messages before exiting.");
+            if (dispatchCount == 0) {
+                Log.e(TAG, "AutoDispatchThread did not dispatch any messages.");
+                mAutoDispatchException = new IllegalStateException(
+                        "TestLooper did not dispatch any messages before exiting.");
+            }
         }
 
         /**
@@ -287,4 +290,17 @@
                     "stopAutoDispatch called without startAutoDispatch.");
         }
     }
+
+    /**
+     * If an AutoDispatchThread is currently running, stop and clean up.
+     * This method ignores exceptions raised for indicating that no messages were dispatched.
+     */
+    public void stopAutoDispatchAndIgnoreExceptions() {
+        try {
+            stopAutoDispatch();
+        } catch (IllegalStateException e) {
+            Log.e(TAG, "stopAutoDispatch", e);
+        }
+
+    }
 }
diff --git a/tools/aapt2/Main.cpp b/tools/aapt2/Main.cpp
index 7966ba2..8a43bb4 100644
--- a/tools/aapt2/Main.cpp
+++ b/tools/aapt2/Main.cpp
@@ -169,17 +169,12 @@
   aapt::text::Printer printer(&fout);
 
   aapt::StdErrDiagnostics diagnostics;
-  auto main_command = new aapt::MainCommand(&printer, &diagnostics);
+  aapt::MainCommand main_command(&printer, &diagnostics);
 
   // Add the daemon subcommand here so it cannot be called while executing the daemon
-  main_command->AddOptionalSubcommand(
+  main_command.AddOptionalSubcommand(
       aapt::util::make_unique<aapt::DaemonCommand>(&fout, &diagnostics));
-  return main_command->Execute(args, &std::cerr);
-}
-
-// TODO(b/141312058) stop leaks
-extern "C" const char *__asan_default_options() {
-    return "detect_leaks=0";
+  return main_command.Execute(args, &std::cerr);
 }
 
 int main(int argc, char** argv) {
diff --git a/tools/codegen/src/com/android/codegen/ClassInfo.kt b/tools/codegen/src/com/android/codegen/ClassInfo.kt
index 5061be2..92da9da 100644
--- a/tools/codegen/src/com/android/codegen/ClassInfo.kt
+++ b/tools/codegen/src/com/android/codegen/ClassInfo.kt
@@ -38,6 +38,11 @@
     val superInterfaces = (fileAst.types[0] as ClassOrInterfaceDeclaration)
             .implementedTypes.map { it.asString() }
 
+    val superClass = run {
+        val superClasses = (fileAst.types[0] as ClassOrInterfaceDeclaration).extendedTypes
+        if (superClasses.isNonEmpty) superClasses[0] else null
+    }
+
     val ClassName = classAst.nameAsString
     private val genericArgsAst = classAst.typeParameters
     val genericArgs = if (genericArgsAst.isEmpty()) "" else {
diff --git a/tools/codegen/src/com/android/codegen/ClassPrinter.kt b/tools/codegen/src/com/android/codegen/ClassPrinter.kt
index 1f0d4b8..bd72d9e 100644
--- a/tools/codegen/src/com/android/codegen/ClassPrinter.kt
+++ b/tools/codegen/src/com/android/codegen/ClassPrinter.kt
@@ -1,6 +1,7 @@
 package com.android.codegen
 
 import com.github.javaparser.ast.Modifier
+import com.github.javaparser.ast.body.CallableDeclaration
 import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
 import com.github.javaparser.ast.body.TypeDeclaration
 import com.github.javaparser.ast.expr.*
@@ -37,6 +38,7 @@
     val GeneratedMember by lazy { classRef("com.android.internal.util.DataClass.Generated.Member") }
     val Parcelling by lazy { classRef("com.android.internal.util.Parcelling") }
     val Parcelable by lazy { classRef("android.os.Parcelable") }
+    val Parcel by lazy { classRef("android.os.Parcel") }
     val UnsupportedAppUsage by lazy { classRef("android.annotation.UnsupportedAppUsage") }
 
     init {
@@ -354,7 +356,9 @@
     }
 
     fun hasMethod(name: String, vararg argTypes: String): Boolean {
-        return classAst.methods.any {
+        val members: List<CallableDeclaration<*>> =
+                if (name == ClassName) classAst.constructors else classAst.methods
+        return members.any {
             it.name.asString() == name &&
                     it.parameters.map { it.type.asString() } == argTypes.toList()
         }
@@ -365,6 +369,10 @@
             .mapIndexed { i, node -> FieldInfo(index = i, fieldAst = node, classInfo = this) }
             .filter { hasMethod("lazyInit${it.NameUpperCamel}") }
 
+    val extendsParcelableClass by lazy {
+        Parcelable !in superInterfaces && superClass != null
+    }
+
     init {
         val builderFactoryOverride = classAst.methods.find {
             it.isStatic && it.nameAsString == "builder"
diff --git a/tools/codegen/src/com/android/codegen/Generators.kt b/tools/codegen/src/com/android/codegen/Generators.kt
index 914e475..5a95676 100644
--- a/tools/codegen/src/com/android/codegen/Generators.kt
+++ b/tools/codegen/src/com/android/codegen/Generators.kt
@@ -341,7 +341,7 @@
             }
         }
 
-        if (Type.contains("Map<")) {
+        if (FieldClass.endsWith("Map") && FieldInnerType != null) {
             generateBuilderMethod(
                     name = adderName,
                     defVisibility = visibility,
@@ -422,6 +422,10 @@
             +"// void parcelFieldName(Parcel dest, int flags) { ... }"
             +""
 
+            if (extendsParcelableClass) {
+                +"super.writeToParcel(dest, flags);\n"
+            }
+
             if (booleanFields.isNotEmpty() || nullableFields.isNotEmpty()) {
                 +"$flagStorageType flg = 0;"
                 booleanFields.forEachApply {
@@ -463,6 +467,123 @@
         +""
     }
 
+    if (!hasMethod(ClassName, Parcel)) {
+        val visibility = if (classAst.isFinal) "/* package-private */" else "protected"
+
+        +"/** @hide */"
+        +"@SuppressWarnings({\"unchecked\", \"RedundantCast\"})"
+        +GENERATED_MEMBER_HEADER
+        "$visibility $ClassName($Parcel in) {" {
+            +"// You can override field unparcelling by defining methods like:"
+            +"// static FieldType unparcelFieldName(Parcel in) { ... }"
+            +""
+
+            if (extendsParcelableClass) {
+                +"super(in);\n"
+            }
+
+            if (booleanFields.isNotEmpty() || nullableFields.isNotEmpty()) {
+                +"$flagStorageType flg = in.read$FlagStorageType();"
+            }
+            booleanFields.forEachApply {
+                +"$Type $_name = (flg & $fieldBit) != 0;"
+            }
+            nonBooleanFields.forEachApply {
+
+                // Handle customized parceling
+                val customParcellingMethod = "unparcel$NameUpperCamel"
+                if (hasMethod(customParcellingMethod, Parcel)) {
+                    +"$Type $_name = $customParcellingMethod(in);"
+                } else if (customParcellingClass != null) {
+                    +"$Type $_name = $sParcelling.unparcel(in);"
+                } else if (hasAnnotation("@$DataClassEnum")) {
+                    val ordinal = "${_name}Ordinal"
+                    +"int $ordinal = in.readInt();"
+                    +"$Type $_name = $ordinal < 0 ? null : $FieldClass.values()[$ordinal];"
+                } else {
+                    val methodArgs = mutableListOf<String>()
+
+                    // Create container if any
+                    val containerInitExpr = when {
+                        FieldClass.endsWith("Map") -> "new $LinkedHashMap<>()"
+                        FieldClass == "List" || FieldClass == "ArrayList" ->
+                            "new ${classRef("java.util.ArrayList")}<>()"
+                        else -> ""
+                    }
+                    val passContainer = containerInitExpr.isNotEmpty()
+
+                    // nullcheck +
+                    // "FieldType fieldName = (FieldType)"
+                    if (passContainer) {
+                        methodArgs.add(_name)
+                        !"$Type $_name = "
+                        if (mayBeNull) {
+                            +"null;"
+                            !"if ((flg & $fieldBit) != 0) {"
+                            pushIndent()
+                            +""
+                            !"$_name = "
+                        }
+                        +"$containerInitExpr;"
+                    } else {
+                        !"$Type $_name = "
+                        if (mayBeNull) !"(flg & $fieldBit) == 0 ? null : "
+                        if (ParcelMethodsSuffix == "StrongInterface") {
+                            !"$FieldClass.Stub.asInterface("
+                        } else if (Type !in PRIMITIVE_TYPES + "String" + "Bundle" &&
+                                (!isArray || FieldInnerType !in PRIMITIVE_TYPES + "String") &&
+                                ParcelMethodsSuffix != "Parcelable") {
+                            !"($FieldClass) "
+                        }
+                    }
+
+                    // Determine method args
+                    when {
+                        ParcelMethodsSuffix == "Parcelable" ->
+                            methodArgs += "$FieldClass.class.getClassLoader()"
+                        ParcelMethodsSuffix == "SparseArray" ->
+                            methodArgs += "$FieldInnerClass.class.getClassLoader()"
+                        ParcelMethodsSuffix == "TypedObject" ->
+                            methodArgs += "$FieldClass.CREATOR"
+                        ParcelMethodsSuffix == "TypedArray" ->
+                            methodArgs += "$FieldInnerClass.CREATOR"
+                        ParcelMethodsSuffix == "Map" ->
+                            methodArgs += "${fieldTypeGenegicArgs[1].substringBefore("<")}.class.getClassLoader()"
+                        ParcelMethodsSuffix.startsWith("Parcelable")
+                                || (isList || isArray)
+                                && FieldInnerType !in PRIMITIVE_TYPES + "String" ->
+                            methodArgs += "$FieldInnerClass.class.getClassLoader()"
+                    }
+
+                    // ...in.readFieldType(args...);
+                    when {
+                        ParcelMethodsSuffix == "StrongInterface" -> !"in.readStrongBinder"
+                        isArray -> !"in.create$ParcelMethodsSuffix"
+                        else -> !"in.read$ParcelMethodsSuffix"
+                    }
+                    !"(${methodArgs.joinToString(", ")})"
+                    if (ParcelMethodsSuffix == "StrongInterface") !")"
+                    +";"
+
+                    // Cleanup if passContainer
+                    if (passContainer && mayBeNull) {
+                        popIndent()
+                        rmEmptyLine()
+                        +"\n}"
+                    }
+                }
+            }
+
+            +""
+            fields.forEachApply {
+                !"this."
+                generateSetFrom(_name)
+            }
+
+            generateOnConstructedCallback()
+        }
+    }
+
     if (classAst.fields.none { it.variables[0].nameAsString == "CREATOR" }) {
         val Creator = classRef("android.os.Parcelable.Creator")
 
@@ -477,104 +598,8 @@
             }
 
             +"@Override"
-            +"@SuppressWarnings({\"unchecked\", \"RedundantCast\"})"
             "public $ClassName createFromParcel($Parcel in)" {
-                +"// You can override field unparcelling by defining methods like:"
-                +"// static FieldType unparcelFieldName(Parcel in) { ... }"
-                +""
-                if (booleanFields.isNotEmpty() || nullableFields.isNotEmpty()) {
-                    +"$flagStorageType flg = in.read$FlagStorageType();"
-                }
-                booleanFields.forEachApply {
-                    +"$Type $_name = (flg & $fieldBit) != 0;"
-                }
-                nonBooleanFields.forEachApply {
-
-                    // Handle customized parceling
-                    val customParcellingMethod = "unparcel$NameUpperCamel"
-                    if (hasMethod(customParcellingMethod, Parcel)) {
-                        +"$Type $_name = $customParcellingMethod(in);"
-                    } else if (customParcellingClass != null) {
-                        +"$Type $_name = $sParcelling.unparcel(in);"
-                    } else if (hasAnnotation("@$DataClassEnum")) {
-                        val ordinal = "${_name}Ordinal"
-                        +"int $ordinal = in.readInt();"
-                        +"$Type $_name = $ordinal < 0 ? null : $FieldClass.values()[$ordinal];"
-                    } else {
-                        val methodArgs = mutableListOf<String>()
-
-                        // Create container if any
-                        val containerInitExpr = when {
-                            FieldClass.endsWith("Map") -> "new $LinkedHashMap<>()"
-                            FieldClass == "List" || FieldClass == "ArrayList" ->
-                                "new ${classRef("java.util.ArrayList")}<>()"
-                            else -> ""
-                        }
-                        val passContainer = containerInitExpr.isNotEmpty()
-
-                        // nullcheck +
-                        // "FieldType fieldName = (FieldType)"
-                        if (passContainer) {
-                            methodArgs.add(_name)
-                            !"$Type $_name = "
-                            if (mayBeNull) {
-                                +"null;"
-                                !"if ((flg & $fieldBit) != 0) {"
-                                pushIndent()
-                                +""
-                                !"$_name = "
-                            }
-                            +"$containerInitExpr;"
-                        } else {
-                            !"$Type $_name = "
-                            if (mayBeNull) !"(flg & $fieldBit) == 0 ? null : "
-                            if (ParcelMethodsSuffix == "StrongInterface") {
-                                !"$FieldClass.Stub.asInterface("
-                            } else if (Type !in PRIMITIVE_TYPES + "String" + "Bundle" &&
-                                    (!isArray || FieldInnerType !in PRIMITIVE_TYPES + "String") &&
-                                    ParcelMethodsSuffix != "Parcelable") {
-                                !"($Type) "
-                            }
-                        }
-
-                        // Determine method args
-                        when {
-                            ParcelMethodsSuffix == "Parcelable" ->
-                                methodArgs += "$FieldClass.class.getClassLoader()"
-                            ParcelMethodsSuffix == "TypedObject" ->
-                                methodArgs += "$FieldClass.CREATOR"
-                            ParcelMethodsSuffix == "TypedArray" ->
-                                methodArgs += "$FieldInnerClass.CREATOR"
-                            ParcelMethodsSuffix.startsWith("Parcelable")
-                                    || FieldClass == "Map"
-                                    || (isList || isArray)
-                                    && FieldInnerType !in PRIMITIVE_TYPES + "String" ->
-                                methodArgs += "$FieldInnerClass.class.getClassLoader()"
-                        }
-
-                        // ...in.readFieldType(args...);
-                        when {
-                            ParcelMethodsSuffix == "StrongInterface" -> !"in.readStrongBinder"
-                            isArray -> !"in.create$ParcelMethodsSuffix"
-                            else -> !"in.read$ParcelMethodsSuffix"
-                        }
-                        !"(${methodArgs.joinToString(", ")})"
-                        if (ParcelMethodsSuffix == "StrongInterface") !")"
-                        +";"
-
-                        // Cleanup if passContainer
-                        if (passContainer && mayBeNull) {
-                            popIndent()
-                            rmEmptyLine()
-                            +"\n}"
-                        }
-                    }
-                }
-                "return new $ClassType(" {
-                    fields.forEachTrimmingTrailingComma {
-                        +"$_name,"
-                    }
-                } + ";"
+                +"return new $ClassName(in);"
             }
             rmEmptyLine()
         } + ";"
diff --git a/tools/codegen/src/com/android/codegen/Main.kt b/tools/codegen/src/com/android/codegen/Main.kt
index fa2b41a..039f7b2 100755
--- a/tools/codegen/src/com/android/codegen/Main.kt
+++ b/tools/codegen/src/com/android/codegen/Main.kt
@@ -95,7 +95,13 @@
       you can use with final fields.
 
 Version: $CODEGEN_VERSION
-Questions? Feedback? Contact: eugenesusla@
+
+Questions? Feedback?
+Contact: eugenesusla@
+Bug/feature request: http://go/codegen-bug
+
+Slides: http://go/android-codegen
+In-depth example: http://go/SampleDataClass
 """
 
 fun main(args: Array<String>) {
@@ -132,11 +138,11 @@
         // $GENERATED_WARNING_PREFIX v$CODEGEN_VERSION.
         //
         // DO NOT MODIFY!
+        // CHECKSTYLE:OFF Generated code
         //
         // To regenerate run:
         // $ $cliExecutable ${cliArgs.dropLast(1).joinToString("") { "$it " }}$fileEscaped
-        //
-        // CHECKSTYLE:OFF Generated code
+
         """
 
         if (FeatureFlag.CONST_DEFS()) generateConstDefs()
@@ -146,8 +152,7 @@
             generateConstructor("public")
         } else if (FeatureFlag.BUILDER()
                 || FeatureFlag.COPY_CONSTRUCTOR()
-                || FeatureFlag.WITHERS()
-                || FeatureFlag.PARCELABLE()) {
+                || FeatureFlag.WITHERS()) {
             generateConstructor("/* package-private */")
         }
         if (FeatureFlag.COPY_CONSTRUCTOR()) generateCopyConstructor()
diff --git a/tools/codegen/src/com/android/codegen/SharedConstants.kt b/tools/codegen/src/com/android/codegen/SharedConstants.kt
index b2cc813..47f774f 100644
--- a/tools/codegen/src/com/android/codegen/SharedConstants.kt
+++ b/tools/codegen/src/com/android/codegen/SharedConstants.kt
@@ -1,7 +1,7 @@
 package com.android.codegen
 
 const val CODEGEN_NAME = "codegen"
-const val CODEGEN_VERSION = "1.0.1"
+const val CODEGEN_VERSION = "1.0.7"
 
 const val CANONICAL_BUILDER_CLASS = "Builder"
 const val BASE_BUILDER_CLASS = "BaseBuilder"
diff --git a/tools/processors/staledataclass/src/android/processor/staledataclass/StaleDataclassProcessor.kt b/tools/processors/staledataclass/src/android/processor/staledataclass/StaleDataclassProcessor.kt
index d00def6..7fe21c7 100644
--- a/tools/processors/staledataclass/src/android/processor/staledataclass/StaleDataclassProcessor.kt
+++ b/tools/processors/staledataclass/src/android/processor/staledataclass/StaleDataclassProcessor.kt
@@ -182,6 +182,11 @@
                 .filterNot {
                     it.kind == ElementKind.CLASS
                             || it.kind == ElementKind.CONSTRUCTOR
+                            || it.kind == ElementKind.INTERFACE
+                            || it.kind == ElementKind.ENUM
+                            || it.kind == ElementKind.ANNOTATION_TYPE
+                            || it.kind == ElementKind.INSTANCE_INIT
+                            || it.kind == ElementKind.STATIC_INIT
                             || isGenerated(it)
                 }.map {
                     elemToString(it)
diff --git a/tools/protologtool/Android.bp b/tools/protologtool/Android.bp
index a86c226..d1a86c2 100644
--- a/tools/protologtool/Android.bp
+++ b/tools/protologtool/Android.bp
@@ -1,13 +1,21 @@
+java_library_host {
+    name: "protologtool-lib",
+    srcs: [
+        "src/com/android/protolog/tool/**/*.kt",
+    ],
+    static_libs: [
+        "protolog-common",
+        "javaparser",
+        "protolog-proto",
+        "jsonlib",
+    ],
+}
+
 java_binary_host {
     name: "protologtool",
     manifest: "manifest.txt",
-    srcs: [
-        "src/**/*.kt",
-    ],
     static_libs: [
-        "javaparser",
-        "windowmanager-log-proto",
-        "jsonlib",
+        "protologtool-lib",
     ],
 }
 
@@ -15,13 +23,10 @@
     name: "protologtool-tests",
     test_suites: ["general-tests"],
     srcs: [
-        "src/**/*.kt",
         "tests/**/*.kt",
     ],
     static_libs: [
-        "javaparser",
-        "windowmanager-log-proto",
-        "jsonlib",
+        "protologtool-lib",
         "junit",
         "mockito",
     ],
diff --git a/tools/protologtool/README.md b/tools/protologtool/README.md
index 3439357..ba63957 100644
--- a/tools/protologtool/README.md
+++ b/tools/protologtool/README.md
@@ -8,8 +8,13 @@
 
 ### Code transformation
 
-Command: `process <protolog class path> <protolog implementation class path>
- <protolog groups class path> <config.jar> [<input.java>] <output.srcjar>`
+Command: `protologtool transform-protolog-calls 
+    --protolog-class <protolog class name> 
+    --protolog-impl-class <protolog implementation class name>
+    --loggroups-class <protolog groups class name>
+    --loggroups-jar <config jar path>
+    --output-srcjar <output.srcjar>
+    [<input.java>]`
 
 In this mode ProtoLogTool transforms every ProtoLog logging call in form of:
 ```java
@@ -17,16 +22,20 @@
 ```
 into:
 ```java
-if (GROUP_NAME.isLogToAny()) {
-    ProtoLogImpl.x(ProtoLogGroup.GROUP_NAME, 123456, "Format string %d %s or null", value1, value2);
+if (ProtoLogImpl.isEnabled(GROUP_NAME)) {
+    int protoLogParam0 = value1;
+    String protoLogParam1 = String.valueOf(value2);
+    ProtoLogImpl.x(ProtoLogGroup.GROUP_NAME, 123456, 0b0100, "Format string %d %s or null", protoLogParam0, protoLogParam1);
 }
 ```
 where `ProtoLog`, `ProtoLogImpl` and `ProtoLogGroup` are the classes provided as arguments
  (can be imported, static imported or full path, wildcard imports are not allowed) and, `x` is the
  logging method. The transformation is done on the source level. A hash is generated from the format
- string and log level and inserted after the `ProtoLogGroup` argument. The format string is replaced
+ string, log level and log group name and inserted after the `ProtoLogGroup` argument. After the hash
+ we insert a bitmask specifying the types of logged parameters. The format string is replaced
  by `null` if `ProtoLogGroup.GROUP_NAME.isLogToLogcat()` returns false. If `ProtoLogGroup.GROUP_NAME.isEnabled()`
- returns false the log statement is removed entirely from the resultant code.
+ returns false the log statement is removed entirely from the resultant code. The real generated code is inlined
+ and a number of new line characters is added as to preserve line numbering in file.
 
 Input is provided as a list of java source file names. Transformed source is saved to a single
 source jar file. The ProtoLogGroup class with all dependencies should be provided as a compiled
@@ -34,8 +43,12 @@
 
 ### Viewer config generation
 
-Command: `viewerconf <protolog class path> <protolog implementation class path
-<protolog groups class path> <config.jar> [<input.java>] <output.json>`
+Command: `generate-viewer-config
+    --protolog-class <protolog class name> 
+    --loggroups-class <protolog groups class name>
+    --loggroups-jar <config jar path>
+    --viewer-conf <viewer.json>
+    [<input.java>]`
 
 This command is similar in it's syntax to the previous one, only instead of creating a processed source jar
 it writes a viewer configuration file with following schema:
@@ -46,8 +59,9 @@
     "123456": {
       "message": "Format string %d %s",
       "level": "ERROR",
-      "group": "GROUP_NAME"
-    },
+      "group": "GROUP_NAME",
+      "at": "com\/android\/server\/example\/Class.java"
+    }
   },
   "groups": {
     "GROUP_NAME": {
@@ -60,13 +74,13 @@
 
 ### Binary log viewing
 
-Command: `read <viewer.json> <wm_log.pb>`
+Command: `read-log --viewer-conf <viewer.json> <wm_log.pb>`
 
 Reads the binary ProtoLog log file and outputs a human-readable LogCat-like text log.
 
 ## What is ProtoLog?
 
-ProtoLog is a logging system created for the WindowManager project. It allows both binary and text logging
+ProtoLog is a generic logging system created for the WindowManager project. It allows both binary and text logging
 and is tunable in runtime. It consists of 3 different submodules:
 * logging system built-in the Android app,
 * log viewer for reading binary logs,
@@ -94,8 +108,7 @@
 
 To add a new logging statement just add a new call to ProtoLog.x where x is a log level.
 
-After doing any changes to logging groups or statements you should run `make update-protolog` to update
-viewer configuration saved in the code repository.
+After doing any changes to logging groups or statements you should build the project and follow instructions printed by the tool.
 
 ## How to change settings on device in runtime?
 Use the `adb shell su root cmd window logging` command. To get help just type
diff --git a/tools/protologtool/manifest.txt b/tools/protologtool/manifest.txt
index f5e53c4..cabebd5 100644
--- a/tools/protologtool/manifest.txt
+++ b/tools/protologtool/manifest.txt
@@ -1 +1 @@
-Main-class: com.android.protologtool.ProtoLogTool
+Main-class: com.android.protolog.tool.ProtoLogTool
diff --git a/tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt b/tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt
new file mode 100644
index 0000000..a52c804
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/CodeUtils.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.ast.CompilationUnit
+import com.github.javaparser.ast.ImportDeclaration
+import com.github.javaparser.ast.expr.BinaryExpr
+import com.github.javaparser.ast.expr.Expression
+import com.github.javaparser.ast.expr.StringLiteralExpr
+
+object CodeUtils {
+    /**
+     * Returns a stable hash of a string.
+     * We reimplement String::hashCode() for readability reasons.
+     */
+    fun hash(position: String, messageString: String, logLevel: LogLevel, logGroup: LogGroup): Int {
+        return (position + messageString + logLevel.name + logGroup.name)
+                .map { c -> c.toInt() }.reduce { h, c -> h * 31 + c }
+    }
+
+    fun checkWildcardStaticImported(code: CompilationUnit, className: String, fileName: String) {
+        code.findAll(ImportDeclaration::class.java)
+                .forEach { im ->
+                    if (im.isStatic && im.isAsterisk && im.name.toString() == className) {
+                        throw IllegalImportException("Wildcard static imports of $className " +
+                                "methods are not supported.", ParsingContext(fileName, im))
+                    }
+                }
+    }
+
+    fun isClassImportedOrSamePackage(code: CompilationUnit, className: String): Boolean {
+        val packageName = className.substringBeforeLast('.')
+        return code.packageDeclaration.isPresent &&
+                code.packageDeclaration.get().nameAsString == packageName ||
+                code.findAll(ImportDeclaration::class.java)
+                        .any { im ->
+                            !im.isStatic &&
+                                    ((!im.isAsterisk && im.name.toString() == className) ||
+                                            (im.isAsterisk && im.name.toString() == packageName))
+                        }
+    }
+
+    fun staticallyImportedMethods(code: CompilationUnit, className: String): Set<String> {
+        return code.findAll(ImportDeclaration::class.java)
+                .filter { im ->
+                    im.isStatic &&
+                            im.name.toString().substringBeforeLast('.') == className
+                }
+                .map { im -> im.name.toString().substringAfterLast('.') }.toSet()
+    }
+
+    fun concatMultilineString(expr: Expression, context: ParsingContext): String {
+        return when (expr) {
+            is StringLiteralExpr -> expr.asString()
+            is BinaryExpr -> when {
+                expr.operator == BinaryExpr.Operator.PLUS ->
+                    concatMultilineString(expr.left, context) +
+                            concatMultilineString(expr.right, context)
+                else -> throw InvalidProtoLogCallException(
+                        "expected a string literal " +
+                                "or concatenation of string literals, got: $expr", context)
+            }
+            else -> throw InvalidProtoLogCallException("expected a string literal " +
+                    "or concatenation of string literals, got: $expr", context)
+        }
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/CommandOptions.kt b/tools/protologtool/src/com/android/protolog/tool/CommandOptions.kt
new file mode 100644
index 0000000..3dfa4d2
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/CommandOptions.kt
@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import java.util.regex.Pattern
+
+class CommandOptions(args: Array<String>) {
+    companion object {
+        const val TRANSFORM_CALLS_CMD = "transform-protolog-calls"
+        const val GENERATE_CONFIG_CMD = "generate-viewer-config"
+        const val READ_LOG_CMD = "read-log"
+        private val commands = setOf(TRANSFORM_CALLS_CMD, GENERATE_CONFIG_CMD, READ_LOG_CMD)
+
+        private const val PROTOLOG_CLASS_PARAM = "--protolog-class"
+        private const val PROTOLOGIMPL_CLASS_PARAM = "--protolog-impl-class"
+        private const val PROTOLOGGROUP_CLASS_PARAM = "--loggroups-class"
+        private const val PROTOLOGGROUP_JAR_PARAM = "--loggroups-jar"
+        private const val VIEWER_CONFIG_JSON_PARAM = "--viewer-conf"
+        private const val OUTPUT_SOURCE_JAR_PARAM = "--output-srcjar"
+        private val parameters = setOf(PROTOLOG_CLASS_PARAM, PROTOLOGIMPL_CLASS_PARAM,
+                PROTOLOGGROUP_CLASS_PARAM, PROTOLOGGROUP_JAR_PARAM, VIEWER_CONFIG_JSON_PARAM,
+                OUTPUT_SOURCE_JAR_PARAM)
+
+        val USAGE = """
+            Usage: ${Constants.NAME} <command> [<args>]
+            Available commands:
+
+            $TRANSFORM_CALLS_CMD $PROTOLOG_CLASS_PARAM <class name> $PROTOLOGIMPL_CLASS_PARAM
+                <class name> $PROTOLOGGROUP_CLASS_PARAM <class name> $PROTOLOGGROUP_JAR_PARAM
+                <config.jar> $OUTPUT_SOURCE_JAR_PARAM <output.srcjar> [<input.java>]
+            - processes java files replacing stub calls with logging code.
+
+            $GENERATE_CONFIG_CMD $PROTOLOG_CLASS_PARAM <class name> $PROTOLOGGROUP_CLASS_PARAM
+                <class name> $PROTOLOGGROUP_JAR_PARAM <config.jar> $VIEWER_CONFIG_JSON_PARAM
+                <viewer.json> [<input.java>]
+            - creates viewer config file from given java files.
+
+            $READ_LOG_CMD $VIEWER_CONFIG_JSON_PARAM <viewer.json> <wm_log.pb>
+            - translates a binary log to a readable format.
+        """.trimIndent()
+
+        private fun validateClassName(name: String): String {
+            if (!Pattern.matches("^([a-z]+[A-Za-z0-9]*\\.)+([A-Za-z0-9]+)$", name)) {
+                throw InvalidCommandException("Invalid class name $name")
+            }
+            return name
+        }
+
+        private fun getParam(paramName: String, params: Map<String, String>): String {
+            if (!params.containsKey(paramName)) {
+                throw InvalidCommandException("Param $paramName required")
+            }
+            return params.getValue(paramName)
+        }
+
+        private fun validateNotSpecified(paramName: String, params: Map<String, String>): String {
+            if (params.containsKey(paramName)) {
+                throw InvalidCommandException("Unsupported param $paramName")
+            }
+            return ""
+        }
+
+        private fun validateJarName(name: String): String {
+            if (!name.endsWith(".jar")) {
+                throw InvalidCommandException("Jar file required, got $name instead")
+            }
+            return name
+        }
+
+        private fun validateSrcJarName(name: String): String {
+            if (!name.endsWith(".srcjar")) {
+                throw InvalidCommandException("Source jar file required, got $name instead")
+            }
+            return name
+        }
+
+        private fun validateJSONName(name: String): String {
+            if (!name.endsWith(".json")) {
+                throw InvalidCommandException("Json file required, got $name instead")
+            }
+            return name
+        }
+
+        private fun validateJavaInputList(list: List<String>): List<String> {
+            if (list.isEmpty()) {
+                throw InvalidCommandException("No java source input files")
+            }
+            list.forEach { name ->
+                if (!name.endsWith(".java")) {
+                    throw InvalidCommandException("Not a java source file $name")
+                }
+            }
+            return list
+        }
+
+        private fun validateLogInputList(list: List<String>): String {
+            if (list.isEmpty()) {
+                throw InvalidCommandException("No log input file")
+            }
+            if (list.size > 1) {
+                throw InvalidCommandException("Only one log input file allowed")
+            }
+            return list[0]
+        }
+    }
+
+    val protoLogClassNameArg: String
+    val protoLogGroupsClassNameArg: String
+    val protoLogImplClassNameArg: String
+    val protoLogGroupsJarArg: String
+    val viewerConfigJsonArg: String
+    val outputSourceJarArg: String
+    val logProtofileArg: String
+    val javaSourceArgs: List<String>
+    val command: String
+
+    init {
+        if (args.isEmpty()) {
+            throw InvalidCommandException("No command specified.")
+        }
+        command = args[0]
+        if (command !in commands) {
+            throw InvalidCommandException("Unknown command.")
+        }
+
+        val params: MutableMap<String, String> = mutableMapOf()
+        val inputFiles: MutableList<String> = mutableListOf()
+
+        var idx = 1
+        while (idx < args.size) {
+            if (args[idx].startsWith("--")) {
+                if (idx + 1 >= args.size) {
+                    throw InvalidCommandException("No value for ${args[idx]}")
+                }
+                if (args[idx] !in parameters) {
+                    throw InvalidCommandException("Unknown parameter ${args[idx]}")
+                }
+                if (args[idx + 1].startsWith("--")) {
+                    throw InvalidCommandException("No value for ${args[idx]}")
+                }
+                if (params.containsKey(args[idx])) {
+                    throw InvalidCommandException("Duplicated parameter ${args[idx]}")
+                }
+                params[args[idx]] = args[idx + 1]
+                idx += 2
+            } else {
+                inputFiles.add(args[idx])
+                idx += 1
+            }
+        }
+
+        when (command) {
+            TRANSFORM_CALLS_CMD -> {
+                protoLogClassNameArg = validateClassName(getParam(PROTOLOG_CLASS_PARAM, params))
+                protoLogGroupsClassNameArg = validateClassName(getParam(PROTOLOGGROUP_CLASS_PARAM,
+                        params))
+                protoLogImplClassNameArg = validateClassName(getParam(PROTOLOGIMPL_CLASS_PARAM,
+                        params))
+                protoLogGroupsJarArg = validateJarName(getParam(PROTOLOGGROUP_JAR_PARAM, params))
+                viewerConfigJsonArg = validateNotSpecified(VIEWER_CONFIG_JSON_PARAM, params)
+                outputSourceJarArg = validateSrcJarName(getParam(OUTPUT_SOURCE_JAR_PARAM, params))
+                javaSourceArgs = validateJavaInputList(inputFiles)
+                logProtofileArg = ""
+            }
+            GENERATE_CONFIG_CMD -> {
+                protoLogClassNameArg = validateClassName(getParam(PROTOLOG_CLASS_PARAM, params))
+                protoLogGroupsClassNameArg = validateClassName(getParam(PROTOLOGGROUP_CLASS_PARAM,
+                        params))
+                protoLogImplClassNameArg = validateNotSpecified(PROTOLOGIMPL_CLASS_PARAM, params)
+                protoLogGroupsJarArg = validateJarName(getParam(PROTOLOGGROUP_JAR_PARAM, params))
+                viewerConfigJsonArg = validateJSONName(getParam(VIEWER_CONFIG_JSON_PARAM, params))
+                outputSourceJarArg = validateNotSpecified(OUTPUT_SOURCE_JAR_PARAM, params)
+                javaSourceArgs = validateJavaInputList(inputFiles)
+                logProtofileArg = ""
+            }
+            READ_LOG_CMD -> {
+                protoLogClassNameArg = validateNotSpecified(PROTOLOG_CLASS_PARAM, params)
+                protoLogGroupsClassNameArg = validateNotSpecified(PROTOLOGGROUP_CLASS_PARAM, params)
+                protoLogImplClassNameArg = validateNotSpecified(PROTOLOGIMPL_CLASS_PARAM, params)
+                protoLogGroupsJarArg = validateNotSpecified(PROTOLOGGROUP_JAR_PARAM, params)
+                viewerConfigJsonArg = validateJSONName(getParam(VIEWER_CONFIG_JSON_PARAM, params))
+                outputSourceJarArg = validateNotSpecified(OUTPUT_SOURCE_JAR_PARAM, params)
+                javaSourceArgs = listOf()
+                logProtofileArg = validateLogInputList(inputFiles)
+            }
+            else -> {
+                throw InvalidCommandException("Unknown command.")
+            }
+        }
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/Constants.kt b/tools/protologtool/src/com/android/protolog/tool/Constants.kt
new file mode 100644
index 0000000..aa3e00f
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/Constants.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+object Constants {
+        const val NAME = "protologtool"
+        const val VERSION = "1.0.0"
+        const val IS_ENABLED_METHOD = "isEnabled"
+        const val ENUM_VALUES_METHOD = "values"
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/LogGroup.kt b/tools/protologtool/src/com/android/protolog/tool/LogGroup.kt
new file mode 100644
index 0000000..587f7b9
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/LogGroup.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+data class LogGroup(
+    val name: String,
+    val enabled: Boolean,
+    val textEnabled: Boolean,
+    val tag: String
+)
diff --git a/tools/protologtool/src/com/android/protolog/tool/LogLevel.kt b/tools/protologtool/src/com/android/protolog/tool/LogLevel.kt
new file mode 100644
index 0000000..e88f0f8
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/LogLevel.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.ast.Node
+
+enum class LogLevel {
+    DEBUG, VERBOSE, INFO, WARN, ERROR, WTF;
+
+    companion object {
+        fun getLevelForMethodName(name: String, node: Node, context: ParsingContext): LogLevel {
+            return when (name) {
+                "d" -> DEBUG
+                "v" -> VERBOSE
+                "i" -> INFO
+                "w" -> WARN
+                "e" -> ERROR
+                "wtf" -> WTF
+                else ->
+                    throw InvalidProtoLogCallException("Unknown log level $name in $node", context)
+            }
+        }
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/LogParser.kt b/tools/protologtool/src/com/android/protolog/tool/LogParser.kt
new file mode 100644
index 0000000..a59038f
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/LogParser.kt
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.json.stream.JsonReader
+import com.android.server.protolog.common.InvalidFormatStringException
+import com.android.server.protolog.common.LogDataType
+import com.android.server.protolog.ProtoLogMessage
+import com.android.server.protolog.ProtoLogFileProto
+import java.io.BufferedReader
+import java.io.InputStream
+import java.io.InputStreamReader
+import java.io.PrintStream
+import java.lang.Exception
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+/**
+ * Implements a simple parser/viewer for binary ProtoLog logs.
+ * A binary log is translated into Android "LogCat"-like text log.
+ */
+class LogParser(private val configParser: ViewerConfigParser) {
+    companion object {
+        private val dateFormat = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US)
+        private val magicNumber =
+                ProtoLogFileProto.MagicNumber.MAGIC_NUMBER_H.number.toLong() shl 32 or
+                        ProtoLogFileProto.MagicNumber.MAGIC_NUMBER_L.number.toLong()
+    }
+
+    private fun printTime(time: Long, offset: Long, ps: PrintStream) {
+        ps.print(dateFormat.format(Date(time / 1000000 + offset)) + " ")
+    }
+
+    private fun printFormatted(
+        protoLogMessage: ProtoLogMessage,
+        configEntry: ViewerConfigParser.ConfigEntry,
+        ps: PrintStream
+    ) {
+        val strParmIt = protoLogMessage.strParamsList.iterator()
+        val longParamsIt = protoLogMessage.sint64ParamsList.iterator()
+        val doubleParamsIt = protoLogMessage.doubleParamsList.iterator()
+        val boolParamsIt = protoLogMessage.booleanParamsList.iterator()
+        val args = mutableListOf<Any>()
+        val format = configEntry.messageString
+        val argTypes = LogDataType.parseFormatString(format)
+        try {
+            argTypes.forEach {
+                when (it) {
+                    LogDataType.BOOLEAN -> args.add(boolParamsIt.next())
+                    LogDataType.LONG -> args.add(longParamsIt.next())
+                    LogDataType.DOUBLE -> args.add(doubleParamsIt.next())
+                    LogDataType.STRING -> args.add(strParmIt.next())
+                    null -> throw NullPointerException()
+                }
+            }
+        } catch (ex: NoSuchElementException) {
+            throw InvalidFormatStringException("Invalid format string in config", ex)
+        }
+        if (strParmIt.hasNext() || longParamsIt.hasNext() ||
+                doubleParamsIt.hasNext() || boolParamsIt.hasNext()) {
+            throw RuntimeException("Invalid format string in config - no enough matchers")
+        }
+        val formatted = format.format(*(args.toTypedArray()))
+        ps.print("${configEntry.level} ${configEntry.tag}: $formatted\n")
+    }
+
+    private fun printUnformatted(protoLogMessage: ProtoLogMessage, ps: PrintStream, tag: String) {
+        ps.println("$tag: ${protoLogMessage.messageHash} - ${protoLogMessage.strParamsList}" +
+                " ${protoLogMessage.sint64ParamsList} ${protoLogMessage.doubleParamsList}" +
+                " ${protoLogMessage.booleanParamsList}")
+    }
+
+    fun parse(protoLogInput: InputStream, jsonConfigInput: InputStream, ps: PrintStream) {
+        val jsonReader = JsonReader(BufferedReader(InputStreamReader(jsonConfigInput)))
+        val config = configParser.parseConfig(jsonReader)
+        val protoLog = ProtoLogFileProto.parseFrom(protoLogInput)
+
+        if (protoLog.magicNumber != magicNumber) {
+            throw InvalidInputException("ProtoLog file magic number is invalid.")
+        }
+        if (protoLog.version != Constants.VERSION) {
+            throw InvalidInputException("ProtoLog file version not supported by this tool," +
+                    " log version ${protoLog.version}, viewer version ${Constants.VERSION}")
+        }
+
+        protoLog.logList.forEach { log ->
+            printTime(log.elapsedRealtimeNanos, protoLog.realTimeToElapsedTimeOffsetMillis, ps)
+            if (log.messageHash !in config) {
+                printUnformatted(log, ps, "UNKNOWN")
+            } else {
+                val conf = config.getValue(log.messageHash)
+                try {
+                    printFormatted(log, conf, ps)
+                } catch (ex: Exception) {
+                    printUnformatted(log, ps, "INVALID")
+                }
+            }
+        }
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ParsingContext.kt b/tools/protologtool/src/com/android/protolog/tool/ParsingContext.kt
new file mode 100644
index 0000000..c6aedfc
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/ParsingContext.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.ast.Node
+
+data class ParsingContext(val filePath: String, val lineNumber: Int) {
+    constructor(filePath: String, node: Node)
+            : this(filePath, if (node.range.isPresent) node.range.get().begin.line else -1)
+
+    constructor() : this("", -1)
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ProtoLogCallProcessor.kt b/tools/protologtool/src/com/android/protolog/tool/ProtoLogCallProcessor.kt
new file mode 100644
index 0000000..2181cf6
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/ProtoLogCallProcessor.kt
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.ast.CompilationUnit
+import com.github.javaparser.ast.expr.Expression
+import com.github.javaparser.ast.expr.FieldAccessExpr
+import com.github.javaparser.ast.expr.MethodCallExpr
+import com.github.javaparser.ast.expr.NameExpr
+
+/**
+ * Helper class for visiting all ProtoLog calls.
+ * For every valid call in the given {@code CompilationUnit} a {@code ProtoLogCallVisitor} callback
+ * is executed.
+ */
+open class ProtoLogCallProcessor(
+    private val protoLogClassName: String,
+    private val protoLogGroupClassName: String,
+    private val groupMap: Map<String, LogGroup>
+) {
+    private val protoLogSimpleClassName = protoLogClassName.substringAfterLast('.')
+    private val protoLogGroupSimpleClassName = protoLogGroupClassName.substringAfterLast('.')
+
+    private fun getLogGroupName(
+        expr: Expression,
+        isClassImported: Boolean,
+        staticImports: Set<String>,
+        fileName: String
+    ): String {
+        val context = ParsingContext(fileName, expr)
+        return when (expr) {
+            is NameExpr -> when {
+                expr.nameAsString in staticImports -> expr.nameAsString
+                else ->
+                    throw InvalidProtoLogCallException("Unknown/not imported ProtoLogGroup: $expr",
+                            context)
+            }
+            is FieldAccessExpr -> when {
+                expr.scope.toString() == protoLogGroupClassName
+                        || isClassImported &&
+                        expr.scope.toString() == protoLogGroupSimpleClassName -> expr.nameAsString
+                else ->
+                    throw InvalidProtoLogCallException("Unknown/not imported ProtoLogGroup: $expr",
+                            context)
+            }
+            else -> throw InvalidProtoLogCallException("Invalid group argument " +
+                    "- must be ProtoLogGroup enum member reference: $expr", context)
+        }
+    }
+
+    private fun isProtoCall(
+        call: MethodCallExpr,
+        isLogClassImported: Boolean,
+        staticLogImports: Collection<String>
+    ): Boolean {
+        return call.scope.isPresent && call.scope.get().toString() == protoLogClassName ||
+                isLogClassImported && call.scope.isPresent &&
+                call.scope.get().toString() == protoLogSimpleClassName ||
+                !call.scope.isPresent && staticLogImports.contains(call.name.toString())
+    }
+
+    open fun process(code: CompilationUnit, callVisitor: ProtoLogCallVisitor?, fileName: String):
+            CompilationUnit {
+        CodeUtils.checkWildcardStaticImported(code, protoLogClassName, fileName)
+        CodeUtils.checkWildcardStaticImported(code, protoLogGroupClassName, fileName)
+
+        val isLogClassImported = CodeUtils.isClassImportedOrSamePackage(code, protoLogClassName)
+        val staticLogImports = CodeUtils.staticallyImportedMethods(code, protoLogClassName)
+        val isGroupClassImported = CodeUtils.isClassImportedOrSamePackage(code,
+                protoLogGroupClassName)
+        val staticGroupImports = CodeUtils.staticallyImportedMethods(code, protoLogGroupClassName)
+
+        code.findAll(MethodCallExpr::class.java)
+                .filter { call ->
+                    isProtoCall(call, isLogClassImported, staticLogImports)
+                }.forEach { call ->
+                    val context = ParsingContext(fileName, call)
+                    if (call.arguments.size < 2) {
+                        throw InvalidProtoLogCallException("Method signature does not match " +
+                                "any ProtoLog method: $call", context)
+                    }
+
+                    val messageString = CodeUtils.concatMultilineString(call.getArgument(1),
+                            context)
+                    val groupNameArg = call.getArgument(0)
+                    val groupName =
+                            getLogGroupName(groupNameArg, isGroupClassImported,
+                                    staticGroupImports, fileName)
+                    if (groupName !in groupMap) {
+                        throw InvalidProtoLogCallException("Unknown group argument " +
+                                "- not a ProtoLogGroup enum member: $call", context)
+                    }
+
+                    callVisitor?.processCall(call, messageString, LogLevel.getLevelForMethodName(
+                            call.name.toString(), call, context), groupMap.getValue(groupName))
+                }
+        return code
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ProtoLogCallVisitor.kt b/tools/protologtool/src/com/android/protolog/tool/ProtoLogCallVisitor.kt
new file mode 100644
index 0000000..aa58b69
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/ProtoLogCallVisitor.kt
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.ast.expr.MethodCallExpr
+
+interface ProtoLogCallVisitor {
+    fun processCall(call: MethodCallExpr, messageString: String, level: LogLevel, group: LogGroup)
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ProtoLogGroupReader.kt b/tools/protologtool/src/com/android/protolog/tool/ProtoLogGroupReader.kt
new file mode 100644
index 0000000..75493b6
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/ProtoLogGroupReader.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.protolog.tool.Constants.ENUM_VALUES_METHOD
+import com.android.server.protolog.common.IProtoLogGroup
+import java.io.File
+import java.net.URLClassLoader
+
+class ProtoLogGroupReader {
+    private fun getClassloaderForJar(jarPath: String): ClassLoader {
+        val jarFile = File(jarPath)
+        val url = jarFile.toURI().toURL()
+        return URLClassLoader(arrayOf(url), ProtoLogGroupReader::class.java.classLoader)
+    }
+
+    private fun getEnumValues(clazz: Class<*>): List<IProtoLogGroup> {
+        val valuesMethod = clazz.getMethod(ENUM_VALUES_METHOD)
+        @Suppress("UNCHECKED_CAST")
+        return (valuesMethod.invoke(null) as Array<IProtoLogGroup>).toList()
+    }
+
+    fun loadFromJar(jarPath: String, className: String): Map<String, LogGroup> {
+        try {
+            val classLoader = getClassloaderForJar(jarPath)
+            val clazz = classLoader.loadClass(className)
+            val values = getEnumValues(clazz)
+            return values.map { group ->
+                group.name() to
+                        LogGroup(group.name(), group.isEnabled, group.isLogToLogcat, group.tag)
+            }.toMap()
+        } catch (ex: ReflectiveOperationException) {
+            throw RuntimeException("Unable to load ProtoLogGroup enum class", ex)
+        }
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt b/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
new file mode 100644
index 0000000..70ac0be
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.protolog.tool.CommandOptions.Companion.USAGE
+import com.github.javaparser.ParseProblemException
+import com.github.javaparser.StaticJavaParser
+import com.github.javaparser.ast.CompilationUnit
+import java.io.File
+import java.io.FileInputStream
+import java.io.FileOutputStream
+import java.util.jar.JarOutputStream
+import java.util.zip.ZipEntry
+import kotlin.system.exitProcess
+
+object ProtoLogTool {
+    private fun showHelpAndExit() {
+        println(USAGE)
+        exitProcess(-1)
+    }
+
+    private fun containsProtoLogText(source: String, protoLogClassName: String): Boolean {
+        val protoLogSimpleClassName = protoLogClassName.substringAfterLast('.')
+        return source.contains(protoLogSimpleClassName)
+    }
+
+    private fun processClasses(command: CommandOptions) {
+        val groups = ProtoLogGroupReader()
+                .loadFromJar(command.protoLogGroupsJarArg, command.protoLogGroupsClassNameArg)
+        val out = FileOutputStream(command.outputSourceJarArg)
+        val outJar = JarOutputStream(out)
+        val processor = ProtoLogCallProcessor(command.protoLogClassNameArg,
+                command.protoLogGroupsClassNameArg, groups)
+        val transformer = SourceTransformer(command.protoLogImplClassNameArg, processor)
+
+        command.javaSourceArgs.forEach { path ->
+            val file = File(path)
+            val text = file.readText()
+            val newPath = path
+            val outSrc = try {
+                val code = tryParse(text, path)
+                if (containsProtoLogText(text, command.protoLogClassNameArg)) {
+                    transformer.processClass(text, newPath, code)
+                } else {
+                    text
+                }
+            } catch (ex: ParsingException) {
+                // If we cannot parse this file, skip it (and log why). Compilation will fail
+                // in a subsequent build step.
+                println("\n${ex.message}\n")
+                text
+            }
+            outJar.putNextEntry(ZipEntry(newPath))
+            outJar.write(outSrc.toByteArray())
+            outJar.closeEntry()
+        }
+
+        outJar.close()
+        out.close()
+    }
+
+    private fun tryParse(code: String, fileName: String): CompilationUnit {
+        try {
+            return StaticJavaParser.parse(code)
+        } catch (ex: ParseProblemException) {
+            val problem = ex.problems.first()
+            throw ParsingException("Java parsing erro" +
+                    "r: ${problem.verboseMessage}",
+                    ParsingContext(fileName, problem.location.orElse(null)
+                            ?.begin?.range?.orElse(null)?.begin?.line
+                            ?: 0))
+        }
+    }
+
+    private fun viewerConf(command: CommandOptions) {
+        val groups = ProtoLogGroupReader()
+                .loadFromJar(command.protoLogGroupsJarArg, command.protoLogGroupsClassNameArg)
+        val processor = ProtoLogCallProcessor(command.protoLogClassNameArg,
+                command.protoLogGroupsClassNameArg, groups)
+        val builder = ViewerConfigBuilder(processor)
+        command.javaSourceArgs.forEach { path ->
+            val file = File(path)
+            val text = file.readText()
+            if (containsProtoLogText(text, command.protoLogClassNameArg)) {
+                try {
+                    val code = tryParse(text, path)
+                    val pack = if (code.packageDeclaration.isPresent) code.packageDeclaration
+                            .get().nameAsString else ""
+                    val newPath = pack.replace('.', '/') + '/' + file.name
+                    builder.processClass(code, newPath)
+                } catch (ex: ParsingException) {
+                    // If we cannot parse this file, skip it (and log why). Compilation will fail
+                    // in a subsequent build step.
+                    println("\n${ex.message}\n")
+                }
+            }
+        }
+        val out = FileOutputStream(command.viewerConfigJsonArg)
+        out.write(builder.build().toByteArray())
+        out.close()
+    }
+
+    private fun read(command: CommandOptions) {
+        LogParser(ViewerConfigParser())
+                .parse(FileInputStream(command.logProtofileArg),
+                        FileInputStream(command.viewerConfigJsonArg), System.out)
+    }
+
+    @JvmStatic
+    fun main(args: Array<String>) {
+        try {
+            val command = CommandOptions(args)
+            when (command.command) {
+                CommandOptions.TRANSFORM_CALLS_CMD -> processClasses(command)
+                CommandOptions.GENERATE_CONFIG_CMD -> viewerConf(command)
+                CommandOptions.READ_LOG_CMD -> read(command)
+            }
+        } catch (ex: InvalidCommandException) {
+            println("\n${ex.message}\n")
+            showHelpAndExit()
+        } catch (ex: CodeProcessingException) {
+            println("\n${ex.message}\n")
+            exitProcess(1)
+        }
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt b/tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt
new file mode 100644
index 0000000..00fd038
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/SourceTransformer.kt
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.protolog.tool.Constants.IS_ENABLED_METHOD
+import com.android.server.protolog.common.LogDataType
+import com.github.javaparser.StaticJavaParser
+import com.github.javaparser.ast.CompilationUnit
+import com.github.javaparser.ast.NodeList
+import com.github.javaparser.ast.body.VariableDeclarator
+import com.github.javaparser.ast.expr.BooleanLiteralExpr
+import com.github.javaparser.ast.expr.CastExpr
+import com.github.javaparser.ast.expr.Expression
+import com.github.javaparser.ast.expr.FieldAccessExpr
+import com.github.javaparser.ast.expr.IntegerLiteralExpr
+import com.github.javaparser.ast.expr.MethodCallExpr
+import com.github.javaparser.ast.expr.NameExpr
+import com.github.javaparser.ast.expr.NullLiteralExpr
+import com.github.javaparser.ast.expr.SimpleName
+import com.github.javaparser.ast.expr.TypeExpr
+import com.github.javaparser.ast.expr.VariableDeclarationExpr
+import com.github.javaparser.ast.stmt.BlockStmt
+import com.github.javaparser.ast.stmt.ExpressionStmt
+import com.github.javaparser.ast.stmt.IfStmt
+import com.github.javaparser.ast.type.ArrayType
+import com.github.javaparser.ast.type.ClassOrInterfaceType
+import com.github.javaparser.ast.type.PrimitiveType
+import com.github.javaparser.ast.type.Type
+import com.github.javaparser.printer.PrettyPrinter
+import com.github.javaparser.printer.PrettyPrinterConfiguration
+import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter
+
+class SourceTransformer(
+    protoLogImplClassName: String,
+    private val protoLogCallProcessor: ProtoLogCallProcessor
+) : ProtoLogCallVisitor {
+    override fun processCall(
+        call: MethodCallExpr,
+        messageString: String,
+        level: LogLevel,
+        group: LogGroup
+    ) {
+        // Input format: ProtoLog.e(GROUP, "msg %d", arg)
+        if (!call.parentNode.isPresent) {
+            // Should never happen
+            throw RuntimeException("Unable to process log call $call " +
+                    "- no parent node in AST")
+        }
+        if (call.parentNode.get() !is ExpressionStmt) {
+            // Should never happen
+            throw RuntimeException("Unable to process log call $call " +
+                    "- parent node in AST is not an ExpressionStmt")
+        }
+        val parentStmt = call.parentNode.get() as ExpressionStmt
+        if (!parentStmt.parentNode.isPresent) {
+            // Should never happen
+            throw RuntimeException("Unable to process log call $call " +
+                    "- no grandparent node in AST")
+        }
+        val ifStmt: IfStmt
+        if (group.enabled) {
+            val hash = CodeUtils.hash(fileName, messageString, level, group)
+            val newCall = call.clone()
+            if (!group.textEnabled) {
+                // Remove message string if text logging is not enabled by default.
+                // Out: ProtoLog.e(GROUP, null, arg)
+                newCall.arguments[1].replace(NameExpr("null"))
+            }
+            // Insert message string hash as a second argument.
+            // Out: ProtoLog.e(GROUP, 1234, null, arg)
+            newCall.arguments.add(1, IntegerLiteralExpr(hash))
+            val argTypes = LogDataType.parseFormatString(messageString)
+            val typeMask = LogDataType.logDataTypesToBitMask(argTypes)
+            // Insert bitmap representing which Number parameters are to be considered as
+            // floating point numbers.
+            // Out: ProtoLog.e(GROUP, 1234, 0, null, arg)
+            newCall.arguments.add(2, IntegerLiteralExpr(typeMask))
+            // Replace call to a stub method with an actual implementation.
+            // Out: com.android.server.protolog.ProtoLogImpl.e(GROUP, 1234, null, arg)
+            newCall.setScope(protoLogImplClassNode)
+            // Create a call to ProtoLogImpl.isEnabled(GROUP)
+            // Out: com.android.server.protolog.ProtoLogImpl.isEnabled(GROUP)
+            val isLogEnabled = MethodCallExpr(protoLogImplClassNode, IS_ENABLED_METHOD,
+                NodeList<Expression>(newCall.arguments[0].clone()))
+            if (argTypes.size != call.arguments.size - 2) {
+                throw InvalidProtoLogCallException(
+                        "Number of arguments (${argTypes.size} does not mach format" +
+                                " string in: $call", ParsingContext(fileName, call))
+            }
+            val blockStmt = BlockStmt()
+            if (argTypes.isNotEmpty()) {
+                // Assign every argument to a variable to check its type in compile time
+                // (this is assignment is optimized-out by dex tool, there is no runtime impact)/
+                // Out: long protoLogParam0 = arg
+                argTypes.forEachIndexed { idx, type ->
+                    val varName = "protoLogParam$idx"
+                    val declaration = VariableDeclarator(getASTTypeForDataType(type), varName,
+                            getConversionForType(type)(newCall.arguments[idx + 4].clone()))
+                    blockStmt.addStatement(ExpressionStmt(VariableDeclarationExpr(declaration)))
+                    newCall.setArgument(idx + 4, NameExpr(SimpleName(varName)))
+                }
+            } else {
+                // Assign (Object[])null as the vararg parameter to prevent allocating an empty
+                // object array.
+                val nullArray = CastExpr(ArrayType(objectType), NullLiteralExpr())
+                newCall.addArgument(nullArray)
+            }
+            blockStmt.addStatement(ExpressionStmt(newCall))
+            // Create an IF-statement with the previously created condition.
+            // Out: if (com.android.server.protolog.ProtoLogImpl.isEnabled(GROUP)) {
+            //          long protoLogParam0 = arg;
+            //          com.android.server.protolog.ProtoLogImpl.e(GROUP, 1234, 0, null, protoLogParam0);
+            //      }
+            ifStmt = IfStmt(isLogEnabled, blockStmt, null)
+        } else {
+            // Surround with if (false).
+            val newCall = parentStmt.clone()
+            ifStmt = IfStmt(BooleanLiteralExpr(false), BlockStmt(NodeList(newCall)), null)
+            newCall.setBlockComment(" ${group.name} is disabled ")
+        }
+        // Inline the new statement.
+        val printedIfStmt = inlinePrinter.print(ifStmt)
+        // Append blank lines to preserve line numbering in file (to allow debugging)
+        val newLines = LexicalPreservingPrinter.print(parentStmt).count { c -> c == '\n' }
+        val newStmt = printedIfStmt.substringBeforeLast('}') + ("\n".repeat(newLines)) + '}'
+        // pre-workaround code, see explanation below
+        /*
+        val inlinedIfStmt = StaticJavaParser.parseStatement(newStmt)
+        LexicalPreservingPrinter.setup(inlinedIfStmt)
+        // Replace the original call.
+        if (!parentStmt.replace(inlinedIfStmt)) {
+            // Should never happen
+            throw RuntimeException("Unable to process log call $call " +
+                    "- unable to replace the call.")
+        }
+        */
+        /** Workaround for a bug in JavaParser (AST tree invalid after replacing a node when using
+         * LexicalPreservingPrinter (https://github.com/javaparser/javaparser/issues/2290).
+         * Replace the code below with the one commended-out above one the issue is resolved. */
+        if (!parentStmt.range.isPresent) {
+            // Should never happen
+            throw RuntimeException("Unable to process log call $call " +
+                    "- unable to replace the call.")
+        }
+        val range = parentStmt.range.get()
+        val begin = range.begin.line - 1
+        val oldLines = processedCode.subList(begin, range.end.line)
+        val oldCode = oldLines.joinToString("\n")
+        val newCode = oldCode.replaceRange(
+                offsets[begin] + range.begin.column - 1,
+                oldCode.length - oldLines.lastOrNull()!!.length +
+                        range.end.column + offsets[range.end.line - 1], newStmt)
+        newCode.split("\n").forEachIndexed { idx, line ->
+            offsets[begin + idx] += line.length - processedCode[begin + idx].length
+            processedCode[begin + idx] = line
+        }
+    }
+
+    private val inlinePrinter: PrettyPrinter
+    private val objectType = StaticJavaParser.parseClassOrInterfaceType("Object")
+
+    init {
+        val config = PrettyPrinterConfiguration()
+        config.endOfLineCharacter = " "
+        config.indentSize = 0
+        config.tabWidth = 1
+        inlinePrinter = PrettyPrinter(config)
+    }
+
+    companion object {
+        private val stringType: ClassOrInterfaceType =
+                StaticJavaParser.parseClassOrInterfaceType("String")
+
+        fun getASTTypeForDataType(type: Int): Type {
+            return when (type) {
+                LogDataType.STRING -> stringType.clone()
+                LogDataType.LONG -> PrimitiveType.longType()
+                LogDataType.DOUBLE -> PrimitiveType.doubleType()
+                LogDataType.BOOLEAN -> PrimitiveType.booleanType()
+                else -> {
+                    // Should never happen.
+                    throw RuntimeException("Invalid LogDataType")
+                }
+            }
+        }
+
+        fun getConversionForType(type: Int): (Expression) -> Expression {
+            return when (type) {
+                LogDataType.STRING -> { expr ->
+                    MethodCallExpr(TypeExpr(StaticJavaParser.parseClassOrInterfaceType("String")),
+                            SimpleName("valueOf"), NodeList(expr))
+                }
+                else -> { expr -> expr }
+            }
+        }
+    }
+
+    private val protoLogImplClassNode =
+            StaticJavaParser.parseExpression<FieldAccessExpr>(protoLogImplClassName)
+    private var processedCode: MutableList<String> = mutableListOf()
+    private var offsets: IntArray = IntArray(0)
+    private var fileName: String = ""
+
+    fun processClass(
+        code: String,
+        path: String,
+        compilationUnit: CompilationUnit =
+               StaticJavaParser.parse(code)
+    ): String {
+        fileName = path
+        processedCode = code.split('\n').toMutableList()
+        offsets = IntArray(processedCode.size)
+        LexicalPreservingPrinter.setup(compilationUnit)
+        protoLogCallProcessor.process(compilationUnit, this, fileName)
+        // return LexicalPreservingPrinter.print(compilationUnit)
+        return processedCode.joinToString("\n")
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt b/tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt
new file mode 100644
index 0000000..941455a
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/ViewerConfigBuilder.kt
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.json.stream.JsonWriter
+import com.github.javaparser.ast.CompilationUnit
+import com.android.protolog.tool.Constants.VERSION
+import com.github.javaparser.ast.expr.MethodCallExpr
+import java.io.StringWriter
+
+class ViewerConfigBuilder(
+    private val protoLogCallVisitor: ProtoLogCallProcessor
+) : ProtoLogCallVisitor {
+    override fun processCall(
+        call: MethodCallExpr,
+        messageString: String,
+        level: LogLevel,
+        group: LogGroup
+    ) {
+        if (group.enabled) {
+            val position = fileName
+            val key = CodeUtils.hash(position, messageString, level, group)
+            if (statements.containsKey(key)) {
+                if (statements[key] != LogCall(messageString, level, group, position)) {
+                    throw HashCollisionException(
+                            "Please modify the log message \"$messageString\" " +
+                                    "or \"${statements[key]}\" - their hashes are equal.",
+                            ParsingContext(fileName, call))
+                }
+            } else {
+                groups.add(group)
+                statements[key] = LogCall(messageString, level, group, position)
+                call.range.isPresent
+            }
+        }
+    }
+
+    private val statements: MutableMap<Int, LogCall> = mutableMapOf()
+    private val groups: MutableSet<LogGroup> = mutableSetOf()
+    private var fileName: String = ""
+
+    fun processClass(unit: CompilationUnit, fileName: String) {
+        this.fileName = fileName
+        protoLogCallVisitor.process(unit, this, fileName)
+    }
+
+    fun build(): String {
+        val stringWriter = StringWriter()
+        val writer = JsonWriter(stringWriter)
+        writer.setIndent("  ")
+        writer.beginObject()
+        writer.name("version")
+        writer.value(VERSION)
+        writer.name("messages")
+        writer.beginObject()
+        statements.toSortedMap().forEach { (key, value) ->
+            writer.name(key.toString())
+            writer.beginObject()
+            writer.name("message")
+            writer.value(value.messageString)
+            writer.name("level")
+            writer.value(value.logLevel.name)
+            writer.name("group")
+            writer.value(value.logGroup.name)
+            writer.name("at")
+            writer.value(value.position)
+            writer.endObject()
+        }
+        writer.endObject()
+        writer.name("groups")
+        writer.beginObject()
+        groups.toSortedSet(Comparator { o1, o2 -> o1.name.compareTo(o2.name) }).forEach { group ->
+            writer.name(group.name)
+            writer.beginObject()
+            writer.name("tag")
+            writer.value(group.tag)
+            writer.endObject()
+        }
+        writer.endObject()
+        writer.endObject()
+        stringWriter.buffer.append('\n')
+        return stringWriter.toString()
+    }
+
+    data class LogCall(
+        val messageString: String,
+        val logLevel: LogLevel,
+        val logGroup: LogGroup,
+        val position: String
+    )
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/ViewerConfigParser.kt b/tools/protologtool/src/com/android/protolog/tool/ViewerConfigParser.kt
new file mode 100644
index 0000000..7278db0
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/ViewerConfigParser.kt
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.json.stream.JsonReader
+
+open class ViewerConfigParser {
+    data class MessageEntry(
+        val messageString: String,
+        val level: String,
+        val groupName: String
+    )
+
+    fun parseMessage(jsonReader: JsonReader): MessageEntry {
+        jsonReader.beginObject()
+        var message: String? = null
+        var level: String? = null
+        var groupName: String? = null
+        while (jsonReader.hasNext()) {
+            when (jsonReader.nextName()) {
+                "message" -> message = jsonReader.nextString()
+                "level" -> level = jsonReader.nextString()
+                "group" -> groupName = jsonReader.nextString()
+                else -> jsonReader.skipValue()
+            }
+        }
+        jsonReader.endObject()
+        if (message.isNullOrBlank() || level.isNullOrBlank() || groupName.isNullOrBlank()) {
+            throw InvalidViewerConfigException("Invalid message entry in viewer config")
+        }
+        return MessageEntry(message, level, groupName)
+    }
+
+    data class GroupEntry(val tag: String)
+
+    fun parseGroup(jsonReader: JsonReader): GroupEntry {
+        jsonReader.beginObject()
+        var tag: String? = null
+        while (jsonReader.hasNext()) {
+            when (jsonReader.nextName()) {
+                "tag" -> tag = jsonReader.nextString()
+                else -> jsonReader.skipValue()
+            }
+        }
+        jsonReader.endObject()
+        if (tag.isNullOrBlank()) {
+            throw InvalidViewerConfigException("Invalid group entry in viewer config")
+        }
+        return GroupEntry(tag)
+    }
+
+    fun parseMessages(jsonReader: JsonReader): Map<Int, MessageEntry> {
+        val config: MutableMap<Int, MessageEntry> = mutableMapOf()
+        jsonReader.beginObject()
+        while (jsonReader.hasNext()) {
+            val key = jsonReader.nextName()
+            val hash = key.toIntOrNull()
+                    ?: throw InvalidViewerConfigException("Invalid key in messages viewer config")
+            config[hash] = parseMessage(jsonReader)
+        }
+        jsonReader.endObject()
+        return config
+    }
+
+    fun parseGroups(jsonReader: JsonReader): Map<String, GroupEntry> {
+        val config: MutableMap<String, GroupEntry> = mutableMapOf()
+        jsonReader.beginObject()
+        while (jsonReader.hasNext()) {
+            val key = jsonReader.nextName()
+            config[key] = parseGroup(jsonReader)
+        }
+        jsonReader.endObject()
+        return config
+    }
+
+    data class ConfigEntry(val messageString: String, val level: String, val tag: String)
+
+    open fun parseConfig(jsonReader: JsonReader): Map<Int, ConfigEntry> {
+        var messages: Map<Int, MessageEntry>? = null
+        var groups: Map<String, GroupEntry>? = null
+        var version: String? = null
+
+        jsonReader.beginObject()
+        while (jsonReader.hasNext()) {
+            when (jsonReader.nextName()) {
+                "messages" -> messages = parseMessages(jsonReader)
+                "groups" -> groups = parseGroups(jsonReader)
+                "version" -> version = jsonReader.nextString()
+
+                else -> jsonReader.skipValue()
+            }
+        }
+        jsonReader.endObject()
+        if (messages == null || groups == null || version == null) {
+            throw InvalidViewerConfigException("Invalid config - definitions missing")
+        }
+        if (version != Constants.VERSION) {
+            throw InvalidViewerConfigException("Viewer config version not supported by this tool," +
+                    " config version $version, viewer version ${Constants.VERSION}")
+        }
+        return messages.map { msg ->
+            msg.key to ConfigEntry(
+                    msg.value.messageString, msg.value.level, groups[msg.value.groupName]?.tag
+                    ?: throw InvalidViewerConfigException(
+                            "Group definition missing for ${msg.value.groupName}"))
+        }.toMap()
+    }
+}
diff --git a/tools/protologtool/src/com/android/protolog/tool/exceptions.kt b/tools/protologtool/src/com/android/protolog/tool/exceptions.kt
new file mode 100644
index 0000000..ae00df1
--- /dev/null
+++ b/tools/protologtool/src/com/android/protolog/tool/exceptions.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import java.lang.Exception
+
+open class CodeProcessingException(message: String, context: ParsingContext)
+    : Exception("Code processing error in ${context.filePath}:${context.lineNumber}:\n" +
+        "  $message")
+
+class HashCollisionException(message: String, context: ParsingContext) :
+        CodeProcessingException(message, context)
+
+class IllegalImportException(message: String, context: ParsingContext) :
+        CodeProcessingException("Illegal import: $message", context)
+
+class InvalidProtoLogCallException(message: String, context: ParsingContext)
+    : CodeProcessingException("InvalidProtoLogCall: $message", context)
+
+class ParsingException(message: String, context: ParsingContext)
+    : CodeProcessingException(message, context)
+
+class InvalidViewerConfigException(message: String) : Exception(message)
+
+class InvalidInputException(message: String) : Exception(message)
+
+class InvalidCommandException(message: String) : Exception(message)
diff --git a/tools/protologtool/src/com/android/protologtool/CodeUtils.kt b/tools/protologtool/src/com/android/protologtool/CodeUtils.kt
deleted file mode 100644
index facca62..0000000
--- a/tools/protologtool/src/com/android/protologtool/CodeUtils.kt
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.StaticJavaParser
-import com.github.javaparser.ast.CompilationUnit
-import com.github.javaparser.ast.ImportDeclaration
-import com.github.javaparser.ast.NodeList
-import com.github.javaparser.ast.expr.BinaryExpr
-import com.github.javaparser.ast.expr.Expression
-import com.github.javaparser.ast.expr.MethodCallExpr
-import com.github.javaparser.ast.expr.SimpleName
-import com.github.javaparser.ast.expr.StringLiteralExpr
-import com.github.javaparser.ast.expr.TypeExpr
-import com.github.javaparser.ast.type.PrimitiveType
-import com.github.javaparser.ast.type.Type
-
-object CodeUtils {
-    /**
-     * Returns a stable hash of a string.
-     * We reimplement String::hashCode() for readability reasons.
-     */
-    fun hash(str: String, level: LogLevel): Int {
-        return (level.name + str).map { c -> c.toInt() }.reduce { h, c -> h * 31 + c }
-    }
-
-    fun isWildcardStaticImported(code: CompilationUnit, className: String): Boolean {
-        return code.findAll(ImportDeclaration::class.java)
-                .any { im -> im.isStatic && im.isAsterisk && im.name.toString() == className }
-    }
-
-    fun isClassImportedOrSamePackage(code: CompilationUnit, className: String): Boolean {
-        val packageName = className.substringBeforeLast('.')
-        return code.packageDeclaration.isPresent &&
-                code.packageDeclaration.get().nameAsString == packageName ||
-                code.findAll(ImportDeclaration::class.java)
-                        .any { im ->
-                            !im.isStatic &&
-                                    ((!im.isAsterisk && im.name.toString() == className) ||
-                                            (im.isAsterisk && im.name.toString() == packageName))
-                        }
-    }
-
-    fun staticallyImportedMethods(code: CompilationUnit, className: String): Set<String> {
-        return code.findAll(ImportDeclaration::class.java)
-                .filter { im ->
-                    im.isStatic &&
-                            im.name.toString().substringBeforeLast('.') == className
-                }
-                .map { im -> im.name.toString().substringAfterLast('.') }.toSet()
-    }
-
-    fun concatMultilineString(expr: Expression): String {
-        return when (expr) {
-            is StringLiteralExpr -> expr.asString()
-            is BinaryExpr -> when {
-                expr.operator == BinaryExpr.Operator.PLUS ->
-                    concatMultilineString(expr.left) + concatMultilineString(expr.right)
-                else -> throw InvalidProtoLogCallException(
-                        "messageString must be a string literal " +
-                                "or concatenation of string literals.", expr)
-            }
-            else -> throw InvalidProtoLogCallException("messageString must be a string literal " +
-                    "or concatenation of string literals.", expr)
-        }
-    }
-
-    enum class LogDataTypes(
-        val type: Type,
-        val toType: (Expression) -> Expression = { expr -> expr }
-    ) {
-        // When adding new LogDataType make sure to update {@code logDataTypesToBitMask} accordingly
-        STRING(StaticJavaParser.parseClassOrInterfaceType("String"),
-                { expr ->
-                    MethodCallExpr(TypeExpr(StaticJavaParser.parseClassOrInterfaceType("String")),
-                            SimpleName("valueOf"), NodeList(expr))
-                }),
-        LONG(PrimitiveType.longType()),
-        DOUBLE(PrimitiveType.doubleType()),
-        BOOLEAN(PrimitiveType.booleanType());
-    }
-
-    fun parseFormatString(messageString: String): List<LogDataTypes> {
-        val types = mutableListOf<LogDataTypes>()
-        var i = 0
-        while (i < messageString.length) {
-            if (messageString[i] == '%') {
-                if (i + 1 >= messageString.length) {
-                    throw InvalidFormatStringException("Invalid format string in config")
-                }
-                when (messageString[i + 1]) {
-                    'b' -> types.add(CodeUtils.LogDataTypes.BOOLEAN)
-                    'd', 'o', 'x' -> types.add(CodeUtils.LogDataTypes.LONG)
-                    'f', 'e', 'g' -> types.add(CodeUtils.LogDataTypes.DOUBLE)
-                    's' -> types.add(CodeUtils.LogDataTypes.STRING)
-                    '%' -> {
-                    }
-                    else -> throw InvalidFormatStringException("Invalid format string field" +
-                            " %${messageString[i + 1]}")
-                }
-                i += 2
-            } else {
-                i += 1
-            }
-        }
-        return types
-    }
-
-    fun logDataTypesToBitMask(types: List<LogDataTypes>): Int {
-        if (types.size > 16) {
-            throw InvalidFormatStringException("Too many log call parameters " +
-                    "- max 16 parameters supported")
-        }
-        var mask = 0
-        types.forEachIndexed { idx, type ->
-            val x = LogDataTypes.values().indexOf(type)
-            mask = mask or (x shl (idx * 2))
-        }
-        return mask
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/CommandOptions.kt b/tools/protologtool/src/com/android/protologtool/CommandOptions.kt
deleted file mode 100644
index df49e15..0000000
--- a/tools/protologtool/src/com/android/protologtool/CommandOptions.kt
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import java.util.regex.Pattern
-
-class CommandOptions(args: Array<String>) {
-    companion object {
-        const val TRANSFORM_CALLS_CMD = "transform-protolog-calls"
-        const val GENERATE_CONFIG_CMD = "generate-viewer-config"
-        const val READ_LOG_CMD = "read-log"
-        private val commands = setOf(TRANSFORM_CALLS_CMD, GENERATE_CONFIG_CMD, READ_LOG_CMD)
-
-        private const val PROTOLOG_CLASS_PARAM = "--protolog-class"
-        private const val PROTOLOGIMPL_CLASS_PARAM = "--protolog-impl-class"
-        private const val PROTOLOGGROUP_CLASS_PARAM = "--loggroups-class"
-        private const val PROTOLOGGROUP_JAR_PARAM = "--loggroups-jar"
-        private const val VIEWER_CONFIG_JSON_PARAM = "--viewer-conf"
-        private const val OUTPUT_SOURCE_JAR_PARAM = "--output-srcjar"
-        private val parameters = setOf(PROTOLOG_CLASS_PARAM, PROTOLOGIMPL_CLASS_PARAM,
-                PROTOLOGGROUP_CLASS_PARAM, PROTOLOGGROUP_JAR_PARAM, VIEWER_CONFIG_JSON_PARAM,
-                OUTPUT_SOURCE_JAR_PARAM)
-
-        val USAGE = """
-            Usage: ${Constants.NAME} <command> [<args>]
-            Available commands:
-
-            $TRANSFORM_CALLS_CMD $PROTOLOG_CLASS_PARAM <class name> $PROTOLOGIMPL_CLASS_PARAM
-                <class name> $PROTOLOGGROUP_CLASS_PARAM <class name> $PROTOLOGGROUP_JAR_PARAM
-                <config.jar> $OUTPUT_SOURCE_JAR_PARAM <output.srcjar> [<input.java>]
-            - processes java files replacing stub calls with logging code.
-
-            $GENERATE_CONFIG_CMD $PROTOLOG_CLASS_PARAM <class name> $PROTOLOGGROUP_CLASS_PARAM
-                <class name> $PROTOLOGGROUP_JAR_PARAM <config.jar> $VIEWER_CONFIG_JSON_PARAM
-                <viewer.json> [<input.java>]
-            - creates viewer config file from given java files.
-
-            $READ_LOG_CMD $VIEWER_CONFIG_JSON_PARAM <viewer.json> <wm_log.pb>
-            - translates a binary log to a readable format.
-        """.trimIndent()
-
-        private fun validateClassName(name: String): String {
-            if (!Pattern.matches("^([a-z]+[A-Za-z0-9]*\\.)+([A-Za-z0-9]+)$", name)) {
-                throw InvalidCommandException("Invalid class name $name")
-            }
-            return name
-        }
-
-        private fun getParam(paramName: String, params: Map<String, String>): String {
-            if (!params.containsKey(paramName)) {
-                throw InvalidCommandException("Param $paramName required")
-            }
-            return params.getValue(paramName)
-        }
-
-        private fun validateNotSpecified(paramName: String, params: Map<String, String>): String {
-            if (params.containsKey(paramName)) {
-                throw InvalidCommandException("Unsupported param $paramName")
-            }
-            return ""
-        }
-
-        private fun validateJarName(name: String): String {
-            if (!name.endsWith(".jar")) {
-                throw InvalidCommandException("Jar file required, got $name instead")
-            }
-            return name
-        }
-
-        private fun validateSrcJarName(name: String): String {
-            if (!name.endsWith(".srcjar")) {
-                throw InvalidCommandException("Source jar file required, got $name instead")
-            }
-            return name
-        }
-
-        private fun validateJSONName(name: String): String {
-            if (!name.endsWith(".json")) {
-                throw InvalidCommandException("Json file required, got $name instead")
-            }
-            return name
-        }
-
-        private fun validateJavaInputList(list: List<String>): List<String> {
-            if (list.isEmpty()) {
-                throw InvalidCommandException("No java source input files")
-            }
-            list.forEach { name ->
-                if (!name.endsWith(".java")) {
-                    throw InvalidCommandException("Not a java source file $name")
-                }
-            }
-            return list
-        }
-
-        private fun validateLogInputList(list: List<String>): String {
-            if (list.isEmpty()) {
-                throw InvalidCommandException("No log input file")
-            }
-            if (list.size > 1) {
-                throw InvalidCommandException("Only one log input file allowed")
-            }
-            return list[0]
-        }
-    }
-
-    val protoLogClassNameArg: String
-    val protoLogGroupsClassNameArg: String
-    val protoLogImplClassNameArg: String
-    val protoLogGroupsJarArg: String
-    val viewerConfigJsonArg: String
-    val outputSourceJarArg: String
-    val logProtofileArg: String
-    val javaSourceArgs: List<String>
-    val command: String
-
-    init {
-        if (args.isEmpty()) {
-            throw InvalidCommandException("No command specified.")
-        }
-        command = args[0]
-        if (command !in commands) {
-            throw InvalidCommandException("Unknown command.")
-        }
-
-        val params: MutableMap<String, String> = mutableMapOf()
-        val inputFiles: MutableList<String> = mutableListOf()
-
-        var idx = 1
-        while (idx < args.size) {
-            if (args[idx].startsWith("--")) {
-                if (idx + 1 >= args.size) {
-                    throw InvalidCommandException("No value for ${args[idx]}")
-                }
-                if (args[idx] !in parameters) {
-                    throw InvalidCommandException("Unknown parameter ${args[idx]}")
-                }
-                if (args[idx + 1].startsWith("--")) {
-                    throw InvalidCommandException("No value for ${args[idx]}")
-                }
-                if (params.containsKey(args[idx])) {
-                    throw InvalidCommandException("Duplicated parameter ${args[idx]}")
-                }
-                params[args[idx]] = args[idx + 1]
-                idx += 2
-            } else {
-                inputFiles.add(args[idx])
-                idx += 1
-            }
-        }
-
-        when (command) {
-            TRANSFORM_CALLS_CMD -> {
-                protoLogClassNameArg = validateClassName(getParam(PROTOLOG_CLASS_PARAM, params))
-                protoLogGroupsClassNameArg = validateClassName(getParam(PROTOLOGGROUP_CLASS_PARAM,
-                        params))
-                protoLogImplClassNameArg = validateClassName(getParam(PROTOLOGIMPL_CLASS_PARAM,
-                        params))
-                protoLogGroupsJarArg = validateJarName(getParam(PROTOLOGGROUP_JAR_PARAM, params))
-                viewerConfigJsonArg = validateNotSpecified(VIEWER_CONFIG_JSON_PARAM, params)
-                outputSourceJarArg = validateSrcJarName(getParam(OUTPUT_SOURCE_JAR_PARAM, params))
-                javaSourceArgs = validateJavaInputList(inputFiles)
-                logProtofileArg = ""
-            }
-            GENERATE_CONFIG_CMD -> {
-                protoLogClassNameArg = validateClassName(getParam(PROTOLOG_CLASS_PARAM, params))
-                protoLogGroupsClassNameArg = validateClassName(getParam(PROTOLOGGROUP_CLASS_PARAM,
-                        params))
-                protoLogImplClassNameArg = validateNotSpecified(PROTOLOGIMPL_CLASS_PARAM, params)
-                protoLogGroupsJarArg = validateJarName(getParam(PROTOLOGGROUP_JAR_PARAM, params))
-                viewerConfigJsonArg = validateJSONName(getParam(VIEWER_CONFIG_JSON_PARAM, params))
-                outputSourceJarArg = validateNotSpecified(OUTPUT_SOURCE_JAR_PARAM, params)
-                javaSourceArgs = validateJavaInputList(inputFiles)
-                logProtofileArg = ""
-            }
-            READ_LOG_CMD -> {
-                protoLogClassNameArg = validateNotSpecified(PROTOLOG_CLASS_PARAM, params)
-                protoLogGroupsClassNameArg = validateNotSpecified(PROTOLOGGROUP_CLASS_PARAM, params)
-                protoLogImplClassNameArg = validateNotSpecified(PROTOLOGIMPL_CLASS_PARAM, params)
-                protoLogGroupsJarArg = validateNotSpecified(PROTOLOGGROUP_JAR_PARAM, params)
-                viewerConfigJsonArg = validateJSONName(getParam(VIEWER_CONFIG_JSON_PARAM, params))
-                outputSourceJarArg = validateNotSpecified(OUTPUT_SOURCE_JAR_PARAM, params)
-                javaSourceArgs = listOf()
-                logProtofileArg = validateLogInputList(inputFiles)
-            }
-            else -> {
-                throw InvalidCommandException("Unknown command.")
-            }
-        }
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/Constants.kt b/tools/protologtool/src/com/android/protologtool/Constants.kt
deleted file mode 100644
index 2ccfc4d..0000000
--- a/tools/protologtool/src/com/android/protologtool/Constants.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-object Constants {
-        const val NAME = "protologtool"
-        const val VERSION = "1.0.0"
-        const val IS_ENABLED_METHOD = "isEnabled"
-        const val IS_LOG_TO_LOGCAT_METHOD = "isLogToLogcat"
-        const val IS_LOG_TO_ANY_METHOD = "isLogToAny"
-        const val GET_TAG_METHOD = "getTag"
-        const val ENUM_VALUES_METHOD = "values"
-}
diff --git a/tools/protologtool/src/com/android/protologtool/LogGroup.kt b/tools/protologtool/src/com/android/protologtool/LogGroup.kt
deleted file mode 100644
index 42a37a2..0000000
--- a/tools/protologtool/src/com/android/protologtool/LogGroup.kt
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-data class LogGroup(
-    val name: String,
-    val enabled: Boolean,
-    val textEnabled: Boolean,
-    val tag: String
-)
diff --git a/tools/protologtool/src/com/android/protologtool/LogLevel.kt b/tools/protologtool/src/com/android/protologtool/LogLevel.kt
deleted file mode 100644
index dc29557..0000000
--- a/tools/protologtool/src/com/android/protologtool/LogLevel.kt
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.ast.Node
-
-enum class LogLevel {
-    DEBUG, VERBOSE, INFO, WARN, ERROR, WTF;
-
-    companion object {
-        fun getLevelForMethodName(name: String, node: Node): LogLevel {
-            return when (name) {
-                "d" -> DEBUG
-                "v" -> VERBOSE
-                "i" -> INFO
-                "w" -> WARN
-                "e" -> ERROR
-                "wtf" -> WTF
-                else -> throw InvalidProtoLogCallException("Unknown log level $name", node)
-            }
-        }
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/LogParser.kt b/tools/protologtool/src/com/android/protologtool/LogParser.kt
deleted file mode 100644
index 4d0eb0e..0000000
--- a/tools/protologtool/src/com/android/protologtool/LogParser.kt
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.json.stream.JsonReader
-import com.android.server.wm.ProtoLogMessage
-import com.android.server.wm.WindowManagerLogFileProto
-import java.io.BufferedReader
-import java.io.InputStream
-import java.io.InputStreamReader
-import java.io.PrintStream
-import java.lang.Exception
-import java.text.SimpleDateFormat
-import java.util.Date
-import java.util.Locale
-
-/**
- * Implements a simple parser/viewer for binary ProtoLog logs.
- * A binary log is translated into Android "LogCat"-like text log.
- */
-class LogParser(private val configParser: ViewerConfigParser) {
-    companion object {
-        private val dateFormat = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US)
-        private val magicNumber =
-                WindowManagerLogFileProto.MagicNumber.MAGIC_NUMBER_H.number.toLong() shl 32 or
-                        WindowManagerLogFileProto.MagicNumber.MAGIC_NUMBER_L.number.toLong()
-    }
-
-    private fun printTime(time: Long, offset: Long, ps: PrintStream) {
-        ps.print(dateFormat.format(Date(time / 1000000 + offset)) + " ")
-    }
-
-    private fun printFormatted(
-        protoLogMessage: ProtoLogMessage,
-        configEntry: ViewerConfigParser.ConfigEntry,
-        ps: PrintStream
-    ) {
-        val strParmIt = protoLogMessage.strParamsList.iterator()
-        val longParamsIt = protoLogMessage.sint64ParamsList.iterator()
-        val doubleParamsIt = protoLogMessage.doubleParamsList.iterator()
-        val boolParamsIt = protoLogMessage.booleanParamsList.iterator()
-        val args = mutableListOf<Any>()
-        val format = configEntry.messageString
-        val argTypes = CodeUtils.parseFormatString(format)
-        try {
-            argTypes.forEach {
-                when (it) {
-                    CodeUtils.LogDataTypes.BOOLEAN -> args.add(boolParamsIt.next())
-                    CodeUtils.LogDataTypes.LONG -> args.add(longParamsIt.next())
-                    CodeUtils.LogDataTypes.DOUBLE -> args.add(doubleParamsIt.next())
-                    CodeUtils.LogDataTypes.STRING -> args.add(strParmIt.next())
-                }
-            }
-        } catch (ex: NoSuchElementException) {
-            throw InvalidFormatStringException("Invalid format string in config", ex)
-        }
-        if (strParmIt.hasNext() || longParamsIt.hasNext() ||
-                doubleParamsIt.hasNext() || boolParamsIt.hasNext()) {
-            throw RuntimeException("Invalid format string in config - no enough matchers")
-        }
-        val formatted = format.format(*(args.toTypedArray()))
-        ps.print("${configEntry.level} ${configEntry.tag}: $formatted\n")
-    }
-
-    private fun printUnformatted(protoLogMessage: ProtoLogMessage, ps: PrintStream, tag: String) {
-        ps.println("$tag: ${protoLogMessage.messageHash} - ${protoLogMessage.strParamsList}" +
-                " ${protoLogMessage.sint64ParamsList} ${protoLogMessage.doubleParamsList}" +
-                " ${protoLogMessage.booleanParamsList}")
-    }
-
-    fun parse(protoLogInput: InputStream, jsonConfigInput: InputStream, ps: PrintStream) {
-        val jsonReader = JsonReader(BufferedReader(InputStreamReader(jsonConfigInput)))
-        val config = configParser.parseConfig(jsonReader)
-        val protoLog = WindowManagerLogFileProto.parseFrom(protoLogInput)
-
-        if (protoLog.magicNumber != magicNumber) {
-            throw InvalidInputException("ProtoLog file magic number is invalid.")
-        }
-        if (protoLog.version != Constants.VERSION) {
-            throw InvalidInputException("ProtoLog file version not supported by this tool," +
-                    " log version ${protoLog.version}, viewer version ${Constants.VERSION}")
-        }
-
-        protoLog.logList.forEach { log ->
-            printTime(log.elapsedRealtimeNanos, protoLog.realTimeToElapsedTimeOffsetMillis, ps)
-            if (log.messageHash !in config) {
-                printUnformatted(log, ps, "UNKNOWN")
-            } else {
-                val conf = config.getValue(log.messageHash)
-                try {
-                    printFormatted(log, conf, ps)
-                } catch (ex: Exception) {
-                    printUnformatted(log, ps, "INVALID")
-                }
-            }
-        }
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/ProtoLogCallProcessor.kt b/tools/protologtool/src/com/android/protologtool/ProtoLogCallProcessor.kt
deleted file mode 100644
index 29d8ae5..0000000
--- a/tools/protologtool/src/com/android/protologtool/ProtoLogCallProcessor.kt
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.ast.CompilationUnit
-import com.github.javaparser.ast.expr.Expression
-import com.github.javaparser.ast.expr.FieldAccessExpr
-import com.github.javaparser.ast.expr.MethodCallExpr
-import com.github.javaparser.ast.expr.NameExpr
-
-/**
- * Helper class for visiting all ProtoLog calls.
- * For every valid call in the given {@code CompilationUnit} a {@code ProtoLogCallVisitor} callback
- * is executed.
- */
-open class ProtoLogCallProcessor(
-    private val protoLogClassName: String,
-    private val protoLogGroupClassName: String,
-    private val groupMap: Map<String, LogGroup>
-) {
-    private val protoLogSimpleClassName = protoLogClassName.substringAfterLast('.')
-    private val protoLogGroupSimpleClassName = protoLogGroupClassName.substringAfterLast('.')
-
-    private fun getLogGroupName(
-        expr: Expression,
-        isClassImported: Boolean,
-        staticImports: Set<String>
-    ): String {
-        return when (expr) {
-            is NameExpr -> when {
-                expr.nameAsString in staticImports -> expr.nameAsString
-                else ->
-                    throw InvalidProtoLogCallException("Unknown/not imported ProtoLogGroup", expr)
-            }
-            is FieldAccessExpr -> when {
-                expr.scope.toString() == protoLogGroupClassName
-                        || isClassImported &&
-                        expr.scope.toString() == protoLogGroupSimpleClassName -> expr.nameAsString
-                else ->
-                    throw InvalidProtoLogCallException("Unknown/not imported ProtoLogGroup", expr)
-            }
-            else -> throw InvalidProtoLogCallException("Invalid group argument " +
-                    "- must be ProtoLogGroup enum member reference", expr)
-        }
-    }
-
-    private fun isProtoCall(
-        call: MethodCallExpr,
-        isLogClassImported: Boolean,
-        staticLogImports: Collection<String>
-    ): Boolean {
-        return call.scope.isPresent && call.scope.get().toString() == protoLogClassName ||
-                isLogClassImported && call.scope.isPresent &&
-                call.scope.get().toString() == protoLogSimpleClassName ||
-                !call.scope.isPresent && staticLogImports.contains(call.name.toString())
-    }
-
-    open fun process(code: CompilationUnit, callVisitor: ProtoLogCallVisitor?): CompilationUnit {
-        if (CodeUtils.isWildcardStaticImported(code, protoLogClassName) ||
-                CodeUtils.isWildcardStaticImported(code, protoLogGroupClassName)) {
-            throw IllegalImportException("Wildcard static imports of $protoLogClassName " +
-                    "and $protoLogGroupClassName methods are not supported.")
-        }
-
-        val isLogClassImported = CodeUtils.isClassImportedOrSamePackage(code, protoLogClassName)
-        val staticLogImports = CodeUtils.staticallyImportedMethods(code, protoLogClassName)
-        val isGroupClassImported = CodeUtils.isClassImportedOrSamePackage(code,
-                protoLogGroupClassName)
-        val staticGroupImports = CodeUtils.staticallyImportedMethods(code, protoLogGroupClassName)
-
-        code.findAll(MethodCallExpr::class.java)
-                .filter { call ->
-                    isProtoCall(call, isLogClassImported, staticLogImports)
-                }.forEach { call ->
-                    if (call.arguments.size < 2) {
-                        throw InvalidProtoLogCallException("Method signature does not match " +
-                                "any ProtoLog method.", call)
-                    }
-
-                    val messageString = CodeUtils.concatMultilineString(call.getArgument(1))
-                    val groupNameArg = call.getArgument(0)
-                    val groupName =
-                            getLogGroupName(groupNameArg, isGroupClassImported, staticGroupImports)
-                    if (groupName !in groupMap) {
-                        throw InvalidProtoLogCallException("Unknown group argument " +
-                                "- not a ProtoLogGroup enum member", call)
-                    }
-
-                    callVisitor?.processCall(call, messageString, LogLevel.getLevelForMethodName(
-                            call.name.toString(), call), groupMap.getValue(groupName))
-                }
-        return code
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/ProtoLogCallVisitor.kt b/tools/protologtool/src/com/android/protologtool/ProtoLogCallVisitor.kt
deleted file mode 100644
index 42a75f8..0000000
--- a/tools/protologtool/src/com/android/protologtool/ProtoLogCallVisitor.kt
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.ast.expr.MethodCallExpr
-
-interface ProtoLogCallVisitor {
-    fun processCall(call: MethodCallExpr, messageString: String, level: LogLevel, group: LogGroup)
-}
diff --git a/tools/protologtool/src/com/android/protologtool/ProtoLogGroupReader.kt b/tools/protologtool/src/com/android/protologtool/ProtoLogGroupReader.kt
deleted file mode 100644
index 664c8a6..0000000
--- a/tools/protologtool/src/com/android/protologtool/ProtoLogGroupReader.kt
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.protologtool.Constants.ENUM_VALUES_METHOD
-import com.android.protologtool.Constants.GET_TAG_METHOD
-import com.android.protologtool.Constants.IS_ENABLED_METHOD
-import com.android.protologtool.Constants.IS_LOG_TO_LOGCAT_METHOD
-import java.io.File
-import java.lang.RuntimeException
-import java.net.URLClassLoader
-
-class ProtoLogGroupReader {
-    private fun getClassloaderForJar(jarPath: String): ClassLoader {
-        val jarFile = File(jarPath)
-        val url = jarFile.toURI().toURL()
-        return URLClassLoader(arrayOf(url), ProtoLogGroupReader::class.java.classLoader)
-    }
-
-    private fun getEnumValues(clazz: Class<*>): List<Enum<*>> {
-        val valuesMethod = clazz.getMethod(ENUM_VALUES_METHOD)
-        @Suppress("UNCHECKED_CAST")
-        return (valuesMethod.invoke(null) as Array<Enum<*>>).toList()
-    }
-
-    private fun getLogGroupFromEnumValue(group: Any, clazz: Class<*>): LogGroup {
-        val enabled = clazz.getMethod(IS_ENABLED_METHOD).invoke(group) as Boolean
-        val textEnabled = clazz.getMethod(IS_LOG_TO_LOGCAT_METHOD).invoke(group) as Boolean
-        val tag = clazz.getMethod(GET_TAG_METHOD).invoke(group) as String
-        val name = (group as Enum<*>).name
-        return LogGroup(name, enabled, textEnabled, tag)
-    }
-
-    fun loadFromJar(jarPath: String, className: String): Map<String, LogGroup> {
-        try {
-            val classLoader = getClassloaderForJar(jarPath)
-            val clazz = classLoader.loadClass(className)
-            val values = getEnumValues(clazz)
-            return values.map { group ->
-                group.name to getLogGroupFromEnumValue(group, clazz)
-            }.toMap()
-        } catch (ex: ReflectiveOperationException) {
-            throw RuntimeException("Unable to load ProtoLogGroup enum class", ex)
-        }
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/ProtoLogTool.kt b/tools/protologtool/src/com/android/protologtool/ProtoLogTool.kt
deleted file mode 100644
index 618e4b1..0000000
--- a/tools/protologtool/src/com/android/protologtool/ProtoLogTool.kt
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.protologtool.CommandOptions.Companion.USAGE
-import com.github.javaparser.StaticJavaParser
-import java.io.File
-import java.io.FileInputStream
-import java.io.FileOutputStream
-import java.util.jar.JarOutputStream
-import java.util.zip.ZipEntry
-import kotlin.system.exitProcess
-
-object ProtoLogTool {
-    private fun showHelpAndExit() {
-        println(USAGE)
-        exitProcess(-1)
-    }
-
-    private fun processClasses(command: CommandOptions) {
-        val groups = ProtoLogGroupReader()
-                .loadFromJar(command.protoLogGroupsJarArg, command.protoLogGroupsClassNameArg)
-        val out = FileOutputStream(command.outputSourceJarArg)
-        val outJar = JarOutputStream(out)
-        val processor = ProtoLogCallProcessor(command.protoLogClassNameArg,
-                command.protoLogGroupsClassNameArg, groups)
-        val transformer = SourceTransformer(command.protoLogImplClassNameArg, processor)
-
-        command.javaSourceArgs.forEach { path ->
-            val file = File(path)
-            val text = file.readText()
-            val code = StaticJavaParser.parse(text)
-            val outSrc = transformer.processClass(text, code)
-            val pack = if (code.packageDeclaration.isPresent) code.packageDeclaration
-                    .get().nameAsString else ""
-            val newPath = pack.replace('.', '/') + '/' + file.name
-            outJar.putNextEntry(ZipEntry(newPath))
-            outJar.write(outSrc.toByteArray())
-            outJar.closeEntry()
-        }
-
-        outJar.close()
-        out.close()
-    }
-
-    private fun viewerConf(command: CommandOptions) {
-        val groups = ProtoLogGroupReader()
-                .loadFromJar(command.protoLogGroupsJarArg, command.protoLogGroupsClassNameArg)
-        val processor = ProtoLogCallProcessor(command.protoLogClassNameArg,
-                command.protoLogGroupsClassNameArg, groups)
-        val builder = ViewerConfigBuilder(processor)
-        command.javaSourceArgs.forEach { path ->
-            val file = File(path)
-            builder.processClass(StaticJavaParser.parse(file))
-        }
-        val out = FileOutputStream(command.viewerConfigJsonArg)
-        out.write(builder.build().toByteArray())
-        out.close()
-    }
-
-    fun read(command: CommandOptions) {
-        LogParser(ViewerConfigParser())
-                .parse(FileInputStream(command.logProtofileArg),
-                        FileInputStream(command.viewerConfigJsonArg), System.out)
-    }
-
-    @JvmStatic
-    fun main(args: Array<String>) {
-        try {
-            val command = CommandOptions(args)
-            when (command.command) {
-                CommandOptions.TRANSFORM_CALLS_CMD -> processClasses(command)
-                CommandOptions.GENERATE_CONFIG_CMD -> viewerConf(command)
-                CommandOptions.READ_LOG_CMD -> read(command)
-            }
-        } catch (ex: InvalidCommandException) {
-            println(ex.message)
-            showHelpAndExit()
-        }
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/SourceTransformer.kt b/tools/protologtool/src/com/android/protologtool/SourceTransformer.kt
deleted file mode 100644
index f915ea6..0000000
--- a/tools/protologtool/src/com/android/protologtool/SourceTransformer.kt
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.protologtool.Constants.IS_LOG_TO_ANY_METHOD
-import com.github.javaparser.StaticJavaParser
-import com.github.javaparser.ast.CompilationUnit
-import com.github.javaparser.ast.NodeList
-import com.github.javaparser.ast.body.VariableDeclarator
-import com.github.javaparser.ast.expr.BooleanLiteralExpr
-import com.github.javaparser.ast.expr.CastExpr
-import com.github.javaparser.ast.expr.FieldAccessExpr
-import com.github.javaparser.ast.expr.IntegerLiteralExpr
-import com.github.javaparser.ast.expr.MethodCallExpr
-import com.github.javaparser.ast.expr.NameExpr
-import com.github.javaparser.ast.expr.NullLiteralExpr
-import com.github.javaparser.ast.expr.SimpleName
-import com.github.javaparser.ast.expr.VariableDeclarationExpr
-import com.github.javaparser.ast.stmt.BlockStmt
-import com.github.javaparser.ast.stmt.ExpressionStmt
-import com.github.javaparser.ast.stmt.IfStmt
-import com.github.javaparser.ast.type.ArrayType
-import com.github.javaparser.printer.PrettyPrinter
-import com.github.javaparser.printer.PrettyPrinterConfiguration
-import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter
-
-class SourceTransformer(
-    protoLogImplClassName: String,
-    private val protoLogCallProcessor: ProtoLogCallProcessor
-) : ProtoLogCallVisitor {
-    override fun processCall(
-        call: MethodCallExpr,
-        messageString: String,
-        level: LogLevel,
-        group: LogGroup
-    ) {
-        // Input format: ProtoLog.e(GROUP, "msg %d", arg)
-        if (!call.parentNode.isPresent) {
-            // Should never happen
-            throw RuntimeException("Unable to process log call $call " +
-                    "- no parent node in AST")
-        }
-        if (call.parentNode.get() !is ExpressionStmt) {
-            // Should never happen
-            throw RuntimeException("Unable to process log call $call " +
-                    "- parent node in AST is not an ExpressionStmt")
-        }
-        val parentStmt = call.parentNode.get() as ExpressionStmt
-        if (!parentStmt.parentNode.isPresent) {
-            // Should never happen
-            throw RuntimeException("Unable to process log call $call " +
-                    "- no grandparent node in AST")
-        }
-        val ifStmt: IfStmt
-        if (group.enabled) {
-            val hash = CodeUtils.hash(messageString, level)
-            val newCall = call.clone()
-            if (!group.textEnabled) {
-                // Remove message string if text logging is not enabled by default.
-                // Out: ProtoLog.e(GROUP, null, arg)
-                newCall.arguments[1].replace(NameExpr("null"))
-            }
-            // Insert message string hash as a second argument.
-            // Out: ProtoLog.e(GROUP, 1234, null, arg)
-            newCall.arguments.add(1, IntegerLiteralExpr(hash))
-            val argTypes = CodeUtils.parseFormatString(messageString)
-            val typeMask = CodeUtils.logDataTypesToBitMask(argTypes)
-            // Insert bitmap representing which Number parameters are to be considered as
-            // floating point numbers.
-            // Out: ProtoLog.e(GROUP, 1234, 0, null, arg)
-            newCall.arguments.add(2, IntegerLiteralExpr(typeMask))
-            // Replace call to a stub method with an actual implementation.
-            // Out: com.android.server.wm.ProtoLogImpl.e(GROUP, 1234, null, arg)
-            newCall.setScope(protoLogImplClassNode)
-            // Create a call to GROUP.isLogAny()
-            // Out: GROUP.isLogAny()
-            val isLogAnyExpr = MethodCallExpr(newCall.arguments[0].clone(),
-                    SimpleName(IS_LOG_TO_ANY_METHOD))
-            if (argTypes.size != call.arguments.size - 2) {
-                throw InvalidProtoLogCallException(
-                        "Number of arguments does not mach format string", call)
-            }
-            val blockStmt = BlockStmt()
-            if (argTypes.isNotEmpty()) {
-                // Assign every argument to a variable to check its type in compile time
-                // (this is assignment is optimized-out by dex tool, there is no runtime impact)/
-                // Out: long protoLogParam0 = arg
-                argTypes.forEachIndexed { idx, type ->
-                    val varName = "protoLogParam$idx"
-                    val declaration = VariableDeclarator(type.type, varName,
-                            type.toType(newCall.arguments[idx + 4].clone()))
-                    blockStmt.addStatement(ExpressionStmt(VariableDeclarationExpr(declaration)))
-                    newCall.setArgument(idx + 4, NameExpr(SimpleName(varName)))
-                }
-            } else {
-                // Assign (Object[])null as the vararg parameter to prevent allocating an empty
-                // object array.
-                val nullArray = CastExpr(ArrayType(objectType), NullLiteralExpr())
-                newCall.addArgument(nullArray)
-            }
-            blockStmt.addStatement(ExpressionStmt(newCall))
-            // Create an IF-statement with the previously created condition.
-            // Out: if (GROUP.isLogAny()) {
-            //          long protoLogParam0 = arg;
-            //          com.android.server.wm.ProtoLogImpl.e(GROUP, 1234, 0, null, protoLogParam0);
-            //      }
-            ifStmt = IfStmt(isLogAnyExpr, blockStmt, null)
-        } else {
-            // Surround with if (false).
-            val newCall = parentStmt.clone()
-            ifStmt = IfStmt(BooleanLiteralExpr(false), BlockStmt(NodeList(newCall)), null)
-            newCall.setBlockComment(" ${group.name} is disabled ")
-        }
-        // Inline the new statement.
-        val printedIfStmt = inlinePrinter.print(ifStmt)
-        // Append blank lines to preserve line numbering in file (to allow debugging)
-        val newLines = LexicalPreservingPrinter.print(parentStmt).count { c -> c == '\n' }
-        val newStmt = printedIfStmt.substringBeforeLast('}') + ("\n".repeat(newLines)) + '}'
-        // pre-workaround code, see explanation below
-        /*
-        val inlinedIfStmt = StaticJavaParser.parseStatement(newStmt)
-        LexicalPreservingPrinter.setup(inlinedIfStmt)
-        // Replace the original call.
-        if (!parentStmt.replace(inlinedIfStmt)) {
-            // Should never happen
-            throw RuntimeException("Unable to process log call $call " +
-                    "- unable to replace the call.")
-        }
-        */
-        /** Workaround for a bug in JavaParser (AST tree invalid after replacing a node when using
-         * LexicalPreservingPrinter (https://github.com/javaparser/javaparser/issues/2290).
-         * Replace the code below with the one commended-out above one the issue is resolved. */
-        if (!parentStmt.range.isPresent) {
-            // Should never happen
-            throw RuntimeException("Unable to process log call $call " +
-                    "- unable to replace the call.")
-        }
-        val range = parentStmt.range.get()
-        val begin = range.begin.line - 1
-        val oldLines = processedCode.subList(begin, range.end.line)
-        val oldCode = oldLines.joinToString("\n")
-        val newCode = oldCode.replaceRange(
-                offsets[begin] + range.begin.column - 1,
-                oldCode.length - oldLines.lastOrNull()!!.length +
-                        range.end.column + offsets[range.end.line - 1], newStmt)
-        newCode.split("\n").forEachIndexed { idx, line ->
-            offsets[begin + idx] += line.length - processedCode[begin + idx].length
-            processedCode[begin + idx] = line
-        }
-    }
-
-    private val inlinePrinter: PrettyPrinter
-    private val objectType = StaticJavaParser.parseClassOrInterfaceType("Object")
-
-    init {
-        val config = PrettyPrinterConfiguration()
-        config.endOfLineCharacter = " "
-        config.indentSize = 0
-        config.tabWidth = 1
-        inlinePrinter = PrettyPrinter(config)
-    }
-
-    private val protoLogImplClassNode =
-            StaticJavaParser.parseExpression<FieldAccessExpr>(protoLogImplClassName)
-    private var processedCode: MutableList<String> = mutableListOf()
-    private var offsets: IntArray = IntArray(0)
-
-    fun processClass(
-        code: String,
-        compilationUnit: CompilationUnit =
-               StaticJavaParser.parse(code)
-    ): String {
-        processedCode = code.split('\n').toMutableList()
-        offsets = IntArray(processedCode.size)
-        LexicalPreservingPrinter.setup(compilationUnit)
-        protoLogCallProcessor.process(compilationUnit, this)
-        // return LexicalPreservingPrinter.print(compilationUnit)
-        return processedCode.joinToString("\n")
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/ViewerConfigBuilder.kt b/tools/protologtool/src/com/android/protologtool/ViewerConfigBuilder.kt
deleted file mode 100644
index 8ce9a49..0000000
--- a/tools/protologtool/src/com/android/protologtool/ViewerConfigBuilder.kt
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.json.stream.JsonWriter
-import com.github.javaparser.ast.CompilationUnit
-import com.android.protologtool.Constants.VERSION
-import com.github.javaparser.ast.expr.MethodCallExpr
-import java.io.StringWriter
-
-class ViewerConfigBuilder(
-    private val protoLogCallVisitor: ProtoLogCallProcessor
-) : ProtoLogCallVisitor {
-    override fun processCall(
-        call: MethodCallExpr,
-        messageString: String,
-        level: LogLevel,
-        group: LogGroup
-    ) {
-        if (group.enabled) {
-            val key = CodeUtils.hash(messageString, level)
-            if (statements.containsKey(key)) {
-                if (statements[key] != Triple(messageString, level, group)) {
-                    throw HashCollisionException(
-                            "Please modify the log message \"$messageString\" " +
-                                    "or \"${statements[key]}\" - their hashes are equal.")
-                }
-            } else {
-                groups.add(group)
-                statements[key] = Triple(messageString, level, group)
-            }
-        }
-    }
-
-    private val statements: MutableMap<Int, Triple<String, LogLevel, LogGroup>> = mutableMapOf()
-    private val groups: MutableSet<LogGroup> = mutableSetOf()
-
-    fun processClass(unit: CompilationUnit) {
-        protoLogCallVisitor.process(unit, this)
-    }
-
-    fun build(): String {
-        val stringWriter = StringWriter()
-        val writer = JsonWriter(stringWriter)
-        writer.setIndent("  ")
-        writer.beginObject()
-        writer.name("version")
-        writer.value(VERSION)
-        writer.name("messages")
-        writer.beginObject()
-        statements.toSortedMap().forEach { (key, value) ->
-            writer.name(key.toString())
-            writer.beginObject()
-            writer.name("message")
-            writer.value(value.first)
-            writer.name("level")
-            writer.value(value.second.name)
-            writer.name("group")
-            writer.value(value.third.name)
-            writer.endObject()
-        }
-        writer.endObject()
-        writer.name("groups")
-        writer.beginObject()
-        groups.toSortedSet(Comparator { o1, o2 -> o1.name.compareTo(o2.name) }).forEach { group ->
-            writer.name(group.name)
-            writer.beginObject()
-            writer.name("tag")
-            writer.value(group.tag)
-            writer.endObject()
-        }
-        writer.endObject()
-        writer.endObject()
-        stringWriter.buffer.append('\n')
-        return stringWriter.toString()
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/ViewerConfigParser.kt b/tools/protologtool/src/com/android/protologtool/ViewerConfigParser.kt
deleted file mode 100644
index 69cf92d..0000000
--- a/tools/protologtool/src/com/android/protologtool/ViewerConfigParser.kt
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.json.stream.JsonReader
-
-open class ViewerConfigParser {
-    data class MessageEntry(
-        val messageString: String,
-        val level: String,
-        val groupName: String
-    )
-
-    fun parseMessage(jsonReader: JsonReader): MessageEntry {
-        jsonReader.beginObject()
-        var message: String? = null
-        var level: String? = null
-        var groupName: String? = null
-        while (jsonReader.hasNext()) {
-            val key = jsonReader.nextName()
-            when (key) {
-                "message" -> message = jsonReader.nextString()
-                "level" -> level = jsonReader.nextString()
-                "group" -> groupName = jsonReader.nextString()
-                else -> jsonReader.skipValue()
-            }
-        }
-        jsonReader.endObject()
-        if (message.isNullOrBlank() || level.isNullOrBlank() || groupName.isNullOrBlank()) {
-            throw InvalidViewerConfigException("Invalid message entry in viewer config")
-        }
-        return MessageEntry(message, level, groupName)
-    }
-
-    data class GroupEntry(val tag: String)
-
-    fun parseGroup(jsonReader: JsonReader): GroupEntry {
-        jsonReader.beginObject()
-        var tag: String? = null
-        while (jsonReader.hasNext()) {
-            val key = jsonReader.nextName()
-            when (key) {
-                "tag" -> tag = jsonReader.nextString()
-                else -> jsonReader.skipValue()
-            }
-        }
-        jsonReader.endObject()
-        if (tag.isNullOrBlank()) {
-            throw InvalidViewerConfigException("Invalid group entry in viewer config")
-        }
-        return GroupEntry(tag)
-    }
-
-    fun parseMessages(jsonReader: JsonReader): Map<Int, MessageEntry> {
-        val config: MutableMap<Int, MessageEntry> = mutableMapOf()
-        jsonReader.beginObject()
-        while (jsonReader.hasNext()) {
-            val key = jsonReader.nextName()
-            val hash = key.toIntOrNull()
-                    ?: throw InvalidViewerConfigException("Invalid key in messages viewer config")
-            config[hash] = parseMessage(jsonReader)
-        }
-        jsonReader.endObject()
-        return config
-    }
-
-    fun parseGroups(jsonReader: JsonReader): Map<String, GroupEntry> {
-        val config: MutableMap<String, GroupEntry> = mutableMapOf()
-        jsonReader.beginObject()
-        while (jsonReader.hasNext()) {
-            val key = jsonReader.nextName()
-            config[key] = parseGroup(jsonReader)
-        }
-        jsonReader.endObject()
-        return config
-    }
-
-    data class ConfigEntry(val messageString: String, val level: String, val tag: String)
-
-    open fun parseConfig(jsonReader: JsonReader): Map<Int, ConfigEntry> {
-        var messages: Map<Int, MessageEntry>? = null
-        var groups: Map<String, GroupEntry>? = null
-        var version: String? = null
-
-        jsonReader.beginObject()
-        while (jsonReader.hasNext()) {
-            val key = jsonReader.nextName()
-            when (key) {
-                "messages" -> messages = parseMessages(jsonReader)
-                "groups" -> groups = parseGroups(jsonReader)
-                "version" -> version = jsonReader.nextString()
-
-                else -> jsonReader.skipValue()
-            }
-        }
-        jsonReader.endObject()
-        if (messages == null || groups == null || version == null) {
-            throw InvalidViewerConfigException("Invalid config - definitions missing")
-        }
-        if (version != Constants.VERSION) {
-            throw InvalidViewerConfigException("Viewer config version not supported by this tool," +
-                    " config version $version, viewer version ${Constants.VERSION}")
-        }
-        return messages.map { msg ->
-            msg.key to ConfigEntry(
-                    msg.value.messageString, msg.value.level, groups[msg.value.groupName]?.tag
-                    ?: throw InvalidViewerConfigException(
-                            "Group definition missing for ${msg.value.groupName}"))
-        }.toMap()
-    }
-}
diff --git a/tools/protologtool/src/com/android/protologtool/exceptions.kt b/tools/protologtool/src/com/android/protologtool/exceptions.kt
deleted file mode 100644
index 2199785..0000000
--- a/tools/protologtool/src/com/android/protologtool/exceptions.kt
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.ast.Node
-import java.lang.Exception
-import java.lang.RuntimeException
-
-class HashCollisionException(message: String) : RuntimeException(message)
-
-class IllegalImportException(message: String) : Exception(message)
-
-class InvalidProtoLogCallException(message: String, node: Node)
-    : RuntimeException("$message\nAt: $node")
-
-class InvalidViewerConfigException : Exception {
-    constructor(message: String) : super(message)
-
-    constructor(message: String, ex: Exception) : super(message, ex)
-}
-
-class InvalidFormatStringException : Exception {
-    constructor(message: String) : super(message)
-
-    constructor(message: String, ex: Exception) : super(message, ex)
-}
-
-class InvalidInputException(message: String) : Exception(message)
-
-class InvalidCommandException(message: String) : Exception(message)
diff --git a/tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt b/tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt
new file mode 100644
index 0000000..b916f8f
--- /dev/null
+++ b/tools/protologtool/tests/com/android/protolog/tool/CodeUtilsTest.kt
@@ -0,0 +1,182 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.StaticJavaParser
+import com.github.javaparser.ast.expr.BinaryExpr
+import com.github.javaparser.ast.expr.StringLiteralExpr
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class CodeUtilsTest {
+    @Test
+    fun hash() {
+        assertEquals(-1259556708, CodeUtils.hash("Test.java:50", "test",
+                LogLevel.DEBUG, LogGroup("test", true, true, "TAG")))
+    }
+
+    @Test
+    fun hash_changeLocation() {
+        assertEquals(15793504, CodeUtils.hash("Test.java:10", "test2",
+                LogLevel.DEBUG, LogGroup("test", true, true, "TAG")))
+    }
+
+    @Test
+    fun hash_changeLevel() {
+        assertEquals(-731772463, CodeUtils.hash("Test.java:50", "test",
+                LogLevel.ERROR, LogGroup("test", true, true, "TAG")))
+    }
+
+    @Test
+    fun hash_changeMessage() {
+        assertEquals(-2026343204, CodeUtils.hash("Test.java:50", "test2",
+                LogLevel.DEBUG, LogGroup("test", true, true, "TAG")))
+    }
+
+    @Test
+    fun hash_changeGroup() {
+        assertEquals(1607870166, CodeUtils.hash("Test.java:50", "test2",
+                LogLevel.DEBUG, LogGroup("test2", true, true, "TAG")))
+    }
+
+    @Test(expected = IllegalImportException::class)
+    fun checkWildcardStaticImported_true() {
+        val code = """package org.example.test;
+            import static org.example.Test.*;
+        """
+        CodeUtils.checkWildcardStaticImported(
+                StaticJavaParser.parse(code), "org.example.Test", "")
+    }
+
+    @Test
+    fun checkWildcardStaticImported_notStatic() {
+        val code = """package org.example.test;
+            import org.example.Test.*;
+        """
+        CodeUtils.checkWildcardStaticImported(
+                StaticJavaParser.parse(code), "org.example.Test", "")
+    }
+
+    @Test
+    fun checkWildcardStaticImported_differentClass() {
+        val code = """package org.example.test;
+            import static org.example.Test2.*;
+        """
+        CodeUtils.checkWildcardStaticImported(
+                StaticJavaParser.parse(code), "org.example.Test", "")
+    }
+
+    @Test
+    fun checkWildcardStaticImported_notWildcard() {
+        val code = """package org.example.test;
+            import org.example.Test.test;
+        """
+        CodeUtils.checkWildcardStaticImported(
+                StaticJavaParser.parse(code), "org.example.Test", "")
+    }
+
+    @Test
+    fun isClassImportedOrSamePackage_imported() {
+        val code = """package org.example.test;
+            import org.example.Test;
+        """
+        assertTrue(CodeUtils.isClassImportedOrSamePackage(
+                StaticJavaParser.parse(code), "org.example.Test"))
+    }
+
+    @Test
+    fun isClassImportedOrSamePackage_samePackage() {
+        val code = """package org.example.test;
+        """
+        assertTrue(CodeUtils.isClassImportedOrSamePackage(
+                StaticJavaParser.parse(code), "org.example.test.Test"))
+    }
+
+    @Test
+    fun isClassImportedOrSamePackage_false() {
+        val code = """package org.example.test;
+            import org.example.Test;
+        """
+        assertFalse(CodeUtils.isClassImportedOrSamePackage(
+                StaticJavaParser.parse(code), "org.example.Test2"))
+    }
+
+    @Test
+    fun staticallyImportedMethods_ab() {
+        val code = """
+            import static org.example.Test.a;
+            import static org.example.Test.b;
+        """
+        val imported = CodeUtils.staticallyImportedMethods(StaticJavaParser.parse(code),
+                "org.example.Test")
+        assertTrue(imported.containsAll(listOf("a", "b")))
+        assertEquals(2, imported.size)
+    }
+
+    @Test
+    fun staticallyImportedMethods_differentClass() {
+        val code = """
+            import static org.example.Test.a;
+            import static org.example.Test2.b;
+        """
+        val imported = CodeUtils.staticallyImportedMethods(StaticJavaParser.parse(code),
+                "org.example.Test")
+        assertTrue(imported.containsAll(listOf("a")))
+        assertEquals(1, imported.size)
+    }
+
+    @Test
+    fun staticallyImportedMethods_notStatic() {
+        val code = """
+            import static org.example.Test.a;
+            import org.example.Test.b;
+        """
+        val imported = CodeUtils.staticallyImportedMethods(StaticJavaParser.parse(code),
+                "org.example.Test")
+        assertTrue(imported.containsAll(listOf("a")))
+        assertEquals(1, imported.size)
+    }
+
+    @Test
+    fun concatMultilineString_single() {
+        val str = StringLiteralExpr("test")
+        val out = CodeUtils.concatMultilineString(str, ParsingContext())
+        assertEquals("test", out)
+    }
+
+    @Test
+    fun concatMultilineString_double() {
+        val str = """
+            "test" + "abc"
+        """
+        val code = StaticJavaParser.parseExpression<BinaryExpr>(str)
+        val out = CodeUtils.concatMultilineString(code, ParsingContext())
+        assertEquals("testabc", out)
+    }
+
+    @Test
+    fun concatMultilineString_multiple() {
+        val str = """
+            "test" + "abc" + "1234" + "test"
+        """
+        val code = StaticJavaParser.parseExpression<BinaryExpr>(str)
+        val out = CodeUtils.concatMultilineString(code, ParsingContext())
+        assertEquals("testabc1234test", out)
+    }
+}
diff --git a/tools/protologtool/tests/com/android/protolog/tool/CommandOptionsTest.kt b/tools/protologtool/tests/com/android/protolog/tool/CommandOptionsTest.kt
new file mode 100644
index 0000000..615712e
--- /dev/null
+++ b/tools/protologtool/tests/com/android/protolog/tool/CommandOptionsTest.kt
@@ -0,0 +1,250 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class CommandOptionsTest {
+    companion object {
+        val TEST_JAVA_SRC = listOf(
+                "frameworks/base/services/core/java/com/android/server/wm/" +
+                        "AccessibilityController.java",
+                "frameworks/base/services/core/java/com/android/server/wm/ActivityDisplay.java",
+                "frameworks/base/services/core/java/com/android/server/wm/" +
+                        "ActivityMetricsLaunchObserver.java"
+        )
+        private const val TEST_PROTOLOG_CLASS = "com.android.server.wm.ProtoLog"
+        private const val TEST_PROTOLOGIMPL_CLASS = "com.android.server.wm.ProtoLogImpl"
+        private const val TEST_PROTOLOGGROUP_CLASS = "com.android.server.wm.ProtoLogGroup"
+        private const val TEST_PROTOLOGGROUP_JAR = "out/soong/.intermediates/frameworks/base/" +
+                "services/core/services.core.wm.protologgroups/android_common/javac/" +
+                "services.core.wm.protologgroups.jar"
+        private const val TEST_SRC_JAR = "out/soong/.temp/sbox175955373/" +
+                "services.core.wm.protolog.srcjar"
+        private const val TEST_VIEWER_JSON = "out/soong/.temp/sbox175955373/" +
+                "services.core.wm.protolog.json"
+        private const val TEST_LOG = "./test_log.pb"
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun noCommand() {
+        CommandOptions(arrayOf())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun invalidCommand() {
+        val testLine = "invalid"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test
+    fun transformClasses() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        val cmd = CommandOptions(testLine.split(' ').toTypedArray())
+        assertEquals(CommandOptions.TRANSFORM_CALLS_CMD, cmd.command)
+        assertEquals(TEST_PROTOLOG_CLASS, cmd.protoLogClassNameArg)
+        assertEquals(TEST_PROTOLOGIMPL_CLASS, cmd.protoLogImplClassNameArg)
+        assertEquals(TEST_PROTOLOGGROUP_CLASS, cmd.protoLogGroupsClassNameArg)
+        assertEquals(TEST_PROTOLOGGROUP_JAR, cmd.protoLogGroupsJarArg)
+        assertEquals(TEST_SRC_JAR, cmd.outputSourceJarArg)
+        assertEquals(TEST_JAVA_SRC, cmd.javaSourceArgs)
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_noProtoLogClass() {
+        val testLine = "transform-protolog-calls " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_noProtoLogImplClass() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_noProtoLogGroupClass() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_noProtoLogGroupJar() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_noOutJar() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                TEST_JAVA_SRC.joinToString(" ")
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_noJavaInput() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_invalidProtoLogClass() {
+        val testLine = "transform-protolog-calls --protolog-class invalid " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_invalidProtoLogImplClass() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class invalid " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_invalidProtoLogGroupClass() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class invalid " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_invalidProtoLogGroupJar() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar invalid.txt " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_invalidOutJar() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar invalid.db ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_invalidJavaInput() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR invalid.py"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_unknownParam() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--unknown test --protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun transformClasses_noValue() {
+        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--protolog-impl-class " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test
+    fun generateConfig() {
+        val testLine = "generate-viewer-config --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--viewer-conf $TEST_VIEWER_JSON ${TEST_JAVA_SRC.joinToString(" ")}"
+        val cmd = CommandOptions(testLine.split(' ').toTypedArray())
+        assertEquals(CommandOptions.GENERATE_CONFIG_CMD, cmd.command)
+        assertEquals(TEST_PROTOLOG_CLASS, cmd.protoLogClassNameArg)
+        assertEquals(TEST_PROTOLOGGROUP_CLASS, cmd.protoLogGroupsClassNameArg)
+        assertEquals(TEST_PROTOLOGGROUP_JAR, cmd.protoLogGroupsJarArg)
+        assertEquals(TEST_VIEWER_JSON, cmd.viewerConfigJsonArg)
+        assertEquals(TEST_JAVA_SRC, cmd.javaSourceArgs)
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun generateConfig_noViewerConfig() {
+        val testLine = "generate-viewer-config --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                TEST_JAVA_SRC.joinToString(" ")
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test(expected = InvalidCommandException::class)
+    fun generateConfig_invalidViewerConfig() {
+        val testLine = "generate-viewer-config --protolog-class $TEST_PROTOLOG_CLASS " +
+                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
+                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
+                "--viewer-conf invalid.yaml ${TEST_JAVA_SRC.joinToString(" ")}"
+        CommandOptions(testLine.split(' ').toTypedArray())
+    }
+
+    @Test
+    fun readLog() {
+        val testLine = "read-log --viewer-conf $TEST_VIEWER_JSON $TEST_LOG"
+        val cmd = CommandOptions(testLine.split(' ').toTypedArray())
+        assertEquals(CommandOptions.READ_LOG_CMD, cmd.command)
+        assertEquals(TEST_VIEWER_JSON, cmd.viewerConfigJsonArg)
+        assertEquals(TEST_LOG, cmd.logProtofileArg)
+    }
+}
diff --git a/tools/protologtool/tests/com/android/protolog/tool/LogParserTest.kt b/tools/protologtool/tests/com/android/protolog/tool/LogParserTest.kt
new file mode 100644
index 0000000..04a3bfa
--- /dev/null
+++ b/tools/protologtool/tests/com/android/protolog/tool/LogParserTest.kt
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.json.stream.JsonReader
+import com.android.server.protolog.ProtoLogMessage
+import com.android.server.protolog.ProtoLogFileProto
+import org.junit.Assert.assertEquals
+import org.junit.Before
+import org.junit.Test
+import org.mockito.Mockito
+import org.mockito.Mockito.mock
+import java.io.ByteArrayOutputStream
+import java.io.InputStream
+import java.io.OutputStream
+import java.io.PrintStream
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+class LogParserTest {
+    private val configParser: ViewerConfigParser = mock(ViewerConfigParser::class.java)
+    private val parser = LogParser(configParser)
+    private var config: MutableMap<Int, ViewerConfigParser.ConfigEntry> = mutableMapOf()
+    private var outStream: OutputStream = ByteArrayOutputStream()
+    private var printStream: PrintStream = PrintStream(outStream)
+    private val dateFormat = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US)
+
+    @Before
+    fun init() {
+        Mockito.`when`(configParser.parseConfig(any(JsonReader::class.java))).thenReturn(config)
+    }
+
+    private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
+
+    private fun getConfigDummyStream(): InputStream {
+        return "".byteInputStream()
+    }
+
+    private fun buildProtoInput(logBuilder: ProtoLogFileProto.Builder): InputStream {
+        logBuilder.setVersion(Constants.VERSION)
+        logBuilder.magicNumber =
+                ProtoLogFileProto.MagicNumber.MAGIC_NUMBER_H.number.toLong() shl 32 or
+                        ProtoLogFileProto.MagicNumber.MAGIC_NUMBER_L.number.toLong()
+        return logBuilder.build().toByteArray().inputStream()
+    }
+
+    private fun testDate(timeMS: Long): String {
+        return dateFormat.format(Date(timeMS))
+    }
+
+    @Test
+    fun parse() {
+        config[70933285] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b",
+                "ERROR", "WindowManager")
+
+        val logBuilder = ProtoLogFileProto.newBuilder()
+        val logMessageBuilder = ProtoLogMessage.newBuilder()
+        logMessageBuilder
+                .setMessageHash(70933285)
+                .setElapsedRealtimeNanos(0)
+                .addBooleanParams(true)
+        logBuilder.addLog(logMessageBuilder.build())
+
+        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
+
+        assertEquals("${testDate(0)} ERROR WindowManager: Test completed successfully: true\n",
+                outStream.toString())
+    }
+
+    @Test
+    fun parse_formatting() {
+        config[123] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b %d %% %o" +
+                " %x %e %g %s %f", "ERROR", "WindowManager")
+
+        val logBuilder = ProtoLogFileProto.newBuilder()
+        val logMessageBuilder = ProtoLogMessage.newBuilder()
+        logMessageBuilder
+                .setMessageHash(123)
+                .setElapsedRealtimeNanos(0)
+                .addBooleanParams(true)
+                .addAllSint64Params(listOf(1000, 20000, 300000))
+                .addAllDoubleParams(listOf(0.1, 0.00001, 1000.1))
+                .addStrParams("test")
+        logBuilder.addLog(logMessageBuilder.build())
+
+        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
+
+        assertEquals("${testDate(0)} ERROR WindowManager: Test completed successfully: " +
+                "true 1000 % 47040 493e0 1.000000e-01 1.00000e-05 test 1000.100000\n",
+                outStream.toString())
+    }
+
+    @Test
+    fun parse_invalidParamsTooMany() {
+        config[123] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b %d %% %o",
+                "ERROR", "WindowManager")
+
+        val logBuilder = ProtoLogFileProto.newBuilder()
+        val logMessageBuilder = ProtoLogMessage.newBuilder()
+        logMessageBuilder
+                .setMessageHash(123)
+                .setElapsedRealtimeNanos(0)
+                .addBooleanParams(true)
+                .addAllSint64Params(listOf(1000, 20000, 300000))
+                .addAllDoubleParams(listOf(0.1, 0.00001, 1000.1))
+                .addStrParams("test")
+        logBuilder.addLog(logMessageBuilder.build())
+
+        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
+
+        assertEquals("${testDate(0)} INVALID: 123 - [test] [1000, 20000, 300000] " +
+                "[0.1, 1.0E-5, 1000.1] [true]\n", outStream.toString())
+    }
+
+    @Test
+    fun parse_invalidParamsNotEnough() {
+        config[123] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b %d %% %o" +
+                " %x %e %g %s %f", "ERROR", "WindowManager")
+
+        val logBuilder = ProtoLogFileProto.newBuilder()
+        val logMessageBuilder = ProtoLogMessage.newBuilder()
+        logMessageBuilder
+                .setMessageHash(123)
+                .setElapsedRealtimeNanos(0)
+                .addBooleanParams(true)
+                .addStrParams("test")
+        logBuilder.addLog(logMessageBuilder.build())
+
+        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
+
+        assertEquals("${testDate(0)} INVALID: 123 - [test] [] [] [true]\n",
+                outStream.toString())
+    }
+
+    @Test(expected = InvalidInputException::class)
+    fun parse_invalidMagicNumber() {
+        val logBuilder = ProtoLogFileProto.newBuilder()
+        logBuilder.setVersion(Constants.VERSION)
+        logBuilder.magicNumber = 0
+        val stream = logBuilder.build().toByteArray().inputStream()
+
+        parser.parse(stream, getConfigDummyStream(), printStream)
+    }
+
+    @Test(expected = InvalidInputException::class)
+    fun parse_invalidVersion() {
+        val logBuilder = ProtoLogFileProto.newBuilder()
+        logBuilder.setVersion("invalid")
+        logBuilder.magicNumber =
+                ProtoLogFileProto.MagicNumber.MAGIC_NUMBER_H.number.toLong() shl 32 or
+                        ProtoLogFileProto.MagicNumber.MAGIC_NUMBER_L.number.toLong()
+        val stream = logBuilder.build().toByteArray().inputStream()
+
+        parser.parse(stream, getConfigDummyStream(), printStream)
+    }
+
+    @Test
+    fun parse_noConfig() {
+        val logBuilder = ProtoLogFileProto.newBuilder()
+        val logMessageBuilder = ProtoLogMessage.newBuilder()
+        logMessageBuilder
+                .setMessageHash(70933285)
+                .setElapsedRealtimeNanos(0)
+                .addBooleanParams(true)
+        logBuilder.addLog(logMessageBuilder.build())
+
+        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
+
+        assertEquals("${testDate(0)} UNKNOWN: 70933285 - [] [] [] [true]\n",
+                outStream.toString())
+    }
+}
diff --git a/tools/protologtool/tests/com/android/protolog/tool/ProtoLogCallProcessorTest.kt b/tools/protologtool/tests/com/android/protolog/tool/ProtoLogCallProcessorTest.kt
new file mode 100644
index 0000000..97f67a0
--- /dev/null
+++ b/tools/protologtool/tests/com/android/protolog/tool/ProtoLogCallProcessorTest.kt
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.StaticJavaParser
+import com.github.javaparser.ast.expr.MethodCallExpr
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class ProtoLogCallProcessorTest {
+    private data class LogCall(
+        val call: MethodCallExpr,
+        val messageString: String,
+        val level: LogLevel,
+        val group: LogGroup
+    )
+
+    private val groupMap: MutableMap<String, LogGroup> = mutableMapOf()
+    private val calls: MutableList<LogCall> = mutableListOf()
+    private val visitor = ProtoLogCallProcessor("org.example.ProtoLog", "org.example.ProtoLogGroup",
+            groupMap)
+    private val processor = object : ProtoLogCallVisitor {
+        override fun processCall(
+            call: MethodCallExpr,
+            messageString: String,
+            level: LogLevel,
+            group: LogGroup
+        ) {
+            calls.add(LogCall(call, messageString, level, group))
+        }
+    }
+
+    private fun checkCalls() {
+        assertEquals(1, calls.size)
+        val c = calls[0]
+        assertEquals("test %b", c.messageString)
+        assertEquals(groupMap["TEST"], c.group)
+        assertEquals(LogLevel.DEBUG, c.level)
+    }
+
+    @Test
+    fun process_samePackage() {
+        val code = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
+                    ProtoLog.e(ProtoLogGroup.ERROR, "error %d", 1);
+                }
+            }
+        """
+        groupMap["TEST"] = LogGroup("TEST", true, false, "WindowManager")
+        groupMap["ERROR"] = LogGroup("ERROR", true, true, "WindowManagerERROR")
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+        assertEquals(2, calls.size)
+        var c = calls[0]
+        assertEquals("test %b", c.messageString)
+        assertEquals(groupMap["TEST"], c.group)
+        assertEquals(LogLevel.DEBUG, c.level)
+        c = calls[1]
+        assertEquals("error %d", c.messageString)
+        assertEquals(groupMap["ERROR"], c.group)
+        assertEquals(LogLevel.ERROR, c.level)
+    }
+
+    @Test
+    fun process_imported() {
+        val code = """
+            package org.example2;
+
+            import org.example.ProtoLog;
+            import org.example.ProtoLogGroup;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
+                }
+            }
+        """
+        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+        checkCalls()
+    }
+
+    @Test
+    fun process_importedStatic() {
+        val code = """
+            package org.example2;
+
+            import static org.example.ProtoLog.d;
+            import static org.example.ProtoLogGroup.TEST;
+
+            class Test {
+                void test() {
+                    d(TEST, "test %b", true);
+                }
+            }
+        """
+        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+        checkCalls()
+    }
+
+    @Test(expected = InvalidProtoLogCallException::class)
+    fun process_groupNotImported() {
+        val code = """
+            package org.example2;
+
+            import org.example.ProtoLog;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
+                }
+            }
+        """
+        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+    }
+
+    @Test
+    fun process_protoLogNotImported() {
+        val code = """
+            package org.example2;
+
+            import org.example.ProtoLogGroup;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
+                }
+            }
+        """
+        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+        assertEquals(0, calls.size)
+    }
+
+    @Test(expected = InvalidProtoLogCallException::class)
+    fun process_unknownGroup() {
+        val code = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
+                }
+            }
+        """
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+    }
+
+    @Test(expected = InvalidProtoLogCallException::class)
+    fun process_staticGroup() {
+        val code = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(TEST, "test %b", true);
+                }
+            }
+        """
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+    }
+
+    @Test(expected = InvalidProtoLogCallException::class)
+    fun process_badGroup() {
+        val code = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(0, "test %b", true);
+                }
+            }
+        """
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+    }
+
+    @Test(expected = InvalidProtoLogCallException::class)
+    fun process_invalidSignature() {
+        val code = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.d("test");
+                }
+            }
+        """
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+    }
+
+    @Test
+    fun process_disabled() {
+        // Disabled groups are also processed.
+        val code = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
+                }
+            }
+        """
+        groupMap["TEST"] = LogGroup("TEST", false, true, "WindowManager")
+        visitor.process(StaticJavaParser.parse(code), processor, "")
+        checkCalls()
+    }
+}
diff --git a/tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt b/tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt
new file mode 100644
index 0000000..e746300
--- /dev/null
+++ b/tools/protologtool/tests/com/android/protolog/tool/SourceTransformerTest.kt
@@ -0,0 +1,456 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.github.javaparser.StaticJavaParser
+import com.github.javaparser.ast.CompilationUnit
+import com.github.javaparser.ast.expr.MethodCallExpr
+import com.github.javaparser.ast.stmt.IfStmt
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Test
+import org.mockito.Mockito
+
+class SourceTransformerTest {
+    companion object {
+        private const val PROTO_LOG_IMPL_PATH = "org.example.ProtoLogImpl"
+
+        /* ktlint-disable max-line-length */
+        private val TEST_CODE = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1);
+                }
+            }
+            """.trimIndent()
+
+        private val TEST_CODE_MULTILINE = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.w(TEST_GROUP, "test %d %f " + 
+                    "abc %s\n test", 100,
+                     0.1, "test");
+                }
+            }
+            """.trimIndent()
+
+        private val TEST_CODE_MULTICALLS = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); /* ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); */ ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1);
+                    ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1);
+                }
+            }
+            """.trimIndent()
+
+        private val TEST_CODE_NO_PARAMS = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    ProtoLog.w(TEST_GROUP, "test");
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_TEXT_ENABLED = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1698911065, 9, "test %d %f", protoLogParam0, protoLogParam1); }
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_MULTILINE_TEXT_ENABLED = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, 1780316587, 9, "test %d %f " + "abc %s\n test", protoLogParam0, protoLogParam1, protoLogParam2); 
+            
+            }
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_MULTICALL_TEXT_ENABLED = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1698911065, 9, "test %d %f", protoLogParam0, protoLogParam1); } /* ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); */ if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1698911065, 9, "test %d %f", protoLogParam0, protoLogParam1); }
+                    if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1698911065, 9, "test %d %f", protoLogParam0, protoLogParam1); }
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_NO_PARAMS = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { org.example.ProtoLogImpl.w(TEST_GROUP, -1741986185, 0, "test", (Object[]) null); }
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_TEXT_DISABLED = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 1698911065, 9, null, protoLogParam0, protoLogParam1); }
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_MULTILINE_TEXT_DISABLED = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (org.example.ProtoLogImpl.isEnabled(TEST_GROUP)) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, 1780316587, 9, null, protoLogParam0, protoLogParam1, protoLogParam2); 
+            
+            }
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_DISABLED = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (false) { /* TEST_GROUP is disabled */ ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); }
+                }
+            }
+            """.trimIndent()
+
+        private val TRANSFORMED_CODE_MULTILINE_DISABLED = """
+            package org.example;
+
+            class Test {
+                void test() {
+                    if (false) { /* TEST_GROUP is disabled */ ProtoLog.w(TEST_GROUP, "test %d %f " + "abc %s\n test", 100, 0.1, "test"); 
+            
+            }
+                }
+            }
+            """.trimIndent()
+        /* ktlint-enable max-line-length */
+
+        private const val PATH = "com.example.Test.java"
+    }
+
+    private val processor: ProtoLogCallProcessor = Mockito.mock(ProtoLogCallProcessor::class.java)
+    private val implPath = "org.example.ProtoLogImpl"
+    private val sourceJarWriter = SourceTransformer(implPath, processor)
+
+    private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
+
+    @Test
+    fun processClass_textEnabled() {
+        var code = StaticJavaParser.parse(TEST_CODE)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test %d %f",
+                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(1, ifStmts.size)
+        val ifStmt = ifStmts[0]
+        assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
+                ifStmt.condition.toString())
+        assertFalse(ifStmt.elseStmt.isPresent)
+        assertEquals(3, ifStmt.thenStmt.childNodes.size)
+        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
+        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
+        assertEquals("w", methodCall.name.asString())
+        assertEquals(6, methodCall.arguments.size)
+        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
+        assertEquals("1698911065", methodCall.arguments[1].toString())
+        assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
+        assertEquals("\"test %d %f\"", methodCall.arguments[3].toString())
+        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
+        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
+        assertEquals(TRANSFORMED_CODE_TEXT_ENABLED, out)
+    }
+
+    @Test
+    fun processClass_textEnabledMulticalls() {
+        var code = StaticJavaParser.parse(TEST_CODE_MULTICALLS)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            val calls = code.findAll(MethodCallExpr::class.java)
+            visitor.processCall(calls[0], "test %d %f",
+                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
+            visitor.processCall(calls[1], "test %d %f",
+                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
+            visitor.processCall(calls[2], "test %d %f",
+                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE_MULTICALLS, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(3, ifStmts.size)
+        val ifStmt = ifStmts[1]
+        assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
+                ifStmt.condition.toString())
+        assertFalse(ifStmt.elseStmt.isPresent)
+        assertEquals(3, ifStmt.thenStmt.childNodes.size)
+        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
+        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
+        assertEquals("w", methodCall.name.asString())
+        assertEquals(6, methodCall.arguments.size)
+        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
+        assertEquals("1698911065", methodCall.arguments[1].toString())
+        assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
+        assertEquals("\"test %d %f\"", methodCall.arguments[3].toString())
+        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
+        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
+        assertEquals(TRANSFORMED_CODE_MULTICALL_TEXT_ENABLED, out)
+    }
+
+    @Test
+    fun processClass_textEnabledMultiline() {
+        var code = StaticJavaParser.parse(TEST_CODE_MULTILINE)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0],
+                    "test %d %f abc %s\n test", LogLevel.WARN, LogGroup("TEST_GROUP",
+                    true, true, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(1, ifStmts.size)
+        val ifStmt = ifStmts[0]
+        assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
+                ifStmt.condition.toString())
+        assertFalse(ifStmt.elseStmt.isPresent)
+        assertEquals(4, ifStmt.thenStmt.childNodes.size)
+        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[1] as MethodCallExpr
+        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
+        assertEquals("w", methodCall.name.asString())
+        assertEquals(7, methodCall.arguments.size)
+        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
+        assertEquals("1780316587", methodCall.arguments[1].toString())
+        assertEquals(0b001001.toString(), methodCall.arguments[2].toString())
+        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
+        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
+        assertEquals("protoLogParam2", methodCall.arguments[6].toString())
+        assertEquals(TRANSFORMED_CODE_MULTILINE_TEXT_ENABLED, out)
+    }
+
+    @Test
+    fun processClass_noParams() {
+        var code = StaticJavaParser.parse(TEST_CODE_NO_PARAMS)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test",
+                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE_NO_PARAMS, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(1, ifStmts.size)
+        val ifStmt = ifStmts[0]
+        assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
+                ifStmt.condition.toString())
+        assertFalse(ifStmt.elseStmt.isPresent)
+        assertEquals(1, ifStmt.thenStmt.childNodes.size)
+        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
+        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
+        assertEquals("w", methodCall.name.asString())
+        assertEquals(5, methodCall.arguments.size)
+        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
+        assertEquals("-1741986185", methodCall.arguments[1].toString())
+        assertEquals(0.toString(), methodCall.arguments[2].toString())
+        assertEquals(TRANSFORMED_CODE_NO_PARAMS, out)
+    }
+
+    @Test
+    fun processClass_textDisabled() {
+        var code = StaticJavaParser.parse(TEST_CODE)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test %d %f",
+                    LogLevel.WARN, LogGroup("TEST_GROUP", true, false, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(1, ifStmts.size)
+        val ifStmt = ifStmts[0]
+        assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
+                ifStmt.condition.toString())
+        assertFalse(ifStmt.elseStmt.isPresent)
+        assertEquals(3, ifStmt.thenStmt.childNodes.size)
+        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
+        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
+        assertEquals("w", methodCall.name.asString())
+        assertEquals(6, methodCall.arguments.size)
+        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
+        assertEquals("1698911065", methodCall.arguments[1].toString())
+        assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
+        assertEquals("null", methodCall.arguments[3].toString())
+        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
+        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
+        assertEquals(TRANSFORMED_CODE_TEXT_DISABLED, out)
+    }
+
+    @Test
+    fun processClass_textDisabledMultiline() {
+        var code = StaticJavaParser.parse(TEST_CODE_MULTILINE)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0],
+                    "test %d %f abc %s\n test", LogLevel.WARN, LogGroup("TEST_GROUP",
+                    true, false, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(1, ifStmts.size)
+        val ifStmt = ifStmts[0]
+        assertEquals("$implPath.${Constants.IS_ENABLED_METHOD}(TEST_GROUP)",
+                ifStmt.condition.toString())
+        assertFalse(ifStmt.elseStmt.isPresent)
+        assertEquals(4, ifStmt.thenStmt.childNodes.size)
+        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[1] as MethodCallExpr
+        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
+        assertEquals("w", methodCall.name.asString())
+        assertEquals(7, methodCall.arguments.size)
+        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
+        assertEquals("1780316587", methodCall.arguments[1].toString())
+        assertEquals(0b001001.toString(), methodCall.arguments[2].toString())
+        assertEquals("null", methodCall.arguments[3].toString())
+        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
+        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
+        assertEquals("protoLogParam2", methodCall.arguments[6].toString())
+        assertEquals(TRANSFORMED_CODE_MULTILINE_TEXT_DISABLED, out)
+    }
+
+    @Test
+    fun processClass_disabled() {
+        var code = StaticJavaParser.parse(TEST_CODE)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test %d %f",
+                    LogLevel.WARN, LogGroup("TEST_GROUP", false, true, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(1, ifStmts.size)
+        val ifStmt = ifStmts[0]
+        assertEquals("false", ifStmt.condition.toString())
+        assertEquals(TRANSFORMED_CODE_DISABLED, out)
+    }
+
+    @Test
+    fun processClass_disabledMultiline() {
+        var code = StaticJavaParser.parse(TEST_CODE_MULTILINE)
+
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0],
+                    "test %d %f abc %s\n test", LogLevel.WARN, LogGroup("TEST_GROUP",
+                    false, true, "WM_TEST"))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, PATH, code)
+        code = StaticJavaParser.parse(out)
+
+        val ifStmts = code.findAll(IfStmt::class.java)
+        assertEquals(1, ifStmts.size)
+        val ifStmt = ifStmts[0]
+        assertEquals("false", ifStmt.condition.toString())
+        assertEquals(TRANSFORMED_CODE_MULTILINE_DISABLED, out)
+    }
+}
diff --git a/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt b/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt
new file mode 100644
index 0000000..2b6abcd
--- /dev/null
+++ b/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigBuilderTest.kt
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.json.stream.JsonReader
+import com.github.javaparser.ast.CompilationUnit
+import com.github.javaparser.ast.expr.MethodCallExpr
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.mockito.Mockito
+import java.io.StringReader
+
+class ViewerConfigBuilderTest {
+    companion object {
+        private val TAG1 = "WM_TEST"
+        private val TAG2 = "WM_DEBUG"
+        private val TEST1 = ViewerConfigParser.ConfigEntry("test1", LogLevel.INFO.name, TAG1)
+        private val TEST2 = ViewerConfigParser.ConfigEntry("test2", LogLevel.DEBUG.name, TAG2)
+        private val TEST3 = ViewerConfigParser.ConfigEntry("test3", LogLevel.ERROR.name, TAG2)
+        private val GROUP1 = LogGroup("TEST_GROUP", true, true, TAG1)
+        private val GROUP2 = LogGroup("DEBUG_GROUP", true, true, TAG2)
+        private val GROUP3 = LogGroup("DEBUG_GROUP", true, true, TAG2)
+        private const val PATH = "/tmp/test.java"
+    }
+
+    private val processor: ProtoLogCallProcessor = Mockito.mock(ProtoLogCallProcessor::class.java)
+    private val configBuilder = ViewerConfigBuilder(processor)
+    private val dummyCompilationUnit = CompilationUnit()
+
+    private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
+
+    private fun parseConfig(json: String): Map<Int, ViewerConfigParser.ConfigEntry> {
+        return ViewerConfigParser().parseConfig(JsonReader(StringReader(json)))
+    }
+
+    @Test
+    fun processClass() {
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
+                    GROUP1)
+            visitor.processCall(MethodCallExpr(), TEST2.messageString, LogLevel.DEBUG,
+                    GROUP2)
+            visitor.processCall(MethodCallExpr(), TEST3.messageString, LogLevel.ERROR,
+                    GROUP3)
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        configBuilder.processClass(dummyCompilationUnit, PATH)
+
+        val parsedConfig = parseConfig(configBuilder.build())
+        assertEquals(3, parsedConfig.size)
+        assertEquals(TEST1, parsedConfig[CodeUtils.hash(PATH,
+	           TEST1.messageString, LogLevel.INFO, GROUP1)])
+        assertEquals(TEST2, parsedConfig[CodeUtils.hash(PATH, TEST2.messageString,
+	           LogLevel.DEBUG, GROUP2)])
+        assertEquals(TEST3, parsedConfig[CodeUtils.hash(PATH, TEST3.messageString,
+	           LogLevel.ERROR, GROUP3)])
+    }
+
+    @Test
+    fun processClass_nonUnique() {
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
+                    GROUP1)
+            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
+                    GROUP1)
+            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
+                    GROUP1)
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        configBuilder.processClass(dummyCompilationUnit, PATH)
+
+        val parsedConfig = parseConfig(configBuilder.build())
+        assertEquals(1, parsedConfig.size)
+        assertEquals(TEST1, parsedConfig[CodeUtils.hash(PATH, TEST1.messageString,
+            	   LogLevel.INFO, GROUP1)])
+    }
+
+    @Test
+    fun processClass_disabled() {
+        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
+                any(ProtoLogCallVisitor::class.java), any(String::class.java)))
+                .thenAnswer { invocation ->
+            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
+
+            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
+                    GROUP1)
+            visitor.processCall(MethodCallExpr(), TEST2.messageString, LogLevel.DEBUG,
+                    LogGroup("DEBUG_GROUP", false, true, TAG2))
+            visitor.processCall(MethodCallExpr(), TEST3.messageString, LogLevel.ERROR,
+                    LogGroup("DEBUG_GROUP", true, false, TAG2))
+
+            invocation.arguments[0] as CompilationUnit
+        }
+
+        configBuilder.processClass(dummyCompilationUnit, PATH)
+
+        val parsedConfig = parseConfig(configBuilder.build())
+        assertEquals(2, parsedConfig.size)
+        assertEquals(TEST1, parsedConfig[CodeUtils.hash(PATH, TEST1.messageString,
+	           LogLevel.INFO, GROUP1)])
+        assertEquals(TEST3, parsedConfig[CodeUtils.hash(PATH, TEST3.messageString,
+	           LogLevel.ERROR, LogGroup("DEBUG_GROUP", true, false, TAG2))])
+    }
+}
diff --git a/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigParserTest.kt b/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigParserTest.kt
new file mode 100644
index 0000000..dc3ef7c
--- /dev/null
+++ b/tools/protologtool/tests/com/android/protolog/tool/ViewerConfigParserTest.kt
@@ -0,0 +1,327 @@
+/*
+ * Copyright (C) 2019 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.protolog.tool
+
+import com.android.json.stream.JsonReader
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import java.io.StringReader
+
+class ViewerConfigParserTest {
+    private val parser = ViewerConfigParser()
+
+    private fun getJSONReader(str: String): JsonReader {
+        return JsonReader(StringReader(str))
+    }
+
+    @Test
+    fun parseMessage() {
+        val json = """
+        {
+            "message": "Test completed successfully: %b",
+            "level": "ERROR",
+            "group": "GENERIC_WM"
+        }
+        """
+        val msg = parser.parseMessage(getJSONReader(json))
+        assertEquals("Test completed successfully: %b", msg.messageString)
+        assertEquals("ERROR", msg.level)
+        assertEquals("GENERIC_WM", msg.groupName)
+    }
+
+    @Test
+    fun parseMessage_reorder() {
+        val json = """
+        {
+            "group": "GENERIC_WM",
+            "level": "ERROR",
+            "message": "Test completed successfully: %b"
+        }
+        """
+        val msg = parser.parseMessage(getJSONReader(json))
+        assertEquals("Test completed successfully: %b", msg.messageString)
+        assertEquals("ERROR", msg.level)
+        assertEquals("GENERIC_WM", msg.groupName)
+    }
+
+    @Test
+    fun parseMessage_unknownEntry() {
+        val json = """
+        {
+            "unknown": "unknown entries should not block parsing",
+            "message": "Test completed successfully: %b",
+            "level": "ERROR",
+            "group": "GENERIC_WM"
+        }
+        """
+        val msg = parser.parseMessage(getJSONReader(json))
+        assertEquals("Test completed successfully: %b", msg.messageString)
+        assertEquals("ERROR", msg.level)
+        assertEquals("GENERIC_WM", msg.groupName)
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseMessage_noMessage() {
+        val json = """
+        {
+            "level": "ERROR",
+            "group": "GENERIC_WM"
+        }
+        """
+        parser.parseMessage(getJSONReader(json))
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseMessage_noLevel() {
+        val json = """
+        {
+            "message": "Test completed successfully: %b",
+            "group": "GENERIC_WM"
+        }
+        """
+        parser.parseMessage(getJSONReader(json))
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseMessage_noGroup() {
+        val json = """
+        {
+            "message": "Test completed successfully: %b",
+            "level": "ERROR"
+        }
+        """
+        parser.parseMessage(getJSONReader(json))
+    }
+
+    @Test
+    fun parseGroup() {
+        val json = """
+        {
+            "tag": "WindowManager"
+        }
+        """
+        val group = parser.parseGroup(getJSONReader(json))
+        assertEquals("WindowManager", group.tag)
+    }
+
+    @Test
+    fun parseGroup_unknownEntry() {
+        val json = """
+        {
+            "unknown": "unknown entries should not block parsing",
+            "tag": "WindowManager"
+        }
+        """
+        val group = parser.parseGroup(getJSONReader(json))
+        assertEquals("WindowManager", group.tag)
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseGroup_noTag() {
+        val json = """
+        {
+        }
+        """
+        parser.parseGroup(getJSONReader(json))
+    }
+
+    @Test
+    fun parseMessages() {
+        val json = """
+        {
+            "70933285": {
+              "message": "Test completed successfully: %b",
+              "level": "ERROR",
+              "group": "GENERIC_WM"
+            },
+            "1792430067": {
+              "message": "Attempted to add window to a display that does not exist: %d. Aborting.",
+              "level": "WARN",
+              "group": "ERROR_WM"
+            }
+        }
+        """
+        val messages = parser.parseMessages(getJSONReader(json))
+        assertEquals(2, messages.size)
+        val msg1 =
+                ViewerConfigParser.MessageEntry("Test completed successfully: %b",
+                        "ERROR", "GENERIC_WM")
+        val msg2 =
+                ViewerConfigParser.MessageEntry("Attempted to add window to a display that " +
+                        "does not exist: %d. Aborting.", "WARN", "ERROR_WM")
+
+        assertEquals(msg1, messages[70933285])
+        assertEquals(msg2, messages[1792430067])
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseMessages_invalidHash() {
+        val json = """
+        {
+            "invalid": {
+              "message": "Test completed successfully: %b",
+              "level": "ERROR",
+              "group": "GENERIC_WM"
+            }
+        }
+        """
+        parser.parseMessages(getJSONReader(json))
+    }
+
+    @Test
+    fun parseGroups() {
+        val json = """
+        {
+            "GENERIC_WM": {
+              "tag": "WindowManager"
+            },
+            "ERROR_WM": {
+              "tag": "WindowManagerError"
+            }
+        }
+        """
+        val groups = parser.parseGroups(getJSONReader(json))
+        assertEquals(2, groups.size)
+        val grp1 = ViewerConfigParser.GroupEntry("WindowManager")
+        val grp2 = ViewerConfigParser.GroupEntry("WindowManagerError")
+        assertEquals(grp1, groups["GENERIC_WM"])
+        assertEquals(grp2, groups["ERROR_WM"])
+    }
+
+    @Test
+    fun parseConfig() {
+        val json = """
+        {
+          "version": "${Constants.VERSION}",
+          "messages": {
+            "70933285": {
+              "message": "Test completed successfully: %b",
+              "level": "ERROR",
+              "group": "GENERIC_WM"
+            }
+          },
+          "groups": {
+            "GENERIC_WM": {
+              "tag": "WindowManager"
+            }
+          }
+        }
+        """
+        val config = parser.parseConfig(getJSONReader(json))
+        assertEquals(1, config.size)
+        val cfg1 = ViewerConfigParser.ConfigEntry("Test completed successfully: %b",
+                "ERROR", "WindowManager")
+        assertEquals(cfg1, config[70933285])
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseConfig_invalidVersion() {
+        val json = """
+        {
+          "version": "invalid",
+          "messages": {
+            "70933285": {
+              "message": "Test completed successfully: %b",
+              "level": "ERROR",
+              "group": "GENERIC_WM"
+            }
+          },
+          "groups": {
+            "GENERIC_WM": {
+              "tag": "WindowManager"
+            }
+          }
+        }
+        """
+        parser.parseConfig(getJSONReader(json))
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseConfig_noVersion() {
+        val json = """
+        {
+          "messages": {
+            "70933285": {
+              "message": "Test completed successfully: %b",
+              "level": "ERROR",
+              "group": "GENERIC_WM"
+            }
+          },
+          "groups": {
+            "GENERIC_WM": {
+              "tag": "WindowManager"
+            }
+          }
+        }
+        """
+        parser.parseConfig(getJSONReader(json))
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseConfig_noMessages() {
+        val json = """
+        {
+          "version": "${Constants.VERSION}",
+          "groups": {
+            "GENERIC_WM": {
+              "tag": "WindowManager"
+            }
+          }
+        }
+        """
+        parser.parseConfig(getJSONReader(json))
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseConfig_noGroups() {
+        val json = """
+        {
+          "version": "${Constants.VERSION}",
+          "messages": {
+            "70933285": {
+              "message": "Test completed successfully: %b",
+              "level": "ERROR",
+              "group": "GENERIC_WM"
+            }
+          }
+        }
+        """
+        parser.parseConfig(getJSONReader(json))
+    }
+
+    @Test(expected = InvalidViewerConfigException::class)
+    fun parseConfig_missingGroup() {
+        val json = """
+        {
+          "version": "${Constants.VERSION}",
+          "messages": {
+            "70933285": {
+              "message": "Test completed successfully: %b",
+              "level": "ERROR",
+              "group": "GENERIC_WM"
+            }
+          },
+          "groups": {
+            "ERROR_WM": {
+              "tag": "WindowManager"
+            }
+          }
+        }
+        """
+        parser.parseConfig(getJSONReader(json))
+    }
+}
diff --git a/tools/protologtool/tests/com/android/protologtool/CodeUtilsTest.kt b/tools/protologtool/tests/com/android/protologtool/CodeUtilsTest.kt
deleted file mode 100644
index 82daa73..0000000
--- a/tools/protologtool/tests/com/android/protologtool/CodeUtilsTest.kt
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.StaticJavaParser
-import com.github.javaparser.ast.expr.BinaryExpr
-import com.github.javaparser.ast.expr.StringLiteralExpr
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertTrue
-import org.junit.Test
-
-class CodeUtilsTest {
-    @Test
-    fun hash() {
-        assertEquals(-1704685243, CodeUtils.hash("test", LogLevel.DEBUG))
-    }
-
-    @Test
-    fun hash_changeLevel() {
-        assertEquals(-1176900998, CodeUtils.hash("test", LogLevel.ERROR))
-    }
-
-    @Test
-    fun hash_changeMessage() {
-        assertEquals(-1305634931, CodeUtils.hash("test2", LogLevel.DEBUG))
-    }
-
-    @Test
-    fun isWildcardStaticImported_true() {
-        val code = """package org.example.test;
-            import static org.example.Test.*;
-        """
-        assertTrue(CodeUtils.isWildcardStaticImported(
-                StaticJavaParser.parse(code), "org.example.Test"))
-    }
-
-    @Test
-    fun isWildcardStaticImported_notStatic() {
-        val code = """package org.example.test;
-            import org.example.Test.*;
-        """
-        assertFalse(CodeUtils.isWildcardStaticImported(
-                StaticJavaParser.parse(code), "org.example.Test"))
-    }
-
-    @Test
-    fun isWildcardStaticImported_differentClass() {
-        val code = """package org.example.test;
-            import static org.example.Test2.*;
-        """
-        assertFalse(CodeUtils.isWildcardStaticImported(
-                StaticJavaParser.parse(code), "org.example.Test"))
-    }
-
-    @Test
-    fun isWildcardStaticImported_notWildcard() {
-        val code = """package org.example.test;
-            import org.example.Test.test;
-        """
-        assertFalse(CodeUtils.isWildcardStaticImported(
-                StaticJavaParser.parse(code), "org.example.Test"))
-    }
-
-    @Test
-    fun isClassImportedOrSamePackage_imported() {
-        val code = """package org.example.test;
-            import org.example.Test;
-        """
-        assertTrue(CodeUtils.isClassImportedOrSamePackage(
-                StaticJavaParser.parse(code), "org.example.Test"))
-    }
-
-    @Test
-    fun isClassImportedOrSamePackage_samePackage() {
-        val code = """package org.example.test;
-        """
-        assertTrue(CodeUtils.isClassImportedOrSamePackage(
-                StaticJavaParser.parse(code), "org.example.test.Test"))
-    }
-
-    @Test
-    fun isClassImportedOrSamePackage_false() {
-        val code = """package org.example.test;
-            import org.example.Test;
-        """
-        assertFalse(CodeUtils.isClassImportedOrSamePackage(
-                StaticJavaParser.parse(code), "org.example.Test2"))
-    }
-
-    @Test
-    fun staticallyImportedMethods_ab() {
-        val code = """
-            import static org.example.Test.a;
-            import static org.example.Test.b;
-        """
-        val imported = CodeUtils.staticallyImportedMethods(StaticJavaParser.parse(code),
-                "org.example.Test")
-        assertTrue(imported.containsAll(listOf("a", "b")))
-        assertEquals(2, imported.size)
-    }
-
-    @Test
-    fun staticallyImportedMethods_differentClass() {
-        val code = """
-            import static org.example.Test.a;
-            import static org.example.Test2.b;
-        """
-        val imported = CodeUtils.staticallyImportedMethods(StaticJavaParser.parse(code),
-                "org.example.Test")
-        assertTrue(imported.containsAll(listOf("a")))
-        assertEquals(1, imported.size)
-    }
-
-    @Test
-    fun staticallyImportedMethods_notStatic() {
-        val code = """
-            import static org.example.Test.a;
-            import org.example.Test.b;
-        """
-        val imported = CodeUtils.staticallyImportedMethods(StaticJavaParser.parse(code),
-                "org.example.Test")
-        assertTrue(imported.containsAll(listOf("a")))
-        assertEquals(1, imported.size)
-    }
-
-    @Test
-    fun concatMultilineString_single() {
-        val str = StringLiteralExpr("test")
-        val out = CodeUtils.concatMultilineString(str)
-        assertEquals("test", out)
-    }
-
-    @Test
-    fun concatMultilineString_double() {
-        val str = """
-            "test" + "abc"
-        """
-        val code = StaticJavaParser.parseExpression<BinaryExpr>(str)
-        val out = CodeUtils.concatMultilineString(code)
-        assertEquals("testabc", out)
-    }
-
-    @Test
-    fun concatMultilineString_multiple() {
-        val str = """
-            "test" + "abc" + "1234" + "test"
-        """
-        val code = StaticJavaParser.parseExpression<BinaryExpr>(str)
-        val out = CodeUtils.concatMultilineString(code)
-        assertEquals("testabc1234test", out)
-    }
-
-    @Test
-    fun parseFormatString() {
-        val str = "%b %d %o %x %f %e %g %s %%"
-        val out = CodeUtils.parseFormatString(str)
-        assertEquals(listOf(
-                CodeUtils.LogDataTypes.BOOLEAN,
-                CodeUtils.LogDataTypes.LONG,
-                CodeUtils.LogDataTypes.LONG,
-                CodeUtils.LogDataTypes.LONG,
-                CodeUtils.LogDataTypes.DOUBLE,
-                CodeUtils.LogDataTypes.DOUBLE,
-                CodeUtils.LogDataTypes.DOUBLE,
-                CodeUtils.LogDataTypes.STRING
-        ), out)
-    }
-
-    @Test(expected = InvalidFormatStringException::class)
-    fun parseFormatString_invalid() {
-        val str = "%q"
-        CodeUtils.parseFormatString(str)
-    }
-
-    @Test
-    fun logDataTypesToBitMask() {
-        val types = listOf(CodeUtils.LogDataTypes.STRING, CodeUtils.LogDataTypes.DOUBLE,
-                CodeUtils.LogDataTypes.LONG, CodeUtils.LogDataTypes.BOOLEAN)
-        val mask = CodeUtils.logDataTypesToBitMask(types)
-        assertEquals(0b11011000, mask)
-    }
-
-    @Test(expected = InvalidFormatStringException::class)
-    fun logDataTypesToBitMask_toManyParams() {
-        val types = mutableListOf<CodeUtils.LogDataTypes>()
-        for (i in 0..16) {
-            types.add(CodeUtils.LogDataTypes.STRING)
-        }
-        CodeUtils.logDataTypesToBitMask(types)
-    }
-}
diff --git a/tools/protologtool/tests/com/android/protologtool/CommandOptionsTest.kt b/tools/protologtool/tests/com/android/protologtool/CommandOptionsTest.kt
deleted file mode 100644
index c1cd473..0000000
--- a/tools/protologtool/tests/com/android/protologtool/CommandOptionsTest.kt
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import org.junit.Assert.assertEquals
-import org.junit.Test
-
-class CommandOptionsTest {
-    companion object {
-        val TEST_JAVA_SRC = listOf(
-                "frameworks/base/services/core/java/com/android/server/wm/" +
-                        "AccessibilityController.java",
-                "frameworks/base/services/core/java/com/android/server/wm/ActivityDisplay.java",
-                "frameworks/base/services/core/java/com/android/server/wm/" +
-                        "ActivityMetricsLaunchObserver.java"
-        )
-        private const val TEST_PROTOLOG_CLASS = "com.android.server.wm.ProtoLog"
-        private const val TEST_PROTOLOGIMPL_CLASS = "com.android.server.wm.ProtoLogImpl"
-        private const val TEST_PROTOLOGGROUP_CLASS = "com.android.server.wm.ProtoLogGroup"
-        private const val TEST_PROTOLOGGROUP_JAR = "out/soong/.intermediates/frameworks/base/" +
-                "services/core/services.core.wm.protologgroups/android_common/javac/" +
-                "services.core.wm.protologgroups.jar"
-        private const val TEST_SRC_JAR = "out/soong/.temp/sbox175955373/" +
-                "services.core.wm.protolog.srcjar"
-        private const val TEST_VIEWER_JSON = "out/soong/.temp/sbox175955373/" +
-                "services.core.wm.protolog.json"
-        private const val TEST_LOG = "./test_log.pb"
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun noCommand() {
-        CommandOptions(arrayOf())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun invalidCommand() {
-        val testLine = "invalid"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test
-    fun transformClasses() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        val cmd = CommandOptions(testLine.split(' ').toTypedArray())
-        assertEquals(CommandOptions.TRANSFORM_CALLS_CMD, cmd.command)
-        assertEquals(TEST_PROTOLOG_CLASS, cmd.protoLogClassNameArg)
-        assertEquals(TEST_PROTOLOGIMPL_CLASS, cmd.protoLogImplClassNameArg)
-        assertEquals(TEST_PROTOLOGGROUP_CLASS, cmd.protoLogGroupsClassNameArg)
-        assertEquals(TEST_PROTOLOGGROUP_JAR, cmd.protoLogGroupsJarArg)
-        assertEquals(TEST_SRC_JAR, cmd.outputSourceJarArg)
-        assertEquals(TEST_JAVA_SRC, cmd.javaSourceArgs)
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_noProtoLogClass() {
-        val testLine = "transform-protolog-calls " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_noProtoLogImplClass() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_noProtoLogGroupClass() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_noProtoLogGroupJar() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_noOutJar() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                TEST_JAVA_SRC.joinToString(" ")
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_noJavaInput() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_invalidProtoLogClass() {
-        val testLine = "transform-protolog-calls --protolog-class invalid " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_invalidProtoLogImplClass() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class invalid " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_invalidProtoLogGroupClass() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class invalid " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_invalidProtoLogGroupJar() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar invalid.txt " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_invalidOutJar() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar invalid.db ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_invalidJavaInput() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR invalid.py"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_unknownParam() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--unknown test --protolog-impl-class $TEST_PROTOLOGIMPL_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun transformClasses_noValue() {
-        val testLine = "transform-protolog-calls --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--protolog-impl-class " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--output-srcjar $TEST_SRC_JAR ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test
-    fun generateConfig() {
-        val testLine = "generate-viewer-config --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--viewer-conf $TEST_VIEWER_JSON ${TEST_JAVA_SRC.joinToString(" ")}"
-        val cmd = CommandOptions(testLine.split(' ').toTypedArray())
-        assertEquals(CommandOptions.GENERATE_CONFIG_CMD, cmd.command)
-        assertEquals(TEST_PROTOLOG_CLASS, cmd.protoLogClassNameArg)
-        assertEquals(TEST_PROTOLOGGROUP_CLASS, cmd.protoLogGroupsClassNameArg)
-        assertEquals(TEST_PROTOLOGGROUP_JAR, cmd.protoLogGroupsJarArg)
-        assertEquals(TEST_VIEWER_JSON, cmd.viewerConfigJsonArg)
-        assertEquals(TEST_JAVA_SRC, cmd.javaSourceArgs)
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun generateConfig_noViewerConfig() {
-        val testLine = "generate-viewer-config --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                TEST_JAVA_SRC.joinToString(" ")
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test(expected = InvalidCommandException::class)
-    fun generateConfig_invalidViewerConfig() {
-        val testLine = "generate-viewer-config --protolog-class $TEST_PROTOLOG_CLASS " +
-                "--loggroups-class $TEST_PROTOLOGGROUP_CLASS " +
-                "--loggroups-jar $TEST_PROTOLOGGROUP_JAR " +
-                "--viewer-conf invalid.yaml ${TEST_JAVA_SRC.joinToString(" ")}"
-        CommandOptions(testLine.split(' ').toTypedArray())
-    }
-
-    @Test
-    fun readLog() {
-        val testLine = "read-log --viewer-conf $TEST_VIEWER_JSON $TEST_LOG"
-        val cmd = CommandOptions(testLine.split(' ').toTypedArray())
-        assertEquals(CommandOptions.READ_LOG_CMD, cmd.command)
-        assertEquals(TEST_VIEWER_JSON, cmd.viewerConfigJsonArg)
-        assertEquals(TEST_LOG, cmd.logProtofileArg)
-    }
-}
diff --git a/tools/protologtool/tests/com/android/protologtool/LogParserTest.kt b/tools/protologtool/tests/com/android/protologtool/LogParserTest.kt
deleted file mode 100644
index 7106ea6..0000000
--- a/tools/protologtool/tests/com/android/protologtool/LogParserTest.kt
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.json.stream.JsonReader
-import com.android.server.wm.ProtoLogMessage
-import com.android.server.wm.WindowManagerLogFileProto
-import org.junit.Assert.assertEquals
-import org.junit.Before
-import org.junit.Test
-import org.mockito.Mockito
-import org.mockito.Mockito.mock
-import java.io.ByteArrayOutputStream
-import java.io.InputStream
-import java.io.OutputStream
-import java.io.PrintStream
-import java.text.SimpleDateFormat
-import java.util.Date
-import java.util.Locale
-
-class LogParserTest {
-    private val configParser: ViewerConfigParser = mock(ViewerConfigParser::class.java)
-    private val parser = LogParser(configParser)
-    private var config: MutableMap<Int, ViewerConfigParser.ConfigEntry> = mutableMapOf()
-    private var outStream: OutputStream = ByteArrayOutputStream()
-    private var printStream: PrintStream = PrintStream(outStream)
-    private val dateFormat = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US)
-
-    @Before
-    fun init() {
-        Mockito.`when`(configParser.parseConfig(any(JsonReader::class.java))).thenReturn(config)
-    }
-
-    private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
-
-    private fun getConfigDummyStream(): InputStream {
-        return "".byteInputStream()
-    }
-
-    private fun buildProtoInput(logBuilder: WindowManagerLogFileProto.Builder): InputStream {
-        logBuilder.setVersion(Constants.VERSION)
-        logBuilder.magicNumber =
-                WindowManagerLogFileProto.MagicNumber.MAGIC_NUMBER_H.number.toLong() shl 32 or
-                        WindowManagerLogFileProto.MagicNumber.MAGIC_NUMBER_L.number.toLong()
-        return logBuilder.build().toByteArray().inputStream()
-    }
-
-    private fun testDate(timeMS: Long): String {
-        return dateFormat.format(Date(timeMS))
-    }
-
-    @Test
-    fun parse() {
-        config[70933285] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b",
-                "ERROR", "WindowManager")
-
-        val logBuilder = WindowManagerLogFileProto.newBuilder()
-        val logMessageBuilder = ProtoLogMessage.newBuilder()
-        logMessageBuilder
-                .setMessageHash(70933285)
-                .setElapsedRealtimeNanos(0)
-                .addBooleanParams(true)
-        logBuilder.addLog(logMessageBuilder.build())
-
-        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
-
-        assertEquals("${testDate(0)} ERROR WindowManager: Test completed successfully: true\n",
-                outStream.toString())
-    }
-
-    @Test
-    fun parse_formatting() {
-        config[123] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b %d %% %o" +
-                " %x %e %g %s %f", "ERROR", "WindowManager")
-
-        val logBuilder = WindowManagerLogFileProto.newBuilder()
-        val logMessageBuilder = ProtoLogMessage.newBuilder()
-        logMessageBuilder
-                .setMessageHash(123)
-                .setElapsedRealtimeNanos(0)
-                .addBooleanParams(true)
-                .addAllSint64Params(listOf(1000, 20000, 300000))
-                .addAllDoubleParams(listOf(0.1, 0.00001, 1000.1))
-                .addStrParams("test")
-        logBuilder.addLog(logMessageBuilder.build())
-
-        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
-
-        assertEquals("${testDate(0)} ERROR WindowManager: Test completed successfully: " +
-                "true 1000 % 47040 493e0 1.000000e-01 1.00000e-05 test 1000.100000\n",
-                outStream.toString())
-    }
-
-    @Test
-    fun parse_invalidParamsTooMany() {
-        config[123] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b %d %% %o",
-                "ERROR", "WindowManager")
-
-        val logBuilder = WindowManagerLogFileProto.newBuilder()
-        val logMessageBuilder = ProtoLogMessage.newBuilder()
-        logMessageBuilder
-                .setMessageHash(123)
-                .setElapsedRealtimeNanos(0)
-                .addBooleanParams(true)
-                .addAllSint64Params(listOf(1000, 20000, 300000))
-                .addAllDoubleParams(listOf(0.1, 0.00001, 1000.1))
-                .addStrParams("test")
-        logBuilder.addLog(logMessageBuilder.build())
-
-        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
-
-        assertEquals("${testDate(0)} INVALID: 123 - [test] [1000, 20000, 300000] " +
-                "[0.1, 1.0E-5, 1000.1] [true]\n", outStream.toString())
-    }
-
-    @Test
-    fun parse_invalidParamsNotEnough() {
-        config[123] = ViewerConfigParser.ConfigEntry("Test completed successfully: %b %d %% %o" +
-                " %x %e %g %s %f", "ERROR", "WindowManager")
-
-        val logBuilder = WindowManagerLogFileProto.newBuilder()
-        val logMessageBuilder = ProtoLogMessage.newBuilder()
-        logMessageBuilder
-                .setMessageHash(123)
-                .setElapsedRealtimeNanos(0)
-                .addBooleanParams(true)
-                .addStrParams("test")
-        logBuilder.addLog(logMessageBuilder.build())
-
-        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
-
-        assertEquals("${testDate(0)} INVALID: 123 - [test] [] [] [true]\n",
-                outStream.toString())
-    }
-
-    @Test(expected = InvalidInputException::class)
-    fun parse_invalidMagicNumber() {
-        val logBuilder = WindowManagerLogFileProto.newBuilder()
-        logBuilder.setVersion(Constants.VERSION)
-        logBuilder.magicNumber = 0
-        val stream = logBuilder.build().toByteArray().inputStream()
-
-        parser.parse(stream, getConfigDummyStream(), printStream)
-    }
-
-    @Test(expected = InvalidInputException::class)
-    fun parse_invalidVersion() {
-        val logBuilder = WindowManagerLogFileProto.newBuilder()
-        logBuilder.setVersion("invalid")
-        logBuilder.magicNumber =
-                WindowManagerLogFileProto.MagicNumber.MAGIC_NUMBER_H.number.toLong() shl 32 or
-                        WindowManagerLogFileProto.MagicNumber.MAGIC_NUMBER_L.number.toLong()
-        val stream = logBuilder.build().toByteArray().inputStream()
-
-        parser.parse(stream, getConfigDummyStream(), printStream)
-    }
-
-    @Test
-    fun parse_noConfig() {
-        val logBuilder = WindowManagerLogFileProto.newBuilder()
-        val logMessageBuilder = ProtoLogMessage.newBuilder()
-        logMessageBuilder
-                .setMessageHash(70933285)
-                .setElapsedRealtimeNanos(0)
-                .addBooleanParams(true)
-        logBuilder.addLog(logMessageBuilder.build())
-
-        parser.parse(buildProtoInput(logBuilder), getConfigDummyStream(), printStream)
-
-        assertEquals("${testDate(0)} UNKNOWN: 70933285 - [] [] [] [true]\n",
-                outStream.toString())
-    }
-}
diff --git a/tools/protologtool/tests/com/android/protologtool/ProtoLogCallProcessorTest.kt b/tools/protologtool/tests/com/android/protologtool/ProtoLogCallProcessorTest.kt
deleted file mode 100644
index dcb1f7f..0000000
--- a/tools/protologtool/tests/com/android/protologtool/ProtoLogCallProcessorTest.kt
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.StaticJavaParser
-import com.github.javaparser.ast.expr.MethodCallExpr
-import org.junit.Assert.assertEquals
-import org.junit.Test
-
-class ProtoLogCallProcessorTest {
-    private data class LogCall(
-        val call: MethodCallExpr,
-        val messageString: String,
-        val level: LogLevel,
-        val group: LogGroup
-    )
-
-    private val groupMap: MutableMap<String, LogGroup> = mutableMapOf()
-    private val calls: MutableList<LogCall> = mutableListOf()
-    private val visitor = ProtoLogCallProcessor("org.example.ProtoLog", "org.example.ProtoLogGroup",
-            groupMap)
-    private val processor = object : ProtoLogCallVisitor {
-        override fun processCall(
-            call: MethodCallExpr,
-            messageString: String,
-            level: LogLevel,
-            group: LogGroup
-        ) {
-            calls.add(LogCall(call, messageString, level, group))
-        }
-    }
-
-    private fun checkCalls() {
-        assertEquals(1, calls.size)
-        val c = calls[0]
-        assertEquals("test %b", c.messageString)
-        assertEquals(groupMap["TEST"], c.group)
-        assertEquals(LogLevel.DEBUG, c.level)
-    }
-
-    @Test
-    fun process_samePackage() {
-        val code = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
-                    ProtoLog.e(ProtoLogGroup.ERROR, "error %d", 1);
-                }
-            }
-        """
-        groupMap["TEST"] = LogGroup("TEST", true, false, "WindowManager")
-        groupMap["ERROR"] = LogGroup("ERROR", true, true, "WindowManagerERROR")
-        visitor.process(StaticJavaParser.parse(code), processor)
-        assertEquals(2, calls.size)
-        var c = calls[0]
-        assertEquals("test %b", c.messageString)
-        assertEquals(groupMap["TEST"], c.group)
-        assertEquals(LogLevel.DEBUG, c.level)
-        c = calls[1]
-        assertEquals("error %d", c.messageString)
-        assertEquals(groupMap["ERROR"], c.group)
-        assertEquals(LogLevel.ERROR, c.level)
-    }
-
-    @Test
-    fun process_imported() {
-        val code = """
-            package org.example2;
-
-            import org.example.ProtoLog;
-            import org.example.ProtoLogGroup;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
-                }
-            }
-        """
-        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
-        visitor.process(StaticJavaParser.parse(code), processor)
-        checkCalls()
-    }
-
-    @Test
-    fun process_importedStatic() {
-        val code = """
-            package org.example2;
-
-            import static org.example.ProtoLog.d;
-            import static org.example.ProtoLogGroup.TEST;
-
-            class Test {
-                void test() {
-                    d(TEST, "test %b", true);
-                }
-            }
-        """
-        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
-        visitor.process(StaticJavaParser.parse(code), processor)
-        checkCalls()
-    }
-
-    @Test(expected = InvalidProtoLogCallException::class)
-    fun process_groupNotImported() {
-        val code = """
-            package org.example2;
-
-            import org.example.ProtoLog;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
-                }
-            }
-        """
-        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
-        visitor.process(StaticJavaParser.parse(code), processor)
-    }
-
-    @Test
-    fun process_protoLogNotImported() {
-        val code = """
-            package org.example2;
-
-            import org.example.ProtoLogGroup;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
-                }
-            }
-        """
-        groupMap["TEST"] = LogGroup("TEST", true, true, "WindowManager")
-        visitor.process(StaticJavaParser.parse(code), processor)
-        assertEquals(0, calls.size)
-    }
-
-    @Test(expected = InvalidProtoLogCallException::class)
-    fun process_unknownGroup() {
-        val code = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
-                }
-            }
-        """
-        visitor.process(StaticJavaParser.parse(code), processor)
-    }
-
-    @Test(expected = InvalidProtoLogCallException::class)
-    fun process_staticGroup() {
-        val code = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(TEST, "test %b", true);
-                }
-            }
-        """
-        visitor.process(StaticJavaParser.parse(code), processor)
-    }
-
-    @Test(expected = InvalidProtoLogCallException::class)
-    fun process_badGroup() {
-        val code = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(0, "test %b", true);
-                }
-            }
-        """
-        visitor.process(StaticJavaParser.parse(code), processor)
-    }
-
-    @Test(expected = InvalidProtoLogCallException::class)
-    fun process_invalidSignature() {
-        val code = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.d("test");
-                }
-            }
-        """
-        visitor.process(StaticJavaParser.parse(code), processor)
-    }
-
-    @Test
-    fun process_disabled() {
-        // Disabled groups are also processed.
-        val code = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.d(ProtoLogGroup.TEST, "test %b", true);
-                }
-            }
-        """
-        groupMap["TEST"] = LogGroup("TEST", false, true, "WindowManager")
-        visitor.process(StaticJavaParser.parse(code), processor)
-        checkCalls()
-    }
-}
diff --git a/tools/protologtool/tests/com/android/protologtool/SourceTransformerTest.kt b/tools/protologtool/tests/com/android/protologtool/SourceTransformerTest.kt
deleted file mode 100644
index 2cd8562..0000000
--- a/tools/protologtool/tests/com/android/protologtool/SourceTransformerTest.kt
+++ /dev/null
@@ -1,445 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.github.javaparser.StaticJavaParser
-import com.github.javaparser.ast.CompilationUnit
-import com.github.javaparser.ast.expr.MethodCallExpr
-import com.github.javaparser.ast.stmt.IfStmt
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Test
-import org.mockito.Mockito
-
-class SourceTransformerTest {
-    companion object {
-        private const val PROTO_LOG_IMPL_PATH = "org.example.ProtoLogImpl"
-
-        /* ktlint-disable max-line-length */
-        private val TEST_CODE = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1);
-                }
-            }
-            """.trimIndent()
-
-        private val TEST_CODE_MULTILINE = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.w(TEST_GROUP, "test %d %f " + 
-                    "abc %s\n test", 100,
-                     0.1, "test");
-                }
-            }
-            """.trimIndent()
-
-        private val TEST_CODE_MULTICALLS = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); /* ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); */ ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1);
-                    ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1);
-                }
-            }
-            """.trimIndent()
-
-        private val TEST_CODE_NO_PARAMS = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    ProtoLog.w(TEST_GROUP, "test");
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_TEXT_ENABLED = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); }
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_MULTILINE_TEXT_ENABLED = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, -986393606, 9, "test %d %f " + "abc %s\n test", protoLogParam0, protoLogParam1, protoLogParam2); 
-            
-            }
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_MULTICALL_TEXT_ENABLED = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); } /* ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); */ if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); }
-                    if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, "test %d %f", protoLogParam0, protoLogParam1); }
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_NO_PARAMS = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (TEST_GROUP.isLogToAny()) { org.example.ProtoLogImpl.w(TEST_GROUP, 1282022424, 0, "test", (Object[]) null); }
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_TEXT_DISABLED = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; org.example.ProtoLogImpl.w(TEST_GROUP, 835524026, 9, null, protoLogParam0, protoLogParam1); }
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_MULTILINE_TEXT_DISABLED = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (TEST_GROUP.isLogToAny()) { long protoLogParam0 = 100; double protoLogParam1 = 0.1; String protoLogParam2 = String.valueOf("test"); org.example.ProtoLogImpl.w(TEST_GROUP, -986393606, 9, null, protoLogParam0, protoLogParam1, protoLogParam2); 
-            
-            }
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_DISABLED = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (false) { /* TEST_GROUP is disabled */ ProtoLog.w(TEST_GROUP, "test %d %f", 100, 0.1); }
-                }
-            }
-            """.trimIndent()
-
-        private val TRANSFORMED_CODE_MULTILINE_DISABLED = """
-            package org.example;
-
-            class Test {
-                void test() {
-                    if (false) { /* TEST_GROUP is disabled */ ProtoLog.w(TEST_GROUP, "test %d %f " + "abc %s\n test", 100, 0.1, "test"); 
-            
-            }
-                }
-            }
-            """.trimIndent()
-        /* ktlint-enable max-line-length */
-    }
-
-    private val processor: ProtoLogCallProcessor = Mockito.mock(ProtoLogCallProcessor::class.java)
-    private val sourceJarWriter = SourceTransformer("org.example.ProtoLogImpl", processor)
-
-    private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
-
-    @Test
-    fun processClass_textEnabled() {
-        var code = StaticJavaParser.parse(TEST_CODE)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test %d %f",
-                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(1, ifStmts.size)
-        val ifStmt = ifStmts[0]
-        assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
-                ifStmt.condition.toString())
-        assertFalse(ifStmt.elseStmt.isPresent)
-        assertEquals(3, ifStmt.thenStmt.childNodes.size)
-        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
-        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
-        assertEquals("w", methodCall.name.asString())
-        assertEquals(6, methodCall.arguments.size)
-        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
-        assertEquals("835524026", methodCall.arguments[1].toString())
-        assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
-        assertEquals("\"test %d %f\"", methodCall.arguments[3].toString())
-        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
-        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
-        assertEquals(TRANSFORMED_CODE_TEXT_ENABLED, out)
-    }
-
-    @Test
-    fun processClass_textEnabledMulticalls() {
-        var code = StaticJavaParser.parse(TEST_CODE_MULTICALLS)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            val calls = code.findAll(MethodCallExpr::class.java)
-            visitor.processCall(calls[0], "test %d %f",
-                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
-            visitor.processCall(calls[1], "test %d %f",
-                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
-            visitor.processCall(calls[2], "test %d %f",
-                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE_MULTICALLS, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(3, ifStmts.size)
-        val ifStmt = ifStmts[1]
-        assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
-                ifStmt.condition.toString())
-        assertFalse(ifStmt.elseStmt.isPresent)
-        assertEquals(3, ifStmt.thenStmt.childNodes.size)
-        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
-        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
-        assertEquals("w", methodCall.name.asString())
-        assertEquals(6, methodCall.arguments.size)
-        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
-        assertEquals("835524026", methodCall.arguments[1].toString())
-        assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
-        assertEquals("\"test %d %f\"", methodCall.arguments[3].toString())
-        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
-        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
-        assertEquals(TRANSFORMED_CODE_MULTICALL_TEXT_ENABLED, out)
-    }
-
-    @Test
-    fun processClass_textEnabledMultiline() {
-        var code = StaticJavaParser.parse(TEST_CODE_MULTILINE)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0],
-                    "test %d %f abc %s\n test", LogLevel.WARN, LogGroup("TEST_GROUP",
-                    true, true, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(1, ifStmts.size)
-        val ifStmt = ifStmts[0]
-        assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
-                ifStmt.condition.toString())
-        assertFalse(ifStmt.elseStmt.isPresent)
-        assertEquals(4, ifStmt.thenStmt.childNodes.size)
-        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[1] as MethodCallExpr
-        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
-        assertEquals("w", methodCall.name.asString())
-        assertEquals(7, methodCall.arguments.size)
-        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
-        assertEquals("-986393606", methodCall.arguments[1].toString())
-        assertEquals(0b001001.toString(), methodCall.arguments[2].toString())
-        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
-        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
-        assertEquals("protoLogParam2", methodCall.arguments[6].toString())
-        assertEquals(TRANSFORMED_CODE_MULTILINE_TEXT_ENABLED, out)
-    }
-
-    @Test
-    fun processClass_noParams() {
-        var code = StaticJavaParser.parse(TEST_CODE_NO_PARAMS)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test",
-                    LogLevel.WARN, LogGroup("TEST_GROUP", true, true, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE_NO_PARAMS, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(1, ifStmts.size)
-        val ifStmt = ifStmts[0]
-        assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
-                ifStmt.condition.toString())
-        assertFalse(ifStmt.elseStmt.isPresent)
-        assertEquals(1, ifStmt.thenStmt.childNodes.size)
-        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
-        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
-        assertEquals("w", methodCall.name.asString())
-        assertEquals(5, methodCall.arguments.size)
-        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
-        assertEquals("1282022424", methodCall.arguments[1].toString())
-        assertEquals(0.toString(), methodCall.arguments[2].toString())
-        assertEquals(TRANSFORMED_CODE_NO_PARAMS, out)
-    }
-
-    @Test
-    fun processClass_textDisabled() {
-        var code = StaticJavaParser.parse(TEST_CODE)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test %d %f",
-                    LogLevel.WARN, LogGroup("TEST_GROUP", true, false, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(1, ifStmts.size)
-        val ifStmt = ifStmts[0]
-        assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
-                ifStmt.condition.toString())
-        assertFalse(ifStmt.elseStmt.isPresent)
-        assertEquals(3, ifStmt.thenStmt.childNodes.size)
-        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[0] as MethodCallExpr
-        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
-        assertEquals("w", methodCall.name.asString())
-        assertEquals(6, methodCall.arguments.size)
-        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
-        assertEquals("835524026", methodCall.arguments[1].toString())
-        assertEquals(0b1001.toString(), methodCall.arguments[2].toString())
-        assertEquals("null", methodCall.arguments[3].toString())
-        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
-        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
-        assertEquals(TRANSFORMED_CODE_TEXT_DISABLED, out)
-    }
-
-    @Test
-    fun processClass_textDisabledMultiline() {
-        var code = StaticJavaParser.parse(TEST_CODE_MULTILINE)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0],
-                    "test %d %f abc %s\n test", LogLevel.WARN, LogGroup("TEST_GROUP",
-                    true, false, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(1, ifStmts.size)
-        val ifStmt = ifStmts[0]
-        assertEquals("TEST_GROUP.${Constants.IS_LOG_TO_ANY_METHOD}()",
-                ifStmt.condition.toString())
-        assertFalse(ifStmt.elseStmt.isPresent)
-        assertEquals(4, ifStmt.thenStmt.childNodes.size)
-        val methodCall = ifStmt.thenStmt.findAll(MethodCallExpr::class.java)[1] as MethodCallExpr
-        assertEquals(PROTO_LOG_IMPL_PATH, methodCall.scope.get().toString())
-        assertEquals("w", methodCall.name.asString())
-        assertEquals(7, methodCall.arguments.size)
-        assertEquals("TEST_GROUP", methodCall.arguments[0].toString())
-        assertEquals("-986393606", methodCall.arguments[1].toString())
-        assertEquals(0b001001.toString(), methodCall.arguments[2].toString())
-        assertEquals("null", methodCall.arguments[3].toString())
-        assertEquals("protoLogParam0", methodCall.arguments[4].toString())
-        assertEquals("protoLogParam1", methodCall.arguments[5].toString())
-        assertEquals("protoLogParam2", methodCall.arguments[6].toString())
-        assertEquals(TRANSFORMED_CODE_MULTILINE_TEXT_DISABLED, out)
-    }
-
-    @Test
-    fun processClass_disabled() {
-        var code = StaticJavaParser.parse(TEST_CODE)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0], "test %d %f",
-                    LogLevel.WARN, LogGroup("TEST_GROUP", false, true, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(1, ifStmts.size)
-        val ifStmt = ifStmts[0]
-        assertEquals("false", ifStmt.condition.toString())
-        assertEquals(TRANSFORMED_CODE_DISABLED, out)
-    }
-
-    @Test
-    fun processClass_disabledMultiline() {
-        var code = StaticJavaParser.parse(TEST_CODE_MULTILINE)
-
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(code.findAll(MethodCallExpr::class.java)[0],
-                    "test %d %f abc %s\n test", LogLevel.WARN, LogGroup("TEST_GROUP",
-                    false, true, "WM_TEST"))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        val out = sourceJarWriter.processClass(TEST_CODE_MULTILINE, code)
-        code = StaticJavaParser.parse(out)
-
-        val ifStmts = code.findAll(IfStmt::class.java)
-        assertEquals(1, ifStmts.size)
-        val ifStmt = ifStmts[0]
-        assertEquals("false", ifStmt.condition.toString())
-        assertEquals(TRANSFORMED_CODE_MULTILINE_DISABLED, out)
-    }
-}
diff --git a/tools/protologtool/tests/com/android/protologtool/ViewerConfigBuilderTest.kt b/tools/protologtool/tests/com/android/protologtool/ViewerConfigBuilderTest.kt
deleted file mode 100644
index 53d2e8b..0000000
--- a/tools/protologtool/tests/com/android/protologtool/ViewerConfigBuilderTest.kt
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.json.stream.JsonReader
-import com.github.javaparser.ast.CompilationUnit
-import com.github.javaparser.ast.expr.MethodCallExpr
-import org.junit.Assert.assertEquals
-import org.junit.Test
-import org.mockito.Mockito
-import java.io.StringReader
-
-class ViewerConfigBuilderTest {
-    companion object {
-        private val TAG1 = "WM_TEST"
-        private val TAG2 = "WM_DEBUG"
-        private val TEST1 = ViewerConfigParser.ConfigEntry("test1", LogLevel.INFO.name, TAG1)
-        private val TEST2 = ViewerConfigParser.ConfigEntry("test2", LogLevel.DEBUG.name, TAG2)
-        private val TEST3 = ViewerConfigParser.ConfigEntry("test3", LogLevel.ERROR.name, TAG2)
-    }
-
-    private val processor: ProtoLogCallProcessor = Mockito.mock(ProtoLogCallProcessor::class.java)
-    private val configBuilder = ViewerConfigBuilder(processor)
-    private val dummyCompilationUnit = CompilationUnit()
-
-    private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)
-
-    private fun parseConfig(json: String): Map<Int, ViewerConfigParser.ConfigEntry> {
-        return ViewerConfigParser().parseConfig(JsonReader(StringReader(json)))
-    }
-
-    @Test
-    fun processClass() {
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
-                    LogGroup("TEST_GROUP", true, true, TAG1))
-            visitor.processCall(MethodCallExpr(), TEST2.messageString, LogLevel.DEBUG,
-                    LogGroup("DEBUG_GROUP", true, true, TAG2))
-            visitor.processCall(MethodCallExpr(), TEST3.messageString, LogLevel.ERROR,
-                    LogGroup("DEBUG_GROUP", true, true, TAG2))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        configBuilder.processClass(dummyCompilationUnit)
-
-        val parsedConfig = parseConfig(configBuilder.build())
-        assertEquals(3, parsedConfig.size)
-        assertEquals(TEST1, parsedConfig[CodeUtils.hash(TEST1.messageString,
-                LogLevel.INFO)])
-        assertEquals(TEST2, parsedConfig[CodeUtils.hash(TEST2.messageString,
-                LogLevel.DEBUG)])
-        assertEquals(TEST3, parsedConfig[CodeUtils.hash(TEST3.messageString,
-                LogLevel.ERROR)])
-    }
-
-    @Test
-    fun processClass_nonUnique() {
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
-                    LogGroup("TEST_GROUP", true, true, TAG1))
-            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
-                    LogGroup("TEST_GROUP", true, true, TAG1))
-            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
-                    LogGroup("TEST_GROUP", true, true, TAG1))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        configBuilder.processClass(dummyCompilationUnit)
-
-        val parsedConfig = parseConfig(configBuilder.build())
-        assertEquals(1, parsedConfig.size)
-        assertEquals(TEST1, parsedConfig[CodeUtils.hash(TEST1.messageString, LogLevel.INFO)])
-    }
-
-    @Test
-    fun processClass_disabled() {
-        Mockito.`when`(processor.process(any(CompilationUnit::class.java),
-                any(ProtoLogCallVisitor::class.java))).thenAnswer { invocation ->
-            val visitor = invocation.arguments[1] as ProtoLogCallVisitor
-
-            visitor.processCall(MethodCallExpr(), TEST1.messageString, LogLevel.INFO,
-                    LogGroup("TEST_GROUP", true, true, TAG1))
-            visitor.processCall(MethodCallExpr(), TEST2.messageString, LogLevel.DEBUG,
-                    LogGroup("DEBUG_GROUP", false, true, TAG2))
-            visitor.processCall(MethodCallExpr(), TEST3.messageString, LogLevel.ERROR,
-                    LogGroup("DEBUG_GROUP", true, false, TAG2))
-
-            invocation.arguments[0] as CompilationUnit
-        }
-
-        configBuilder.processClass(dummyCompilationUnit)
-
-        val parsedConfig = parseConfig(configBuilder.build())
-        assertEquals(2, parsedConfig.size)
-        assertEquals(TEST1, parsedConfig[CodeUtils.hash(TEST1.messageString, LogLevel.INFO)])
-        assertEquals(TEST3, parsedConfig[CodeUtils.hash(TEST3.messageString, LogLevel.ERROR)])
-    }
-}
diff --git a/tools/protologtool/tests/com/android/protologtool/ViewerConfigParserTest.kt b/tools/protologtool/tests/com/android/protologtool/ViewerConfigParserTest.kt
deleted file mode 100644
index c0cea73..0000000
--- a/tools/protologtool/tests/com/android/protologtool/ViewerConfigParserTest.kt
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * Copyright (C) 2019 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.protologtool
-
-import com.android.json.stream.JsonReader
-import org.junit.Test
-import java.io.StringReader
-import org.junit.Assert.assertEquals
-
-class ViewerConfigParserTest {
-    private val parser = ViewerConfigParser()
-
-    private fun getJSONReader(str: String): JsonReader {
-        return JsonReader(StringReader(str))
-    }
-
-    @Test
-    fun parseMessage() {
-        val json = """
-        {
-            "message": "Test completed successfully: %b",
-            "level": "ERROR",
-            "group": "GENERIC_WM"
-        }
-        """
-        val msg = parser.parseMessage(getJSONReader(json))
-        assertEquals("Test completed successfully: %b", msg.messageString)
-        assertEquals("ERROR", msg.level)
-        assertEquals("GENERIC_WM", msg.groupName)
-    }
-
-    @Test
-    fun parseMessage_reorder() {
-        val json = """
-        {
-            "group": "GENERIC_WM",
-            "level": "ERROR",
-            "message": "Test completed successfully: %b"
-        }
-        """
-        val msg = parser.parseMessage(getJSONReader(json))
-        assertEquals("Test completed successfully: %b", msg.messageString)
-        assertEquals("ERROR", msg.level)
-        assertEquals("GENERIC_WM", msg.groupName)
-    }
-
-    @Test
-    fun parseMessage_unknownEntry() {
-        val json = """
-        {
-            "unknown": "unknown entries should not block parsing",
-            "message": "Test completed successfully: %b",
-            "level": "ERROR",
-            "group": "GENERIC_WM"
-        }
-        """
-        val msg = parser.parseMessage(getJSONReader(json))
-        assertEquals("Test completed successfully: %b", msg.messageString)
-        assertEquals("ERROR", msg.level)
-        assertEquals("GENERIC_WM", msg.groupName)
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseMessage_noMessage() {
-        val json = """
-        {
-            "level": "ERROR",
-            "group": "GENERIC_WM"
-        }
-        """
-        parser.parseMessage(getJSONReader(json))
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseMessage_noLevel() {
-        val json = """
-        {
-            "message": "Test completed successfully: %b",
-            "group": "GENERIC_WM"
-        }
-        """
-        parser.parseMessage(getJSONReader(json))
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseMessage_noGroup() {
-        val json = """
-        {
-            "message": "Test completed successfully: %b",
-            "level": "ERROR"
-        }
-        """
-        parser.parseMessage(getJSONReader(json))
-    }
-
-    @Test
-    fun parseGroup() {
-        val json = """
-        {
-            "tag": "WindowManager"
-        }
-        """
-        val group = parser.parseGroup(getJSONReader(json))
-        assertEquals("WindowManager", group.tag)
-    }
-
-    @Test
-    fun parseGroup_unknownEntry() {
-        val json = """
-        {
-            "unknown": "unknown entries should not block parsing",
-            "tag": "WindowManager"
-        }
-        """
-        val group = parser.parseGroup(getJSONReader(json))
-        assertEquals("WindowManager", group.tag)
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseGroup_noTag() {
-        val json = """
-        {
-        }
-        """
-        parser.parseGroup(getJSONReader(json))
-    }
-
-    @Test
-    fun parseMessages() {
-        val json = """
-        {
-            "70933285": {
-              "message": "Test completed successfully: %b",
-              "level": "ERROR",
-              "group": "GENERIC_WM"
-            },
-            "1792430067": {
-              "message": "Attempted to add window to a display that does not exist: %d. Aborting.",
-              "level": "WARN",
-              "group": "ERROR_WM"
-            }
-        }
-        """
-        val messages = parser.parseMessages(getJSONReader(json))
-        assertEquals(2, messages.size)
-        val msg1 =
-                ViewerConfigParser.MessageEntry("Test completed successfully: %b",
-                        "ERROR", "GENERIC_WM")
-        val msg2 =
-                ViewerConfigParser.MessageEntry("Attempted to add window to a display that " +
-                        "does not exist: %d. Aborting.", "WARN", "ERROR_WM")
-
-        assertEquals(msg1, messages[70933285])
-        assertEquals(msg2, messages[1792430067])
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseMessages_invalidHash() {
-        val json = """
-        {
-            "invalid": {
-              "message": "Test completed successfully: %b",
-              "level": "ERROR",
-              "group": "GENERIC_WM"
-            }
-        }
-        """
-        parser.parseMessages(getJSONReader(json))
-    }
-
-    @Test
-    fun parseGroups() {
-        val json = """
-        {
-            "GENERIC_WM": {
-              "tag": "WindowManager"
-            },
-            "ERROR_WM": {
-              "tag": "WindowManagerError"
-            }
-        }
-        """
-        val groups = parser.parseGroups(getJSONReader(json))
-        assertEquals(2, groups.size)
-        val grp1 = ViewerConfigParser.GroupEntry("WindowManager")
-        val grp2 = ViewerConfigParser.GroupEntry("WindowManagerError")
-        assertEquals(grp1, groups["GENERIC_WM"])
-        assertEquals(grp2, groups["ERROR_WM"])
-    }
-
-    @Test
-    fun parseConfig() {
-        val json = """
-        {
-          "version": "${Constants.VERSION}",
-          "messages": {
-            "70933285": {
-              "message": "Test completed successfully: %b",
-              "level": "ERROR",
-              "group": "GENERIC_WM"
-            }
-          },
-          "groups": {
-            "GENERIC_WM": {
-              "tag": "WindowManager"
-            }
-          }
-        }
-        """
-        val config = parser.parseConfig(getJSONReader(json))
-        assertEquals(1, config.size)
-        val cfg1 = ViewerConfigParser.ConfigEntry("Test completed successfully: %b",
-                "ERROR", "WindowManager")
-        assertEquals(cfg1, config[70933285])
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseConfig_invalidVersion() {
-        val json = """
-        {
-          "version": "invalid",
-          "messages": {
-            "70933285": {
-              "message": "Test completed successfully: %b",
-              "level": "ERROR",
-              "group": "GENERIC_WM"
-            }
-          },
-          "groups": {
-            "GENERIC_WM": {
-              "tag": "WindowManager"
-            }
-          }
-        }
-        """
-        parser.parseConfig(getJSONReader(json))
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseConfig_noVersion() {
-        val json = """
-        {
-          "messages": {
-            "70933285": {
-              "message": "Test completed successfully: %b",
-              "level": "ERROR",
-              "group": "GENERIC_WM"
-            }
-          },
-          "groups": {
-            "GENERIC_WM": {
-              "tag": "WindowManager"
-            }
-          }
-        }
-        """
-        parser.parseConfig(getJSONReader(json))
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseConfig_noMessages() {
-        val json = """
-        {
-          "version": "${Constants.VERSION}",
-          "groups": {
-            "GENERIC_WM": {
-              "tag": "WindowManager"
-            }
-          }
-        }
-        """
-        parser.parseConfig(getJSONReader(json))
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseConfig_noGroups() {
-        val json = """
-        {
-          "version": "${Constants.VERSION}",
-          "messages": {
-            "70933285": {
-              "message": "Test completed successfully: %b",
-              "level": "ERROR",
-              "group": "GENERIC_WM"
-            }
-          }
-        }
-        """
-        parser.parseConfig(getJSONReader(json))
-    }
-
-    @Test(expected = InvalidViewerConfigException::class)
-    fun parseConfig_missingGroup() {
-        val json = """
-        {
-          "version": "${Constants.VERSION}",
-          "messages": {
-            "70933285": {
-              "message": "Test completed successfully: %b",
-              "level": "ERROR",
-              "group": "GENERIC_WM"
-            }
-          },
-          "groups": {
-            "ERROR_WM": {
-              "tag": "WindowManager"
-            }
-          }
-        }
-        """
-        val config = parser.parseConfig(getJSONReader(json))
-    }
-}
diff --git a/tools/validatekeymaps/Main.cpp b/tools/validatekeymaps/Main.cpp
index 56a242f..5ac9dfd 100644
--- a/tools/validatekeymaps/Main.cpp
+++ b/tools/validatekeymaps/Main.cpp
@@ -137,7 +137,6 @@
     }
     }
 
-    log("No errors.\n\n");
     return true;
 }
 
diff --git a/wifi/java/android/net/wifi/IActionListener.aidl b/wifi/java/android/net/wifi/IActionListener.aidl
new file mode 100644
index 0000000..faa0901
--- /dev/null
+++ b/wifi/java/android/net/wifi/IActionListener.aidl
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2019 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.net.wifi;
+
+/**
+ * Interface for generic wifi callbacks.
+ * @hide
+ */
+oneway interface IActionListener
+{
+    void onSuccess();
+    void onFailure(int reason);
+}
diff --git a/wifi/java/android/net/wifi/ILocalOnlyHotspotCallback.aidl b/wifi/java/android/net/wifi/ILocalOnlyHotspotCallback.aidl
new file mode 100644
index 0000000..b83b594
--- /dev/null
+++ b/wifi/java/android/net/wifi/ILocalOnlyHotspotCallback.aidl
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) 2019, 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.net.wifi;
+
+import android.net.wifi.WifiConfiguration;
+
+/**
+ * Communicates LOHS status back to the application process.
+ *
+ * @hide
+ */
+oneway interface ILocalOnlyHotspotCallback {
+    void onHotspotStarted(in WifiConfiguration config);
+    void onHotspotStopped();
+    void onHotspotFailed(int reason);
+}
diff --git a/wifi/java/android/net/wifi/ITxPacketCountListener.aidl b/wifi/java/android/net/wifi/ITxPacketCountListener.aidl
new file mode 100644
index 0000000..8606ab5
--- /dev/null
+++ b/wifi/java/android/net/wifi/ITxPacketCountListener.aidl
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2019 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.net.wifi;
+
+/**
+ * Interface for tx packet counter callback.
+ * @hide
+ */
+oneway interface ITxPacketCountListener
+{
+    void onSuccess(int count);
+    void onFailure(int reason);
+}
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
index 931e5dd..b7e1094 100644
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ b/wifi/java/android/net/wifi/IWifiManager.aidl
@@ -24,10 +24,13 @@
 
 import android.net.DhcpInfo;
 import android.net.Network;
+import android.net.wifi.IActionListener;
 import android.net.wifi.IDppCallback;
+import android.net.wifi.ILocalOnlyHotspotCallback;
 import android.net.wifi.INetworkRequestMatchCallback;
 import android.net.wifi.ISoftApCallback;
 import android.net.wifi.ITrafficStateCallback;
+import android.net.wifi.ITxPacketCountListener;
 import android.net.wifi.IOnWifiUsabilityStatsListener;
 import android.net.wifi.ScanResult;
 import android.net.wifi.WifiActivityEnergyInfo;
@@ -106,8 +109,6 @@
 
     int getWifiEnabledState();
 
-    void setCountryCode(String country);
-
     String getCountryCode();
 
     boolean isDualBandSupported();
@@ -138,11 +139,11 @@
 
     boolean stopSoftAp();
 
-    int startLocalOnlyHotspot(in Messenger messenger, in IBinder binder, String packageName);
+    int startLocalOnlyHotspot(in ILocalOnlyHotspotCallback callback, String packageName);
 
     void stopLocalOnlyHotspot();
 
-    void startWatchLocalOnlyHotspot(in Messenger messenger, in IBinder binder);
+    void startWatchLocalOnlyHotspot(in ILocalOnlyHotspotCallback callback);
 
     void stopWatchLocalOnlyHotspot();
 
@@ -156,8 +157,6 @@
 
     void notifyUserOfApBandConversion(String packageName);
 
-    Messenger getWifiServiceMessenger(String packageName);
-
     void enableTdls(String remoteIPAddress, boolean enable);
 
     void enableTdlsWithMacAddress(String remoteMacAddress, boolean enable);
@@ -220,4 +219,12 @@
     void stopDppSession();
 
     void updateWifiUsabilityScore(int seqNum, int score, int predictionHorizonSec);
+
+    oneway void connect(in WifiConfiguration config, int netId, in IBinder binder, in IActionListener listener, int callbackIdentifier);
+
+    oneway void save(in WifiConfiguration config, in IBinder binder, in IActionListener listener, int callbackIdentifier);
+
+    oneway void forget(int netId, in IBinder binder, in IActionListener listener, int callbackIdentifier);
+
+    oneway void getTxPacketCount(String packageName, in IBinder binder, in ITxPacketCountListener listener, int callbackIdentifier);
 }
diff --git a/wifi/java/android/net/wifi/RssiPacketCountInfo.java b/wifi/java/android/net/wifi/RssiPacketCountInfo.java
deleted file mode 100644
index 4301165..0000000
--- a/wifi/java/android/net/wifi/RssiPacketCountInfo.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2012 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.net.wifi;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * Bundle of RSSI and packet count information, for WiFi watchdog
- *
- * @see WifiWatchdogStateMachine
- *
- * @hide
- */
-public class RssiPacketCountInfo implements Parcelable {
-
-    public int rssi;
-
-    public int txgood;
-
-    public int txbad;
-
-    public int rxgood;
-
-    public RssiPacketCountInfo() {
-        rssi = txgood = txbad = rxgood = 0;
-    }
-
-    private RssiPacketCountInfo(Parcel in) {
-        rssi = in.readInt();
-        txgood = in.readInt();
-        txbad = in.readInt();
-        rxgood = in.readInt();
-    }
-
-    @Override
-    public void writeToParcel(Parcel out, int flags) {
-        out.writeInt(rssi);
-        out.writeInt(txgood);
-        out.writeInt(txbad);
-        out.writeInt(rxgood);
-    }
-
-    @Override
-    public int describeContents() {
-        return 0;
-    }
-
-    public static final @android.annotation.NonNull Parcelable.Creator<RssiPacketCountInfo> CREATOR =
-            new Parcelable.Creator<RssiPacketCountInfo>() {
-        @Override
-        public RssiPacketCountInfo createFromParcel(Parcel in) {
-            return new RssiPacketCountInfo(in);
-        }
-
-        @Override
-        public RssiPacketCountInfo[] newArray(int size) {
-            return new RssiPacketCountInfo[size];
-        }
-    };
-}
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
index eb5a717..2afb14a 100644
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ b/wifi/java/android/net/wifi/WifiConfiguration.java
@@ -1056,26 +1056,6 @@
     }
 
     /**
-     * @hide
-     * Returns Randomized MAC address to use with the network.
-     * If it is not set/valid, creates a new randomized address.
-     * If it can't generate a valid mac, returns the default MAC.
-     */
-    public @NonNull MacAddress getOrCreateRandomizedMacAddress() {
-        int randomMacGenerationCount = 0;
-        while (!isValidMacAddressForRandomization(mRandomizedMacAddress)
-                && randomMacGenerationCount < MAXIMUM_RANDOM_MAC_GENERATION_RETRY) {
-            mRandomizedMacAddress = MacAddress.createRandomUnicastAddress();
-            randomMacGenerationCount++;
-        }
-
-        if (!isValidMacAddressForRandomization(mRandomizedMacAddress)) {
-            mRandomizedMacAddress = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
-        }
-        return mRandomizedMacAddress;
-    }
-
-    /**
      * Returns MAC address set to be the local randomized MAC address.
      * Depending on user preference, the device may or may not use the returned MAC address for
      * connections to this network.
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 0fa0ec7..5782f5b 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -45,23 +45,19 @@
 import android.os.Binder;
 import android.os.Build;
 import android.os.Handler;
+import android.os.HandlerExecutor;
 import android.os.IBinder;
 import android.os.Looper;
-import android.os.Message;
-import android.os.Messenger;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.WorkSource;
 import android.text.TextUtils;
 import android.util.Log;
 import android.util.Pair;
-import android.util.SparseArray;
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.ArrayUtils;
-import com.android.internal.util.AsyncChannel;
-import com.android.internal.util.Protocol;
 import com.android.server.net.NetworkPinner;
 
 import dalvik.system.CloseGuard;
@@ -75,7 +71,6 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 
 /**
@@ -1128,26 +1123,9 @@
     IWifiManager mService;
     private final int mTargetSdkVersion;
 
-    private static final int INVALID_KEY = 0;
-    private int mListenerKey = 1;
-    private final SparseArray mListenerMap = new SparseArray();
-    private final Object mListenerMapLock = new Object();
-
-    private AsyncChannel mAsyncChannel;
-    private CountDownLatch mConnected;
     private Looper mLooper;
     private boolean mVerboseLoggingEnabled = false;
 
-    /* LocalOnlyHotspot callback message types */
-    /** @hide */
-    public static final int HOTSPOT_STARTED = 0;
-    /** @hide */
-    public static final int HOTSPOT_STOPPED = 1;
-    /** @hide */
-    public static final int HOTSPOT_FAILED = 2;
-    /** @hide */
-    public static final int HOTSPOT_OBSERVER_REGISTERED = 3;
-
     private final Object mLock = new Object(); // lock guarding access to the following vars
     @GuardedBy("mLock")
     private LocalOnlyHotspotCallbackProxy mLOHSCallbackProxy;
@@ -2501,25 +2479,6 @@
     }
 
     /**
-     * Set the country code.
-     * @param countryCode country code in ISO 3166 format.
-     *
-     * @hide
-     */
-    public void setCountryCode(@NonNull String country) {
-        try {
-            IWifiManager iWifiManager = getIWifiManager();
-            if (iWifiManager == null) {
-                if (TextUtils.isEmpty(country)) return;
-                throw new RemoteException("Wifi service is not running");
-            }
-            iWifiManager.setCountryCode(country);
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-    /**
     * get the country code.
     * @return the country code in ISO 3166 format.
     *
@@ -2644,8 +2603,23 @@
      *
      * @hide for CTS test only
      */
-    public void getTxPacketCount(TxPacketCountListener listener) {
-        getChannel().sendMessage(RSSI_PKTCNT_FETCH, 0, putListener(listener));
+    public void getTxPacketCount(@NonNull TxPacketCountListener listener) {
+        if (listener == null) throw new IllegalArgumentException("listener cannot be null");
+        Binder binder = new Binder();
+        TxPacketCountListenerProxy listenerProxy =
+                new TxPacketCountListenerProxy(mLooper, listener);
+        try {
+            IWifiManager iWifiManager = getIWifiManager();
+            if (iWifiManager == null) {
+                throw new RemoteException("Wifi service is not running");
+            }
+            iWifiManager.getTxPacketCount(mContext.getOpPackageName(), binder, listenerProxy,
+                    listener.hashCode());
+        } catch (RemoteException e) {
+            listenerProxy.onFailure(ERROR);
+        } catch (SecurityException e) {
+            listenerProxy.onFailure(NOT_AUTHORIZED);
+        }
     }
 
     /**
@@ -2745,6 +2719,13 @@
         }
     }
 
+    private Executor executorForHandler(@Nullable Handler handler) {
+        if (handler == null) {
+            return mContext.getMainExecutor();
+        }
+        return new HandlerExecutor(handler);
+    }
+
     /**
      * Request a local only hotspot that an application can use to communicate between co-located
      * devices connected to the created WiFi hotspot.  The network created by this method will not
@@ -2802,21 +2783,20 @@
      */
     public void startLocalOnlyHotspot(LocalOnlyHotspotCallback callback,
             @Nullable Handler handler) {
+        Executor executor = executorForHandler(handler);
         synchronized (mLock) {
-            Looper looper = (handler == null) ? mContext.getMainLooper() : handler.getLooper();
             LocalOnlyHotspotCallbackProxy proxy =
-                    new LocalOnlyHotspotCallbackProxy(this, looper, callback);
+                    new LocalOnlyHotspotCallbackProxy(this, executor, callback);
             try {
                 IWifiManager iWifiManager = getIWifiManager();
                 if (iWifiManager == null) {
                     throw new RemoteException("Wifi service is not running");
                 }
                 String packageName = mContext.getOpPackageName();
-                int returnCode = iWifiManager.startLocalOnlyHotspot(
-                        proxy.getMessenger(), new Binder(), packageName);
+                int returnCode = iWifiManager.startLocalOnlyHotspot(proxy, packageName);
                 if (returnCode != LocalOnlyHotspotCallback.REQUEST_REGISTERED) {
                     // Send message to the proxy to make sure we call back on the correct thread
-                    proxy.notifyFailed(returnCode);
+                    proxy.onHotspotFailed(returnCode);
                     return;
                 }
                 mLOHSCallbackProxy = proxy;
@@ -2894,16 +2874,16 @@
      */
     public void watchLocalOnlyHotspot(LocalOnlyHotspotObserver observer,
             @Nullable Handler handler) {
+        Executor executor = executorForHandler(handler);
         synchronized (mLock) {
-            Looper looper = (handler == null) ? mContext.getMainLooper() : handler.getLooper();
-            mLOHSObserverProxy = new LocalOnlyHotspotObserverProxy(this, looper, observer);
+            mLOHSObserverProxy =
+                    new LocalOnlyHotspotObserverProxy(this, executor, observer);
             try {
                 IWifiManager iWifiManager = getIWifiManager();
                 if (iWifiManager == null) {
                     throw new RemoteException("Wifi service is not running");
                 }
-                iWifiManager.startWatchLocalOnlyHotspot(
-                        mLOHSObserverProxy.getMessenger(), new Binder());
+                iWifiManager.startWatchLocalOnlyHotspot(mLOHSObserverProxy);
                 mLOHSObserverProxy.registered();
             } catch (RemoteException e) {
                 mLOHSObserverProxy = null;
@@ -3080,76 +3060,6 @@
         }
     }
 
-    /* TODO: deprecate synchronous API and open up the following API */
-
-    private static final int BASE = Protocol.BASE_WIFI_MANAGER;
-
-    /* Commands to WifiService */
-    /** @hide */
-    public static final int CONNECT_NETWORK                 = BASE + 1;
-    /** @hide */
-    public static final int CONNECT_NETWORK_FAILED          = BASE + 2;
-    /** @hide */
-    public static final int CONNECT_NETWORK_SUCCEEDED       = BASE + 3;
-
-    /** @hide */
-    public static final int FORGET_NETWORK                  = BASE + 4;
-    /** @hide */
-    public static final int FORGET_NETWORK_FAILED           = BASE + 5;
-    /** @hide */
-    public static final int FORGET_NETWORK_SUCCEEDED        = BASE + 6;
-
-    /** @hide */
-    public static final int SAVE_NETWORK                    = BASE + 7;
-    /** @hide */
-    public static final int SAVE_NETWORK_FAILED             = BASE + 8;
-    /** @hide */
-    public static final int SAVE_NETWORK_SUCCEEDED          = BASE + 9;
-
-    /** @hide
-     * @deprecated This is deprecated
-     */
-    public static final int START_WPS                       = BASE + 10;
-    /** @hide
-     * @deprecated This is deprecated
-     */
-    public static final int START_WPS_SUCCEEDED             = BASE + 11;
-    /** @hide
-     * @deprecated This is deprecated
-     */
-    public static final int WPS_FAILED                      = BASE + 12;
-    /** @hide
-     * @deprecated This is deprecated
-     */
-    public static final int WPS_COMPLETED                   = BASE + 13;
-
-    /** @hide
-     * @deprecated This is deprecated
-     */
-    public static final int CANCEL_WPS                      = BASE + 14;
-    /** @hide
-     * @deprecated This is deprecated
-     */
-    public static final int CANCEL_WPS_FAILED               = BASE + 15;
-    /** @hide
-     * @deprecated This is deprecated
-     */
-    public static final int CANCEL_WPS_SUCCEDED             = BASE + 16;
-
-    /** @hide */
-    public static final int DISABLE_NETWORK                 = BASE + 17;
-    /** @hide */
-    public static final int DISABLE_NETWORK_FAILED          = BASE + 18;
-    /** @hide */
-    public static final int DISABLE_NETWORK_SUCCEEDED       = BASE + 19;
-
-    /** @hide */
-    public static final int RSSI_PKTCNT_FETCH               = BASE + 20;
-    /** @hide */
-    public static final int RSSI_PKTCNT_FETCH_SUCCEEDED     = BASE + 21;
-    /** @hide */
-    public static final int RSSI_PKTCNT_FETCH_FAILED        = BASE + 22;
-
     /**
      * Passed with {@link ActionListener#onFailure}.
      * Indicates that the operation failed due to an internal error.
@@ -3172,6 +3082,11 @@
      */
     public static final int BUSY                        = 2;
 
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef({ERROR, IN_PROGRESS, BUSY})
+    public @interface ActionListenerFailureReason {}
+
     /* WPS specific errors */
     /** WPS overlap detected
      * @deprecated This is deprecated
@@ -3216,20 +3131,13 @@
     public interface ActionListener {
         /**
          * The operation succeeded.
-         * This is called when the scan request has been validated and ready
-         * to sent to driver.
          */
-        public void onSuccess();
+        void onSuccess();
         /**
          * The operation failed.
-         * This is called when the scan request failed.
-         * @param reason The reason for failure could be one of the following:
-         * {@link #REASON_INVALID_REQUEST}} is specified when scan request parameters are invalid.
-         * {@link #REASON_NOT_AUTHORIZED} is specified when requesting app doesn't have the required
-         * permission to request a scan.
-         * {@link #REASON_UNSPECIFIED} is specified when driver reports a scan failure.
+         * @param reason The reason for failure depends on the operation.
          */
-        public void onFailure(int reason);
+        void onFailure(@ActionListenerFailureReason int reason);
     }
 
     /** Interface for callback invocation on a start WPS action
@@ -3274,6 +3182,41 @@
     }
 
     /**
+     * Callback proxy for TxPacketCountListener objects.
+     *
+     * @hide
+     */
+    private class TxPacketCountListenerProxy extends ITxPacketCountListener.Stub {
+        private final Handler mHandler;
+        private final TxPacketCountListener mCallback;
+
+        TxPacketCountListenerProxy(Looper looper, TxPacketCountListener callback) {
+            mHandler = new Handler(looper);
+            mCallback = callback;
+        }
+
+        @Override
+        public void onSuccess(int count) {
+            if (mVerboseLoggingEnabled) {
+                Log.v(TAG, "TxPacketCounterProxy: onSuccess: count=" + count);
+            }
+            mHandler.post(() -> {
+                mCallback.onSuccess(count);
+            });
+        }
+
+        @Override
+        public void onFailure(int reason) {
+            if (mVerboseLoggingEnabled) {
+                Log.v(TAG, "TxPacketCounterProxy: onFailure: reason=" + reason);
+            }
+            mHandler.post(() -> {
+                mCallback.onFailure(reason);
+            });
+        }
+    }
+
+    /**
      * Base class for soft AP callback. Should be extended by applications and set when calling
      * {@link WifiManager#registerSoftApCallback(SoftApCallback, Handler)}.
      *
@@ -3498,82 +3441,58 @@
     /**
      * Callback proxy for LocalOnlyHotspotCallback objects.
      */
-    private static class LocalOnlyHotspotCallbackProxy {
-        private final Handler mHandler;
+    private static class LocalOnlyHotspotCallbackProxy extends ILocalOnlyHotspotCallback.Stub {
         private final WeakReference<WifiManager> mWifiManager;
-        private final Looper mLooper;
-        private final Messenger mMessenger;
+        private final Executor mExecutor;
+        private final LocalOnlyHotspotCallback mCallback;
 
         /**
-         * Constructs a {@link LocalOnlyHotspotCallback} using the specified looper.  All callbacks
-         * will be delivered on the thread of the specified looper.
+         * Constructs a {@link LocalOnlyHotspotCallbackProxy} using the specified executor.  All
+         * callbacks will run using the given executor.
          *
          * @param manager WifiManager
-         * @param looper Looper for delivering callbacks
+         * @param executor Executor for delivering callbacks.
          * @param callback LocalOnlyHotspotCallback to notify the calling application.
          */
-        LocalOnlyHotspotCallbackProxy(WifiManager manager, Looper looper,
-                final LocalOnlyHotspotCallback callback) {
+        LocalOnlyHotspotCallbackProxy(WifiManager manager, Executor executor,
+                                      LocalOnlyHotspotCallback callback) {
             mWifiManager = new WeakReference<>(manager);
-            mLooper = looper;
-
-            mHandler = new Handler(looper) {
-                @Override
-                public void handleMessage(Message msg) {
-                    Log.d(TAG, "LocalOnlyHotspotCallbackProxy: handle message what: "
-                            + msg.what + " msg: " + msg);
-
-                    WifiManager manager = mWifiManager.get();
-                    if (manager == null) {
-                        Log.w(TAG, "LocalOnlyHotspotCallbackProxy: handle message post GC");
-                        return;
-                    }
-
-                    switch (msg.what) {
-                        case HOTSPOT_STARTED:
-                            WifiConfiguration config = (WifiConfiguration) msg.obj;
-                            if (config == null) {
-                                Log.e(TAG, "LocalOnlyHotspotCallbackProxy: config cannot be null.");
-                                callback.onFailed(LocalOnlyHotspotCallback.ERROR_GENERIC);
-                                return;
-                            }
-                            callback.onStarted(manager.new LocalOnlyHotspotReservation(config));
-                            break;
-                        case HOTSPOT_STOPPED:
-                            Log.w(TAG, "LocalOnlyHotspotCallbackProxy: hotspot stopped");
-                            callback.onStopped();
-                            break;
-                        case HOTSPOT_FAILED:
-                            int reasonCode = msg.arg1;
-                            Log.w(TAG, "LocalOnlyHotspotCallbackProxy: failed to start.  reason: "
-                                    + reasonCode);
-                            callback.onFailed(reasonCode);
-                            Log.w(TAG, "done with the callback...");
-                            break;
-                        default:
-                            Log.e(TAG, "LocalOnlyHotspotCallbackProxy unhandled message.  type: "
-                                    + msg.what);
-                    }
-                }
-            };
-            mMessenger = new Messenger(mHandler);
+            mExecutor = executor;
+            mCallback = callback;
         }
 
-        public Messenger getMessenger() {
-            return mMessenger;
+        @Override
+        public void onHotspotStarted(WifiConfiguration config) {
+            WifiManager manager = mWifiManager.get();
+            if (manager == null) return;
+
+            if (config == null) {
+                Log.e(TAG, "LocalOnlyHotspotCallbackProxy: config cannot be null.");
+                onHotspotFailed(LocalOnlyHotspotCallback.ERROR_GENERIC);
+                return;
+            }
+            final LocalOnlyHotspotReservation reservation =
+                    manager.new LocalOnlyHotspotReservation(config);
+            mExecutor.execute(() -> mCallback.onStarted(reservation));
         }
 
-        /**
-         * Helper method allowing the the incoming application call to move the onFailed callback
-         * over to the desired callback thread.
-         *
-         * @param reason int representing the error type
-         */
-        public void notifyFailed(int reason) throws RemoteException {
-            Message msg = Message.obtain();
-            msg.what = HOTSPOT_FAILED;
-            msg.arg1 = reason;
-            mMessenger.send(msg);
+        @Override
+        public void onHotspotStopped() {
+            WifiManager manager = mWifiManager.get();
+            if (manager == null) return;
+
+            Log.w(TAG, "LocalOnlyHotspotCallbackProxy: hotspot stopped");
+            mExecutor.execute(() -> mCallback.onStopped());
+        }
+
+        @Override
+        public void onHotspotFailed(int reason) {
+            WifiManager manager = mWifiManager.get();
+            if (manager == null) return;
+
+            Log.w(TAG, "LocalOnlyHotspotCallbackProxy: failed to start.  reason: "
+                    + reason);
+            mExecutor.execute(() -> mCallback.onFailed(reason));
         }
     }
 
@@ -3641,191 +3560,115 @@
     /**
      * Callback proxy for LocalOnlyHotspotObserver objects.
      */
-    private static class LocalOnlyHotspotObserverProxy {
-        private final Handler mHandler;
+    private static class LocalOnlyHotspotObserverProxy extends ILocalOnlyHotspotCallback.Stub {
         private final WeakReference<WifiManager> mWifiManager;
-        private final Looper mLooper;
-        private final Messenger mMessenger;
+        private final Executor mExecutor;
+        private final LocalOnlyHotspotObserver mObserver;
 
         /**
          * Constructs a {@link LocalOnlyHotspotObserverProxy} using the specified looper.
          * All callbacks will be delivered on the thread of the specified looper.
          *
          * @param manager WifiManager
-         * @param looper Looper for delivering callbacks
+         * @param executor Executor for delivering callbacks
          * @param observer LocalOnlyHotspotObserver to notify the calling application.
          */
-        LocalOnlyHotspotObserverProxy(WifiManager manager, Looper looper,
+        LocalOnlyHotspotObserverProxy(WifiManager manager, Executor executor,
                 final LocalOnlyHotspotObserver observer) {
             mWifiManager = new WeakReference<>(manager);
-            mLooper = looper;
-
-            mHandler = new Handler(looper) {
-                @Override
-                public void handleMessage(Message msg) {
-                    Log.d(TAG, "LocalOnlyHotspotObserverProxy: handle message what: "
-                            + msg.what + " msg: " + msg);
-
-                    WifiManager manager = mWifiManager.get();
-                    if (manager == null) {
-                        Log.w(TAG, "LocalOnlyHotspotObserverProxy: handle message post GC");
-                        return;
-                    }
-
-                    switch (msg.what) {
-                        case HOTSPOT_OBSERVER_REGISTERED:
-                            observer.onRegistered(manager.new LocalOnlyHotspotSubscription());
-                            break;
-                        case HOTSPOT_STARTED:
-                            WifiConfiguration config = (WifiConfiguration) msg.obj;
-                            if (config == null) {
-                                Log.e(TAG, "LocalOnlyHotspotObserverProxy: config cannot be null.");
-                                return;
-                            }
-                            observer.onStarted(config);
-                            break;
-                        case HOTSPOT_STOPPED:
-                            observer.onStopped();
-                            break;
-                        default:
-                            Log.e(TAG, "LocalOnlyHotspotObserverProxy unhandled message.  type: "
-                                    + msg.what);
-                    }
-                }
-            };
-            mMessenger = new Messenger(mHandler);
-        }
-
-        public Messenger getMessenger() {
-            return mMessenger;
+            mExecutor = executor;
+            mObserver = observer;
         }
 
         public void registered() throws RemoteException {
-            Message msg = Message.obtain();
-            msg.what = HOTSPOT_OBSERVER_REGISTERED;
-            mMessenger.send(msg);
-        }
-    }
+            WifiManager manager = mWifiManager.get();
+            if (manager == null) return;
 
-    // Ensure that multiple ServiceHandler threads do not interleave message dispatch.
-    private static final Object sServiceHandlerDispatchLock = new Object();
-
-    private class ServiceHandler extends Handler {
-        ServiceHandler(Looper looper) {
-            super(looper);
+            mExecutor.execute(() ->
+                    mObserver.onRegistered(manager.new LocalOnlyHotspotSubscription()));
         }
 
         @Override
-        public void handleMessage(Message message) {
-            synchronized (sServiceHandlerDispatchLock) {
-                dispatchMessageToListeners(message);
+        public void onHotspotStarted(WifiConfiguration config) {
+            WifiManager manager = mWifiManager.get();
+            if (manager == null) return;
+
+            if (config == null) {
+                Log.e(TAG, "LocalOnlyHotspotObserverProxy: config cannot be null.");
+                return;
             }
+            mExecutor.execute(() -> mObserver.onStarted(config));
         }
 
-        private void dispatchMessageToListeners(Message message) {
-            Object listener = removeListener(message.arg2);
-            switch (message.what) {
-                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
-                    if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
-                        mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
-                    } else {
-                        Log.e(TAG, "Failed to set up channel connection");
-                        // This will cause all further async API calls on the WifiManager
-                        // to fail and throw an exception
-                        mAsyncChannel = null;
-                    }
-                    mConnected.countDown();
-                    break;
-                case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED:
-                    // Ignore
-                    break;
-                case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
-                    Log.e(TAG, "Channel connection lost");
-                    // This will cause all further async API calls on the WifiManager
-                    // to fail and throw an exception
-                    mAsyncChannel = null;
-                    getLooper().quit();
-                    break;
-                    /* ActionListeners grouped together */
-                case WifiManager.CONNECT_NETWORK_FAILED:
-                case WifiManager.FORGET_NETWORK_FAILED:
-                case WifiManager.SAVE_NETWORK_FAILED:
-                case WifiManager.DISABLE_NETWORK_FAILED:
-                    if (listener != null) {
-                        ((ActionListener) listener).onFailure(message.arg1);
-                    }
-                    break;
-                    /* ActionListeners grouped together */
-                case WifiManager.CONNECT_NETWORK_SUCCEEDED:
-                case WifiManager.FORGET_NETWORK_SUCCEEDED:
-                case WifiManager.SAVE_NETWORK_SUCCEEDED:
-                case WifiManager.DISABLE_NETWORK_SUCCEEDED:
-                    if (listener != null) {
-                        ((ActionListener) listener).onSuccess();
-                    }
-                    break;
-                case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED:
-                    if (listener != null) {
-                        RssiPacketCountInfo info = (RssiPacketCountInfo) message.obj;
-                        if (info != null)
-                            ((TxPacketCountListener) listener).onSuccess(info.txgood + info.txbad);
-                        else
-                            ((TxPacketCountListener) listener).onFailure(ERROR);
-                    }
-                    break;
-                case WifiManager.RSSI_PKTCNT_FETCH_FAILED:
-                    if (listener != null) {
-                        ((TxPacketCountListener) listener).onFailure(message.arg1);
-                    }
-                    break;
-                default:
-                    //ignore
-                    break;
-            }
+        @Override
+        public void onHotspotStopped() {
+            WifiManager manager = mWifiManager.get();
+            if (manager == null) return;
+
+            mExecutor.execute(() -> mObserver.onStopped());
+        }
+
+        @Override
+        public void onHotspotFailed(int reason) {
+            // do nothing
         }
     }
 
-    private int putListener(Object listener) {
-        if (listener == null) return INVALID_KEY;
-        int key;
-        synchronized (mListenerMapLock) {
-            do {
-                key = mListenerKey++;
-            } while (key == INVALID_KEY);
-            mListenerMap.put(key, listener);
-        }
-        return key;
-    }
+    /**
+     * Callback proxy for ActionListener objects.
+     */
+    private class ActionListenerProxy extends IActionListener.Stub {
+        private final String mActionTag;
+        private final Handler mHandler;
+        private final ActionListener mCallback;
 
-    private Object removeListener(int key) {
-        if (key == INVALID_KEY) return null;
-        synchronized (mListenerMapLock) {
-            Object listener = mListenerMap.get(key);
-            mListenerMap.remove(key);
-            return listener;
+        ActionListenerProxy(String actionTag, Looper looper, ActionListener callback) {
+            mActionTag = actionTag;
+            mHandler = new Handler(looper);
+            mCallback = callback;
+        }
+
+        @Override
+        public void onSuccess() {
+            if (mVerboseLoggingEnabled) {
+                Log.v(TAG, "ActionListenerProxy:" + mActionTag + ": onSuccess");
+            }
+            mHandler.post(() -> {
+                mCallback.onSuccess();
+            });
+        }
+
+        @Override
+        public void onFailure(@ActionListenerFailureReason int reason) {
+            if (mVerboseLoggingEnabled) {
+                Log.v(TAG, "ActionListenerProxy:" + mActionTag + ": onFailure=" + reason);
+            }
+            mHandler.post(() -> {
+                mCallback.onFailure(reason);
+            });
         }
     }
 
-    private synchronized AsyncChannel getChannel() {
-        if (mAsyncChannel == null) {
-            Messenger messenger = getWifiServiceMessenger();
-            if (messenger == null) {
-                throw new IllegalStateException(
-                        "getWifiServiceMessenger() returned null!  This is invalid.");
-            }
-
-            mAsyncChannel = new AsyncChannel();
-            mConnected = new CountDownLatch(1);
-
-            Handler handler = new ServiceHandler(mLooper);
-            mAsyncChannel.connect(mContext, handler, messenger);
-            try {
-                mConnected.await();
-            } catch (InterruptedException e) {
-                Log.e(TAG, "interrupted wait at init");
-            }
+    private void connectInternal(@Nullable WifiConfiguration config, int networkId,
+            @Nullable ActionListener listener) {
+        ActionListenerProxy listenerProxy = null;
+        Binder binder = null;
+        if (listener != null) {
+            listenerProxy = new ActionListenerProxy("connect", mLooper, listener);
+            binder = new Binder();
         }
-        return mAsyncChannel;
+        try {
+            IWifiManager iWifiManager = getIWifiManager();
+            if (iWifiManager == null) {
+                throw new RemoteException("Wifi service is not running");
+            }
+            iWifiManager.connect(config, networkId, binder, listenerProxy,
+                    listener == null ? 0 : listener.hashCode());
+        } catch (RemoteException e) {
+            if (listenerProxy != null) listenerProxy.onFailure(ERROR);
+        } catch (SecurityException e) {
+            if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
+        }
     }
 
     /**
@@ -3851,10 +3694,7 @@
     })
     public void connect(@NonNull WifiConfiguration config, @Nullable ActionListener listener) {
         if (config == null) throw new IllegalArgumentException("config cannot be null");
-        // Use INVALID_NETWORK_ID for arg1 when passing a config object
-        // arg1 is used to pass network id when the network already exists
-        getChannel().sendMessage(CONNECT_NETWORK, WifiConfiguration.INVALID_NETWORK_ID,
-                putListener(listener), config);
+        connectInternal(config, WifiConfiguration.INVALID_NETWORK_ID, listener);
     }
 
     /**
@@ -3877,7 +3717,7 @@
     })
     public void connect(int networkId, @Nullable ActionListener listener) {
         if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative");
-        getChannel().sendMessage(CONNECT_NETWORK, networkId, putListener(listener));
+        connectInternal(null, networkId, listener);
     }
 
     /**
@@ -3908,7 +3748,24 @@
     })
     public void save(@NonNull WifiConfiguration config, @Nullable ActionListener listener) {
         if (config == null) throw new IllegalArgumentException("config cannot be null");
-        getChannel().sendMessage(SAVE_NETWORK, 0, putListener(listener), config);
+        ActionListenerProxy listenerProxy = null;
+        Binder binder = null;
+        if (listener != null) {
+            listenerProxy = new ActionListenerProxy("save", mLooper, listener);
+            binder = new Binder();
+        }
+        try {
+            IWifiManager iWifiManager = getIWifiManager();
+            if (iWifiManager == null) {
+                throw new RemoteException("Wifi service is not running");
+            }
+            iWifiManager.save(config, binder, listenerProxy,
+                    listener == null ? 0 : listener.hashCode());
+        } catch (RemoteException e) {
+            if (listenerProxy != null) listenerProxy.onFailure(ERROR);
+        } catch (SecurityException e) {
+            if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
+        }
     }
 
     /**
@@ -3932,7 +3789,24 @@
     })
     public void forget(int netId, @Nullable ActionListener listener) {
         if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
-        getChannel().sendMessage(FORGET_NETWORK, netId, putListener(listener));
+        ActionListenerProxy listenerProxy = null;
+        Binder binder = null;
+        if (listener != null) {
+            listenerProxy = new ActionListenerProxy("forget", mLooper, listener);
+            binder = new Binder();
+        }
+        try {
+            IWifiManager iWifiManager = getIWifiManager();
+            if (iWifiManager == null) {
+                throw new RemoteException("Wifi service is not running");
+            }
+            iWifiManager.forget(netId, binder, listenerProxy,
+                    listener == null ? 0 : listener.hashCode());
+        } catch (RemoteException e) {
+            if (listenerProxy != null) listenerProxy.onFailure(ERROR);
+        } catch (SecurityException e) {
+            if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
+        }
     }
 
     /**
@@ -3942,6 +3816,7 @@
      * @param listener for callbacks on success or failure. Can be null.
      * @throws IllegalStateException if the WifiManager instance needs to be
      * initialized again
+     * @deprecated This API is deprecated. Use {@link #disableNetwork(int)} instead.
      * @hide
      */
     @SystemApi
@@ -3950,9 +3825,19 @@
             android.Manifest.permission.NETWORK_SETUP_WIZARD,
             android.Manifest.permission.NETWORK_STACK
     })
+    @Deprecated
     public void disable(int netId, @Nullable ActionListener listener) {
         if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
-        getChannel().sendMessage(DISABLE_NETWORK, netId, putListener(listener));
+        // Simple wrapper which forwards the call to disableNetwork. This is a temporary
+        // implementation until we can remove this API completely.
+        boolean status = disableNetwork(netId);
+        if (listener != null) {
+            if (status) {
+                listener.onSuccess();
+            } else {
+                listener.onFailure(ERROR);
+            }
+        }
     }
 
     /**
@@ -4008,24 +3893,6 @@
     }
 
     /**
-     * Get a reference to WifiService handler. This is used by a client to establish
-     * an AsyncChannel communication with WifiService
-     *
-     * @return Messenger pointing to the WifiService handler
-     */
-    @UnsupportedAppUsage
-    private Messenger getWifiServiceMessenger() {
-        try {
-            IWifiManager iWifiManager = getIWifiManager();
-            if (iWifiManager == null) return null;
-            return iWifiManager.getWifiServiceMessenger(mContext.getOpPackageName());
-        } catch (RemoteException e) {
-            throw e.rethrowFromSystemServer();
-        }
-    }
-
-
-    /**
      * Allows an application to keep the Wi-Fi radio awake.
      * Normally the Wi-Fi radio may turn off when the user has not used the device in a while.
      * Acquiring a WifiLock will keep the radio on until the lock is released.  Multiple
@@ -4485,16 +4352,6 @@
         }
     }
 
-    protected void finalize() throws Throwable {
-        try {
-            if (mAsyncChannel != null) {
-                mAsyncChannel.disconnect();
-            }
-        } finally {
-            super.finalize();
-        }
-    }
-
     /**
      * Set wifi verbose log. Called from developer settings.
      * @hide
diff --git a/wifi/java/android/net/wifi/WifiScanner.java b/wifi/java/android/net/wifi/WifiScanner.java
index 075531c..68948cb 100644
--- a/wifi/java/android/net/wifi/WifiScanner.java
+++ b/wifi/java/android/net/wifi/WifiScanner.java
@@ -17,6 +17,7 @@
 package android.net.wifi;
 
 import android.Manifest;
+import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
 import android.annotation.SuppressLint;
 import android.annotation.SystemApi;
@@ -58,13 +59,23 @@
     /** 5 GHz band excluding DFS channels */
     public static final int WIFI_BAND_5_GHZ = 2;            /* 5 GHz band without DFS channels */
     /** DFS channels from 5 GHz band only */
-    public static final int WIFI_BAND_5_GHZ_DFS_ONLY  = 4;  /* 5 GHz band with DFS channels */
+    public static final int WIFI_BAND_5_GHZ_DFS_ONLY  = 4;  /* 5 GHz band DFS channels */
+    /**
+     * 2.4Ghz band + DFS channels from 5 GHz band only
+     * @hide
+     */
+    public static final int WIFI_BAND_24_GHZ_WITH_5GHZ_DFS  = 5;
     /** 5 GHz band including DFS channels */
     public static final int WIFI_BAND_5_GHZ_WITH_DFS  = 6;  /* 5 GHz band with DFS channels */
     /** Both 2.4 GHz band and 5 GHz band; no DFS channels */
     public static final int WIFI_BAND_BOTH = 3;             /* both bands without DFS channels */
     /** Both 2.4 GHz band and 5 GHz band; with DFS channels */
     public static final int WIFI_BAND_BOTH_WITH_DFS = 7;    /* both bands with DFS channels */
+    /**
+     * Max band value
+     * @hide
+     */
+    public static final int WIFI_BAND_MAX = 8;
 
     /** Minimum supported scanning period */
     public static final int MIN_SCAN_PERIOD_MS = 1000;      /* minimum supported period */
@@ -375,19 +386,27 @@
          */
         private int mBandScanned;
         /** all scan results discovered in this scan, sorted by timestamp in ascending order */
-        private ScanResult mResults[];
+        private final List<ScanResult> mResults;
 
-        ScanData() {}
+        ScanData() {
+            mResults = new ArrayList<>();
+        }
 
         public ScanData(int id, int flags, ScanResult[] results) {
             mId = id;
             mFlags = flags;
-            mResults = results;
+            mResults = new ArrayList<>(Arrays.asList(results));
         }
 
         /** {@hide} */
         public ScanData(int id, int flags, int bucketsScanned, int bandScanned,
                         ScanResult[] results) {
+            this(id, flags, bucketsScanned, bandScanned, new ArrayList<>(Arrays.asList(results)));
+        }
+
+        /** {@hide} */
+        public ScanData(int id, int flags, int bucketsScanned, int bandScanned,
+                        List<ScanResult> results) {
             mId = id;
             mFlags = flags;
             mBucketsScanned = bucketsScanned;
@@ -400,11 +419,9 @@
             mFlags = s.mFlags;
             mBucketsScanned = s.mBucketsScanned;
             mBandScanned = s.mBandScanned;
-            mResults = new ScanResult[s.mResults.length];
-            for (int i = 0; i < s.mResults.length; i++) {
-                ScanResult result = s.mResults[i];
-                ScanResult newResult = new ScanResult(result);
-                mResults[i] = newResult;
+            mResults = new ArrayList<>();
+            for (ScanResult scanResult : s.mResults) {
+                mResults.add(new ScanResult(scanResult));
             }
         }
 
@@ -427,7 +444,14 @@
         }
 
         public ScanResult[] getResults() {
-            return mResults;
+            return mResults.toArray(new ScanResult[0]);
+        }
+
+        /** {@hide} */
+        public void addResults(@NonNull ScanResult[] newResults) {
+            for (ScanResult result : newResults) {
+                mResults.add(new ScanResult(result));
+            }
         }
 
         /** Implement the Parcelable interface {@hide} */
@@ -437,19 +461,11 @@
 
         /** Implement the Parcelable interface {@hide} */
         public void writeToParcel(Parcel dest, int flags) {
-            if (mResults != null) {
-                dest.writeInt(mId);
-                dest.writeInt(mFlags);
-                dest.writeInt(mBucketsScanned);
-                dest.writeInt(mBandScanned);
-                dest.writeInt(mResults.length);
-                for (int i = 0; i < mResults.length; i++) {
-                    ScanResult result = mResults[i];
-                    result.writeToParcel(dest, flags);
-                }
-            } else {
-                dest.writeInt(0);
-            }
+            dest.writeInt(mId);
+            dest.writeInt(mFlags);
+            dest.writeInt(mBucketsScanned);
+            dest.writeInt(mBandScanned);
+            dest.writeParcelableList(mResults, 0);
         }
 
         /** Implement the Parcelable interface {@hide} */
@@ -460,11 +476,8 @@
                         int flags = in.readInt();
                         int bucketsScanned = in.readInt();
                         int bandScanned = in.readInt();
-                        int n = in.readInt();
-                        ScanResult results[] = new ScanResult[n];
-                        for (int i = 0; i < n; i++) {
-                            results[i] = ScanResult.CREATOR.createFromParcel(in);
-                        }
+                        List<ScanResult> results = new ArrayList<>();
+                        in.readParcelableList(results, ScanResult.class.getClassLoader());
                         return new ScanData(id, flags, bucketsScanned, bandScanned, results);
                     }
 
diff --git a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
index e595164..8f3635f 100644
--- a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
+++ b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
@@ -20,8 +20,8 @@
 import android.annotation.SystemApi;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.telephony.TelephonyManager.NetworkType;
 
+import android.telephony.Annotation.NetworkType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 
diff --git a/wifi/java/com/android/server/wifi/BaseWifiService.java b/wifi/java/com/android/server/wifi/BaseWifiService.java
index bc06e7d..4ca2a16 100644
--- a/wifi/java/com/android/server/wifi/BaseWifiService.java
+++ b/wifi/java/com/android/server/wifi/BaseWifiService.java
@@ -21,11 +21,14 @@
 import android.content.pm.ParceledListSlice;
 import android.net.DhcpInfo;
 import android.net.Network;
+import android.net.wifi.IActionListener;
 import android.net.wifi.IDppCallback;
+import android.net.wifi.ILocalOnlyHotspotCallback;
 import android.net.wifi.INetworkRequestMatchCallback;
 import android.net.wifi.IOnWifiUsabilityStatsListener;
 import android.net.wifi.ISoftApCallback;
 import android.net.wifi.ITrafficStateCallback;
+import android.net.wifi.ITxPacketCountListener;
 import android.net.wifi.IWifiManager;
 import android.net.wifi.ScanResult;
 import android.net.wifi.WifiActivityEnergyInfo;
@@ -204,11 +207,6 @@
     }
 
     @Override
-    public void setCountryCode(String country) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
     public String getCountryCode() {
         throw new UnsupportedOperationException();
     }
@@ -283,22 +281,34 @@
         throw new UnsupportedOperationException();
     }
 
-    @Override
+    /** @deprecated replaced by {@link #startLocalOnlyHotspot(ILocalOnlyHotspotCallback, String)} */
+    @Deprecated
     public int startLocalOnlyHotspot(Messenger messenger, IBinder binder, String packageName) {
         throw new UnsupportedOperationException();
     }
 
     @Override
+    public int startLocalOnlyHotspot(ILocalOnlyHotspotCallback callback, String packageName) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
     public void stopLocalOnlyHotspot() {
         throw new UnsupportedOperationException();
     }
 
-    @Override
+    /** @deprecated replaced by {@link #startWatchLocalOnlyHotspot(ILocalOnlyHotspotCallback)} */
+    @Deprecated
     public void startWatchLocalOnlyHotspot(Messenger messenger, IBinder binder) {
         throw new UnsupportedOperationException();
     }
 
     @Override
+    public void startWatchLocalOnlyHotspot(ILocalOnlyHotspotCallback callback) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
     public void stopWatchLocalOnlyHotspot() {
         throw new UnsupportedOperationException();
     }
@@ -324,11 +334,6 @@
     }
 
     @Override
-    public Messenger getWifiServiceMessenger(String packageName) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
     public void enableTdls(String remoteIPAddress, boolean enable) {
         throw new UnsupportedOperationException();
     }
@@ -486,4 +491,28 @@
     public void updateWifiUsabilityScore(int seqNum, int score, int predictionHorizonSec) {
         throw new UnsupportedOperationException();
     }
+
+    @Override
+    public void connect(WifiConfiguration config, int netId, IBinder binder,
+            IActionListener callback, int callbackIdentifier) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void save(WifiConfiguration config, IBinder binder, IActionListener callback,
+            int callbackIdentifier) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void forget(int netId, IBinder binder, IActionListener callback,
+            int callbackIdentifier) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void getTxPacketCount(String packageName, IBinder binder,
+            ITxPacketCountListener callback, int callbackIdentifier) {
+        throw new UnsupportedOperationException();
+    }
 }
diff --git a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
index ba9fc78..6d7e621 100644
--- a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
@@ -19,7 +19,6 @@
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertTrue;
 
 import android.net.MacAddress;
@@ -62,7 +61,8 @@
         config.updateIdentifier = "1234";
         config.fromWifiNetworkSpecifier = true;
         config.fromWifiNetworkSuggestion = true;
-        MacAddress macBeforeParcel = config.getOrCreateRandomizedMacAddress();
+        config.setRandomizedMacAddress(MacAddress.createRandomUnicastAddress());
+        MacAddress macBeforeParcel = config.getRandomizedMacAddress();
         Parcel parcelW = Parcel.obtain();
         config.writeToParcel(parcelW, 0);
         byte[] bytes = parcelW.marshall();
@@ -75,7 +75,7 @@
 
         // lacking a useful config.equals, check two fields near the end.
         assertEquals(cookie, reconfig.getMoTree());
-        assertEquals(macBeforeParcel, reconfig.getOrCreateRandomizedMacAddress());
+        assertEquals(macBeforeParcel, reconfig.getRandomizedMacAddress());
         assertEquals(config.updateIdentifier, reconfig.updateIdentifier);
         assertFalse(reconfig.trusted);
         assertTrue(config.fromWifiNetworkSpecifier);
@@ -193,19 +193,6 @@
     }
 
     @Test
-    public void testGetOrCreateRandomizedMacAddress_SavesAndReturnsSameAddress() {
-        WifiConfiguration config = new WifiConfiguration();
-        MacAddress defaultMac = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
-        assertEquals(defaultMac, config.getRandomizedMacAddress());
-
-        MacAddress firstMacAddress = config.getOrCreateRandomizedMacAddress();
-        MacAddress secondMacAddress = config.getOrCreateRandomizedMacAddress();
-
-        assertNotEquals(defaultMac, firstMacAddress);
-        assertEquals(firstMacAddress, secondMacAddress);
-    }
-
-    @Test
     public void testSetRandomizedMacAddress_ChangesSavedAddress() {
         WifiConfiguration config = new WifiConfiguration();
         MacAddress defaultMac = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
@@ -219,36 +206,6 @@
     }
 
     @Test
-    public void testGetOrCreateRandomizedMacAddress_ReRandomizesInvalidAddress() {
-        WifiConfiguration config =  new WifiConfiguration();
-
-        MacAddress defaultMac = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
-        MacAddress macAddressZeroes = MacAddress.ALL_ZEROS_ADDRESS;
-        MacAddress macAddressMulticast = MacAddress.fromString("03:ff:ff:ff:ff:ff");
-        MacAddress macAddressGlobal = MacAddress.fromString("fc:ff:ff:ff:ff:ff");
-
-        config.setRandomizedMacAddress(null);
-        MacAddress macAfterChange = config.getOrCreateRandomizedMacAddress();
-        assertNotEquals(macAfterChange, null);
-
-        config.setRandomizedMacAddress(defaultMac);
-        macAfterChange = config.getOrCreateRandomizedMacAddress();
-        assertNotEquals(macAfterChange, defaultMac);
-
-        config.setRandomizedMacAddress(macAddressZeroes);
-        macAfterChange = config.getOrCreateRandomizedMacAddress();
-        assertNotEquals(macAfterChange, macAddressZeroes);
-
-        config.setRandomizedMacAddress(macAddressMulticast);
-        macAfterChange = config.getOrCreateRandomizedMacAddress();
-        assertNotEquals(macAfterChange, macAddressMulticast);
-
-        config.setRandomizedMacAddress(macAddressGlobal);
-        macAfterChange = config.getOrCreateRandomizedMacAddress();
-        assertNotEquals(macAfterChange, macAddressGlobal);
-    }
-
-    @Test
     public void testSetRandomizedMacAddress_DoesNothingWhenNull() {
         WifiConfiguration config = new WifiConfiguration();
         MacAddress defaultMac = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
diff --git a/wifi/tests/src/android/net/wifi/WifiManagerTest.java b/wifi/tests/src/android/net/wifi/WifiManagerTest.java
index e478f38..885139b 100644
--- a/wifi/tests/src/android/net/wifi/WifiManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiManagerTest.java
@@ -16,9 +16,6 @@
 
 package android.net.wifi;
 
-import static android.net.wifi.WifiManager.HOTSPOT_FAILED;
-import static android.net.wifi.WifiManager.HOTSPOT_STARTED;
-import static android.net.wifi.WifiManager.HOTSPOT_STOPPED;
 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_GENERIC;
 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE;
 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_NO_CHANNEL;
@@ -64,11 +61,11 @@
 import android.net.wifi.WifiManager.OnWifiUsabilityStatsListener;
 import android.net.wifi.WifiManager.SoftApCallback;
 import android.net.wifi.WifiManager.TrafficStateCallback;
+import android.os.Binder;
 import android.os.Build;
 import android.os.Handler;
 import android.os.IBinder;
-import android.os.Message;
-import android.os.Messenger;
+import android.os.RemoteException;
 import android.os.test.TestLooper;
 
 import androidx.test.filters.SmallTest;
@@ -115,8 +112,6 @@
     private Handler mHandler;
     private TestLooper mLooper;
     private WifiManager mWifiManager;
-    private Messenger mWifiServiceMessenger;
-    final ArgumentCaptor<Messenger> mMessengerCaptor = ArgumentCaptor.forClass(Messenger.class);
 
     @Before public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
@@ -126,7 +121,6 @@
         when(mContext.getApplicationInfo()).thenReturn(mApplicationInfo);
         when(mContext.getOpPackageName()).thenReturn(TEST_PACKAGE_NAME);
 
-        mWifiServiceMessenger = new Messenger(mHandler);
         mWifiManager = new WifiManager(mContext, mWifiService, mLooper.getLooper());
         verify(mWifiService).getVerboseLoggingLevel();
     }
@@ -176,7 +170,7 @@
     @Test
     public void testCreationAndCloseOfLocalOnlyHotspotReservation() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
 
@@ -194,7 +188,7 @@
     public void testLocalOnlyHotspotReservationCallsStopProperlyInTryWithResources()
             throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
 
@@ -355,7 +349,7 @@
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
 
         verify(mWifiService)
-                .startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class), anyString());
+                .startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class), anyString());
     }
 
     /**
@@ -366,7 +360,7 @@
     public void testStartLocalOnlyHotspotThrowsSecurityException() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
         doThrow(new SecurityException()).when(mWifiService)
-                .startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class), anyString());
+                .startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class), anyString());
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
     }
 
@@ -378,7 +372,7 @@
     public void testStartLocalOnlyHotspotThrowsIllegalStateException() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
         doThrow(new IllegalStateException()).when(mWifiService)
-                .startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class), anyString());
+                .startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class), anyString());
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
     }
 
@@ -388,12 +382,13 @@
     @Test
     public void testCorrectLooperIsUsedForHandler() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(ERROR_INCOMPATIBLE_MODE);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         mLooper.dispatchAll();
         assertEquals(ERROR_INCOMPATIBLE_MODE, callback.mFailureReason);
         verify(mContext, never()).getMainLooper();
+        verify(mContext, never()).getMainExecutor();
     }
 
     /**
@@ -404,15 +399,15 @@
     public void testMainLooperIsUsedWhenHandlerNotProvided() throws Exception {
         // record thread from looper.getThread and check ids.
         TestLooper altLooper = new TestLooper();
-        when(mContext.getMainLooper()).thenReturn(altLooper.getLooper());
+        when(mContext.getMainExecutor()).thenReturn(altLooper.getNewExecutor());
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(ERROR_INCOMPATIBLE_MODE);
         mWifiManager.startLocalOnlyHotspot(callback, null);
         altLooper.dispatchAll();
         assertEquals(ERROR_INCOMPATIBLE_MODE, callback.mFailureReason);
         assertEquals(altLooper.getLooper().getThread().getId(), callback.mCallingThreadId);
-        verify(mContext).getMainLooper();
+        verify(mContext).getMainExecutor();
     }
 
     /**
@@ -424,18 +419,17 @@
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
         TestLooper callbackLooper = new TestLooper();
         Handler callbackHandler = new Handler(callbackLooper.getLooper());
-        when(mWifiService.startLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class), anyString())).thenReturn(REQUEST_REGISTERED);
+        ArgumentCaptor<ILocalOnlyHotspotCallback> internalCallback =
+                ArgumentCaptor.forClass(ILocalOnlyHotspotCallback.class);
+        when(mWifiService.startLocalOnlyHotspot(internalCallback.capture(), anyString()))
+                .thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, callbackHandler);
         callbackLooper.dispatchAll();
         mLooper.dispatchAll();
         assertFalse(callback.mOnStartedCalled);
         assertEquals(null, callback.mRes);
         // now trigger the callback
-        Message msg = new Message();
-        msg.what = HOTSPOT_STARTED;
-        msg.obj = mApConfig;
-        mMessengerCaptor.getValue().send(msg);
+        internalCallback.getValue().onHotspotStarted(mApConfig);
         mLooper.dispatchAll();
         callbackLooper.dispatchAll();
         assertTrue(callback.mOnStartedCalled);
@@ -451,17 +445,17 @@
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
         TestLooper callbackLooper = new TestLooper();
         Handler callbackHandler = new Handler(callbackLooper.getLooper());
-        when(mWifiService.startLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class), anyString())).thenReturn(REQUEST_REGISTERED);
+        ArgumentCaptor<ILocalOnlyHotspotCallback> internalCallback =
+                ArgumentCaptor.forClass(ILocalOnlyHotspotCallback.class);
+        when(mWifiService.startLocalOnlyHotspot(internalCallback.capture(), anyString()))
+                .thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, callbackHandler);
         callbackLooper.dispatchAll();
         mLooper.dispatchAll();
         assertFalse(callback.mOnStartedCalled);
         assertEquals(null, callback.mRes);
         // now trigger the callback
-        Message msg = new Message();
-        msg.what = HOTSPOT_STARTED;
-        mMessengerCaptor.getValue().send(msg);
+        internalCallback.getValue().onHotspotStarted(null);
         mLooper.dispatchAll();
         callbackLooper.dispatchAll();
         assertFalse(callback.mOnStartedCalled);
@@ -476,16 +470,16 @@
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
         TestLooper callbackLooper = new TestLooper();
         Handler callbackHandler = new Handler(callbackLooper.getLooper());
-        when(mWifiService.startLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class), anyString())).thenReturn(REQUEST_REGISTERED);
+        ArgumentCaptor<ILocalOnlyHotspotCallback> internalCallback =
+                ArgumentCaptor.forClass(ILocalOnlyHotspotCallback.class);
+        when(mWifiService.startLocalOnlyHotspot(internalCallback.capture(), anyString()))
+                .thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, callbackHandler);
         callbackLooper.dispatchAll();
         mLooper.dispatchAll();
         assertFalse(callback.mOnStoppedCalled);
         // now trigger the callback
-        Message msg = new Message();
-        msg.what = HOTSPOT_STOPPED;
-        mMessengerCaptor.getValue().send(msg);
+        internalCallback.getValue().onHotspotStopped();
         mLooper.dispatchAll();
         callbackLooper.dispatchAll();
         assertTrue(callback.mOnStoppedCalled);
@@ -499,17 +493,16 @@
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
         TestLooper callbackLooper = new TestLooper();
         Handler callbackHandler = new Handler(callbackLooper.getLooper());
-        when(mWifiService.startLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class), anyString())).thenReturn(REQUEST_REGISTERED);
+        ArgumentCaptor<ILocalOnlyHotspotCallback> internalCallback =
+                ArgumentCaptor.forClass(ILocalOnlyHotspotCallback.class);
+        when(mWifiService.startLocalOnlyHotspot(internalCallback.capture(), anyString()))
+                .thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, callbackHandler);
         callbackLooper.dispatchAll();
         mLooper.dispatchAll();
         assertEquals(ERROR_NOT_SET, callback.mFailureReason);
         // now trigger the callback
-        Message msg = new Message();
-        msg.what = HOTSPOT_FAILED;
-        msg.arg1 = ERROR_NO_CHANNEL;
-        mMessengerCaptor.getValue().send(msg);
+        internalCallback.getValue().onHotspotFailed(ERROR_NO_CHANNEL);
         mLooper.dispatchAll();
         callbackLooper.dispatchAll();
         assertEquals(ERROR_NO_CHANNEL, callback.mFailureReason);
@@ -521,7 +514,7 @@
     @Test
     public void testLocalOnlyHotspotCallbackFullOnIncompatibleMode() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(ERROR_INCOMPATIBLE_MODE);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         mLooper.dispatchAll();
@@ -537,7 +530,7 @@
     @Test
     public void testLocalOnlyHotspotCallbackFullOnTetheringDisallowed() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(ERROR_TETHERING_DISALLOWED);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         mLooper.dispatchAll();
@@ -555,7 +548,7 @@
     public void testLocalOnlyHotspotCallbackFullOnSecurityException() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
         doThrow(new SecurityException()).when(mWifiService)
-                .startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class), anyString());
+                .startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class), anyString());
         try {
             mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         } catch (SecurityException e) {
@@ -575,7 +568,7 @@
     @Test
     public void testLocalOnlyHotspotCallbackFullOnNoChannelError() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         mLooper.dispatchAll();
@@ -591,7 +584,7 @@
     @Test
     public void testCancelLocalOnlyHotspotRequestCallsStopOnWifiService() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         mWifiManager.cancelLocalOnlyHotspotRequest();
@@ -613,7 +606,7 @@
     @Test
     public void testCallbackAfterLocalOnlyHotspotWasCancelled() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(REQUEST_REGISTERED);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         mWifiManager.cancelLocalOnlyHotspotRequest();
@@ -632,7 +625,7 @@
     @Test
     public void testCancelAfterLocalOnlyHotspotCallbackTriggered() throws Exception {
         TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback();
-        when(mWifiService.startLocalOnlyHotspot(any(Messenger.class), any(IBinder.class),
+        when(mWifiService.startLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class),
                 anyString())).thenReturn(ERROR_INCOMPATIBLE_MODE);
         mWifiManager.startLocalOnlyHotspot(callback, mHandler);
         mLooper.dispatchAll();
@@ -652,7 +645,7 @@
         TestLocalOnlyHotspotObserver observer = new TestLocalOnlyHotspotObserver();
 
         mWifiManager.watchLocalOnlyHotspot(observer, mHandler);
-        verify(mWifiService).startWatchLocalOnlyHotspot(any(Messenger.class), any(IBinder.class));
+        verify(mWifiService).startWatchLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class));
     }
 
     /**
@@ -663,7 +656,7 @@
     public void testStartWatchLocalOnlyHotspotThrowsSecurityException() throws Exception {
         TestLocalOnlyHotspotObserver observer = new TestLocalOnlyHotspotObserver();
         doThrow(new SecurityException()).when(mWifiService)
-                .startWatchLocalOnlyHotspot(any(Messenger.class), any(IBinder.class));
+                .startWatchLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class));
         mWifiManager.watchLocalOnlyHotspot(observer, mHandler);
     }
 
@@ -675,7 +668,7 @@
     public void testStartWatchLocalOnlyHotspotThrowsIllegalStateException() throws Exception {
         TestLocalOnlyHotspotObserver observer = new TestLocalOnlyHotspotObserver();
         doThrow(new IllegalStateException()).when(mWifiService)
-                .startWatchLocalOnlyHotspot(any(Messenger.class), any(IBinder.class));
+                .startWatchLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class));
         mWifiManager.watchLocalOnlyHotspot(observer, mHandler);
     }
 
@@ -820,6 +813,7 @@
         verify(mWifiService).registerSoftApCallback(any(IBinder.class),
                 any(ISoftApCallback.Stub.class), anyInt());
         verify(mContext, never()).getMainLooper();
+        verify(mContext, never()).getMainExecutor();
     }
 
     /**
@@ -832,6 +826,7 @@
         mLooper.dispatchAll();
         assertTrue(observer.mOnRegistered);
         verify(mContext, never()).getMainLooper();
+        verify(mContext, never()).getMainExecutor();
     }
 
     /**
@@ -842,13 +837,13 @@
     public void testMainLooperIsUsedWhenHandlerNotProvidedForObserver() throws Exception {
         // record thread from looper.getThread and check ids.
         TestLooper altLooper = new TestLooper();
-        when(mContext.getMainLooper()).thenReturn(altLooper.getLooper());
+        when(mContext.getMainExecutor()).thenReturn(altLooper.getNewExecutor());
         TestLocalOnlyHotspotObserver observer = new TestLocalOnlyHotspotObserver();
         mWifiManager.watchLocalOnlyHotspot(observer, null);
         altLooper.dispatchAll();
         assertTrue(observer.mOnRegistered);
         assertEquals(altLooper.getLooper().getThread().getId(), observer.mCallingThreadId);
-        verify(mContext).getMainLooper();
+        verify(mContext).getMainExecutor();
     }
 
     /**
@@ -863,8 +858,7 @@
         assertFalse(observer.mOnRegistered);
         assertEquals(null, observer.mSub);
         mWifiManager.watchLocalOnlyHotspot(observer, observerHandler);
-        verify(mWifiService).startWatchLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class));
+        verify(mWifiService).startWatchLocalOnlyHotspot(any(ILocalOnlyHotspotCallback.class));
         // now trigger the callback
         observerLooper.dispatchAll();
         mLooper.dispatchAll();
@@ -882,16 +876,14 @@
         TestLooper observerLooper = new TestLooper();
         Handler observerHandler = new Handler(observerLooper.getLooper());
         mWifiManager.watchLocalOnlyHotspot(observer, observerHandler);
-        verify(mWifiService).startWatchLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class));
+        ArgumentCaptor<ILocalOnlyHotspotCallback> internalCallback =
+                ArgumentCaptor.forClass(ILocalOnlyHotspotCallback.class);
+        verify(mWifiService).startWatchLocalOnlyHotspot(internalCallback.capture());
         observerLooper.dispatchAll();
         mLooper.dispatchAll();
         assertFalse(observer.mOnStartedCalled);
         // now trigger the callback
-        Message msg = new Message();
-        msg.what = HOTSPOT_STARTED;
-        msg.obj = mApConfig;
-        mMessengerCaptor.getValue().send(msg);
+        internalCallback.getValue().onHotspotStarted(mApConfig);
         mLooper.dispatchAll();
         observerLooper.dispatchAll();
         assertTrue(observer.mOnStartedCalled);
@@ -908,15 +900,14 @@
         TestLooper observerLooper = new TestLooper();
         Handler observerHandler = new Handler(observerLooper.getLooper());
         mWifiManager.watchLocalOnlyHotspot(observer, observerHandler);
-        verify(mWifiService).startWatchLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class));
+        ArgumentCaptor<ILocalOnlyHotspotCallback> internalCallback =
+                ArgumentCaptor.forClass(ILocalOnlyHotspotCallback.class);
+        verify(mWifiService).startWatchLocalOnlyHotspot(internalCallback.capture());
         observerLooper.dispatchAll();
         mLooper.dispatchAll();
         assertFalse(observer.mOnStartedCalled);
         // now trigger the callback
-        Message msg = new Message();
-        msg.what = HOTSPOT_STARTED;
-        mMessengerCaptor.getValue().send(msg);
+        internalCallback.getValue().onHotspotStarted(null);
         mLooper.dispatchAll();
         observerLooper.dispatchAll();
         assertFalse(observer.mOnStartedCalled);
@@ -934,15 +925,14 @@
         TestLooper observerLooper = new TestLooper();
         Handler observerHandler = new Handler(observerLooper.getLooper());
         mWifiManager.watchLocalOnlyHotspot(observer, observerHandler);
-        verify(mWifiService).startWatchLocalOnlyHotspot(mMessengerCaptor.capture(),
-                  any(IBinder.class));
+        ArgumentCaptor<ILocalOnlyHotspotCallback> internalCallback =
+                ArgumentCaptor.forClass(ILocalOnlyHotspotCallback.class);
+        verify(mWifiService).startWatchLocalOnlyHotspot(internalCallback.capture());
         observerLooper.dispatchAll();
         mLooper.dispatchAll();
         assertFalse(observer.mOnStoppedCalled);
         // now trigger the callback
-        Message msg = new Message();
-        msg.what = HOTSPOT_STOPPED;
-        mMessengerCaptor.getValue().send(msg);
+        internalCallback.getValue().onHotspotStopped();
         mLooper.dispatchAll();
         observerLooper.dispatchAll();
         assertTrue(observer.mOnStoppedCalled);
@@ -971,25 +961,6 @@
     }
 
     /**
-     * Verify that calls WifiServiceImpl to set country code when no exception happens.
-     */
-    @Test
-    public void testSetWifiCountryCode() throws Exception {
-        mWifiManager.setCountryCode(TEST_COUNTRY_CODE);
-        verify(mWifiService).setCountryCode(TEST_COUNTRY_CODE);
-    }
-
-    /**
-     * Verify that WifiManager.setCountryCode() rethrows exceptions if caller does not
-     * have necessary permissions.
-     */
-    @Test(expected = SecurityException.class)
-    public void testSetWifiCountryCodeFailedOnSecurityException() throws Exception {
-        doThrow(new SecurityException()).when(mWifiService).setCountryCode(anyString());
-        mWifiManager.setCountryCode(TEST_COUNTRY_CODE);
-    }
-
-    /**
      * Test that calls to get the current WPS config token return null and do not have any
      * interactions with WifiServiceImpl.
      */
@@ -1190,6 +1161,7 @@
         Handler altHandler = new Handler(altLooper.getLooper());
         mWifiManager.registerTrafficStateCallback(mTrafficStateCallback, altHandler);
         verify(mContext, never()).getMainLooper();
+        verify(mContext, never()).getMainExecutor();
         verify(mWifiService).registerTrafficStateCallback(
                 any(IBinder.class), callbackCaptor.capture(), anyInt());
 
@@ -1646,4 +1618,97 @@
         assertTrue(mWifiManager.setWifiEnabled(false));
         verify(mWifiService).setWifiEnabled(mContext.getOpPackageName(), false);
     }
+
+    /**
+     * Test behavior of {@link WifiManager#connect(int, WifiManager.ActionListener)}
+     */
+    @Test
+    public void testConnectWithListener() throws Exception {
+        WifiManager.ActionListener externalListener = mock(WifiManager.ActionListener.class);
+        mWifiManager.connect(TEST_NETWORK_ID, externalListener);
+
+        ArgumentCaptor<IActionListener> binderListenerCaptor =
+                ArgumentCaptor.forClass(IActionListener.class);
+        verify(mWifiService).connect(eq(null), eq(TEST_NETWORK_ID), any(Binder.class),
+                binderListenerCaptor.capture(), anyInt());
+        assertNotNull(binderListenerCaptor.getValue());
+
+        // Trigger on success.
+        binderListenerCaptor.getValue().onSuccess();
+        mLooper.dispatchAll();
+        verify(externalListener).onSuccess();
+
+        // Trigger on failure.
+        binderListenerCaptor.getValue().onFailure(WifiManager.BUSY);
+        mLooper.dispatchAll();
+        verify(externalListener).onFailure(WifiManager.BUSY);
+    }
+
+    /**
+     * Test behavior of {@link WifiManager#connect(int, WifiManager.ActionListener)}
+     */
+    @Test
+    public void testConnectWithListenerHandleSecurityException() throws Exception {
+        doThrow(new SecurityException()).when(mWifiService)
+                .connect(eq(null), anyInt(), any(IBinder.class),
+                        any(IActionListener.class), anyInt());
+        WifiManager.ActionListener externalListener = mock(WifiManager.ActionListener.class);
+        mWifiManager.connect(TEST_NETWORK_ID, externalListener);
+
+        mLooper.dispatchAll();
+        verify(externalListener).onFailure(WifiManager.NOT_AUTHORIZED);
+    }
+
+    /**
+     * Test behavior of {@link WifiManager#connect(int, WifiManager.ActionListener)}
+     */
+    @Test
+    public void testConnectWithListenerHandleRemoteException() throws Exception {
+        doThrow(new RemoteException()).when(mWifiService)
+                .connect(eq(null), anyInt(), any(IBinder.class),
+                        any(IActionListener.class), anyInt());
+        WifiManager.ActionListener externalListener = mock(WifiManager.ActionListener.class);
+        mWifiManager.connect(TEST_NETWORK_ID, externalListener);
+
+        mLooper.dispatchAll();
+        verify(externalListener).onFailure(WifiManager.ERROR);
+    }
+
+    /**
+     * Test behavior of {@link WifiManager#connect(int, WifiManager.ActionListener)}
+     */
+    @Test
+    public void testConnectWithoutListener() throws Exception {
+        WifiConfiguration configuration = new WifiConfiguration();
+        mWifiManager.connect(configuration, null);
+
+        verify(mWifiService).connect(configuration, WifiConfiguration.INVALID_NETWORK_ID, null,
+                null, 0);
+    }
+
+    /**
+     * Test behavior of {@link WifiManager#getTxPacketCount(WifiManager.TxPacketCountListener)}
+     */
+    @Test
+    public void testGetTxPacketCount() throws Exception {
+        WifiManager.TxPacketCountListener externalListener =
+                mock(WifiManager.TxPacketCountListener.class);
+        mWifiManager.getTxPacketCount(externalListener);
+
+        ArgumentCaptor<ITxPacketCountListener> binderListenerCaptor =
+                ArgumentCaptor.forClass(ITxPacketCountListener.class);
+        verify(mWifiService).getTxPacketCount(anyString(), any(Binder.class),
+                binderListenerCaptor.capture(), anyInt());
+        assertNotNull(binderListenerCaptor.getValue());
+
+        // Trigger on success.
+        binderListenerCaptor.getValue().onSuccess(6);
+        mLooper.dispatchAll();
+        verify(externalListener).onSuccess(6);
+
+        // Trigger on failure.
+        binderListenerCaptor.getValue().onFailure(WifiManager.BUSY);
+        mLooper.dispatchAll();
+        verify(externalListener).onFailure(WifiManager.BUSY);
+    }
 }
diff --git a/wifi/tests/src/android/net/wifi/WifiScannerTest.java b/wifi/tests/src/android/net/wifi/WifiScannerTest.java
index dd05b47..ea136d6 100644
--- a/wifi/tests/src/android/net/wifi/WifiScannerTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiScannerTest.java
@@ -22,7 +22,6 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
@@ -445,4 +444,37 @@
 
         assertEquals(WifiScanner.CMD_STOP_PNO_SCAN, message.what);
     }
+
+    @Test
+    public void testScanDataAddResults() throws Exception {
+        ScanResult scanResult1 = new ScanResult();
+        scanResult1.SSID = TEST_SSID_1;
+        ScanData scanData = new ScanData(0, 0, new ScanResult[]{scanResult1});
+
+        ScanResult scanResult2 = new ScanResult();
+        scanResult2.SSID = TEST_SSID_2;
+        scanData.addResults(new ScanResult[]{scanResult2});
+
+        ScanResult[] consolidatedScanResults = scanData.getResults();
+        assertEquals(2, consolidatedScanResults.length);
+        assertEquals(TEST_SSID_1, consolidatedScanResults[0].SSID);
+        assertEquals(TEST_SSID_2, consolidatedScanResults[1].SSID);
+    }
+
+    @Test
+    public void testScanDataParcel() throws Exception {
+        ScanResult scanResult1 = new ScanResult();
+        scanResult1.SSID = TEST_SSID_1;
+        ScanData scanData = new ScanData(5, 4, new ScanResult[]{scanResult1});
+
+        Parcel parcel = Parcel.obtain();
+        scanData.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);    // Rewind data position back to the beginning for read.
+        ScanData readScanData = ScanData.CREATOR.createFromParcel(parcel);
+
+        assertEquals(scanData.getId(), readScanData.getId());
+        assertEquals(scanData.getFlags(), readScanData.getFlags());
+        assertEquals(scanData.getResults().length, readScanData.getResults().length);
+        assertEquals(scanData.getResults()[0].SSID, readScanData.getResults()[0].SSID);
+    }
 }